]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - sys/kern/vfs_bio.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / sys / kern / vfs_bio.c
1 /*-
2  * Copyright (c) 2004 Poul-Henning Kamp
3  * Copyright (c) 1994,1997 John S. Dyson
4  * Copyright (c) 2013 The FreeBSD Foundation
5  * All rights reserved.
6  *
7  * Portions of this software were developed by Konstantin Belousov
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32 /*
33  * this file contains a new buffer I/O scheme implementing a coherent
34  * VM object and buffer cache scheme.  Pains have been taken to make
35  * sure that the performance degradation associated with schemes such
36  * as this is not realized.
37  *
38  * Author:  John S. Dyson
39  * Significant help during the development and debugging phases
40  * had been provided by David Greenman, also of the FreeBSD core team.
41  *
42  * see man buf(9) for more info.
43  */
44
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/bio.h>
51 #include <sys/conf.h>
52 #include <sys/buf.h>
53 #include <sys/devicestat.h>
54 #include <sys/eventhandler.h>
55 #include <sys/fail.h>
56 #include <sys/limits.h>
57 #include <sys/lock.h>
58 #include <sys/malloc.h>
59 #include <sys/mount.h>
60 #include <sys/mutex.h>
61 #include <sys/kernel.h>
62 #include <sys/kthread.h>
63 #include <sys/proc.h>
64 #include <sys/resourcevar.h>
65 #include <sys/sysctl.h>
66 #include <sys/vmmeter.h>
67 #include <sys/vnode.h>
68 #include <geom/geom.h>
69 #include <vm/vm.h>
70 #include <vm/vm_param.h>
71 #include <vm/vm_kern.h>
72 #include <vm/vm_pageout.h>
73 #include <vm/vm_page.h>
74 #include <vm/vm_object.h>
75 #include <vm/vm_extern.h>
76 #include <vm/vm_map.h>
77 #include "opt_compat.h"
78 #include "opt_directio.h"
79 #include "opt_swap.h"
80
81 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
82
83 struct  bio_ops bioops;         /* I/O operation notification */
84
85 struct  buf_ops buf_ops_bio = {
86         .bop_name       =       "buf_ops_bio",
87         .bop_write      =       bufwrite,
88         .bop_strategy   =       bufstrategy,
89         .bop_sync       =       bufsync,
90         .bop_bdflush    =       bufbdflush,
91 };
92
93 /*
94  * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
95  * carnal knowledge of buffers.  This knowledge should be moved to vfs_bio.c.
96  */
97 struct buf *buf;                /* buffer header pool */
98 caddr_t unmapped_buf;
99
100 static struct proc *bufdaemonproc;
101
102 static int inmem(struct vnode *vp, daddr_t blkno);
103 static void vm_hold_free_pages(struct buf *bp, int newbsize);
104 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
105                 vm_offset_t to);
106 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
107 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
108                 vm_page_t m);
109 static void vfs_drain_busy_pages(struct buf *bp);
110 static void vfs_clean_pages_dirty_buf(struct buf *bp);
111 static void vfs_setdirty_locked_object(struct buf *bp);
112 static void vfs_vmio_release(struct buf *bp);
113 static int vfs_bio_clcheck(struct vnode *vp, int size,
114                 daddr_t lblkno, daddr_t blkno);
115 static int buf_do_flush(struct vnode *vp);
116 static int flushbufqueues(struct vnode *, int, int);
117 static void buf_daemon(void);
118 static void bremfreel(struct buf *bp);
119 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
120     defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
121 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
122 #endif
123
124 int vmiodirenable = TRUE;
125 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
126     "Use the VM system for directory writes");
127 long runningbufspace;
128 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
129     "Amount of presently outstanding async buffer io");
130 static long bufspace;
131 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
132     defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
133 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
134     &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
135 #else
136 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
137     "Virtual memory used for buffers");
138 #endif
139 static long unmapped_bufspace;
140 SYSCTL_LONG(_vfs, OID_AUTO, unmapped_bufspace, CTLFLAG_RD,
141     &unmapped_bufspace, 0,
142     "Amount of unmapped buffers, inclusive in the bufspace");
143 static long maxbufspace;
144 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
145     "Maximum allowed value of bufspace (including buf_daemon)");
146 static long bufmallocspace;
147 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
148     "Amount of malloced memory for buffers");
149 static long maxbufmallocspace;
150 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
151     "Maximum amount of malloced memory for buffers");
152 static long lobufspace;
153 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
154     "Minimum amount of buffers we want to have");
155 long hibufspace;
156 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
157     "Maximum allowed value of bufspace (excluding buf_daemon)");
158 static int bufreusecnt;
159 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
160     "Number of times we have reused a buffer");
161 static int buffreekvacnt;
162 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
163     "Number of times we have freed the KVA space from some buffer");
164 static int bufdefragcnt;
165 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
166     "Number of times we have had to repeat buffer allocation to defragment");
167 static long lorunningspace;
168 SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
169     "Minimum preferred space used for in-progress I/O");
170 static long hirunningspace;
171 SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
172     "Maximum amount of space to use for in-progress I/O");
173 int dirtybufferflushes;
174 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
175     0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
176 int bdwriteskip;
177 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
178     0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
179 int altbufferflushes;
180 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
181     0, "Number of fsync flushes to limit dirty buffers");
182 static int recursiveflushes;
183 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
184     0, "Number of flushes skipped due to being recursive");
185 static int numdirtybuffers;
186 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
187     "Number of buffers that are dirty (has unwritten changes) at the moment");
188 static int lodirtybuffers;
189 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
190     "How many buffers we want to have free before bufdaemon can sleep");
191 static int hidirtybuffers;
192 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
193     "When the number of dirty buffers is considered severe");
194 int dirtybufthresh;
195 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
196     0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
197 static int numfreebuffers;
198 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
199     "Number of free buffers");
200 static int lofreebuffers;
201 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
202    "XXX Unused");
203 static int hifreebuffers;
204 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
205    "XXX Complicatedly unused");
206 static int getnewbufcalls;
207 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
208    "Number of calls to getnewbuf");
209 static int getnewbufrestarts;
210 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
211     "Number of times getnewbuf has had to restart a buffer aquisition");
212 static int mappingrestarts;
213 SYSCTL_INT(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RW, &mappingrestarts, 0,
214     "Number of times getblk has had to restart a buffer mapping for "
215     "unmapped buffer");
216 static int flushbufqtarget = 100;
217 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
218     "Amount of work to do in flushbufqueues when helping bufdaemon");
219 static long notbufdflashes;
220 SYSCTL_LONG(_vfs, OID_AUTO, notbufdflashes, CTLFLAG_RD, &notbufdflashes, 0,
221     "Number of dirty buffer flushes done by the bufdaemon helpers");
222 static long barrierwrites;
223 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW, &barrierwrites, 0,
224     "Number of barrier writes");
225 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed, CTLFLAG_RD,
226     &unmapped_buf_allowed, 0,
227     "Permit the use of the unmapped i/o");
228
229 /*
230  * Wakeup point for bufdaemon, as well as indicator of whether it is already
231  * active.  Set to 1 when the bufdaemon is already "on" the queue, 0 when it
232  * is idling.
233  */
234 static int bd_request;
235
236 /*
237  * Request for the buf daemon to write more buffers than is indicated by
238  * lodirtybuf.  This may be necessary to push out excess dependencies or
239  * defragment the address space where a simple count of the number of dirty
240  * buffers is insufficient to characterize the demand for flushing them.
241  */
242 static int bd_speedupreq;
243
244 /*
245  * This lock synchronizes access to bd_request.
246  */
247 static struct mtx bdlock;
248
249 /*
250  * bogus page -- for I/O to/from partially complete buffers
251  * this is a temporary solution to the problem, but it is not
252  * really that bad.  it would be better to split the buffer
253  * for input in the case of buffers partially already in memory,
254  * but the code is intricate enough already.
255  */
256 vm_page_t bogus_page;
257
258 /*
259  * Synchronization (sleep/wakeup) variable for active buffer space requests.
260  * Set when wait starts, cleared prior to wakeup().
261  * Used in runningbufwakeup() and waitrunningbufspace().
262  */
263 static int runningbufreq;
264
265 /*
266  * This lock protects the runningbufreq and synchronizes runningbufwakeup and
267  * waitrunningbufspace().
268  */
269 static struct mtx rbreqlock;
270
271 /* 
272  * Synchronization (sleep/wakeup) variable for buffer requests.
273  * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
274  * by and/or.
275  * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
276  * getnewbuf(), and getblk().
277  */
278 static int needsbuffer;
279
280 /*
281  * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
282  */
283 static struct mtx nblock;
284
285 /*
286  * Definitions for the buffer free lists.
287  */
288 #define BUFFER_QUEUES   6       /* number of free buffer queues */
289
290 #define QUEUE_NONE      0       /* on no queue */
291 #define QUEUE_CLEAN     1       /* non-B_DELWRI buffers */
292 #define QUEUE_DIRTY     2       /* B_DELWRI buffers */
293 #define QUEUE_DIRTY_GIANT 3     /* B_DELWRI buffers that need giant */
294 #define QUEUE_EMPTYKVA  4       /* empty buffer headers w/KVA assignment */
295 #define QUEUE_EMPTY     5       /* empty buffer headers */
296 #define QUEUE_SENTINEL  1024    /* not an queue index, but mark for sentinel */
297
298 /* Queues for free buffers with various properties */
299 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
300 #ifdef INVARIANTS
301 static int bq_len[BUFFER_QUEUES];
302 #endif
303
304 /* Lock for the bufqueues */
305 static struct mtx bqlock;
306
307 /*
308  * Single global constant for BUF_WMESG, to avoid getting multiple references.
309  * buf_wmesg is referred from macros.
310  */
311 const char *buf_wmesg = BUF_WMESG;
312
313 #define VFS_BIO_NEED_ANY        0x01    /* any freeable buffer */
314 #define VFS_BIO_NEED_DIRTYFLUSH 0x02    /* waiting for dirty buffer flush */
315 #define VFS_BIO_NEED_FREE       0x04    /* wait for free bufs, hi hysteresis */
316 #define VFS_BIO_NEED_BUFSPACE   0x08    /* wait for buf space, lo hysteresis */
317
318 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
319     defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
320 static int
321 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
322 {
323         long lvalue;
324         int ivalue;
325
326         if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
327                 return (sysctl_handle_long(oidp, arg1, arg2, req));
328         lvalue = *(long *)arg1;
329         if (lvalue > INT_MAX)
330                 /* On overflow, still write out a long to trigger ENOMEM. */
331                 return (sysctl_handle_long(oidp, &lvalue, 0, req));
332         ivalue = lvalue;
333         return (sysctl_handle_int(oidp, &ivalue, 0, req));
334 }
335 #endif
336
337 #ifdef DIRECTIO
338 extern void ffs_rawread_setup(void);
339 #endif /* DIRECTIO */
340 /*
341  *      numdirtywakeup:
342  *
343  *      If someone is blocked due to there being too many dirty buffers,
344  *      and numdirtybuffers is now reasonable, wake them up.
345  */
346
347 static __inline void
348 numdirtywakeup(int level)
349 {
350
351         if (numdirtybuffers <= level) {
352                 mtx_lock(&nblock);
353                 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
354                         needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
355                         wakeup(&needsbuffer);
356                 }
357                 mtx_unlock(&nblock);
358         }
359 }
360
361 /*
362  *      bufspacewakeup:
363  *
364  *      Called when buffer space is potentially available for recovery.
365  *      getnewbuf() will block on this flag when it is unable to free 
366  *      sufficient buffer space.  Buffer space becomes recoverable when 
367  *      bp's get placed back in the queues.
368  */
369
370 static __inline void
371 bufspacewakeup(void)
372 {
373
374         /*
375          * If someone is waiting for BUF space, wake them up.  Even
376          * though we haven't freed the kva space yet, the waiting
377          * process will be able to now.
378          */
379         mtx_lock(&nblock);
380         if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
381                 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
382                 wakeup(&needsbuffer);
383         }
384         mtx_unlock(&nblock);
385 }
386
387 /*
388  * runningbufwakeup() - in-progress I/O accounting.
389  *
390  */
391 void
392 runningbufwakeup(struct buf *bp)
393 {
394
395         if (bp->b_runningbufspace) {
396                 atomic_subtract_long(&runningbufspace, bp->b_runningbufspace);
397                 bp->b_runningbufspace = 0;
398                 mtx_lock(&rbreqlock);
399                 if (runningbufreq && runningbufspace <= lorunningspace) {
400                         runningbufreq = 0;
401                         wakeup(&runningbufreq);
402                 }
403                 mtx_unlock(&rbreqlock);
404         }
405 }
406
407 /*
408  *      bufcountwakeup:
409  *
410  *      Called when a buffer has been added to one of the free queues to
411  *      account for the buffer and to wakeup anyone waiting for free buffers.
412  *      This typically occurs when large amounts of metadata are being handled
413  *      by the buffer cache ( else buffer space runs out first, usually ).
414  */
415
416 static __inline void
417 bufcountwakeup(struct buf *bp) 
418 {
419         int old;
420
421         KASSERT((bp->b_vflags & BV_INFREECNT) == 0,
422             ("buf %p already counted as free", bp));
423         if (bp->b_bufobj != NULL)
424                 mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
425         bp->b_vflags |= BV_INFREECNT;
426         old = atomic_fetchadd_int(&numfreebuffers, 1);
427         KASSERT(old >= 0 && old < nbuf,
428             ("numfreebuffers climbed to %d", old + 1));
429         mtx_lock(&nblock);
430         if (needsbuffer) {
431                 needsbuffer &= ~VFS_BIO_NEED_ANY;
432                 if (numfreebuffers >= hifreebuffers)
433                         needsbuffer &= ~VFS_BIO_NEED_FREE;
434                 wakeup(&needsbuffer);
435         }
436         mtx_unlock(&nblock);
437 }
438
439 /*
440  *      waitrunningbufspace()
441  *
442  *      runningbufspace is a measure of the amount of I/O currently
443  *      running.  This routine is used in async-write situations to
444  *      prevent creating huge backups of pending writes to a device.
445  *      Only asynchronous writes are governed by this function.
446  *
447  *      Reads will adjust runningbufspace, but will not block based on it.
448  *      The read load has a side effect of reducing the allowed write load.
449  *
450  *      This does NOT turn an async write into a sync write.  It waits  
451  *      for earlier writes to complete and generally returns before the
452  *      caller's write has reached the device.
453  */
454 void
455 waitrunningbufspace(void)
456 {
457
458         mtx_lock(&rbreqlock);
459         while (runningbufspace > hirunningspace) {
460                 ++runningbufreq;
461                 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
462         }
463         mtx_unlock(&rbreqlock);
464 }
465
466
467 /*
468  *      vfs_buf_test_cache:
469  *
470  *      Called when a buffer is extended.  This function clears the B_CACHE
471  *      bit if the newly extended portion of the buffer does not contain
472  *      valid data.
473  */
474 static __inline
475 void
476 vfs_buf_test_cache(struct buf *bp,
477                   vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
478                   vm_page_t m)
479 {
480
481         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
482         if (bp->b_flags & B_CACHE) {
483                 int base = (foff + off) & PAGE_MASK;
484                 if (vm_page_is_valid(m, base, size) == 0)
485                         bp->b_flags &= ~B_CACHE;
486         }
487 }
488
489 /* Wake up the buffer daemon if necessary */
490 static __inline
491 void
492 bd_wakeup(int dirtybuflevel)
493 {
494
495         mtx_lock(&bdlock);
496         if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
497                 bd_request = 1;
498                 wakeup(&bd_request);
499         }
500         mtx_unlock(&bdlock);
501 }
502
503 /*
504  * bd_speedup - speedup the buffer cache flushing code
505  */
506
507 void
508 bd_speedup(void)
509 {
510         int needwake;
511
512         mtx_lock(&bdlock);
513         needwake = 0;
514         if (bd_speedupreq == 0 || bd_request == 0)
515                 needwake = 1;
516         bd_speedupreq = 1;
517         bd_request = 1;
518         if (needwake)
519                 wakeup(&bd_request);
520         mtx_unlock(&bdlock);
521 }
522
523 #ifdef __i386__
524 #define TRANSIENT_DENOM 5
525 #else
526 #define TRANSIENT_DENOM 10
527 #endif
528
529 /*
530  * Calculating buffer cache scaling values and reserve space for buffer
531  * headers.  This is called during low level kernel initialization and
532  * may be called more then once.  We CANNOT write to the memory area
533  * being reserved at this time.
534  */
535 caddr_t
536 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
537 {
538         int tuned_nbuf;
539         long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
540
541         /*
542          * physmem_est is in pages.  Convert it to kilobytes (assumes
543          * PAGE_SIZE is >= 1K)
544          */
545         physmem_est = physmem_est * (PAGE_SIZE / 1024);
546
547         /*
548          * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
549          * For the first 64MB of ram nominally allocate sufficient buffers to
550          * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
551          * buffers to cover 1/10 of our ram over 64MB.  When auto-sizing
552          * the buffer cache we limit the eventual kva reservation to
553          * maxbcache bytes.
554          *
555          * factor represents the 1/4 x ram conversion.
556          */
557         if (nbuf == 0) {
558                 int factor = 4 * BKVASIZE / 1024;
559
560                 nbuf = 50;
561                 if (physmem_est > 4096)
562                         nbuf += min((physmem_est - 4096) / factor,
563                             65536 / factor);
564                 if (physmem_est > 65536)
565                         nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
566                             32 * 1024 * 1024 / (factor * 5));
567
568                 if (maxbcache && nbuf > maxbcache / BKVASIZE)
569                         nbuf = maxbcache / BKVASIZE;
570                 tuned_nbuf = 1;
571         } else
572                 tuned_nbuf = 0;
573
574         /* XXX Avoid unsigned long overflows later on with maxbufspace. */
575         maxbuf = (LONG_MAX / 3) / BKVASIZE;
576         if (nbuf > maxbuf) {
577                 if (!tuned_nbuf)
578                         printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
579                             maxbuf);
580                 nbuf = maxbuf;
581         }
582
583         /*
584          * Ideal allocation size for the transient bio submap if 10%
585          * of the maximal space buffer map.  This roughly corresponds
586          * to the amount of the buffer mapped for typical UFS load.
587          *
588          * Clip the buffer map to reserve space for the transient
589          * BIOs, if its extent is bigger than 90% (80% on i386) of the
590          * maximum buffer map extent on the platform.
591          *
592          * The fall-back to the maxbuf in case of maxbcache unset,
593          * allows to not trim the buffer KVA for the architectures
594          * with ample KVA space.
595          */
596         if (bio_transient_maxcnt == 0) {
597                 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
598                 buf_sz = (long)nbuf * BKVASIZE;
599                 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
600                     (TRANSIENT_DENOM - 1)) {
601                         /*
602                          * There is more KVA than memory.  Do not
603                          * adjust buffer map size, and assign the rest
604                          * of maxbuf to transient map.
605                          */
606                         biotmap_sz = maxbuf_sz - buf_sz;
607                 } else {
608                         /*
609                          * Buffer map spans all KVA we could afford on
610                          * this platform.  Give 10% (20% on i386) of
611                          * the buffer map to the transient bio map.
612                          */
613                         biotmap_sz = buf_sz / TRANSIENT_DENOM;
614                         buf_sz -= biotmap_sz;
615                 }
616                 if (biotmap_sz / INT_MAX > MAXPHYS)
617                         bio_transient_maxcnt = INT_MAX;
618                 else
619                         bio_transient_maxcnt = biotmap_sz / MAXPHYS;
620                 /*
621                  * Artifically limit to 1024 simultaneous in-flight I/Os
622                  * using the transient mapping.
623                  */
624                 if (bio_transient_maxcnt > 1024)
625                         bio_transient_maxcnt = 1024;
626                 if (tuned_nbuf)
627                         nbuf = buf_sz / BKVASIZE;
628         }
629
630         /*
631          * swbufs are used as temporary holders for I/O, such as paging I/O.
632          * We have no less then 16 and no more then 256.
633          */
634         nswbuf = max(min(nbuf/4, 256), 16);
635 #ifdef NSWBUF_MIN
636         if (nswbuf < NSWBUF_MIN)
637                 nswbuf = NSWBUF_MIN;
638 #endif
639 #ifdef DIRECTIO
640         ffs_rawread_setup();
641 #endif
642
643         /*
644          * Reserve space for the buffer cache buffers
645          */
646         swbuf = (void *)v;
647         v = (caddr_t)(swbuf + nswbuf);
648         buf = (void *)v;
649         v = (caddr_t)(buf + nbuf);
650
651         return(v);
652 }
653
654 /* Initialize the buffer subsystem.  Called before use of any buffers. */
655 void
656 bufinit(void)
657 {
658         struct buf *bp;
659         int i;
660
661         mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
662         mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
663         mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
664         mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
665
666         /* next, make a null set of free lists */
667         for (i = 0; i < BUFFER_QUEUES; i++)
668                 TAILQ_INIT(&bufqueues[i]);
669
670         /* finally, initialize each buffer header and stick on empty q */
671         for (i = 0; i < nbuf; i++) {
672                 bp = &buf[i];
673                 bzero(bp, sizeof *bp);
674                 bp->b_flags = B_INVAL;  /* we're just an empty header */
675                 bp->b_rcred = NOCRED;
676                 bp->b_wcred = NOCRED;
677                 bp->b_qindex = QUEUE_EMPTY;
678                 bp->b_vflags = BV_INFREECNT;    /* buf is counted as free */
679                 bp->b_xflags = 0;
680                 LIST_INIT(&bp->b_dep);
681                 BUF_LOCKINIT(bp);
682                 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
683 #ifdef INVARIANTS
684                 bq_len[QUEUE_EMPTY]++;
685 #endif
686         }
687
688         /*
689          * maxbufspace is the absolute maximum amount of buffer space we are 
690          * allowed to reserve in KVM and in real terms.  The absolute maximum
691          * is nominally used by buf_daemon.  hibufspace is the nominal maximum
692          * used by most other processes.  The differential is required to 
693          * ensure that buf_daemon is able to run when other processes might 
694          * be blocked waiting for buffer space.
695          *
696          * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
697          * this may result in KVM fragmentation which is not handled optimally
698          * by the system.
699          */
700         maxbufspace = (long)nbuf * BKVASIZE;
701         hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
702         lobufspace = hibufspace - MAXBSIZE;
703
704         /*
705          * Note: The 16 MiB upper limit for hirunningspace was chosen
706          * arbitrarily and may need further tuning. It corresponds to
707          * 128 outstanding write IO requests (if IO size is 128 KiB),
708          * which fits with many RAID controllers' tagged queuing limits.
709          * The lower 1 MiB limit is the historical upper limit for
710          * hirunningspace.
711          */
712         hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBSIZE),
713             16 * 1024 * 1024), 1024 * 1024);
714         lorunningspace = roundup((hirunningspace * 2) / 3, MAXBSIZE);
715
716 /*
717  * Limit the amount of malloc memory since it is wired permanently into
718  * the kernel space.  Even though this is accounted for in the buffer
719  * allocation, we don't want the malloced region to grow uncontrolled.
720  * The malloc scheme improves memory utilization significantly on average
721  * (small) directories.
722  */
723         maxbufmallocspace = hibufspace / 20;
724
725 /*
726  * Reduce the chance of a deadlock occuring by limiting the number
727  * of delayed-write dirty buffers we allow to stack up.
728  */
729         hidirtybuffers = nbuf / 4 + 20;
730         dirtybufthresh = hidirtybuffers * 9 / 10;
731         numdirtybuffers = 0;
732 /*
733  * To support extreme low-memory systems, make sure hidirtybuffers cannot
734  * eat up all available buffer space.  This occurs when our minimum cannot
735  * be met.  We try to size hidirtybuffers to 3/4 our buffer space assuming
736  * BKVASIZE'd buffers.
737  */
738         while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
739                 hidirtybuffers >>= 1;
740         }
741         lodirtybuffers = hidirtybuffers / 2;
742
743 /*
744  * Try to keep the number of free buffers in the specified range,
745  * and give special processes (e.g. like buf_daemon) access to an 
746  * emergency reserve.
747  */
748         lofreebuffers = nbuf / 18 + 5;
749         hifreebuffers = 2 * lofreebuffers;
750         numfreebuffers = nbuf;
751
752         bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
753             VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
754         unmapped_buf = (caddr_t)kmem_alloc_nofault(kernel_map, MAXPHYS);
755 }
756
757 #ifdef INVARIANTS
758 static inline void
759 vfs_buf_check_mapped(struct buf *bp)
760 {
761
762         KASSERT((bp->b_flags & B_UNMAPPED) == 0,
763             ("mapped buf %p %x", bp, bp->b_flags));
764         KASSERT(bp->b_kvabase != unmapped_buf,
765             ("mapped buf: b_kvabase was not updated %p", bp));
766         KASSERT(bp->b_data != unmapped_buf,
767             ("mapped buf: b_data was not updated %p", bp));
768 }
769
770 static inline void
771 vfs_buf_check_unmapped(struct buf *bp)
772 {
773
774         KASSERT((bp->b_flags & B_UNMAPPED) == B_UNMAPPED,
775             ("unmapped buf %p %x", bp, bp->b_flags));
776         KASSERT(bp->b_kvabase == unmapped_buf,
777             ("unmapped buf: corrupted b_kvabase %p", bp));
778         KASSERT(bp->b_data == unmapped_buf,
779             ("unmapped buf: corrupted b_data %p", bp));
780 }
781
782 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
783 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
784 #else
785 #define BUF_CHECK_MAPPED(bp) do {} while (0)
786 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
787 #endif
788
789 static void
790 bpmap_qenter(struct buf *bp)
791 {
792
793         BUF_CHECK_MAPPED(bp);
794
795         /*
796          * bp->b_data is relative to bp->b_offset, but
797          * bp->b_offset may be offset into the first page.
798          */
799         bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
800         pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
801         bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
802             (vm_offset_t)(bp->b_offset & PAGE_MASK));
803 }
804
805 /*
806  * bfreekva() - free the kva allocation for a buffer.
807  *
808  *      Since this call frees up buffer space, we call bufspacewakeup().
809  */
810 static void
811 bfreekva(struct buf *bp)
812 {
813
814         if (bp->b_kvasize == 0)
815                 return;
816
817         atomic_add_int(&buffreekvacnt, 1);
818         atomic_subtract_long(&bufspace, bp->b_kvasize);
819         if ((bp->b_flags & B_UNMAPPED) == 0) {
820                 BUF_CHECK_MAPPED(bp);
821                 vm_map_remove(buffer_map, (vm_offset_t)bp->b_kvabase,
822                     (vm_offset_t)bp->b_kvabase + bp->b_kvasize);
823         } else {
824                 BUF_CHECK_UNMAPPED(bp);
825                 if ((bp->b_flags & B_KVAALLOC) != 0) {
826                         vm_map_remove(buffer_map, (vm_offset_t)bp->b_kvaalloc,
827                             (vm_offset_t)bp->b_kvaalloc + bp->b_kvasize);
828                 }
829                 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
830                 bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
831         }
832         bp->b_kvasize = 0;
833         bufspacewakeup();
834 }
835
836 /*
837  *      bremfree:
838  *
839  *      Mark the buffer for removal from the appropriate free list in brelse.
840  *      
841  */
842 void
843 bremfree(struct buf *bp)
844 {
845         int old;
846
847         CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
848         KASSERT((bp->b_flags & B_REMFREE) == 0,
849             ("bremfree: buffer %p already marked for delayed removal.", bp));
850         KASSERT(bp->b_qindex != QUEUE_NONE,
851             ("bremfree: buffer %p not on a queue.", bp));
852         BUF_ASSERT_HELD(bp);
853
854         bp->b_flags |= B_REMFREE;
855         /* Fixup numfreebuffers count.  */
856         if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
857                 KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
858                     ("buf %p not counted in numfreebuffers", bp));
859                 if (bp->b_bufobj != NULL)
860                         mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
861                 bp->b_vflags &= ~BV_INFREECNT;
862                 old = atomic_fetchadd_int(&numfreebuffers, -1);
863                 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
864         }
865 }
866
867 /*
868  *      bremfreef:
869  *
870  *      Force an immediate removal from a free list.  Used only in nfs when
871  *      it abuses the b_freelist pointer.
872  */
873 void
874 bremfreef(struct buf *bp)
875 {
876         mtx_lock(&bqlock);
877         bremfreel(bp);
878         mtx_unlock(&bqlock);
879 }
880
881 /*
882  *      bremfreel:
883  *
884  *      Removes a buffer from the free list, must be called with the
885  *      bqlock held.
886  */
887 static void
888 bremfreel(struct buf *bp)
889 {
890         int old;
891
892         CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
893             bp, bp->b_vp, bp->b_flags);
894         KASSERT(bp->b_qindex != QUEUE_NONE,
895             ("bremfreel: buffer %p not on a queue.", bp));
896         BUF_ASSERT_HELD(bp);
897         mtx_assert(&bqlock, MA_OWNED);
898
899         TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
900 #ifdef INVARIANTS
901         KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
902             bp->b_qindex));
903         bq_len[bp->b_qindex]--;
904 #endif
905         bp->b_qindex = QUEUE_NONE;
906         /*
907          * If this was a delayed bremfree() we only need to remove the buffer
908          * from the queue and return the stats are already done.
909          */
910         if (bp->b_flags & B_REMFREE) {
911                 bp->b_flags &= ~B_REMFREE;
912                 return;
913         }
914         /*
915          * Fixup numfreebuffers count.  If the buffer is invalid or not
916          * delayed-write, the buffer was free and we must decrement
917          * numfreebuffers.
918          */
919         if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
920                 KASSERT((bp->b_vflags & BV_INFREECNT) != 0,
921                     ("buf %p not counted in numfreebuffers", bp));
922                 if (bp->b_bufobj != NULL)
923                         mtx_assert(BO_MTX(bp->b_bufobj), MA_OWNED);
924                 bp->b_vflags &= ~BV_INFREECNT;
925                 old = atomic_fetchadd_int(&numfreebuffers, -1);
926                 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
927         }
928 }
929
930 /*
931  * Get a buffer with the specified data.
932  */
933 int
934 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
935     struct buf **bpp)
936 {
937
938         return (breadn_flags(vp, blkno, size, 0, 0, 0, cred, 0, bpp));
939 }
940
941 /*
942  * Attempt to initiate asynchronous I/O on read-ahead blocks.  We must
943  * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
944  * the buffer is valid and we do not have to do anything.
945  */
946 void
947 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
948     int cnt, struct ucred * cred)
949 {
950         struct buf *rabp;
951         int i;
952
953         for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
954                 if (inmem(vp, *rablkno))
955                         continue;
956                 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
957
958                 if ((rabp->b_flags & B_CACHE) == 0) {
959                         if (!TD_IS_IDLETHREAD(curthread))
960                                 curthread->td_ru.ru_inblock++;
961                         rabp->b_flags |= B_ASYNC;
962                         rabp->b_flags &= ~B_INVAL;
963                         rabp->b_ioflags &= ~BIO_ERROR;
964                         rabp->b_iocmd = BIO_READ;
965                         if (rabp->b_rcred == NOCRED && cred != NOCRED)
966                                 rabp->b_rcred = crhold(cred);
967                         vfs_busy_pages(rabp, 0);
968                         BUF_KERNPROC(rabp);
969                         rabp->b_iooffset = dbtob(rabp->b_blkno);
970                         bstrategy(rabp);
971                 } else {
972                         brelse(rabp);
973                 }
974         }
975 }
976
977 /*
978  * Operates like bread, but with getblk flags.
979  */
980 int
981 bread_gb(struct vnode * vp, daddr_t blkno, int cnt, struct ucred * cred,
982     int gbflags, struct buf **bpp)
983 {
984
985         return (breadn_flags(vp, blkno, cnt, NULL, NULL, 0,
986                     cred, gbflags, bpp));
987 }
988
989 /*
990  * Operates like bread, but also starts asynchronous I/O on
991  * read-ahead blocks.
992  */
993 int
994 breadn(struct vnode * vp, daddr_t blkno, int size,
995     daddr_t * rablkno, int *rabsize,
996     int cnt, struct ucred * cred, struct buf **bpp)
997 {
998
999         return (breadn_flags(vp, blkno, size, rablkno, rabsize, cnt,
1000                     cred, 0, bpp));
1001 }
1002
1003 /*
1004  * Entry point for bread() and breadn().
1005  *
1006  * Get a buffer with the specified data.  Look in the cache first.  We
1007  * must clear BIO_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
1008  * is set, the buffer is valid and we do not have to do anything, see
1009  * getblk(). Also starts asynchronous I/O on read-ahead blocks.
1010  */
1011 int
1012 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
1013     int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
1014 {
1015         struct buf *bp;
1016         int rv = 0, readwait = 0;
1017
1018         CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
1019         /*
1020          * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
1021          */
1022         *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
1023         if (bp == NULL)
1024                 return (EBUSY);
1025
1026         /* if not found in cache, do some I/O */
1027         if ((bp->b_flags & B_CACHE) == 0) {
1028                 if (!TD_IS_IDLETHREAD(curthread))
1029                         curthread->td_ru.ru_inblock++;
1030                 bp->b_iocmd = BIO_READ;
1031                 bp->b_flags &= ~B_INVAL;
1032                 bp->b_ioflags &= ~BIO_ERROR;
1033                 if (bp->b_rcred == NOCRED && cred != NOCRED)
1034                         bp->b_rcred = crhold(cred);
1035                 vfs_busy_pages(bp, 0);
1036                 bp->b_iooffset = dbtob(bp->b_blkno);
1037                 bstrategy(bp);
1038                 ++readwait;
1039         }
1040
1041         breada(vp, rablkno, rabsize, cnt, cred);
1042
1043         if (readwait) {
1044                 rv = bufwait(bp);
1045         }
1046         return (rv);
1047 }
1048
1049 /*
1050  * Write, release buffer on completion.  (Done by iodone
1051  * if async).  Do not bother writing anything if the buffer
1052  * is invalid.
1053  *
1054  * Note that we set B_CACHE here, indicating that buffer is
1055  * fully valid and thus cacheable.  This is true even of NFS
1056  * now so we set it generally.  This could be set either here 
1057  * or in biodone() since the I/O is synchronous.  We put it
1058  * here.
1059  */
1060 int
1061 bufwrite(struct buf *bp)
1062 {
1063         int oldflags;
1064         struct vnode *vp;
1065         int vp_md;
1066
1067         CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1068         if (bp->b_flags & B_INVAL) {
1069                 brelse(bp);
1070                 return (0);
1071         }
1072
1073         if (bp->b_flags & B_BARRIER)
1074                 barrierwrites++;
1075
1076         oldflags = bp->b_flags;
1077
1078         BUF_ASSERT_HELD(bp);
1079
1080         if (bp->b_pin_count > 0)
1081                 bunpin_wait(bp);
1082
1083         KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1084             ("FFS background buffer should not get here %p", bp));
1085
1086         vp = bp->b_vp;
1087         if (vp)
1088                 vp_md = vp->v_vflag & VV_MD;
1089         else
1090                 vp_md = 0;
1091
1092         /*
1093          * Mark the buffer clean.  Increment the bufobj write count
1094          * before bundirty() call, to prevent other thread from seeing
1095          * empty dirty list and zero counter for writes in progress,
1096          * falsely indicating that the bufobj is clean.
1097          */
1098         bufobj_wref(bp->b_bufobj);
1099         bundirty(bp);
1100
1101         bp->b_flags &= ~B_DONE;
1102         bp->b_ioflags &= ~BIO_ERROR;
1103         bp->b_flags |= B_CACHE;
1104         bp->b_iocmd = BIO_WRITE;
1105
1106         vfs_busy_pages(bp, 1);
1107
1108         /*
1109          * Normal bwrites pipeline writes
1110          */
1111         bp->b_runningbufspace = bp->b_bufsize;
1112         atomic_add_long(&runningbufspace, bp->b_runningbufspace);
1113
1114         if (!TD_IS_IDLETHREAD(curthread))
1115                 curthread->td_ru.ru_oublock++;
1116         if (oldflags & B_ASYNC)
1117                 BUF_KERNPROC(bp);
1118         bp->b_iooffset = dbtob(bp->b_blkno);
1119         bstrategy(bp);
1120
1121         if ((oldflags & B_ASYNC) == 0) {
1122                 int rtval = bufwait(bp);
1123                 brelse(bp);
1124                 return (rtval);
1125         } else {
1126                 /*
1127                  * don't allow the async write to saturate the I/O
1128                  * system.  We will not deadlock here because
1129                  * we are blocking waiting for I/O that is already in-progress
1130                  * to complete. We do not block here if it is the update
1131                  * or syncer daemon trying to clean up as that can lead
1132                  * to deadlock.
1133                  */
1134                 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1135                         waitrunningbufspace();
1136         }
1137
1138         return (0);
1139 }
1140
1141 void
1142 bufbdflush(struct bufobj *bo, struct buf *bp)
1143 {
1144         struct buf *nbp;
1145
1146         if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1147                 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
1148                 altbufferflushes++;
1149         } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1150                 BO_LOCK(bo);
1151                 /*
1152                  * Try to find a buffer to flush.
1153                  */
1154                 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1155                         if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1156                             BUF_LOCK(nbp,
1157                                      LK_EXCLUSIVE | LK_NOWAIT, NULL))
1158                                 continue;
1159                         if (bp == nbp)
1160                                 panic("bdwrite: found ourselves");
1161                         BO_UNLOCK(bo);
1162                         /* Don't countdeps with the bo lock held. */
1163                         if (buf_countdeps(nbp, 0)) {
1164                                 BO_LOCK(bo);
1165                                 BUF_UNLOCK(nbp);
1166                                 continue;
1167                         }
1168                         if (nbp->b_flags & B_CLUSTEROK) {
1169                                 vfs_bio_awrite(nbp);
1170                         } else {
1171                                 bremfree(nbp);
1172                                 bawrite(nbp);
1173                         }
1174                         dirtybufferflushes++;
1175                         break;
1176                 }
1177                 if (nbp == NULL)
1178                         BO_UNLOCK(bo);
1179         }
1180 }
1181
1182 /*
1183  * Delayed write. (Buffer is marked dirty).  Do not bother writing
1184  * anything if the buffer is marked invalid.
1185  *
1186  * Note that since the buffer must be completely valid, we can safely
1187  * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
1188  * biodone() in order to prevent getblk from writing the buffer
1189  * out synchronously.
1190  */
1191 void
1192 bdwrite(struct buf *bp)
1193 {
1194         struct thread *td = curthread;
1195         struct vnode *vp;
1196         struct bufobj *bo;
1197
1198         CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1199         KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1200         KASSERT((bp->b_flags & B_BARRIER) == 0,
1201             ("Barrier request in delayed write %p", bp));
1202         BUF_ASSERT_HELD(bp);
1203
1204         if (bp->b_flags & B_INVAL) {
1205                 brelse(bp);
1206                 return;
1207         }
1208
1209         /*
1210          * If we have too many dirty buffers, don't create any more.
1211          * If we are wildly over our limit, then force a complete
1212          * cleanup. Otherwise, just keep the situation from getting
1213          * out of control. Note that we have to avoid a recursive
1214          * disaster and not try to clean up after our own cleanup!
1215          */
1216         vp = bp->b_vp;
1217         bo = bp->b_bufobj;
1218         if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1219                 td->td_pflags |= TDP_INBDFLUSH;
1220                 BO_BDFLUSH(bo, bp);
1221                 td->td_pflags &= ~TDP_INBDFLUSH;
1222         } else
1223                 recursiveflushes++;
1224
1225         bdirty(bp);
1226         /*
1227          * Set B_CACHE, indicating that the buffer is fully valid.  This is
1228          * true even of NFS now.
1229          */
1230         bp->b_flags |= B_CACHE;
1231
1232         /*
1233          * This bmap keeps the system from needing to do the bmap later,
1234          * perhaps when the system is attempting to do a sync.  Since it
1235          * is likely that the indirect block -- or whatever other datastructure
1236          * that the filesystem needs is still in memory now, it is a good
1237          * thing to do this.  Note also, that if the pageout daemon is
1238          * requesting a sync -- there might not be enough memory to do
1239          * the bmap then...  So, this is important to do.
1240          */
1241         if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1242                 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1243         }
1244
1245         /*
1246          * Set the *dirty* buffer range based upon the VM system dirty
1247          * pages.
1248          *
1249          * Mark the buffer pages as clean.  We need to do this here to
1250          * satisfy the vnode_pager and the pageout daemon, so that it
1251          * thinks that the pages have been "cleaned".  Note that since
1252          * the pages are in a delayed write buffer -- the VFS layer
1253          * "will" see that the pages get written out on the next sync,
1254          * or perhaps the cluster will be completed.
1255          */
1256         vfs_clean_pages_dirty_buf(bp);
1257         bqrelse(bp);
1258
1259         /*
1260          * Wakeup the buffer flushing daemon if we have a lot of dirty
1261          * buffers (midpoint between our recovery point and our stall
1262          * point).
1263          */
1264         bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1265
1266         /*
1267          * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1268          * due to the softdep code.
1269          */
1270 }
1271
1272 /*
1273  *      bdirty:
1274  *
1275  *      Turn buffer into delayed write request.  We must clear BIO_READ and
1276  *      B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to 
1277  *      itself to properly update it in the dirty/clean lists.  We mark it
1278  *      B_DONE to ensure that any asynchronization of the buffer properly
1279  *      clears B_DONE ( else a panic will occur later ).  
1280  *
1281  *      bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1282  *      might have been set pre-getblk().  Unlike bwrite/bdwrite, bdirty()
1283  *      should only be called if the buffer is known-good.
1284  *
1285  *      Since the buffer is not on a queue, we do not update the numfreebuffers
1286  *      count.
1287  *
1288  *      The buffer must be on QUEUE_NONE.
1289  */
1290 void
1291 bdirty(struct buf *bp)
1292 {
1293
1294         CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1295             bp, bp->b_vp, bp->b_flags);
1296         KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1297         KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1298             ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1299         BUF_ASSERT_HELD(bp);
1300         bp->b_flags &= ~(B_RELBUF);
1301         bp->b_iocmd = BIO_WRITE;
1302
1303         if ((bp->b_flags & B_DELWRI) == 0) {
1304                 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1305                 reassignbuf(bp);
1306                 atomic_add_int(&numdirtybuffers, 1);
1307                 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1308         }
1309 }
1310
1311 /*
1312  *      bundirty:
1313  *
1314  *      Clear B_DELWRI for buffer.
1315  *
1316  *      Since the buffer is not on a queue, we do not update the numfreebuffers
1317  *      count.
1318  *      
1319  *      The buffer must be on QUEUE_NONE.
1320  */
1321
1322 void
1323 bundirty(struct buf *bp)
1324 {
1325
1326         CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1327         KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1328         KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1329             ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1330         BUF_ASSERT_HELD(bp);
1331
1332         if (bp->b_flags & B_DELWRI) {
1333                 bp->b_flags &= ~B_DELWRI;
1334                 reassignbuf(bp);
1335                 atomic_subtract_int(&numdirtybuffers, 1);
1336                 numdirtywakeup(lodirtybuffers);
1337         }
1338         /*
1339          * Since it is now being written, we can clear its deferred write flag.
1340          */
1341         bp->b_flags &= ~B_DEFERRED;
1342 }
1343
1344 /*
1345  *      bawrite:
1346  *
1347  *      Asynchronous write.  Start output on a buffer, but do not wait for
1348  *      it to complete.  The buffer is released when the output completes.
1349  *
1350  *      bwrite() ( or the VOP routine anyway ) is responsible for handling 
1351  *      B_INVAL buffers.  Not us.
1352  */
1353 void
1354 bawrite(struct buf *bp)
1355 {
1356
1357         bp->b_flags |= B_ASYNC;
1358         (void) bwrite(bp);
1359 }
1360
1361 /*
1362  *      babarrierwrite:
1363  *
1364  *      Asynchronous barrier write.  Start output on a buffer, but do not
1365  *      wait for it to complete.  Place a write barrier after this write so
1366  *      that this buffer and all buffers written before it are committed to
1367  *      the disk before any buffers written after this write are committed
1368  *      to the disk.  The buffer is released when the output completes.
1369  */
1370 void
1371 babarrierwrite(struct buf *bp)
1372 {
1373
1374         bp->b_flags |= B_ASYNC | B_BARRIER;
1375         (void) bwrite(bp);
1376 }
1377
1378 /*
1379  *      bbarrierwrite:
1380  *
1381  *      Synchronous barrier write.  Start output on a buffer and wait for
1382  *      it to complete.  Place a write barrier after this write so that
1383  *      this buffer and all buffers written before it are committed to 
1384  *      the disk before any buffers written after this write are committed
1385  *      to the disk.  The buffer is released when the output completes.
1386  */
1387 int
1388 bbarrierwrite(struct buf *bp)
1389 {
1390
1391         bp->b_flags |= B_BARRIER;
1392         return (bwrite(bp));
1393 }
1394
1395 /*
1396  *      bwillwrite:
1397  *
1398  *      Called prior to the locking of any vnodes when we are expecting to
1399  *      write.  We do not want to starve the buffer cache with too many
1400  *      dirty buffers so we block here.  By blocking prior to the locking
1401  *      of any vnodes we attempt to avoid the situation where a locked vnode
1402  *      prevents the various system daemons from flushing related buffers.
1403  */
1404
1405 void
1406 bwillwrite(void)
1407 {
1408
1409         if (numdirtybuffers >= hidirtybuffers) {
1410                 mtx_lock(&nblock);
1411                 while (numdirtybuffers >= hidirtybuffers) {
1412                         bd_wakeup(1);
1413                         needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1414                         msleep(&needsbuffer, &nblock,
1415                             (PRIBIO + 4), "flswai", 0);
1416                 }
1417                 mtx_unlock(&nblock);
1418         }
1419 }
1420
1421 /*
1422  * Return true if we have too many dirty buffers.
1423  */
1424 int
1425 buf_dirty_count_severe(void)
1426 {
1427
1428         return(numdirtybuffers >= hidirtybuffers);
1429 }
1430
1431 static __noinline int
1432 buf_vm_page_count_severe(void)
1433 {
1434
1435         KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1436
1437         return vm_page_count_severe();
1438 }
1439
1440 /*
1441  *      brelse:
1442  *
1443  *      Release a busy buffer and, if requested, free its resources.  The
1444  *      buffer will be stashed in the appropriate bufqueue[] allowing it
1445  *      to be accessed later as a cache entity or reused for other purposes.
1446  */
1447 void
1448 brelse(struct buf *bp)
1449 {
1450         CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1451             bp, bp->b_vp, bp->b_flags);
1452         KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1453             ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1454
1455         if (BUF_LOCKRECURSED(bp)) {
1456                 /*
1457                  * Do not process, in particular, do not handle the
1458                  * B_INVAL/B_RELBUF and do not release to free list.
1459                  */
1460                 BUF_UNLOCK(bp);
1461                 return;
1462         }
1463
1464         if (bp->b_flags & B_MANAGED) {
1465                 bqrelse(bp);
1466                 return;
1467         }
1468
1469         if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1470             bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1471                 /*
1472                  * Failed write, redirty.  Must clear BIO_ERROR to prevent
1473                  * pages from being scrapped.  If the error is anything
1474                  * other than an I/O error (EIO), assume that retrying
1475                  * is futile.
1476                  */
1477                 bp->b_ioflags &= ~BIO_ERROR;
1478                 bdirty(bp);
1479         } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1480             (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1481                 /*
1482                  * Either a failed I/O or we were asked to free or not
1483                  * cache the buffer.
1484                  */
1485                 bp->b_flags |= B_INVAL;
1486                 if (!LIST_EMPTY(&bp->b_dep))
1487                         buf_deallocate(bp);
1488                 if (bp->b_flags & B_DELWRI) {
1489                         atomic_subtract_int(&numdirtybuffers, 1);
1490                         numdirtywakeup(lodirtybuffers);
1491                 }
1492                 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1493                 if ((bp->b_flags & B_VMIO) == 0) {
1494                         if (bp->b_bufsize)
1495                                 allocbuf(bp, 0);
1496                         if (bp->b_vp)
1497                                 brelvp(bp);
1498                 }
1499         }
1500
1501         /*
1502          * We must clear B_RELBUF if B_DELWRI is set.  If vfs_vmio_release() 
1503          * is called with B_DELWRI set, the underlying pages may wind up
1504          * getting freed causing a previous write (bdwrite()) to get 'lost'
1505          * because pages associated with a B_DELWRI bp are marked clean.
1506          * 
1507          * We still allow the B_INVAL case to call vfs_vmio_release(), even
1508          * if B_DELWRI is set.
1509          *
1510          * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1511          * on pages to return pages to the VM page queues.
1512          */
1513         if (bp->b_flags & B_DELWRI)
1514                 bp->b_flags &= ~B_RELBUF;
1515         else if (buf_vm_page_count_severe()) {
1516                 /*
1517                  * The locking of the BO_LOCK is not necessary since
1518                  * BKGRDINPROG cannot be set while we hold the buf
1519                  * lock, it can only be cleared if it is already
1520                  * pending.
1521                  */
1522                 if (bp->b_vp) {
1523                         if (!(bp->b_vflags & BV_BKGRDINPROG))
1524                                 bp->b_flags |= B_RELBUF;
1525                 } else
1526                         bp->b_flags |= B_RELBUF;
1527         }
1528
1529         /*
1530          * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
1531          * constituted, not even NFS buffers now.  Two flags effect this.  If
1532          * B_INVAL, the struct buf is invalidated but the VM object is kept
1533          * around ( i.e. so it is trivial to reconstitute the buffer later ).
1534          *
1535          * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1536          * invalidated.  BIO_ERROR cannot be set for a failed write unless the
1537          * buffer is also B_INVAL because it hits the re-dirtying code above.
1538          *
1539          * Normally we can do this whether a buffer is B_DELWRI or not.  If
1540          * the buffer is an NFS buffer, it is tracking piecemeal writes or
1541          * the commit state and we cannot afford to lose the buffer. If the
1542          * buffer has a background write in progress, we need to keep it
1543          * around to prevent it from being reconstituted and starting a second
1544          * background write.
1545          */
1546         if ((bp->b_flags & B_VMIO)
1547             && !(bp->b_vp->v_mount != NULL &&
1548                  (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1549                  !vn_isdisk(bp->b_vp, NULL) &&
1550                  (bp->b_flags & B_DELWRI))
1551             ) {
1552
1553                 int i, j, resid;
1554                 vm_page_t m;
1555                 off_t foff;
1556                 vm_pindex_t poff;
1557                 vm_object_t obj;
1558
1559                 obj = bp->b_bufobj->bo_object;
1560
1561                 /*
1562                  * Get the base offset and length of the buffer.  Note that 
1563                  * in the VMIO case if the buffer block size is not
1564                  * page-aligned then b_data pointer may not be page-aligned.
1565                  * But our b_pages[] array *IS* page aligned.
1566                  *
1567                  * block sizes less then DEV_BSIZE (usually 512) are not 
1568                  * supported due to the page granularity bits (m->valid,
1569                  * m->dirty, etc...). 
1570                  *
1571                  * See man buf(9) for more information
1572                  */
1573                 resid = bp->b_bufsize;
1574                 foff = bp->b_offset;
1575                 VM_OBJECT_LOCK(obj);
1576                 for (i = 0; i < bp->b_npages; i++) {
1577                         int had_bogus = 0;
1578
1579                         m = bp->b_pages[i];
1580
1581                         /*
1582                          * If we hit a bogus page, fixup *all* the bogus pages
1583                          * now.
1584                          */
1585                         if (m == bogus_page) {
1586                                 poff = OFF_TO_IDX(bp->b_offset);
1587                                 had_bogus = 1;
1588
1589                                 for (j = i; j < bp->b_npages; j++) {
1590                                         vm_page_t mtmp;
1591                                         mtmp = bp->b_pages[j];
1592                                         if (mtmp == bogus_page) {
1593                                                 mtmp = vm_page_lookup(obj, poff + j);
1594                                                 if (!mtmp) {
1595                                                         panic("brelse: page missing\n");
1596                                                 }
1597                                                 bp->b_pages[j] = mtmp;
1598                                         }
1599                                 }
1600
1601                                 if ((bp->b_flags & (B_INVAL | B_UNMAPPED)) == 0) {
1602                                         BUF_CHECK_MAPPED(bp);
1603                                         pmap_qenter(
1604                                             trunc_page((vm_offset_t)bp->b_data),
1605                                             bp->b_pages, bp->b_npages);
1606                                 }
1607                                 m = bp->b_pages[i];
1608                         }
1609                         if ((bp->b_flags & B_NOCACHE) ||
1610                             (bp->b_ioflags & BIO_ERROR &&
1611                              bp->b_iocmd == BIO_READ)) {
1612                                 int poffset = foff & PAGE_MASK;
1613                                 int presid = resid > (PAGE_SIZE - poffset) ?
1614                                         (PAGE_SIZE - poffset) : resid;
1615
1616                                 KASSERT(presid >= 0, ("brelse: extra page"));
1617                                 vm_page_set_invalid(m, poffset, presid);
1618                                 if (had_bogus)
1619                                         printf("avoided corruption bug in bogus_page/brelse code\n");
1620                         }
1621                         resid -= PAGE_SIZE - (foff & PAGE_MASK);
1622                         foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1623                 }
1624                 VM_OBJECT_UNLOCK(obj);
1625                 if (bp->b_flags & (B_INVAL | B_RELBUF))
1626                         vfs_vmio_release(bp);
1627
1628         } else if (bp->b_flags & B_VMIO) {
1629
1630                 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1631                         vfs_vmio_release(bp);
1632                 }
1633
1634         } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1635                 if (bp->b_bufsize != 0)
1636                         allocbuf(bp, 0);
1637                 if (bp->b_vp != NULL)
1638                         brelvp(bp);
1639         }
1640                         
1641         /* enqueue */
1642         mtx_lock(&bqlock);
1643         /* Handle delayed bremfree() processing. */
1644         if (bp->b_flags & B_REMFREE) {
1645                 struct bufobj *bo;
1646
1647                 bo = bp->b_bufobj;
1648                 if (bo != NULL)
1649                         BO_LOCK(bo);
1650                 bremfreel(bp);
1651                 if (bo != NULL)
1652                         BO_UNLOCK(bo);
1653         }
1654         if (bp->b_qindex != QUEUE_NONE)
1655                 panic("brelse: free buffer onto another queue???");
1656
1657         /*
1658          * If the buffer has junk contents signal it and eventually
1659          * clean up B_DELWRI and diassociate the vnode so that gbincore()
1660          * doesn't find it.
1661          */
1662         if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1663             (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1664                 bp->b_flags |= B_INVAL;
1665         if (bp->b_flags & B_INVAL) {
1666                 if (bp->b_flags & B_DELWRI)
1667                         bundirty(bp);
1668                 if (bp->b_vp)
1669                         brelvp(bp);
1670         }
1671
1672         /* buffers with no memory */
1673         if (bp->b_bufsize == 0) {
1674                 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1675                 if (bp->b_vflags & BV_BKGRDINPROG)
1676                         panic("losing buffer 1");
1677                 if (bp->b_kvasize) {
1678                         bp->b_qindex = QUEUE_EMPTYKVA;
1679                 } else {
1680                         bp->b_qindex = QUEUE_EMPTY;
1681                 }
1682                 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1683         /* buffers with junk contents */
1684         } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1685             (bp->b_ioflags & BIO_ERROR)) {
1686                 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1687                 if (bp->b_vflags & BV_BKGRDINPROG)
1688                         panic("losing buffer 2");
1689                 bp->b_qindex = QUEUE_CLEAN;
1690                 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1691         /* remaining buffers */
1692         } else {
1693                 if ((bp->b_flags & (B_DELWRI|B_NEEDSGIANT)) ==
1694                     (B_DELWRI|B_NEEDSGIANT))
1695                         bp->b_qindex = QUEUE_DIRTY_GIANT;
1696                 else if (bp->b_flags & B_DELWRI)
1697                         bp->b_qindex = QUEUE_DIRTY;
1698                 else
1699                         bp->b_qindex = QUEUE_CLEAN;
1700                 if (bp->b_flags & B_AGE) {
1701                         TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp,
1702                             b_freelist);
1703                 } else {
1704                         TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp,
1705                             b_freelist);
1706                 }
1707         }
1708 #ifdef INVARIANTS
1709         bq_len[bp->b_qindex]++;
1710 #endif
1711         mtx_unlock(&bqlock);
1712
1713         /*
1714          * Fixup numfreebuffers count.  The bp is on an appropriate queue
1715          * unless locked.  We then bump numfreebuffers if it is not B_DELWRI.
1716          * We've already handled the B_INVAL case ( B_DELWRI will be clear
1717          * if B_INVAL is set ).
1718          */
1719
1720         if (!(bp->b_flags & B_DELWRI)) {
1721                 struct bufobj *bo;
1722
1723                 bo = bp->b_bufobj;
1724                 if (bo != NULL)
1725                         BO_LOCK(bo);
1726                 bufcountwakeup(bp);
1727                 if (bo != NULL)
1728                         BO_UNLOCK(bo);
1729         }
1730
1731         /*
1732          * Something we can maybe free or reuse
1733          */
1734         if (bp->b_bufsize || bp->b_kvasize)
1735                 bufspacewakeup();
1736
1737         bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1738         if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1739                 panic("brelse: not dirty");
1740         /* unlock */
1741         BUF_UNLOCK(bp);
1742 }
1743
1744 /*
1745  * Release a buffer back to the appropriate queue but do not try to free
1746  * it.  The buffer is expected to be used again soon.
1747  *
1748  * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1749  * biodone() to requeue an async I/O on completion.  It is also used when
1750  * known good buffers need to be requeued but we think we may need the data
1751  * again soon.
1752  *
1753  * XXX we should be able to leave the B_RELBUF hint set on completion.
1754  */
1755 void
1756 bqrelse(struct buf *bp)
1757 {
1758         struct bufobj *bo;
1759
1760         CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1761         KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1762             ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1763
1764         if (BUF_LOCKRECURSED(bp)) {
1765                 /* do not release to free list */
1766                 BUF_UNLOCK(bp);
1767                 return;
1768         }
1769
1770         bo = bp->b_bufobj;
1771         if (bp->b_flags & B_MANAGED) {
1772                 if (bp->b_flags & B_REMFREE) {
1773                         mtx_lock(&bqlock);
1774                         if (bo != NULL)
1775                                 BO_LOCK(bo);
1776                         bremfreel(bp);
1777                         if (bo != NULL)
1778                                 BO_UNLOCK(bo);
1779                         mtx_unlock(&bqlock);
1780                 }
1781                 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1782                 BUF_UNLOCK(bp);
1783                 return;
1784         }
1785
1786         mtx_lock(&bqlock);
1787         /* Handle delayed bremfree() processing. */
1788         if (bp->b_flags & B_REMFREE) {
1789                 if (bo != NULL)
1790                         BO_LOCK(bo);
1791                 bremfreel(bp);
1792                 if (bo != NULL)
1793                         BO_UNLOCK(bo);
1794         }
1795         if (bp->b_qindex != QUEUE_NONE)
1796                 panic("bqrelse: free buffer onto another queue???");
1797         /* buffers with stale but valid contents */
1798         if (bp->b_flags & B_DELWRI) {
1799                 if (bp->b_flags & B_NEEDSGIANT)
1800                         bp->b_qindex = QUEUE_DIRTY_GIANT;
1801                 else
1802                         bp->b_qindex = QUEUE_DIRTY;
1803                 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1804 #ifdef INVARIANTS
1805                 bq_len[bp->b_qindex]++;
1806 #endif
1807         } else {
1808                 /*
1809                  * The locking of the BO_LOCK for checking of the
1810                  * BV_BKGRDINPROG is not necessary since the
1811                  * BV_BKGRDINPROG cannot be set while we hold the buf
1812                  * lock, it can only be cleared if it is already
1813                  * pending.
1814                  */
1815                 if (!buf_vm_page_count_severe() || (bp->b_vflags & BV_BKGRDINPROG)) {
1816                         bp->b_qindex = QUEUE_CLEAN;
1817                         TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1818                             b_freelist);
1819 #ifdef INVARIANTS
1820                         bq_len[QUEUE_CLEAN]++;
1821 #endif
1822                 } else {
1823                         /*
1824                          * We are too low on memory, we have to try to free
1825                          * the buffer (most importantly: the wired pages
1826                          * making up its backing store) *now*.
1827                          */
1828                         mtx_unlock(&bqlock);
1829                         brelse(bp);
1830                         return;
1831                 }
1832         }
1833         mtx_unlock(&bqlock);
1834
1835         if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI)) {
1836                 if (bo != NULL)
1837                         BO_LOCK(bo);
1838                 bufcountwakeup(bp);
1839                 if (bo != NULL)
1840                         BO_UNLOCK(bo);
1841         }
1842
1843         /*
1844          * Something we can maybe free or reuse.
1845          */
1846         if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1847                 bufspacewakeup();
1848
1849         bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1850         if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1851                 panic("bqrelse: not dirty");
1852         /* unlock */
1853         BUF_UNLOCK(bp);
1854 }
1855
1856 /* Give pages used by the bp back to the VM system (where possible) */
1857 static void
1858 vfs_vmio_release(struct buf *bp)
1859 {
1860         int i;
1861         vm_page_t m;
1862
1863         if ((bp->b_flags & B_UNMAPPED) == 0) {
1864                 BUF_CHECK_MAPPED(bp);
1865                 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
1866         } else
1867                 BUF_CHECK_UNMAPPED(bp);
1868         VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
1869         for (i = 0; i < bp->b_npages; i++) {
1870                 m = bp->b_pages[i];
1871                 bp->b_pages[i] = NULL;
1872                 /*
1873                  * In order to keep page LRU ordering consistent, put
1874                  * everything on the inactive queue.
1875                  */
1876                 vm_page_lock(m);
1877                 vm_page_unwire(m, 0);
1878                 /*
1879                  * We don't mess with busy pages, it is
1880                  * the responsibility of the process that
1881                  * busied the pages to deal with them.
1882                  */
1883                 if ((m->oflags & VPO_BUSY) == 0 && m->busy == 0 &&
1884                     m->wire_count == 0) {
1885                         /*
1886                          * Might as well free the page if we can and it has
1887                          * no valid data.  We also free the page if the
1888                          * buffer was used for direct I/O
1889                          */
1890                         if ((bp->b_flags & B_ASYNC) == 0 && !m->valid) {
1891                                 vm_page_free(m);
1892                         } else if (bp->b_flags & B_DIRECT) {
1893                                 vm_page_try_to_free(m);
1894                         } else if (buf_vm_page_count_severe()) {
1895                                 vm_page_try_to_cache(m);
1896                         }
1897                 }
1898                 vm_page_unlock(m);
1899         }
1900         VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
1901         
1902         if (bp->b_bufsize) {
1903                 bufspacewakeup();
1904                 bp->b_bufsize = 0;
1905         }
1906         bp->b_npages = 0;
1907         bp->b_flags &= ~B_VMIO;
1908         if (bp->b_vp)
1909                 brelvp(bp);
1910 }
1911
1912 /*
1913  * Check to see if a block at a particular lbn is available for a clustered
1914  * write.
1915  */
1916 static int
1917 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1918 {
1919         struct buf *bpa;
1920         int match;
1921
1922         match = 0;
1923
1924         /* If the buf isn't in core skip it */
1925         if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1926                 return (0);
1927
1928         /* If the buf is busy we don't want to wait for it */
1929         if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1930                 return (0);
1931
1932         /* Only cluster with valid clusterable delayed write buffers */
1933         if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1934             (B_DELWRI | B_CLUSTEROK))
1935                 goto done;
1936
1937         if (bpa->b_bufsize != size)
1938                 goto done;
1939
1940         /*
1941          * Check to see if it is in the expected place on disk and that the
1942          * block has been mapped.
1943          */
1944         if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1945                 match = 1;
1946 done:
1947         BUF_UNLOCK(bpa);
1948         return (match);
1949 }
1950
1951 /*
1952  *      vfs_bio_awrite:
1953  *
1954  *      Implement clustered async writes for clearing out B_DELWRI buffers.
1955  *      This is much better then the old way of writing only one buffer at
1956  *      a time.  Note that we may not be presented with the buffers in the 
1957  *      correct order, so we search for the cluster in both directions.
1958  */
1959 int
1960 vfs_bio_awrite(struct buf *bp)
1961 {
1962         struct bufobj *bo;
1963         int i;
1964         int j;
1965         daddr_t lblkno = bp->b_lblkno;
1966         struct vnode *vp = bp->b_vp;
1967         int ncl;
1968         int nwritten;
1969         int size;
1970         int maxcl;
1971         int gbflags;
1972
1973         bo = &vp->v_bufobj;
1974         gbflags = (bp->b_flags & B_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
1975         /*
1976          * right now we support clustered writing only to regular files.  If
1977          * we find a clusterable block we could be in the middle of a cluster
1978          * rather then at the beginning.
1979          */
1980         if ((vp->v_type == VREG) && 
1981             (vp->v_mount != 0) && /* Only on nodes that have the size info */
1982             (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1983
1984                 size = vp->v_mount->mnt_stat.f_iosize;
1985                 maxcl = MAXPHYS / size;
1986
1987                 BO_LOCK(bo);
1988                 for (i = 1; i < maxcl; i++)
1989                         if (vfs_bio_clcheck(vp, size, lblkno + i,
1990                             bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1991                                 break;
1992
1993                 for (j = 1; i + j <= maxcl && j <= lblkno; j++) 
1994                         if (vfs_bio_clcheck(vp, size, lblkno - j,
1995                             bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1996                                 break;
1997                 BO_UNLOCK(bo);
1998                 --j;
1999                 ncl = i + j;
2000                 /*
2001                  * this is a possible cluster write
2002                  */
2003                 if (ncl != 1) {
2004                         BUF_UNLOCK(bp);
2005                         nwritten = cluster_wbuild_gb(vp, size, lblkno - j,
2006                             ncl, gbflags);
2007                         return (nwritten);
2008                 }
2009         }
2010         bremfree(bp);
2011         bp->b_flags |= B_ASYNC;
2012         /*
2013          * default (old) behavior, writing out only one block
2014          *
2015          * XXX returns b_bufsize instead of b_bcount for nwritten?
2016          */
2017         nwritten = bp->b_bufsize;
2018         (void) bwrite(bp);
2019
2020         return (nwritten);
2021 }
2022
2023 static void
2024 setbufkva(struct buf *bp, vm_offset_t addr, int maxsize, int gbflags)
2025 {
2026
2027         KASSERT((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2028             bp->b_kvasize == 0, ("call bfreekva(%p)", bp));
2029         if ((gbflags & GB_UNMAPPED) == 0) {
2030                 bp->b_kvabase = (caddr_t)addr;
2031         } else if ((gbflags & GB_KVAALLOC) != 0) {
2032                 KASSERT((gbflags & GB_UNMAPPED) != 0,
2033                     ("GB_KVAALLOC without GB_UNMAPPED"));
2034                 bp->b_kvaalloc = (caddr_t)addr;
2035                 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2036                 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2037         }
2038         bp->b_kvasize = maxsize;
2039 }
2040
2041 /*
2042  * Allocate the buffer KVA and set b_kvasize. Also set b_kvabase if
2043  * needed.
2044  */
2045 static int
2046 allocbufkva(struct buf *bp, int maxsize, int gbflags)
2047 {
2048         vm_offset_t addr;
2049         int rv;
2050
2051         bfreekva(bp);
2052         addr = 0;
2053
2054         vm_map_lock(buffer_map);
2055         if (vm_map_findspace(buffer_map, vm_map_min(buffer_map), maxsize,
2056             &addr)) {
2057                 vm_map_unlock(buffer_map);
2058                 /*
2059                  * Buffer map is too fragmented.  Request the caller
2060                  * to defragment the map.
2061                  */
2062                 atomic_add_int(&bufdefragcnt, 1);
2063                 return (1);
2064         }
2065         rv = vm_map_insert(buffer_map, NULL, 0, addr, addr + maxsize,
2066             VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
2067         KASSERT(rv == KERN_SUCCESS, ("vm_map_insert(buffer_map) rv %d", rv));
2068         vm_map_unlock(buffer_map);
2069         setbufkva(bp, addr, maxsize, gbflags);
2070         atomic_add_long(&bufspace, bp->b_kvasize);
2071         return (0);
2072 }
2073
2074 /*
2075  * Ask the bufdaemon for help, or act as bufdaemon itself, when a
2076  * locked vnode is supplied.
2077  */
2078 static void
2079 getnewbuf_bufd_help(struct vnode *vp, int gbflags, int slpflag, int slptimeo,
2080     int defrag)
2081 {
2082         struct thread *td;
2083         char *waitmsg;
2084         int fl, flags, norunbuf;
2085
2086         mtx_assert(&bqlock, MA_OWNED);
2087
2088         if (defrag) {
2089                 flags = VFS_BIO_NEED_BUFSPACE;
2090                 waitmsg = "nbufkv";
2091         } else if (bufspace >= hibufspace) {
2092                 waitmsg = "nbufbs";
2093                 flags = VFS_BIO_NEED_BUFSPACE;
2094         } else {
2095                 waitmsg = "newbuf";
2096                 flags = VFS_BIO_NEED_ANY;
2097         }
2098         mtx_lock(&nblock);
2099         needsbuffer |= flags;
2100         mtx_unlock(&nblock);
2101         mtx_unlock(&bqlock);
2102
2103         bd_speedup();   /* heeeelp */
2104         if ((gbflags & GB_NOWAIT_BD) != 0)
2105                 return;
2106
2107         td = curthread;
2108         mtx_lock(&nblock);
2109         while (needsbuffer & flags) {
2110                 if (vp != NULL && (td->td_pflags & TDP_BUFNEED) == 0) {
2111                         mtx_unlock(&nblock);
2112                         /*
2113                          * getblk() is called with a vnode locked, and
2114                          * some majority of the dirty buffers may as
2115                          * well belong to the vnode.  Flushing the
2116                          * buffers there would make a progress that
2117                          * cannot be achieved by the buf_daemon, that
2118                          * cannot lock the vnode.
2119                          */
2120                         norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
2121                             (td->td_pflags & TDP_NORUNNINGBUF);
2122                         /* play bufdaemon */
2123                         td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
2124                         fl = buf_do_flush(vp);
2125                         td->td_pflags &= norunbuf;
2126                         mtx_lock(&nblock);
2127                         if (fl != 0)
2128                                 continue;
2129                         if ((needsbuffer & flags) == 0)
2130                                 break;
2131                 }
2132                 if (msleep(&needsbuffer, &nblock, (PRIBIO + 4) | slpflag,
2133                     waitmsg, slptimeo))
2134                         break;
2135         }
2136         mtx_unlock(&nblock);
2137 }
2138
2139 static void
2140 getnewbuf_reuse_bp(struct buf *bp, int qindex)
2141 {
2142
2143         CTR6(KTR_BUF, "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
2144             "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
2145              bp->b_kvasize, bp->b_bufsize, qindex);
2146         mtx_assert(&bqlock, MA_NOTOWNED);
2147
2148         /*
2149          * Note: we no longer distinguish between VMIO and non-VMIO
2150          * buffers.
2151          */
2152         KASSERT((bp->b_flags & B_DELWRI) == 0,
2153             ("delwri buffer %p found in queue %d", bp, qindex));
2154
2155         if (qindex == QUEUE_CLEAN) {
2156                 if (bp->b_flags & B_VMIO) {
2157                         bp->b_flags &= ~B_ASYNC;
2158                         vfs_vmio_release(bp);
2159                 }
2160                 if (bp->b_vp != NULL)
2161                         brelvp(bp);
2162         }
2163
2164         /*
2165          * Get the rest of the buffer freed up.  b_kva* is still valid
2166          * after this operation.
2167          */
2168
2169         if (bp->b_rcred != NOCRED) {
2170                 crfree(bp->b_rcred);
2171                 bp->b_rcred = NOCRED;
2172         }
2173         if (bp->b_wcred != NOCRED) {
2174                 crfree(bp->b_wcred);
2175                 bp->b_wcred = NOCRED;
2176         }
2177         if (!LIST_EMPTY(&bp->b_dep))
2178                 buf_deallocate(bp);
2179         if (bp->b_vflags & BV_BKGRDINPROG)
2180                 panic("losing buffer 3");
2181         KASSERT(bp->b_vp == NULL, ("bp: %p still has vnode %p.  qindex: %d",
2182             bp, bp->b_vp, qindex));
2183         KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
2184             ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
2185
2186         if (bp->b_bufsize)
2187                 allocbuf(bp, 0);
2188
2189         bp->b_flags &= B_UNMAPPED | B_KVAALLOC;
2190         bp->b_ioflags = 0;
2191         bp->b_xflags = 0;
2192         KASSERT((bp->b_vflags & BV_INFREECNT) == 0,
2193             ("buf %p still counted as free?", bp));
2194         bp->b_vflags = 0;
2195         bp->b_vp = NULL;
2196         bp->b_blkno = bp->b_lblkno = 0;
2197         bp->b_offset = NOOFFSET;
2198         bp->b_iodone = 0;
2199         bp->b_error = 0;
2200         bp->b_resid = 0;
2201         bp->b_bcount = 0;
2202         bp->b_npages = 0;
2203         bp->b_dirtyoff = bp->b_dirtyend = 0;
2204         bp->b_bufobj = NULL;
2205         bp->b_pin_count = 0;
2206         bp->b_fsprivate1 = NULL;
2207         bp->b_fsprivate2 = NULL;
2208         bp->b_fsprivate3 = NULL;
2209
2210         LIST_INIT(&bp->b_dep);
2211 }
2212
2213 static int flushingbufs;
2214
2215 static struct buf *
2216 getnewbuf_scan(int maxsize, int defrag, int unmapped, int metadata)
2217 {
2218         struct buf *bp, *nbp;
2219         int nqindex, qindex, pass;
2220
2221         KASSERT(!unmapped || !defrag, ("both unmapped and defrag"));
2222
2223         pass = 1;
2224 restart:
2225         atomic_add_int(&getnewbufrestarts, 1);
2226
2227         /*
2228          * Setup for scan.  If we do not have enough free buffers,
2229          * we setup a degenerate case that immediately fails.  Note
2230          * that if we are specially marked process, we are allowed to
2231          * dip into our reserves.
2232          *
2233          * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
2234          * for the allocation of the mapped buffer.  For unmapped, the
2235          * easiest is to start with EMPTY outright.
2236          *
2237          * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
2238          * However, there are a number of cases (defragging, reusing, ...)
2239          * where we cannot backup.
2240          */
2241         nbp = NULL;
2242         mtx_lock(&bqlock);
2243         if (!defrag && unmapped) {
2244                 nqindex = QUEUE_EMPTY;
2245                 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2246         }
2247         if (nbp == NULL) {
2248                 nqindex = QUEUE_EMPTYKVA;
2249                 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2250         }
2251
2252         /*
2253          * If no EMPTYKVA buffers and we are either defragging or
2254          * reusing, locate a CLEAN buffer to free or reuse.  If
2255          * bufspace useage is low skip this step so we can allocate a
2256          * new buffer.
2257          */
2258         if (nbp == NULL && (defrag || bufspace >= lobufspace)) {
2259                 nqindex = QUEUE_CLEAN;
2260                 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2261         }
2262
2263         /*
2264          * If we could not find or were not allowed to reuse a CLEAN
2265          * buffer, check to see if it is ok to use an EMPTY buffer.
2266          * We can only use an EMPTY buffer if allocating its KVA would
2267          * not otherwise run us out of buffer space.  No KVA is needed
2268          * for the unmapped allocation.
2269          */
2270         if (nbp == NULL && defrag == 0 && (bufspace + maxsize < hibufspace ||
2271             metadata)) {
2272                 nqindex = QUEUE_EMPTY;
2273                 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2274         }
2275
2276         /*
2277          * All available buffers might be clean, retry ignoring the
2278          * lobufspace as the last resort.
2279          */
2280         if (nbp == NULL && !TAILQ_EMPTY(&bufqueues[QUEUE_CLEAN])) {
2281                 nqindex = QUEUE_CLEAN;
2282                 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2283         }
2284
2285         /*
2286          * Run scan, possibly freeing data and/or kva mappings on the fly
2287          * depending.
2288          */
2289         while ((bp = nbp) != NULL) {
2290                 qindex = nqindex;
2291
2292                 /*
2293                  * Calculate next bp (we can only use it if we do not
2294                  * block or do other fancy things).
2295                  */
2296                 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
2297                         switch (qindex) {
2298                         case QUEUE_EMPTY:
2299                                 nqindex = QUEUE_EMPTYKVA;
2300                                 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2301                                 if (nbp != NULL)
2302                                         break;
2303                                 /* FALLTHROUGH */
2304                         case QUEUE_EMPTYKVA:
2305                                 nqindex = QUEUE_CLEAN;
2306                                 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2307                                 if (nbp != NULL)
2308                                         break;
2309                                 /* FALLTHROUGH */
2310                         case QUEUE_CLEAN:
2311                                 if (metadata && pass == 1) {
2312                                         pass = 2;
2313                                         nqindex = QUEUE_EMPTY;
2314                                         nbp = TAILQ_FIRST(
2315                                             &bufqueues[QUEUE_EMPTY]);
2316                                 }
2317                                 /*
2318                                  * nbp is NULL. 
2319                                  */
2320                                 break;
2321                         }
2322                 }
2323                 /*
2324                  * If we are defragging then we need a buffer with 
2325                  * b_kvasize != 0.  XXX this situation should no longer
2326                  * occur, if defrag is non-zero the buffer's b_kvasize
2327                  * should also be non-zero at this point.  XXX
2328                  */
2329                 if (defrag && bp->b_kvasize == 0) {
2330                         printf("Warning: defrag empty buffer %p\n", bp);
2331                         continue;
2332                 }
2333
2334                 /*
2335                  * Start freeing the bp.  This is somewhat involved.  nbp
2336                  * remains valid only for QUEUE_EMPTY[KVA] bp's.
2337                  */
2338                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2339                         continue;
2340                 if (bp->b_vp) {
2341                         BO_LOCK(bp->b_bufobj);
2342                         if (bp->b_vflags & BV_BKGRDINPROG) {
2343                                 BO_UNLOCK(bp->b_bufobj);
2344                                 BUF_UNLOCK(bp);
2345                                 continue;
2346                         }
2347                         BO_UNLOCK(bp->b_bufobj);
2348                 }
2349
2350                 KASSERT(bp->b_qindex == qindex,
2351                     ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2352
2353                 if (bp->b_bufobj != NULL)
2354                         BO_LOCK(bp->b_bufobj);
2355                 bremfreel(bp);
2356                 if (bp->b_bufobj != NULL)
2357                         BO_UNLOCK(bp->b_bufobj);
2358                 mtx_unlock(&bqlock);
2359                 /*
2360                  * NOTE:  nbp is now entirely invalid.  We can only restart
2361                  * the scan from this point on.
2362                  */
2363
2364                 getnewbuf_reuse_bp(bp, qindex);
2365                 mtx_assert(&bqlock, MA_NOTOWNED);
2366
2367                 /*
2368                  * If we are defragging then free the buffer.
2369                  */
2370                 if (defrag) {
2371                         bp->b_flags |= B_INVAL;
2372                         bfreekva(bp);
2373                         brelse(bp);
2374                         defrag = 0;
2375                         goto restart;
2376                 }
2377
2378                 /*
2379                  * Notify any waiters for the buffer lock about
2380                  * identity change by freeing the buffer.
2381                  */
2382                 if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2383                         bp->b_flags |= B_INVAL;
2384                         bfreekva(bp);
2385                         brelse(bp);
2386                         goto restart;
2387                 }
2388
2389                 if (metadata)
2390                         break;
2391
2392                 /*
2393                  * If we are overcomitted then recover the buffer and its
2394                  * KVM space.  This occurs in rare situations when multiple
2395                  * processes are blocked in getnewbuf() or allocbuf().
2396                  */
2397                 if (bufspace >= hibufspace)
2398                         flushingbufs = 1;
2399                 if (flushingbufs && bp->b_kvasize != 0) {
2400                         bp->b_flags |= B_INVAL;
2401                         bfreekva(bp);
2402                         brelse(bp);
2403                         goto restart;
2404                 }
2405                 if (bufspace < lobufspace)
2406                         flushingbufs = 0;
2407                 break;
2408         }
2409         return (bp);
2410 }
2411
2412 /*
2413  *      getnewbuf:
2414  *
2415  *      Find and initialize a new buffer header, freeing up existing buffers
2416  *      in the bufqueues as necessary.  The new buffer is returned locked.
2417  *
2418  *      Important:  B_INVAL is not set.  If the caller wishes to throw the
2419  *      buffer away, the caller must set B_INVAL prior to calling brelse().
2420  *
2421  *      We block if:
2422  *              We have insufficient buffer headers
2423  *              We have insufficient buffer space
2424  *              buffer_map is too fragmented ( space reservation fails )
2425  *              If we have to flush dirty buffers ( but we try to avoid this )
2426  *
2427  *      To avoid VFS layer recursion we do not flush dirty buffers ourselves.
2428  *      Instead we ask the buf daemon to do it for us.  We attempt to
2429  *      avoid piecemeal wakeups of the pageout daemon.
2430  */
2431 static struct buf *
2432 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
2433     int gbflags)
2434 {
2435         struct buf *bp;
2436         int defrag, metadata;
2437
2438         KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2439             ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2440         if (!unmapped_buf_allowed)
2441                 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2442
2443         defrag = 0;
2444         if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2445             vp->v_type == VCHR)
2446                 metadata = 1;
2447         else
2448                 metadata = 0;
2449         /*
2450          * We can't afford to block since we might be holding a vnode lock,
2451          * which may prevent system daemons from running.  We deal with
2452          * low-memory situations by proactively returning memory and running
2453          * async I/O rather then sync I/O.
2454          */
2455         atomic_add_int(&getnewbufcalls, 1);
2456         atomic_subtract_int(&getnewbufrestarts, 1);
2457 restart:
2458         bp = getnewbuf_scan(maxsize, defrag, (gbflags & (GB_UNMAPPED |
2459             GB_KVAALLOC)) == GB_UNMAPPED, metadata);
2460         if (bp != NULL)
2461                 defrag = 0;
2462
2463         /*
2464          * If we exhausted our list, sleep as appropriate.  We may have to
2465          * wakeup various daemons and write out some dirty buffers.
2466          *
2467          * Generally we are sleeping due to insufficient buffer space.
2468          */
2469         if (bp == NULL) {
2470                 mtx_assert(&bqlock, MA_OWNED);
2471                 getnewbuf_bufd_help(vp, gbflags, slpflag, slptimeo, defrag);
2472                 mtx_assert(&bqlock, MA_NOTOWNED);
2473         } else if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == GB_UNMAPPED) {
2474                 mtx_assert(&bqlock, MA_NOTOWNED);
2475
2476                 bfreekva(bp);
2477                 bp->b_flags |= B_UNMAPPED;
2478                 bp->b_kvabase = bp->b_data = unmapped_buf;
2479                 bp->b_kvasize = maxsize;
2480                 atomic_add_long(&bufspace, bp->b_kvasize);
2481                 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2482                 atomic_add_int(&bufreusecnt, 1);
2483         } else {
2484                 mtx_assert(&bqlock, MA_NOTOWNED);
2485
2486                 /*
2487                  * We finally have a valid bp.  We aren't quite out of the
2488                  * woods, we still have to reserve kva space.  In order
2489                  * to keep fragmentation sane we only allocate kva in
2490                  * BKVASIZE chunks.
2491                  */
2492                 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2493
2494                 if (maxsize != bp->b_kvasize || (bp->b_flags & (B_UNMAPPED |
2495                     B_KVAALLOC)) == B_UNMAPPED) {
2496                         if (allocbufkva(bp, maxsize, gbflags)) {
2497                                 defrag = 1;
2498                                 bp->b_flags |= B_INVAL;
2499                                 brelse(bp);
2500                                 goto restart;
2501                         }
2502                         atomic_add_int(&bufreusecnt, 1);
2503                 } else if ((bp->b_flags & B_KVAALLOC) != 0 &&
2504                     (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == 0) {
2505                         /*
2506                          * If the reused buffer has KVA allocated,
2507                          * reassign b_kvaalloc to b_kvabase.
2508                          */
2509                         bp->b_kvabase = bp->b_kvaalloc;
2510                         bp->b_flags &= ~B_KVAALLOC;
2511                         atomic_subtract_long(&unmapped_bufspace,
2512                             bp->b_kvasize);
2513                         atomic_add_int(&bufreusecnt, 1);
2514                 } else if ((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2515                     (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == (GB_UNMAPPED |
2516                     GB_KVAALLOC)) {
2517                         /*
2518                          * The case of reused buffer already have KVA
2519                          * mapped, but the request is for unmapped
2520                          * buffer with KVA allocated.
2521                          */
2522                         bp->b_kvaalloc = bp->b_kvabase;
2523                         bp->b_data = bp->b_kvabase = unmapped_buf;
2524                         bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2525                         atomic_add_long(&unmapped_bufspace,
2526                             bp->b_kvasize);
2527                         atomic_add_int(&bufreusecnt, 1);
2528                 }
2529                 if ((gbflags & GB_UNMAPPED) == 0) {
2530                         bp->b_saveaddr = bp->b_kvabase;
2531                         bp->b_data = bp->b_saveaddr;
2532                         bp->b_flags &= ~B_UNMAPPED;
2533                         BUF_CHECK_MAPPED(bp);
2534                 }
2535         }
2536         return (bp);
2537 }
2538
2539 /*
2540  *      buf_daemon:
2541  *
2542  *      buffer flushing daemon.  Buffers are normally flushed by the
2543  *      update daemon but if it cannot keep up this process starts to
2544  *      take the load in an attempt to prevent getnewbuf() from blocking.
2545  */
2546
2547 static struct kproc_desc buf_kp = {
2548         "bufdaemon",
2549         buf_daemon,
2550         &bufdaemonproc
2551 };
2552 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2553
2554 static int
2555 buf_do_flush(struct vnode *vp)
2556 {
2557         int flushed;
2558
2559         flushed = flushbufqueues(vp, QUEUE_DIRTY, 0);
2560         /* The list empty check here is slightly racy */
2561         if (!TAILQ_EMPTY(&bufqueues[QUEUE_DIRTY_GIANT])) {
2562                 mtx_lock(&Giant);
2563                 flushed += flushbufqueues(vp, QUEUE_DIRTY_GIANT, 0);
2564                 mtx_unlock(&Giant);
2565         }
2566         if (flushed == 0) {
2567                 /*
2568                  * Could not find any buffers without rollback
2569                  * dependencies, so just write the first one
2570                  * in the hopes of eventually making progress.
2571                  */
2572                 flushbufqueues(vp, QUEUE_DIRTY, 1);
2573                 if (!TAILQ_EMPTY(
2574                             &bufqueues[QUEUE_DIRTY_GIANT])) {
2575                         mtx_lock(&Giant);
2576                         flushbufqueues(vp, QUEUE_DIRTY_GIANT, 1);
2577                         mtx_unlock(&Giant);
2578                 }
2579         }
2580         return (flushed);
2581 }
2582
2583 static void
2584 buf_daemon()
2585 {
2586         int lodirtysave;
2587
2588         /*
2589          * This process needs to be suspended prior to shutdown sync.
2590          */
2591         EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2592             SHUTDOWN_PRI_LAST);
2593
2594         /*
2595          * This process is allowed to take the buffer cache to the limit
2596          */
2597         curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2598         mtx_lock(&bdlock);
2599         for (;;) {
2600                 bd_request = 0;
2601                 mtx_unlock(&bdlock);
2602
2603                 kproc_suspend_check(bufdaemonproc);
2604                 lodirtysave = lodirtybuffers;
2605                 if (bd_speedupreq) {
2606                         lodirtybuffers = numdirtybuffers / 2;
2607                         bd_speedupreq = 0;
2608                 }
2609                 /*
2610                  * Do the flush.  Limit the amount of in-transit I/O we
2611                  * allow to build up, otherwise we would completely saturate
2612                  * the I/O system.  Wakeup any waiting processes before we
2613                  * normally would so they can run in parallel with our drain.
2614                  */
2615                 while (numdirtybuffers > lodirtybuffers) {
2616                         if (buf_do_flush(NULL) == 0)
2617                                 break;
2618                         kern_yield(PRI_UNCHANGED);
2619                 }
2620                 lodirtybuffers = lodirtysave;
2621
2622                 /*
2623                  * Only clear bd_request if we have reached our low water
2624                  * mark.  The buf_daemon normally waits 1 second and
2625                  * then incrementally flushes any dirty buffers that have
2626                  * built up, within reason.
2627                  *
2628                  * If we were unable to hit our low water mark and couldn't
2629                  * find any flushable buffers, we sleep half a second.
2630                  * Otherwise we loop immediately.
2631                  */
2632                 mtx_lock(&bdlock);
2633                 if (numdirtybuffers <= lodirtybuffers) {
2634                         /*
2635                          * We reached our low water mark, reset the
2636                          * request and sleep until we are needed again.
2637                          * The sleep is just so the suspend code works.
2638                          */
2639                         bd_request = 0;
2640                         msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2641                 } else {
2642                         /*
2643                          * We couldn't find any flushable dirty buffers but
2644                          * still have too many dirty buffers, we
2645                          * have to sleep and try again.  (rare)
2646                          */
2647                         msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2648                 }
2649         }
2650 }
2651
2652 /*
2653  *      flushbufqueues:
2654  *
2655  *      Try to flush a buffer in the dirty queue.  We must be careful to
2656  *      free up B_INVAL buffers instead of write them, which NFS is 
2657  *      particularly sensitive to.
2658  */
2659 static int flushwithdeps = 0;
2660 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2661     0, "Number of buffers flushed with dependecies that require rollbacks");
2662
2663 static int
2664 flushbufqueues(struct vnode *lvp, int queue, int flushdeps)
2665 {
2666         struct buf *sentinel;
2667         struct vnode *vp;
2668         struct mount *mp;
2669         struct buf *bp;
2670         int hasdeps;
2671         int flushed;
2672         int target;
2673
2674         if (lvp == NULL) {
2675                 target = numdirtybuffers - lodirtybuffers;
2676                 if (flushdeps && target > 2)
2677                         target /= 2;
2678         } else
2679                 target = flushbufqtarget;
2680         flushed = 0;
2681         bp = NULL;
2682         sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2683         sentinel->b_qindex = QUEUE_SENTINEL;
2684         mtx_lock(&bqlock);
2685         TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2686         while (flushed != target) {
2687                 bp = TAILQ_NEXT(sentinel, b_freelist);
2688                 if (bp != NULL) {
2689                         TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2690                         TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2691                             b_freelist);
2692                 } else
2693                         break;
2694                 /*
2695                  * Skip sentinels inserted by other invocations of the
2696                  * flushbufqueues(), taking care to not reorder them.
2697                  */
2698                 if (bp->b_qindex == QUEUE_SENTINEL)
2699                         continue;
2700                 /*
2701                  * Only flush the buffers that belong to the
2702                  * vnode locked by the curthread.
2703                  */
2704                 if (lvp != NULL && bp->b_vp != lvp)
2705                         continue;
2706                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2707                         continue;
2708                 if (bp->b_pin_count > 0) {
2709                         BUF_UNLOCK(bp);
2710                         continue;
2711                 }
2712                 BO_LOCK(bp->b_bufobj);
2713                 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2714                     (bp->b_flags & B_DELWRI) == 0) {
2715                         BO_UNLOCK(bp->b_bufobj);
2716                         BUF_UNLOCK(bp);
2717                         continue;
2718                 }
2719                 BO_UNLOCK(bp->b_bufobj);
2720                 if (bp->b_flags & B_INVAL) {
2721                         bremfreel(bp);
2722                         mtx_unlock(&bqlock);
2723                         brelse(bp);
2724                         flushed++;
2725                         numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2726                         mtx_lock(&bqlock);
2727                         continue;
2728                 }
2729
2730                 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2731                         if (flushdeps == 0) {
2732                                 BUF_UNLOCK(bp);
2733                                 continue;
2734                         }
2735                         hasdeps = 1;
2736                 } else
2737                         hasdeps = 0;
2738                 /*
2739                  * We must hold the lock on a vnode before writing
2740                  * one of its buffers. Otherwise we may confuse, or
2741                  * in the case of a snapshot vnode, deadlock the
2742                  * system.
2743                  *
2744                  * The lock order here is the reverse of the normal
2745                  * of vnode followed by buf lock.  This is ok because
2746                  * the NOWAIT will prevent deadlock.
2747                  */
2748                 vp = bp->b_vp;
2749                 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2750                         BUF_UNLOCK(bp);
2751                         continue;
2752                 }
2753                 if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_CANRECURSE) == 0) {
2754                         mtx_unlock(&bqlock);
2755                         CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2756                             bp, bp->b_vp, bp->b_flags);
2757                         if (curproc == bufdaemonproc)
2758                                 vfs_bio_awrite(bp);
2759                         else {
2760                                 bremfree(bp);
2761                                 bwrite(bp);
2762                                 notbufdflashes++;
2763                         }
2764                         vn_finished_write(mp);
2765                         VOP_UNLOCK(vp, 0);
2766                         flushwithdeps += hasdeps;
2767                         flushed++;
2768
2769                         /*
2770                          * Sleeping on runningbufspace while holding
2771                          * vnode lock leads to deadlock.
2772                          */
2773                         if (curproc == bufdaemonproc)
2774                                 waitrunningbufspace();
2775                         numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2776                         mtx_lock(&bqlock);
2777                         continue;
2778                 }
2779                 vn_finished_write(mp);
2780                 BUF_UNLOCK(bp);
2781         }
2782         TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2783         mtx_unlock(&bqlock);
2784         free(sentinel, M_TEMP);
2785         return (flushed);
2786 }
2787
2788 /*
2789  * Check to see if a block is currently memory resident.
2790  */
2791 struct buf *
2792 incore(struct bufobj *bo, daddr_t blkno)
2793 {
2794         struct buf *bp;
2795
2796         BO_LOCK(bo);
2797         bp = gbincore(bo, blkno);
2798         BO_UNLOCK(bo);
2799         return (bp);
2800 }
2801
2802 /*
2803  * Returns true if no I/O is needed to access the
2804  * associated VM object.  This is like incore except
2805  * it also hunts around in the VM system for the data.
2806  */
2807
2808 static int
2809 inmem(struct vnode * vp, daddr_t blkno)
2810 {
2811         vm_object_t obj;
2812         vm_offset_t toff, tinc, size;
2813         vm_page_t m;
2814         vm_ooffset_t off;
2815
2816         ASSERT_VOP_LOCKED(vp, "inmem");
2817
2818         if (incore(&vp->v_bufobj, blkno))
2819                 return 1;
2820         if (vp->v_mount == NULL)
2821                 return 0;
2822         obj = vp->v_object;
2823         if (obj == NULL)
2824                 return (0);
2825
2826         size = PAGE_SIZE;
2827         if (size > vp->v_mount->mnt_stat.f_iosize)
2828                 size = vp->v_mount->mnt_stat.f_iosize;
2829         off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2830
2831         VM_OBJECT_LOCK(obj);
2832         for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2833                 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2834                 if (!m)
2835                         goto notinmem;
2836                 tinc = size;
2837                 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2838                         tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2839                 if (vm_page_is_valid(m,
2840                     (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2841                         goto notinmem;
2842         }
2843         VM_OBJECT_UNLOCK(obj);
2844         return 1;
2845
2846 notinmem:
2847         VM_OBJECT_UNLOCK(obj);
2848         return (0);
2849 }
2850
2851 /*
2852  * Set the dirty range for a buffer based on the status of the dirty
2853  * bits in the pages comprising the buffer.  The range is limited
2854  * to the size of the buffer.
2855  *
2856  * Tell the VM system that the pages associated with this buffer
2857  * are clean.  This is used for delayed writes where the data is
2858  * going to go to disk eventually without additional VM intevention.
2859  *
2860  * Note that while we only really need to clean through to b_bcount, we
2861  * just go ahead and clean through to b_bufsize.
2862  */
2863 static void
2864 vfs_clean_pages_dirty_buf(struct buf *bp)
2865 {
2866         vm_ooffset_t foff, noff, eoff;
2867         vm_page_t m;
2868         int i;
2869
2870         if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2871                 return;
2872
2873         foff = bp->b_offset;
2874         KASSERT(bp->b_offset != NOOFFSET,
2875             ("vfs_clean_pages_dirty_buf: no buffer offset"));
2876
2877         VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2878         vfs_drain_busy_pages(bp);
2879         vfs_setdirty_locked_object(bp);
2880         for (i = 0; i < bp->b_npages; i++) {
2881                 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2882                 eoff = noff;
2883                 if (eoff > bp->b_offset + bp->b_bufsize)
2884                         eoff = bp->b_offset + bp->b_bufsize;
2885                 m = bp->b_pages[i];
2886                 vfs_page_set_validclean(bp, foff, m);
2887                 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2888                 foff = noff;
2889         }
2890         VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2891 }
2892
2893 static void
2894 vfs_setdirty_locked_object(struct buf *bp)
2895 {
2896         vm_object_t object;
2897         int i;
2898
2899         object = bp->b_bufobj->bo_object;
2900         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2901
2902         /*
2903          * We qualify the scan for modified pages on whether the
2904          * object has been flushed yet.
2905          */
2906         if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
2907                 vm_offset_t boffset;
2908                 vm_offset_t eoffset;
2909
2910                 /*
2911                  * test the pages to see if they have been modified directly
2912                  * by users through the VM system.
2913                  */
2914                 for (i = 0; i < bp->b_npages; i++)
2915                         vm_page_test_dirty(bp->b_pages[i]);
2916
2917                 /*
2918                  * Calculate the encompassing dirty range, boffset and eoffset,
2919                  * (eoffset - boffset) bytes.
2920                  */
2921
2922                 for (i = 0; i < bp->b_npages; i++) {
2923                         if (bp->b_pages[i]->dirty)
2924                                 break;
2925                 }
2926                 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2927
2928                 for (i = bp->b_npages - 1; i >= 0; --i) {
2929                         if (bp->b_pages[i]->dirty) {
2930                                 break;
2931                         }
2932                 }
2933                 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2934
2935                 /*
2936                  * Fit it to the buffer.
2937                  */
2938
2939                 if (eoffset > bp->b_bcount)
2940                         eoffset = bp->b_bcount;
2941
2942                 /*
2943                  * If we have a good dirty range, merge with the existing
2944                  * dirty range.
2945                  */
2946
2947                 if (boffset < eoffset) {
2948                         if (bp->b_dirtyoff > boffset)
2949                                 bp->b_dirtyoff = boffset;
2950                         if (bp->b_dirtyend < eoffset)
2951                                 bp->b_dirtyend = eoffset;
2952                 }
2953         }
2954 }
2955
2956 /*
2957  * Allocate the KVA mapping for an existing buffer. It handles the
2958  * cases of both B_UNMAPPED buffer, and buffer with the preallocated
2959  * KVA which is not mapped (B_KVAALLOC).
2960  */
2961 static void
2962 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
2963 {
2964         struct buf *scratch_bp;
2965         int bsize, maxsize, need_mapping, need_kva;
2966         off_t offset;
2967
2968         need_mapping = (bp->b_flags & B_UNMAPPED) != 0 &&
2969             (gbflags & GB_UNMAPPED) == 0;
2970         need_kva = (bp->b_flags & (B_KVAALLOC | B_UNMAPPED)) == B_UNMAPPED &&
2971             (gbflags & GB_KVAALLOC) != 0;
2972         if (!need_mapping && !need_kva)
2973                 return;
2974
2975         BUF_CHECK_UNMAPPED(bp);
2976
2977         if (need_mapping && (bp->b_flags & B_KVAALLOC) != 0) {
2978                 /*
2979                  * Buffer is not mapped, but the KVA was already
2980                  * reserved at the time of the instantiation.  Use the
2981                  * allocated space.
2982                  */
2983                 bp->b_flags &= ~B_KVAALLOC;
2984                 KASSERT(bp->b_kvaalloc != 0, ("kvaalloc == 0"));
2985                 bp->b_kvabase = bp->b_kvaalloc;
2986                 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
2987                 goto has_addr;
2988         }
2989
2990         /*
2991          * Calculate the amount of the address space we would reserve
2992          * if the buffer was mapped.
2993          */
2994         bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
2995         offset = blkno * bsize;
2996         maxsize = size + (offset & PAGE_MASK);
2997         maxsize = imax(maxsize, bsize);
2998
2999 mapping_loop:
3000         if (allocbufkva(bp, maxsize, gbflags)) {
3001                 /*
3002                  * Request defragmentation. getnewbuf() returns us the
3003                  * allocated space by the scratch buffer KVA.
3004                  */
3005                 scratch_bp = getnewbuf(bp->b_vp, 0, 0, size, maxsize, gbflags |
3006                     (GB_UNMAPPED | GB_KVAALLOC));
3007                 if (scratch_bp == NULL) {
3008                         if ((gbflags & GB_NOWAIT_BD) != 0) {
3009                                 /*
3010                                  * XXXKIB: defragmentation cannot
3011                                  * succeed, not sure what else to do.
3012                                  */
3013                                 panic("GB_NOWAIT_BD and B_UNMAPPED %p", bp);
3014                         }
3015                         atomic_add_int(&mappingrestarts, 1);
3016                         goto mapping_loop;
3017                 }
3018                 KASSERT((scratch_bp->b_flags & B_KVAALLOC) != 0,
3019                     ("scratch bp !B_KVAALLOC %p", scratch_bp));
3020                 setbufkva(bp, (vm_offset_t)scratch_bp->b_kvaalloc,
3021                     scratch_bp->b_kvasize, gbflags);
3022
3023                 /* Get rid of the scratch buffer. */
3024                 scratch_bp->b_kvasize = 0;
3025                 scratch_bp->b_flags |= B_INVAL;
3026                 scratch_bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
3027                 brelse(scratch_bp);
3028         }
3029         if (!need_mapping)
3030                 return;
3031
3032 has_addr:
3033         bp->b_saveaddr = bp->b_kvabase;
3034         bp->b_data = bp->b_saveaddr; /* b_offset is handled by bpmap_qenter */
3035         bp->b_flags &= ~B_UNMAPPED;
3036         BUF_CHECK_MAPPED(bp);
3037         bpmap_qenter(bp);
3038 }
3039
3040 /*
3041  *      getblk:
3042  *
3043  *      Get a block given a specified block and offset into a file/device.
3044  *      The buffers B_DONE bit will be cleared on return, making it almost
3045  *      ready for an I/O initiation.  B_INVAL may or may not be set on 
3046  *      return.  The caller should clear B_INVAL prior to initiating a
3047  *      READ.
3048  *
3049  *      For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3050  *      an existing buffer.
3051  *
3052  *      For a VMIO buffer, B_CACHE is modified according to the backing VM.
3053  *      If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3054  *      and then cleared based on the backing VM.  If the previous buffer is
3055  *      non-0-sized but invalid, B_CACHE will be cleared.
3056  *
3057  *      If getblk() must create a new buffer, the new buffer is returned with
3058  *      both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3059  *      case it is returned with B_INVAL clear and B_CACHE set based on the
3060  *      backing VM.
3061  *
3062  *      getblk() also forces a bwrite() for any B_DELWRI buffer whos
3063  *      B_CACHE bit is clear.
3064  *      
3065  *      What this means, basically, is that the caller should use B_CACHE to
3066  *      determine whether the buffer is fully valid or not and should clear
3067  *      B_INVAL prior to issuing a read.  If the caller intends to validate
3068  *      the buffer by loading its data area with something, the caller needs
3069  *      to clear B_INVAL.  If the caller does this without issuing an I/O, 
3070  *      the caller should set B_CACHE ( as an optimization ), else the caller
3071  *      should issue the I/O and biodone() will set B_CACHE if the I/O was
3072  *      a write attempt or if it was a successfull read.  If the caller 
3073  *      intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3074  *      prior to issuing the READ.  biodone() will *not* clear B_INVAL.
3075  */
3076 struct buf *
3077 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3078     int flags)
3079 {
3080         struct buf *bp;
3081         struct bufobj *bo;
3082         int bsize, error, maxsize, vmio;
3083         off_t offset;
3084
3085         CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3086         KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3087             ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3088         ASSERT_VOP_LOCKED(vp, "getblk");
3089         if (size > MAXBSIZE)
3090                 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
3091         if (!unmapped_buf_allowed)
3092                 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3093
3094         bo = &vp->v_bufobj;
3095 loop:
3096         /*
3097          * Block if we are low on buffers.   Certain processes are allowed
3098          * to completely exhaust the buffer cache.
3099          *
3100          * If this check ever becomes a bottleneck it may be better to
3101          * move it into the else, when gbincore() fails.  At the moment
3102          * it isn't a problem.
3103          */
3104         if (numfreebuffers == 0) {
3105                 if (TD_IS_IDLETHREAD(curthread))
3106                         return NULL;
3107                 mtx_lock(&nblock);
3108                 needsbuffer |= VFS_BIO_NEED_ANY;
3109                 mtx_unlock(&nblock);
3110         }
3111
3112         BO_LOCK(bo);
3113         bp = gbincore(bo, blkno);
3114         if (bp != NULL) {
3115                 int lockflags;
3116                 /*
3117                  * Buffer is in-core.  If the buffer is not busy, it must
3118                  * be on a queue.
3119                  */
3120                 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3121
3122                 if (flags & GB_LOCK_NOWAIT)
3123                         lockflags |= LK_NOWAIT;
3124
3125                 error = BUF_TIMELOCK(bp, lockflags,
3126                     BO_MTX(bo), "getblk", slpflag, slptimeo);
3127
3128                 /*
3129                  * If we slept and got the lock we have to restart in case
3130                  * the buffer changed identities.
3131                  */
3132                 if (error == ENOLCK)
3133                         goto loop;
3134                 /* We timed out or were interrupted. */
3135                 else if (error)
3136                         return (NULL);
3137                 /* If recursed, assume caller knows the rules. */
3138                 else if (BUF_LOCKRECURSED(bp))
3139                         goto end;
3140
3141                 /*
3142                  * The buffer is locked.  B_CACHE is cleared if the buffer is 
3143                  * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
3144                  * and for a VMIO buffer B_CACHE is adjusted according to the
3145                  * backing VM cache.
3146                  */
3147                 if (bp->b_flags & B_INVAL)
3148                         bp->b_flags &= ~B_CACHE;
3149                 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3150                         bp->b_flags |= B_CACHE;
3151                 BO_LOCK(bo);
3152                 bremfree(bp);
3153                 BO_UNLOCK(bo);
3154
3155                 /*
3156                  * check for size inconsistencies for non-VMIO case.
3157                  */
3158                 if (bp->b_bcount != size) {
3159                         if ((bp->b_flags & B_VMIO) == 0 ||
3160                             (size > bp->b_kvasize)) {
3161                                 if (bp->b_flags & B_DELWRI) {
3162                                         /*
3163                                          * If buffer is pinned and caller does
3164                                          * not want sleep  waiting for it to be
3165                                          * unpinned, bail out
3166                                          * */
3167                                         if (bp->b_pin_count > 0) {
3168                                                 if (flags & GB_LOCK_NOWAIT) {
3169                                                         bqrelse(bp);
3170                                                         return (NULL);
3171                                                 } else {
3172                                                         bunpin_wait(bp);
3173                                                 }
3174                                         }
3175                                         bp->b_flags |= B_NOCACHE;
3176                                         bwrite(bp);
3177                                 } else {
3178                                         if (LIST_EMPTY(&bp->b_dep)) {
3179                                                 bp->b_flags |= B_RELBUF;
3180                                                 brelse(bp);
3181                                         } else {
3182                                                 bp->b_flags |= B_NOCACHE;
3183                                                 bwrite(bp);
3184                                         }
3185                                 }
3186                                 goto loop;
3187                         }
3188                 }
3189
3190                 /*
3191                  * Handle the case of unmapped buffer which should
3192                  * become mapped, or the buffer for which KVA
3193                  * reservation is requested.
3194                  */
3195                 bp_unmapped_get_kva(bp, blkno, size, flags);
3196
3197                 /*
3198                  * If the size is inconsistant in the VMIO case, we can resize
3199                  * the buffer.  This might lead to B_CACHE getting set or
3200                  * cleared.  If the size has not changed, B_CACHE remains
3201                  * unchanged from its previous state.
3202                  */
3203                 if (bp->b_bcount != size)
3204                         allocbuf(bp, size);
3205
3206                 KASSERT(bp->b_offset != NOOFFSET, 
3207                     ("getblk: no buffer offset"));
3208
3209                 /*
3210                  * A buffer with B_DELWRI set and B_CACHE clear must
3211                  * be committed before we can return the buffer in
3212                  * order to prevent the caller from issuing a read
3213                  * ( due to B_CACHE not being set ) and overwriting
3214                  * it.
3215                  *
3216                  * Most callers, including NFS and FFS, need this to
3217                  * operate properly either because they assume they
3218                  * can issue a read if B_CACHE is not set, or because
3219                  * ( for example ) an uncached B_DELWRI might loop due 
3220                  * to softupdates re-dirtying the buffer.  In the latter
3221                  * case, B_CACHE is set after the first write completes,
3222                  * preventing further loops.
3223                  * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
3224                  * above while extending the buffer, we cannot allow the
3225                  * buffer to remain with B_CACHE set after the write
3226                  * completes or it will represent a corrupt state.  To
3227                  * deal with this we set B_NOCACHE to scrap the buffer
3228                  * after the write.
3229                  *
3230                  * We might be able to do something fancy, like setting
3231                  * B_CACHE in bwrite() except if B_DELWRI is already set,
3232                  * so the below call doesn't set B_CACHE, but that gets real
3233                  * confusing.  This is much easier.
3234                  */
3235
3236                 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3237                         bp->b_flags |= B_NOCACHE;
3238                         bwrite(bp);
3239                         goto loop;
3240                 }
3241                 bp->b_flags &= ~B_DONE;
3242         } else {
3243                 /*
3244                  * Buffer is not in-core, create new buffer.  The buffer
3245                  * returned by getnewbuf() is locked.  Note that the returned
3246                  * buffer is also considered valid (not marked B_INVAL).
3247                  */
3248                 BO_UNLOCK(bo);
3249                 /*
3250                  * If the user does not want us to create the buffer, bail out
3251                  * here.
3252                  */
3253                 if (flags & GB_NOCREAT)
3254                         return NULL;
3255                 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3256                 offset = blkno * bsize;
3257                 vmio = vp->v_object != NULL;
3258                 if (vmio) {
3259                         maxsize = size + (offset & PAGE_MASK);
3260                 } else {
3261                         maxsize = size;
3262                         /* Do not allow non-VMIO notmapped buffers. */
3263                         flags &= ~GB_UNMAPPED;
3264                 }
3265                 maxsize = imax(maxsize, bsize);
3266
3267                 bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
3268                 if (bp == NULL) {
3269                         if (slpflag || slptimeo)
3270                                 return NULL;
3271                         goto loop;
3272                 }
3273
3274                 /*
3275                  * This code is used to make sure that a buffer is not
3276                  * created while the getnewbuf routine is blocked.
3277                  * This can be a problem whether the vnode is locked or not.
3278                  * If the buffer is created out from under us, we have to
3279                  * throw away the one we just created.
3280                  *
3281                  * Note: this must occur before we associate the buffer
3282                  * with the vp especially considering limitations in
3283                  * the splay tree implementation when dealing with duplicate
3284                  * lblkno's.
3285                  */
3286                 BO_LOCK(bo);
3287                 if (gbincore(bo, blkno)) {
3288                         BO_UNLOCK(bo);
3289                         bp->b_flags |= B_INVAL;
3290                         brelse(bp);
3291                         goto loop;
3292                 }
3293
3294                 /*
3295                  * Insert the buffer into the hash, so that it can
3296                  * be found by incore.
3297                  */
3298                 bp->b_blkno = bp->b_lblkno = blkno;
3299                 bp->b_offset = offset;
3300                 bgetvp(vp, bp);
3301                 BO_UNLOCK(bo);
3302
3303                 /*
3304                  * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
3305                  * buffer size starts out as 0, B_CACHE will be set by
3306                  * allocbuf() for the VMIO case prior to it testing the
3307                  * backing store for validity.
3308                  */
3309
3310                 if (vmio) {
3311                         bp->b_flags |= B_VMIO;
3312                         KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3313                             ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3314                             bp, vp->v_object, bp->b_bufobj->bo_object));
3315                 } else {
3316                         bp->b_flags &= ~B_VMIO;
3317                         KASSERT(bp->b_bufobj->bo_object == NULL,
3318                             ("ARGH! has b_bufobj->bo_object %p %p\n",
3319                             bp, bp->b_bufobj->bo_object));
3320                         BUF_CHECK_MAPPED(bp);
3321                 }
3322
3323                 allocbuf(bp, size);
3324                 bp->b_flags &= ~B_DONE;
3325         }
3326         CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3327         BUF_ASSERT_HELD(bp);
3328 end:
3329         KASSERT(bp->b_bufobj == bo,
3330             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3331         return (bp);
3332 }
3333
3334 /*
3335  * Get an empty, disassociated buffer of given size.  The buffer is initially
3336  * set to B_INVAL.
3337  */
3338 struct buf *
3339 geteblk(int size, int flags)
3340 {
3341         struct buf *bp;
3342         int maxsize;
3343
3344         maxsize = (size + BKVAMASK) & ~BKVAMASK;
3345         while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
3346                 if ((flags & GB_NOWAIT_BD) &&
3347                     (curthread->td_pflags & TDP_BUFNEED) != 0)
3348                         return (NULL);
3349         }
3350         allocbuf(bp, size);
3351         bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3352         BUF_ASSERT_HELD(bp);
3353         return (bp);
3354 }
3355
3356
3357 /*
3358  * This code constitutes the buffer memory from either anonymous system
3359  * memory (in the case of non-VMIO operations) or from an associated
3360  * VM object (in the case of VMIO operations).  This code is able to
3361  * resize a buffer up or down.
3362  *
3363  * Note that this code is tricky, and has many complications to resolve
3364  * deadlock or inconsistant data situations.  Tread lightly!!! 
3365  * There are B_CACHE and B_DELWRI interactions that must be dealt with by 
3366  * the caller.  Calling this code willy nilly can result in the loss of data.
3367  *
3368  * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
3369  * B_CACHE for the non-VMIO case.
3370  */
3371
3372 int
3373 allocbuf(struct buf *bp, int size)
3374 {
3375         int newbsize, mbsize;
3376         int i;
3377
3378         BUF_ASSERT_HELD(bp);
3379
3380         if (bp->b_kvasize < size)
3381                 panic("allocbuf: buffer too small");
3382
3383         if ((bp->b_flags & B_VMIO) == 0) {
3384                 caddr_t origbuf;
3385                 int origbufsize;
3386                 /*
3387                  * Just get anonymous memory from the kernel.  Don't
3388                  * mess with B_CACHE.
3389                  */
3390                 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3391                 if (bp->b_flags & B_MALLOC)
3392                         newbsize = mbsize;
3393                 else
3394                         newbsize = round_page(size);
3395
3396                 if (newbsize < bp->b_bufsize) {
3397                         /*
3398                          * malloced buffers are not shrunk
3399                          */
3400                         if (bp->b_flags & B_MALLOC) {
3401                                 if (newbsize) {
3402                                         bp->b_bcount = size;
3403                                 } else {
3404                                         free(bp->b_data, M_BIOBUF);
3405                                         if (bp->b_bufsize) {
3406                                                 atomic_subtract_long(
3407                                                     &bufmallocspace,
3408                                                     bp->b_bufsize);
3409                                                 bufspacewakeup();
3410                                                 bp->b_bufsize = 0;
3411                                         }
3412                                         bp->b_saveaddr = bp->b_kvabase;
3413                                         bp->b_data = bp->b_saveaddr;
3414                                         bp->b_bcount = 0;
3415                                         bp->b_flags &= ~B_MALLOC;
3416                                 }
3417                                 return 1;
3418                         }               
3419                         vm_hold_free_pages(bp, newbsize);
3420                 } else if (newbsize > bp->b_bufsize) {
3421                         /*
3422                          * We only use malloced memory on the first allocation.
3423                          * and revert to page-allocated memory when the buffer
3424                          * grows.
3425                          */
3426                         /*
3427                          * There is a potential smp race here that could lead
3428                          * to bufmallocspace slightly passing the max.  It
3429                          * is probably extremely rare and not worth worrying
3430                          * over.
3431                          */
3432                         if ( (bufmallocspace < maxbufmallocspace) &&
3433                                 (bp->b_bufsize == 0) &&
3434                                 (mbsize <= PAGE_SIZE/2)) {
3435
3436                                 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
3437                                 bp->b_bufsize = mbsize;
3438                                 bp->b_bcount = size;
3439                                 bp->b_flags |= B_MALLOC;
3440                                 atomic_add_long(&bufmallocspace, mbsize);
3441                                 return 1;
3442                         }
3443                         origbuf = NULL;
3444                         origbufsize = 0;
3445                         /*
3446                          * If the buffer is growing on its other-than-first allocation,
3447                          * then we revert to the page-allocation scheme.
3448                          */
3449                         if (bp->b_flags & B_MALLOC) {
3450                                 origbuf = bp->b_data;
3451                                 origbufsize = bp->b_bufsize;
3452                                 bp->b_data = bp->b_kvabase;
3453                                 if (bp->b_bufsize) {
3454                                         atomic_subtract_long(&bufmallocspace,
3455                                             bp->b_bufsize);
3456                                         bufspacewakeup();
3457                                         bp->b_bufsize = 0;
3458                                 }
3459                                 bp->b_flags &= ~B_MALLOC;
3460                                 newbsize = round_page(newbsize);
3461                         }
3462                         vm_hold_load_pages(
3463                             bp,
3464                             (vm_offset_t) bp->b_data + bp->b_bufsize,
3465                             (vm_offset_t) bp->b_data + newbsize);
3466                         if (origbuf) {
3467                                 bcopy(origbuf, bp->b_data, origbufsize);
3468                                 free(origbuf, M_BIOBUF);
3469                         }
3470                 }
3471         } else {
3472                 int desiredpages;
3473
3474                 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3475                 desiredpages = (size == 0) ? 0 :
3476                         num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3477
3478                 if (bp->b_flags & B_MALLOC)
3479                         panic("allocbuf: VMIO buffer can't be malloced");
3480                 /*
3481                  * Set B_CACHE initially if buffer is 0 length or will become
3482                  * 0-length.
3483                  */
3484                 if (size == 0 || bp->b_bufsize == 0)
3485                         bp->b_flags |= B_CACHE;
3486
3487                 if (newbsize < bp->b_bufsize) {
3488                         /*
3489                          * DEV_BSIZE aligned new buffer size is less then the
3490                          * DEV_BSIZE aligned existing buffer size.  Figure out
3491                          * if we have to remove any pages.
3492                          */
3493                         if (desiredpages < bp->b_npages) {
3494                                 vm_page_t m;
3495
3496                                 if ((bp->b_flags & B_UNMAPPED) == 0) {
3497                                         BUF_CHECK_MAPPED(bp);
3498                                         pmap_qremove((vm_offset_t)trunc_page(
3499                                             (vm_offset_t)bp->b_data) +
3500                                             (desiredpages << PAGE_SHIFT),
3501                                             (bp->b_npages - desiredpages));
3502                                 } else
3503                                         BUF_CHECK_UNMAPPED(bp);
3504                                 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3505                                 for (i = desiredpages; i < bp->b_npages; i++) {
3506                                         /*
3507                                          * the page is not freed here -- it
3508                                          * is the responsibility of 
3509                                          * vnode_pager_setsize
3510                                          */
3511                                         m = bp->b_pages[i];
3512                                         KASSERT(m != bogus_page,
3513                                             ("allocbuf: bogus page found"));
3514                                         while (vm_page_sleep_if_busy(m, TRUE,
3515                                             "biodep"))
3516                                                 continue;
3517
3518                                         bp->b_pages[i] = NULL;
3519                                         vm_page_lock(m);
3520                                         vm_page_unwire(m, 0);
3521                                         vm_page_unlock(m);
3522                                 }
3523                                 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3524                                 bp->b_npages = desiredpages;
3525                         }
3526                 } else if (size > bp->b_bcount) {
3527                         /*
3528                          * We are growing the buffer, possibly in a 
3529                          * byte-granular fashion.
3530                          */
3531                         vm_object_t obj;
3532                         vm_offset_t toff;
3533                         vm_offset_t tinc;
3534
3535                         /*
3536                          * Step 1, bring in the VM pages from the object, 
3537                          * allocating them if necessary.  We must clear
3538                          * B_CACHE if these pages are not valid for the 
3539                          * range covered by the buffer.
3540                          */
3541
3542                         obj = bp->b_bufobj->bo_object;
3543
3544                         VM_OBJECT_LOCK(obj);
3545                         while (bp->b_npages < desiredpages) {
3546                                 vm_page_t m;
3547
3548                                 /*
3549                                  * We must allocate system pages since blocking
3550                                  * here could interfere with paging I/O, no
3551                                  * matter which process we are.
3552                                  *
3553                                  * We can only test VPO_BUSY here.  Blocking on
3554                                  * m->busy might lead to a deadlock:
3555                                  *  vm_fault->getpages->cluster_read->allocbuf
3556                                  * Thus, we specify VM_ALLOC_IGN_SBUSY.
3557                                  */
3558                                 m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) +
3559                                     bp->b_npages, VM_ALLOC_NOBUSY |
3560                                     VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3561                                     VM_ALLOC_RETRY | VM_ALLOC_IGN_SBUSY |
3562                                     VM_ALLOC_COUNT(desiredpages - bp->b_npages));
3563                                 if (m->valid == 0)
3564                                         bp->b_flags &= ~B_CACHE;
3565                                 bp->b_pages[bp->b_npages] = m;
3566                                 ++bp->b_npages;
3567                         }
3568
3569                         /*
3570                          * Step 2.  We've loaded the pages into the buffer,
3571                          * we have to figure out if we can still have B_CACHE
3572                          * set.  Note that B_CACHE is set according to the
3573                          * byte-granular range ( bcount and size ), new the
3574                          * aligned range ( newbsize ).
3575                          *
3576                          * The VM test is against m->valid, which is DEV_BSIZE
3577                          * aligned.  Needless to say, the validity of the data
3578                          * needs to also be DEV_BSIZE aligned.  Note that this
3579                          * fails with NFS if the server or some other client
3580                          * extends the file's EOF.  If our buffer is resized, 
3581                          * B_CACHE may remain set! XXX
3582                          */
3583
3584                         toff = bp->b_bcount;
3585                         tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3586
3587                         while ((bp->b_flags & B_CACHE) && toff < size) {
3588                                 vm_pindex_t pi;
3589
3590                                 if (tinc > (size - toff))
3591                                         tinc = size - toff;
3592
3593                                 pi = ((bp->b_offset & PAGE_MASK) + toff) >> 
3594                                     PAGE_SHIFT;
3595
3596                                 vfs_buf_test_cache(
3597                                     bp, 
3598                                     bp->b_offset,
3599                                     toff, 
3600                                     tinc, 
3601                                     bp->b_pages[pi]
3602                                 );
3603                                 toff += tinc;
3604                                 tinc = PAGE_SIZE;
3605                         }
3606                         VM_OBJECT_UNLOCK(obj);
3607
3608                         /*
3609                          * Step 3, fixup the KVM pmap.
3610                          */
3611                         if ((bp->b_flags & B_UNMAPPED) == 0)
3612                                 bpmap_qenter(bp);
3613                         else
3614                                 BUF_CHECK_UNMAPPED(bp);
3615                 }
3616         }
3617         if (newbsize < bp->b_bufsize)
3618                 bufspacewakeup();
3619         bp->b_bufsize = newbsize;       /* actual buffer allocation     */
3620         bp->b_bcount = size;            /* requested buffer size        */
3621         return 1;
3622 }
3623
3624 extern int inflight_transient_maps;
3625
3626 void
3627 biodone(struct bio *bp)
3628 {
3629         struct mtx *mtxp;
3630         void (*done)(struct bio *);
3631         vm_offset_t start, end;
3632         int transient;
3633
3634         mtxp = mtx_pool_find(mtxpool_sleep, bp);
3635         mtx_lock(mtxp);
3636         bp->bio_flags |= BIO_DONE;
3637         if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3638                 start = trunc_page((vm_offset_t)bp->bio_data);
3639                 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3640                 transient = 1;
3641         } else {
3642                 transient = 0;
3643                 start = end = 0;
3644         }
3645         done = bp->bio_done;
3646         if (done == NULL)
3647                 wakeup(bp);
3648         mtx_unlock(mtxp);
3649         if (done != NULL)
3650                 done(bp);
3651         if (transient) {
3652                 pmap_qremove(start, OFF_TO_IDX(end - start));
3653                 vm_map_remove(bio_transient_map, start, end);
3654                 atomic_add_int(&inflight_transient_maps, -1);
3655         }
3656 }
3657
3658 /*
3659  * Wait for a BIO to finish.
3660  *
3661  * XXX: resort to a timeout for now.  The optimal locking (if any) for this
3662  * case is not yet clear.
3663  */
3664 int
3665 biowait(struct bio *bp, const char *wchan)
3666 {
3667         struct mtx *mtxp;
3668
3669         mtxp = mtx_pool_find(mtxpool_sleep, bp);
3670         mtx_lock(mtxp);
3671         while ((bp->bio_flags & BIO_DONE) == 0)
3672                 msleep(bp, mtxp, PRIBIO, wchan, hz / 10);
3673         mtx_unlock(mtxp);
3674         if (bp->bio_error != 0)
3675                 return (bp->bio_error);
3676         if (!(bp->bio_flags & BIO_ERROR))
3677                 return (0);
3678         return (EIO);
3679 }
3680
3681 void
3682 biofinish(struct bio *bp, struct devstat *stat, int error)
3683 {
3684         
3685         if (error) {
3686                 bp->bio_error = error;
3687                 bp->bio_flags |= BIO_ERROR;
3688         }
3689         if (stat != NULL)
3690                 devstat_end_transaction_bio(stat, bp);
3691         biodone(bp);
3692 }
3693
3694 /*
3695  *      bufwait:
3696  *
3697  *      Wait for buffer I/O completion, returning error status.  The buffer
3698  *      is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
3699  *      error and cleared.
3700  */
3701 int
3702 bufwait(struct buf *bp)
3703 {
3704         if (bp->b_iocmd == BIO_READ)
3705                 bwait(bp, PRIBIO, "biord");
3706         else
3707                 bwait(bp, PRIBIO, "biowr");
3708         if (bp->b_flags & B_EINTR) {
3709                 bp->b_flags &= ~B_EINTR;
3710                 return (EINTR);
3711         }
3712         if (bp->b_ioflags & BIO_ERROR) {
3713                 return (bp->b_error ? bp->b_error : EIO);
3714         } else {
3715                 return (0);
3716         }
3717 }
3718
3719  /*
3720   * Call back function from struct bio back up to struct buf.
3721   */
3722 static void
3723 bufdonebio(struct bio *bip)
3724 {
3725         struct buf *bp;
3726
3727         bp = bip->bio_caller2;
3728         bp->b_resid = bp->b_bcount - bip->bio_completed;
3729         bp->b_resid = bip->bio_resid;   /* XXX: remove */
3730         bp->b_ioflags = bip->bio_flags;
3731         bp->b_error = bip->bio_error;
3732         if (bp->b_error)
3733                 bp->b_ioflags |= BIO_ERROR;
3734         bufdone(bp);
3735         g_destroy_bio(bip);
3736 }
3737
3738 void
3739 dev_strategy(struct cdev *dev, struct buf *bp)
3740 {
3741         struct cdevsw *csw;
3742         int ref;
3743
3744         KASSERT(dev->si_refcount > 0,
3745             ("dev_strategy on un-referenced struct cdev *(%s) %p",
3746             devtoname(dev), dev));
3747
3748         csw = dev_refthread(dev, &ref);
3749         dev_strategy_csw(dev, csw, bp);
3750         dev_relthread(dev, ref);
3751 }
3752
3753 void
3754 dev_strategy_csw(struct cdev *dev, struct cdevsw *csw, struct buf *bp)
3755 {
3756         struct bio *bip;
3757
3758         KASSERT(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE,
3759             ("b_iocmd botch"));
3760         KASSERT(((dev->si_flags & SI_ETERNAL) != 0 && csw != NULL) ||
3761             dev->si_threadcount > 0,
3762             ("dev_strategy_csw threadcount cdev *(%s) %p", devtoname(dev),
3763             dev));
3764         if (csw == NULL) {
3765                 bp->b_error = ENXIO;
3766                 bp->b_ioflags = BIO_ERROR;
3767                 bufdone(bp);
3768                 return;
3769         }
3770         for (;;) {
3771                 bip = g_new_bio();
3772                 if (bip != NULL)
3773                         break;
3774                 /* Try again later */
3775                 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3776         }
3777         bip->bio_cmd = bp->b_iocmd;
3778         bip->bio_offset = bp->b_iooffset;
3779         bip->bio_length = bp->b_bcount;
3780         bip->bio_bcount = bp->b_bcount; /* XXX: remove */
3781         bdata2bio(bp, bip);
3782         bip->bio_done = bufdonebio;
3783         bip->bio_caller2 = bp;
3784         bip->bio_dev = dev;
3785         (*csw->d_strategy)(bip);
3786 }
3787
3788 /*
3789  *      bufdone:
3790  *
3791  *      Finish I/O on a buffer, optionally calling a completion function.
3792  *      This is usually called from an interrupt so process blocking is
3793  *      not allowed.
3794  *
3795  *      biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3796  *      In a non-VMIO bp, B_CACHE will be set on the next getblk() 
3797  *      assuming B_INVAL is clear.
3798  *
3799  *      For the VMIO case, we set B_CACHE if the op was a read and no
3800  *      read error occured, or if the op was a write.  B_CACHE is never
3801  *      set if the buffer is invalid or otherwise uncacheable.
3802  *
3803  *      biodone does not mess with B_INVAL, allowing the I/O routine or the
3804  *      initiator to leave B_INVAL set to brelse the buffer out of existance
3805  *      in the biodone routine.
3806  */
3807 void
3808 bufdone(struct buf *bp)
3809 {
3810         struct bufobj *dropobj;
3811         void    (*biodone)(struct buf *);
3812
3813         CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3814         dropobj = NULL;
3815
3816         KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3817         BUF_ASSERT_HELD(bp);
3818
3819         runningbufwakeup(bp);
3820         if (bp->b_iocmd == BIO_WRITE)
3821                 dropobj = bp->b_bufobj;
3822         /* call optional completion function if requested */
3823         if (bp->b_iodone != NULL) {
3824                 biodone = bp->b_iodone;
3825                 bp->b_iodone = NULL;
3826                 (*biodone) (bp);
3827                 if (dropobj)
3828                         bufobj_wdrop(dropobj);
3829                 return;
3830         }
3831
3832         bufdone_finish(bp);
3833
3834         if (dropobj)
3835                 bufobj_wdrop(dropobj);
3836 }
3837
3838 void
3839 bufdone_finish(struct buf *bp)
3840 {
3841         BUF_ASSERT_HELD(bp);
3842
3843         if (!LIST_EMPTY(&bp->b_dep))
3844                 buf_complete(bp);
3845
3846         if (bp->b_flags & B_VMIO) {
3847                 vm_ooffset_t foff;
3848                 vm_page_t m;
3849                 vm_object_t obj;
3850                 struct vnode *vp;
3851                 int bogus, i, iosize;
3852
3853                 obj = bp->b_bufobj->bo_object;
3854                 KASSERT(obj->paging_in_progress >= bp->b_npages,
3855                     ("biodone_finish: paging in progress(%d) < b_npages(%d)",
3856                     obj->paging_in_progress, bp->b_npages));
3857
3858                 vp = bp->b_vp;
3859                 KASSERT(vp->v_holdcnt > 0,
3860                     ("biodone_finish: vnode %p has zero hold count", vp));
3861                 KASSERT(vp->v_object != NULL,
3862                     ("biodone_finish: vnode %p has no vm_object", vp));
3863
3864                 foff = bp->b_offset;
3865                 KASSERT(bp->b_offset != NOOFFSET,
3866                     ("biodone_finish: bp %p has no buffer offset", bp));
3867
3868                 /*
3869                  * Set B_CACHE if the op was a normal read and no error
3870                  * occured.  B_CACHE is set for writes in the b*write()
3871                  * routines.
3872                  */
3873                 iosize = bp->b_bcount - bp->b_resid;
3874                 if (bp->b_iocmd == BIO_READ &&
3875                     !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3876                     !(bp->b_ioflags & BIO_ERROR)) {
3877                         bp->b_flags |= B_CACHE;
3878                 }
3879                 bogus = 0;
3880                 VM_OBJECT_LOCK(obj);
3881                 for (i = 0; i < bp->b_npages; i++) {
3882                         int bogusflag = 0;
3883                         int resid;
3884
3885                         resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3886                         if (resid > iosize)
3887                                 resid = iosize;
3888
3889                         /*
3890                          * cleanup bogus pages, restoring the originals
3891                          */
3892                         m = bp->b_pages[i];
3893                         if (m == bogus_page) {
3894                                 bogus = bogusflag = 1;
3895                                 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3896                                 if (m == NULL)
3897                                         panic("biodone: page disappeared!");
3898                                 bp->b_pages[i] = m;
3899                         }
3900                         KASSERT(OFF_TO_IDX(foff) == m->pindex,
3901                             ("biodone_finish: foff(%jd)/pindex(%ju) mismatch",
3902                             (intmax_t)foff, (uintmax_t)m->pindex));
3903
3904                         /*
3905                          * In the write case, the valid and clean bits are
3906                          * already changed correctly ( see bdwrite() ), so we 
3907                          * only need to do this here in the read case.
3908                          */
3909                         if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3910                                 KASSERT((m->dirty & vm_page_bits(foff &
3911                                     PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3912                                     " page %p has unexpected dirty bits", m));
3913                                 vfs_page_set_valid(bp, foff, m);
3914                         }
3915
3916                         vm_page_io_finish(m);
3917                         vm_object_pip_subtract(obj, 1);
3918                         foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3919                         iosize -= resid;
3920                 }
3921                 vm_object_pip_wakeupn(obj, 0);
3922                 VM_OBJECT_UNLOCK(obj);
3923                 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
3924                         BUF_CHECK_MAPPED(bp);
3925                         pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3926                             bp->b_pages, bp->b_npages);
3927                 }
3928         }
3929
3930         /*
3931          * For asynchronous completions, release the buffer now. The brelse
3932          * will do a wakeup there if necessary - so no need to do a wakeup
3933          * here in the async case. The sync case always needs to do a wakeup.
3934          */
3935
3936         if (bp->b_flags & B_ASYNC) {
3937                 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3938                         brelse(bp);
3939                 else
3940                         bqrelse(bp);
3941         } else
3942                 bdone(bp);
3943 }
3944
3945 /*
3946  * This routine is called in lieu of iodone in the case of
3947  * incomplete I/O.  This keeps the busy status for pages
3948  * consistant.
3949  */
3950 void
3951 vfs_unbusy_pages(struct buf *bp)
3952 {
3953         int i;
3954         vm_object_t obj;
3955         vm_page_t m;
3956
3957         runningbufwakeup(bp);
3958         if (!(bp->b_flags & B_VMIO))
3959                 return;
3960
3961         obj = bp->b_bufobj->bo_object;
3962         VM_OBJECT_LOCK(obj);
3963         for (i = 0; i < bp->b_npages; i++) {
3964                 m = bp->b_pages[i];
3965                 if (m == bogus_page) {
3966                         m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3967                         if (!m)
3968                                 panic("vfs_unbusy_pages: page missing\n");
3969                         bp->b_pages[i] = m;
3970                         if ((bp->b_flags & B_UNMAPPED) == 0) {
3971                                 BUF_CHECK_MAPPED(bp);
3972                                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3973                                     bp->b_pages, bp->b_npages);
3974                         } else
3975                                 BUF_CHECK_UNMAPPED(bp);
3976                 }
3977                 vm_object_pip_subtract(obj, 1);
3978                 vm_page_io_finish(m);
3979         }
3980         vm_object_pip_wakeupn(obj, 0);
3981         VM_OBJECT_UNLOCK(obj);
3982 }
3983
3984 /*
3985  * vfs_page_set_valid:
3986  *
3987  *      Set the valid bits in a page based on the supplied offset.   The
3988  *      range is restricted to the buffer's size.
3989  *
3990  *      This routine is typically called after a read completes.
3991  */
3992 static void
3993 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3994 {
3995         vm_ooffset_t eoff;
3996
3997         /*
3998          * Compute the end offset, eoff, such that [off, eoff) does not span a
3999          * page boundary and eoff is not greater than the end of the buffer.
4000          * The end of the buffer, in this case, is our file EOF, not the
4001          * allocation size of the buffer.
4002          */
4003         eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
4004         if (eoff > bp->b_offset + bp->b_bcount)
4005                 eoff = bp->b_offset + bp->b_bcount;
4006
4007         /*
4008          * Set valid range.  This is typically the entire buffer and thus the
4009          * entire page.
4010          */
4011         if (eoff > off)
4012                 vm_page_set_valid(m, off & PAGE_MASK, eoff - off);
4013 }
4014
4015 /*
4016  * vfs_page_set_validclean:
4017  *
4018  *      Set the valid bits and clear the dirty bits in a page based on the
4019  *      supplied offset.   The range is restricted to the buffer's size.
4020  */
4021 static void
4022 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4023 {
4024         vm_ooffset_t soff, eoff;
4025
4026         /*
4027          * Start and end offsets in buffer.  eoff - soff may not cross a
4028          * page boundry or cross the end of the buffer.  The end of the
4029          * buffer, in this case, is our file EOF, not the allocation size
4030          * of the buffer.
4031          */
4032         soff = off;
4033         eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4034         if (eoff > bp->b_offset + bp->b_bcount)
4035                 eoff = bp->b_offset + bp->b_bcount;
4036
4037         /*
4038          * Set valid range.  This is typically the entire buffer and thus the
4039          * entire page.
4040          */
4041         if (eoff > soff) {
4042                 vm_page_set_validclean(
4043                     m,
4044                    (vm_offset_t) (soff & PAGE_MASK),
4045                    (vm_offset_t) (eoff - soff)
4046                 );
4047         }
4048 }
4049
4050 /*
4051  * Ensure that all buffer pages are not busied by VPO_BUSY flag. If
4052  * any page is busy, drain the flag.
4053  */
4054 static void
4055 vfs_drain_busy_pages(struct buf *bp)
4056 {
4057         vm_page_t m;
4058         int i, last_busied;
4059
4060         VM_OBJECT_LOCK_ASSERT(bp->b_bufobj->bo_object, MA_OWNED);
4061         last_busied = 0;
4062         for (i = 0; i < bp->b_npages; i++) {
4063                 m = bp->b_pages[i];
4064                 if ((m->oflags & VPO_BUSY) != 0) {
4065                         for (; last_busied < i; last_busied++)
4066                                 vm_page_busy(bp->b_pages[last_busied]);
4067                         while ((m->oflags & VPO_BUSY) != 0)
4068                                 vm_page_sleep(m, "vbpage");
4069                 }
4070         }
4071         for (i = 0; i < last_busied; i++)
4072                 vm_page_wakeup(bp->b_pages[i]);
4073 }
4074
4075 /*
4076  * This routine is called before a device strategy routine.
4077  * It is used to tell the VM system that paging I/O is in
4078  * progress, and treat the pages associated with the buffer
4079  * almost as being VPO_BUSY.  Also the object paging_in_progress
4080  * flag is handled to make sure that the object doesn't become
4081  * inconsistant.
4082  *
4083  * Since I/O has not been initiated yet, certain buffer flags
4084  * such as BIO_ERROR or B_INVAL may be in an inconsistant state
4085  * and should be ignored.
4086  */
4087 void
4088 vfs_busy_pages(struct buf *bp, int clear_modify)
4089 {
4090         int i, bogus;
4091         vm_object_t obj;
4092         vm_ooffset_t foff;
4093         vm_page_t m;
4094
4095         if (!(bp->b_flags & B_VMIO))
4096                 return;
4097
4098         obj = bp->b_bufobj->bo_object;
4099         foff = bp->b_offset;
4100         KASSERT(bp->b_offset != NOOFFSET,
4101             ("vfs_busy_pages: no buffer offset"));
4102         VM_OBJECT_LOCK(obj);
4103         vfs_drain_busy_pages(bp);
4104         if (bp->b_bufsize != 0)
4105                 vfs_setdirty_locked_object(bp);
4106         bogus = 0;
4107         for (i = 0; i < bp->b_npages; i++) {
4108                 m = bp->b_pages[i];
4109
4110                 if ((bp->b_flags & B_CLUSTER) == 0) {
4111                         vm_object_pip_add(obj, 1);
4112                         vm_page_io_start(m);
4113                 }
4114                 /*
4115                  * When readying a buffer for a read ( i.e
4116                  * clear_modify == 0 ), it is important to do
4117                  * bogus_page replacement for valid pages in 
4118                  * partially instantiated buffers.  Partially 
4119                  * instantiated buffers can, in turn, occur when
4120                  * reconstituting a buffer from its VM backing store
4121                  * base.  We only have to do this if B_CACHE is
4122                  * clear ( which causes the I/O to occur in the
4123                  * first place ).  The replacement prevents the read
4124                  * I/O from overwriting potentially dirty VM-backed
4125                  * pages.  XXX bogus page replacement is, uh, bogus.
4126                  * It may not work properly with small-block devices.
4127                  * We need to find a better way.
4128                  */
4129                 if (clear_modify) {
4130                         pmap_remove_write(m);
4131                         vfs_page_set_validclean(bp, foff, m);
4132                 } else if (m->valid == VM_PAGE_BITS_ALL &&
4133                     (bp->b_flags & B_CACHE) == 0) {
4134                         bp->b_pages[i] = bogus_page;
4135                         bogus++;
4136                 }
4137                 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4138         }
4139         VM_OBJECT_UNLOCK(obj);
4140         if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
4141                 BUF_CHECK_MAPPED(bp);
4142                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4143                     bp->b_pages, bp->b_npages);
4144         }
4145 }
4146
4147 /*
4148  *      vfs_bio_set_valid:
4149  *
4150  *      Set the range within the buffer to valid.  The range is
4151  *      relative to the beginning of the buffer, b_offset.  Note that
4152  *      b_offset itself may be offset from the beginning of the first
4153  *      page.
4154  */
4155 void   
4156 vfs_bio_set_valid(struct buf *bp, int base, int size)
4157 {
4158         int i, n;
4159         vm_page_t m;
4160
4161         if (!(bp->b_flags & B_VMIO))
4162                 return;
4163
4164         /*
4165          * Fixup base to be relative to beginning of first page.
4166          * Set initial n to be the maximum number of bytes in the
4167          * first page that can be validated.
4168          */
4169         base += (bp->b_offset & PAGE_MASK);
4170         n = PAGE_SIZE - (base & PAGE_MASK);
4171
4172         VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
4173         for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4174                 m = bp->b_pages[i];
4175                 if (n > size)
4176                         n = size;
4177                 vm_page_set_valid(m, base & PAGE_MASK, n);
4178                 base += n;
4179                 size -= n;
4180                 n = PAGE_SIZE;
4181         }
4182         VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
4183 }
4184
4185 /*
4186  *      vfs_bio_clrbuf:
4187  *
4188  *      If the specified buffer is a non-VMIO buffer, clear the entire
4189  *      buffer.  If the specified buffer is a VMIO buffer, clear and
4190  *      validate only the previously invalid portions of the buffer.
4191  *      This routine essentially fakes an I/O, so we need to clear
4192  *      BIO_ERROR and B_INVAL.
4193  *
4194  *      Note that while we only theoretically need to clear through b_bcount,
4195  *      we go ahead and clear through b_bufsize.
4196  */
4197 void
4198 vfs_bio_clrbuf(struct buf *bp) 
4199 {
4200         int i, j, mask, sa, ea, slide;
4201
4202         if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4203                 clrbuf(bp);
4204                 return;
4205         }
4206         bp->b_flags &= ~B_INVAL;
4207         bp->b_ioflags &= ~BIO_ERROR;
4208         VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
4209         if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4210             (bp->b_offset & PAGE_MASK) == 0) {
4211                 if (bp->b_pages[0] == bogus_page)
4212                         goto unlock;
4213                 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4214                 VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
4215                 if ((bp->b_pages[0]->valid & mask) == mask)
4216                         goto unlock;
4217                 if ((bp->b_pages[0]->valid & mask) == 0) {
4218                         pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4219                         bp->b_pages[0]->valid |= mask;
4220                         goto unlock;
4221                 }
4222         }
4223         sa = bp->b_offset & PAGE_MASK;
4224         slide = 0;
4225         for (i = 0; i < bp->b_npages; i++, sa = 0) {
4226                 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4227                 ea = slide & PAGE_MASK;
4228                 if (ea == 0)
4229                         ea = PAGE_SIZE;
4230                 if (bp->b_pages[i] == bogus_page)
4231                         continue;
4232                 j = sa / DEV_BSIZE;
4233                 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4234                 VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
4235                 if ((bp->b_pages[i]->valid & mask) == mask)
4236                         continue;
4237                 if ((bp->b_pages[i]->valid & mask) == 0)
4238                         pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4239                 else {
4240                         for (; sa < ea; sa += DEV_BSIZE, j++) {
4241                                 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4242                                         pmap_zero_page_area(bp->b_pages[i],
4243                                             sa, DEV_BSIZE);
4244                                 }
4245                         }
4246                 }
4247                 bp->b_pages[i]->valid |= mask;
4248         }
4249 unlock:
4250         VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
4251         bp->b_resid = 0;
4252 }
4253
4254 void
4255 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4256 {
4257         vm_page_t m;
4258         int i, n;
4259
4260         if ((bp->b_flags & B_UNMAPPED) == 0) {
4261                 BUF_CHECK_MAPPED(bp);
4262                 bzero(bp->b_data + base, size);
4263         } else {
4264                 BUF_CHECK_UNMAPPED(bp);
4265                 n = PAGE_SIZE - (base & PAGE_MASK);
4266                 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
4267                 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4268                         m = bp->b_pages[i];
4269                         if (n > size)
4270                                 n = size;
4271                         pmap_zero_page_area(m, base & PAGE_MASK, n);
4272                         base += n;
4273                         size -= n;
4274                         n = PAGE_SIZE;
4275                 }
4276                 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
4277         }
4278 }
4279
4280 /*
4281  * vm_hold_load_pages and vm_hold_free_pages get pages into
4282  * a buffers address space.  The pages are anonymous and are
4283  * not associated with a file object.
4284  */
4285 static void
4286 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4287 {
4288         vm_offset_t pg;
4289         vm_page_t p;
4290         int index;
4291
4292         BUF_CHECK_MAPPED(bp);
4293
4294         to = round_page(to);
4295         from = round_page(from);
4296         index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4297
4298         for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4299 tryagain:
4300                 /*
4301                  * note: must allocate system pages since blocking here
4302                  * could interfere with paging I/O, no matter which
4303                  * process we are.
4304                  */
4305                 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4306                     VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4307                 if (p == NULL) {
4308                         VM_WAIT;
4309                         goto tryagain;
4310                 }
4311                 pmap_qenter(pg, &p, 1);
4312                 bp->b_pages[index] = p;
4313         }
4314         bp->b_npages = index;
4315 }
4316
4317 /* Return pages associated with this buf to the vm system */
4318 static void
4319 vm_hold_free_pages(struct buf *bp, int newbsize)
4320 {
4321         vm_offset_t from;
4322         vm_page_t p;
4323         int index, newnpages;
4324
4325         BUF_CHECK_MAPPED(bp);
4326
4327         from = round_page((vm_offset_t)bp->b_data + newbsize);
4328         newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4329         if (bp->b_npages > newnpages)
4330                 pmap_qremove(from, bp->b_npages - newnpages);
4331         for (index = newnpages; index < bp->b_npages; index++) {
4332                 p = bp->b_pages[index];
4333                 bp->b_pages[index] = NULL;
4334                 if (p->busy != 0)
4335                         printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
4336                             (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
4337                 p->wire_count--;
4338                 vm_page_free(p);
4339                 atomic_subtract_int(&cnt.v_wire_count, 1);
4340         }
4341         bp->b_npages = newnpages;
4342 }
4343
4344 /*
4345  * Map an IO request into kernel virtual address space.
4346  *
4347  * All requests are (re)mapped into kernel VA space.
4348  * Notice that we use b_bufsize for the size of the buffer
4349  * to be mapped.  b_bcount might be modified by the driver.
4350  *
4351  * Note that even if the caller determines that the address space should
4352  * be valid, a race or a smaller-file mapped into a larger space may
4353  * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4354  * check the return value.
4355  */
4356 int
4357 vmapbuf(struct buf *bp, int mapbuf)
4358 {
4359         caddr_t kva;
4360         vm_prot_t prot;
4361         int pidx;
4362
4363         if (bp->b_bufsize < 0)
4364                 return (-1);
4365         prot = VM_PROT_READ;
4366         if (bp->b_iocmd == BIO_READ)
4367                 prot |= VM_PROT_WRITE;  /* Less backwards than it looks */
4368         if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4369             (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4370             btoc(MAXPHYS))) < 0)
4371                 return (-1);
4372         bp->b_npages = pidx;
4373         if (mapbuf || !unmapped_buf_allowed) {
4374                 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
4375                 kva = bp->b_saveaddr;
4376                 bp->b_saveaddr = bp->b_data;
4377                 bp->b_data = kva + (((vm_offset_t)bp->b_data) & PAGE_MASK);
4378                 bp->b_flags &= ~B_UNMAPPED;
4379         } else {
4380                 bp->b_flags |= B_UNMAPPED;
4381                 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4382                 bp->b_saveaddr = bp->b_data;
4383                 bp->b_data = unmapped_buf;
4384         }
4385         return(0);
4386 }
4387
4388 /*
4389  * Free the io map PTEs associated with this IO operation.
4390  * We also invalidate the TLB entries and restore the original b_addr.
4391  */
4392 void
4393 vunmapbuf(struct buf *bp)
4394 {
4395         int npages;
4396
4397         npages = bp->b_npages;
4398         if (bp->b_flags & B_UNMAPPED)
4399                 bp->b_flags &= ~B_UNMAPPED;
4400         else
4401                 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4402         vm_page_unhold_pages(bp->b_pages, npages);
4403         
4404         bp->b_data = bp->b_saveaddr;
4405 }
4406
4407 void
4408 bdone(struct buf *bp)
4409 {
4410         struct mtx *mtxp;
4411
4412         mtxp = mtx_pool_find(mtxpool_sleep, bp);
4413         mtx_lock(mtxp);
4414         bp->b_flags |= B_DONE;
4415         wakeup(bp);
4416         mtx_unlock(mtxp);
4417 }
4418
4419 void
4420 bwait(struct buf *bp, u_char pri, const char *wchan)
4421 {
4422         struct mtx *mtxp;
4423
4424         mtxp = mtx_pool_find(mtxpool_sleep, bp);
4425         mtx_lock(mtxp);
4426         while ((bp->b_flags & B_DONE) == 0)
4427                 msleep(bp, mtxp, pri, wchan, 0);
4428         mtx_unlock(mtxp);
4429 }
4430
4431 int
4432 bufsync(struct bufobj *bo, int waitfor)
4433 {
4434
4435         return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4436 }
4437
4438 void
4439 bufstrategy(struct bufobj *bo, struct buf *bp)
4440 {
4441         int i = 0;
4442         struct vnode *vp;
4443
4444         vp = bp->b_vp;
4445         KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4446         KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4447             ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4448         i = VOP_STRATEGY(vp, bp);
4449         KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4450 }
4451
4452 void
4453 bufobj_wrefl(struct bufobj *bo)
4454 {
4455
4456         KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4457         ASSERT_BO_LOCKED(bo);
4458         bo->bo_numoutput++;
4459 }
4460
4461 void
4462 bufobj_wref(struct bufobj *bo)
4463 {
4464
4465         KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4466         BO_LOCK(bo);
4467         bo->bo_numoutput++;
4468         BO_UNLOCK(bo);
4469 }
4470
4471 void
4472 bufobj_wdrop(struct bufobj *bo)
4473 {
4474
4475         KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4476         BO_LOCK(bo);
4477         KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4478         if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4479                 bo->bo_flag &= ~BO_WWAIT;
4480                 wakeup(&bo->bo_numoutput);
4481         }
4482         BO_UNLOCK(bo);
4483 }
4484
4485 int
4486 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4487 {
4488         int error;
4489
4490         KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4491         ASSERT_BO_LOCKED(bo);
4492         error = 0;
4493         while (bo->bo_numoutput) {
4494                 bo->bo_flag |= BO_WWAIT;
4495                 error = msleep(&bo->bo_numoutput, BO_MTX(bo),
4496                     slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4497                 if (error)
4498                         break;
4499         }
4500         return (error);
4501 }
4502
4503 void
4504 bpin(struct buf *bp)
4505 {
4506         struct mtx *mtxp;
4507
4508         mtxp = mtx_pool_find(mtxpool_sleep, bp);
4509         mtx_lock(mtxp);
4510         bp->b_pin_count++;
4511         mtx_unlock(mtxp);
4512 }
4513
4514 void
4515 bunpin(struct buf *bp)
4516 {
4517         struct mtx *mtxp;
4518
4519         mtxp = mtx_pool_find(mtxpool_sleep, bp);
4520         mtx_lock(mtxp);
4521         if (--bp->b_pin_count == 0)
4522                 wakeup(bp);
4523         mtx_unlock(mtxp);
4524 }
4525
4526 void
4527 bunpin_wait(struct buf *bp)
4528 {
4529         struct mtx *mtxp;
4530
4531         mtxp = mtx_pool_find(mtxpool_sleep, bp);
4532         mtx_lock(mtxp);
4533         while (bp->b_pin_count > 0)
4534                 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4535         mtx_unlock(mtxp);
4536 }
4537
4538 /*
4539  * Set bio_data or bio_ma for struct bio from the struct buf.
4540  */
4541 void
4542 bdata2bio(struct buf *bp, struct bio *bip)
4543 {
4544
4545         if ((bp->b_flags & B_UNMAPPED) != 0) {
4546                 KASSERT(unmapped_buf_allowed, ("unmapped"));
4547                 bip->bio_ma = bp->b_pages;
4548                 bip->bio_ma_n = bp->b_npages;
4549                 bip->bio_data = unmapped_buf;
4550                 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4551                 bip->bio_flags |= BIO_UNMAPPED;
4552                 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4553                     PAGE_SIZE == bp->b_npages,
4554                     ("Buffer %p too short: %d %jd %d", bp, bip->bio_ma_offset,
4555                     (uintmax_t)bip->bio_length, bip->bio_ma_n));
4556         } else {
4557                 bip->bio_data = bp->b_data;
4558                 bip->bio_ma = NULL;
4559         }
4560 }
4561
4562 #include "opt_ddb.h"
4563 #ifdef DDB
4564 #include <ddb/ddb.h>
4565
4566 /* DDB command to show buffer data */
4567 DB_SHOW_COMMAND(buffer, db_show_buffer)
4568 {
4569         /* get args */
4570         struct buf *bp = (struct buf *)addr;
4571
4572         if (!have_addr) {
4573                 db_printf("usage: show buffer <addr>\n");
4574                 return;
4575         }
4576
4577         db_printf("buf at %p\n", bp);
4578         db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4579             (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4580             PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4581         db_printf(
4582             "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4583             "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4584             "b_dep = %p\n",
4585             bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4586             bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4587             (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4588         if (bp->b_npages) {
4589                 int i;
4590                 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4591                 for (i = 0; i < bp->b_npages; i++) {
4592                         vm_page_t m;
4593                         m = bp->b_pages[i];
4594                         db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4595                             (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4596                         if ((i + 1) < bp->b_npages)
4597                                 db_printf(",");
4598                 }
4599                 db_printf("\n");
4600         }
4601         db_printf(" ");
4602         BUF_LOCKPRINTINFO(bp);
4603 }
4604
4605 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4606 {
4607         struct buf *bp;
4608         int i;
4609
4610         for (i = 0; i < nbuf; i++) {
4611                 bp = &buf[i];
4612                 if (BUF_ISLOCKED(bp)) {
4613                         db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4614                         db_printf("\n");
4615                 }
4616         }
4617 }
4618
4619 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4620 {
4621         struct vnode *vp;
4622         struct buf *bp;
4623
4624         if (!have_addr) {
4625                 db_printf("usage: show vnodebufs <addr>\n");
4626                 return;
4627         }
4628         vp = (struct vnode *)addr;
4629         db_printf("Clean buffers:\n");
4630         TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4631                 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4632                 db_printf("\n");
4633         }
4634         db_printf("Dirty buffers:\n");
4635         TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4636                 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4637                 db_printf("\n");
4638         }
4639 }
4640
4641 DB_COMMAND(countfreebufs, db_coundfreebufs)
4642 {
4643         struct buf *bp;
4644         int i, used = 0, nfree = 0;
4645
4646         if (have_addr) {
4647                 db_printf("usage: countfreebufs\n");
4648                 return;
4649         }
4650
4651         for (i = 0; i < nbuf; i++) {
4652                 bp = &buf[i];
4653                 if ((bp->b_vflags & BV_INFREECNT) != 0)
4654                         nfree++;
4655                 else
4656                         used++;
4657         }
4658
4659         db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4660             nfree + used);
4661         db_printf("numfreebuffers is %d\n", numfreebuffers);
4662 }
4663 #endif /* DDB */