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