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