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