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