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