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