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