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