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