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