vfs_cluster.c revision 86089
1/*-
2 * Copyright (c) 1993
3 *	The Regents of the University of California.  All rights reserved.
4 * Modifications/enhancements:
5 * 	Copyright (c) 1995 John S. Dyson.  All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 *    must display the following acknowledgement:
17 *	This product includes software developed by the University of
18 *	California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 *    may be used to endorse or promote products derived from this software
21 *    without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 *
35 *	@(#)vfs_cluster.c	8.7 (Berkeley) 2/13/94
36 * $FreeBSD: head/sys/kern/vfs_cluster.c 86089 2001-11-05 18:48:54Z dillon $
37 */
38
39#include "opt_debug_cluster.h"
40
41#include <sys/param.h>
42#include <sys/systm.h>
43#include <sys/kernel.h>
44#include <sys/proc.h>
45#include <sys/bio.h>
46#include <sys/buf.h>
47#include <sys/vnode.h>
48#include <sys/malloc.h>
49#include <sys/mount.h>
50#include <sys/resourcevar.h>
51#include <sys/vmmeter.h>
52#include <vm/vm.h>
53#include <vm/vm_object.h>
54#include <vm/vm_page.h>
55#include <sys/sysctl.h>
56
57#if defined(CLUSTERDEBUG)
58#include <sys/sysctl.h>
59static int	rcluster= 0;
60SYSCTL_INT(_debug, OID_AUTO, rcluster, CTLFLAG_RW, &rcluster, 0, "");
61#endif
62
63static MALLOC_DEFINE(M_SEGMENT, "cluster_save buffer", "cluster_save buffer");
64
65static struct cluster_save *
66	cluster_collectbufs __P((struct vnode *vp, struct buf *last_bp));
67static struct buf *
68	cluster_rbuild __P((struct vnode *vp, u_quad_t filesize, daddr_t lbn,
69			    daddr_t blkno, long size, int run, struct buf *fbp));
70
71static int write_behind = 1;
72SYSCTL_INT(_vfs, OID_AUTO, write_behind, CTLFLAG_RW, &write_behind, 0, "");
73
74extern vm_page_t	bogus_page;
75
76extern int cluster_pbuf_freecnt;
77
78/*
79 * Maximum number of blocks for read-ahead.
80 */
81#define MAXRA 32
82
83/*
84 * This replaces bread.
85 */
86int
87cluster_read(vp, filesize, lblkno, size, cred, totread, seqcount, bpp)
88	struct vnode *vp;
89	u_quad_t filesize;
90	daddr_t lblkno;
91	long size;
92	struct ucred *cred;
93	long totread;
94	int seqcount;
95	struct buf **bpp;
96{
97	struct buf *bp, *rbp, *reqbp;
98	daddr_t blkno, origblkno;
99	int error, num_ra;
100	int i;
101	int maxra, racluster;
102	long origtotread;
103
104	error = 0;
105
106	/*
107	 * Try to limit the amount of read-ahead by a few
108	 * ad-hoc parameters.  This needs work!!!
109	 */
110	racluster = vp->v_mount->mnt_iosize_max / size;
111	maxra = 2 * racluster + (totread / size);
112	if (maxra > MAXRA)
113		maxra = MAXRA;
114	if (maxra > nbuf/8)
115		maxra = nbuf/8;
116
117	/*
118	 * get the requested block
119	 */
120	*bpp = reqbp = bp = getblk(vp, lblkno, size, 0, 0);
121	origblkno = lblkno;
122	origtotread = totread;
123
124	/*
125	 * if it is in the cache, then check to see if the reads have been
126	 * sequential.  If they have, then try some read-ahead, otherwise
127	 * back-off on prospective read-aheads.
128	 */
129	if (bp->b_flags & B_CACHE) {
130		if (!seqcount) {
131			return 0;
132		} else if ((bp->b_flags & B_RAM) == 0) {
133			return 0;
134		} else {
135			int s;
136			struct buf *tbp;
137			bp->b_flags &= ~B_RAM;
138			/*
139			 * We do the spl here so that there is no window
140			 * between the incore and the b_usecount increment
141			 * below.  We opt to keep the spl out of the loop
142			 * for efficiency.
143			 */
144			s = splbio();
145			for (i = 1; i < maxra; i++) {
146
147				if (!(tbp = incore(vp, lblkno+i))) {
148					break;
149				}
150
151				/*
152				 * Set another read-ahead mark so we know
153				 * to check again.
154				 */
155				if (((i % racluster) == (racluster - 1)) ||
156					(i == (maxra - 1)))
157					tbp->b_flags |= B_RAM;
158			}
159			splx(s);
160			if (i >= maxra) {
161				return 0;
162			}
163			lblkno += i;
164		}
165		reqbp = bp = NULL;
166	} else {
167		off_t firstread = bp->b_offset;
168
169		KASSERT(bp->b_offset != NOOFFSET,
170		    ("cluster_read: no buffer offset"));
171		if (firstread + totread > filesize)
172			totread = filesize - firstread;
173		if (totread > size) {
174			int nblks = 0;
175			int ncontigafter;
176			while (totread > 0) {
177				nblks++;
178				totread -= size;
179			}
180			if (nblks == 1)
181				goto single_block_read;
182			if (nblks > racluster)
183				nblks = racluster;
184
185	    		error = VOP_BMAP(vp, lblkno, NULL,
186				&blkno, &ncontigafter, NULL);
187			if (error)
188				goto single_block_read;
189			if (blkno == -1)
190				goto single_block_read;
191			if (ncontigafter == 0)
192				goto single_block_read;
193			if (ncontigafter + 1 < nblks)
194				nblks = ncontigafter + 1;
195
196			bp = cluster_rbuild(vp, filesize, lblkno,
197				blkno, size, nblks, bp);
198			lblkno += (bp->b_bufsize / size);
199		} else {
200single_block_read:
201			/*
202			 * if it isn't in the cache, then get a chunk from
203			 * disk if sequential, otherwise just get the block.
204			 */
205			bp->b_flags |= B_RAM;
206			bp->b_iocmd = BIO_READ;
207			lblkno += 1;
208		}
209	}
210
211	/*
212	 * if we have been doing sequential I/O, then do some read-ahead
213	 */
214	rbp = NULL;
215	if (seqcount && (lblkno < (origblkno + seqcount))) {
216		/*
217		 * we now build the read-ahead buffer if it is desirable.
218		 */
219		if (((u_quad_t)(lblkno + 1) * size) <= filesize &&
220		    !(error = VOP_BMAP(vp, lblkno, NULL, &blkno, &num_ra, NULL)) &&
221		    blkno != -1) {
222			int nblksread;
223			int ntoread = num_ra + 1;
224			nblksread = (origtotread + size - 1) / size;
225			if (seqcount < nblksread)
226				seqcount = nblksread;
227			if (seqcount < ntoread)
228				ntoread = seqcount;
229			if (num_ra) {
230				rbp = cluster_rbuild(vp, filesize, lblkno,
231					blkno, size, ntoread, NULL);
232			} else {
233				rbp = getblk(vp, lblkno, size, 0, 0);
234				rbp->b_flags |= B_ASYNC | B_RAM;
235				rbp->b_iocmd = BIO_READ;
236				rbp->b_blkno = blkno;
237			}
238		}
239	}
240
241	/*
242	 * handle the synchronous read
243	 */
244	if (bp) {
245#if defined(CLUSTERDEBUG)
246		if (rcluster)
247			printf("S(%ld,%ld,%d) ",
248			    (long)bp->b_lblkno, bp->b_bcount, seqcount);
249#endif
250		if ((bp->b_flags & B_CLUSTER) == 0) {
251			vfs_busy_pages(bp, 0);
252		}
253		bp->b_flags &= ~B_INVAL;
254		bp->b_ioflags &= ~BIO_ERROR;
255		if ((bp->b_flags & B_ASYNC) || bp->b_iodone != NULL)
256			BUF_KERNPROC(bp);
257		error = VOP_STRATEGY(vp, bp);
258		curproc->p_stats->p_ru.ru_inblock++;
259	}
260
261	/*
262	 * and if we have read-aheads, do them too
263	 */
264	if (rbp) {
265		if (error) {
266			rbp->b_flags &= ~B_ASYNC;
267			brelse(rbp);
268		} else if (rbp->b_flags & B_CACHE) {
269			rbp->b_flags &= ~B_ASYNC;
270			bqrelse(rbp);
271		} else {
272#if defined(CLUSTERDEBUG)
273			if (rcluster) {
274				if (bp)
275					printf("A+(%ld,%ld,%ld,%d) ",
276					    (long)rbp->b_lblkno, rbp->b_bcount,
277					    (long)(rbp->b_lblkno - origblkno),
278					    seqcount);
279				else
280					printf("A(%ld,%ld,%ld,%d) ",
281					    (long)rbp->b_lblkno, rbp->b_bcount,
282					    (long)(rbp->b_lblkno - origblkno),
283					    seqcount);
284			}
285#endif
286
287			if ((rbp->b_flags & B_CLUSTER) == 0) {
288				vfs_busy_pages(rbp, 0);
289			}
290			rbp->b_flags &= ~B_INVAL;
291			rbp->b_ioflags &= ~BIO_ERROR;
292			if ((rbp->b_flags & B_ASYNC) || rbp->b_iodone != NULL)
293				BUF_KERNPROC(rbp);
294			(void) VOP_STRATEGY(vp, rbp);
295			curproc->p_stats->p_ru.ru_inblock++;
296		}
297	}
298	if (reqbp)
299		return (bufwait(reqbp));
300	else
301		return (error);
302}
303
304/*
305 * If blocks are contiguous on disk, use this to provide clustered
306 * read ahead.  We will read as many blocks as possible sequentially
307 * and then parcel them up into logical blocks in the buffer hash table.
308 */
309static struct buf *
310cluster_rbuild(vp, filesize, lbn, blkno, size, run, fbp)
311	struct vnode *vp;
312	u_quad_t filesize;
313	daddr_t lbn;
314	daddr_t blkno;
315	long size;
316	int run;
317	struct buf *fbp;
318{
319	struct buf *bp, *tbp;
320	daddr_t bn;
321	int i, inc, j;
322
323	GIANT_REQUIRED;
324
325	KASSERT(size == vp->v_mount->mnt_stat.f_iosize,
326	    ("cluster_rbuild: size %ld != filesize %ld\n",
327	    size, vp->v_mount->mnt_stat.f_iosize));
328
329	/*
330	 * avoid a division
331	 */
332	while ((u_quad_t) size * (lbn + run) > filesize) {
333		--run;
334	}
335
336	if (fbp) {
337		tbp = fbp;
338		tbp->b_iocmd = BIO_READ;
339	} else {
340		tbp = getblk(vp, lbn, size, 0, 0);
341		if (tbp->b_flags & B_CACHE)
342			return tbp;
343		tbp->b_flags |= B_ASYNC | B_RAM;
344		tbp->b_iocmd = BIO_READ;
345	}
346
347	tbp->b_blkno = blkno;
348	if( (tbp->b_flags & B_MALLOC) ||
349		((tbp->b_flags & B_VMIO) == 0) || (run <= 1) )
350		return tbp;
351
352	bp = trypbuf(&cluster_pbuf_freecnt);
353	if (bp == 0)
354		return tbp;
355
356	/*
357	 * We are synthesizing a buffer out of vm_page_t's, but
358	 * if the block size is not page aligned then the starting
359	 * address may not be either.  Inherit the b_data offset
360	 * from the original buffer.
361	 */
362	bp->b_data = (char *)((vm_offset_t)bp->b_data |
363	    ((vm_offset_t)tbp->b_data & PAGE_MASK));
364	bp->b_flags = B_ASYNC | B_CLUSTER | B_VMIO;
365	bp->b_iocmd = BIO_READ;
366	bp->b_iodone = cluster_callback;
367	bp->b_blkno = blkno;
368	bp->b_lblkno = lbn;
369	bp->b_offset = tbp->b_offset;
370	KASSERT(bp->b_offset != NOOFFSET, ("cluster_rbuild: no buffer offset"));
371	pbgetvp(vp, bp);
372
373	TAILQ_INIT(&bp->b_cluster.cluster_head);
374
375	bp->b_bcount = 0;
376	bp->b_bufsize = 0;
377	bp->b_npages = 0;
378
379	inc = btodb(size);
380	for (bn = blkno, i = 0; i < run; ++i, bn += inc) {
381		if (i != 0) {
382			if ((bp->b_npages * PAGE_SIZE) +
383			    round_page(size) > vp->v_mount->mnt_iosize_max) {
384				break;
385			}
386
387			/*
388			 * Shortcut some checks and try to avoid buffers that
389			 * would block in the lock.  The same checks have to
390			 * be made again after we officially get the buffer.
391			 */
392			if ((tbp = incore(vp, lbn + i)) != NULL) {
393				if (BUF_LOCK(tbp, LK_EXCLUSIVE | LK_NOWAIT))
394					break;
395				BUF_UNLOCK(tbp);
396
397				for (j = 0; j < tbp->b_npages; j++) {
398					if (tbp->b_pages[j]->valid)
399						break;
400				}
401
402				if (j != tbp->b_npages)
403					break;
404
405				if (tbp->b_bcount != size)
406					break;
407			}
408
409			tbp = getblk(vp, lbn + i, size, 0, 0);
410
411			/*
412			 * Stop scanning if the buffer is fully valid
413			 * (marked B_CACHE), or locked (may be doing a
414			 * background write), or if the buffer is not
415			 * VMIO backed.  The clustering code can only deal
416			 * with VMIO-backed buffers.
417			 */
418			if ((tbp->b_flags & (B_CACHE|B_LOCKED)) ||
419				(tbp->b_flags & B_VMIO) == 0) {
420				bqrelse(tbp);
421				break;
422			}
423
424			/*
425			 * The buffer must be completely invalid in order to
426			 * take part in the cluster.  If it is partially valid
427			 * then we stop.
428			 */
429			for (j = 0;j < tbp->b_npages; j++) {
430				if (tbp->b_pages[j]->valid)
431					break;
432			}
433			if (j != tbp->b_npages) {
434				bqrelse(tbp);
435				break;
436			}
437
438			/*
439			 * Set a read-ahead mark as appropriate
440			 */
441			if ((fbp && (i == 1)) || (i == (run - 1)))
442				tbp->b_flags |= B_RAM;
443
444			/*
445			 * Set the buffer up for an async read (XXX should
446			 * we do this only if we do not wind up brelse()ing?).
447			 * Set the block number if it isn't set, otherwise
448			 * if it is make sure it matches the block number we
449			 * expect.
450			 */
451			tbp->b_flags |= B_ASYNC;
452			tbp->b_iocmd = BIO_READ;
453			if (tbp->b_blkno == tbp->b_lblkno) {
454				tbp->b_blkno = bn;
455			} else if (tbp->b_blkno != bn) {
456				brelse(tbp);
457				break;
458			}
459		}
460		/*
461		 * XXX fbp from caller may not be B_ASYNC, but we are going
462		 * to biodone() it in cluster_callback() anyway
463		 */
464		BUF_KERNPROC(tbp);
465		TAILQ_INSERT_TAIL(&bp->b_cluster.cluster_head,
466			tbp, b_cluster.cluster_entry);
467		for (j = 0; j < tbp->b_npages; j += 1) {
468			vm_page_t m;
469			m = tbp->b_pages[j];
470			vm_page_io_start(m);
471			vm_object_pip_add(m->object, 1);
472			if ((bp->b_npages == 0) ||
473				(bp->b_pages[bp->b_npages-1] != m)) {
474				bp->b_pages[bp->b_npages] = m;
475				bp->b_npages++;
476			}
477			if ((m->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL)
478				tbp->b_pages[j] = bogus_page;
479		}
480		/*
481		 * XXX shouldn't this be += size for both, like in
482		 * cluster_wbuild()?
483		 *
484		 * Don't inherit tbp->b_bufsize as it may be larger due to
485		 * a non-page-aligned size.  Instead just aggregate using
486		 * 'size'.
487		 */
488		if (tbp->b_bcount != size)
489			printf("warning: tbp->b_bcount wrong %ld vs %ld\n", tbp->b_bcount, size);
490		if (tbp->b_bufsize != size)
491			printf("warning: tbp->b_bufsize wrong %ld vs %ld\n", tbp->b_bufsize, size);
492		bp->b_bcount += size;
493		bp->b_bufsize += size;
494	}
495
496	/*
497	 * Fully valid pages in the cluster are already good and do not need
498	 * to be re-read from disk.  Replace the page with bogus_page
499	 */
500	for (j = 0; j < bp->b_npages; j++) {
501		if ((bp->b_pages[j]->valid & VM_PAGE_BITS_ALL) ==
502		    VM_PAGE_BITS_ALL) {
503			bp->b_pages[j] = bogus_page;
504		}
505	}
506	if (bp->b_bufsize > bp->b_kvasize)
507		panic("cluster_rbuild: b_bufsize(%ld) > b_kvasize(%d)\n",
508		    bp->b_bufsize, bp->b_kvasize);
509	bp->b_kvasize = bp->b_bufsize;
510
511	pmap_qenter(trunc_page((vm_offset_t) bp->b_data),
512		(vm_page_t *)bp->b_pages, bp->b_npages);
513	return (bp);
514}
515
516/*
517 * Cleanup after a clustered read or write.
518 * This is complicated by the fact that any of the buffers might have
519 * extra memory (if there were no empty buffer headers at allocbuf time)
520 * that we will need to shift around.
521 */
522void
523cluster_callback(bp)
524	struct buf *bp;
525{
526	struct buf *nbp, *tbp;
527	int error = 0;
528
529	GIANT_REQUIRED;
530
531	/*
532	 * Must propogate errors to all the components.
533	 */
534	if (bp->b_ioflags & BIO_ERROR)
535		error = bp->b_error;
536
537	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
538	/*
539	 * Move memory from the large cluster buffer into the component
540	 * buffers and mark IO as done on these.
541	 */
542	for (tbp = TAILQ_FIRST(&bp->b_cluster.cluster_head);
543		tbp; tbp = nbp) {
544		nbp = TAILQ_NEXT(&tbp->b_cluster, cluster_entry);
545		if (error) {
546			tbp->b_ioflags |= BIO_ERROR;
547			tbp->b_error = error;
548		} else {
549			tbp->b_dirtyoff = tbp->b_dirtyend = 0;
550			tbp->b_flags &= ~B_INVAL;
551			tbp->b_ioflags &= ~BIO_ERROR;
552			/*
553			 * XXX the bdwrite()/bqrelse() issued during
554			 * cluster building clears B_RELBUF (see bqrelse()
555			 * comment).  If direct I/O was specified, we have
556			 * to restore it here to allow the buffer and VM
557			 * to be freed.
558			 */
559			if (tbp->b_flags & B_DIRECT)
560				tbp->b_flags |= B_RELBUF;
561		}
562		bufdone(tbp);
563	}
564	relpbuf(bp, &cluster_pbuf_freecnt);
565}
566
567/*
568 *	cluster_wbuild_wb:
569 *
570 *	Implement modified write build for cluster.
571 *
572 *		write_behind = 0	write behind disabled
573 *		write_behind = 1	write behind normal (default)
574 *		write_behind = 2	write behind backed-off
575 */
576
577static __inline int
578cluster_wbuild_wb(struct vnode *vp, long size, daddr_t start_lbn, int len)
579{
580	int r = 0;
581
582	switch(write_behind) {
583	case 2:
584		if (start_lbn < len)
585			break;
586		start_lbn -= len;
587		/* fall through */
588	case 1:
589		r = cluster_wbuild(vp, size, start_lbn, len);
590		/* fall through */
591	default:
592		/* fall through */
593		break;
594	}
595	return(r);
596}
597
598/*
599 * Do clustered write for FFS.
600 *
601 * Three cases:
602 *	1. Write is not sequential (write asynchronously)
603 *	Write is sequential:
604 *	2.	beginning of cluster - begin cluster
605 *	3.	middle of a cluster - add to cluster
606 *	4.	end of a cluster - asynchronously write cluster
607 */
608void
609cluster_write(bp, filesize, seqcount)
610	struct buf *bp;
611	u_quad_t filesize;
612	int seqcount;
613{
614	struct vnode *vp;
615	daddr_t lbn;
616	int maxclen, cursize;
617	int lblocksize;
618	int async;
619
620	vp = bp->b_vp;
621	if (vp->v_type == VREG) {
622		async = vp->v_mount->mnt_flag & MNT_ASYNC;
623		lblocksize = vp->v_mount->mnt_stat.f_iosize;
624	} else {
625		async = 0;
626		lblocksize = bp->b_bufsize;
627	}
628	lbn = bp->b_lblkno;
629	KASSERT(bp->b_offset != NOOFFSET, ("cluster_write: no buffer offset"));
630
631	/* Initialize vnode to beginning of file. */
632	if (lbn == 0)
633		vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
634
635	if (vp->v_clen == 0 || lbn != vp->v_lastw + 1 ||
636	    (bp->b_blkno != vp->v_lasta + btodb(lblocksize))) {
637		maxclen = vp->v_mount->mnt_iosize_max / lblocksize - 1;
638		if (vp->v_clen != 0) {
639			/*
640			 * Next block is not sequential.
641			 *
642			 * If we are not writing at end of file, the process
643			 * seeked to another point in the file since its last
644			 * write, or we have reached our maximum cluster size,
645			 * then push the previous cluster. Otherwise try
646			 * reallocating to make it sequential.
647			 *
648			 * Change to algorithm: only push previous cluster if
649			 * it was sequential from the point of view of the
650			 * seqcount heuristic, otherwise leave the buffer
651			 * intact so we can potentially optimize the I/O
652			 * later on in the buf_daemon or update daemon
653			 * flush.
654			 */
655			cursize = vp->v_lastw - vp->v_cstart + 1;
656			if (((u_quad_t) bp->b_offset + lblocksize) != filesize ||
657			    lbn != vp->v_lastw + 1 || vp->v_clen <= cursize) {
658				if (!async && seqcount > 0) {
659					cluster_wbuild_wb(vp, lblocksize,
660						vp->v_cstart, cursize);
661				}
662			} else {
663				struct buf **bpp, **endbp;
664				struct cluster_save *buflist;
665
666				buflist = cluster_collectbufs(vp, bp);
667				endbp = &buflist->bs_children
668				    [buflist->bs_nchildren - 1];
669				if (VOP_REALLOCBLKS(vp, buflist)) {
670					/*
671					 * Failed, push the previous cluster
672					 * if *really* writing sequentially
673					 * in the logical file (seqcount > 1),
674					 * otherwise delay it in the hopes that
675					 * the low level disk driver can
676					 * optimize the write ordering.
677					 */
678					for (bpp = buflist->bs_children;
679					     bpp < endbp; bpp++)
680						brelse(*bpp);
681					free(buflist, M_SEGMENT);
682					if (seqcount > 1) {
683						cluster_wbuild_wb(vp,
684						    lblocksize, vp->v_cstart,
685						    cursize);
686					}
687				} else {
688					/*
689					 * Succeeded, keep building cluster.
690					 */
691					for (bpp = buflist->bs_children;
692					     bpp <= endbp; bpp++)
693						bdwrite(*bpp);
694					free(buflist, M_SEGMENT);
695					vp->v_lastw = lbn;
696					vp->v_lasta = bp->b_blkno;
697					return;
698				}
699			}
700		}
701		/*
702		 * Consider beginning a cluster. If at end of file, make
703		 * cluster as large as possible, otherwise find size of
704		 * existing cluster.
705		 */
706		if ((vp->v_type == VREG) &&
707			((u_quad_t) bp->b_offset + lblocksize) != filesize &&
708		    (bp->b_blkno == bp->b_lblkno) &&
709		    (VOP_BMAP(vp, lbn, NULL, &bp->b_blkno, &maxclen, NULL) ||
710		     bp->b_blkno == -1)) {
711			bawrite(bp);
712			vp->v_clen = 0;
713			vp->v_lasta = bp->b_blkno;
714			vp->v_cstart = lbn + 1;
715			vp->v_lastw = lbn;
716			return;
717		}
718		vp->v_clen = maxclen;
719		if (!async && maxclen == 0) {	/* I/O not contiguous */
720			vp->v_cstart = lbn + 1;
721			bawrite(bp);
722		} else {	/* Wait for rest of cluster */
723			vp->v_cstart = lbn;
724			bdwrite(bp);
725		}
726	} else if (lbn == vp->v_cstart + vp->v_clen) {
727		/*
728		 * At end of cluster, write it out if seqcount tells us we
729		 * are operating sequentially, otherwise let the buf or
730		 * update daemon handle it.
731		 */
732		bdwrite(bp);
733		if (seqcount > 1)
734			cluster_wbuild_wb(vp, lblocksize, vp->v_cstart, vp->v_clen + 1);
735		vp->v_clen = 0;
736		vp->v_cstart = lbn + 1;
737	} else if (vm_page_count_severe()) {
738		/*
739		 * We are low on memory, get it going NOW
740		 */
741		bawrite(bp);
742	} else {
743		/*
744		 * In the middle of a cluster, so just delay the I/O for now.
745		 */
746		bdwrite(bp);
747	}
748	vp->v_lastw = lbn;
749	vp->v_lasta = bp->b_blkno;
750}
751
752
753/*
754 * This is an awful lot like cluster_rbuild...wish they could be combined.
755 * The last lbn argument is the current block on which I/O is being
756 * performed.  Check to see that it doesn't fall in the middle of
757 * the current block (if last_bp == NULL).
758 */
759int
760cluster_wbuild(vp, size, start_lbn, len)
761	struct vnode *vp;
762	long size;
763	daddr_t start_lbn;
764	int len;
765{
766	struct buf *bp, *tbp;
767	int i, j, s;
768	int totalwritten = 0;
769	int dbsize = btodb(size);
770
771	GIANT_REQUIRED;
772
773	while (len > 0) {
774		s = splbio();
775		/*
776		 * If the buffer is not delayed-write (i.e. dirty), or it
777		 * is delayed-write but either locked or inval, it cannot
778		 * partake in the clustered write.
779		 */
780		if (((tbp = gbincore(vp, start_lbn)) == NULL) ||
781		  ((tbp->b_flags & (B_LOCKED | B_INVAL | B_DELWRI)) != B_DELWRI) ||
782		  BUF_LOCK(tbp, LK_EXCLUSIVE | LK_NOWAIT)) {
783			++start_lbn;
784			--len;
785			splx(s);
786			continue;
787		}
788		bremfree(tbp);
789		tbp->b_flags &= ~B_DONE;
790		splx(s);
791
792		/*
793		 * Extra memory in the buffer, punt on this buffer.
794		 * XXX we could handle this in most cases, but we would
795		 * have to push the extra memory down to after our max
796		 * possible cluster size and then potentially pull it back
797		 * up if the cluster was terminated prematurely--too much
798		 * hassle.
799		 */
800		if (((tbp->b_flags & (B_CLUSTEROK | B_MALLOC | B_VMIO)) !=
801		     (B_CLUSTEROK | B_VMIO)) ||
802		  (tbp->b_bcount != tbp->b_bufsize) ||
803		  (tbp->b_bcount != size) ||
804		  (len == 1) ||
805		  ((bp = getpbuf(&cluster_pbuf_freecnt)) == NULL)) {
806			totalwritten += tbp->b_bufsize;
807			bawrite(tbp);
808			++start_lbn;
809			--len;
810			continue;
811		}
812
813		/*
814		 * We got a pbuf to make the cluster in.
815		 * so initialise it.
816		 */
817		TAILQ_INIT(&bp->b_cluster.cluster_head);
818		bp->b_bcount = 0;
819		bp->b_magic = tbp->b_magic;
820		bp->b_op = tbp->b_op;
821		bp->b_bufsize = 0;
822		bp->b_npages = 0;
823		if (tbp->b_wcred != NOCRED)
824			bp->b_wcred = crhold(tbp->b_wcred);
825
826		bp->b_blkno = tbp->b_blkno;
827		bp->b_lblkno = tbp->b_lblkno;
828		bp->b_offset = tbp->b_offset;
829
830		/*
831		 * We are synthesizing a buffer out of vm_page_t's, but
832		 * if the block size is not page aligned then the starting
833		 * address may not be either.  Inherit the b_data offset
834		 * from the original buffer.
835		 */
836		bp->b_data = (char *)((vm_offset_t)bp->b_data |
837		    ((vm_offset_t)tbp->b_data & PAGE_MASK));
838		bp->b_flags |= B_CLUSTER |
839				(tbp->b_flags & (B_VMIO | B_NEEDCOMMIT | B_NOWDRAIN));
840		bp->b_iodone = cluster_callback;
841		pbgetvp(vp, bp);
842		/*
843		 * From this location in the file, scan forward to see
844		 * if there are buffers with adjacent data that need to
845		 * be written as well.
846		 */
847		for (i = 0; i < len; ++i, ++start_lbn) {
848			if (i != 0) { /* If not the first buffer */
849				s = splbio();
850				/*
851				 * If the adjacent data is not even in core it
852				 * can't need to be written.
853				 */
854				if ((tbp = gbincore(vp, start_lbn)) == NULL) {
855					splx(s);
856					break;
857				}
858
859				/*
860				 * If it IS in core, but has different
861				 * characteristics, or is locked (which
862				 * means it could be undergoing a background
863				 * I/O or be in a weird state), then don't
864				 * cluster with it.
865				 */
866				if ((tbp->b_flags & (B_VMIO | B_CLUSTEROK |
867				    B_INVAL | B_DELWRI | B_NEEDCOMMIT))
868				  != (B_DELWRI | B_CLUSTEROK |
869				    (bp->b_flags & (B_VMIO | B_NEEDCOMMIT))) ||
870				    (tbp->b_flags & B_LOCKED) ||
871				    tbp->b_wcred != bp->b_wcred ||
872				    BUF_LOCK(tbp, LK_EXCLUSIVE | LK_NOWAIT)) {
873					splx(s);
874					break;
875				}
876
877				/*
878				 * Check that the combined cluster
879				 * would make sense with regard to pages
880				 * and would not be too large
881				 */
882				if ((tbp->b_bcount != size) ||
883				  ((bp->b_blkno + (dbsize * i)) !=
884				    tbp->b_blkno) ||
885				  ((tbp->b_npages + bp->b_npages) >
886				    (vp->v_mount->mnt_iosize_max / PAGE_SIZE))) {
887					BUF_UNLOCK(tbp);
888					splx(s);
889					break;
890				}
891				/*
892				 * Ok, it's passed all the tests,
893				 * so remove it from the free list
894				 * and mark it busy. We will use it.
895				 */
896				bremfree(tbp);
897				tbp->b_flags &= ~B_DONE;
898				splx(s);
899			} /* end of code for non-first buffers only */
900			/* check for latent dependencies to be handled */
901			if ((LIST_FIRST(&tbp->b_dep)) != NULL)
902				buf_start(tbp);
903			/*
904			 * If the IO is via the VM then we do some
905			 * special VM hackery (yuck).  Since the buffer's
906			 * block size may not be page-aligned it is possible
907			 * for a page to be shared between two buffers.  We
908			 * have to get rid of the duplication when building
909			 * the cluster.
910			 */
911			if (tbp->b_flags & B_VMIO) {
912				vm_page_t m;
913
914				if (i != 0) { /* if not first buffer */
915					for (j = 0; j < tbp->b_npages; j += 1) {
916						m = tbp->b_pages[j];
917						if (m->flags & PG_BUSY) {
918							bqrelse(tbp);
919							goto finishcluster;
920						}
921					}
922				}
923
924				for (j = 0; j < tbp->b_npages; j += 1) {
925					m = tbp->b_pages[j];
926					vm_page_io_start(m);
927					vm_object_pip_add(m->object, 1);
928					if ((bp->b_npages == 0) ||
929					  (bp->b_pages[bp->b_npages - 1] != m)) {
930						bp->b_pages[bp->b_npages] = m;
931						bp->b_npages++;
932					}
933				}
934			}
935			bp->b_bcount += size;
936			bp->b_bufsize += size;
937
938			s = splbio();
939			bundirty(tbp);
940			tbp->b_flags &= ~B_DONE;
941			tbp->b_ioflags &= ~BIO_ERROR;
942			tbp->b_flags |= B_ASYNC;
943			tbp->b_iocmd = BIO_WRITE;
944			reassignbuf(tbp, tbp->b_vp);	/* put on clean list */
945			++tbp->b_vp->v_numoutput;
946			splx(s);
947			BUF_KERNPROC(tbp);
948			TAILQ_INSERT_TAIL(&bp->b_cluster.cluster_head,
949				tbp, b_cluster.cluster_entry);
950		}
951	finishcluster:
952		pmap_qenter(trunc_page((vm_offset_t) bp->b_data),
953			(vm_page_t *) bp->b_pages, bp->b_npages);
954		if (bp->b_bufsize > bp->b_kvasize)
955			panic(
956			    "cluster_wbuild: b_bufsize(%ld) > b_kvasize(%d)\n",
957			    bp->b_bufsize, bp->b_kvasize);
958		bp->b_kvasize = bp->b_bufsize;
959		totalwritten += bp->b_bufsize;
960		bp->b_dirtyoff = 0;
961		bp->b_dirtyend = bp->b_bufsize;
962		bawrite(bp);
963
964		len -= i;
965	}
966	return totalwritten;
967}
968
969/*
970 * Collect together all the buffers in a cluster.
971 * Plus add one additional buffer.
972 */
973static struct cluster_save *
974cluster_collectbufs(vp, last_bp)
975	struct vnode *vp;
976	struct buf *last_bp;
977{
978	struct cluster_save *buflist;
979	struct buf *bp;
980	daddr_t lbn;
981	int i, len;
982
983	len = vp->v_lastw - vp->v_cstart + 1;
984	buflist = malloc(sizeof(struct buf *) * (len + 1) + sizeof(*buflist),
985	    M_SEGMENT, M_WAITOK);
986	buflist->bs_nchildren = 0;
987	buflist->bs_children = (struct buf **) (buflist + 1);
988	for (lbn = vp->v_cstart, i = 0; i < len; lbn++, i++) {
989		(void) bread(vp, lbn, last_bp->b_bcount, NOCRED, &bp);
990		buflist->bs_children[i] = bp;
991		if (bp->b_blkno == bp->b_lblkno)
992			VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno,
993				NULL, NULL);
994	}
995	buflist->bs_children[i] = bp = last_bp;
996	if (bp->b_blkno == bp->b_lblkno)
997		VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno,
998			NULL, NULL);
999	buflist->bs_nchildren = i + 1;
1000	return (buflist);
1001}
1002