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