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