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