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