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