Remove the code which disables port status change interrupts for 1 second
[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.36 2008/05/18 05:54:25 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 = vmaxiosize(vp) / 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         int maxiosize = vmaxiosize(vp);
320
321         /*
322          * This is a filesystem sanity check.  For regular files h
323          * cluster_write() currently uses f_iosize, make sure cluster_read()
324          * uses the same block size.
325          *
326          * NOTE: The vp can be a block device
327          */
328         if (vp->v_type == VREG) {
329                 KASSERT(size == vp->v_mount->mnt_stat.f_iosize,
330                     ("cluster_rbuild: size %d != filesize %ld\n",
331                     size, vp->v_mount->mnt_stat.f_iosize));
332         }
333
334         /*
335          * avoid a division
336          */
337         while (loffset + run * size > filesize) {
338                 --run;
339         }
340
341         tbp = fbp;
342         tbp->b_bio2.bio_offset = doffset;
343         if((tbp->b_flags & B_MALLOC) ||
344             ((tbp->b_flags & B_VMIO) == 0) || (run <= 1)) {
345                 return tbp;
346         }
347
348         bp = trypbuf(&cluster_pbuf_freecnt);
349         if (bp == NULL)
350                 return tbp;
351
352         /*
353          * We are synthesizing a buffer out of vm_page_t's, but
354          * if the block size is not page aligned then the starting
355          * address may not be either.  Inherit the b_data offset
356          * from the original buffer.
357          */
358         bp->b_data = (char *)((vm_offset_t)bp->b_data |
359             ((vm_offset_t)tbp->b_data & PAGE_MASK));
360         bp->b_flags |= B_ASYNC | B_CLUSTER | B_VMIO;
361         bp->b_cmd = BUF_CMD_READ;
362         bp->b_bio1.bio_done = cluster_callback;
363         bp->b_bio1.bio_caller_info1.cluster_head = NULL;
364         bp->b_bio1.bio_caller_info2.cluster_tail = NULL;
365         bp->b_loffset = loffset;
366         bp->b_bio2.bio_offset = NOOFFSET;
367         KASSERT(bp->b_loffset != NOOFFSET,
368                 ("cluster_rbuild: no buffer offset"));
369
370         bp->b_bcount = 0;
371         bp->b_bufsize = 0;
372         bp->b_xio.xio_npages = 0;
373
374         for (boffset = doffset, i = 0; i < run; ++i, boffset += size) {
375                 if (i) {
376                         if ((bp->b_xio.xio_npages * PAGE_SIZE) +
377                             round_page(size) > maxiosize) {
378                                 break;
379                         }
380
381                         /*
382                          * Shortcut some checks and try to avoid buffers that
383                          * would block in the lock.  The same checks have to
384                          * be made again after we officially get the buffer.
385                          */
386                         if ((tbp = findblk(vp, loffset + i * size)) != NULL) {
387                                 if (BUF_LOCK(tbp, LK_EXCLUSIVE | LK_NOWAIT))
388                                         break;
389                                 BUF_UNLOCK(tbp);
390
391                                 for (j = 0; j < tbp->b_xio.xio_npages; j++) {
392                                         if (tbp->b_xio.xio_pages[j]->valid)
393                                                 break;
394                                 }
395                                 
396                                 if (j != tbp->b_xio.xio_npages)
397                                         break;
398         
399                                 if (tbp->b_bcount != size)
400                                         break;
401                         }
402
403                         tbp = getblk(vp, loffset + i * size, size, 0, 0);
404
405                         /*
406                          * Stop scanning if the buffer is fuly valid 
407                          * (marked B_CACHE), or locked (may be doing a
408                          * background write), or if the buffer is not
409                          * VMIO backed.  The clustering code can only deal
410                          * with VMIO-backed buffers.
411                          */
412                         if ((tbp->b_flags & (B_CACHE|B_LOCKED)) ||
413                             (tbp->b_flags & B_VMIO) == 0 ||
414                             (LIST_FIRST(&tbp->b_dep) != NULL &&
415                              buf_checkread(tbp))
416                         ) {
417                                 bqrelse(tbp);
418                                 break;
419                         }
420
421                         /*
422                          * The buffer must be completely invalid in order to
423                          * take part in the cluster.  If it is partially valid
424                          * then we stop.
425                          */
426                         for (j = 0;j < tbp->b_xio.xio_npages; j++) {
427                                 if (tbp->b_xio.xio_pages[j]->valid)
428                                         break;
429                         }
430                         if (j != tbp->b_xio.xio_npages) {
431                                 bqrelse(tbp);
432                                 break;
433                         }
434
435                         /*
436                          * Set a read-ahead mark as appropriate
437                          */
438                         if (i == 1 || i == (run - 1))
439                                 tbp->b_flags |= B_RAM;
440
441                         /*
442                          * Set the block number if it isn't set, otherwise
443                          * if it is make sure it matches the block number we
444                          * expect.
445                          */
446                         if (tbp->b_bio2.bio_offset == NOOFFSET) {
447                                 tbp->b_bio2.bio_offset = boffset;
448                         } else if (tbp->b_bio2.bio_offset != boffset) {
449                                 brelse(tbp);
450                                 break;
451                         }
452                 }
453                 /*
454                  * The first buffer is setup async if doasync is specified.
455                  * All other buffers in the cluster are setup async.  This
456                  * way the caller can decide how to deal with the requested
457                  * buffer.
458                  */
459                 if (i || doasync)
460                         tbp->b_flags |= B_ASYNC;
461                 tbp->b_cmd = BUF_CMD_READ;
462                 BUF_KERNPROC(tbp);
463                 cluster_append(&bp->b_bio1, tbp);
464                 for (j = 0; j < tbp->b_xio.xio_npages; ++j) {
465                         vm_page_t m;
466                         m = tbp->b_xio.xio_pages[j];
467                         vm_page_io_start(m);
468                         vm_object_pip_add(m->object, 1);
469                         if ((bp->b_xio.xio_npages == 0) ||
470                                 (bp->b_xio.xio_pages[bp->b_xio.xio_npages-1] != m)) {
471                                 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
472                                 bp->b_xio.xio_npages++;
473                         }
474                         if ((m->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL)
475                                 tbp->b_xio.xio_pages[j] = bogus_page;
476                 }
477                 /*
478                  * XXX shouldn't this be += size for both, like in 
479                  * cluster_wbuild()?
480                  *
481                  * Don't inherit tbp->b_bufsize as it may be larger due to
482                  * a non-page-aligned size.  Instead just aggregate using
483                  * 'size'.
484                  */
485                 if (tbp->b_bcount != size)
486                     kprintf("warning: tbp->b_bcount wrong %d vs %d\n", tbp->b_bcount, size);
487                 if (tbp->b_bufsize != size)
488                     kprintf("warning: tbp->b_bufsize wrong %d vs %d\n", tbp->b_bufsize, size);
489                 bp->b_bcount += size;
490                 bp->b_bufsize += size;
491         }
492
493         /*
494          * Fully valid pages in the cluster are already good and do not need
495          * to be re-read from disk.  Replace the page with bogus_page
496          */
497         for (j = 0; j < bp->b_xio.xio_npages; j++) {
498                 if ((bp->b_xio.xio_pages[j]->valid & VM_PAGE_BITS_ALL) ==
499                     VM_PAGE_BITS_ALL) {
500                         bp->b_xio.xio_pages[j] = bogus_page;
501                 }
502         }
503         if (bp->b_bufsize > bp->b_kvasize) {
504                 panic("cluster_rbuild: b_bufsize(%d) > b_kvasize(%d)",
505                     bp->b_bufsize, bp->b_kvasize);
506         }
507
508         pmap_qenter(trunc_page((vm_offset_t) bp->b_data),
509                 (vm_page_t *)bp->b_xio.xio_pages, bp->b_xio.xio_npages);
510         return (bp);
511 }
512
513 /*
514  * Cleanup after a clustered read or write.
515  * This is complicated by the fact that any of the buffers might have
516  * extra memory (if there were no empty buffer headers at allocbuf time)
517  * that we will need to shift around.
518  *
519  * The returned bio is &bp->b_bio1
520  */
521 void
522 cluster_callback(struct bio *bio)
523 {
524         struct buf *bp = bio->bio_buf;
525         struct buf *tbp;
526         int error = 0;
527
528         /*
529          * Must propogate errors to all the components.  A short read (EOF)
530          * is a critical error.
531          */
532         if (bp->b_flags & B_ERROR) {
533                 error = bp->b_error;
534         } else if (bp->b_bcount != bp->b_bufsize) {
535                 panic("cluster_callback: unexpected EOF on cluster %p!", bio);
536         }
537
538         pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
539         /*
540          * Move memory from the large cluster buffer into the component
541          * buffers and mark IO as done on these.  Since the memory map
542          * is the same, no actual copying is required.
543          */
544         while ((tbp = bio->bio_caller_info1.cluster_head) != NULL) {
545                 bio->bio_caller_info1.cluster_head = tbp->b_cluster_next;
546                 if (error) {
547                         tbp->b_flags |= B_ERROR;
548                         tbp->b_error = error;
549                 } else {
550                         tbp->b_dirtyoff = tbp->b_dirtyend = 0;
551                         tbp->b_flags &= ~(B_ERROR|B_INVAL);
552                         /*
553                          * XXX the bdwrite()/bqrelse() issued during
554                          * cluster building clears B_RELBUF (see bqrelse()
555                          * comment).  If direct I/O was specified, we have
556                          * to restore it here to allow the buffer and VM
557                          * to be freed.
558                          */
559                         if (tbp->b_flags & B_DIRECT)
560                                 tbp->b_flags |= B_RELBUF;
561                 }
562                 biodone(&tbp->b_bio1);
563         }
564         relpbuf(bp, &cluster_pbuf_freecnt);
565 }
566
567 /*
568  *      cluster_wbuild_wb:
569  *
570  *      Implement modified write build for cluster.
571  *
572  *              write_behind = 0        write behind disabled
573  *              write_behind = 1        write behind normal (default)
574  *              write_behind = 2        write behind backed-off
575  */
576
577 static __inline int
578 cluster_wbuild_wb(struct vnode *vp, int size, off_t start_loffset, int len)
579 {
580         int r = 0;
581
582         switch(write_behind) {
583         case 2:
584                 if (start_loffset < len)
585                         break;
586                 start_loffset -= len;
587                 /* fall through */
588         case 1:
589                 r = cluster_wbuild(vp, size, start_loffset, len);
590                 /* fall through */
591         default:
592                 /* fall through */
593                 break;
594         }
595         return(r);
596 }
597
598 /*
599  * Do clustered write for FFS.
600  *
601  * Three cases:
602  *      1. Write is not sequential (write asynchronously)
603  *      Write is sequential:
604  *      2.      beginning of cluster - begin cluster
605  *      3.      middle of a cluster - add to cluster
606  *      4.      end of a cluster - asynchronously write cluster
607  */
608 void
609 cluster_write(struct buf *bp, off_t filesize, int seqcount)
610 {
611         struct vnode *vp;
612         off_t loffset;
613         int maxclen, cursize;
614         int lblocksize;
615         int async;
616
617         vp = bp->b_vp;
618         if (vp->v_type == VREG) {
619                 async = vp->v_mount->mnt_flag & MNT_ASYNC;
620                 lblocksize = vp->v_mount->mnt_stat.f_iosize;
621         } else {
622                 async = 0;
623                 lblocksize = bp->b_bufsize;
624         }
625         loffset = bp->b_loffset;
626         KASSERT(bp->b_loffset != NOOFFSET, 
627                 ("cluster_write: no buffer offset"));
628
629         /* Initialize vnode to beginning of file. */
630         if (loffset == 0)
631                 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
632
633         if (vp->v_clen == 0 || loffset != vp->v_lastw + lblocksize ||
634             bp->b_bio2.bio_offset == NOOFFSET ||
635             (bp->b_bio2.bio_offset != vp->v_lasta + lblocksize)) {
636                 maxclen = vmaxiosize(vp);
637                 if (vp->v_clen != 0) {
638                         /*
639                          * Next block is not sequential.
640                          *
641                          * If we are not writing at end of file, the process
642                          * seeked to another point in the file since its last
643                          * write, or we have reached our maximum cluster size,
644                          * then push the previous cluster. Otherwise try
645                          * reallocating to make it sequential.
646                          *
647                          * Change to algorithm: only push previous cluster if
648                          * it was sequential from the point of view of the
649                          * seqcount heuristic, otherwise leave the buffer 
650                          * intact so we can potentially optimize the I/O
651                          * later on in the buf_daemon or update daemon
652                          * flush.
653                          */
654                         cursize = vp->v_lastw - vp->v_cstart + lblocksize;
655                         if (bp->b_loffset + lblocksize != filesize ||
656                             loffset != vp->v_lastw + lblocksize || vp->v_clen <= cursize) {
657                                 if (!async && seqcount > 0) {
658                                         cluster_wbuild_wb(vp, lblocksize,
659                                                 vp->v_cstart, cursize);
660                                 }
661                         } else {
662                                 struct buf **bpp, **endbp;
663                                 struct cluster_save *buflist;
664
665                                 buflist = cluster_collectbufs(vp, bp,
666                                                               lblocksize);
667                                 endbp = &buflist->bs_children
668                                     [buflist->bs_nchildren - 1];
669                                 if (VOP_REALLOCBLKS(vp, buflist)) {
670                                         /*
671                                          * Failed, push the previous cluster
672                                          * if *really* writing sequentially
673                                          * in the logical file (seqcount > 1),
674                                          * otherwise delay it in the hopes that
675                                          * the low level disk driver can
676                                          * optimize the write ordering.
677                                          */
678                                         for (bpp = buflist->bs_children;
679                                              bpp < endbp; bpp++)
680                                                 brelse(*bpp);
681                                         kfree(buflist, M_SEGMENT);
682                                         if (seqcount > 1) {
683                                                 cluster_wbuild_wb(vp, 
684                                                     lblocksize, vp->v_cstart, 
685                                                     cursize);
686                                         }
687                                 } else {
688                                         /*
689                                          * Succeeded, keep building cluster.
690                                          */
691                                         for (bpp = buflist->bs_children;
692                                              bpp <= endbp; bpp++)
693                                                 bdwrite(*bpp);
694                                         kfree(buflist, M_SEGMENT);
695                                         vp->v_lastw = loffset;
696                                         vp->v_lasta = bp->b_bio2.bio_offset;
697                                         return;
698                                 }
699                         }
700                 }
701                 /*
702                  * Consider beginning a cluster. If at end of file, make
703                  * cluster as large as possible, otherwise find size of
704                  * existing cluster.
705                  */
706                 if ((vp->v_type == VREG) &&
707                     bp->b_loffset + lblocksize != filesize &&
708                     (bp->b_bio2.bio_offset == NOOFFSET) &&
709                     (VOP_BMAP(vp, loffset, &bp->b_bio2.bio_offset, &maxclen, NULL) ||
710                      bp->b_bio2.bio_offset == NOOFFSET)) {
711                         bawrite(bp);
712                         vp->v_clen = 0;
713                         vp->v_lasta = bp->b_bio2.bio_offset;
714                         vp->v_cstart = loffset + lblocksize;
715                         vp->v_lastw = loffset;
716                         return;
717                 }
718                 if (maxclen > lblocksize)
719                         vp->v_clen = maxclen - lblocksize;
720                 else
721                         vp->v_clen = 0;
722                 if (!async && vp->v_clen == 0) { /* I/O not contiguous */
723                         vp->v_cstart = loffset + lblocksize;
724                         bawrite(bp);
725                 } else {        /* Wait for rest of cluster */
726                         vp->v_cstart = loffset;
727                         bdwrite(bp);
728                 }
729         } else if (loffset == vp->v_cstart + vp->v_clen) {
730                 /*
731                  * At end of cluster, write it out if seqcount tells us we
732                  * are operating sequentially, otherwise let the buf or
733                  * update daemon handle it.
734                  */
735                 bdwrite(bp);
736                 if (seqcount > 1)
737                         cluster_wbuild_wb(vp, lblocksize, vp->v_cstart,
738                                           vp->v_clen + lblocksize);
739                 vp->v_clen = 0;
740                 vp->v_cstart = loffset + lblocksize;
741         } else if (vm_page_count_severe()) {
742                 /*
743                  * We are low on memory, get it going NOW
744                  */
745                 bawrite(bp);
746         } else {
747                 /*
748                  * In the middle of a cluster, so just delay the I/O for now.
749                  */
750                 bdwrite(bp);
751         }
752         vp->v_lastw = loffset;
753         vp->v_lasta = bp->b_bio2.bio_offset;
754 }
755
756
757 /*
758  * This is an awful lot like cluster_rbuild...wish they could be combined.
759  * The last lbn argument is the current block on which I/O is being
760  * performed.  Check to see that it doesn't fall in the middle of
761  * the current block (if last_bp == NULL).
762  */
763 int
764 cluster_wbuild(struct vnode *vp, int size, off_t start_loffset, int bytes)
765 {
766         struct buf *bp, *tbp;
767         int i, j;
768         int totalwritten = 0;
769         int maxiosize = vmaxiosize(vp);
770
771         while (bytes > 0) {
772                 crit_enter();
773                 /*
774                  * If the buffer is not delayed-write (i.e. dirty), or it 
775                  * is delayed-write but either locked or inval, it cannot 
776                  * partake in the clustered write.
777                  */
778                 if (((tbp = findblk(vp, start_loffset)) == NULL) ||
779                   ((tbp->b_flags & (B_LOCKED | B_INVAL | B_DELWRI)) != B_DELWRI) ||
780                   (LIST_FIRST(&tbp->b_dep) != NULL && buf_checkwrite(tbp)) ||
781                   BUF_LOCK(tbp, LK_EXCLUSIVE | LK_NOWAIT)) {
782                         start_loffset += size;
783                         bytes -= size;
784                         crit_exit();
785                         continue;
786                 }
787                 bremfree(tbp);
788                 KKASSERT(tbp->b_cmd == BUF_CMD_DONE);
789                 crit_exit();
790
791                 /*
792                  * Extra memory in the buffer, punt on this buffer.
793                  * XXX we could handle this in most cases, but we would
794                  * have to push the extra memory down to after our max
795                  * possible cluster size and then potentially pull it back
796                  * up if the cluster was terminated prematurely--too much
797                  * hassle.
798                  */
799                 if (((tbp->b_flags & (B_CLUSTEROK|B_MALLOC)) != B_CLUSTEROK) ||
800                   (tbp->b_bcount != tbp->b_bufsize) ||
801                   (tbp->b_bcount != size) ||
802                   (bytes == size) ||
803                   ((bp = getpbuf(&cluster_pbuf_freecnt)) == NULL)) {
804                         totalwritten += tbp->b_bufsize;
805                         bawrite(tbp);
806                         start_loffset += size;
807                         bytes -= size;
808                         continue;
809                 }
810
811                 /*
812                  * Set up the pbuf.  Track our append point with b_bcount
813                  * and b_bufsize.  b_bufsize is not used by the device but
814                  * our caller uses it to loop clusters and we use it to
815                  * detect a premature EOF on the block device.
816                  */
817                 bp->b_bcount = 0;
818                 bp->b_bufsize = 0;
819                 bp->b_xio.xio_npages = 0;
820                 bp->b_loffset = tbp->b_loffset;
821                 bp->b_bio2.bio_offset = tbp->b_bio2.bio_offset;
822
823                 /*
824                  * We are synthesizing a buffer out of vm_page_t's, but
825                  * if the block size is not page aligned then the starting
826                  * address may not be either.  Inherit the b_data offset
827                  * from the original buffer.
828                  */
829                 bp->b_data = (char *)((vm_offset_t)bp->b_data |
830                     ((vm_offset_t)tbp->b_data & PAGE_MASK));
831                 bp->b_flags &= ~B_ERROR;
832                 bp->b_flags |= B_CLUSTER | B_BNOCLIP |
833                         (tbp->b_flags & (B_VMIO | B_NEEDCOMMIT));
834                 bp->b_bio1.bio_done = cluster_callback;
835                 bp->b_bio1.bio_caller_info1.cluster_head = NULL;
836                 bp->b_bio1.bio_caller_info2.cluster_tail = NULL;
837                 /*
838                  * From this location in the file, scan forward to see
839                  * if there are buffers with adjacent data that need to
840                  * be written as well.
841                  */
842                 for (i = 0; i < bytes; (i += size), (start_loffset += size)) {
843                         if (i != 0) { /* If not the first buffer */
844                                 crit_enter();
845                                 /*
846                                  * If the adjacent data is not even in core it
847                                  * can't need to be written.
848                                  */
849                                 if ((tbp = findblk(vp, start_loffset)) == NULL) {
850                                         crit_exit();
851                                         break;
852                                 }
853
854                                 /*
855                                  * If it IS in core, but has different
856                                  * characteristics, or is locked (which
857                                  * means it could be undergoing a background
858                                  * I/O or be in a weird state), then don't
859                                  * cluster 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) != NULL && buf_checkwrite(tbp)) ||
867                                     BUF_LOCK(tbp, LK_EXCLUSIVE | LK_NOWAIT)) {
868                                         crit_exit();
869                                         break;
870                                 }
871
872                                 /*
873                                  * Check that the combined cluster
874                                  * would make sense with regard to pages
875                                  * and would not be too large
876                                  */
877                                 if ((tbp->b_bcount != size) ||
878                                   ((bp->b_bio2.bio_offset + i) !=
879                                     tbp->b_bio2.bio_offset) ||
880                                   ((tbp->b_xio.xio_npages + bp->b_xio.xio_npages) >
881                                     (maxiosize / PAGE_SIZE))) {
882                                         BUF_UNLOCK(tbp);
883                                         crit_exit();
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                                 crit_exit();
894                         } /* end of code for non-first buffers only */
895
896                         /*
897                          * If the IO is via the VM then we do some
898                          * special VM hackery (yuck).  Since the buffer's
899                          * block size may not be page-aligned it is possible
900                          * for a page to be shared between two buffers.  We
901                          * have to get rid of the duplication when building
902                          * the cluster.
903                          */
904                         if (tbp->b_flags & B_VMIO) {
905                                 vm_page_t m;
906
907                                 if (i != 0) { /* if not first buffer */
908                                         for (j = 0; j < tbp->b_xio.xio_npages; ++j) {
909                                                 m = tbp->b_xio.xio_pages[j];
910                                                 if (m->flags & PG_BUSY) {
911                                                         bqrelse(tbp);
912                                                         goto finishcluster;
913                                                 }
914                                         }
915                                 }
916                                         
917                                 for (j = 0; j < tbp->b_xio.xio_npages; ++j) {
918                                         m = tbp->b_xio.xio_pages[j];
919                                         vm_page_io_start(m);
920                                         vm_object_pip_add(m->object, 1);
921                                         if ((bp->b_xio.xio_npages == 0) ||
922                                           (bp->b_xio.xio_pages[bp->b_xio.xio_npages - 1] != m)) {
923                                                 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
924                                                 bp->b_xio.xio_npages++;
925                                         }
926                                 }
927                         }
928                         bp->b_bcount += size;
929                         bp->b_bufsize += size;
930
931                         crit_enter();
932                         bundirty(tbp);
933                         tbp->b_flags &= ~B_ERROR;
934                         tbp->b_flags |= B_ASYNC;
935                         tbp->b_cmd = BUF_CMD_WRITE;
936                         crit_exit();
937                         BUF_KERNPROC(tbp);
938                         cluster_append(&bp->b_bio1, tbp);
939
940                         /*
941                          * check for latent dependencies to be handled 
942                          */
943                         if (LIST_FIRST(&tbp->b_dep) != NULL)
944                                 buf_start(tbp);
945                 }
946         finishcluster:
947                 pmap_qenter(trunc_page((vm_offset_t) bp->b_data),
948                         (vm_page_t *) bp->b_xio.xio_pages, bp->b_xio.xio_npages);
949                 if (bp->b_bufsize > bp->b_kvasize) {
950                         panic(
951                             "cluster_wbuild: b_bufsize(%d) > b_kvasize(%d)\n",
952                             bp->b_bufsize, bp->b_kvasize);
953                 }
954                 totalwritten += bp->b_bufsize;
955                 bp->b_dirtyoff = 0;
956                 bp->b_dirtyend = bp->b_bufsize;
957                 bp->b_flags |= B_ASYNC;
958                 bp->b_cmd = BUF_CMD_WRITE;
959                 vfs_busy_pages(vp, bp);
960                 bp->b_runningbufspace = bp->b_bufsize;
961                 if (bp->b_runningbufspace) {
962                         runningbufspace += bp->b_runningbufspace;
963                         ++runningbufcount;
964                 }
965                 BUF_KERNPROC(bp);       /* B_ASYNC */
966                 vn_strategy(vp, &bp->b_bio1);
967
968                 bytes -= i;
969         }
970         return totalwritten;
971 }
972
973 /*
974  * Collect together all the buffers in a cluster.
975  * Plus add one additional buffer.
976  */
977 static struct cluster_save *
978 cluster_collectbufs(struct vnode *vp, struct buf *last_bp, int lblocksize)
979 {
980         struct cluster_save *buflist;
981         struct buf *bp;
982         off_t loffset;
983         int i, len;
984
985         len = (int)(vp->v_lastw - vp->v_cstart + lblocksize) / lblocksize;
986         buflist = kmalloc(sizeof(struct buf *) * (len + 1) + sizeof(*buflist),
987                          M_SEGMENT, M_WAITOK);
988         buflist->bs_nchildren = 0;
989         buflist->bs_children = (struct buf **) (buflist + 1);
990         for (loffset = vp->v_cstart, i = 0; i < len; (loffset += lblocksize), i++) {
991                 (void) bread(vp, loffset, last_bp->b_bcount, &bp);
992                 buflist->bs_children[i] = bp;
993                 if (bp->b_bio2.bio_offset == NOOFFSET) {
994                         VOP_BMAP(bp->b_vp, bp->b_loffset,
995                                  &bp->b_bio2.bio_offset, NULL, NULL);
996                 }
997         }
998         buflist->bs_children[i] = bp = last_bp;
999         if (bp->b_bio2.bio_offset == NOOFFSET) {
1000                 VOP_BMAP(bp->b_vp, bp->b_loffset,
1001                          &bp->b_bio2.bio_offset, NULL, NULL);
1002         }
1003         buflist->bs_nchildren = i + 1;
1004         return (buflist);
1005 }
1006
1007 void
1008 cluster_append(struct bio *bio, struct buf *tbp)
1009 {
1010         tbp->b_cluster_next = NULL;
1011         if (bio->bio_caller_info1.cluster_head == NULL) {
1012                 bio->bio_caller_info1.cluster_head = tbp;
1013                 bio->bio_caller_info2.cluster_tail = tbp;
1014         } else {
1015                 bio->bio_caller_info2.cluster_tail->b_cluster_next = tbp;
1016                 bio->bio_caller_info2.cluster_tail = tbp;
1017         }
1018 }
1019