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