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