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