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