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