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