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