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