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