xref: /freebsd/sys/kern/vfs_cluster.c (revision 1f4bcc459a76b7aa664f3fd557684cd0ba6da352)
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  * 4. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)vfs_cluster.c	8.7 (Berkeley) 2/13/94
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_debug_cluster.h"
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/proc.h>
43 #include <sys/bio.h>
44 #include <sys/buf.h>
45 #include <sys/vnode.h>
46 #include <sys/malloc.h>
47 #include <sys/mount.h>
48 #include <sys/resourcevar.h>
49 #include <sys/rwlock.h>
50 #include <sys/vmmeter.h>
51 #include <vm/vm.h>
52 #include <vm/vm_object.h>
53 #include <vm/vm_page.h>
54 #include <sys/sysctl.h>
55 
56 #if defined(CLUSTERDEBUG)
57 static int	rcluster= 0;
58 SYSCTL_INT(_debug, OID_AUTO, rcluster, CTLFLAG_RW, &rcluster, 0,
59     "Debug VFS clustering code");
60 #endif
61 
62 static MALLOC_DEFINE(M_SEGMENT, "cl_savebuf", "cluster_save buffer");
63 
64 static struct cluster_save *cluster_collectbufs(struct vnode *vp,
65 	    struct buf *last_bp, int gbflags);
66 static struct buf *cluster_rbuild(struct vnode *vp, u_quad_t filesize,
67 	    daddr_t lbn, daddr_t blkno, long size, int run, int gbflags,
68 	    struct buf *fbp);
69 static void cluster_callback(struct buf *);
70 
71 static int write_behind = 1;
72 SYSCTL_INT(_vfs, OID_AUTO, write_behind, CTLFLAG_RW, &write_behind, 0,
73     "Cluster write-behind; 0: disable, 1: enable, 2: backed off");
74 
75 static int read_max = 64;
76 SYSCTL_INT(_vfs, OID_AUTO, read_max, CTLFLAG_RW, &read_max, 0,
77     "Cluster read-ahead max block count");
78 
79 static int read_min = 1;
80 SYSCTL_INT(_vfs, OID_AUTO, read_min, CTLFLAG_RW, &read_min, 0,
81     "Cluster read min block count");
82 
83 /* Page expended to mark partially backed buffers */
84 extern vm_page_t	bogus_page;
85 
86 /*
87  * Read data to a buf, including read-ahead if we find this to be beneficial.
88  * cluster_read replaces bread.
89  */
90 int
91 cluster_read(struct vnode *vp, u_quad_t filesize, daddr_t lblkno, long size,
92     struct ucred *cred, long totread, int seqcount, int gbflags,
93     struct buf **bpp)
94 {
95 	struct buf *bp, *rbp, *reqbp;
96 	struct bufobj *bo;
97 	daddr_t blkno, origblkno;
98 	int maxra, racluster;
99 	int error, ncontig;
100 	int i;
101 
102 	error = 0;
103 	bo = &vp->v_bufobj;
104 	if (!unmapped_buf_allowed)
105 		gbflags &= ~GB_UNMAPPED;
106 
107 	/*
108 	 * Try to limit the amount of read-ahead by a few
109 	 * ad-hoc parameters.  This needs work!!!
110 	 */
111 	racluster = vp->v_mount->mnt_iosize_max / size;
112 	maxra = seqcount;
113 	maxra = min(read_max, maxra);
114 	maxra = min(nbuf/8, maxra);
115 	if (((u_quad_t)(lblkno + maxra + 1) * size) > filesize)
116 		maxra = (filesize / size) - lblkno;
117 
118 	/*
119 	 * get the requested block
120 	 */
121 	*bpp = reqbp = bp = getblk(vp, lblkno, size, 0, 0, gbflags);
122 	if (bp == NULL)
123 		return (EBUSY);
124 	origblkno = lblkno;
125 
126 	/*
127 	 * if it is in the cache, then check to see if the reads have been
128 	 * sequential.  If they have, then try some read-ahead, otherwise
129 	 * back-off on prospective read-aheads.
130 	 */
131 	if (bp->b_flags & B_CACHE) {
132 		if (!seqcount) {
133 			return 0;
134 		} else if ((bp->b_flags & B_RAM) == 0) {
135 			return 0;
136 		} else {
137 			bp->b_flags &= ~B_RAM;
138 			BO_RLOCK(bo);
139 			for (i = 1; i < maxra; i++) {
140 				/*
141 				 * Stop if the buffer does not exist or it
142 				 * is invalid (about to go away?)
143 				 */
144 				rbp = gbincore(&vp->v_bufobj, lblkno+i);
145 				if (rbp == NULL || (rbp->b_flags & B_INVAL))
146 					break;
147 
148 				/*
149 				 * Set another read-ahead mark so we know
150 				 * to check again. (If we can lock the
151 				 * buffer without waiting)
152 				 */
153 				if ((((i % racluster) == (racluster - 1)) ||
154 				    (i == (maxra - 1)))
155 				    && (0 == BUF_LOCK(rbp,
156 					LK_EXCLUSIVE | LK_NOWAIT, NULL))) {
157 					rbp->b_flags |= B_RAM;
158 					BUF_UNLOCK(rbp);
159 				}
160 			}
161 			BO_RUNLOCK(bo);
162 			if (i >= maxra) {
163 				return 0;
164 			}
165 			lblkno += i;
166 		}
167 		reqbp = bp = NULL;
168 	/*
169 	 * If it isn't in the cache, then get a chunk from
170 	 * disk if sequential, otherwise just get the block.
171 	 */
172 	} else {
173 		off_t firstread = bp->b_offset;
174 		int nblks;
175 		long minread;
176 
177 		KASSERT(bp->b_offset != NOOFFSET,
178 		    ("cluster_read: no buffer offset"));
179 
180 		ncontig = 0;
181 
182 		/*
183 		 * Adjust totread if needed
184 		 */
185 		minread = read_min * size;
186 		if (minread > totread)
187 			totread = minread;
188 
189 		/*
190 		 * Compute the total number of blocks that we should read
191 		 * synchronously.
192 		 */
193 		if (firstread + totread > filesize)
194 			totread = filesize - firstread;
195 		nblks = howmany(totread, size);
196 		if (nblks > racluster)
197 			nblks = racluster;
198 
199 		/*
200 		 * Now compute the number of contiguous blocks.
201 		 */
202 		if (nblks > 1) {
203 	    		error = VOP_BMAP(vp, lblkno, NULL,
204 				&blkno, &ncontig, NULL);
205 			/*
206 			 * If this failed to map just do the original block.
207 			 */
208 			if (error || blkno == -1)
209 				ncontig = 0;
210 		}
211 
212 		/*
213 		 * If we have contiguous data available do a cluster
214 		 * otherwise just read the requested block.
215 		 */
216 		if (ncontig) {
217 			/* Account for our first block. */
218 			ncontig = min(ncontig + 1, nblks);
219 			if (ncontig < nblks)
220 				nblks = ncontig;
221 			bp = cluster_rbuild(vp, filesize, lblkno,
222 			    blkno, size, nblks, gbflags, bp);
223 			lblkno += (bp->b_bufsize / size);
224 		} else {
225 			bp->b_flags |= B_RAM;
226 			bp->b_iocmd = BIO_READ;
227 			lblkno += 1;
228 		}
229 	}
230 
231 	/*
232 	 * handle the synchronous read so that it is available ASAP.
233 	 */
234 	if (bp) {
235 		if ((bp->b_flags & B_CLUSTER) == 0) {
236 			vfs_busy_pages(bp, 0);
237 		}
238 		bp->b_flags &= ~B_INVAL;
239 		bp->b_ioflags &= ~BIO_ERROR;
240 		if ((bp->b_flags & B_ASYNC) || bp->b_iodone != NULL)
241 			BUF_KERNPROC(bp);
242 		bp->b_iooffset = dbtob(bp->b_blkno);
243 		bstrategy(bp);
244 		curthread->td_ru.ru_inblock++;
245 	}
246 
247 	/*
248 	 * If we have been doing sequential I/O, then do some read-ahead.
249 	 */
250 	while (lblkno < (origblkno + maxra)) {
251 		error = VOP_BMAP(vp, lblkno, NULL, &blkno, &ncontig, NULL);
252 		if (error)
253 			break;
254 
255 		if (blkno == -1)
256 			break;
257 
258 		/*
259 		 * We could throttle ncontig here by maxra but we might as
260 		 * well read the data if it is contiguous.  We're throttled
261 		 * by racluster anyway.
262 		 */
263 		if (ncontig) {
264 			ncontig = min(ncontig + 1, racluster);
265 			rbp = cluster_rbuild(vp, filesize, lblkno, blkno,
266 			    size, ncontig, gbflags, NULL);
267 			lblkno += (rbp->b_bufsize / size);
268 			if (rbp->b_flags & B_DELWRI) {
269 				bqrelse(rbp);
270 				continue;
271 			}
272 		} else {
273 			rbp = getblk(vp, lblkno, size, 0, 0, gbflags);
274 			lblkno += 1;
275 			if (rbp->b_flags & B_DELWRI) {
276 				bqrelse(rbp);
277 				continue;
278 			}
279 			rbp->b_flags |= B_ASYNC | B_RAM;
280 			rbp->b_iocmd = BIO_READ;
281 			rbp->b_blkno = blkno;
282 		}
283 		if (rbp->b_flags & B_CACHE) {
284 			rbp->b_flags &= ~B_ASYNC;
285 			bqrelse(rbp);
286 			continue;
287 		}
288 		if ((rbp->b_flags & B_CLUSTER) == 0) {
289 			vfs_busy_pages(rbp, 0);
290 		}
291 		rbp->b_flags &= ~B_INVAL;
292 		rbp->b_ioflags &= ~BIO_ERROR;
293 		if ((rbp->b_flags & B_ASYNC) || rbp->b_iodone != NULL)
294 			BUF_KERNPROC(rbp);
295 		rbp->b_iooffset = dbtob(rbp->b_blkno);
296 		bstrategy(rbp);
297 		curthread->td_ru.ru_inblock++;
298 	}
299 
300 	if (reqbp) {
301 		/*
302 		 * Like bread, always brelse() the buffer when
303 		 * returning an error.
304 		 */
305 		error = bufwait(reqbp);
306 		if (error != 0) {
307 			brelse(reqbp);
308 			*bpp = NULL;
309 		}
310 	}
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, u_quad_t filesize, daddr_t lbn,
321     daddr_t blkno, long size, int run, int gbflags, struct buf *fbp)
322 {
323 	struct buf *bp, *tbp;
324 	daddr_t bn;
325 	off_t off;
326 	long tinc, tsize;
327 	int i, inc, j, k, toff;
328 
329 	KASSERT(size == vp->v_mount->mnt_stat.f_iosize,
330 	    ("cluster_rbuild: size %ld != f_iosize %jd\n",
331 	    size, (intmax_t)vp->v_mount->mnt_stat.f_iosize));
332 
333 	/*
334 	 * avoid a division
335 	 */
336 	while ((u_quad_t) size * (lbn + run) > filesize) {
337 		--run;
338 	}
339 
340 	if (fbp) {
341 		tbp = fbp;
342 		tbp->b_iocmd = BIO_READ;
343 	} else {
344 		tbp = getblk(vp, lbn, size, 0, 0, gbflags);
345 		if (tbp->b_flags & B_CACHE)
346 			return tbp;
347 		tbp->b_flags |= B_ASYNC | B_RAM;
348 		tbp->b_iocmd = BIO_READ;
349 	}
350 	tbp->b_blkno = blkno;
351 	if( (tbp->b_flags & B_MALLOC) ||
352 		((tbp->b_flags & B_VMIO) == 0) || (run <= 1) )
353 		return tbp;
354 
355 	bp = trypbuf(&cluster_pbuf_freecnt);
356 	if (bp == 0)
357 		return tbp;
358 
359 	/*
360 	 * We are synthesizing a buffer out of vm_page_t's, but
361 	 * if the block size is not page aligned then the starting
362 	 * address may not be either.  Inherit the b_data offset
363 	 * from the original buffer.
364 	 */
365 	bp->b_flags = B_ASYNC | B_CLUSTER | B_VMIO;
366 	if ((gbflags & GB_UNMAPPED) != 0) {
367 		bp->b_data = unmapped_buf;
368 	} else {
369 		bp->b_data = (char *)((vm_offset_t)bp->b_data |
370 		    ((vm_offset_t)tbp->b_data & PAGE_MASK));
371 	}
372 	bp->b_iocmd = BIO_READ;
373 	bp->b_iodone = cluster_callback;
374 	bp->b_blkno = blkno;
375 	bp->b_lblkno = lbn;
376 	bp->b_offset = tbp->b_offset;
377 	KASSERT(bp->b_offset != NOOFFSET, ("cluster_rbuild: no buffer offset"));
378 	pbgetvp(vp, bp);
379 
380 	TAILQ_INIT(&bp->b_cluster.cluster_head);
381 
382 	bp->b_bcount = 0;
383 	bp->b_bufsize = 0;
384 	bp->b_npages = 0;
385 
386 	inc = btodb(size);
387 	for (bn = blkno, i = 0; i < run; ++i, bn += inc) {
388 		if (i == 0) {
389 			VM_OBJECT_WLOCK(tbp->b_bufobj->bo_object);
390 			vfs_drain_busy_pages(tbp);
391 			vm_object_pip_add(tbp->b_bufobj->bo_object,
392 			    tbp->b_npages);
393 			for (k = 0; k < tbp->b_npages; k++)
394 				vm_page_sbusy(tbp->b_pages[k]);
395 			VM_OBJECT_WUNLOCK(tbp->b_bufobj->bo_object);
396 		} else {
397 			if ((bp->b_npages * PAGE_SIZE) +
398 			    round_page(size) > vp->v_mount->mnt_iosize_max) {
399 				break;
400 			}
401 
402 			tbp = getblk(vp, lbn + i, size, 0, 0, GB_LOCK_NOWAIT |
403 			    (gbflags & GB_UNMAPPED));
404 
405 			/* Don't wait around for locked bufs. */
406 			if (tbp == NULL)
407 				break;
408 
409 			/*
410 			 * Stop scanning if the buffer is fully valid
411 			 * (marked B_CACHE), or locked (may be doing a
412 			 * background write), or if the buffer is not
413 			 * VMIO backed.  The clustering code can only deal
414 			 * with VMIO-backed buffers.  The bo lock is not
415 			 * required for the BKGRDINPROG check since it
416 			 * can not be set without the buf lock.
417 			 */
418 			if ((tbp->b_vflags & BV_BKGRDINPROG) ||
419 			    (tbp->b_flags & B_CACHE) ||
420 			    (tbp->b_flags & B_VMIO) == 0) {
421 				bqrelse(tbp);
422 				break;
423 			}
424 
425 			/*
426 			 * The buffer must be completely invalid in order to
427 			 * take part in the cluster.  If it is partially valid
428 			 * then we stop.
429 			 */
430 			off = tbp->b_offset;
431 			tsize = size;
432 			VM_OBJECT_WLOCK(tbp->b_bufobj->bo_object);
433 			for (j = 0; tsize > 0; j++) {
434 				toff = off & PAGE_MASK;
435 				tinc = tsize;
436 				if (toff + tinc > PAGE_SIZE)
437 					tinc = PAGE_SIZE - toff;
438 				VM_OBJECT_ASSERT_WLOCKED(tbp->b_pages[j]->object);
439 				if ((tbp->b_pages[j]->valid &
440 				    vm_page_bits(toff, tinc)) != 0)
441 					break;
442 				if (vm_page_xbusied(tbp->b_pages[j]))
443 					break;
444 				vm_object_pip_add(tbp->b_bufobj->bo_object, 1);
445 				vm_page_sbusy(tbp->b_pages[j]);
446 				off += tinc;
447 				tsize -= tinc;
448 			}
449 			if (tsize > 0) {
450 clean_sbusy:
451 				vm_object_pip_add(tbp->b_bufobj->bo_object, -j);
452 				for (k = 0; k < j; k++)
453 					vm_page_sunbusy(tbp->b_pages[k]);
454 				VM_OBJECT_WUNLOCK(tbp->b_bufobj->bo_object);
455 				bqrelse(tbp);
456 				break;
457 			}
458 			VM_OBJECT_WUNLOCK(tbp->b_bufobj->bo_object);
459 
460 			/*
461 			 * Set a read-ahead mark as appropriate
462 			 */
463 			if ((fbp && (i == 1)) || (i == (run - 1)))
464 				tbp->b_flags |= B_RAM;
465 
466 			/*
467 			 * Set the buffer up for an async read (XXX should
468 			 * we do this only if we do not wind up brelse()ing?).
469 			 * Set the block number if it isn't set, otherwise
470 			 * if it is make sure it matches the block number we
471 			 * expect.
472 			 */
473 			tbp->b_flags |= B_ASYNC;
474 			tbp->b_iocmd = BIO_READ;
475 			if (tbp->b_blkno == tbp->b_lblkno) {
476 				tbp->b_blkno = bn;
477 			} else if (tbp->b_blkno != bn) {
478 				VM_OBJECT_WLOCK(tbp->b_bufobj->bo_object);
479 				goto clean_sbusy;
480 			}
481 		}
482 		/*
483 		 * XXX fbp from caller may not be B_ASYNC, but we are going
484 		 * to biodone() it in cluster_callback() anyway
485 		 */
486 		BUF_KERNPROC(tbp);
487 		TAILQ_INSERT_TAIL(&bp->b_cluster.cluster_head,
488 			tbp, b_cluster.cluster_entry);
489 		VM_OBJECT_WLOCK(tbp->b_bufobj->bo_object);
490 		for (j = 0; j < tbp->b_npages; j += 1) {
491 			vm_page_t m;
492 			m = tbp->b_pages[j];
493 			if ((bp->b_npages == 0) ||
494 			    (bp->b_pages[bp->b_npages-1] != m)) {
495 				bp->b_pages[bp->b_npages] = m;
496 				bp->b_npages++;
497 			}
498 			if (m->valid == VM_PAGE_BITS_ALL)
499 				tbp->b_pages[j] = bogus_page;
500 		}
501 		VM_OBJECT_WUNLOCK(tbp->b_bufobj->bo_object);
502 		/*
503 		 * Don't inherit tbp->b_bufsize as it may be larger due to
504 		 * a non-page-aligned size.  Instead just aggregate using
505 		 * 'size'.
506 		 */
507 		if (tbp->b_bcount != size)
508 			printf("warning: tbp->b_bcount wrong %ld vs %ld\n", tbp->b_bcount, size);
509 		if (tbp->b_bufsize != size)
510 			printf("warning: tbp->b_bufsize wrong %ld vs %ld\n", tbp->b_bufsize, size);
511 		bp->b_bcount += size;
512 		bp->b_bufsize += size;
513 	}
514 
515 	/*
516 	 * Fully valid pages in the cluster are already good and do not need
517 	 * to be re-read from disk.  Replace the page with bogus_page
518 	 */
519 	VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
520 	for (j = 0; j < bp->b_npages; j++) {
521 		VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[j]->object);
522 		if (bp->b_pages[j]->valid == VM_PAGE_BITS_ALL)
523 			bp->b_pages[j] = bogus_page;
524 	}
525 	VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
526 	if (bp->b_bufsize > bp->b_kvasize)
527 		panic("cluster_rbuild: b_bufsize(%ld) > b_kvasize(%d)\n",
528 		    bp->b_bufsize, bp->b_kvasize);
529 
530 	if (buf_mapped(bp)) {
531 		pmap_qenter(trunc_page((vm_offset_t) bp->b_data),
532 		    (vm_page_t *)bp->b_pages, bp->b_npages);
533 	}
534 	return (bp);
535 }
536 
537 /*
538  * Cleanup after a clustered read or write.
539  * This is complicated by the fact that any of the buffers might have
540  * extra memory (if there were no empty buffer headers at allocbuf time)
541  * that we will need to shift around.
542  */
543 static void
544 cluster_callback(bp)
545 	struct buf *bp;
546 {
547 	struct buf *nbp, *tbp;
548 	int error = 0;
549 
550 	/*
551 	 * Must propogate errors to all the components.
552 	 */
553 	if (bp->b_ioflags & BIO_ERROR)
554 		error = bp->b_error;
555 
556 	if (buf_mapped(bp)) {
557 		pmap_qremove(trunc_page((vm_offset_t) bp->b_data),
558 		    bp->b_npages);
559 	}
560 	/*
561 	 * Move memory from the large cluster buffer into the component
562 	 * buffers and mark IO as done on these.
563 	 */
564 	for (tbp = TAILQ_FIRST(&bp->b_cluster.cluster_head);
565 		tbp; tbp = nbp) {
566 		nbp = TAILQ_NEXT(&tbp->b_cluster, cluster_entry);
567 		if (error) {
568 			tbp->b_ioflags |= BIO_ERROR;
569 			tbp->b_error = error;
570 		} else {
571 			tbp->b_dirtyoff = tbp->b_dirtyend = 0;
572 			tbp->b_flags &= ~B_INVAL;
573 			tbp->b_ioflags &= ~BIO_ERROR;
574 			/*
575 			 * XXX the bdwrite()/bqrelse() issued during
576 			 * cluster building clears B_RELBUF (see bqrelse()
577 			 * comment).  If direct I/O was specified, we have
578 			 * to restore it here to allow the buffer and VM
579 			 * to be freed.
580 			 */
581 			if (tbp->b_flags & B_DIRECT)
582 				tbp->b_flags |= B_RELBUF;
583 		}
584 		bufdone(tbp);
585 	}
586 	pbrelvp(bp);
587 	relpbuf(bp, &cluster_pbuf_freecnt);
588 }
589 
590 /*
591  *	cluster_wbuild_wb:
592  *
593  *	Implement modified write build for cluster.
594  *
595  *		write_behind = 0	write behind disabled
596  *		write_behind = 1	write behind normal (default)
597  *		write_behind = 2	write behind backed-off
598  */
599 
600 static __inline int
601 cluster_wbuild_wb(struct vnode *vp, long size, daddr_t start_lbn, int len,
602     int gbflags)
603 {
604 	int r = 0;
605 
606 	switch (write_behind) {
607 	case 2:
608 		if (start_lbn < len)
609 			break;
610 		start_lbn -= len;
611 		/* FALLTHROUGH */
612 	case 1:
613 		r = cluster_wbuild(vp, size, start_lbn, len, gbflags);
614 		/* FALLTHROUGH */
615 	default:
616 		/* FALLTHROUGH */
617 		break;
618 	}
619 	return(r);
620 }
621 
622 /*
623  * Do clustered write for FFS.
624  *
625  * Three cases:
626  *	1. Write is not sequential (write asynchronously)
627  *	Write is sequential:
628  *	2.	beginning of cluster - begin cluster
629  *	3.	middle of a cluster - add to cluster
630  *	4.	end of a cluster - asynchronously write cluster
631  */
632 void
633 cluster_write(struct vnode *vp, struct buf *bp, u_quad_t filesize, int seqcount,
634     int gbflags)
635 {
636 	daddr_t lbn;
637 	int maxclen, cursize;
638 	int lblocksize;
639 	int async;
640 
641 	if (!unmapped_buf_allowed)
642 		gbflags &= ~GB_UNMAPPED;
643 
644 	if (vp->v_type == VREG) {
645 		async = DOINGASYNC(vp);
646 		lblocksize = vp->v_mount->mnt_stat.f_iosize;
647 	} else {
648 		async = 0;
649 		lblocksize = bp->b_bufsize;
650 	}
651 	lbn = bp->b_lblkno;
652 	KASSERT(bp->b_offset != NOOFFSET, ("cluster_write: no buffer offset"));
653 
654 	/* Initialize vnode to beginning of file. */
655 	if (lbn == 0)
656 		vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
657 
658 	if (vp->v_clen == 0 || lbn != vp->v_lastw + 1 ||
659 	    (bp->b_blkno != vp->v_lasta + btodb(lblocksize))) {
660 		maxclen = vp->v_mount->mnt_iosize_max / lblocksize - 1;
661 		if (vp->v_clen != 0) {
662 			/*
663 			 * Next block is not sequential.
664 			 *
665 			 * If we are not writing at end of file, the process
666 			 * seeked to another point in the file since its last
667 			 * write, or we have reached our maximum cluster size,
668 			 * then push the previous cluster. Otherwise try
669 			 * reallocating to make it sequential.
670 			 *
671 			 * Change to algorithm: only push previous cluster if
672 			 * it was sequential from the point of view of the
673 			 * seqcount heuristic, otherwise leave the buffer
674 			 * intact so we can potentially optimize the I/O
675 			 * later on in the buf_daemon or update daemon
676 			 * flush.
677 			 */
678 			cursize = vp->v_lastw - vp->v_cstart + 1;
679 			if (((u_quad_t) bp->b_offset + lblocksize) != filesize ||
680 			    lbn != vp->v_lastw + 1 || vp->v_clen <= cursize) {
681 				if (!async && seqcount > 0) {
682 					cluster_wbuild_wb(vp, lblocksize,
683 					    vp->v_cstart, cursize, gbflags);
684 				}
685 			} else {
686 				struct buf **bpp, **endbp;
687 				struct cluster_save *buflist;
688 
689 				buflist = cluster_collectbufs(vp, bp, gbflags);
690 				endbp = &buflist->bs_children
691 				    [buflist->bs_nchildren - 1];
692 				if (VOP_REALLOCBLKS(vp, buflist)) {
693 					/*
694 					 * Failed, push the previous cluster
695 					 * if *really* writing sequentially
696 					 * in the logical file (seqcount > 1),
697 					 * otherwise delay it in the hopes that
698 					 * the low level disk driver can
699 					 * optimize the write ordering.
700 					 */
701 					for (bpp = buflist->bs_children;
702 					     bpp < endbp; bpp++)
703 						brelse(*bpp);
704 					free(buflist, M_SEGMENT);
705 					if (seqcount > 1) {
706 						cluster_wbuild_wb(vp,
707 						    lblocksize, vp->v_cstart,
708 						    cursize, gbflags);
709 					}
710 				} else {
711 					/*
712 					 * Succeeded, keep building cluster.
713 					 */
714 					for (bpp = buflist->bs_children;
715 					     bpp <= endbp; bpp++)
716 						bdwrite(*bpp);
717 					free(buflist, M_SEGMENT);
718 					vp->v_lastw = lbn;
719 					vp->v_lasta = bp->b_blkno;
720 					return;
721 				}
722 			}
723 		}
724 		/*
725 		 * Consider beginning a cluster. If at end of file, make
726 		 * cluster as large as possible, otherwise find size of
727 		 * existing cluster.
728 		 */
729 		if ((vp->v_type == VREG) &&
730 			((u_quad_t) bp->b_offset + lblocksize) != filesize &&
731 		    (bp->b_blkno == bp->b_lblkno) &&
732 		    (VOP_BMAP(vp, lbn, NULL, &bp->b_blkno, &maxclen, NULL) ||
733 		     bp->b_blkno == -1)) {
734 			bawrite(bp);
735 			vp->v_clen = 0;
736 			vp->v_lasta = bp->b_blkno;
737 			vp->v_cstart = lbn + 1;
738 			vp->v_lastw = lbn;
739 			return;
740 		}
741 		vp->v_clen = maxclen;
742 		if (!async && maxclen == 0) {	/* I/O not contiguous */
743 			vp->v_cstart = lbn + 1;
744 			bawrite(bp);
745 		} else {	/* Wait for rest of cluster */
746 			vp->v_cstart = lbn;
747 			bdwrite(bp);
748 		}
749 	} else if (lbn == vp->v_cstart + vp->v_clen) {
750 		/*
751 		 * At end of cluster, write it out if seqcount tells us we
752 		 * are operating sequentially, otherwise let the buf or
753 		 * update daemon handle it.
754 		 */
755 		bdwrite(bp);
756 		if (seqcount > 1) {
757 			cluster_wbuild_wb(vp, lblocksize, vp->v_cstart,
758 			    vp->v_clen + 1, gbflags);
759 		}
760 		vp->v_clen = 0;
761 		vp->v_cstart = lbn + 1;
762 	} else if (vm_page_count_severe()) {
763 		/*
764 		 * We are low on memory, get it going NOW
765 		 */
766 		bawrite(bp);
767 	} else {
768 		/*
769 		 * In the middle of a cluster, so just delay the I/O for now.
770 		 */
771 		bdwrite(bp);
772 	}
773 	vp->v_lastw = lbn;
774 	vp->v_lasta = bp->b_blkno;
775 }
776 
777 
778 /*
779  * This is an awful lot like cluster_rbuild...wish they could be combined.
780  * The last lbn argument is the current block on which I/O is being
781  * performed.  Check to see that it doesn't fall in the middle of
782  * the current block (if last_bp == NULL).
783  */
784 int
785 cluster_wbuild(struct vnode *vp, long size, daddr_t start_lbn, int len,
786     int gbflags)
787 {
788 	struct buf *bp, *tbp;
789 	struct bufobj *bo;
790 	int i, j;
791 	int totalwritten = 0;
792 	int dbsize = btodb(size);
793 
794 	if (!unmapped_buf_allowed)
795 		gbflags &= ~GB_UNMAPPED;
796 
797 	bo = &vp->v_bufobj;
798 	while (len > 0) {
799 		/*
800 		 * If the buffer is not delayed-write (i.e. dirty), or it
801 		 * is delayed-write but either locked or inval, it cannot
802 		 * partake in the clustered write.
803 		 */
804 		BO_LOCK(bo);
805 		if ((tbp = gbincore(&vp->v_bufobj, start_lbn)) == NULL ||
806 		    (tbp->b_vflags & BV_BKGRDINPROG)) {
807 			BO_UNLOCK(bo);
808 			++start_lbn;
809 			--len;
810 			continue;
811 		}
812 		if (BUF_LOCK(tbp,
813 		    LK_EXCLUSIVE | LK_NOWAIT | LK_INTERLOCK, BO_LOCKPTR(bo))) {
814 			++start_lbn;
815 			--len;
816 			continue;
817 		}
818 		if ((tbp->b_flags & (B_INVAL | B_DELWRI)) != B_DELWRI) {
819 			BUF_UNLOCK(tbp);
820 			++start_lbn;
821 			--len;
822 			continue;
823 		}
824 		if (tbp->b_pin_count >  0) {
825 			BUF_UNLOCK(tbp);
826 			++start_lbn;
827 			--len;
828 			continue;
829 		}
830 		bremfree(tbp);
831 		tbp->b_flags &= ~B_DONE;
832 
833 		/*
834 		 * Extra memory in the buffer, punt on this buffer.
835 		 * XXX we could handle this in most cases, but we would
836 		 * have to push the extra memory down to after our max
837 		 * possible cluster size and then potentially pull it back
838 		 * up if the cluster was terminated prematurely--too much
839 		 * hassle.
840 		 */
841 		if (((tbp->b_flags & (B_CLUSTEROK | B_MALLOC | B_VMIO)) !=
842 		     (B_CLUSTEROK | B_VMIO)) ||
843 		  (tbp->b_bcount != tbp->b_bufsize) ||
844 		  (tbp->b_bcount != size) ||
845 		  (len == 1) ||
846 		  ((bp = (vp->v_vflag & VV_MD) != 0 ?
847 		  trypbuf(&cluster_pbuf_freecnt) :
848 		  getpbuf(&cluster_pbuf_freecnt)) == NULL)) {
849 			totalwritten += tbp->b_bufsize;
850 			bawrite(tbp);
851 			++start_lbn;
852 			--len;
853 			continue;
854 		}
855 
856 		/*
857 		 * We got a pbuf to make the cluster in.
858 		 * so initialise it.
859 		 */
860 		TAILQ_INIT(&bp->b_cluster.cluster_head);
861 		bp->b_bcount = 0;
862 		bp->b_bufsize = 0;
863 		bp->b_npages = 0;
864 		if (tbp->b_wcred != NOCRED)
865 			bp->b_wcred = crhold(tbp->b_wcred);
866 
867 		bp->b_blkno = tbp->b_blkno;
868 		bp->b_lblkno = tbp->b_lblkno;
869 		bp->b_offset = tbp->b_offset;
870 
871 		/*
872 		 * We are synthesizing a buffer out of vm_page_t's, but
873 		 * if the block size is not page aligned then the starting
874 		 * address may not be either.  Inherit the b_data offset
875 		 * from the original buffer.
876 		 */
877 		if ((gbflags & GB_UNMAPPED) == 0 ||
878 		    (tbp->b_flags & B_VMIO) == 0) {
879 			bp->b_data = (char *)((vm_offset_t)bp->b_data |
880 			    ((vm_offset_t)tbp->b_data & PAGE_MASK));
881 		} else {
882 			bp->b_data = unmapped_buf;
883 		}
884 		bp->b_flags |= B_CLUSTER | (tbp->b_flags & (B_VMIO |
885 		    B_NEEDCOMMIT));
886 		bp->b_iodone = cluster_callback;
887 		pbgetvp(vp, bp);
888 		/*
889 		 * From this location in the file, scan forward to see
890 		 * if there are buffers with adjacent data that need to
891 		 * be written as well.
892 		 */
893 		for (i = 0; i < len; ++i, ++start_lbn) {
894 			if (i != 0) { /* If not the first buffer */
895 				/*
896 				 * If the adjacent data is not even in core it
897 				 * can't need to be written.
898 				 */
899 				BO_LOCK(bo);
900 				if ((tbp = gbincore(bo, start_lbn)) == NULL ||
901 				    (tbp->b_vflags & BV_BKGRDINPROG)) {
902 					BO_UNLOCK(bo);
903 					break;
904 				}
905 
906 				/*
907 				 * If it IS in core, but has different
908 				 * characteristics, or is locked (which
909 				 * means it could be undergoing a background
910 				 * I/O or be in a weird state), then don't
911 				 * cluster with it.
912 				 */
913 				if (BUF_LOCK(tbp,
914 				    LK_EXCLUSIVE | LK_NOWAIT | LK_INTERLOCK,
915 				    BO_LOCKPTR(bo)))
916 					break;
917 
918 				if ((tbp->b_flags & (B_VMIO | B_CLUSTEROK |
919 				    B_INVAL | B_DELWRI | B_NEEDCOMMIT))
920 				    != (B_DELWRI | B_CLUSTEROK |
921 				    (bp->b_flags & (B_VMIO | B_NEEDCOMMIT))) ||
922 				    tbp->b_wcred != bp->b_wcred) {
923 					BUF_UNLOCK(tbp);
924 					break;
925 				}
926 
927 				/*
928 				 * Check that the combined cluster
929 				 * would make sense with regard to pages
930 				 * and would not be too large
931 				 */
932 				if ((tbp->b_bcount != size) ||
933 				  ((bp->b_blkno + (dbsize * i)) !=
934 				    tbp->b_blkno) ||
935 				  ((tbp->b_npages + bp->b_npages) >
936 				    (vp->v_mount->mnt_iosize_max / PAGE_SIZE))) {
937 					BUF_UNLOCK(tbp);
938 					break;
939 				}
940 
941 				/*
942 				 * Do not pull in pinned buffers.
943 				 */
944 				if (tbp->b_pin_count > 0) {
945 					BUF_UNLOCK(tbp);
946 					break;
947 				}
948 
949 				/*
950 				 * Ok, it's passed all the tests,
951 				 * so remove it from the free list
952 				 * and mark it busy. We will use it.
953 				 */
954 				bremfree(tbp);
955 				tbp->b_flags &= ~B_DONE;
956 			} /* end of code for non-first buffers only */
957 			/*
958 			 * If the IO is via the VM then we do some
959 			 * special VM hackery (yuck).  Since the buffer's
960 			 * block size may not be page-aligned it is possible
961 			 * for a page to be shared between two buffers.  We
962 			 * have to get rid of the duplication when building
963 			 * the cluster.
964 			 */
965 			if (tbp->b_flags & B_VMIO) {
966 				vm_page_t m;
967 
968 				VM_OBJECT_WLOCK(tbp->b_bufobj->bo_object);
969 				if (i == 0) {
970 					vfs_drain_busy_pages(tbp);
971 				} else { /* if not first buffer */
972 					for (j = 0; j < tbp->b_npages; j += 1) {
973 						m = tbp->b_pages[j];
974 						if (vm_page_xbusied(m)) {
975 							VM_OBJECT_WUNLOCK(
976 							    tbp->b_object);
977 							bqrelse(tbp);
978 							goto finishcluster;
979 						}
980 					}
981 				}
982 				for (j = 0; j < tbp->b_npages; j += 1) {
983 					m = tbp->b_pages[j];
984 					vm_page_sbusy(m);
985 					vm_object_pip_add(m->object, 1);
986 					if ((bp->b_npages == 0) ||
987 					  (bp->b_pages[bp->b_npages - 1] != m)) {
988 						bp->b_pages[bp->b_npages] = m;
989 						bp->b_npages++;
990 					}
991 				}
992 				VM_OBJECT_WUNLOCK(tbp->b_bufobj->bo_object);
993 			}
994 			bp->b_bcount += size;
995 			bp->b_bufsize += size;
996 			/*
997 			 * If any of the clustered buffers have their
998 			 * B_BARRIER flag set, transfer that request to
999 			 * the cluster.
1000 			 */
1001 			bp->b_flags |= (tbp->b_flags & B_BARRIER);
1002 			tbp->b_flags &= ~(B_DONE | B_BARRIER);
1003 			tbp->b_flags |= B_ASYNC;
1004 			tbp->b_ioflags &= ~BIO_ERROR;
1005 			tbp->b_iocmd = BIO_WRITE;
1006 			bundirty(tbp);
1007 			reassignbuf(tbp);		/* put on clean list */
1008 			bufobj_wref(tbp->b_bufobj);
1009 			BUF_KERNPROC(tbp);
1010 			TAILQ_INSERT_TAIL(&bp->b_cluster.cluster_head,
1011 				tbp, b_cluster.cluster_entry);
1012 		}
1013 	finishcluster:
1014 		if (buf_mapped(bp)) {
1015 			pmap_qenter(trunc_page((vm_offset_t) bp->b_data),
1016 			    (vm_page_t *)bp->b_pages, bp->b_npages);
1017 		}
1018 		if (bp->b_bufsize > bp->b_kvasize)
1019 			panic(
1020 			    "cluster_wbuild: b_bufsize(%ld) > b_kvasize(%d)\n",
1021 			    bp->b_bufsize, bp->b_kvasize);
1022 		totalwritten += bp->b_bufsize;
1023 		bp->b_dirtyoff = 0;
1024 		bp->b_dirtyend = bp->b_bufsize;
1025 		bawrite(bp);
1026 
1027 		len -= i;
1028 	}
1029 	return totalwritten;
1030 }
1031 
1032 /*
1033  * Collect together all the buffers in a cluster.
1034  * Plus add one additional buffer.
1035  */
1036 static struct cluster_save *
1037 cluster_collectbufs(struct vnode *vp, struct buf *last_bp, int gbflags)
1038 {
1039 	struct cluster_save *buflist;
1040 	struct buf *bp;
1041 	daddr_t lbn;
1042 	int i, len;
1043 
1044 	len = vp->v_lastw - vp->v_cstart + 1;
1045 	buflist = malloc(sizeof(struct buf *) * (len + 1) + sizeof(*buflist),
1046 	    M_SEGMENT, M_WAITOK);
1047 	buflist->bs_nchildren = 0;
1048 	buflist->bs_children = (struct buf **) (buflist + 1);
1049 	for (lbn = vp->v_cstart, i = 0; i < len; lbn++, i++) {
1050 		(void)bread_gb(vp, lbn, last_bp->b_bcount, NOCRED,
1051 		    gbflags, &bp);
1052 		buflist->bs_children[i] = bp;
1053 		if (bp->b_blkno == bp->b_lblkno)
1054 			VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno,
1055 				NULL, NULL);
1056 	}
1057 	buflist->bs_children[i] = bp = last_bp;
1058 	if (bp->b_blkno == bp->b_lblkno)
1059 		VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1060 	buflist->bs_nchildren = i + 1;
1061 	return (buflist);
1062 }
1063