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