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