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