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