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