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