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