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