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