]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_cluster.c
Merge from vmcontention.
[FreeBSD/FreeBSD.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  * 4. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *      @(#)vfs_cluster.c       8.7 (Berkeley) 2/13/94
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include "opt_debug_cluster.h"
38
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/proc.h>
43 #include <sys/bio.h>
44 #include <sys/buf.h>
45 #include <sys/vnode.h>
46 #include <sys/malloc.h>
47 #include <sys/mount.h>
48 #include <sys/resourcevar.h>
49 #include <sys/rwlock.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 static int      rcluster= 0;
58 SYSCTL_INT(_debug, OID_AUTO, rcluster, CTLFLAG_RW, &rcluster, 0,
59     "Debug VFS clustering code");
60 #endif
61
62 static MALLOC_DEFINE(M_SEGMENT, "cl_savebuf", "cluster_save buffer");
63
64 static struct cluster_save *
65         cluster_collectbufs(struct vnode *vp, struct buf *last_bp);
66 static struct buf *
67         cluster_rbuild(struct vnode *vp, u_quad_t filesize, daddr_t lbn,
68                          daddr_t blkno, long size, int run, struct buf *fbp);
69 static void cluster_callback(struct buf *);
70
71 static int write_behind = 1;
72 SYSCTL_INT(_vfs, OID_AUTO, write_behind, CTLFLAG_RW, &write_behind, 0,
73     "Cluster write-behind; 0: disable, 1: enable, 2: backed off");
74
75 static int read_max = 64;
76 SYSCTL_INT(_vfs, OID_AUTO, read_max, CTLFLAG_RW, &read_max, 0,
77     "Cluster read-ahead max block count");
78
79 /* Page expended to mark partially backed buffers */
80 extern vm_page_t        bogus_page;
81
82 /*
83  * Read data to a buf, including read-ahead if we find this to be beneficial.
84  * cluster_read replaces bread.
85  */
86 int
87 cluster_read(vp, filesize, lblkno, size, cred, totread, seqcount, bpp)
88         struct vnode *vp;
89         u_quad_t filesize;
90         daddr_t lblkno;
91         long size;
92         struct ucred *cred;
93         long totread;
94         int seqcount;
95         struct buf **bpp;
96 {
97         struct buf *bp, *rbp, *reqbp;
98         struct bufobj *bo;
99         daddr_t blkno, origblkno;
100         int maxra, racluster;
101         int error, ncontig;
102         int i;
103
104         error = 0;
105         bo = &vp->v_bufobj;
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 = seqcount;
113         maxra = min(read_max, maxra);
114         maxra = min(nbuf/8, maxra);
115         if (((u_quad_t)(lblkno + maxra + 1) * size) > filesize)
116                 maxra = (filesize / size) - lblkno;
117
118         /*
119          * get the requested block
120          */
121         *bpp = reqbp = bp = getblk(vp, lblkno, size, 0, 0, 0);
122         origblkno = lblkno;
123
124         /*
125          * if it is in the cache, then check to see if the reads have been
126          * sequential.  If they have, then try some read-ahead, otherwise
127          * back-off on prospective read-aheads.
128          */
129         if (bp->b_flags & B_CACHE) {
130                 if (!seqcount) {
131                         return 0;
132                 } else if ((bp->b_flags & B_RAM) == 0) {
133                         return 0;
134                 } else {
135                         bp->b_flags &= ~B_RAM;
136                         BO_LOCK(bo);
137                         for (i = 1; i < maxra; i++) {
138                                 /*
139                                  * Stop if the buffer does not exist or it
140                                  * is invalid (about to go away?)
141                                  */
142                                 rbp = gbincore(&vp->v_bufobj, lblkno+i);
143                                 if (rbp == NULL || (rbp->b_flags & B_INVAL))
144                                         break;
145
146                                 /*
147                                  * Set another read-ahead mark so we know 
148                                  * to check again. (If we can lock the
149                                  * buffer without waiting)
150                                  */
151                                 if ((((i % racluster) == (racluster - 1)) ||
152                                     (i == (maxra - 1))) 
153                                     && (0 == BUF_LOCK(rbp, 
154                                         LK_EXCLUSIVE | LK_NOWAIT, NULL))) {
155                                         rbp->b_flags |= B_RAM;
156                                         BUF_UNLOCK(rbp);
157                                 }                       
158                         }
159                         BO_UNLOCK(bo);
160                         if (i >= maxra) {
161                                 return 0;
162                         }
163                         lblkno += i;
164                 }
165                 reqbp = bp = NULL;
166         /*
167          * If it isn't in the cache, then get a chunk from
168          * disk if sequential, otherwise just get the block.
169          */
170         } else {
171                 off_t firstread = bp->b_offset;
172                 int nblks;
173
174                 KASSERT(bp->b_offset != NOOFFSET,
175                     ("cluster_read: no buffer offset"));
176
177                 ncontig = 0;
178
179                 /*
180                  * Compute the total number of blocks that we should read
181                  * synchronously.
182                  */
183                 if (firstread + totread > filesize)
184                         totread = filesize - firstread;
185                 nblks = howmany(totread, size);
186                 if (nblks > racluster)
187                         nblks = racluster;
188
189                 /*
190                  * Now compute the number of contiguous blocks.
191                  */
192                 if (nblks > 1) {
193                         error = VOP_BMAP(vp, lblkno, NULL,
194                                 &blkno, &ncontig, NULL);
195                         /*
196                          * If this failed to map just do the original block.
197                          */
198                         if (error || blkno == -1)
199                                 ncontig = 0;
200                 }
201
202                 /*
203                  * If we have contiguous data available do a cluster
204                  * otherwise just read the requested block.
205                  */
206                 if (ncontig) {
207                         /* Account for our first block. */
208                         ncontig = min(ncontig + 1, nblks);
209                         if (ncontig < nblks)
210                                 nblks = ncontig;
211                         bp = cluster_rbuild(vp, filesize, lblkno,
212                                 blkno, size, nblks, bp);
213                         lblkno += (bp->b_bufsize / size);
214                 } else {
215                         bp->b_flags |= B_RAM;
216                         bp->b_iocmd = BIO_READ;
217                         lblkno += 1;
218                 }
219         }
220
221         /*
222          * handle the synchronous read so that it is available ASAP.
223          */
224         if (bp) {
225                 if ((bp->b_flags & B_CLUSTER) == 0) {
226                         vfs_busy_pages(bp, 0);
227                 }
228                 bp->b_flags &= ~B_INVAL;
229                 bp->b_ioflags &= ~BIO_ERROR;
230                 if ((bp->b_flags & B_ASYNC) || bp->b_iodone != NULL)
231                         BUF_KERNPROC(bp);
232                 bp->b_iooffset = dbtob(bp->b_blkno);
233                 bstrategy(bp);
234                 curthread->td_ru.ru_inblock++;
235         }
236
237         /*
238          * If we have been doing sequential I/O, then do some read-ahead.
239          */
240         while (lblkno < (origblkno + maxra)) {
241                 error = VOP_BMAP(vp, lblkno, NULL, &blkno, &ncontig, NULL);
242                 if (error)
243                         break;
244
245                 if (blkno == -1)
246                         break;
247
248                 /*
249                  * We could throttle ncontig here by maxra but we might as
250                  * well read the data if it is contiguous.  We're throttled
251                  * by racluster anyway.
252                  */
253                 if (ncontig) {
254                         ncontig = min(ncontig + 1, racluster);
255                         rbp = cluster_rbuild(vp, filesize, lblkno, blkno,
256                                 size, ncontig, NULL);
257                         lblkno += (rbp->b_bufsize / size);
258                         if (rbp->b_flags & B_DELWRI) {
259                                 bqrelse(rbp);
260                                 continue;
261                         }
262                 } else {
263                         rbp = getblk(vp, lblkno, size, 0, 0, 0);
264                         lblkno += 1;
265                         if (rbp->b_flags & B_DELWRI) {
266                                 bqrelse(rbp);
267                                 continue;
268                         }
269                         rbp->b_flags |= B_ASYNC | B_RAM;
270                         rbp->b_iocmd = BIO_READ;
271                         rbp->b_blkno = blkno;
272                 }
273                 if (rbp->b_flags & B_CACHE) {
274                         rbp->b_flags &= ~B_ASYNC;
275                         bqrelse(rbp);
276                         continue;
277                 }
278                 if ((rbp->b_flags & B_CLUSTER) == 0) {
279                         vfs_busy_pages(rbp, 0);
280                 }
281                 rbp->b_flags &= ~B_INVAL;
282                 rbp->b_ioflags &= ~BIO_ERROR;
283                 if ((rbp->b_flags & B_ASYNC) || rbp->b_iodone != NULL)
284                         BUF_KERNPROC(rbp);
285                 rbp->b_iooffset = dbtob(rbp->b_blkno);
286                 bstrategy(rbp);
287                 curthread->td_ru.ru_inblock++;
288         }
289
290         if (reqbp)
291                 return (bufwait(reqbp));
292         else
293                 return (error);
294 }
295
296 /*
297  * If blocks are contiguous on disk, use this to provide clustered
298  * read ahead.  We will read as many blocks as possible sequentially
299  * and then parcel them up into logical blocks in the buffer hash table.
300  */
301 static struct buf *
302 cluster_rbuild(vp, filesize, lbn, blkno, size, run, fbp)
303         struct vnode *vp;
304         u_quad_t filesize;
305         daddr_t lbn;
306         daddr_t blkno;
307         long size;
308         int run;
309         struct buf *fbp;
310 {
311         struct bufobj *bo;
312         struct buf *bp, *tbp;
313         daddr_t bn;
314         off_t off;
315         long tinc, tsize;
316         int i, inc, j, toff;
317
318         KASSERT(size == vp->v_mount->mnt_stat.f_iosize,
319             ("cluster_rbuild: size %ld != f_iosize %jd\n",
320             size, (intmax_t)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_iocmd = BIO_READ; 
332         } else {
333                 tbp = getblk(vp, lbn, size, 0, 0, 0);
334                 if (tbp->b_flags & B_CACHE)
335                         return tbp;
336                 tbp->b_flags |= B_ASYNC | B_RAM;
337                 tbp->b_iocmd = BIO_READ;
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_CLUSTER | B_VMIO;
357         bp->b_iocmd = BIO_READ;
358         bp->b_iodone = cluster_callback;
359         bp->b_blkno = blkno;
360         bp->b_lblkno = lbn;
361         bp->b_offset = tbp->b_offset;
362         KASSERT(bp->b_offset != NOOFFSET, ("cluster_rbuild: no buffer offset"));
363         pbgetvp(vp, bp);
364
365         TAILQ_INIT(&bp->b_cluster.cluster_head);
366
367         bp->b_bcount = 0;
368         bp->b_bufsize = 0;
369         bp->b_npages = 0;
370
371         inc = btodb(size);
372         bo = &vp->v_bufobj;
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                         tbp = getblk(vp, lbn + i, size, 0, 0, GB_LOCK_NOWAIT);
381
382                         /* Don't wait around for locked bufs. */
383                         if (tbp == NULL)
384                                 break;
385
386                         /*
387                          * Stop scanning if the buffer is fully valid
388                          * (marked B_CACHE), or locked (may be doing a
389                          * background write), or if the buffer is not
390                          * VMIO backed.  The clustering code can only deal
391                          * with VMIO-backed buffers.
392                          */
393                         BO_LOCK(bo);
394                         if ((tbp->b_vflags & BV_BKGRDINPROG) ||
395                             (tbp->b_flags & B_CACHE) ||
396                             (tbp->b_flags & B_VMIO) == 0) {
397                                 BO_UNLOCK(bo);
398                                 bqrelse(tbp);
399                                 break;
400                         }
401                         BO_UNLOCK(bo);
402
403                         /*
404                          * The buffer must be completely invalid in order to
405                          * take part in the cluster.  If it is partially valid
406                          * then we stop.
407                          */
408                         off = tbp->b_offset;
409                         tsize = size;
410                         VM_OBJECT_WLOCK(tbp->b_bufobj->bo_object);
411                         for (j = 0; tsize > 0; j++) {
412                                 toff = off & PAGE_MASK;
413                                 tinc = tsize;
414                                 if (toff + tinc > PAGE_SIZE)
415                                         tinc = PAGE_SIZE - toff;
416                                 VM_OBJECT_ASSERT_WLOCKED(tbp->b_pages[j]->object);
417                                 if ((tbp->b_pages[j]->valid &
418                                     vm_page_bits(toff, tinc)) != 0)
419                                         break;
420                                 off += tinc;
421                                 tsize -= tinc;
422                         }
423                         VM_OBJECT_WUNLOCK(tbp->b_bufobj->bo_object);
424                         if (tsize > 0) {
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_ASYNC;
443                         tbp->b_iocmd = BIO_READ;
444                         if (tbp->b_blkno == tbp->b_lblkno) {
445                                 tbp->b_blkno = bn;
446                         } else if (tbp->b_blkno != bn) {
447                                 brelse(tbp);
448                                 break;
449                         }
450                 }
451                 /*
452                  * XXX fbp from caller may not be B_ASYNC, but we are going
453                  * to biodone() it in cluster_callback() anyway
454                  */
455                 BUF_KERNPROC(tbp);
456                 TAILQ_INSERT_TAIL(&bp->b_cluster.cluster_head,
457                         tbp, b_cluster.cluster_entry);
458                 VM_OBJECT_WLOCK(tbp->b_bufobj->bo_object);
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)
470                                 tbp->b_pages[j] = bogus_page;
471                 }
472                 VM_OBJECT_WUNLOCK(tbp->b_bufobj->bo_object);
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         VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
491         for (j = 0; j < bp->b_npages; j++) {
492                 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[j]->object);
493                 if (bp->b_pages[j]->valid == VM_PAGE_BITS_ALL)
494                         bp->b_pages[j] = bogus_page;
495         }
496         VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
497         if (bp->b_bufsize > bp->b_kvasize)
498                 panic("cluster_rbuild: b_bufsize(%ld) > b_kvasize(%d)\n",
499                     bp->b_bufsize, bp->b_kvasize);
500         bp->b_kvasize = bp->b_bufsize;
501
502         pmap_qenter(trunc_page((vm_offset_t) bp->b_data),
503                 (vm_page_t *)bp->b_pages, bp->b_npages);
504         return (bp);
505 }
506
507 /*
508  * Cleanup after a clustered read or write.
509  * This is complicated by the fact that any of the buffers might have
510  * extra memory (if there were no empty buffer headers at allocbuf time)
511  * that we will need to shift around.
512  */
513 static void
514 cluster_callback(bp)
515         struct buf *bp;
516 {
517         struct buf *nbp, *tbp;
518         int error = 0;
519
520         /*
521          * Must propogate errors to all the components.
522          */
523         if (bp->b_ioflags & BIO_ERROR)
524                 error = bp->b_error;
525
526         pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
527         /*
528          * Move memory from the large cluster buffer into the component
529          * buffers and mark IO as done on these.
530          */
531         for (tbp = TAILQ_FIRST(&bp->b_cluster.cluster_head);
532                 tbp; tbp = nbp) {
533                 nbp = TAILQ_NEXT(&tbp->b_cluster, cluster_entry);
534                 if (error) {
535                         tbp->b_ioflags |= BIO_ERROR;
536                         tbp->b_error = error;
537                 } else {
538                         tbp->b_dirtyoff = tbp->b_dirtyend = 0;
539                         tbp->b_flags &= ~B_INVAL;
540                         tbp->b_ioflags &= ~BIO_ERROR;
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                 bufdone(tbp);
552         }
553         pbrelvp(bp);
554         relpbuf(bp, &cluster_pbuf_freecnt);
555 }
556
557 /*
558  *      cluster_wbuild_wb:
559  *
560  *      Implement modified write build for cluster.
561  *
562  *              write_behind = 0        write behind disabled
563  *              write_behind = 1        write behind normal (default)
564  *              write_behind = 2        write behind backed-off
565  */
566
567 static __inline int
568 cluster_wbuild_wb(struct vnode *vp, long size, daddr_t start_lbn, int len)
569 {
570         int r = 0;
571
572         switch(write_behind) {
573         case 2:
574                 if (start_lbn < len)
575                         break;
576                 start_lbn -= len;
577                 /* FALLTHROUGH */
578         case 1:
579                 r = cluster_wbuild(vp, size, start_lbn, len);
580                 /* FALLTHROUGH */
581         default:
582                 /* FALLTHROUGH */
583                 break;
584         }
585         return(r);
586 }
587
588 /*
589  * Do clustered write for FFS.
590  *
591  * Three cases:
592  *      1. Write is not sequential (write asynchronously)
593  *      Write is sequential:
594  *      2.      beginning of cluster - begin cluster
595  *      3.      middle of a cluster - add to cluster
596  *      4.      end of a cluster - asynchronously write cluster
597  */
598 void
599 cluster_write(struct vnode *vp, struct buf *bp, u_quad_t filesize, int seqcount)
600 {
601         daddr_t lbn;
602         int maxclen, cursize;
603         int lblocksize;
604         int async;
605
606         if (vp->v_type == VREG) {
607                 async = DOINGASYNC(vp);
608                 lblocksize = vp->v_mount->mnt_stat.f_iosize;
609         } else {
610                 async = 0;
611                 lblocksize = bp->b_bufsize;
612         }
613         lbn = bp->b_lblkno;
614         KASSERT(bp->b_offset != NOOFFSET, ("cluster_write: no buffer offset"));
615
616         /* Initialize vnode to beginning of file. */
617         if (lbn == 0)
618                 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
619
620         if (vp->v_clen == 0 || lbn != vp->v_lastw + 1 ||
621             (bp->b_blkno != vp->v_lasta + btodb(lblocksize))) {
622                 maxclen = vp->v_mount->mnt_iosize_max / lblocksize - 1;
623                 if (vp->v_clen != 0) {
624                         /*
625                          * Next block is not sequential.
626                          *
627                          * If we are not writing at end of file, the process
628                          * seeked to another point in the file since its last
629                          * write, or we have reached our maximum cluster size,
630                          * then push the previous cluster. Otherwise try
631                          * reallocating to make it sequential.
632                          *
633                          * Change to algorithm: only push previous cluster if
634                          * it was sequential from the point of view of the
635                          * seqcount heuristic, otherwise leave the buffer 
636                          * intact so we can potentially optimize the I/O
637                          * later on in the buf_daemon or update daemon
638                          * flush.
639                          */
640                         cursize = vp->v_lastw - vp->v_cstart + 1;
641                         if (((u_quad_t) bp->b_offset + lblocksize) != filesize ||
642                             lbn != vp->v_lastw + 1 || vp->v_clen <= cursize) {
643                                 if (!async && seqcount > 0) {
644                                         cluster_wbuild_wb(vp, lblocksize,
645                                                 vp->v_cstart, cursize);
646                                 }
647                         } else {
648                                 struct buf **bpp, **endbp;
649                                 struct cluster_save *buflist;
650
651                                 buflist = cluster_collectbufs(vp, bp);
652                                 endbp = &buflist->bs_children
653                                     [buflist->bs_nchildren - 1];
654                                 if (VOP_REALLOCBLKS(vp, buflist)) {
655                                         /*
656                                          * Failed, push the previous cluster
657                                          * if *really* writing sequentially
658                                          * in the logical file (seqcount > 1),
659                                          * otherwise delay it in the hopes that
660                                          * the low level disk driver can
661                                          * optimize the write ordering.
662                                          */
663                                         for (bpp = buflist->bs_children;
664                                              bpp < endbp; bpp++)
665                                                 brelse(*bpp);
666                                         free(buflist, M_SEGMENT);
667                                         if (seqcount > 1) {
668                                                 cluster_wbuild_wb(vp, 
669                                                     lblocksize, vp->v_cstart, 
670                                                     cursize);
671                                         }
672                                 } else {
673                                         /*
674                                          * Succeeded, keep building cluster.
675                                          */
676                                         for (bpp = buflist->bs_children;
677                                              bpp <= endbp; bpp++)
678                                                 bdwrite(*bpp);
679                                         free(buflist, M_SEGMENT);
680                                         vp->v_lastw = lbn;
681                                         vp->v_lasta = bp->b_blkno;
682                                         return;
683                                 }
684                         }
685                 }
686                 /*
687                  * Consider beginning a cluster. If at end of file, make
688                  * cluster as large as possible, otherwise find size of
689                  * existing cluster.
690                  */
691                 if ((vp->v_type == VREG) &&
692                         ((u_quad_t) bp->b_offset + lblocksize) != filesize &&
693                     (bp->b_blkno == bp->b_lblkno) &&
694                     (VOP_BMAP(vp, lbn, NULL, &bp->b_blkno, &maxclen, NULL) ||
695                      bp->b_blkno == -1)) {
696                         bawrite(bp);
697                         vp->v_clen = 0;
698                         vp->v_lasta = bp->b_blkno;
699                         vp->v_cstart = lbn + 1;
700                         vp->v_lastw = lbn;
701                         return;
702                 }
703                 vp->v_clen = maxclen;
704                 if (!async && maxclen == 0) {   /* I/O not contiguous */
705                         vp->v_cstart = lbn + 1;
706                         bawrite(bp);
707                 } else {        /* Wait for rest of cluster */
708                         vp->v_cstart = lbn;
709                         bdwrite(bp);
710                 }
711         } else if (lbn == vp->v_cstart + vp->v_clen) {
712                 /*
713                  * At end of cluster, write it out if seqcount tells us we
714                  * are operating sequentially, otherwise let the buf or
715                  * update daemon handle it.
716                  */
717                 bdwrite(bp);
718                 if (seqcount > 1)
719                         cluster_wbuild_wb(vp, lblocksize, vp->v_cstart, vp->v_clen + 1);
720                 vp->v_clen = 0;
721                 vp->v_cstart = lbn + 1;
722         } else if (vm_page_count_severe()) {
723                 /*
724                  * We are low on memory, get it going NOW
725                  */
726                 bawrite(bp);
727         } else {
728                 /*
729                  * In the middle of a cluster, so just delay the I/O for now.
730                  */
731                 bdwrite(bp);
732         }
733         vp->v_lastw = lbn;
734         vp->v_lasta = bp->b_blkno;
735 }
736
737
738 /*
739  * This is an awful lot like cluster_rbuild...wish they could be combined.
740  * The last lbn argument is the current block on which I/O is being
741  * performed.  Check to see that it doesn't fall in the middle of
742  * the current block (if last_bp == NULL).
743  */
744 int
745 cluster_wbuild(vp, size, start_lbn, len)
746         struct vnode *vp;
747         long size;
748         daddr_t start_lbn;
749         int len;
750 {
751         struct buf *bp, *tbp;
752         struct bufobj *bo;
753         int i, j;
754         int totalwritten = 0;
755         int dbsize = btodb(size);
756
757         bo = &vp->v_bufobj;
758         while (len > 0) {
759                 /*
760                  * If the buffer is not delayed-write (i.e. dirty), or it
761                  * is delayed-write but either locked or inval, it cannot
762                  * partake in the clustered write.
763                  */
764                 BO_LOCK(bo);
765                 if ((tbp = gbincore(&vp->v_bufobj, start_lbn)) == NULL ||
766                     (tbp->b_vflags & BV_BKGRDINPROG)) {
767                         BO_UNLOCK(bo);
768                         ++start_lbn;
769                         --len;
770                         continue;
771                 }
772                 if (BUF_LOCK(tbp,
773                     LK_EXCLUSIVE | LK_NOWAIT | LK_INTERLOCK, BO_MTX(bo))) {
774                         ++start_lbn;
775                         --len;
776                         continue;
777                 }
778                 if ((tbp->b_flags & (B_INVAL | B_DELWRI)) != B_DELWRI) {
779                         BUF_UNLOCK(tbp);
780                         ++start_lbn;
781                         --len;
782                         continue;
783                 }
784                 if (tbp->b_pin_count >  0) {
785                         BUF_UNLOCK(tbp);
786                         ++start_lbn;
787                         --len;
788                         continue;
789                 }
790                 bremfree(tbp);
791                 tbp->b_flags &= ~B_DONE;
792
793                 /*
794                  * Extra memory in the buffer, punt on this buffer.
795                  * XXX we could handle this in most cases, but we would
796                  * have to push the extra memory down to after our max
797                  * possible cluster size and then potentially pull it back
798                  * up if the cluster was terminated prematurely--too much
799                  * hassle.
800                  */
801                 if (((tbp->b_flags & (B_CLUSTEROK | B_MALLOC | B_VMIO)) != 
802                      (B_CLUSTEROK | B_VMIO)) ||
803                   (tbp->b_bcount != tbp->b_bufsize) ||
804                   (tbp->b_bcount != size) ||
805                   (len == 1) ||
806                   ((bp = getpbuf(&cluster_pbuf_freecnt)) == NULL)) {
807                         totalwritten += tbp->b_bufsize;
808                         bawrite(tbp);
809                         ++start_lbn;
810                         --len;
811                         continue;
812                 }
813
814                 /*
815                  * We got a pbuf to make the cluster in.
816                  * so initialise it.
817                  */
818                 TAILQ_INIT(&bp->b_cluster.cluster_head);
819                 bp->b_bcount = 0;
820                 bp->b_bufsize = 0;
821                 bp->b_npages = 0;
822                 if (tbp->b_wcred != NOCRED)
823                         bp->b_wcred = crhold(tbp->b_wcred);
824
825                 bp->b_blkno = tbp->b_blkno;
826                 bp->b_lblkno = tbp->b_lblkno;
827                 bp->b_offset = tbp->b_offset;
828
829                 /*
830                  * We are synthesizing a buffer out of vm_page_t's, but
831                  * if the block size is not page aligned then the starting
832                  * address may not be either.  Inherit the b_data offset
833                  * from the original buffer.
834                  */
835                 bp->b_data = (char *)((vm_offset_t)bp->b_data |
836                     ((vm_offset_t)tbp->b_data & PAGE_MASK));
837                 bp->b_flags |= B_CLUSTER |
838                                 (tbp->b_flags & (B_VMIO | B_NEEDCOMMIT));
839                 bp->b_iodone = cluster_callback;
840                 pbgetvp(vp, bp);
841                 /*
842                  * From this location in the file, scan forward to see
843                  * if there are buffers with adjacent data that need to
844                  * be written as well.
845                  */
846                 for (i = 0; i < len; ++i, ++start_lbn) {
847                         if (i != 0) { /* If not the first buffer */
848                                 /*
849                                  * If the adjacent data is not even in core it
850                                  * can't need to be written.
851                                  */
852                                 BO_LOCK(bo);
853                                 if ((tbp = gbincore(bo, start_lbn)) == NULL ||
854                                     (tbp->b_vflags & BV_BKGRDINPROG)) {
855                                         BO_UNLOCK(bo);
856                                         break;
857                                 }
858
859                                 /*
860                                  * If it IS in core, but has different
861                                  * characteristics, or is locked (which
862                                  * means it could be undergoing a background
863                                  * I/O or be in a weird state), then don't
864                                  * cluster with it.
865                                  */
866                                 if (BUF_LOCK(tbp,
867                                     LK_EXCLUSIVE | LK_NOWAIT | LK_INTERLOCK,
868                                     BO_MTX(bo)))
869                                         break;
870
871                                 if ((tbp->b_flags & (B_VMIO | B_CLUSTEROK |
872                                     B_INVAL | B_DELWRI | B_NEEDCOMMIT))
873                                     != (B_DELWRI | B_CLUSTEROK |
874                                     (bp->b_flags & (B_VMIO | B_NEEDCOMMIT))) ||
875                                     tbp->b_wcred != bp->b_wcred) {
876                                         BUF_UNLOCK(tbp);
877                                         break;
878                                 }
879
880                                 /*
881                                  * Check that the combined cluster
882                                  * would make sense with regard to pages
883                                  * and would not be too large
884                                  */
885                                 if ((tbp->b_bcount != size) ||
886                                   ((bp->b_blkno + (dbsize * i)) !=
887                                     tbp->b_blkno) ||
888                                   ((tbp->b_npages + bp->b_npages) >
889                                     (vp->v_mount->mnt_iosize_max / PAGE_SIZE))) {
890                                         BUF_UNLOCK(tbp);
891                                         break;
892                                 }
893
894                                 /*
895                                  * Do not pull in pinned buffers.
896                                  */
897                                 if (tbp->b_pin_count > 0) {
898                                         BUF_UNLOCK(tbp);
899                                         break;
900                                 }
901
902                                 /*
903                                  * Ok, it's passed all the tests,
904                                  * so remove it from the free list
905                                  * and mark it busy. We will use it.
906                                  */
907                                 bremfree(tbp);
908                                 tbp->b_flags &= ~B_DONE;
909                         } /* end of code for non-first buffers only */
910                         /*
911                          * If the IO is via the VM then we do some
912                          * special VM hackery (yuck).  Since the buffer's
913                          * block size may not be page-aligned it is possible
914                          * for a page to be shared between two buffers.  We
915                          * have to get rid of the duplication when building
916                          * the cluster.
917                          */
918                         if (tbp->b_flags & B_VMIO) {
919                                 vm_page_t m;
920
921                                 VM_OBJECT_WLOCK(tbp->b_bufobj->bo_object);
922                                 if (i != 0) { /* if not first buffer */
923                                         for (j = 0; j < tbp->b_npages; j += 1) {
924                                                 m = tbp->b_pages[j];
925                                                 if (m->oflags & VPO_BUSY) {
926                                                         VM_OBJECT_WUNLOCK(
927                                                             tbp->b_object);
928                                                         bqrelse(tbp);
929                                                         goto finishcluster;
930                                                 }
931                                         }
932                                 }
933                                 for (j = 0; j < tbp->b_npages; j += 1) {
934                                         m = tbp->b_pages[j];
935                                         vm_page_io_start(m);
936                                         vm_object_pip_add(m->object, 1);
937                                         if ((bp->b_npages == 0) ||
938                                           (bp->b_pages[bp->b_npages - 1] != m)) {
939                                                 bp->b_pages[bp->b_npages] = m;
940                                                 bp->b_npages++;
941                                         }
942                                 }
943                                 VM_OBJECT_WUNLOCK(tbp->b_bufobj->bo_object);
944                         }
945                         bp->b_bcount += size;
946                         bp->b_bufsize += size;
947                         /*
948                          * If any of the clustered buffers have their
949                          * B_BARRIER flag set, transfer that request to
950                          * the cluster.
951                          */
952                         bp->b_flags |= (tbp->b_flags & B_BARRIER);
953                         tbp->b_flags &= ~(B_DONE | B_BARRIER);
954                         tbp->b_flags |= B_ASYNC;
955                         tbp->b_ioflags &= ~BIO_ERROR;
956                         tbp->b_iocmd = BIO_WRITE;
957                         bundirty(tbp);
958                         reassignbuf(tbp);               /* put on clean list */
959                         bufobj_wref(tbp->b_bufobj);
960                         BUF_KERNPROC(tbp);
961                         TAILQ_INSERT_TAIL(&bp->b_cluster.cluster_head,
962                                 tbp, b_cluster.cluster_entry);
963                 }
964         finishcluster:
965                 pmap_qenter(trunc_page((vm_offset_t) bp->b_data),
966                         (vm_page_t *) bp->b_pages, bp->b_npages);
967                 if (bp->b_bufsize > bp->b_kvasize)
968                         panic(
969                             "cluster_wbuild: b_bufsize(%ld) > b_kvasize(%d)\n",
970                             bp->b_bufsize, bp->b_kvasize);
971                 bp->b_kvasize = bp->b_bufsize;
972                 totalwritten += bp->b_bufsize;
973                 bp->b_dirtyoff = 0;
974                 bp->b_dirtyend = bp->b_bufsize;
975                 bawrite(bp);
976
977                 len -= i;
978         }
979         return totalwritten;
980 }
981
982 /*
983  * Collect together all the buffers in a cluster.
984  * Plus add one additional buffer.
985  */
986 static struct cluster_save *
987 cluster_collectbufs(vp, last_bp)
988         struct vnode *vp;
989         struct buf *last_bp;
990 {
991         struct cluster_save *buflist;
992         struct buf *bp;
993         daddr_t lbn;
994         int i, len;
995
996         len = vp->v_lastw - vp->v_cstart + 1;
997         buflist = malloc(sizeof(struct buf *) * (len + 1) + sizeof(*buflist),
998             M_SEGMENT, M_WAITOK);
999         buflist->bs_nchildren = 0;
1000         buflist->bs_children = (struct buf **) (buflist + 1);
1001         for (lbn = vp->v_cstart, i = 0; i < len; lbn++, i++) {
1002                 (void) bread(vp, lbn, last_bp->b_bcount, NOCRED, &bp);
1003                 buflist->bs_children[i] = bp;
1004                 if (bp->b_blkno == bp->b_lblkno)
1005                         VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno,
1006                                 NULL, NULL);
1007         }
1008         buflist->bs_children[i] = bp = last_bp;
1009         if (bp->b_blkno == bp->b_lblkno)
1010                 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1011         buflist->bs_nchildren = i + 1;
1012         return (buflist);
1013 }