vfs_cluster.c revision 84827
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 84827 2001-10-11 23:38:17Z jhb $
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	bp->b_data = (char *)((vm_offset_t)bp->b_data |
357	    ((vm_offset_t)tbp->b_data & PAGE_MASK));
358	bp->b_flags = B_ASYNC | B_CLUSTER | B_VMIO;
359	bp->b_iocmd = BIO_READ;
360	bp->b_iodone = cluster_callback;
361	bp->b_blkno = blkno;
362	bp->b_lblkno = lbn;
363	bp->b_offset = tbp->b_offset;
364	KASSERT(bp->b_offset != NOOFFSET, ("cluster_rbuild: no buffer offset"));
365	pbgetvp(vp, bp);
366
367	TAILQ_INIT(&bp->b_cluster.cluster_head);
368
369	bp->b_bcount = 0;
370	bp->b_bufsize = 0;
371	bp->b_npages = 0;
372
373	inc = btodb(size);
374	for (bn = blkno, i = 0; i < run; ++i, bn += inc) {
375		if (i != 0) {
376			if ((bp->b_npages * PAGE_SIZE) +
377				round_page(size) > vp->v_mount->mnt_iosize_max)
378				break;
379
380			if ((tbp = incore(vp, lbn + i)) != NULL) {
381				if (BUF_LOCK(tbp, LK_EXCLUSIVE | LK_NOWAIT))
382					break;
383				BUF_UNLOCK(tbp);
384
385				for (j = 0; j < tbp->b_npages; j++)
386					if (tbp->b_pages[j]->valid)
387						break;
388
389				if (j != tbp->b_npages)
390					break;
391
392				if (tbp->b_bcount != size)
393					break;
394			}
395
396			tbp = getblk(vp, lbn + i, size, 0, 0);
397
398			/*
399			 * If the buffer is already fully valid or locked
400			 * (which could also mean that a background write is
401			 * in progress), or the buffer is not backed by VMIO,
402			 * stop.
403			 */
404			if ((tbp->b_flags & (B_CACHE|B_LOCKED)) ||
405				(tbp->b_flags & B_VMIO) == 0) {
406				bqrelse(tbp);
407				break;
408			}
409
410			for (j = 0;j < tbp->b_npages; j++) {
411				if (tbp->b_pages[j]->valid)
412					break;
413			}
414
415			if (j != tbp->b_npages) {
416				bqrelse(tbp);
417				break;
418			}
419
420			if ((fbp && (i == 1)) || (i == (run - 1)))
421				tbp->b_flags |= B_RAM;
422			tbp->b_flags |= B_ASYNC;
423			tbp->b_iocmd = BIO_READ;
424			if (tbp->b_blkno == tbp->b_lblkno) {
425				tbp->b_blkno = bn;
426			} else if (tbp->b_blkno != bn) {
427				brelse(tbp);
428				break;
429			}
430		}
431		/*
432		 * XXX fbp from caller may not be B_ASYNC, but we are going
433		 * to biodone() it in cluster_callback() anyway
434		 */
435		BUF_KERNPROC(tbp);
436		TAILQ_INSERT_TAIL(&bp->b_cluster.cluster_head,
437			tbp, b_cluster.cluster_entry);
438		for (j = 0; j < tbp->b_npages; j += 1) {
439			vm_page_t m;
440			m = tbp->b_pages[j];
441			vm_page_io_start(m);
442			vm_object_pip_add(m->object, 1);
443			if ((bp->b_npages == 0) ||
444				(bp->b_pages[bp->b_npages-1] != m)) {
445				bp->b_pages[bp->b_npages] = m;
446				bp->b_npages++;
447			}
448			if ((m->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL)
449				tbp->b_pages[j] = bogus_page;
450		}
451		bp->b_bcount += tbp->b_bcount;
452		bp->b_bufsize += tbp->b_bufsize;
453	}
454
455	for(j=0;j<bp->b_npages;j++) {
456		if ((bp->b_pages[j]->valid & VM_PAGE_BITS_ALL) ==
457			VM_PAGE_BITS_ALL)
458			bp->b_pages[j] = bogus_page;
459	}
460	if (bp->b_bufsize > bp->b_kvasize)
461		panic("cluster_rbuild: b_bufsize(%ld) > b_kvasize(%d)\n",
462		    bp->b_bufsize, bp->b_kvasize);
463	bp->b_kvasize = bp->b_bufsize;
464
465	pmap_qenter(trunc_page((vm_offset_t) bp->b_data),
466		(vm_page_t *)bp->b_pages, bp->b_npages);
467	return (bp);
468}
469
470/*
471 * Cleanup after a clustered read or write.
472 * This is complicated by the fact that any of the buffers might have
473 * extra memory (if there were no empty buffer headers at allocbuf time)
474 * that we will need to shift around.
475 */
476void
477cluster_callback(bp)
478	struct buf *bp;
479{
480	struct buf *nbp, *tbp;
481	int error = 0;
482
483	GIANT_REQUIRED;
484
485	/*
486	 * Must propogate errors to all the components.
487	 */
488	if (bp->b_ioflags & BIO_ERROR)
489		error = bp->b_error;
490
491	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
492	/*
493	 * Move memory from the large cluster buffer into the component
494	 * buffers and mark IO as done on these.
495	 */
496	for (tbp = TAILQ_FIRST(&bp->b_cluster.cluster_head);
497		tbp; tbp = nbp) {
498		nbp = TAILQ_NEXT(&tbp->b_cluster, cluster_entry);
499		if (error) {
500			tbp->b_ioflags |= BIO_ERROR;
501			tbp->b_error = error;
502		} else {
503			tbp->b_dirtyoff = tbp->b_dirtyend = 0;
504			tbp->b_flags &= ~B_INVAL;
505			tbp->b_ioflags &= ~BIO_ERROR;
506			/*
507			 * XXX the bdwrite()/bqrelse() issued during
508			 * cluster building clears B_RELBUF (see bqrelse()
509			 * comment).  If direct I/O was specified, we have
510			 * to restore it here to allow the buffer and VM
511			 * to be freed.
512			 */
513			if (tbp->b_flags & B_DIRECT)
514				tbp->b_flags |= B_RELBUF;
515		}
516		bufdone(tbp);
517	}
518	relpbuf(bp, &cluster_pbuf_freecnt);
519}
520
521/*
522 *	cluster_wbuild_wb:
523 *
524 *	Implement modified write build for cluster.
525 *
526 *		write_behind = 0	write behind disabled
527 *		write_behind = 1	write behind normal (default)
528 *		write_behind = 2	write behind backed-off
529 */
530
531static __inline int
532cluster_wbuild_wb(struct vnode *vp, long size, daddr_t start_lbn, int len)
533{
534	int r = 0;
535
536	switch(write_behind) {
537	case 2:
538		if (start_lbn < len)
539			break;
540		start_lbn -= len;
541		/* fall through */
542	case 1:
543		r = cluster_wbuild(vp, size, start_lbn, len);
544		/* fall through */
545	default:
546		/* fall through */
547		break;
548	}
549	return(r);
550}
551
552/*
553 * Do clustered write for FFS.
554 *
555 * Three cases:
556 *	1. Write is not sequential (write asynchronously)
557 *	Write is sequential:
558 *	2.	beginning of cluster - begin cluster
559 *	3.	middle of a cluster - add to cluster
560 *	4.	end of a cluster - asynchronously write cluster
561 */
562void
563cluster_write(bp, filesize, seqcount)
564	struct buf *bp;
565	u_quad_t filesize;
566	int seqcount;
567{
568	struct vnode *vp;
569	daddr_t lbn;
570	int maxclen, cursize;
571	int lblocksize;
572	int async;
573
574	vp = bp->b_vp;
575	if (vp->v_type == VREG) {
576		async = vp->v_mount->mnt_flag & MNT_ASYNC;
577		lblocksize = vp->v_mount->mnt_stat.f_iosize;
578	} else {
579		async = 0;
580		lblocksize = bp->b_bufsize;
581	}
582	lbn = bp->b_lblkno;
583	KASSERT(bp->b_offset != NOOFFSET, ("cluster_write: no buffer offset"));
584
585	/* Initialize vnode to beginning of file. */
586	if (lbn == 0)
587		vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
588
589	if (vp->v_clen == 0 || lbn != vp->v_lastw + 1 ||
590	    (bp->b_blkno != vp->v_lasta + btodb(lblocksize))) {
591		maxclen = vp->v_mount->mnt_iosize_max / lblocksize - 1;
592		if (vp->v_clen != 0) {
593			/*
594			 * Next block is not sequential.
595			 *
596			 * If we are not writing at end of file, the process
597			 * seeked to another point in the file since its last
598			 * write, or we have reached our maximum cluster size,
599			 * then push the previous cluster. Otherwise try
600			 * reallocating to make it sequential.
601			 *
602			 * Change to algorithm: only push previous cluster if
603			 * it was sequential from the point of view of the
604			 * seqcount heuristic, otherwise leave the buffer
605			 * intact so we can potentially optimize the I/O
606			 * later on in the buf_daemon or update daemon
607			 * flush.
608			 */
609			cursize = vp->v_lastw - vp->v_cstart + 1;
610			if (((u_quad_t) bp->b_offset + lblocksize) != filesize ||
611			    lbn != vp->v_lastw + 1 || vp->v_clen <= cursize) {
612				if (!async && seqcount > 0) {
613					cluster_wbuild_wb(vp, lblocksize,
614						vp->v_cstart, cursize);
615				}
616			} else {
617				struct buf **bpp, **endbp;
618				struct cluster_save *buflist;
619
620				buflist = cluster_collectbufs(vp, bp);
621				endbp = &buflist->bs_children
622				    [buflist->bs_nchildren - 1];
623				if (VOP_REALLOCBLKS(vp, buflist)) {
624					/*
625					 * Failed, push the previous cluster
626					 * if *really* writing sequentially
627					 * in the logical file (seqcount > 1),
628					 * otherwise delay it in the hopes that
629					 * the low level disk driver can
630					 * optimize the write ordering.
631					 */
632					for (bpp = buflist->bs_children;
633					     bpp < endbp; bpp++)
634						brelse(*bpp);
635					free(buflist, M_SEGMENT);
636					if (seqcount > 1) {
637						cluster_wbuild_wb(vp,
638						    lblocksize, vp->v_cstart,
639						    cursize);
640					}
641				} else {
642					/*
643					 * Succeeded, keep building cluster.
644					 */
645					for (bpp = buflist->bs_children;
646					     bpp <= endbp; bpp++)
647						bdwrite(*bpp);
648					free(buflist, M_SEGMENT);
649					vp->v_lastw = lbn;
650					vp->v_lasta = bp->b_blkno;
651					return;
652				}
653			}
654		}
655		/*
656		 * Consider beginning a cluster. If at end of file, make
657		 * cluster as large as possible, otherwise find size of
658		 * existing cluster.
659		 */
660		if ((vp->v_type == VREG) &&
661			((u_quad_t) bp->b_offset + lblocksize) != filesize &&
662		    (bp->b_blkno == bp->b_lblkno) &&
663		    (VOP_BMAP(vp, lbn, NULL, &bp->b_blkno, &maxclen, NULL) ||
664		     bp->b_blkno == -1)) {
665			bawrite(bp);
666			vp->v_clen = 0;
667			vp->v_lasta = bp->b_blkno;
668			vp->v_cstart = lbn + 1;
669			vp->v_lastw = lbn;
670			return;
671		}
672		vp->v_clen = maxclen;
673		if (!async && maxclen == 0) {	/* I/O not contiguous */
674			vp->v_cstart = lbn + 1;
675			bawrite(bp);
676		} else {	/* Wait for rest of cluster */
677			vp->v_cstart = lbn;
678			bdwrite(bp);
679		}
680	} else if (lbn == vp->v_cstart + vp->v_clen) {
681		/*
682		 * At end of cluster, write it out if seqcount tells us we
683		 * are operating sequentially, otherwise let the buf or
684		 * update daemon handle it.
685		 */
686		bdwrite(bp);
687		if (seqcount > 1)
688			cluster_wbuild_wb(vp, lblocksize, vp->v_cstart, vp->v_clen + 1);
689		vp->v_clen = 0;
690		vp->v_cstart = lbn + 1;
691	} else if (vm_page_count_severe()) {
692		/*
693		 * We are low on memory, get it going NOW
694		 */
695		bawrite(bp);
696	} else {
697		/*
698		 * In the middle of a cluster, so just delay the I/O for now.
699		 */
700		bdwrite(bp);
701	}
702	vp->v_lastw = lbn;
703	vp->v_lasta = bp->b_blkno;
704}
705
706
707/*
708 * This is an awful lot like cluster_rbuild...wish they could be combined.
709 * The last lbn argument is the current block on which I/O is being
710 * performed.  Check to see that it doesn't fall in the middle of
711 * the current block (if last_bp == NULL).
712 */
713int
714cluster_wbuild(vp, size, start_lbn, len)
715	struct vnode *vp;
716	long size;
717	daddr_t start_lbn;
718	int len;
719{
720	struct buf *bp, *tbp;
721	int i, j, s;
722	int totalwritten = 0;
723	int dbsize = btodb(size);
724
725	GIANT_REQUIRED;
726
727	while (len > 0) {
728		s = splbio();
729		/*
730		 * If the buffer is not delayed-write (i.e. dirty), or it
731		 * is delayed-write but either locked or inval, it cannot
732		 * partake in the clustered write.
733		 */
734		if (((tbp = gbincore(vp, start_lbn)) == NULL) ||
735		  ((tbp->b_flags & (B_LOCKED | B_INVAL | B_DELWRI)) != B_DELWRI) ||
736		  BUF_LOCK(tbp, LK_EXCLUSIVE | LK_NOWAIT)) {
737			++start_lbn;
738			--len;
739			splx(s);
740			continue;
741		}
742		bremfree(tbp);
743		tbp->b_flags &= ~B_DONE;
744		splx(s);
745
746		/*
747		 * Extra memory in the buffer, punt on this buffer.
748		 * XXX we could handle this in most cases, but we would
749		 * have to push the extra memory down to after our max
750		 * possible cluster size and then potentially pull it back
751		 * up if the cluster was terminated prematurely--too much
752		 * hassle.
753		 */
754		if (((tbp->b_flags & (B_CLUSTEROK | B_MALLOC | B_VMIO)) !=
755		     (B_CLUSTEROK | B_VMIO)) ||
756		  (tbp->b_bcount != tbp->b_bufsize) ||
757		  (tbp->b_bcount != size) ||
758		  (len == 1) ||
759		  ((bp = getpbuf(&cluster_pbuf_freecnt)) == NULL)) {
760			totalwritten += tbp->b_bufsize;
761			bawrite(tbp);
762			++start_lbn;
763			--len;
764			continue;
765		}
766
767		/*
768		 * We got a pbuf to make the cluster in.
769		 * so initialise it.
770		 */
771		TAILQ_INIT(&bp->b_cluster.cluster_head);
772		bp->b_bcount = 0;
773		bp->b_magic = tbp->b_magic;
774		bp->b_op = tbp->b_op;
775		bp->b_bufsize = 0;
776		bp->b_npages = 0;
777		if (tbp->b_wcred != NOCRED)
778			bp->b_wcred = crhold(tbp->b_wcred);
779
780		bp->b_blkno = tbp->b_blkno;
781		bp->b_lblkno = tbp->b_lblkno;
782		bp->b_offset = tbp->b_offset;
783		bp->b_data = (char *)((vm_offset_t)bp->b_data |
784		    ((vm_offset_t)tbp->b_data & PAGE_MASK));
785		bp->b_flags |= B_CLUSTER |
786				(tbp->b_flags & (B_VMIO | B_NEEDCOMMIT));
787		bp->b_iodone = cluster_callback;
788		pbgetvp(vp, bp);
789		/*
790		 * From this location in the file, scan forward to see
791		 * if there are buffers with adjacent data that need to
792		 * be written as well.
793		 */
794		for (i = 0; i < len; ++i, ++start_lbn) {
795			if (i != 0) { /* If not the first buffer */
796				s = splbio();
797				/*
798				 * If the adjacent data is not even in core it
799				 * can't need to be written.
800				 */
801				if ((tbp = gbincore(vp, start_lbn)) == NULL) {
802					splx(s);
803					break;
804				}
805
806				/*
807				 * If it IS in core, but has different
808				 * characteristics, or is locked (which
809				 * means it could be undergoing a background
810				 * I/O or be in a weird state), then don't
811				 * cluster with it.
812				 */
813				if ((tbp->b_flags & (B_VMIO | B_CLUSTEROK |
814				    B_INVAL | B_DELWRI | B_NEEDCOMMIT))
815				  != (B_DELWRI | B_CLUSTEROK |
816				    (bp->b_flags & (B_VMIO | B_NEEDCOMMIT))) ||
817				    (tbp->b_flags & B_LOCKED) ||
818				    tbp->b_wcred != bp->b_wcred ||
819				    BUF_LOCK(tbp, LK_EXCLUSIVE | LK_NOWAIT)) {
820					splx(s);
821					break;
822				}
823
824				/*
825				 * Check that the combined cluster
826				 * would make sense with regard to pages
827				 * and would not be too large
828				 */
829				if ((tbp->b_bcount != size) ||
830				  ((bp->b_blkno + (dbsize * i)) !=
831				    tbp->b_blkno) ||
832				  ((tbp->b_npages + bp->b_npages) >
833				    (vp->v_mount->mnt_iosize_max / PAGE_SIZE))) {
834					BUF_UNLOCK(tbp);
835					splx(s);
836					break;
837				}
838				/*
839				 * Ok, it's passed all the tests,
840				 * so remove it from the free list
841				 * and mark it busy. We will use it.
842				 */
843				bremfree(tbp);
844				tbp->b_flags &= ~B_DONE;
845				splx(s);
846			} /* end of code for non-first buffers only */
847			/* check for latent dependencies to be handled */
848			if ((LIST_FIRST(&tbp->b_dep)) != NULL)
849				buf_start(tbp);
850			/*
851			 * If the IO is via the VM then we do some
852			 * special VM hackery. (yuck)
853			 */
854			if (tbp->b_flags & B_VMIO) {
855				vm_page_t m;
856
857				if (i != 0) { /* if not first buffer */
858					for (j = 0; j < tbp->b_npages; j += 1) {
859						m = tbp->b_pages[j];
860						if (m->flags & PG_BUSY) {
861							bqrelse(tbp);
862							goto finishcluster;
863						}
864					}
865				}
866
867				for (j = 0; j < tbp->b_npages; j += 1) {
868					m = tbp->b_pages[j];
869					vm_page_io_start(m);
870					vm_object_pip_add(m->object, 1);
871					if ((bp->b_npages == 0) ||
872					  (bp->b_pages[bp->b_npages - 1] != m)) {
873						bp->b_pages[bp->b_npages] = m;
874						bp->b_npages++;
875					}
876				}
877			}
878			bp->b_bcount += size;
879			bp->b_bufsize += size;
880
881			s = splbio();
882			bundirty(tbp);
883			tbp->b_flags &= ~B_DONE;
884			tbp->b_ioflags &= ~BIO_ERROR;
885			tbp->b_flags |= B_ASYNC;
886			tbp->b_iocmd = BIO_WRITE;
887			reassignbuf(tbp, tbp->b_vp);	/* put on clean list */
888			++tbp->b_vp->v_numoutput;
889			splx(s);
890			BUF_KERNPROC(tbp);
891			TAILQ_INSERT_TAIL(&bp->b_cluster.cluster_head,
892				tbp, b_cluster.cluster_entry);
893		}
894	finishcluster:
895		pmap_qenter(trunc_page((vm_offset_t) bp->b_data),
896			(vm_page_t *) bp->b_pages, bp->b_npages);
897		if (bp->b_bufsize > bp->b_kvasize)
898			panic(
899			    "cluster_wbuild: b_bufsize(%ld) > b_kvasize(%d)\n",
900			    bp->b_bufsize, bp->b_kvasize);
901		bp->b_kvasize = bp->b_bufsize;
902		totalwritten += bp->b_bufsize;
903		bp->b_dirtyoff = 0;
904		bp->b_dirtyend = bp->b_bufsize;
905		bawrite(bp);
906
907		len -= i;
908	}
909	return totalwritten;
910}
911
912/*
913 * Collect together all the buffers in a cluster.
914 * Plus add one additional buffer.
915 */
916static struct cluster_save *
917cluster_collectbufs(vp, last_bp)
918	struct vnode *vp;
919	struct buf *last_bp;
920{
921	struct cluster_save *buflist;
922	struct buf *bp;
923	daddr_t lbn;
924	int i, len;
925
926	len = vp->v_lastw - vp->v_cstart + 1;
927	buflist = malloc(sizeof(struct buf *) * (len + 1) + sizeof(*buflist),
928	    M_SEGMENT, M_WAITOK);
929	buflist->bs_nchildren = 0;
930	buflist->bs_children = (struct buf **) (buflist + 1);
931	for (lbn = vp->v_cstart, i = 0; i < len; lbn++, i++) {
932		(void) bread(vp, lbn, last_bp->b_bcount, NOCRED, &bp);
933		buflist->bs_children[i] = bp;
934		if (bp->b_blkno == bp->b_lblkno)
935			VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno,
936				NULL, NULL);
937	}
938	buflist->bs_children[i] = bp = last_bp;
939	if (bp->b_blkno == bp->b_lblkno)
940		VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno,
941			NULL, NULL);
942	buflist->bs_nchildren = i + 1;
943	return (buflist);
944}
945