xref: /freebsd/sys/kern/vfs_cluster.c (revision 64db83a8ab2d1f72a9b2174b39d2ef42b5b0580c)
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$
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 <vm/vm.h>
52 #include <vm/vm_object.h>
53 #include <vm/vm_page.h>
54 #include <sys/sysctl.h>
55 
56 #if defined(CLUSTERDEBUG)
57 #include <sys/sysctl.h>
58 static int	rcluster= 0;
59 SYSCTL_INT(_debug, OID_AUTO, rcluster, CTLFLAG_RW, &rcluster, 0, "");
60 #endif
61 
62 static MALLOC_DEFINE(M_SEGMENT, "cluster_save buffer", "cluster_save buffer");
63 
64 static struct cluster_save *
65 	cluster_collectbufs __P((struct vnode *vp, struct buf *last_bp));
66 static struct buf *
67 	cluster_rbuild __P((struct vnode *vp, u_quad_t filesize, daddr_t lbn,
68 			    daddr_t blkno, long size, int run, struct buf *fbp));
69 
70 static int write_behind = 1;
71 SYSCTL_INT(_vfs, OID_AUTO, write_behind, CTLFLAG_RW, &write_behind, 0, "");
72 
73 extern vm_page_t	bogus_page;
74 
75 extern int cluster_pbuf_freecnt;
76 
77 /*
78  * Maximum number of blocks for read-ahead.
79  */
80 #define MAXRA 32
81 
82 /*
83  * This replaces bread.
84  */
85 int
86 cluster_read(vp, filesize, lblkno, size, cred, totread, seqcount, bpp)
87 	struct vnode *vp;
88 	u_quad_t filesize;
89 	daddr_t lblkno;
90 	long size;
91 	struct ucred *cred;
92 	long totread;
93 	int seqcount;
94 	struct buf **bpp;
95 {
96 	struct buf *bp, *rbp, *reqbp;
97 	daddr_t blkno, origblkno;
98 	int error, num_ra;
99 	int i;
100 	int maxra, racluster;
101 	long origtotread;
102 
103 	error = 0;
104 
105 	/*
106 	 * Try to limit the amount of read-ahead by a few
107 	 * ad-hoc parameters.  This needs work!!!
108 	 */
109 	racluster = vp->v_mount->mnt_iosize_max / size;
110 	maxra = 2 * racluster + (totread / size);
111 	if (maxra > MAXRA)
112 		maxra = MAXRA;
113 	if (maxra > nbuf/8)
114 		maxra = nbuf/8;
115 
116 	/*
117 	 * get the requested block
118 	 */
119 	*bpp = reqbp = bp = getblk(vp, lblkno, size, 0, 0);
120 	origblkno = lblkno;
121 	origtotread = totread;
122 
123 	/*
124 	 * if it is in the cache, then check to see if the reads have been
125 	 * sequential.  If they have, then try some read-ahead, otherwise
126 	 * back-off on prospective read-aheads.
127 	 */
128 	if (bp->b_flags & B_CACHE) {
129 		if (!seqcount) {
130 			return 0;
131 		} else if ((bp->b_flags & B_RAM) == 0) {
132 			return 0;
133 		} else {
134 			int s;
135 			struct buf *tbp;
136 			bp->b_flags &= ~B_RAM;
137 			/*
138 			 * We do the spl here so that there is no window
139 			 * between the incore and the b_usecount increment
140 			 * below.  We opt to keep the spl out of the loop
141 			 * for efficiency.
142 			 */
143 			s = splbio();
144 			for (i = 1; i < maxra; i++) {
145 
146 				if (!(tbp = incore(vp, lblkno+i))) {
147 					break;
148 				}
149 
150 				/*
151 				 * Set another read-ahead mark so we know
152 				 * to check again.
153 				 */
154 				if (((i % racluster) == (racluster - 1)) ||
155 					(i == (maxra - 1)))
156 					tbp->b_flags |= B_RAM;
157 			}
158 			splx(s);
159 			if (i >= maxra) {
160 				return 0;
161 			}
162 			lblkno += i;
163 		}
164 		reqbp = bp = NULL;
165 	} else {
166 		off_t firstread = bp->b_offset;
167 
168 		KASSERT(bp->b_offset != NOOFFSET,
169 		    ("cluster_read: no buffer offset"));
170 		if (firstread + totread > filesize)
171 			totread = filesize - firstread;
172 		if (totread > size) {
173 			int nblks = 0;
174 			int ncontigafter;
175 			while (totread > 0) {
176 				nblks++;
177 				totread -= size;
178 			}
179 			if (nblks == 1)
180 				goto single_block_read;
181 			if (nblks > racluster)
182 				nblks = racluster;
183 
184 	    		error = VOP_BMAP(vp, lblkno, NULL,
185 				&blkno, &ncontigafter, NULL);
186 			if (error)
187 				goto single_block_read;
188 			if (blkno == -1)
189 				goto single_block_read;
190 			if (ncontigafter == 0)
191 				goto single_block_read;
192 			if (ncontigafter + 1 < nblks)
193 				nblks = ncontigafter + 1;
194 
195 			bp = cluster_rbuild(vp, filesize, lblkno,
196 				blkno, size, nblks, bp);
197 			lblkno += (bp->b_bufsize / size);
198 		} else {
199 single_block_read:
200 			/*
201 			 * if it isn't in the cache, then get a chunk from
202 			 * disk if sequential, otherwise just get the block.
203 			 */
204 			bp->b_flags |= B_RAM;
205 			bp->b_iocmd = BIO_READ;
206 			lblkno += 1;
207 		}
208 	}
209 
210 	/*
211 	 * if we have been doing sequential I/O, then do some read-ahead
212 	 */
213 	rbp = NULL;
214 	if (seqcount && (lblkno < (origblkno + seqcount))) {
215 		/*
216 		 * we now build the read-ahead buffer if it is desirable.
217 		 */
218 		if (((u_quad_t)(lblkno + 1) * size) <= filesize &&
219 		    !(error = VOP_BMAP(vp, lblkno, NULL, &blkno, &num_ra, NULL)) &&
220 		    blkno != -1) {
221 			int nblksread;
222 			int ntoread = num_ra + 1;
223 			nblksread = (origtotread + size - 1) / size;
224 			if (seqcount < nblksread)
225 				seqcount = nblksread;
226 			if (seqcount < ntoread)
227 				ntoread = seqcount;
228 			if (num_ra) {
229 				rbp = cluster_rbuild(vp, filesize, lblkno,
230 					blkno, size, ntoread, NULL);
231 			} else {
232 				rbp = getblk(vp, lblkno, size, 0, 0);
233 				rbp->b_flags |= B_ASYNC | B_RAM;
234 				rbp->b_iocmd = BIO_READ;
235 				rbp->b_blkno = blkno;
236 			}
237 		}
238 	}
239 
240 	/*
241 	 * handle the synchronous read
242 	 */
243 	if (bp) {
244 #if defined(CLUSTERDEBUG)
245 		if (rcluster)
246 			printf("S(%ld,%ld,%d) ",
247 			    (long)bp->b_lblkno, bp->b_bcount, seqcount);
248 #endif
249 		if ((bp->b_flags & B_CLUSTER) == 0)
250 			vfs_busy_pages(bp, 0);
251 		bp->b_flags &= ~B_INVAL;
252 		bp->b_ioflags &= ~BIO_ERROR;
253 		if ((bp->b_flags & B_ASYNC) || bp->b_iodone != NULL)
254 			BUF_KERNPROC(bp);
255 		error = VOP_STRATEGY(vp, bp);
256 		curproc->p_stats->p_ru.ru_inblock++;
257 	}
258 
259 	/*
260 	 * and if we have read-aheads, do them too
261 	 */
262 	if (rbp) {
263 		if (error) {
264 			rbp->b_flags &= ~B_ASYNC;
265 			brelse(rbp);
266 		} else if (rbp->b_flags & B_CACHE) {
267 			rbp->b_flags &= ~B_ASYNC;
268 			bqrelse(rbp);
269 		} else {
270 #if defined(CLUSTERDEBUG)
271 			if (rcluster) {
272 				if (bp)
273 					printf("A+(%ld,%ld,%ld,%d) ",
274 					    (long)rbp->b_lblkno, rbp->b_bcount,
275 					    (long)(rbp->b_lblkno - origblkno),
276 					    seqcount);
277 				else
278 					printf("A(%ld,%ld,%ld,%d) ",
279 					    (long)rbp->b_lblkno, rbp->b_bcount,
280 					    (long)(rbp->b_lblkno - origblkno),
281 					    seqcount);
282 			}
283 #endif
284 
285 			if ((rbp->b_flags & B_CLUSTER) == 0)
286 				vfs_busy_pages(rbp, 0);
287 			rbp->b_flags &= ~B_INVAL;
288 			rbp->b_ioflags &= ~BIO_ERROR;
289 			if ((rbp->b_flags & B_ASYNC) || rbp->b_iodone != NULL)
290 				BUF_KERNPROC(rbp);
291 			(void) VOP_STRATEGY(vp, rbp);
292 			curproc->p_stats->p_ru.ru_inblock++;
293 		}
294 	}
295 	if (reqbp)
296 		return (bufwait(reqbp));
297 	else
298 		return (error);
299 }
300 
301 /*
302  * If blocks are contiguous on disk, use this to provide clustered
303  * read ahead.  We will read as many blocks as possible sequentially
304  * and then parcel them up into logical blocks in the buffer hash table.
305  */
306 static struct buf *
307 cluster_rbuild(vp, filesize, lbn, blkno, size, run, fbp)
308 	struct vnode *vp;
309 	u_quad_t filesize;
310 	daddr_t lbn;
311 	daddr_t blkno;
312 	long size;
313 	int run;
314 	struct buf *fbp;
315 {
316 	struct buf *bp, *tbp;
317 	daddr_t bn;
318 	int i, inc, j;
319 
320 	KASSERT(size == vp->v_mount->mnt_stat.f_iosize,
321 	    ("cluster_rbuild: size %ld != filesize %ld\n",
322 	    size, vp->v_mount->mnt_stat.f_iosize));
323 
324 	/*
325 	 * avoid a division
326 	 */
327 	while ((u_quad_t) size * (lbn + run) > filesize) {
328 		--run;
329 	}
330 
331 	if (fbp) {
332 		tbp = fbp;
333 		tbp->b_iocmd = BIO_READ;
334 	} else {
335 		tbp = getblk(vp, lbn, size, 0, 0);
336 		if (tbp->b_flags & B_CACHE)
337 			return tbp;
338 		tbp->b_flags |= B_ASYNC | B_RAM;
339 		tbp->b_iocmd = BIO_READ;
340 	}
341 
342 	tbp->b_blkno = blkno;
343 	if( (tbp->b_flags & B_MALLOC) ||
344 		((tbp->b_flags & B_VMIO) == 0) || (run <= 1) )
345 		return tbp;
346 
347 	bp = trypbuf(&cluster_pbuf_freecnt);
348 	if (bp == 0)
349 		return tbp;
350 
351 	bp->b_data = (char *)((vm_offset_t)bp->b_data |
352 	    ((vm_offset_t)tbp->b_data & PAGE_MASK));
353 	bp->b_flags = B_ASYNC | B_CLUSTER | B_VMIO;
354 	bp->b_iocmd = BIO_READ;
355 	bp->b_iodone = cluster_callback;
356 	bp->b_blkno = blkno;
357 	bp->b_lblkno = lbn;
358 	bp->b_offset = tbp->b_offset;
359 	KASSERT(bp->b_offset != NOOFFSET, ("cluster_rbuild: no buffer offset"));
360 	pbgetvp(vp, bp);
361 
362 	TAILQ_INIT(&bp->b_cluster.cluster_head);
363 
364 	bp->b_bcount = 0;
365 	bp->b_bufsize = 0;
366 	bp->b_npages = 0;
367 
368 	inc = btodb(size);
369 	for (bn = blkno, i = 0; i < run; ++i, bn += inc) {
370 		if (i != 0) {
371 			if ((bp->b_npages * PAGE_SIZE) +
372 				round_page(size) > vp->v_mount->mnt_iosize_max)
373 				break;
374 
375 			if ((tbp = incore(vp, lbn + i)) != NULL) {
376 				if (BUF_LOCK(tbp, LK_EXCLUSIVE | LK_NOWAIT))
377 					break;
378 				BUF_UNLOCK(tbp);
379 
380 				for (j = 0; j < tbp->b_npages; j++)
381 					if (tbp->b_pages[j]->valid)
382 						break;
383 
384 				if (j != tbp->b_npages)
385 					break;
386 
387 				if (tbp->b_bcount != size)
388 					break;
389 			}
390 
391 			tbp = getblk(vp, lbn + i, size, 0, 0);
392 
393 			if ((tbp->b_flags & B_CACHE) ||
394 				(tbp->b_flags & B_VMIO) == 0) {
395 				bqrelse(tbp);
396 				break;
397 			}
398 
399 			for (j = 0;j < tbp->b_npages; j++)
400 				if (tbp->b_pages[j]->valid)
401 					break;
402 
403 			if (j != tbp->b_npages) {
404 				bqrelse(tbp);
405 				break;
406 			}
407 
408 			if ((fbp && (i == 1)) || (i == (run - 1)))
409 				tbp->b_flags |= B_RAM;
410 			tbp->b_flags |= B_ASYNC;
411 			tbp->b_iocmd = BIO_READ;
412 			if (tbp->b_blkno == tbp->b_lblkno) {
413 				tbp->b_blkno = bn;
414 			} else if (tbp->b_blkno != bn) {
415 				brelse(tbp);
416 				break;
417 			}
418 		}
419 		/*
420 		 * XXX fbp from caller may not be B_ASYNC, but we are going
421 		 * to biodone() it in cluster_callback() anyway
422 		 */
423 		BUF_KERNPROC(tbp);
424 		TAILQ_INSERT_TAIL(&bp->b_cluster.cluster_head,
425 			tbp, b_cluster.cluster_entry);
426 		for (j = 0; j < tbp->b_npages; j += 1) {
427 			vm_page_t m;
428 			m = tbp->b_pages[j];
429 			vm_page_io_start(m);
430 			vm_object_pip_add(m->object, 1);
431 			if ((bp->b_npages == 0) ||
432 				(bp->b_pages[bp->b_npages-1] != m)) {
433 				bp->b_pages[bp->b_npages] = m;
434 				bp->b_npages++;
435 			}
436 			if ((m->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL)
437 				tbp->b_pages[j] = bogus_page;
438 		}
439 		bp->b_bcount += tbp->b_bcount;
440 		bp->b_bufsize += tbp->b_bufsize;
441 	}
442 
443 	for(j=0;j<bp->b_npages;j++) {
444 		if ((bp->b_pages[j]->valid & VM_PAGE_BITS_ALL) ==
445 			VM_PAGE_BITS_ALL)
446 			bp->b_pages[j] = bogus_page;
447 	}
448 	if (bp->b_bufsize > bp->b_kvasize)
449 		panic("cluster_rbuild: b_bufsize(%ld) > b_kvasize(%d)\n",
450 		    bp->b_bufsize, bp->b_kvasize);
451 	bp->b_kvasize = bp->b_bufsize;
452 
453 	pmap_qenter(trunc_page((vm_offset_t) bp->b_data),
454 		(vm_page_t *)bp->b_pages, bp->b_npages);
455 	return (bp);
456 }
457 
458 /*
459  * Cleanup after a clustered read or write.
460  * This is complicated by the fact that any of the buffers might have
461  * extra memory (if there were no empty buffer headers at allocbuf time)
462  * that we will need to shift around.
463  */
464 void
465 cluster_callback(bp)
466 	struct buf *bp;
467 {
468 	struct buf *nbp, *tbp;
469 	int error = 0;
470 
471 	/*
472 	 * Must propogate errors to all the components.
473 	 */
474 	if (bp->b_ioflags & BIO_ERROR)
475 		error = bp->b_error;
476 
477 	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
478 	/*
479 	 * Move memory from the large cluster buffer into the component
480 	 * buffers and mark IO as done on these.
481 	 */
482 	for (tbp = TAILQ_FIRST(&bp->b_cluster.cluster_head);
483 		tbp; tbp = nbp) {
484 		nbp = TAILQ_NEXT(&tbp->b_cluster, cluster_entry);
485 		if (error) {
486 			tbp->b_ioflags |= BIO_ERROR;
487 			tbp->b_error = error;
488 		} else {
489 			tbp->b_dirtyoff = tbp->b_dirtyend = 0;
490 			tbp->b_flags &= ~B_INVAL;
491 			tbp->b_ioflags &= ~BIO_ERROR;
492 		}
493 		bufdone(tbp);
494 	}
495 	relpbuf(bp, &cluster_pbuf_freecnt);
496 }
497 
498 /*
499  *	cluster_wbuild_wb:
500  *
501  *	Implement modified write build for cluster.
502  *
503  *		write_behind = 0	write behind disabled
504  *		write_behind = 1	write behind normal (default)
505  *		write_behind = 2	write behind backed-off
506  */
507 
508 static __inline int
509 cluster_wbuild_wb(struct vnode *vp, long size, daddr_t start_lbn, int len)
510 {
511 	int r = 0;
512 
513 	switch(write_behind) {
514 	case 2:
515 		if (start_lbn < len)
516 			break;
517 		start_lbn -= len;
518 		/* fall through */
519 	case 1:
520 		r = cluster_wbuild(vp, size, start_lbn, len);
521 		/* fall through */
522 	default:
523 		/* fall through */
524 		break;
525 	}
526 	return(r);
527 }
528 
529 /*
530  * Do clustered write for FFS.
531  *
532  * Three cases:
533  *	1. Write is not sequential (write asynchronously)
534  *	Write is sequential:
535  *	2.	beginning of cluster - begin cluster
536  *	3.	middle of a cluster - add to cluster
537  *	4.	end of a cluster - asynchronously write cluster
538  */
539 void
540 cluster_write(bp, filesize, seqcount)
541 	struct buf *bp;
542 	u_quad_t filesize;
543 	int seqcount;
544 {
545 	struct vnode *vp;
546 	daddr_t lbn;
547 	int maxclen, cursize;
548 	int lblocksize;
549 	int async;
550 
551 	vp = bp->b_vp;
552 	if (vp->v_type == VREG) {
553 		async = vp->v_mount->mnt_flag & MNT_ASYNC;
554 		lblocksize = vp->v_mount->mnt_stat.f_iosize;
555 	} else {
556 		async = 0;
557 		lblocksize = bp->b_bufsize;
558 	}
559 	lbn = bp->b_lblkno;
560 	KASSERT(bp->b_offset != NOOFFSET, ("cluster_write: no buffer offset"));
561 
562 	/* Initialize vnode to beginning of file. */
563 	if (lbn == 0)
564 		vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
565 
566 	if (vp->v_clen == 0 || lbn != vp->v_lastw + 1 ||
567 	    (bp->b_blkno != vp->v_lasta + btodb(lblocksize))) {
568 		maxclen = vp->v_mount->mnt_iosize_max / lblocksize - 1;
569 		if (vp->v_clen != 0) {
570 			/*
571 			 * Next block is not sequential.
572 			 *
573 			 * If we are not writing at end of file, the process
574 			 * seeked to another point in the file since its last
575 			 * write, or we have reached our maximum cluster size,
576 			 * then push the previous cluster. Otherwise try
577 			 * reallocating to make it sequential.
578 			 *
579 			 * Change to algorithm: only push previous cluster if
580 			 * it was sequential from the point of view of the
581 			 * seqcount heuristic, otherwise leave the buffer
582 			 * intact so we can potentially optimize the I/O
583 			 * later on in the buf_daemon or update daemon
584 			 * flush.
585 			 */
586 			cursize = vp->v_lastw - vp->v_cstart + 1;
587 			if (((u_quad_t) bp->b_offset + lblocksize) != filesize ||
588 			    lbn != vp->v_lastw + 1 || vp->v_clen <= cursize) {
589 				if (!async && seqcount > 0) {
590 					cluster_wbuild_wb(vp, lblocksize,
591 						vp->v_cstart, cursize);
592 				}
593 			} else {
594 				struct buf **bpp, **endbp;
595 				struct cluster_save *buflist;
596 
597 				buflist = cluster_collectbufs(vp, bp);
598 				endbp = &buflist->bs_children
599 				    [buflist->bs_nchildren - 1];
600 				if (VOP_REALLOCBLKS(vp, buflist)) {
601 					/*
602 					 * Failed, push the previous cluster
603 					 * if *really* writing sequentially
604 					 * in the logical file (seqcount > 1),
605 					 * otherwise delay it in the hopes that
606 					 * the low level disk driver can
607 					 * optimize the write ordering.
608 					 */
609 					for (bpp = buflist->bs_children;
610 					     bpp < endbp; bpp++)
611 						brelse(*bpp);
612 					free(buflist, M_SEGMENT);
613 					if (seqcount > 1) {
614 						cluster_wbuild_wb(vp,
615 						    lblocksize, vp->v_cstart,
616 						    cursize);
617 					}
618 				} else {
619 					/*
620 					 * Succeeded, keep building cluster.
621 					 */
622 					for (bpp = buflist->bs_children;
623 					     bpp <= endbp; bpp++)
624 						bdwrite(*bpp);
625 					free(buflist, M_SEGMENT);
626 					vp->v_lastw = lbn;
627 					vp->v_lasta = bp->b_blkno;
628 					return;
629 				}
630 			}
631 		}
632 		/*
633 		 * Consider beginning a cluster. If at end of file, make
634 		 * cluster as large as possible, otherwise find size of
635 		 * existing cluster.
636 		 */
637 		if ((vp->v_type == VREG) &&
638 			((u_quad_t) bp->b_offset + lblocksize) != filesize &&
639 		    (bp->b_blkno == bp->b_lblkno) &&
640 		    (VOP_BMAP(vp, lbn, NULL, &bp->b_blkno, &maxclen, NULL) ||
641 		     bp->b_blkno == -1)) {
642 			bawrite(bp);
643 			vp->v_clen = 0;
644 			vp->v_lasta = bp->b_blkno;
645 			vp->v_cstart = lbn + 1;
646 			vp->v_lastw = lbn;
647 			return;
648 		}
649 		vp->v_clen = maxclen;
650 		if (!async && maxclen == 0) {	/* I/O not contiguous */
651 			vp->v_cstart = lbn + 1;
652 			bawrite(bp);
653 		} else {	/* Wait for rest of cluster */
654 			vp->v_cstart = lbn;
655 			bdwrite(bp);
656 		}
657 	} else if (lbn == vp->v_cstart + vp->v_clen) {
658 		/*
659 		 * At end of cluster, write it out if seqcount tells us we
660 		 * are operating sequentially, otherwise let the buf or
661 		 * update daemon handle it.
662 		 */
663 		bdwrite(bp);
664 		if (seqcount > 1)
665 			cluster_wbuild_wb(vp, lblocksize, vp->v_cstart, vp->v_clen + 1);
666 		vp->v_clen = 0;
667 		vp->v_cstart = lbn + 1;
668 	} else {
669 		/*
670 		 * In the middle of a cluster, so just delay the I/O for now.
671 		 */
672 		bdwrite(bp);
673 	}
674 	vp->v_lastw = lbn;
675 	vp->v_lasta = bp->b_blkno;
676 }
677 
678 
679 /*
680  * This is an awful lot like cluster_rbuild...wish they could be combined.
681  * The last lbn argument is the current block on which I/O is being
682  * performed.  Check to see that it doesn't fall in the middle of
683  * the current block (if last_bp == NULL).
684  */
685 int
686 cluster_wbuild(vp, size, start_lbn, len)
687 	struct vnode *vp;
688 	long size;
689 	daddr_t start_lbn;
690 	int len;
691 {
692 	struct buf *bp, *tbp;
693 	int i, j, s;
694 	int totalwritten = 0;
695 	int dbsize = btodb(size);
696 
697 	while (len > 0) {
698 		s = splbio();
699 		if (((tbp = gbincore(vp, start_lbn)) == NULL) ||
700 		  ((tbp->b_flags & (B_INVAL | B_DELWRI)) != B_DELWRI) ||
701 		  BUF_LOCK(tbp, LK_EXCLUSIVE | LK_NOWAIT)) {
702 			++start_lbn;
703 			--len;
704 			splx(s);
705 			continue;
706 		}
707 		bremfree(tbp);
708 		tbp->b_flags &= ~B_DONE;
709 		splx(s);
710 
711 		/*
712 		 * Extra memory in the buffer, punt on this buffer.
713 		 * XXX we could handle this in most cases, but we would
714 		 * have to push the extra memory down to after our max
715 		 * possible cluster size and then potentially pull it back
716 		 * up if the cluster was terminated prematurely--too much
717 		 * hassle.
718 		 */
719 		if (((tbp->b_flags & (B_CLUSTEROK|B_MALLOC)) != B_CLUSTEROK) ||
720 		  (tbp->b_bcount != tbp->b_bufsize) ||
721 		  (tbp->b_bcount != size) ||
722 		  (len == 1) ||
723 		  ((bp = getpbuf(&cluster_pbuf_freecnt)) == NULL)) {
724 			totalwritten += tbp->b_bufsize;
725 			bawrite(tbp);
726 			++start_lbn;
727 			--len;
728 			continue;
729 		}
730 
731 		/*
732 		 * We got a pbuf to make the cluster in.
733 		 * so initialise it.
734 		 */
735 		TAILQ_INIT(&bp->b_cluster.cluster_head);
736 		bp->b_bcount = 0;
737 		bp->b_bufsize = 0;
738 		bp->b_npages = 0;
739 		if (tbp->b_wcred != NOCRED) {
740 		    bp->b_wcred = tbp->b_wcred;
741 		    crhold(bp->b_wcred);
742 		}
743 
744 		bp->b_blkno = tbp->b_blkno;
745 		bp->b_lblkno = tbp->b_lblkno;
746 		bp->b_offset = tbp->b_offset;
747 		bp->b_data = (char *)((vm_offset_t)bp->b_data |
748 		    ((vm_offset_t)tbp->b_data & PAGE_MASK));
749 		bp->b_flags |= B_CLUSTER |
750 				(tbp->b_flags & (B_VMIO | B_NEEDCOMMIT));
751 		bp->b_iodone = cluster_callback;
752 		pbgetvp(vp, bp);
753 		/*
754 		 * From this location in the file, scan forward to see
755 		 * if there are buffers with adjacent data that need to
756 		 * be written as well.
757 		 */
758 		for (i = 0; i < len; ++i, ++start_lbn) {
759 			if (i != 0) { /* If not the first buffer */
760 				s = splbio();
761 				/*
762 				 * If the adjacent data is not even in core it
763 				 * can't need to be written.
764 				 */
765 				if ((tbp = gbincore(vp, start_lbn)) == NULL) {
766 					splx(s);
767 					break;
768 				}
769 
770 				/*
771 				 * If it IS in core, but has different
772 				 * characteristics, don't cluster with it.
773 				 */
774 				if ((tbp->b_flags & (B_VMIO | B_CLUSTEROK |
775 				    B_INVAL | B_DELWRI | B_NEEDCOMMIT))
776 				  != (B_DELWRI | B_CLUSTEROK |
777 				    (bp->b_flags & (B_VMIO | B_NEEDCOMMIT))) ||
778 				    tbp->b_wcred != bp->b_wcred ||
779 				    BUF_LOCK(tbp, LK_EXCLUSIVE | LK_NOWAIT)) {
780 					splx(s);
781 					break;
782 				}
783 
784 				/*
785 				 * Check that the combined cluster
786 				 * would make sense with regard to pages
787 				 * and would not be too large
788 				 */
789 				if ((tbp->b_bcount != size) ||
790 				  ((bp->b_blkno + (dbsize * i)) !=
791 				    tbp->b_blkno) ||
792 				  ((tbp->b_npages + bp->b_npages) >
793 				    (vp->v_mount->mnt_iosize_max / PAGE_SIZE))) {
794 					BUF_UNLOCK(tbp);
795 					splx(s);
796 					break;
797 				}
798 				/*
799 				 * Ok, it's passed all the tests,
800 				 * so remove it from the free list
801 				 * and mark it busy. We will use it.
802 				 */
803 				bremfree(tbp);
804 				tbp->b_flags &= ~B_DONE;
805 				splx(s);
806 			} /* end of code for non-first buffers only */
807 			/* check for latent dependencies to be handled */
808 			if ((LIST_FIRST(&tbp->b_dep)) != NULL &&
809 			    bioops.io_start)
810 				(*bioops.io_start)(tbp);
811 			/*
812 			 * If the IO is via the VM then we do some
813 			 * special VM hackery. (yuck)
814 			 */
815 			if (tbp->b_flags & B_VMIO) {
816 				vm_page_t m;
817 
818 				if (i != 0) { /* if not first buffer */
819 					for (j = 0; j < tbp->b_npages; j += 1) {
820 						m = tbp->b_pages[j];
821 						if (m->flags & PG_BUSY) {
822 							bqrelse(tbp);
823 							goto finishcluster;
824 						}
825 					}
826 				}
827 
828 				for (j = 0; j < tbp->b_npages; j += 1) {
829 					m = tbp->b_pages[j];
830 					vm_page_io_start(m);
831 					vm_object_pip_add(m->object, 1);
832 					if ((bp->b_npages == 0) ||
833 					  (bp->b_pages[bp->b_npages - 1] != m)) {
834 						bp->b_pages[bp->b_npages] = m;
835 						bp->b_npages++;
836 					}
837 				}
838 			}
839 			bp->b_bcount += size;
840 			bp->b_bufsize += size;
841 
842 			s = splbio();
843 			bundirty(tbp);
844 			tbp->b_flags &= ~B_DONE;
845 			tbp->b_ioflags &= ~BIO_ERROR;
846 			tbp->b_flags |= B_ASYNC;
847 			tbp->b_iocmd = BIO_WRITE;
848 			reassignbuf(tbp, tbp->b_vp);	/* put on clean list */
849 			++tbp->b_vp->v_numoutput;
850 			splx(s);
851 			BUF_KERNPROC(tbp);
852 			TAILQ_INSERT_TAIL(&bp->b_cluster.cluster_head,
853 				tbp, b_cluster.cluster_entry);
854 		}
855 	finishcluster:
856 		pmap_qenter(trunc_page((vm_offset_t) bp->b_data),
857 			(vm_page_t *) bp->b_pages, bp->b_npages);
858 		if (bp->b_bufsize > bp->b_kvasize)
859 			panic(
860 			    "cluster_wbuild: b_bufsize(%ld) > b_kvasize(%d)\n",
861 			    bp->b_bufsize, bp->b_kvasize);
862 		bp->b_kvasize = bp->b_bufsize;
863 		totalwritten += bp->b_bufsize;
864 		bp->b_dirtyoff = 0;
865 		bp->b_dirtyend = bp->b_bufsize;
866 		bawrite(bp);
867 
868 		len -= i;
869 	}
870 	return totalwritten;
871 }
872 
873 /*
874  * Collect together all the buffers in a cluster.
875  * Plus add one additional buffer.
876  */
877 static struct cluster_save *
878 cluster_collectbufs(vp, last_bp)
879 	struct vnode *vp;
880 	struct buf *last_bp;
881 {
882 	struct cluster_save *buflist;
883 	struct buf *bp;
884 	daddr_t lbn;
885 	int i, len;
886 
887 	len = vp->v_lastw - vp->v_cstart + 1;
888 	buflist = malloc(sizeof(struct buf *) * (len + 1) + sizeof(*buflist),
889 	    M_SEGMENT, M_WAITOK);
890 	buflist->bs_nchildren = 0;
891 	buflist->bs_children = (struct buf **) (buflist + 1);
892 	for (lbn = vp->v_cstart, i = 0; i < len; lbn++, i++) {
893 		(void) bread(vp, lbn, last_bp->b_bcount, NOCRED, &bp);
894 		buflist->bs_children[i] = bp;
895 		if (bp->b_blkno == bp->b_lblkno)
896 			VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno,
897 				NULL, NULL);
898 	}
899 	buflist->bs_children[i] = bp = last_bp;
900 	if (bp->b_blkno == bp->b_lblkno)
901 		VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno,
902 			NULL, NULL);
903 	buflist->bs_nchildren = i + 1;
904 	return (buflist);
905 }
906