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