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