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