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