kernel - Fix clustered read bug (2)
[dragonfly.git] / sys / kern / vfs_cluster.c
1 /*-
2  * Copyright (c) 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Modifications/enhancements:
5  *      Copyright (c) 1995 John S. Dyson.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *      This product includes software developed by the University of
18  *      California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  *      @(#)vfs_cluster.c       8.7 (Berkeley) 2/13/94
36  * $FreeBSD: src/sys/kern/vfs_cluster.c,v 1.92.2.9 2001/11/18 07:10:59 dillon Exp $
37  * $DragonFly: src/sys/kern/vfs_cluster.c,v 1.40 2008/07/14 03:09:00 dillon Exp $
38  */
39
40 #include "opt_debug_cluster.h"
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/proc.h>
46 #include <sys/buf.h>
47 #include <sys/vnode.h>
48 #include <sys/malloc.h>
49 #include <sys/mount.h>
50 #include <sys/resourcevar.h>
51 #include <sys/vmmeter.h>
52 #include <vm/vm.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_page.h>
55 #include <sys/sysctl.h>
56
57 #include <sys/buf2.h>
58 #include <vm/vm_page2.h>
59
60 #include <machine/limits.h>
61
62 #if defined(CLUSTERDEBUG)
63 #include <sys/sysctl.h>
64 static int      rcluster= 0;
65 SYSCTL_INT(_debug, OID_AUTO, rcluster, CTLFLAG_RW, &rcluster, 0, "");
66 #endif
67
68 static MALLOC_DEFINE(M_SEGMENT, "cluster_save", "cluster_save buffer");
69
70 static struct cluster_save *
71         cluster_collectbufs (struct vnode *vp, struct buf *last_bp,
72                             int blksize);
73 static struct buf *
74         cluster_rbuild (struct vnode *vp, off_t filesize, off_t loffset,
75                             off_t doffset, int blksize, int run, 
76                             struct buf *fbp);
77 static void cluster_callback (struct bio *);
78 static void cluster_setram (struct buf *);
79
80 static int write_behind = 1;
81 SYSCTL_INT(_vfs, OID_AUTO, write_behind, CTLFLAG_RW, &write_behind, 0,
82     "Cluster write-behind setting");
83 static int max_readahead = 2 * 1024 * 1024;
84 SYSCTL_INT(_vfs, OID_AUTO, max_readahead, CTLFLAG_RW, &max_readahead, 0,
85     "Limit in bytes for desired cluster read-ahead");
86
87 extern vm_page_t        bogus_page;
88
89 extern int cluster_pbuf_freecnt;
90
91 /*
92  * This replaces bread.
93  *
94  * filesize     - read-ahead @ blksize will not cross this boundary
95  * loffset      - loffset for returned *bpp
96  * blksize      - blocksize for returned *bpp and read-ahead bps
97  * minreq       - minimum (not a hard minimum) in bytes, typically reflects
98  *                a higher level uio resid.
99  * maxreq       - maximum (sequential heuristic) in bytes (highet typ ~2MB)
100  * bpp          - return buffer (*bpp) for (loffset,blksize)
101  */
102 int
103 cluster_readx(struct vnode *vp, off_t filesize, off_t loffset,
104              int blksize, size_t minreq, size_t maxreq, struct buf **bpp)
105 {
106         struct buf *bp, *rbp, *reqbp;
107         off_t origoffset;
108         off_t doffset;
109         int error;
110         int i;
111         int maxra;
112         int maxrbuild;
113
114         error = 0;
115
116         /*
117          * Calculate the desired read-ahead in blksize'd blocks (maxra).
118          * To do this we calculate maxreq.
119          *
120          * maxreq typically starts out as a sequential heuristic.  If the
121          * high level uio/resid is bigger (minreq), we pop maxreq up to
122          * minreq.  This represents the case where random I/O is being
123          * performed by the userland is issuing big read()'s.
124          *
125          * Then we limit maxreq to max_readahead to ensure it is a reasonable
126          * value.
127          *
128          * Finally we must ensure that (loffset + maxreq) does not cross the
129          * boundary (filesize) for the current blocksize.  If we allowed it
130          * to cross we could end up with buffers past the boundary with the
131          * wrong block size (HAMMER large-data areas use mixed block sizes).
132          * minreq is also absolutely limited to filesize.
133          */
134         if (maxreq < minreq)
135                 maxreq = minreq;
136         /* minreq not used beyond this point */
137
138         if (maxreq > max_readahead) {
139                 maxreq = max_readahead;
140                 if (maxreq > 16 * 1024 * 1024)
141                         maxreq = 16 * 1024 * 1024;
142         }
143         if (maxreq < blksize)
144                 maxreq = blksize;
145         if (loffset + maxreq > filesize) {
146                 if (loffset > filesize)
147                         maxreq = 0;
148                 else
149                         maxreq = filesize - loffset;
150         }
151
152         maxra = (int)(maxreq / blksize);
153
154         /*
155          * Get the requested block.
156          */
157         if (*bpp)
158                 reqbp = bp = *bpp;
159         else
160                 *bpp = reqbp = bp = getblk(vp, loffset, blksize, 0, 0);
161         origoffset = loffset;
162
163         /*
164          * Calculate the maximum cluster size for a single I/O, used
165          * by cluster_rbuild().
166          */
167         maxrbuild = vmaxiosize(vp) / blksize;
168
169         /*
170          * if it is in the cache, then check to see if the reads have been
171          * sequential.  If they have, then try some read-ahead, otherwise
172          * back-off on prospective read-aheads.
173          */
174         if (bp->b_flags & B_CACHE) {
175                 /*
176                  * Not sequential, do not do any read-ahead
177                  */
178                 if (maxra <= 1)
179                         return 0;
180
181                 /*
182                  * No read-ahead mark, do not do any read-ahead
183                  * yet.
184                  */
185                 if ((bp->b_flags & B_RAM) == 0)
186                         return 0;
187
188                 /*
189                  * We hit a read-ahead-mark, figure out how much read-ahead
190                  * to do (maxra) and where to start (loffset).
191                  *
192                  * Shortcut the scan.  Typically the way this works is that
193                  * we've built up all the blocks inbetween except for the
194                  * last in previous iterations, so if the second-to-last
195                  * block is present we just skip ahead to it.
196                  *
197                  * This algorithm has O(1) cpu in the steady state no
198                  * matter how large maxra is.
199                  */
200                 bp->b_flags &= ~B_RAM;
201
202                 if (findblk(vp, loffset + (maxra - 2) * blksize, FINDBLK_TEST))
203                         i = maxra - 1;
204                 else
205                         i = 1;
206                 while (i < maxra) {
207                         if (findblk(vp, loffset + i * blksize,
208                                     FINDBLK_TEST) == NULL) {
209                                 break;
210                         }
211                         ++i;
212                 }
213
214                 /*
215                  * We got everything or everything is in the cache, no
216                  * point continuing.
217                  */
218                 if (i >= maxra)
219                         return 0;
220
221                 /*
222                  * Calculate where to start the read-ahead and how much
223                  * to do.  Generally speaking we want to read-ahead by
224                  * (maxra) when we've found a read-ahead mark.  We do
225                  * not want to reduce maxra here as it will cause
226                  * successive read-ahead I/O's to be smaller and smaller.
227                  *
228                  * However, we have to make sure we don't break the
229                  * filesize limitation for the clustered operation.
230                  */
231                 loffset += i * blksize;
232                 reqbp = bp = NULL;
233
234                 if (loffset >= filesize)
235                         return 0;
236                 if (loffset + maxra * blksize > filesize) {
237                         maxreq = filesize - loffset;
238                         maxra = (int)(maxreq / blksize);
239                 }
240         } else {
241                 __debugvar off_t firstread = bp->b_loffset;
242                 int nblks;
243
244                 /*
245                  * Set-up synchronous read for bp.
246                  */
247                 bp->b_cmd = BUF_CMD_READ;
248                 bp->b_bio1.bio_done = biodone_sync;
249                 bp->b_bio1.bio_flags |= BIO_SYNC;
250
251                 KASSERT(firstread != NOOFFSET, 
252                         ("cluster_read: no buffer offset"));
253
254                 /*
255                  * nblks is our cluster_rbuild request size, limited
256                  * primarily by the device.
257                  */
258                 if ((nblks = maxra) > maxrbuild)
259                         nblks = maxrbuild;
260
261                 if (nblks > 1) {
262                         int burstbytes;
263
264                         error = VOP_BMAP(vp, loffset, &doffset,
265                                          &burstbytes, NULL, BUF_CMD_READ);
266                         if (error)
267                                 goto single_block_read;
268                         if (nblks > burstbytes / blksize)
269                                 nblks = burstbytes / blksize;
270                         if (doffset == NOOFFSET)
271                                 goto single_block_read;
272                         if (nblks <= 1)
273                                 goto single_block_read;
274
275                         bp = cluster_rbuild(vp, filesize, loffset,
276                                             doffset, blksize, nblks, bp);
277                         loffset += bp->b_bufsize;
278                         maxra -= bp->b_bufsize / blksize;
279                 } else {
280 single_block_read:
281                         /*
282                          * If it isn't in the cache, then get a chunk from
283                          * disk if sequential, otherwise just get the block.
284                          */
285                         cluster_setram(bp);
286                         loffset += blksize;
287                         --maxra;
288                 }
289         }
290
291         /*
292          * If B_CACHE was not set issue bp.  bp will either be an
293          * asynchronous cluster buf or a synchronous single-buf.
294          * If it is a single buf it will be the same as reqbp.
295          *
296          * NOTE: Once an async cluster buf is issued bp becomes invalid.
297          */
298         if (bp) {
299 #if defined(CLUSTERDEBUG)
300                 if (rcluster)
301                         kprintf("S(%012jx,%d,%d)\n",
302                             (intmax_t)bp->b_loffset, bp->b_bcount, maxra);
303 #endif
304                 if ((bp->b_flags & B_CLUSTER) == 0)
305                         vfs_busy_pages(vp, bp);
306                 bp->b_flags &= ~(B_ERROR|B_INVAL);
307                 vn_strategy(vp, &bp->b_bio1);
308                 error = 0;
309                 /* bp invalid now */
310         }
311
312         /*
313          * If we have been doing sequential I/O, then do some read-ahead.
314          * The code above us should have positioned us at the next likely
315          * offset.
316          *
317          * Only mess with buffers which we can immediately lock.  HAMMER
318          * will do device-readahead irrespective of what the blocks
319          * represent.
320          */
321         while (error == 0 && maxra > 0) {
322                 int burstbytes;
323                 int tmp_error;
324                 int nblks;
325
326                 rbp = getblk(vp, loffset, blksize,
327                              GETBLK_SZMATCH|GETBLK_NOWAIT, 0);
328                 if (rbp == NULL)
329                         goto no_read_ahead;
330                 if ((rbp->b_flags & B_CACHE)) {
331                         bqrelse(rbp);
332                         goto no_read_ahead;
333                 }
334
335                 /*
336                  * An error from the read-ahead bmap has nothing to do
337                  * with the caller's original request.
338                  */
339                 tmp_error = VOP_BMAP(vp, loffset, &doffset,
340                                      &burstbytes, NULL, BUF_CMD_READ);
341                 if (tmp_error || doffset == NOOFFSET) {
342                         rbp->b_flags |= B_INVAL;
343                         brelse(rbp);
344                         rbp = NULL;
345                         goto no_read_ahead;
346                 }
347                 if ((nblks = maxra) > maxrbuild)
348                         nblks = maxrbuild;
349                 if (nblks > burstbytes / blksize)
350                         nblks = burstbytes / blksize;
351
352                 /*
353                  * rbp: async read
354                  */
355                 rbp->b_cmd = BUF_CMD_READ;
356                 /*rbp->b_flags |= B_AGE*/;
357                 cluster_setram(rbp);
358
359                 if (nblks > 1) {
360                         rbp = cluster_rbuild(vp, filesize, loffset,
361                                              doffset, blksize, 
362                                              nblks, rbp);
363                 } else {
364                         rbp->b_bio2.bio_offset = doffset;
365                 }
366
367 #if defined(CLUSTERDEBUG)
368                 if (rcluster) {
369                         if (bp) {
370                                 kprintf("A+(%012jx,%d,%jd) "
371                                         "doff=%012jx minr=%zd ra=%d\n",
372                                     (intmax_t)loffset, rbp->b_bcount,
373                                     (intmax_t)(loffset - origoffset),
374                                     (intmax_t)doffset, minreq, maxra);
375                         } else {
376                                 kprintf("A-(%012jx,%d,%jd) "
377                                         "doff=%012jx minr=%zd ra=%d\n",
378                                     (intmax_t)rbp->b_loffset, rbp->b_bcount,
379                                     (intmax_t)(loffset - origoffset),
380                                     (intmax_t)doffset, minreq, maxra);
381                         }
382                 }
383 #endif
384                 rbp->b_flags &= ~(B_ERROR|B_INVAL);
385
386                 if ((rbp->b_flags & B_CLUSTER) == 0)
387                         vfs_busy_pages(vp, rbp);
388                 BUF_KERNPROC(rbp);
389                 loffset += rbp->b_bufsize;
390                 maxra -= rbp->b_bufsize / blksize;
391                 vn_strategy(vp, &rbp->b_bio1);
392                 /* rbp invalid now */
393         }
394
395         /*
396          * Wait for our original buffer to complete its I/O.  reqbp will
397          * be NULL if the original buffer was B_CACHE.  We are returning
398          * (*bpp) which is the same as reqbp when reqbp != NULL.
399          */
400 no_read_ahead:
401         if (reqbp) {
402                 KKASSERT(reqbp->b_bio1.bio_flags & BIO_SYNC);
403                 error = biowait(&reqbp->b_bio1, "clurd");
404         }
405         return (error);
406 }
407
408 /*
409  * If blocks are contiguous on disk, use this to provide clustered
410  * read ahead.  We will read as many blocks as possible sequentially
411  * and then parcel them up into logical blocks in the buffer hash table.
412  *
413  * This function either returns a cluster buf or it returns fbp.  fbp is
414  * already expected to be set up as a synchronous or asynchronous request.
415  *
416  * If a cluster buf is returned it will always be async.
417  */
418 static struct buf *
419 cluster_rbuild(struct vnode *vp, off_t filesize, off_t loffset, off_t doffset,
420                int blksize, int run, struct buf *fbp)
421 {
422         struct buf *bp, *tbp;
423         off_t boffset;
424         int i, j;
425         int maxiosize = vmaxiosize(vp);
426
427         /*
428          * avoid a division
429          */
430         while (loffset + run * blksize > filesize) {
431                 --run;
432         }
433
434         tbp = fbp;
435         tbp->b_bio2.bio_offset = doffset;
436         if((tbp->b_flags & B_MALLOC) ||
437             ((tbp->b_flags & B_VMIO) == 0) || (run <= 1)) {
438                 return tbp;
439         }
440
441         bp = trypbuf_kva(&cluster_pbuf_freecnt);
442         if (bp == NULL) {
443                 return tbp;
444         }
445
446         /*
447          * We are synthesizing a buffer out of vm_page_t's, but
448          * if the block size is not page aligned then the starting
449          * address may not be either.  Inherit the b_data offset
450          * from the original buffer.
451          */
452         bp->b_data = (char *)((vm_offset_t)bp->b_data |
453             ((vm_offset_t)tbp->b_data & PAGE_MASK));
454         bp->b_flags |= B_CLUSTER | B_VMIO;
455         bp->b_cmd = BUF_CMD_READ;
456         bp->b_bio1.bio_done = cluster_callback;         /* default to async */
457         bp->b_bio1.bio_caller_info1.cluster_head = NULL;
458         bp->b_bio1.bio_caller_info2.cluster_tail = NULL;
459         bp->b_loffset = loffset;
460         bp->b_bio2.bio_offset = doffset;
461         KASSERT(bp->b_loffset != NOOFFSET,
462                 ("cluster_rbuild: no buffer offset"));
463
464         bp->b_bcount = 0;
465         bp->b_bufsize = 0;
466         bp->b_xio.xio_npages = 0;
467
468         for (boffset = doffset, i = 0; i < run; ++i, boffset += blksize) {
469                 if (i) {
470                         if ((bp->b_xio.xio_npages * PAGE_SIZE) +
471                             round_page(blksize) > maxiosize) {
472                                 break;
473                         }
474
475                         /*
476                          * Shortcut some checks and try to avoid buffers that
477                          * would block in the lock.  The same checks have to
478                          * be made again after we officially get the buffer.
479                          */
480                         tbp = getblk(vp, loffset + i * blksize, blksize,
481                                      GETBLK_SZMATCH|GETBLK_NOWAIT, 0);
482                         if (tbp == NULL)
483                                 break;
484                         for (j = 0; j < tbp->b_xio.xio_npages; j++) {
485                                 if (tbp->b_xio.xio_pages[j]->valid)
486                                         break;
487                         }
488                         if (j != tbp->b_xio.xio_npages) {
489                                 bqrelse(tbp);
490                                 break;
491                         }
492
493                         /*
494                          * Stop scanning if the buffer is fuly valid 
495                          * (marked B_CACHE), or locked (may be doing a
496                          * background write), or if the buffer is not
497                          * VMIO backed.  The clustering code can only deal
498                          * with VMIO-backed buffers.
499                          */
500                         if ((tbp->b_flags & (B_CACHE|B_LOCKED)) ||
501                             (tbp->b_flags & B_VMIO) == 0 ||
502                             (LIST_FIRST(&tbp->b_dep) != NULL &&
503                              buf_checkread(tbp))
504                         ) {
505                                 bqrelse(tbp);
506                                 break;
507                         }
508
509                         /*
510                          * The buffer must be completely invalid in order to
511                          * take part in the cluster.  If it is partially valid
512                          * then we stop.
513                          */
514                         for (j = 0;j < tbp->b_xio.xio_npages; j++) {
515                                 if (tbp->b_xio.xio_pages[j]->valid)
516                                         break;
517                         }
518                         if (j != tbp->b_xio.xio_npages) {
519                                 bqrelse(tbp);
520                                 break;
521                         }
522
523                         /*
524                          * Set a read-ahead mark as appropriate.  Always
525                          * set the read-ahead mark at (run - 1).  It is
526                          * unclear why we were also setting it at i == 1.
527                          */
528                         if (/*i == 1 ||*/ i == (run - 1))
529                                 cluster_setram(tbp);
530
531                         /*
532                          * Depress the priority of buffers not explicitly
533                          * requested.
534                          */
535                         /* tbp->b_flags |= B_AGE; */
536
537                         /*
538                          * Set the block number if it isn't set, otherwise
539                          * if it is make sure it matches the block number we
540                          * expect.
541                          */
542                         if (tbp->b_bio2.bio_offset == NOOFFSET) {
543                                 tbp->b_bio2.bio_offset = boffset;
544                         } else if (tbp->b_bio2.bio_offset != boffset) {
545                                 brelse(tbp);
546                                 break;
547                         }
548                 }
549
550                 /*
551                  * The passed-in tbp (i == 0) will already be set up for
552                  * async or sync operation.  All other tbp's acquire in
553                  * our loop are set up for async operation.
554                  */
555                 tbp->b_cmd = BUF_CMD_READ;
556                 BUF_KERNPROC(tbp);
557                 cluster_append(&bp->b_bio1, tbp);
558                 for (j = 0; j < tbp->b_xio.xio_npages; ++j) {
559                         vm_page_t m;
560
561                         m = tbp->b_xio.xio_pages[j];
562                         vm_page_busy_wait(m, FALSE, "clurpg");
563                         vm_page_io_start(m);
564                         vm_page_wakeup(m);
565                         vm_object_pip_add(m->object, 1);
566                         if ((bp->b_xio.xio_npages == 0) ||
567                                 (bp->b_xio.xio_pages[bp->b_xio.xio_npages-1] != m)) {
568                                 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
569                                 bp->b_xio.xio_npages++;
570                         }
571                         if ((m->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL)
572                                 tbp->b_xio.xio_pages[j] = bogus_page;
573                 }
574                 /*
575                  * XXX shouldn't this be += size for both, like in 
576                  * cluster_wbuild()?
577                  *
578                  * Don't inherit tbp->b_bufsize as it may be larger due to
579                  * a non-page-aligned size.  Instead just aggregate using
580                  * 'size'.
581                  */
582                 if (tbp->b_bcount != blksize)
583                     kprintf("warning: tbp->b_bcount wrong %d vs %d\n", tbp->b_bcount, blksize);
584                 if (tbp->b_bufsize != blksize)
585                     kprintf("warning: tbp->b_bufsize wrong %d vs %d\n", tbp->b_bufsize, blksize);
586                 bp->b_bcount += blksize;
587                 bp->b_bufsize += blksize;
588         }
589
590         /*
591          * Fully valid pages in the cluster are already good and do not need
592          * to be re-read from disk.  Replace the page with bogus_page
593          */
594         for (j = 0; j < bp->b_xio.xio_npages; j++) {
595                 if ((bp->b_xio.xio_pages[j]->valid & VM_PAGE_BITS_ALL) ==
596                     VM_PAGE_BITS_ALL) {
597                         bp->b_xio.xio_pages[j] = bogus_page;
598                 }
599         }
600         if (bp->b_bufsize > bp->b_kvasize) {
601                 panic("cluster_rbuild: b_bufsize(%d) > b_kvasize(%d)",
602                     bp->b_bufsize, bp->b_kvasize);
603         }
604         pmap_qenter(trunc_page((vm_offset_t) bp->b_data),
605                 (vm_page_t *)bp->b_xio.xio_pages, bp->b_xio.xio_npages);
606         BUF_KERNPROC(bp);
607         return (bp);
608 }
609
610 /*
611  * Cleanup after a clustered read or write.
612  * This is complicated by the fact that any of the buffers might have
613  * extra memory (if there were no empty buffer headers at allocbuf time)
614  * that we will need to shift around.
615  *
616  * The returned bio is &bp->b_bio1
617  */
618 void
619 cluster_callback(struct bio *bio)
620 {
621         struct buf *bp = bio->bio_buf;
622         struct buf *tbp;
623         int error = 0;
624
625         /*
626          * Must propogate errors to all the components.  A short read (EOF)
627          * is a critical error.
628          */
629         if (bp->b_flags & B_ERROR) {
630                 error = bp->b_error;
631         } else if (bp->b_bcount != bp->b_bufsize) {
632                 panic("cluster_callback: unexpected EOF on cluster %p!", bio);
633         }
634
635         pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
636         /*
637          * Move memory from the large cluster buffer into the component
638          * buffers and mark IO as done on these.  Since the memory map
639          * is the same, no actual copying is required.
640          */
641         while ((tbp = bio->bio_caller_info1.cluster_head) != NULL) {
642                 bio->bio_caller_info1.cluster_head = tbp->b_cluster_next;
643                 if (error) {
644                         tbp->b_flags |= B_ERROR | B_IODEBUG;
645                         tbp->b_error = error;
646                 } else {
647                         tbp->b_dirtyoff = tbp->b_dirtyend = 0;
648                         tbp->b_flags &= ~(B_ERROR|B_INVAL);
649                         tbp->b_flags |= B_IODEBUG;
650                         /*
651                          * XXX the bdwrite()/bqrelse() issued during
652                          * cluster building clears B_RELBUF (see bqrelse()
653                          * comment).  If direct I/O was specified, we have
654                          * to restore it here to allow the buffer and VM
655                          * to be freed.
656                          */
657                         if (tbp->b_flags & B_DIRECT)
658                                 tbp->b_flags |= B_RELBUF;
659                 }
660                 biodone(&tbp->b_bio1);
661         }
662         relpbuf(bp, &cluster_pbuf_freecnt);
663 }
664
665 /*
666  *      cluster_wbuild_wb:
667  *
668  *      Implement modified write build for cluster.
669  *
670  *              write_behind = 0        write behind disabled
671  *              write_behind = 1        write behind normal (default)
672  *              write_behind = 2        write behind backed-off
673  */
674
675 static __inline int
676 cluster_wbuild_wb(struct vnode *vp, int blksize, off_t start_loffset, int len)
677 {
678         int r = 0;
679
680         switch(write_behind) {
681         case 2:
682                 if (start_loffset < len)
683                         break;
684                 start_loffset -= len;
685                 /* fall through */
686         case 1:
687                 r = cluster_wbuild(vp, blksize, start_loffset, len);
688                 /* fall through */
689         default:
690                 /* fall through */
691                 break;
692         }
693         return(r);
694 }
695
696 /*
697  * Do clustered write for FFS.
698  *
699  * Three cases:
700  *      1. Write is not sequential (write asynchronously)
701  *      Write is sequential:
702  *      2.      beginning of cluster - begin cluster
703  *      3.      middle of a cluster - add to cluster
704  *      4.      end of a cluster - asynchronously write cluster
705  */
706 void
707 cluster_write(struct buf *bp, off_t filesize, int blksize, int seqcount)
708 {
709         struct vnode *vp;
710         off_t loffset;
711         int maxclen, cursize;
712         int async;
713
714         vp = bp->b_vp;
715         if (vp->v_type == VREG)
716                 async = vp->v_mount->mnt_flag & MNT_ASYNC;
717         else
718                 async = 0;
719         loffset = bp->b_loffset;
720         KASSERT(bp->b_loffset != NOOFFSET, 
721                 ("cluster_write: no buffer offset"));
722
723         /* Initialize vnode to beginning of file. */
724         if (loffset == 0)
725                 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
726
727         if (vp->v_clen == 0 || loffset != vp->v_lastw + blksize ||
728             bp->b_bio2.bio_offset == NOOFFSET ||
729             (bp->b_bio2.bio_offset != vp->v_lasta + blksize)) {
730                 maxclen = vmaxiosize(vp);
731                 if (vp->v_clen != 0) {
732                         /*
733                          * Next block is not sequential.
734                          *
735                          * If we are not writing at end of file, the process
736                          * seeked to another point in the file since its last
737                          * write, or we have reached our maximum cluster size,
738                          * then push the previous cluster. Otherwise try
739                          * reallocating to make it sequential.
740                          *
741                          * Change to algorithm: only push previous cluster if
742                          * it was sequential from the point of view of the
743                          * seqcount heuristic, otherwise leave the buffer 
744                          * intact so we can potentially optimize the I/O
745                          * later on in the buf_daemon or update daemon
746                          * flush.
747                          */
748                         cursize = vp->v_lastw - vp->v_cstart + blksize;
749                         if (bp->b_loffset + blksize != filesize ||
750                             loffset != vp->v_lastw + blksize || vp->v_clen <= cursize) {
751                                 if (!async && seqcount > 0) {
752                                         cluster_wbuild_wb(vp, blksize,
753                                                 vp->v_cstart, cursize);
754                                 }
755                         } else {
756                                 struct buf **bpp, **endbp;
757                                 struct cluster_save *buflist;
758
759                                 buflist = cluster_collectbufs(vp, bp, blksize);
760                                 endbp = &buflist->bs_children
761                                     [buflist->bs_nchildren - 1];
762                                 if (VOP_REALLOCBLKS(vp, buflist)) {
763                                         /*
764                                          * Failed, push the previous cluster
765                                          * if *really* writing sequentially
766                                          * in the logical file (seqcount > 1),
767                                          * otherwise delay it in the hopes that
768                                          * the low level disk driver can
769                                          * optimize the write ordering.
770                                          */
771                                         for (bpp = buflist->bs_children;
772                                              bpp < endbp; bpp++)
773                                                 brelse(*bpp);
774                                         kfree(buflist, M_SEGMENT);
775                                         if (seqcount > 1) {
776                                                 cluster_wbuild_wb(vp, 
777                                                     blksize, vp->v_cstart, 
778                                                     cursize);
779                                         }
780                                 } else {
781                                         /*
782                                          * Succeeded, keep building cluster.
783                                          */
784                                         for (bpp = buflist->bs_children;
785                                              bpp <= endbp; bpp++)
786                                                 bdwrite(*bpp);
787                                         kfree(buflist, M_SEGMENT);
788                                         vp->v_lastw = loffset;
789                                         vp->v_lasta = bp->b_bio2.bio_offset;
790                                         return;
791                                 }
792                         }
793                 }
794                 /*
795                  * Consider beginning a cluster. If at end of file, make
796                  * cluster as large as possible, otherwise find size of
797                  * existing cluster.
798                  */
799                 if ((vp->v_type == VREG) &&
800                     bp->b_loffset + blksize != filesize &&
801                     (bp->b_bio2.bio_offset == NOOFFSET) &&
802                     (VOP_BMAP(vp, loffset, &bp->b_bio2.bio_offset, &maxclen, NULL, BUF_CMD_WRITE) ||
803                      bp->b_bio2.bio_offset == NOOFFSET)) {
804                         bawrite(bp);
805                         vp->v_clen = 0;
806                         vp->v_lasta = bp->b_bio2.bio_offset;
807                         vp->v_cstart = loffset + blksize;
808                         vp->v_lastw = loffset;
809                         return;
810                 }
811                 if (maxclen > blksize)
812                         vp->v_clen = maxclen - blksize;
813                 else
814                         vp->v_clen = 0;
815                 if (!async && vp->v_clen == 0) { /* I/O not contiguous */
816                         vp->v_cstart = loffset + blksize;
817                         bawrite(bp);
818                 } else {        /* Wait for rest of cluster */
819                         vp->v_cstart = loffset;
820                         bdwrite(bp);
821                 }
822         } else if (loffset == vp->v_cstart + vp->v_clen) {
823                 /*
824                  * At end of cluster, write it out if seqcount tells us we
825                  * are operating sequentially, otherwise let the buf or
826                  * update daemon handle it.
827                  */
828                 bdwrite(bp);
829                 if (seqcount > 1)
830                         cluster_wbuild_wb(vp, blksize, vp->v_cstart,
831                                           vp->v_clen + blksize);
832                 vp->v_clen = 0;
833                 vp->v_cstart = loffset + blksize;
834         } else if (vm_page_count_severe()) {
835                 /*
836                  * We are low on memory, get it going NOW
837                  */
838                 bawrite(bp);
839         } else {
840                 /*
841                  * In the middle of a cluster, so just delay the I/O for now.
842                  */
843                 bdwrite(bp);
844         }
845         vp->v_lastw = loffset;
846         vp->v_lasta = bp->b_bio2.bio_offset;
847 }
848
849
850 /*
851  * This is an awful lot like cluster_rbuild...wish they could be combined.
852  * The last lbn argument is the current block on which I/O is being
853  * performed.  Check to see that it doesn't fall in the middle of
854  * the current block (if last_bp == NULL).
855  */
856 int
857 cluster_wbuild(struct vnode *vp, int blksize, off_t start_loffset, int bytes)
858 {
859         struct buf *bp, *tbp;
860         int i, j;
861         int totalwritten = 0;
862         int maxiosize = vmaxiosize(vp);
863
864         while (bytes > 0) {
865                 /*
866                  * If the buffer is not delayed-write (i.e. dirty), or it 
867                  * is delayed-write but either locked or inval, it cannot 
868                  * partake in the clustered write.
869                  */
870                 tbp = findblk(vp, start_loffset, FINDBLK_NBLOCK);
871                 if (tbp == NULL ||
872                     (tbp->b_flags & (B_LOCKED | B_INVAL | B_DELWRI)) != B_DELWRI ||
873                     (LIST_FIRST(&tbp->b_dep) && buf_checkwrite(tbp))) {
874                         if (tbp)
875                                 BUF_UNLOCK(tbp);
876                         start_loffset += blksize;
877                         bytes -= blksize;
878                         continue;
879                 }
880                 bremfree(tbp);
881                 KKASSERT(tbp->b_cmd == BUF_CMD_DONE);
882
883                 /*
884                  * Extra memory in the buffer, punt on this buffer.
885                  * XXX we could handle this in most cases, but we would
886                  * have to push the extra memory down to after our max
887                  * possible cluster size and then potentially pull it back
888                  * up if the cluster was terminated prematurely--too much
889                  * hassle.
890                  */
891                 if (((tbp->b_flags & (B_CLUSTEROK|B_MALLOC)) != B_CLUSTEROK) ||
892                     (tbp->b_bcount != tbp->b_bufsize) ||
893                     (tbp->b_bcount != blksize) ||
894                     (bytes == blksize) ||
895                     ((bp = getpbuf_kva(&cluster_pbuf_freecnt)) == NULL)) {
896                         totalwritten += tbp->b_bufsize;
897                         bawrite(tbp);
898                         start_loffset += blksize;
899                         bytes -= blksize;
900                         continue;
901                 }
902
903                 /*
904                  * Set up the pbuf.  Track our append point with b_bcount
905                  * and b_bufsize.  b_bufsize is not used by the device but
906                  * our caller uses it to loop clusters and we use it to
907                  * detect a premature EOF on the block device.
908                  */
909                 bp->b_bcount = 0;
910                 bp->b_bufsize = 0;
911                 bp->b_xio.xio_npages = 0;
912                 bp->b_loffset = tbp->b_loffset;
913                 bp->b_bio2.bio_offset = tbp->b_bio2.bio_offset;
914
915                 /*
916                  * We are synthesizing a buffer out of vm_page_t's, but
917                  * if the block size is not page aligned then the starting
918                  * address may not be either.  Inherit the b_data offset
919                  * from the original buffer.
920                  */
921                 bp->b_data = (char *)((vm_offset_t)bp->b_data |
922                     ((vm_offset_t)tbp->b_data & PAGE_MASK));
923                 bp->b_flags &= ~B_ERROR;
924                 bp->b_flags |= B_CLUSTER | B_BNOCLIP |
925                         (tbp->b_flags & (B_VMIO | B_NEEDCOMMIT));
926                 bp->b_bio1.bio_caller_info1.cluster_head = NULL;
927                 bp->b_bio1.bio_caller_info2.cluster_tail = NULL;
928
929                 /*
930                  * From this location in the file, scan forward to see
931                  * if there are buffers with adjacent data that need to
932                  * be written as well.
933                  */
934                 for (i = 0; i < bytes; (i += blksize), (start_loffset += blksize)) {
935                         if (i != 0) { /* If not the first buffer */
936                                 tbp = findblk(vp, start_loffset,
937                                               FINDBLK_NBLOCK);
938                                 /*
939                                  * Buffer not found or could not be locked
940                                  * non-blocking.
941                                  */
942                                 if (tbp == NULL)
943                                         break;
944
945                                 /*
946                                  * If it IS in core, but has different
947                                  * characteristics, then don't cluster
948                                  * with it.
949                                  */
950                                 if ((tbp->b_flags & (B_VMIO | B_CLUSTEROK |
951                                      B_INVAL | B_DELWRI | B_NEEDCOMMIT))
952                                     != (B_DELWRI | B_CLUSTEROK |
953                                      (bp->b_flags & (B_VMIO | B_NEEDCOMMIT))) ||
954                                     (tbp->b_flags & B_LOCKED) ||
955                                     (LIST_FIRST(&tbp->b_dep) &&
956                                      buf_checkwrite(tbp))
957                                 ) {
958                                         BUF_UNLOCK(tbp);
959                                         break;
960                                 }
961
962                                 /*
963                                  * Check that the combined cluster
964                                  * would make sense with regard to pages
965                                  * and would not be too large
966                                  */
967                                 if ((tbp->b_bcount != blksize) ||
968                                   ((bp->b_bio2.bio_offset + i) !=
969                                     tbp->b_bio2.bio_offset) ||
970                                   ((tbp->b_xio.xio_npages + bp->b_xio.xio_npages) >
971                                     (maxiosize / PAGE_SIZE))) {
972                                         BUF_UNLOCK(tbp);
973                                         break;
974                                 }
975                                 /*
976                                  * Ok, it's passed all the tests,
977                                  * so remove it from the free list
978                                  * and mark it busy. We will use it.
979                                  */
980                                 bremfree(tbp);
981                                 KKASSERT(tbp->b_cmd == BUF_CMD_DONE);
982                         } /* end of code for non-first buffers only */
983
984                         /*
985                          * If the IO is via the VM then we do some
986                          * special VM hackery (yuck).  Since the buffer's
987                          * block size may not be page-aligned it is possible
988                          * for a page to be shared between two buffers.  We
989                          * have to get rid of the duplication when building
990                          * the cluster.
991                          */
992                         if (tbp->b_flags & B_VMIO) {
993                                 vm_page_t m;
994
995                                 if (i != 0) { /* if not first buffer */
996                                         for (j = 0; j < tbp->b_xio.xio_npages; ++j) {
997                                                 m = tbp->b_xio.xio_pages[j];
998                                                 if (m->flags & PG_BUSY) {
999                                                         bqrelse(tbp);
1000                                                         goto finishcluster;
1001                                                 }
1002                                         }
1003                                 }
1004                                         
1005                                 for (j = 0; j < tbp->b_xio.xio_npages; ++j) {
1006                                         m = tbp->b_xio.xio_pages[j];
1007                                         vm_page_busy_wait(m, FALSE, "clurpg");
1008                                         vm_page_io_start(m);
1009                                         vm_page_wakeup(m);
1010                                         vm_object_pip_add(m->object, 1);
1011                                         if ((bp->b_xio.xio_npages == 0) ||
1012                                           (bp->b_xio.xio_pages[bp->b_xio.xio_npages - 1] != m)) {
1013                                                 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
1014                                                 bp->b_xio.xio_npages++;
1015                                         }
1016                                 }
1017                         }
1018                         bp->b_bcount += blksize;
1019                         bp->b_bufsize += blksize;
1020
1021                         bundirty(tbp);
1022                         tbp->b_flags &= ~B_ERROR;
1023                         tbp->b_cmd = BUF_CMD_WRITE;
1024                         BUF_KERNPROC(tbp);
1025                         cluster_append(&bp->b_bio1, tbp);
1026
1027                         /*
1028                          * check for latent dependencies to be handled 
1029                          */
1030                         if (LIST_FIRST(&tbp->b_dep) != NULL)
1031                                 buf_start(tbp);
1032                 }
1033         finishcluster:
1034                 pmap_qenter(trunc_page((vm_offset_t) bp->b_data),
1035                         (vm_page_t *) bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1036                 if (bp->b_bufsize > bp->b_kvasize) {
1037                         panic(
1038                             "cluster_wbuild: b_bufsize(%d) > b_kvasize(%d)\n",
1039                             bp->b_bufsize, bp->b_kvasize);
1040                 }
1041                 totalwritten += bp->b_bufsize;
1042                 bp->b_dirtyoff = 0;
1043                 bp->b_dirtyend = bp->b_bufsize;
1044                 bp->b_bio1.bio_done = cluster_callback;
1045                 bp->b_cmd = BUF_CMD_WRITE;
1046
1047                 vfs_busy_pages(vp, bp);
1048                 bsetrunningbufspace(bp, bp->b_bufsize);
1049                 BUF_KERNPROC(bp);
1050                 vn_strategy(vp, &bp->b_bio1);
1051
1052                 bytes -= i;
1053         }
1054         return totalwritten;
1055 }
1056
1057 /*
1058  * Collect together all the buffers in a cluster.
1059  * Plus add one additional buffer.
1060  */
1061 static struct cluster_save *
1062 cluster_collectbufs(struct vnode *vp, struct buf *last_bp, int blksize)
1063 {
1064         struct cluster_save *buflist;
1065         struct buf *bp;
1066         off_t loffset;
1067         int i, len;
1068
1069         len = (int)(vp->v_lastw - vp->v_cstart + blksize) / blksize;
1070         buflist = kmalloc(sizeof(struct buf *) * (len + 1) + sizeof(*buflist),
1071                          M_SEGMENT, M_WAITOK);
1072         buflist->bs_nchildren = 0;
1073         buflist->bs_children = (struct buf **) (buflist + 1);
1074         for (loffset = vp->v_cstart, i = 0; i < len; (loffset += blksize), i++) {
1075                 (void) bread(vp, loffset, last_bp->b_bcount, &bp);
1076                 buflist->bs_children[i] = bp;
1077                 if (bp->b_bio2.bio_offset == NOOFFSET) {
1078                         VOP_BMAP(bp->b_vp, bp->b_loffset,
1079                                  &bp->b_bio2.bio_offset,
1080                                  NULL, NULL, BUF_CMD_WRITE);
1081                 }
1082         }
1083         buflist->bs_children[i] = bp = last_bp;
1084         if (bp->b_bio2.bio_offset == NOOFFSET) {
1085                 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
1086                          NULL, NULL, BUF_CMD_WRITE);
1087         }
1088         buflist->bs_nchildren = i + 1;
1089         return (buflist);
1090 }
1091
1092 void
1093 cluster_append(struct bio *bio, struct buf *tbp)
1094 {
1095         tbp->b_cluster_next = NULL;
1096         if (bio->bio_caller_info1.cluster_head == NULL) {
1097                 bio->bio_caller_info1.cluster_head = tbp;
1098                 bio->bio_caller_info2.cluster_tail = tbp;
1099         } else {
1100                 bio->bio_caller_info2.cluster_tail->b_cluster_next = tbp;
1101                 bio->bio_caller_info2.cluster_tail = tbp;
1102         }
1103 }
1104
1105 static
1106 void
1107 cluster_setram (struct buf *bp)
1108 {
1109         bp->b_flags |= B_RAM;
1110         if (bp->b_xio.xio_npages)
1111                 vm_page_flag_set(bp->b_xio.xio_pages[0], PG_RAM);
1112 }