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