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