5b6a55d99dbf8fce9e5f88568b53138201cd77b1
[dragonfly.git] / sys / kern / vfs_bio.c
1 /*
2  * Copyright (c) 1994,1997 John S. Dyson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice immediately at the beginning of the file, without modification,
10  *    this list of conditions, and the following disclaimer.
11  * 2. Absolutely no warranty of function or purpose is made by the author
12  *              John S. Dyson.
13  *
14  * $FreeBSD: src/sys/kern/vfs_bio.c,v 1.242.2.20 2003/05/28 18:38:10 alc Exp $
15  * $DragonFly: src/sys/kern/vfs_bio.c,v 1.115 2008/08/13 11:02:31 swildner Exp $
16  */
17
18 /*
19  * this file contains a new buffer I/O scheme implementing a coherent
20  * VM object and buffer cache scheme.  Pains have been taken to make
21  * sure that the performance degradation associated with schemes such
22  * as this is not realized.
23  *
24  * Author:  John S. Dyson
25  * Significant help during the development and debugging phases
26  * had been provided by David Greenman, also of the FreeBSD core team.
27  *
28  * see man buf(9) for more info.
29  */
30
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/buf.h>
34 #include <sys/conf.h>
35 #include <sys/eventhandler.h>
36 #include <sys/lock.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
41 #include <sys/proc.h>
42 #include <sys/reboot.h>
43 #include <sys/resourcevar.h>
44 #include <sys/sysctl.h>
45 #include <sys/vmmeter.h>
46 #include <sys/vnode.h>
47 #include <sys/proc.h>
48 #include <vm/vm.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_pageout.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_map.h>
56
57 #include <sys/buf2.h>
58 #include <sys/thread2.h>
59 #include <sys/spinlock2.h>
60 #include <sys/mplock2.h>
61 #include <vm/vm_page2.h>
62
63 #include "opt_ddb.h"
64 #ifdef DDB
65 #include <ddb/ddb.h>
66 #endif
67
68 /*
69  * Buffer queues.
70  */
71 enum bufq_type {
72         BQUEUE_NONE,            /* not on any queue */
73         BQUEUE_LOCKED,          /* locked buffers */
74         BQUEUE_CLEAN,           /* non-B_DELWRI buffers */
75         BQUEUE_DIRTY,           /* B_DELWRI buffers */
76         BQUEUE_DIRTY_HW,        /* B_DELWRI buffers - heavy weight */
77         BQUEUE_EMPTYKVA,        /* empty buffer headers with KVA assignment */
78         BQUEUE_EMPTY,           /* empty buffer headers */
79
80         BUFFER_QUEUES           /* number of buffer queues */
81 };
82
83 typedef enum bufq_type bufq_type_t;
84
85 #define BD_WAKE_SIZE    16384
86 #define BD_WAKE_MASK    (BD_WAKE_SIZE - 1)
87
88 TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES];
89 struct spinlock bufspin = SPINLOCK_INITIALIZER(&bufspin);
90
91 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
92
93 struct buf *buf;                /* buffer header pool */
94
95 static void vfs_clean_pages(struct buf *bp);
96 static void vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m);
97 static void vfs_vmio_release(struct buf *bp);
98 static int flushbufqueues(bufq_type_t q);
99 static vm_page_t bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit);
100
101 static void bd_signal(int totalspace);
102 static void buf_daemon(void);
103 static void buf_daemon_hw(void);
104
105 /*
106  * bogus page -- for I/O to/from partially complete buffers
107  * this is a temporary solution to the problem, but it is not
108  * really that bad.  it would be better to split the buffer
109  * for input in the case of buffers partially already in memory,
110  * but the code is intricate enough already.
111  */
112 vm_page_t bogus_page;
113
114 /*
115  * These are all static, but make the ones we export globals so we do
116  * not need to use compiler magic.
117  */
118 int bufspace, maxbufspace,
119         bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
120 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
121 static int lorunningspace, hirunningspace, runningbufreq;
122 int dirtybufspace, dirtybufspacehw, lodirtybufspace, hidirtybufspace;
123 int dirtybufcount, dirtybufcounthw;
124 int runningbufspace, runningbufcount;
125 static int getnewbufcalls;
126 static int getnewbufrestarts;
127 static int recoverbufcalls;
128 static int needsbuffer;         /* locked by needsbuffer_spin */
129 static int bd_request;          /* locked by needsbuffer_spin */
130 static int bd_request_hw;       /* locked by needsbuffer_spin */
131 static u_int bd_wake_ary[BD_WAKE_SIZE];
132 static u_int bd_wake_index;
133 static u_int vm_cycle_point = ACT_INIT + ACT_ADVANCE * 6;
134 static struct spinlock needsbuffer_spin;
135
136 static struct thread *bufdaemon_td;
137 static struct thread *bufdaemonhw_td;
138
139
140 /*
141  * Sysctls for operational control of the buffer cache.
142  */
143 SYSCTL_INT(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0,
144         "Number of dirty buffers to flush before bufdaemon becomes inactive");
145 SYSCTL_INT(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0,
146         "High watermark used to trigger explicit flushing of dirty buffers");
147 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
148         "Minimum amount of buffer space required for active I/O");
149 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
150         "Maximum amount of buffer space to usable for active I/O");
151 SYSCTL_UINT(_vfs, OID_AUTO, vm_cycle_point, CTLFLAG_RW, &vm_cycle_point, 0,
152         "Recycle pages to active or inactive queue transition pt 0-64");
153 /*
154  * Sysctls determining current state of the buffer cache.
155  */
156 SYSCTL_INT(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
157         "Total number of buffers in buffer cache");
158 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0,
159         "Pending bytes of dirty buffers (all)");
160 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0,
161         "Pending bytes of dirty buffers (heavy weight)");
162 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcount, CTLFLAG_RD, &dirtybufcount, 0,
163         "Pending number of dirty buffers");
164 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcounthw, CTLFLAG_RD, &dirtybufcounthw, 0,
165         "Pending number of dirty buffers (heavy weight)");
166 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
167         "I/O bytes currently in progress due to asynchronous writes");
168 SYSCTL_INT(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
169         "I/O buffers currently in progress due to asynchronous writes");
170 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
171         "Hard limit on maximum amount of memory usable for buffer space");
172 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
173         "Soft limit on maximum amount of memory usable for buffer space");
174 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
175         "Minimum amount of memory to reserve for system buffer space");
176 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
177         "Amount of memory available for buffers");
178 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
179         0, "Maximum amount of memory reserved for buffers using malloc");
180 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
181         "Amount of memory left for buffers using malloc-scheme");
182 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
183         "New buffer header acquisition requests");
184 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
185         0, "New buffer header acquisition restarts");
186 SYSCTL_INT(_vfs, OID_AUTO, recoverbufcalls, CTLFLAG_RD, &recoverbufcalls, 0,
187         "Recover VM space in an emergency");
188 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
189         "Buffer acquisition restarts due to fragmented buffer map");
190 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
191         "Amount of time KVA space was deallocated in an arbitrary buffer");
192 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
193         "Amount of time buffer re-use operations were successful");
194 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
195         "sizeof(struct buf)");
196
197 char *buf_wmesg = BUF_WMESG;
198
199 extern int vm_swap_size;
200
201 #define VFS_BIO_NEED_ANY        0x01    /* any freeable buffer */
202 #define VFS_BIO_NEED_UNUSED02   0x02
203 #define VFS_BIO_NEED_UNUSED04   0x04
204 #define VFS_BIO_NEED_BUFSPACE   0x08    /* wait for buf space, lo hysteresis */
205
206 /*
207  * bufspacewakeup:
208  *
209  *      Called when buffer space is potentially available for recovery.
210  *      getnewbuf() will block on this flag when it is unable to free 
211  *      sufficient buffer space.  Buffer space becomes recoverable when 
212  *      bp's get placed back in the queues.
213  */
214
215 static __inline void
216 bufspacewakeup(void)
217 {
218         /*
219          * If someone is waiting for BUF space, wake them up.  Even
220          * though we haven't freed the kva space yet, the waiting
221          * process will be able to now.
222          */
223         if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
224                 spin_lock_wr(&needsbuffer_spin);
225                 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
226                 spin_unlock_wr(&needsbuffer_spin);
227                 wakeup(&needsbuffer);
228         }
229 }
230
231 /*
232  * runningbufwakeup:
233  *
234  *      Accounting for I/O in progress.
235  *
236  */
237 static __inline void
238 runningbufwakeup(struct buf *bp)
239 {
240         int totalspace;
241         int limit;
242
243         if ((totalspace = bp->b_runningbufspace) != 0) {
244                 atomic_subtract_int(&runningbufspace, totalspace);
245                 atomic_subtract_int(&runningbufcount, 1);
246                 bp->b_runningbufspace = 0;
247
248                 /*
249                  * see waitrunningbufspace() for limit test.
250                  */
251                 limit = hirunningspace * 2 / 3;
252                 if (runningbufreq && runningbufspace <= limit) {
253                         runningbufreq = 0;
254                         wakeup(&runningbufreq);
255                 }
256                 bd_signal(totalspace);
257         }
258 }
259
260 /*
261  * bufcountwakeup:
262  *
263  *      Called when a buffer has been added to one of the free queues to
264  *      account for the buffer and to wakeup anyone waiting for free buffers.
265  *      This typically occurs when large amounts of metadata are being handled
266  *      by the buffer cache ( else buffer space runs out first, usually ).
267  *
268  * MPSAFE
269  */
270 static __inline void
271 bufcountwakeup(void) 
272 {
273         if (needsbuffer) {
274                 spin_lock_wr(&needsbuffer_spin);
275                 needsbuffer &= ~VFS_BIO_NEED_ANY;
276                 spin_unlock_wr(&needsbuffer_spin);
277                 wakeup(&needsbuffer);
278         }
279 }
280
281 /*
282  * waitrunningbufspace()
283  *
284  * Wait for the amount of running I/O to drop to hirunningspace * 2 / 3.
285  * This is the point where write bursting stops so we don't want to wait
286  * for the running amount to drop below it (at least if we still want bioq
287  * to burst writes).
288  *
289  * The caller may be using this function to block in a tight loop, we
290  * must block while runningbufspace is greater then or equal to
291  * hirunningspace * 2 / 3.
292  *
293  * And even with that it may not be enough, due to the presence of
294  * B_LOCKED dirty buffers, so also wait for at least one running buffer
295  * to complete.
296  */
297 static __inline void
298 waitrunningbufspace(void)
299 {
300         int limit = hirunningspace * 2 / 3;
301
302         crit_enter();
303         if (runningbufspace > limit) {
304                 while (runningbufspace > limit) {
305                         ++runningbufreq;
306                         tsleep(&runningbufreq, 0, "wdrn1", 0);
307                 }
308         } else if (runningbufspace) {
309                 ++runningbufreq;
310                 tsleep(&runningbufreq, 0, "wdrn2", 1);
311         }
312         crit_exit();
313 }
314
315 /*
316  * buf_dirty_count_severe:
317  *
318  *      Return true if we have too many dirty buffers.
319  */
320 int
321 buf_dirty_count_severe(void)
322 {
323         return (runningbufspace + dirtybufspace >= hidirtybufspace ||
324                 dirtybufcount >= nbuf / 2);
325 }
326
327 /*
328  * Return true if the amount of running I/O is severe and BIOQ should
329  * start bursting.
330  */
331 int
332 buf_runningbufspace_severe(void)
333 {
334         return (runningbufspace >= hirunningspace * 2 / 3);
335 }
336
337 /*
338  * vfs_buf_test_cache:
339  *
340  * Called when a buffer is extended.  This function clears the B_CACHE
341  * bit if the newly extended portion of the buffer does not contain
342  * valid data.
343  *
344  * NOTE! Dirty VM pages are not processed into dirty (B_DELWRI) buffer
345  * cache buffers.  The VM pages remain dirty, as someone had mmap()'d
346  * them while a clean buffer was present.
347  */
348 static __inline__
349 void
350 vfs_buf_test_cache(struct buf *bp,
351                   vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
352                   vm_page_t m)
353 {
354         if (bp->b_flags & B_CACHE) {
355                 int base = (foff + off) & PAGE_MASK;
356                 if (vm_page_is_valid(m, base, size) == 0)
357                         bp->b_flags &= ~B_CACHE;
358         }
359 }
360
361 /*
362  * bd_speedup()
363  *
364  * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the
365  * low water mark.
366  *
367  * MPSAFE
368  */
369 static __inline__
370 void
371 bd_speedup(void)
372 {
373         if (dirtybufspace < lodirtybufspace && dirtybufcount < nbuf / 2)
374                 return;
375
376         if (bd_request == 0 &&
377             (dirtybufspace - dirtybufspacehw > lodirtybufspace / 2 ||
378              dirtybufcount - dirtybufcounthw >= nbuf / 2)) {
379                 spin_lock_wr(&needsbuffer_spin);
380                 bd_request = 1;
381                 spin_unlock_wr(&needsbuffer_spin);
382                 wakeup(&bd_request);
383         }
384         if (bd_request_hw == 0 &&
385             (dirtybufspacehw > lodirtybufspace / 2 ||
386              dirtybufcounthw >= nbuf / 2)) {
387                 spin_lock_wr(&needsbuffer_spin);
388                 bd_request_hw = 1;
389                 spin_unlock_wr(&needsbuffer_spin);
390                 wakeup(&bd_request_hw);
391         }
392 }
393
394 /*
395  * bd_heatup()
396  *
397  *      Get the buf_daemon heated up when the number of running and dirty
398  *      buffers exceeds the mid-point.
399  *
400  *      Return the total number of dirty bytes past the second mid point
401  *      as a measure of how much excess dirty data there is in the system.
402  *
403  * MPSAFE
404  */
405 int
406 bd_heatup(void)
407 {
408         int mid1;
409         int mid2;
410         int totalspace;
411
412         mid1 = lodirtybufspace + (hidirtybufspace - lodirtybufspace) / 2;
413
414         totalspace = runningbufspace + dirtybufspace;
415         if (totalspace >= mid1 || dirtybufcount >= nbuf / 2) {
416                 bd_speedup();
417                 mid2 = mid1 + (hidirtybufspace - mid1) / 2;
418                 if (totalspace >= mid2)
419                         return(totalspace - mid2);
420         }
421         return(0);
422 }
423
424 /*
425  * bd_wait()
426  *
427  *      Wait for the buffer cache to flush (totalspace) bytes worth of
428  *      buffers, then return.
429  *
430  *      Regardless this function blocks while the number of dirty buffers
431  *      exceeds hidirtybufspace.
432  *
433  * MPSAFE
434  */
435 void
436 bd_wait(int totalspace)
437 {
438         u_int i;
439         int count;
440
441         if (curthread == bufdaemonhw_td || curthread == bufdaemon_td)
442                 return;
443
444         while (totalspace > 0) {
445                 bd_heatup();
446                 if (totalspace > runningbufspace + dirtybufspace)
447                         totalspace = runningbufspace + dirtybufspace;
448                 count = totalspace / BKVASIZE;
449                 if (count >= BD_WAKE_SIZE)
450                         count = BD_WAKE_SIZE - 1;
451
452                 spin_lock_wr(&needsbuffer_spin);
453                 i = (bd_wake_index + count) & BD_WAKE_MASK;
454                 ++bd_wake_ary[i];
455                 tsleep_interlock(&bd_wake_ary[i], 0);
456                 spin_unlock_wr(&needsbuffer_spin);
457                 tsleep(&bd_wake_ary[i], PINTERLOCKED, "flstik", hz);
458
459                 totalspace = runningbufspace + dirtybufspace - hidirtybufspace;
460         }
461 }
462
463 /*
464  * bd_signal()
465  * 
466  *      This function is called whenever runningbufspace or dirtybufspace
467  *      is reduced.  Track threads waiting for run+dirty buffer I/O
468  *      complete.
469  *
470  * MPSAFE
471  */
472 static void
473 bd_signal(int totalspace)
474 {
475         u_int i;
476
477         if (totalspace > 0) {
478                 if (totalspace > BKVASIZE * BD_WAKE_SIZE)
479                         totalspace = BKVASIZE * BD_WAKE_SIZE;
480                 spin_lock_wr(&needsbuffer_spin);
481                 while (totalspace > 0) {
482                         i = bd_wake_index++;
483                         i &= BD_WAKE_MASK;
484                         if (bd_wake_ary[i]) {
485                                 bd_wake_ary[i] = 0;
486                                 spin_unlock_wr(&needsbuffer_spin);
487                                 wakeup(&bd_wake_ary[i]);
488                                 spin_lock_wr(&needsbuffer_spin);
489                         }
490                         totalspace -= BKVASIZE;
491                 }
492                 spin_unlock_wr(&needsbuffer_spin);
493         }
494 }
495
496 /*
497  * BIO tracking support routines.
498  *
499  * Release a ref on a bio_track.  Wakeup requests are atomically released
500  * along with the last reference so bk_active will never wind up set to
501  * only 0x80000000.
502  *
503  * MPSAFE
504  */
505 static
506 void
507 bio_track_rel(struct bio_track *track)
508 {
509         int     active;
510         int     desired;
511
512         /*
513          * Shortcut
514          */
515         active = track->bk_active;
516         if (active == 1 && atomic_cmpset_int(&track->bk_active, 1, 0))
517                 return;
518
519         /*
520          * Full-on.  Note that the wait flag is only atomically released on
521          * the 1->0 count transition.
522          *
523          * We check for a negative count transition using bit 30 since bit 31
524          * has a different meaning.
525          */
526         for (;;) {
527                 desired = (active & 0x7FFFFFFF) - 1;
528                 if (desired)
529                         desired |= active & 0x80000000;
530                 if (atomic_cmpset_int(&track->bk_active, active, desired)) {
531                         if (desired & 0x40000000)
532                                 panic("bio_track_rel: bad count: %p\n", track);
533                         if (active & 0x80000000)
534                                 wakeup(track);
535                         break;
536                 }
537                 active = track->bk_active;
538         }
539 }
540
541 /*
542  * Wait for the tracking count to reach 0.
543  *
544  * Use atomic ops such that the wait flag is only set atomically when
545  * bk_active is non-zero.
546  *
547  * MPSAFE
548  */
549 int
550 bio_track_wait(struct bio_track *track, int slp_flags, int slp_timo)
551 {
552         int     active;
553         int     desired;
554         int     error;
555
556         /*
557          * Shortcut
558          */
559         if (track->bk_active == 0)
560                 return(0);
561
562         /*
563          * Full-on.  Note that the wait flag may only be atomically set if
564          * the active count is non-zero.
565          */
566         error = 0;
567         while ((active = track->bk_active) != 0) {
568                 desired = active | 0x80000000;
569                 tsleep_interlock(track, slp_flags);
570                 if (active == desired ||
571                     atomic_cmpset_int(&track->bk_active, active, desired)) {
572                         error = tsleep(track, slp_flags | PINTERLOCKED,
573                                        "iowait", slp_timo);
574                         if (error)
575                                 break;
576                 }
577         }
578         return (error);
579 }
580
581 /*
582  * bufinit:
583  *
584  *      Load time initialisation of the buffer cache, called from machine
585  *      dependant initialization code. 
586  */
587 void
588 bufinit(void)
589 {
590         struct buf *bp;
591         vm_offset_t bogus_offset;
592         int i;
593
594         spin_init(&needsbuffer_spin);
595
596         /* next, make a null set of free lists */
597         for (i = 0; i < BUFFER_QUEUES; i++)
598                 TAILQ_INIT(&bufqueues[i]);
599
600         /* finally, initialize each buffer header and stick on empty q */
601         for (i = 0; i < nbuf; i++) {
602                 bp = &buf[i];
603                 bzero(bp, sizeof *bp);
604                 bp->b_flags = B_INVAL;  /* we're just an empty header */
605                 bp->b_cmd = BUF_CMD_DONE;
606                 bp->b_qindex = BQUEUE_EMPTY;
607                 initbufbio(bp);
608                 xio_init(&bp->b_xio);
609                 buf_dep_init(bp);
610                 BUF_LOCKINIT(bp);
611                 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
612         }
613
614         /*
615          * maxbufspace is the absolute maximum amount of buffer space we are 
616          * allowed to reserve in KVM and in real terms.  The absolute maximum
617          * is nominally used by buf_daemon.  hibufspace is the nominal maximum
618          * used by most other processes.  The differential is required to 
619          * ensure that buf_daemon is able to run when other processes might 
620          * be blocked waiting for buffer space.
621          *
622          * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
623          * this may result in KVM fragmentation which is not handled optimally
624          * by the system.
625          */
626         maxbufspace = nbuf * BKVASIZE;
627         hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
628         lobufspace = hibufspace - MAXBSIZE;
629
630         lorunningspace = 512 * 1024;
631         /* hirunningspace -- see below */
632
633         /*
634          * Limit the amount of malloc memory since it is wired permanently
635          * into the kernel space.  Even though this is accounted for in
636          * the buffer allocation, we don't want the malloced region to grow
637          * uncontrolled.  The malloc scheme improves memory utilization
638          * significantly on average (small) directories.
639          */
640         maxbufmallocspace = hibufspace / 20;
641
642         /*
643          * Reduce the chance of a deadlock occuring by limiting the number
644          * of delayed-write dirty buffers we allow to stack up.
645          *
646          * We don't want too much actually queued to the device at once
647          * (XXX this needs to be per-mount!), because the buffers will
648          * wind up locked for a very long period of time while the I/O
649          * drains.
650          */
651         hidirtybufspace = hibufspace / 2;       /* dirty + running */
652         hirunningspace = hibufspace / 16;       /* locked & queued to device */
653         if (hirunningspace < 1024 * 1024)
654                 hirunningspace = 1024 * 1024;
655
656         dirtybufspace = 0;
657         dirtybufspacehw = 0;
658
659         lodirtybufspace = hidirtybufspace / 2;
660
661         /*
662          * Maximum number of async ops initiated per buf_daemon loop.  This is
663          * somewhat of a hack at the moment, we really need to limit ourselves
664          * based on the number of bytes of I/O in-transit that were initiated
665          * from buf_daemon.
666          */
667
668         bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
669         bogus_page = vm_page_alloc(&kernel_object,
670                                    (bogus_offset >> PAGE_SHIFT),
671                                    VM_ALLOC_NORMAL);
672         vmstats.v_wire_count++;
673
674 }
675
676 /*
677  * Initialize the embedded bio structures
678  */
679 void
680 initbufbio(struct buf *bp)
681 {
682         bp->b_bio1.bio_buf = bp;
683         bp->b_bio1.bio_prev = NULL;
684         bp->b_bio1.bio_offset = NOOFFSET;
685         bp->b_bio1.bio_next = &bp->b_bio2;
686         bp->b_bio1.bio_done = NULL;
687         bp->b_bio1.bio_flags = 0;
688
689         bp->b_bio2.bio_buf = bp;
690         bp->b_bio2.bio_prev = &bp->b_bio1;
691         bp->b_bio2.bio_offset = NOOFFSET;
692         bp->b_bio2.bio_next = NULL;
693         bp->b_bio2.bio_done = NULL;
694         bp->b_bio2.bio_flags = 0;
695 }
696
697 /*
698  * Reinitialize the embedded bio structures as well as any additional
699  * translation cache layers.
700  */
701 void
702 reinitbufbio(struct buf *bp)
703 {
704         struct bio *bio;
705
706         for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
707                 bio->bio_done = NULL;
708                 bio->bio_offset = NOOFFSET;
709         }
710 }
711
712 /*
713  * Push another BIO layer onto an existing BIO and return it.  The new
714  * BIO layer may already exist, holding cached translation data.
715  */
716 struct bio *
717 push_bio(struct bio *bio)
718 {
719         struct bio *nbio;
720
721         if ((nbio = bio->bio_next) == NULL) {
722                 int index = bio - &bio->bio_buf->b_bio_array[0];
723                 if (index >= NBUF_BIO - 1) {
724                         panic("push_bio: too many layers bp %p\n",
725                                 bio->bio_buf);
726                 }
727                 nbio = &bio->bio_buf->b_bio_array[index + 1];
728                 bio->bio_next = nbio;
729                 nbio->bio_prev = bio;
730                 nbio->bio_buf = bio->bio_buf;
731                 nbio->bio_offset = NOOFFSET;
732                 nbio->bio_done = NULL;
733                 nbio->bio_next = NULL;
734         }
735         KKASSERT(nbio->bio_done == NULL);
736         return(nbio);
737 }
738
739 /*
740  * Pop a BIO translation layer, returning the previous layer.  The
741  * must have been previously pushed.
742  */
743 struct bio *
744 pop_bio(struct bio *bio)
745 {
746         return(bio->bio_prev);
747 }
748
749 void
750 clearbiocache(struct bio *bio)
751 {
752         while (bio) {
753                 bio->bio_offset = NOOFFSET;
754                 bio = bio->bio_next;
755         }
756 }
757
758 /*
759  * bfreekva:
760  *
761  *      Free the KVA allocation for buffer 'bp'.
762  *
763  *      Must be called from a critical section as this is the only locking for
764  *      buffer_map.
765  *
766  *      Since this call frees up buffer space, we call bufspacewakeup().
767  *
768  * MPALMOSTSAFE
769  */
770 static void
771 bfreekva(struct buf *bp)
772 {
773         int count;
774
775         if (bp->b_kvasize) {
776                 get_mplock();
777                 ++buffreekvacnt;
778                 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
779                 vm_map_lock(&buffer_map);
780                 bufspace -= bp->b_kvasize;
781                 vm_map_delete(&buffer_map,
782                     (vm_offset_t) bp->b_kvabase,
783                     (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
784                     &count
785                 );
786                 vm_map_unlock(&buffer_map);
787                 vm_map_entry_release(count);
788                 bp->b_kvasize = 0;
789                 bufspacewakeup();
790                 rel_mplock();
791         }
792 }
793
794 /*
795  * bremfree:
796  *
797  *      Remove the buffer from the appropriate free list.
798  */
799 static __inline void
800 _bremfree(struct buf *bp)
801 {
802         if (bp->b_qindex != BQUEUE_NONE) {
803                 KASSERT(BUF_REFCNTNB(bp) == 1, 
804                                 ("bremfree: bp %p not locked",bp));
805                 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
806                 bp->b_qindex = BQUEUE_NONE;
807         } else {
808                 if (BUF_REFCNTNB(bp) <= 1)
809                         panic("bremfree: removing a buffer not on a queue");
810         }
811 }
812
813 void
814 bremfree(struct buf *bp)
815 {
816         spin_lock_wr(&bufspin);
817         _bremfree(bp);
818         spin_unlock_wr(&bufspin);
819 }
820
821 static void
822 bremfree_locked(struct buf *bp)
823 {
824         _bremfree(bp);
825 }
826
827 /*
828  * bread:
829  *
830  *      Get a buffer with the specified data.  Look in the cache first.  We
831  *      must clear B_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
832  *      is set, the buffer is valid and we do not have to do anything ( see
833  *      getblk() ).
834  *
835  * MPALMOSTSAFE
836  */
837 int
838 bread(struct vnode *vp, off_t loffset, int size, struct buf **bpp)
839 {
840         struct buf *bp;
841
842         bp = getblk(vp, loffset, size, 0, 0);
843         *bpp = bp;
844
845         /* if not found in cache, do some I/O */
846         if ((bp->b_flags & B_CACHE) == 0) {
847                 get_mplock();
848                 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
849                 bp->b_cmd = BUF_CMD_READ;
850                 bp->b_bio1.bio_done = biodone_sync;
851                 bp->b_bio1.bio_flags |= BIO_SYNC;
852                 vfs_busy_pages(vp, bp);
853                 vn_strategy(vp, &bp->b_bio1);
854                 rel_mplock();
855                 return (biowait(&bp->b_bio1, "biord"));
856         }
857         return (0);
858 }
859
860 /*
861  * breadn:
862  *
863  *      Operates like bread, but also starts asynchronous I/O on
864  *      read-ahead blocks.  We must clear B_ERROR and B_INVAL prior
865  *      to initiating I/O . If B_CACHE is set, the buffer is valid 
866  *      and we do not have to do anything.
867  *
868  * MPALMOSTSAFE
869  */
870 int
871 breadn(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
872         int *rabsize, int cnt, struct buf **bpp)
873 {
874         struct buf *bp, *rabp;
875         int i;
876         int rv = 0, readwait = 0;
877
878         *bpp = bp = getblk(vp, loffset, size, 0, 0);
879
880         /* if not found in cache, do some I/O */
881         if ((bp->b_flags & B_CACHE) == 0) {
882                 get_mplock();
883                 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
884                 bp->b_cmd = BUF_CMD_READ;
885                 bp->b_bio1.bio_done = biodone_sync;
886                 bp->b_bio1.bio_flags |= BIO_SYNC;
887                 vfs_busy_pages(vp, bp);
888                 vn_strategy(vp, &bp->b_bio1);
889                 ++readwait;
890                 rel_mplock();
891         }
892
893         for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
894                 if (inmem(vp, *raoffset))
895                         continue;
896                 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
897
898                 if ((rabp->b_flags & B_CACHE) == 0) {
899                         get_mplock();
900                         rabp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
901                         rabp->b_cmd = BUF_CMD_READ;
902                         vfs_busy_pages(vp, rabp);
903                         BUF_KERNPROC(rabp);
904                         vn_strategy(vp, &rabp->b_bio1);
905                         rel_mplock();
906                 } else {
907                         brelse(rabp);
908                 }
909         }
910         if (readwait)
911                 rv = biowait(&bp->b_bio1, "biord");
912         return (rv);
913 }
914
915 /*
916  * bwrite:
917  *
918  *      Synchronous write, waits for completion.
919  *
920  *      Write, release buffer on completion.  (Done by iodone
921  *      if async).  Do not bother writing anything if the buffer
922  *      is invalid.
923  *
924  *      Note that we set B_CACHE here, indicating that buffer is
925  *      fully valid and thus cacheable.  This is true even of NFS
926  *      now so we set it generally.  This could be set either here 
927  *      or in biodone() since the I/O is synchronous.  We put it
928  *      here.
929  */
930 int
931 bwrite(struct buf *bp)
932 {
933         int error;
934
935         if (bp->b_flags & B_INVAL) {
936                 brelse(bp);
937                 return (0);
938         }
939         if (BUF_REFCNTNB(bp) == 0)
940                 panic("bwrite: buffer is not busy???");
941
942         /* Mark the buffer clean */
943         bundirty(bp);
944
945         bp->b_flags &= ~(B_ERROR | B_EINTR);
946         bp->b_flags |= B_CACHE;
947         bp->b_cmd = BUF_CMD_WRITE;
948         bp->b_bio1.bio_done = biodone_sync;
949         bp->b_bio1.bio_flags |= BIO_SYNC;
950         vfs_busy_pages(bp->b_vp, bp);
951
952         /*
953          * Normal bwrites pipeline writes.  NOTE: b_bufsize is only
954          * valid for vnode-backed buffers.
955          */
956         bp->b_runningbufspace = bp->b_bufsize;
957         if (bp->b_runningbufspace) {
958                 runningbufspace += bp->b_runningbufspace;
959                 ++runningbufcount;
960         }
961
962         vn_strategy(bp->b_vp, &bp->b_bio1);
963         error = biowait(&bp->b_bio1, "biows");
964         brelse(bp);
965         return (error);
966 }
967
968 /*
969  * bawrite:
970  *
971  *      Asynchronous write.  Start output on a buffer, but do not wait for
972  *      it to complete.  The buffer is released when the output completes.
973  *
974  *      bwrite() ( or the VOP routine anyway ) is responsible for handling
975  *      B_INVAL buffers.  Not us.
976  */
977 void
978 bawrite(struct buf *bp)
979 {
980         if (bp->b_flags & B_INVAL) {
981                 brelse(bp);
982                 return;
983         }
984         if (BUF_REFCNTNB(bp) == 0)
985                 panic("bwrite: buffer is not busy???");
986
987         /* Mark the buffer clean */
988         bundirty(bp);
989
990         bp->b_flags &= ~(B_ERROR | B_EINTR);
991         bp->b_flags |= B_CACHE;
992         bp->b_cmd = BUF_CMD_WRITE;
993         KKASSERT(bp->b_bio1.bio_done == NULL);
994         vfs_busy_pages(bp->b_vp, bp);
995
996         /*
997          * Normal bwrites pipeline writes.  NOTE: b_bufsize is only
998          * valid for vnode-backed buffers.
999          */
1000         bp->b_runningbufspace = bp->b_bufsize;
1001         if (bp->b_runningbufspace) {
1002                 runningbufspace += bp->b_runningbufspace;
1003                 ++runningbufcount;
1004         }
1005
1006         BUF_KERNPROC(bp);
1007         vn_strategy(bp->b_vp, &bp->b_bio1);
1008 }
1009
1010 /*
1011  * bowrite:
1012  *
1013  *      Ordered write.  Start output on a buffer, and flag it so that the
1014  *      device will write it in the order it was queued.  The buffer is
1015  *      released when the output completes.  bwrite() ( or the VOP routine
1016  *      anyway ) is responsible for handling B_INVAL buffers.
1017  */
1018 int
1019 bowrite(struct buf *bp)
1020 {
1021         bp->b_flags |= B_ORDERED;
1022         bawrite(bp);
1023         return (0);
1024 }
1025
1026 /*
1027  * bdwrite:
1028  *
1029  *      Delayed write. (Buffer is marked dirty).  Do not bother writing
1030  *      anything if the buffer is marked invalid.
1031  *
1032  *      Note that since the buffer must be completely valid, we can safely
1033  *      set B_CACHE.  In fact, we have to set B_CACHE here rather then in
1034  *      biodone() in order to prevent getblk from writing the buffer
1035  *      out synchronously.
1036  */
1037 void
1038 bdwrite(struct buf *bp)
1039 {
1040         if (BUF_REFCNTNB(bp) == 0)
1041                 panic("bdwrite: buffer is not busy");
1042
1043         if (bp->b_flags & B_INVAL) {
1044                 brelse(bp);
1045                 return;
1046         }
1047         bdirty(bp);
1048
1049         /*
1050          * Set B_CACHE, indicating that the buffer is fully valid.  This is
1051          * true even of NFS now.
1052          */
1053         bp->b_flags |= B_CACHE;
1054
1055         /*
1056          * This bmap keeps the system from needing to do the bmap later,
1057          * perhaps when the system is attempting to do a sync.  Since it
1058          * is likely that the indirect block -- or whatever other datastructure
1059          * that the filesystem needs is still in memory now, it is a good
1060          * thing to do this.  Note also, that if the pageout daemon is
1061          * requesting a sync -- there might not be enough memory to do
1062          * the bmap then...  So, this is important to do.
1063          */
1064         if (bp->b_bio2.bio_offset == NOOFFSET) {
1065                 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
1066                          NULL, NULL, BUF_CMD_WRITE);
1067         }
1068
1069         /*
1070          * Because the underlying pages may still be mapped and
1071          * writable trying to set the dirty buffer (b_dirtyoff/end)
1072          * range here will be inaccurate.
1073          *
1074          * However, we must still clean the pages to satisfy the
1075          * vnode_pager and pageout daemon, so theythink the pages
1076          * have been "cleaned".  What has really occured is that
1077          * they've been earmarked for later writing by the buffer
1078          * cache.
1079          *
1080          * So we get the b_dirtyoff/end update but will not actually
1081          * depend on it (NFS that is) until the pages are busied for
1082          * writing later on.
1083          */
1084         vfs_clean_pages(bp);
1085         bqrelse(bp);
1086
1087         /*
1088          * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1089          * due to the softdep code.
1090          */
1091 }
1092
1093 /*
1094  * bdirty:
1095  *
1096  *      Turn buffer into delayed write request by marking it B_DELWRI.
1097  *      B_RELBUF and B_NOCACHE must be cleared.
1098  *
1099  *      We reassign the buffer to itself to properly update it in the
1100  *      dirty/clean lists. 
1101  *
1102  *      Must be called from a critical section.
1103  *      The buffer must be on BQUEUE_NONE.
1104  */
1105 void
1106 bdirty(struct buf *bp)
1107 {
1108         KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1109         if (bp->b_flags & B_NOCACHE) {
1110                 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
1111                 bp->b_flags &= ~B_NOCACHE;
1112         }
1113         if (bp->b_flags & B_INVAL) {
1114                 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
1115         }
1116         bp->b_flags &= ~B_RELBUF;
1117
1118         if ((bp->b_flags & B_DELWRI) == 0) {
1119                 bp->b_flags |= B_DELWRI;
1120                 reassignbuf(bp);
1121                 atomic_add_int(&dirtybufcount, 1);
1122                 dirtybufspace += bp->b_bufsize;
1123                 if (bp->b_flags & B_HEAVY) {
1124                         atomic_add_int(&dirtybufcounthw, 1);
1125                         atomic_add_int(&dirtybufspacehw, bp->b_bufsize);
1126                 }
1127                 bd_heatup();
1128         }
1129 }
1130
1131 /*
1132  * Set B_HEAVY, indicating that this is a heavy-weight buffer that
1133  * needs to be flushed with a different buf_daemon thread to avoid
1134  * deadlocks.  B_HEAVY also imposes restrictions in getnewbuf().
1135  */
1136 void
1137 bheavy(struct buf *bp)
1138 {
1139         if ((bp->b_flags & B_HEAVY) == 0) {
1140                 bp->b_flags |= B_HEAVY;
1141                 if (bp->b_flags & B_DELWRI) {
1142                         atomic_add_int(&dirtybufcounthw, 1);
1143                         atomic_add_int(&dirtybufspacehw, bp->b_bufsize);
1144                 }
1145         }
1146 }
1147
1148 /*
1149  * bundirty:
1150  *
1151  *      Clear B_DELWRI for buffer.
1152  *
1153  *      Must be called from a critical section.
1154  *
1155  *      The buffer is typically on BQUEUE_NONE but there is one case in 
1156  *      brelse() that calls this function after placing the buffer on
1157  *      a different queue.
1158  *
1159  * MPSAFE
1160  */
1161 void
1162 bundirty(struct buf *bp)
1163 {
1164         if (bp->b_flags & B_DELWRI) {
1165                 bp->b_flags &= ~B_DELWRI;
1166                 reassignbuf(bp);
1167                 atomic_subtract_int(&dirtybufcount, 1);
1168                 atomic_subtract_int(&dirtybufspace, bp->b_bufsize);
1169                 if (bp->b_flags & B_HEAVY) {
1170                         atomic_subtract_int(&dirtybufcounthw, 1);
1171                         atomic_subtract_int(&dirtybufspacehw, bp->b_bufsize);
1172                 }
1173                 bd_signal(bp->b_bufsize);
1174         }
1175         /*
1176          * Since it is now being written, we can clear its deferred write flag.
1177          */
1178         bp->b_flags &= ~B_DEFERRED;
1179 }
1180
1181 /*
1182  * brelse:
1183  *
1184  *      Release a busy buffer and, if requested, free its resources.  The
1185  *      buffer will be stashed in the appropriate bufqueue[] allowing it
1186  *      to be accessed later as a cache entity or reused for other purposes.
1187  *
1188  * MPALMOSTSAFE
1189  */
1190 void
1191 brelse(struct buf *bp)
1192 {
1193 #ifdef INVARIANTS
1194         int saved_flags = bp->b_flags;
1195 #endif
1196
1197         KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1198
1199         /*
1200          * If B_NOCACHE is set we are being asked to destroy the buffer and
1201          * its backing store.  Clear B_DELWRI.
1202          *
1203          * B_NOCACHE is set in two cases: (1) when the caller really wants
1204          * to destroy the buffer and backing store and (2) when the caller
1205          * wants to destroy the buffer and backing store after a write 
1206          * completes.
1207          */
1208         if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1209                 bundirty(bp);
1210         }
1211
1212         if ((bp->b_flags & (B_INVAL | B_DELWRI)) == B_DELWRI) {
1213                 /*
1214                  * A re-dirtied buffer is only subject to destruction
1215                  * by B_INVAL.  B_ERROR and B_NOCACHE are ignored.
1216                  */
1217                 /* leave buffer intact */
1218         } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1219                    (bp->b_bufsize <= 0)) {
1220                 /*
1221                  * Either a failed read or we were asked to free or not
1222                  * cache the buffer.  This path is reached with B_DELWRI
1223                  * set only if B_INVAL is already set.  B_NOCACHE governs
1224                  * backing store destruction.
1225                  *
1226                  * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1227                  * buffer cannot be immediately freed.
1228                  */
1229                 bp->b_flags |= B_INVAL;
1230                 if (LIST_FIRST(&bp->b_dep) != NULL) {
1231                         get_mplock();
1232                         buf_deallocate(bp);
1233                         rel_mplock();
1234                 }
1235                 if (bp->b_flags & B_DELWRI) {
1236                         atomic_subtract_int(&dirtybufcount, 1);
1237                         atomic_subtract_int(&dirtybufspace, bp->b_bufsize);
1238                         if (bp->b_flags & B_HEAVY) {
1239                                 atomic_subtract_int(&dirtybufcounthw, 1);
1240                                 atomic_subtract_int(&dirtybufspacehw, bp->b_bufsize);
1241                         }
1242                         bd_signal(bp->b_bufsize);
1243                 }
1244                 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1245         }
1246
1247         /*
1248          * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set.
1249          * If vfs_vmio_release() is called with either bit set, the
1250          * underlying pages may wind up getting freed causing a previous
1251          * write (bdwrite()) to get 'lost' because pages associated with
1252          * a B_DELWRI bp are marked clean.  Pages associated with a
1253          * B_LOCKED buffer may be mapped by the filesystem.
1254          *
1255          * If we want to release the buffer ourselves (rather then the
1256          * originator asking us to release it), give the originator a
1257          * chance to countermand the release by setting B_LOCKED.
1258          * 
1259          * We still allow the B_INVAL case to call vfs_vmio_release(), even
1260          * if B_DELWRI is set.
1261          *
1262          * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1263          * on pages to return pages to the VM page queues.
1264          */
1265         if (bp->b_flags & (B_DELWRI | B_LOCKED)) {
1266                 bp->b_flags &= ~B_RELBUF;
1267         } else if (vm_page_count_severe()) {
1268                 if (LIST_FIRST(&bp->b_dep) != NULL) {
1269                         get_mplock();
1270                         buf_deallocate(bp);             /* can set B_LOCKED */
1271                         rel_mplock();
1272                 }
1273                 if (bp->b_flags & (B_DELWRI | B_LOCKED))
1274                         bp->b_flags &= ~B_RELBUF;
1275                 else
1276                         bp->b_flags |= B_RELBUF;
1277         }
1278
1279         /*
1280          * Make sure b_cmd is clear.  It may have already been cleared by
1281          * biodone().
1282          *
1283          * At this point destroying the buffer is governed by the B_INVAL 
1284          * or B_RELBUF flags.
1285          */
1286         bp->b_cmd = BUF_CMD_DONE;
1287
1288         /*
1289          * VMIO buffer rundown.  Make sure the VM page array is restored
1290          * after an I/O may have replaces some of the pages with bogus pages
1291          * in order to not destroy dirty pages in a fill-in read.
1292          *
1293          * Note that due to the code above, if a buffer is marked B_DELWRI
1294          * then the B_RELBUF and B_NOCACHE bits will always be clear.
1295          * B_INVAL may still be set, however.
1296          *
1297          * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1298          * but not the backing store.   B_NOCACHE will destroy the backing
1299          * store.
1300          *
1301          * Note that dirty NFS buffers contain byte-granular write ranges
1302          * and should not be destroyed w/ B_INVAL even if the backing store
1303          * is left intact.
1304          */
1305         if (bp->b_flags & B_VMIO) {
1306                 /*
1307                  * Rundown for VMIO buffers which are not dirty NFS buffers.
1308                  */
1309                 int i, j, resid;
1310                 vm_page_t m;
1311                 off_t foff;
1312                 vm_pindex_t poff;
1313                 vm_object_t obj;
1314                 struct vnode *vp;
1315
1316                 vp = bp->b_vp;
1317
1318                 /*
1319                  * Get the base offset and length of the buffer.  Note that 
1320                  * in the VMIO case if the buffer block size is not
1321                  * page-aligned then b_data pointer may not be page-aligned.
1322                  * But our b_xio.xio_pages array *IS* page aligned.
1323                  *
1324                  * block sizes less then DEV_BSIZE (usually 512) are not 
1325                  * supported due to the page granularity bits (m->valid,
1326                  * m->dirty, etc...). 
1327                  *
1328                  * See man buf(9) for more information
1329                  */
1330
1331                 resid = bp->b_bufsize;
1332                 foff = bp->b_loffset;
1333
1334                 get_mplock();
1335                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1336                         m = bp->b_xio.xio_pages[i];
1337                         vm_page_flag_clear(m, PG_ZERO);
1338                         /*
1339                          * If we hit a bogus page, fixup *all* of them
1340                          * now.  Note that we left these pages wired
1341                          * when we removed them so they had better exist,
1342                          * and they cannot be ripped out from under us so
1343                          * no critical section protection is necessary.
1344                          */
1345                         if (m == bogus_page) {
1346                                 obj = vp->v_object;
1347                                 poff = OFF_TO_IDX(bp->b_loffset);
1348
1349                                 for (j = i; j < bp->b_xio.xio_npages; j++) {
1350                                         vm_page_t mtmp;
1351
1352                                         mtmp = bp->b_xio.xio_pages[j];
1353                                         if (mtmp == bogus_page) {
1354                                                 mtmp = vm_page_lookup(obj, poff + j);
1355                                                 if (!mtmp) {
1356                                                         panic("brelse: page missing");
1357                                                 }
1358                                                 bp->b_xio.xio_pages[j] = mtmp;
1359                                         }
1360                                 }
1361
1362                                 if ((bp->b_flags & B_INVAL) == 0) {
1363                                         pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1364                                                 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1365                                 }
1366                                 m = bp->b_xio.xio_pages[i];
1367                         }
1368
1369                         /*
1370                          * Invalidate the backing store if B_NOCACHE is set
1371                          * (e.g. used with vinvalbuf()).  If this is NFS
1372                          * we impose a requirement that the block size be
1373                          * a multiple of PAGE_SIZE and create a temporary
1374                          * hack to basically invalidate the whole page.  The
1375                          * problem is that NFS uses really odd buffer sizes
1376                          * especially when tracking piecemeal writes and
1377                          * it also vinvalbuf()'s a lot, which would result
1378                          * in only partial page validation and invalidation
1379                          * here.  If the file page is mmap()'d, however,
1380                          * all the valid bits get set so after we invalidate
1381                          * here we would end up with weird m->valid values
1382                          * like 0xfc.  nfs_getpages() can't handle this so
1383                          * we clear all the valid bits for the NFS case
1384                          * instead of just some of them.
1385                          *
1386                          * The real bug is the VM system having to set m->valid
1387                          * to VM_PAGE_BITS_ALL for faulted-in pages, which
1388                          * itself is an artifact of the whole 512-byte
1389                          * granular mess that exists to support odd block 
1390                          * sizes and UFS meta-data block sizes (e.g. 6144).
1391                          * A complete rewrite is required.
1392                          *
1393                          * XXX
1394                          */
1395                         if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1396                                 int poffset = foff & PAGE_MASK;
1397                                 int presid;
1398
1399                                 presid = PAGE_SIZE - poffset;
1400                                 if (bp->b_vp->v_tag == VT_NFS &&
1401                                     bp->b_vp->v_type == VREG) {
1402                                         ; /* entire page */
1403                                 } else if (presid > resid) {
1404                                         presid = resid;
1405                                 }
1406                                 KASSERT(presid >= 0, ("brelse: extra page"));
1407                                 vm_page_set_invalid(m, poffset, presid);
1408                         }
1409                         resid -= PAGE_SIZE - (foff & PAGE_MASK);
1410                         foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1411                 }
1412                 if (bp->b_flags & (B_INVAL | B_RELBUF))
1413                         vfs_vmio_release(bp);
1414                 rel_mplock();
1415         } else {
1416                 /*
1417                  * Rundown for non-VMIO buffers.
1418                  */
1419                 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1420                         get_mplock();
1421                         if (bp->b_bufsize)
1422                                 allocbuf(bp, 0);
1423                         KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1424                         if (bp->b_vp)
1425                                 brelvp(bp);
1426                         rel_mplock();
1427                 }
1428         }
1429                         
1430         if (bp->b_qindex != BQUEUE_NONE)
1431                 panic("brelse: free buffer onto another queue???");
1432         if (BUF_REFCNTNB(bp) > 1) {
1433                 /* Temporary panic to verify exclusive locking */
1434                 /* This panic goes away when we allow shared refs */
1435                 panic("brelse: multiple refs");
1436                 /* NOT REACHED */
1437                 return;
1438         }
1439
1440         /*
1441          * Figure out the correct queue to place the cleaned up buffer on.
1442          * Buffers placed in the EMPTY or EMPTYKVA had better already be
1443          * disassociated from their vnode.
1444          */
1445         spin_lock_wr(&bufspin);
1446         if (bp->b_flags & B_LOCKED) {
1447                 /*
1448                  * Buffers that are locked are placed in the locked queue
1449                  * immediately, regardless of their state.
1450                  */
1451                 bp->b_qindex = BQUEUE_LOCKED;
1452                 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1453         } else if (bp->b_bufsize == 0) {
1454                 /*
1455                  * Buffers with no memory.  Due to conditionals near the top
1456                  * of brelse() such buffers should probably already be
1457                  * marked B_INVAL and disassociated from their vnode.
1458                  */
1459                 bp->b_flags |= B_INVAL;
1460                 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1461                 KKASSERT((bp->b_flags & B_HASHED) == 0);
1462                 if (bp->b_kvasize) {
1463                         bp->b_qindex = BQUEUE_EMPTYKVA;
1464                 } else {
1465                         bp->b_qindex = BQUEUE_EMPTY;
1466                 }
1467                 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1468         } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) {
1469                 /*
1470                  * Buffers with junk contents.   Again these buffers had better
1471                  * already be disassociated from their vnode.
1472                  */
1473                 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1474                 KKASSERT((bp->b_flags & B_HASHED) == 0);
1475                 bp->b_flags |= B_INVAL;
1476                 bp->b_qindex = BQUEUE_CLEAN;
1477                 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1478         } else {
1479                 /*
1480                  * Remaining buffers.  These buffers are still associated with
1481                  * their vnode.
1482                  */
1483                 switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
1484                 case B_DELWRI:
1485                     bp->b_qindex = BQUEUE_DIRTY;
1486                     TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1487                     break;
1488                 case B_DELWRI | B_HEAVY:
1489                     bp->b_qindex = BQUEUE_DIRTY_HW;
1490                     TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY_HW], bp,
1491                                       b_freelist);
1492                     break;
1493                 default:
1494                     /*
1495                      * NOTE: Buffers are always placed at the end of the
1496                      * queue.  If B_AGE is not set the buffer will cycle
1497                      * through the queue twice.
1498                      */
1499                     bp->b_qindex = BQUEUE_CLEAN;
1500                     TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1501                     break;
1502                 }
1503         }
1504         spin_unlock_wr(&bufspin);
1505
1506         /*
1507          * If B_INVAL, clear B_DELWRI.  We've already placed the buffer
1508          * on the correct queue.
1509          */
1510         if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1511                 bundirty(bp);
1512
1513         /*
1514          * The bp is on an appropriate queue unless locked.  If it is not
1515          * locked or dirty we can wakeup threads waiting for buffer space.
1516          *
1517          * We've already handled the B_INVAL case ( B_DELWRI will be clear
1518          * if B_INVAL is set ).
1519          */
1520         if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1521                 bufcountwakeup();
1522
1523         /*
1524          * Something we can maybe free or reuse
1525          */
1526         if (bp->b_bufsize || bp->b_kvasize)
1527                 bufspacewakeup();
1528
1529         /*
1530          * Clean up temporary flags and unlock the buffer.
1531          */
1532         bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF | B_DIRECT);
1533         BUF_UNLOCK(bp);
1534 }
1535
1536 /*
1537  * bqrelse:
1538  *
1539  *      Release a buffer back to the appropriate queue but do not try to free
1540  *      it.  The buffer is expected to be used again soon.
1541  *
1542  *      bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1543  *      biodone() to requeue an async I/O on completion.  It is also used when
1544  *      known good buffers need to be requeued but we think we may need the data
1545  *      again soon.
1546  *
1547  *      XXX we should be able to leave the B_RELBUF hint set on completion.
1548  *
1549  * MPSAFE
1550  */
1551 void
1552 bqrelse(struct buf *bp)
1553 {
1554         KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1555
1556         if (bp->b_qindex != BQUEUE_NONE)
1557                 panic("bqrelse: free buffer onto another queue???");
1558         if (BUF_REFCNTNB(bp) > 1) {
1559                 /* do not release to free list */
1560                 panic("bqrelse: multiple refs");
1561                 return;
1562         }
1563
1564         buf_act_advance(bp);
1565
1566         spin_lock_wr(&bufspin);
1567         if (bp->b_flags & B_LOCKED) {
1568                 /*
1569                  * Locked buffers are released to the locked queue.  However,
1570                  * if the buffer is dirty it will first go into the dirty
1571                  * queue and later on after the I/O completes successfully it
1572                  * will be released to the locked queue.
1573                  */
1574                 bp->b_qindex = BQUEUE_LOCKED;
1575                 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1576         } else if (bp->b_flags & B_DELWRI) {
1577                 bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1578                                BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1579                 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1580         } else if (vm_page_count_severe()) {
1581                 /*
1582                  * We are too low on memory, we have to try to free the
1583                  * buffer (most importantly: the wired pages making up its
1584                  * backing store) *now*.
1585                  */
1586                 spin_unlock_wr(&bufspin);
1587                 brelse(bp);
1588                 return;
1589         } else {
1590                 bp->b_qindex = BQUEUE_CLEAN;
1591                 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1592         }
1593         spin_unlock_wr(&bufspin);
1594
1595         if ((bp->b_flags & B_LOCKED) == 0 &&
1596             ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1597                 bufcountwakeup();
1598         }
1599
1600         /*
1601          * Something we can maybe free or reuse.
1602          */
1603         if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1604                 bufspacewakeup();
1605
1606         /*
1607          * Final cleanup and unlock.  Clear bits that are only used while a
1608          * buffer is actively locked.
1609          */
1610         bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF);
1611         BUF_UNLOCK(bp);
1612 }
1613
1614 /*
1615  * vfs_vmio_release:
1616  *
1617  *      Return backing pages held by the buffer 'bp' back to the VM system
1618  *      if possible.  The pages are freed if they are no longer valid or
1619  *      attempt to free if it was used for direct I/O otherwise they are
1620  *      sent to the page cache.
1621  *
1622  *      Pages that were marked busy are left alone and skipped.
1623  *
1624  *      The KVA mapping (b_data) for the underlying pages is removed by
1625  *      this function.
1626  */
1627 static void
1628 vfs_vmio_release(struct buf *bp)
1629 {
1630         int i;
1631         vm_page_t m;
1632
1633         crit_enter();
1634         for (i = 0; i < bp->b_xio.xio_npages; i++) {
1635                 m = bp->b_xio.xio_pages[i];
1636                 bp->b_xio.xio_pages[i] = NULL;
1637
1638                 /*
1639                  * This is a very important bit of code.  We try to track
1640                  * VM page use whether the pages are wired into the buffer
1641                  * cache or not.  While wired into the buffer cache the
1642                  * bp tracks the act_count.
1643                  *
1644                  * We can choose to place unwired pages on the inactive
1645                  * queue (0) or active queue (1).  If we place too many
1646                  * on the active queue the queue will cycle the act_count
1647                  * on pages we'd like to keep, just from single-use pages
1648                  * (such as when doing a tar-up or file scan).
1649                  */
1650                 if (bp->b_act_count < vm_cycle_point)
1651                         vm_page_unwire(m, 0);
1652                 else
1653                         vm_page_unwire(m, 1);
1654
1655                 /*
1656                  * We don't mess with busy pages, it is
1657                  * the responsibility of the process that
1658                  * busied the pages to deal with them.
1659                  */
1660                 if ((m->flags & PG_BUSY) || (m->busy != 0))
1661                         continue;
1662                         
1663                 if (m->wire_count == 0) {
1664                         vm_page_flag_clear(m, PG_ZERO);
1665                         /*
1666                          * Might as well free the page if we can and it has
1667                          * no valid data.  We also free the page if the
1668                          * buffer was used for direct I/O.
1669                          */
1670 #if 0
1671                         if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1672                                         m->hold_count == 0) {
1673                                 vm_page_busy(m);
1674                                 vm_page_protect(m, VM_PROT_NONE);
1675                                 vm_page_free(m);
1676                         } else
1677 #endif
1678                         if (bp->b_flags & B_DIRECT) {
1679                                 vm_page_try_to_free(m);
1680                         } else if (vm_page_count_severe()) {
1681                                 m->act_count = bp->b_act_count;
1682                                 vm_page_try_to_cache(m);
1683                         } else {
1684                                 m->act_count = bp->b_act_count;
1685                         }
1686                 }
1687         }
1688         crit_exit();
1689         pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1690         if (bp->b_bufsize) {
1691                 bufspacewakeup();
1692                 bp->b_bufsize = 0;
1693         }
1694         bp->b_xio.xio_npages = 0;
1695         bp->b_flags &= ~B_VMIO;
1696         KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1697         if (bp->b_vp) {
1698                 get_mplock();
1699                 brelvp(bp);
1700                 rel_mplock();
1701         }
1702 }
1703
1704 /*
1705  * vfs_bio_awrite:
1706  *
1707  *      Implement clustered async writes for clearing out B_DELWRI buffers.
1708  *      This is much better then the old way of writing only one buffer at
1709  *      a time.  Note that we may not be presented with the buffers in the 
1710  *      correct order, so we search for the cluster in both directions.
1711  *
1712  *      The buffer is locked on call.
1713  */
1714 int
1715 vfs_bio_awrite(struct buf *bp)
1716 {
1717         int i;
1718         int j;
1719         off_t loffset = bp->b_loffset;
1720         struct vnode *vp = bp->b_vp;
1721         int nbytes;
1722         struct buf *bpa;
1723         int nwritten;
1724         int size;
1725
1726         /*
1727          * right now we support clustered writing only to regular files.  If
1728          * we find a clusterable block we could be in the middle of a cluster
1729          * rather then at the beginning.
1730          *
1731          * NOTE: b_bio1 contains the logical loffset and is aliased
1732          * to b_loffset.  b_bio2 contains the translated block number.
1733          */
1734         if ((vp->v_type == VREG) && 
1735             (vp->v_mount != 0) && /* Only on nodes that have the size info */
1736             (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1737
1738                 size = vp->v_mount->mnt_stat.f_iosize;
1739
1740                 for (i = size; i < MAXPHYS; i += size) {
1741                         if ((bpa = findblk(vp, loffset + i, FINDBLK_TEST)) &&
1742                             BUF_REFCNT(bpa) == 0 &&
1743                             ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1744                             (B_DELWRI | B_CLUSTEROK)) &&
1745                             (bpa->b_bufsize == size)) {
1746                                 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1747                                     (bpa->b_bio2.bio_offset !=
1748                                      bp->b_bio2.bio_offset + i))
1749                                         break;
1750                         } else {
1751                                 break;
1752                         }
1753                 }
1754                 for (j = size; i + j <= MAXPHYS && j <= loffset; j += size) {
1755                         if ((bpa = findblk(vp, loffset - j, FINDBLK_TEST)) &&
1756                             BUF_REFCNT(bpa) == 0 &&
1757                             ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1758                             (B_DELWRI | B_CLUSTEROK)) &&
1759                             (bpa->b_bufsize == size)) {
1760                                 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1761                                     (bpa->b_bio2.bio_offset !=
1762                                      bp->b_bio2.bio_offset - j))
1763                                         break;
1764                         } else {
1765                                 break;
1766                         }
1767                 }
1768                 j -= size;
1769                 nbytes = (i + j);
1770
1771                 /*
1772                  * this is a possible cluster write
1773                  */
1774                 if (nbytes != size) {
1775                         BUF_UNLOCK(bp);
1776                         nwritten = cluster_wbuild(vp, size,
1777                                                   loffset - j, nbytes);
1778                         return nwritten;
1779                 }
1780         }
1781
1782         /*
1783          * default (old) behavior, writing out only one block
1784          *
1785          * XXX returns b_bufsize instead of b_bcount for nwritten?
1786          */
1787         nwritten = bp->b_bufsize;
1788         bremfree(bp);
1789         bawrite(bp);
1790
1791         return nwritten;
1792 }
1793
1794 /*
1795  * getnewbuf:
1796  *
1797  *      Find and initialize a new buffer header, freeing up existing buffers 
1798  *      in the bufqueues as necessary.  The new buffer is returned locked.
1799  *
1800  *      Important:  B_INVAL is not set.  If the caller wishes to throw the
1801  *      buffer away, the caller must set B_INVAL prior to calling brelse().
1802  *
1803  *      We block if:
1804  *              We have insufficient buffer headers
1805  *              We have insufficient buffer space
1806  *              buffer_map is too fragmented ( space reservation fails )
1807  *              If we have to flush dirty buffers ( but we try to avoid this )
1808  *
1809  *      To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1810  *      Instead we ask the buf daemon to do it for us.  We attempt to
1811  *      avoid piecemeal wakeups of the pageout daemon.
1812  *
1813  * MPALMOSTSAFE
1814  */
1815 static struct buf *
1816 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1817 {
1818         struct buf *bp;
1819         struct buf *nbp;
1820         int defrag = 0;
1821         int nqindex;
1822         int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1823         static int flushingbufs;
1824
1825         /*
1826          * We can't afford to block since we might be holding a vnode lock,
1827          * which may prevent system daemons from running.  We deal with
1828          * low-memory situations by proactively returning memory and running
1829          * async I/O rather then sync I/O.
1830          */
1831         
1832         ++getnewbufcalls;
1833         --getnewbufrestarts;
1834 restart:
1835         ++getnewbufrestarts;
1836
1837         /*
1838          * Setup for scan.  If we do not have enough free buffers,
1839          * we setup a degenerate case that immediately fails.  Note
1840          * that if we are specially marked process, we are allowed to
1841          * dip into our reserves.
1842          *
1843          * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1844          *
1845          * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1846          * However, there are a number of cases (defragging, reusing, ...)
1847          * where we cannot backup.
1848          */
1849         nqindex = BQUEUE_EMPTYKVA;
1850         spin_lock_wr(&bufspin);
1851         nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1852
1853         if (nbp == NULL) {
1854                 /*
1855                  * If no EMPTYKVA buffers and we are either
1856                  * defragging or reusing, locate a CLEAN buffer
1857                  * to free or reuse.  If bufspace useage is low
1858                  * skip this step so we can allocate a new buffer.
1859                  */
1860                 if (defrag || bufspace >= lobufspace) {
1861                         nqindex = BQUEUE_CLEAN;
1862                         nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1863                 }
1864
1865                 /*
1866                  * If we could not find or were not allowed to reuse a
1867                  * CLEAN buffer, check to see if it is ok to use an EMPTY
1868                  * buffer.  We can only use an EMPTY buffer if allocating
1869                  * its KVA would not otherwise run us out of buffer space.
1870                  */
1871                 if (nbp == NULL && defrag == 0 &&
1872                     bufspace + maxsize < hibufspace) {
1873                         nqindex = BQUEUE_EMPTY;
1874                         nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1875                 }
1876         }
1877
1878         /*
1879          * Run scan, possibly freeing data and/or kva mappings on the fly
1880          * depending.
1881          *
1882          * WARNING!  bufspin is held!
1883          */
1884         while ((bp = nbp) != NULL) {
1885                 int qindex = nqindex;
1886
1887                 nbp = TAILQ_NEXT(bp, b_freelist);
1888
1889                 /*
1890                  * BQUEUE_CLEAN - B_AGE special case.  If not set the bp
1891                  * cycles through the queue twice before being selected.
1892                  */
1893                 if (qindex == BQUEUE_CLEAN && 
1894                     (bp->b_flags & B_AGE) == 0 && nbp) {
1895                         bp->b_flags |= B_AGE;
1896                         TAILQ_REMOVE(&bufqueues[qindex], bp, b_freelist);
1897                         TAILQ_INSERT_TAIL(&bufqueues[qindex], bp, b_freelist);
1898                         continue;
1899                 }
1900
1901                 /*
1902                  * Calculate next bp ( we can only use it if we do not block
1903                  * or do other fancy things ).
1904                  */
1905                 if (nbp == NULL) {
1906                         switch(qindex) {
1907                         case BQUEUE_EMPTY:
1908                                 nqindex = BQUEUE_EMPTYKVA;
1909                                 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1910                                         break;
1911                                 /* fall through */
1912                         case BQUEUE_EMPTYKVA:
1913                                 nqindex = BQUEUE_CLEAN;
1914                                 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1915                                         break;
1916                                 /* fall through */
1917                         case BQUEUE_CLEAN:
1918                                 /*
1919                                  * nbp is NULL. 
1920                                  */
1921                                 break;
1922                         }
1923                 }
1924
1925                 /*
1926                  * Sanity Checks
1927                  */
1928                 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1929
1930                 /*
1931                  * Note: we no longer distinguish between VMIO and non-VMIO
1932                  * buffers.
1933                  */
1934
1935                 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1936
1937                 /*
1938                  * If we are defragging then we need a buffer with 
1939                  * b_kvasize != 0.  XXX this situation should no longer
1940                  * occur, if defrag is non-zero the buffer's b_kvasize
1941                  * should also be non-zero at this point.  XXX
1942                  */
1943                 if (defrag && bp->b_kvasize == 0) {
1944                         kprintf("Warning: defrag empty buffer %p\n", bp);
1945                         continue;
1946                 }
1947
1948                 /*
1949                  * Start freeing the bp.  This is somewhat involved.  nbp
1950                  * remains valid only for BQUEUE_EMPTY[KVA] bp's.  Buffers
1951                  * on the clean list must be disassociated from their 
1952                  * current vnode.  Buffers on the empty[kva] lists have
1953                  * already been disassociated.
1954                  */
1955
1956                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1957                         spin_unlock_wr(&bufspin);
1958                         kprintf("getnewbuf: warning, locked buf %p, race corrected\n", bp);
1959                         tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1960                         goto restart;
1961                 }
1962                 if (bp->b_qindex != qindex) {
1963                         spin_unlock_wr(&bufspin);
1964                         kprintf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp, qindex, bp->b_qindex);
1965                         BUF_UNLOCK(bp);
1966                         goto restart;
1967                 }
1968                 bremfree_locked(bp);
1969                 spin_unlock_wr(&bufspin);
1970
1971                 /*
1972                  * Dependancies must be handled before we disassociate the
1973                  * vnode.
1974                  *
1975                  * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1976                  * be immediately disassociated.  HAMMER then becomes
1977                  * responsible for releasing the buffer.
1978                  *
1979                  * NOTE: bufspin is UNLOCKED now.
1980                  */
1981                 if (LIST_FIRST(&bp->b_dep) != NULL) {
1982                         get_mplock();
1983                         buf_deallocate(bp);
1984                         rel_mplock();
1985                         if (bp->b_flags & B_LOCKED) {
1986                                 bqrelse(bp);
1987                                 goto restart;
1988                         }
1989                         KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
1990                 }
1991
1992                 if (qindex == BQUEUE_CLEAN) {
1993                         get_mplock();
1994                         if (bp->b_flags & B_VMIO) {
1995                                 get_mplock();
1996                                 vfs_vmio_release(bp);
1997                                 rel_mplock();
1998                         }
1999                         if (bp->b_vp)
2000                                 brelvp(bp);
2001                         rel_mplock();
2002                 }
2003
2004                 /*
2005                  * NOTE:  nbp is now entirely invalid.  We can only restart
2006                  * the scan from this point on.
2007                  *
2008                  * Get the rest of the buffer freed up.  b_kva* is still
2009                  * valid after this operation.
2010                  */
2011
2012                 KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
2013                 KKASSERT((bp->b_flags & B_HASHED) == 0);
2014
2015                 /*
2016                  * critical section protection is not required when
2017                  * scrapping a buffer's contents because it is already 
2018                  * wired.
2019                  */
2020                 if (bp->b_bufsize) {
2021                         get_mplock();
2022                         allocbuf(bp, 0);
2023                         rel_mplock();
2024                 }
2025
2026                 bp->b_flags = B_BNOCLIP;
2027                 bp->b_cmd = BUF_CMD_DONE;
2028                 bp->b_vp = NULL;
2029                 bp->b_error = 0;
2030                 bp->b_resid = 0;
2031                 bp->b_bcount = 0;
2032                 bp->b_xio.xio_npages = 0;
2033                 bp->b_dirtyoff = bp->b_dirtyend = 0;
2034                 bp->b_act_count = ACT_INIT;
2035                 reinitbufbio(bp);
2036                 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2037                 buf_dep_init(bp);
2038                 if (blkflags & GETBLK_BHEAVY)
2039                         bp->b_flags |= B_HEAVY;
2040
2041                 /*
2042                  * If we are defragging then free the buffer.
2043                  */
2044                 if (defrag) {
2045                         bp->b_flags |= B_INVAL;
2046                         bfreekva(bp);
2047                         brelse(bp);
2048                         defrag = 0;
2049                         goto restart;
2050                 }
2051
2052                 /*
2053                  * If we are overcomitted then recover the buffer and its
2054                  * KVM space.  This occurs in rare situations when multiple
2055                  * processes are blocked in getnewbuf() or allocbuf().
2056                  */
2057                 if (bufspace >= hibufspace)
2058                         flushingbufs = 1;
2059                 if (flushingbufs && bp->b_kvasize != 0) {
2060                         bp->b_flags |= B_INVAL;
2061                         bfreekva(bp);
2062                         brelse(bp);
2063                         goto restart;
2064                 }
2065                 if (bufspace < lobufspace)
2066                         flushingbufs = 0;
2067                 break;
2068                 /* NOT REACHED, bufspin not held */
2069         }
2070
2071         /*
2072          * If we exhausted our list, sleep as appropriate.  We may have to
2073          * wakeup various daemons and write out some dirty buffers.
2074          *
2075          * Generally we are sleeping due to insufficient buffer space.
2076          *
2077          * NOTE: bufspin is held if bp is NULL, else it is not held.
2078          */
2079         if (bp == NULL) {
2080                 int flags;
2081                 char *waitmsg;
2082
2083                 spin_unlock_wr(&bufspin);
2084                 if (defrag) {
2085                         flags = VFS_BIO_NEED_BUFSPACE;
2086                         waitmsg = "nbufkv";
2087                 } else if (bufspace >= hibufspace) {
2088                         waitmsg = "nbufbs";
2089                         flags = VFS_BIO_NEED_BUFSPACE;
2090                 } else {
2091                         waitmsg = "newbuf";
2092                         flags = VFS_BIO_NEED_ANY;
2093                 }
2094
2095                 needsbuffer |= flags;
2096                 bd_speedup();   /* heeeelp */
2097                 while (needsbuffer & flags) {
2098                         if (tsleep(&needsbuffer, slpflags, waitmsg, slptimeo))
2099                                 return (NULL);
2100                 }
2101         } else {
2102                 /*
2103                  * We finally have a valid bp.  We aren't quite out of the
2104                  * woods, we still have to reserve kva space.  In order
2105                  * to keep fragmentation sane we only allocate kva in
2106                  * BKVASIZE chunks.
2107                  *
2108                  * (bufspin is not held)
2109                  */
2110                 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2111
2112                 if (maxsize != bp->b_kvasize) {
2113                         vm_offset_t addr = 0;
2114                         int count;
2115
2116                         bfreekva(bp);
2117
2118                         get_mplock();
2119                         count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2120                         vm_map_lock(&buffer_map);
2121
2122                         if (vm_map_findspace(&buffer_map,
2123                                     vm_map_min(&buffer_map), maxsize,
2124                                     maxsize, 0, &addr)) {
2125                                 /*
2126                                  * Uh oh.  Buffer map is too fragmented.  We
2127                                  * must defragment the map.
2128                                  */
2129                                 vm_map_unlock(&buffer_map);
2130                                 vm_map_entry_release(count);
2131                                 ++bufdefragcnt;
2132                                 defrag = 1;
2133                                 bp->b_flags |= B_INVAL;
2134                                 rel_mplock();
2135                                 brelse(bp);
2136                                 goto restart;
2137                         }
2138                         if (addr) {
2139                                 vm_map_insert(&buffer_map, &count,
2140                                         NULL, 0,
2141                                         addr, addr + maxsize,
2142                                         VM_MAPTYPE_NORMAL,
2143                                         VM_PROT_ALL, VM_PROT_ALL,
2144                                         MAP_NOFAULT);
2145
2146                                 bp->b_kvabase = (caddr_t) addr;
2147                                 bp->b_kvasize = maxsize;
2148                                 bufspace += bp->b_kvasize;
2149                                 ++bufreusecnt;
2150                         }
2151                         vm_map_unlock(&buffer_map);
2152                         vm_map_entry_release(count);
2153                         rel_mplock();
2154                 }
2155                 bp->b_data = bp->b_kvabase;
2156         }
2157         return(bp);
2158 }
2159
2160 /*
2161  * This routine is called in an emergency to recover VM pages from the
2162  * buffer cache by cashing in clean buffers.  The idea is to recover
2163  * enough pages to be able to satisfy a stuck bio_page_alloc().
2164  */
2165 static int
2166 recoverbufpages(void)
2167 {
2168         struct buf *bp;
2169         int bytes = 0;
2170
2171         ++recoverbufcalls;
2172
2173         spin_lock_wr(&bufspin);
2174         while (bytes < MAXBSIZE) {
2175                 bp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
2176                 if (bp == NULL)
2177                         break;
2178
2179                 /*
2180                  * BQUEUE_CLEAN - B_AGE special case.  If not set the bp
2181                  * cycles through the queue twice before being selected.
2182                  */
2183                 if ((bp->b_flags & B_AGE) == 0 && TAILQ_NEXT(bp, b_freelist)) {
2184                         bp->b_flags |= B_AGE;
2185                         TAILQ_REMOVE(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
2186                         TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN],
2187                                           bp, b_freelist);
2188                         continue;
2189                 }
2190
2191                 /*
2192                  * Sanity Checks
2193                  */
2194                 KKASSERT(bp->b_qindex == BQUEUE_CLEAN);
2195                 KKASSERT((bp->b_flags & B_DELWRI) == 0);
2196
2197                 /*
2198                  * Start freeing the bp.  This is somewhat involved.
2199                  *
2200                  * Buffers on the clean list must be disassociated from
2201                  * their current vnode
2202                  */
2203
2204                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
2205                         kprintf("recoverbufpages: warning, locked buf %p, race corrected\n", bp);
2206                         tsleep(&bd_request, 0, "gnbxxx", hz / 100);
2207                         continue;
2208                 }
2209                 if (bp->b_qindex != BQUEUE_CLEAN) {
2210                         kprintf("recoverbufpages: warning, BUF_LOCK blocked unexpectedly on buf %p index %d, race corrected\n", bp, bp->b_qindex);
2211                         BUF_UNLOCK(bp);
2212                         continue;
2213                 }
2214                 bremfree_locked(bp);
2215                 spin_unlock_wr(&bufspin);
2216
2217                 /*
2218                  * Dependancies must be handled before we disassociate the
2219                  * vnode.
2220                  *
2221                  * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2222                  * be immediately disassociated.  HAMMER then becomes
2223                  * responsible for releasing the buffer.
2224                  */
2225                 if (LIST_FIRST(&bp->b_dep) != NULL) {
2226                         buf_deallocate(bp);
2227                         if (bp->b_flags & B_LOCKED) {
2228                                 bqrelse(bp);
2229                                 spin_lock_wr(&bufspin);
2230                                 continue;
2231                         }
2232                         KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2233                 }
2234
2235                 bytes += bp->b_bufsize;
2236
2237                 get_mplock();
2238                 if (bp->b_flags & B_VMIO) {
2239                         bp->b_flags |= B_DIRECT;    /* try to free pages */
2240                         vfs_vmio_release(bp);
2241                 }
2242                 if (bp->b_vp)
2243                         brelvp(bp);
2244
2245                 KKASSERT(bp->b_vp == NULL);
2246                 KKASSERT((bp->b_flags & B_HASHED) == 0);
2247
2248                 /*
2249                  * critical section protection is not required when
2250                  * scrapping a buffer's contents because it is already 
2251                  * wired.
2252                  */
2253                 if (bp->b_bufsize)
2254                         allocbuf(bp, 0);
2255                 rel_mplock();
2256
2257                 bp->b_flags = B_BNOCLIP;
2258                 bp->b_cmd = BUF_CMD_DONE;
2259                 bp->b_vp = NULL;
2260                 bp->b_error = 0;
2261                 bp->b_resid = 0;
2262                 bp->b_bcount = 0;
2263                 bp->b_xio.xio_npages = 0;
2264                 bp->b_dirtyoff = bp->b_dirtyend = 0;
2265                 reinitbufbio(bp);
2266                 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2267                 buf_dep_init(bp);
2268                 bp->b_flags |= B_INVAL;
2269                 /* bfreekva(bp); */
2270                 brelse(bp);
2271                 spin_lock_wr(&bufspin);
2272         }
2273         spin_unlock_wr(&bufspin);
2274         return(bytes);
2275 }
2276
2277 /*
2278  * buf_daemon:
2279  *
2280  *      Buffer flushing daemon.  Buffers are normally flushed by the
2281  *      update daemon but if it cannot keep up this process starts to
2282  *      take the load in an attempt to prevent getnewbuf() from blocking.
2283  *
2284  *      Once a flush is initiated it does not stop until the number
2285  *      of buffers falls below lodirtybuffers, but we will wake up anyone
2286  *      waiting at the mid-point.
2287  */
2288
2289 static struct kproc_desc buf_kp = {
2290         "bufdaemon",
2291         buf_daemon,
2292         &bufdaemon_td
2293 };
2294 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2295         kproc_start, &buf_kp)
2296
2297 static struct kproc_desc bufhw_kp = {
2298         "bufdaemon_hw",
2299         buf_daemon_hw,
2300         &bufdaemonhw_td
2301 };
2302 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2303         kproc_start, &bufhw_kp)
2304
2305 static void
2306 buf_daemon(void)
2307 {
2308         int limit;
2309
2310         /*
2311          * This process needs to be suspended prior to shutdown sync.
2312          */
2313         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2314                               bufdaemon_td, SHUTDOWN_PRI_LAST);
2315         curthread->td_flags |= TDF_SYSTHREAD;
2316
2317         /*
2318          * This process is allowed to take the buffer cache to the limit
2319          */
2320         crit_enter();
2321
2322         for (;;) {
2323                 kproc_suspend_loop();
2324
2325                 /*
2326                  * Do the flush as long as the number of dirty buffers
2327                  * (including those running) exceeds lodirtybufspace.
2328                  *
2329                  * When flushing limit running I/O to hirunningspace
2330                  * Do the flush.  Limit the amount of in-transit I/O we
2331                  * allow to build up, otherwise we would completely saturate
2332                  * the I/O system.  Wakeup any waiting processes before we
2333                  * normally would so they can run in parallel with our drain.
2334                  *
2335                  * Our aggregate normal+HW lo water mark is lodirtybufspace,
2336                  * but because we split the operation into two threads we
2337                  * have to cut it in half for each thread.
2338                  */
2339                 waitrunningbufspace();
2340                 limit = lodirtybufspace / 2;
2341                 while (runningbufspace + dirtybufspace > limit ||
2342                        dirtybufcount - dirtybufcounthw >= nbuf / 2) {
2343                         if (flushbufqueues(BQUEUE_DIRTY) == 0)
2344                                 break;
2345                         if (runningbufspace < hirunningspace)
2346                                 continue;
2347                         waitrunningbufspace();
2348                 }
2349
2350                 /*
2351                  * We reached our low water mark, reset the
2352                  * request and sleep until we are needed again.
2353                  * The sleep is just so the suspend code works.
2354                  */
2355                 spin_lock_wr(&needsbuffer_spin);
2356                 if (bd_request == 0) {
2357                         ssleep(&bd_request, &needsbuffer_spin, 0,
2358                                "psleep", hz);
2359                 }
2360                 bd_request = 0;
2361                 spin_unlock_wr(&needsbuffer_spin);
2362         }
2363 }
2364
2365 static void
2366 buf_daemon_hw(void)
2367 {
2368         int limit;
2369
2370         /*
2371          * This process needs to be suspended prior to shutdown sync.
2372          */
2373         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2374                               bufdaemonhw_td, SHUTDOWN_PRI_LAST);
2375         curthread->td_flags |= TDF_SYSTHREAD;
2376
2377         /*
2378          * This process is allowed to take the buffer cache to the limit
2379          */
2380         crit_enter();
2381
2382         for (;;) {
2383                 kproc_suspend_loop();
2384
2385                 /*
2386                  * Do the flush.  Limit the amount of in-transit I/O we
2387                  * allow to build up, otherwise we would completely saturate
2388                  * the I/O system.  Wakeup any waiting processes before we
2389                  * normally would so they can run in parallel with our drain.
2390                  *
2391                  * Once we decide to flush push the queued I/O up to
2392                  * hirunningspace in order to trigger bursting by the bioq
2393                  * subsystem.
2394                  *
2395                  * Our aggregate normal+HW lo water mark is lodirtybufspace,
2396                  * but because we split the operation into two threads we
2397                  * have to cut it in half for each thread.
2398                  */
2399                 waitrunningbufspace();
2400                 limit = lodirtybufspace / 2;
2401                 while (runningbufspace + dirtybufspacehw > limit ||
2402                        dirtybufcounthw >= nbuf / 2) {
2403                         if (flushbufqueues(BQUEUE_DIRTY_HW) == 0)
2404                                 break;
2405                         if (runningbufspace < hirunningspace)
2406                                 continue;
2407                         waitrunningbufspace();
2408                 }
2409
2410                 /*
2411                  * We reached our low water mark, reset the
2412                  * request and sleep until we are needed again.
2413                  * The sleep is just so the suspend code works.
2414                  */
2415                 spin_lock_wr(&needsbuffer_spin);
2416                 if (bd_request_hw == 0) {
2417                         ssleep(&bd_request_hw, &needsbuffer_spin, 0,
2418                                "psleep", hz);
2419                 }
2420                 bd_request_hw = 0;
2421                 spin_unlock_wr(&needsbuffer_spin);
2422         }
2423 }
2424
2425 /*
2426  * flushbufqueues:
2427  *
2428  *      Try to flush a buffer in the dirty queue.  We must be careful to
2429  *      free up B_INVAL buffers instead of write them, which NFS is 
2430  *      particularly sensitive to.
2431  *
2432  *      B_RELBUF may only be set by VFSs.  We do set B_AGE to indicate
2433  *      that we really want to try to get the buffer out and reuse it
2434  *      due to the write load on the machine.
2435  */
2436 static int
2437 flushbufqueues(bufq_type_t q)
2438 {
2439         struct buf *bp;
2440         int r = 0;
2441         int spun;
2442
2443         spin_lock_wr(&bufspin);
2444         spun = 1;
2445
2446         bp = TAILQ_FIRST(&bufqueues[q]);
2447         while (bp) {
2448                 KASSERT((bp->b_flags & B_DELWRI),
2449                         ("unexpected clean buffer %p", bp));
2450
2451                 if (bp->b_flags & B_DELWRI) {
2452                         if (bp->b_flags & B_INVAL) {
2453                                 spin_unlock_wr(&bufspin);
2454                                 spun = 0;
2455                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2456                                         panic("flushbufqueues: locked buf");
2457                                 bremfree(bp);
2458                                 brelse(bp);
2459                                 ++r;
2460                                 break;
2461                         }
2462                         if (LIST_FIRST(&bp->b_dep) != NULL &&
2463                             (bp->b_flags & B_DEFERRED) == 0 &&
2464                             buf_countdeps(bp, 0)) {
2465                                 TAILQ_REMOVE(&bufqueues[q], bp, b_freelist);
2466                                 TAILQ_INSERT_TAIL(&bufqueues[q], bp,
2467                                                   b_freelist);
2468                                 bp->b_flags |= B_DEFERRED;
2469                                 bp = TAILQ_FIRST(&bufqueues[q]);
2470                                 continue;
2471                         }
2472
2473                         /*
2474                          * Only write it out if we can successfully lock
2475                          * it.  If the buffer has a dependancy,
2476                          * buf_checkwrite must also return 0 for us to
2477                          * be able to initate the write.
2478                          *
2479                          * If the buffer is flagged B_ERROR it may be
2480                          * requeued over and over again, we try to
2481                          * avoid a live lock.
2482                          */
2483                         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
2484                                 spin_unlock_wr(&bufspin);
2485                                 spun = 0;
2486                                 if (LIST_FIRST(&bp->b_dep) != NULL &&
2487                                     buf_checkwrite(bp)) {
2488                                         bremfree(bp);
2489                                         brelse(bp);
2490                                 } else if (bp->b_flags & B_ERROR) {
2491                                         tsleep(bp, 0, "bioer", 1);
2492                                         bp->b_flags &= ~B_AGE;
2493                                         vfs_bio_awrite(bp);
2494                                 } else {
2495                                         bp->b_flags |= B_AGE;
2496                                         vfs_bio_awrite(bp);
2497                                 }
2498                                 ++r;
2499                                 break;
2500                         }
2501                 }
2502                 bp = TAILQ_NEXT(bp, b_freelist);
2503         }
2504         if (spun)
2505                 spin_unlock_wr(&bufspin);
2506         return (r);
2507 }
2508
2509 /*
2510  * inmem:
2511  *
2512  *      Returns true if no I/O is needed to access the associated VM object.
2513  *      This is like findblk except it also hunts around in the VM system for
2514  *      the data.
2515  *
2516  *      Note that we ignore vm_page_free() races from interrupts against our
2517  *      lookup, since if the caller is not protected our return value will not
2518  *      be any more valid then otherwise once we exit the critical section.
2519  */
2520 int
2521 inmem(struct vnode *vp, off_t loffset)
2522 {
2523         vm_object_t obj;
2524         vm_offset_t toff, tinc, size;
2525         vm_page_t m;
2526
2527         if (findblk(vp, loffset, FINDBLK_TEST))
2528                 return 1;
2529         if (vp->v_mount == NULL)
2530                 return 0;
2531         if ((obj = vp->v_object) == NULL)
2532                 return 0;
2533
2534         size = PAGE_SIZE;
2535         if (size > vp->v_mount->mnt_stat.f_iosize)
2536                 size = vp->v_mount->mnt_stat.f_iosize;
2537
2538         for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2539                 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2540                 if (m == NULL)
2541                         return 0;
2542                 tinc = size;
2543                 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2544                         tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2545                 if (vm_page_is_valid(m,
2546                     (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0)
2547                         return 0;
2548         }
2549         return 1;
2550 }
2551
2552 /*
2553  * findblk:
2554  *
2555  *      Locate and return the specified buffer.  Unless flagged otherwise,
2556  *      a locked buffer will be returned if it exists or NULL if it does not.
2557  *
2558  *      findblk()'d buffers are still on the bufqueues and if you intend
2559  *      to use your (locked NON-TEST) buffer you need to bremfree(bp)
2560  *      and possibly do other stuff to it.
2561  *
2562  *      FINDBLK_TEST    - Do not lock the buffer.  The caller is responsible
2563  *                        for locking the buffer and ensuring that it remains
2564  *                        the desired buffer after locking.
2565  *
2566  *      FINDBLK_NBLOCK  - Lock the buffer non-blocking.  If we are unable
2567  *                        to acquire the lock we return NULL, even if the
2568  *                        buffer exists.
2569  *
2570  *      (0)             - Lock the buffer blocking.
2571  *
2572  * MPSAFE
2573  */
2574 struct buf *
2575 findblk(struct vnode *vp, off_t loffset, int flags)
2576 {
2577         lwkt_tokref vlock;
2578         struct buf *bp;
2579         int lkflags;
2580
2581         lkflags = LK_EXCLUSIVE;
2582         if (flags & FINDBLK_NBLOCK)
2583                 lkflags |= LK_NOWAIT;
2584
2585         for (;;) {
2586                 lwkt_gettoken(&vlock, &vp->v_token);
2587                 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2588                 lwkt_reltoken(&vlock);
2589                 if (bp == NULL || (flags & FINDBLK_TEST))
2590                         break;
2591                 if (BUF_LOCK(bp, lkflags)) {
2592                         bp = NULL;
2593                         break;
2594                 }
2595                 if (bp->b_vp == vp && bp->b_loffset == loffset)
2596                         break;
2597                 BUF_UNLOCK(bp);
2598         }
2599         return(bp);
2600 }
2601
2602 /*
2603  * getcacheblk:
2604  *
2605  *      Similar to getblk() except only returns the buffer if it is
2606  *      B_CACHE and requires no other manipulation.  Otherwise NULL
2607  *      is returned.
2608  *
2609  *      If B_RAM is set the buffer might be just fine, but we return
2610  *      NULL anyway because we want the code to fall through to the
2611  *      cluster read.  Otherwise read-ahead breaks.
2612  */
2613 struct buf *
2614 getcacheblk(struct vnode *vp, off_t loffset)
2615 {
2616         struct buf *bp;
2617
2618         bp = findblk(vp, loffset, 0);
2619         if (bp) {
2620                 if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) == B_CACHE) {
2621                         bp->b_flags &= ~B_AGE;
2622                         bremfree(bp);
2623                 } else {
2624                         BUF_UNLOCK(bp);
2625                         bp = NULL;
2626                 }
2627         }
2628         return (bp);
2629 }
2630
2631 /*
2632  * getblk:
2633  *
2634  *      Get a block given a specified block and offset into a file/device.
2635  *      B_INVAL may or may not be set on return.  The caller should clear
2636  *      B_INVAL prior to initiating a READ.
2637  *
2638  *      IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2639  *      IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2640  *      OR SET B_INVAL BEFORE RETIRING IT.  If you retire a getblk'd buffer
2641  *      without doing any of those things the system will likely believe
2642  *      the buffer to be valid (especially if it is not B_VMIO), and the
2643  *      next getblk() will return the buffer with B_CACHE set.
2644  *
2645  *      For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2646  *      an existing buffer.
2647  *
2648  *      For a VMIO buffer, B_CACHE is modified according to the backing VM.
2649  *      If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2650  *      and then cleared based on the backing VM.  If the previous buffer is
2651  *      non-0-sized but invalid, B_CACHE will be cleared.
2652  *
2653  *      If getblk() must create a new buffer, the new buffer is returned with
2654  *      both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2655  *      case it is returned with B_INVAL clear and B_CACHE set based on the
2656  *      backing VM.
2657  *
2658  *      getblk() also forces a bwrite() for any B_DELWRI buffer whos
2659  *      B_CACHE bit is clear.
2660  *      
2661  *      What this means, basically, is that the caller should use B_CACHE to
2662  *      determine whether the buffer is fully valid or not and should clear
2663  *      B_INVAL prior to issuing a read.  If the caller intends to validate
2664  *      the buffer by loading its data area with something, the caller needs
2665  *      to clear B_INVAL.  If the caller does this without issuing an I/O, 
2666  *      the caller should set B_CACHE ( as an optimization ), else the caller
2667  *      should issue the I/O and biodone() will set B_CACHE if the I/O was
2668  *      a write attempt or if it was a successfull read.  If the caller 
2669  *      intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2670  *      prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2671  *
2672  *      getblk flags:
2673  *
2674  *      GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2675  *      GETBLK_BHEAVY - heavy-weight buffer cache buffer
2676  *
2677  * MPALMOSTSAFE
2678  */
2679 struct buf *
2680 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2681 {
2682         struct buf *bp;
2683         int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2684         int error;
2685         int lkflags;
2686
2687         if (size > MAXBSIZE)
2688                 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2689         if (vp->v_object == NULL)
2690                 panic("getblk: vnode %p has no object!", vp);
2691
2692 loop:
2693         if ((bp = findblk(vp, loffset, FINDBLK_TEST)) != NULL) {
2694                 /*
2695                  * The buffer was found in the cache, but we need to lock it.
2696                  * Even with LK_NOWAIT the lockmgr may break our critical
2697                  * section, so double-check the validity of the buffer
2698                  * once the lock has been obtained.
2699                  */
2700                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2701                         if (blkflags & GETBLK_NOWAIT)
2702                                 return(NULL);
2703                         lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2704                         if (blkflags & GETBLK_PCATCH)
2705                                 lkflags |= LK_PCATCH;
2706                         error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2707                         if (error) {
2708                                 if (error == ENOLCK)
2709                                         goto loop;
2710                                 return (NULL);
2711                         }
2712                         /* buffer may have changed on us */
2713                 }
2714
2715                 /*
2716                  * Once the buffer has been locked, make sure we didn't race
2717                  * a buffer recyclement.  Buffers that are no longer hashed
2718                  * will have b_vp == NULL, so this takes care of that check
2719                  * as well.
2720                  */
2721                 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2722                         kprintf("Warning buffer %p (vp %p loffset %lld) "
2723                                 "was recycled\n",
2724                                 bp, vp, (long long)loffset);
2725                         BUF_UNLOCK(bp);
2726                         goto loop;
2727                 }
2728
2729                 /*
2730                  * If SZMATCH any pre-existing buffer must be of the requested
2731                  * size or NULL is returned.  The caller absolutely does not
2732                  * want getblk() to bwrite() the buffer on a size mismatch.
2733                  */
2734                 if ((blkflags & GETBLK_SZMATCH) && size != bp->b_bcount) {
2735                         BUF_UNLOCK(bp);
2736                         return(NULL);
2737                 }
2738
2739                 /*
2740                  * All vnode-based buffers must be backed by a VM object.
2741                  */
2742                 KKASSERT(bp->b_flags & B_VMIO);
2743                 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2744                 bp->b_flags &= ~B_AGE;
2745
2746                 /*
2747                  * Make sure that B_INVAL buffers do not have a cached
2748                  * block number translation.
2749                  */
2750                 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2751                         kprintf("Warning invalid buffer %p (vp %p loffset %lld)"
2752                                 " did not have cleared bio_offset cache\n",
2753                                 bp, vp, (long long)loffset);
2754                         clearbiocache(&bp->b_bio2);
2755                 }
2756
2757                 /*
2758                  * The buffer is locked.  B_CACHE is cleared if the buffer is 
2759                  * invalid.
2760                  */
2761                 if (bp->b_flags & B_INVAL)
2762                         bp->b_flags &= ~B_CACHE;
2763                 bremfree(bp);
2764
2765                 /*
2766                  * Any size inconsistancy with a dirty buffer or a buffer
2767                  * with a softupdates dependancy must be resolved.  Resizing
2768                  * the buffer in such circumstances can lead to problems.
2769                  *
2770                  * Dirty or dependant buffers are written synchronously.
2771                  * Other types of buffers are simply released and
2772                  * reconstituted as they may be backed by valid, dirty VM
2773                  * pages (but not marked B_DELWRI).
2774                  *
2775                  * NFS NOTE: NFS buffers which straddle EOF are oddly-sized
2776                  * and may be left over from a prior truncation (and thus
2777                  * no longer represent the actual EOF point), so we
2778                  * definitely do not want to B_NOCACHE the backing store.
2779                  */
2780                 if (size != bp->b_bcount) {
2781                         get_mplock();
2782                         if (bp->b_flags & B_DELWRI) {
2783                                 bp->b_flags |= B_RELBUF;
2784                                 bwrite(bp);
2785                         } else if (LIST_FIRST(&bp->b_dep)) {
2786                                 bp->b_flags |= B_RELBUF;
2787                                 bwrite(bp);
2788                         } else {
2789                                 bp->b_flags |= B_RELBUF;
2790                                 brelse(bp);
2791                         }
2792                         rel_mplock();
2793                         goto loop;
2794                 }
2795                 KKASSERT(size <= bp->b_kvasize);
2796                 KASSERT(bp->b_loffset != NOOFFSET, 
2797                         ("getblk: no buffer offset"));
2798
2799                 /*
2800                  * A buffer with B_DELWRI set and B_CACHE clear must
2801                  * be committed before we can return the buffer in
2802                  * order to prevent the caller from issuing a read
2803                  * ( due to B_CACHE not being set ) and overwriting
2804                  * it.
2805                  *
2806                  * Most callers, including NFS and FFS, need this to
2807                  * operate properly either because they assume they
2808                  * can issue a read if B_CACHE is not set, or because
2809                  * ( for example ) an uncached B_DELWRI might loop due 
2810                  * to softupdates re-dirtying the buffer.  In the latter
2811                  * case, B_CACHE is set after the first write completes,
2812                  * preventing further loops.
2813                  *
2814                  * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2815                  * above while extending the buffer, we cannot allow the
2816                  * buffer to remain with B_CACHE set after the write
2817                  * completes or it will represent a corrupt state.  To
2818                  * deal with this we set B_NOCACHE to scrap the buffer
2819                  * after the write.
2820                  *
2821                  * XXX Should this be B_RELBUF instead of B_NOCACHE?
2822                  *     I'm not even sure this state is still possible
2823                  *     now that getblk() writes out any dirty buffers
2824                  *     on size changes.
2825                  *
2826                  * We might be able to do something fancy, like setting
2827                  * B_CACHE in bwrite() except if B_DELWRI is already set,
2828                  * so the below call doesn't set B_CACHE, but that gets real
2829                  * confusing.  This is much easier.
2830                  */
2831
2832                 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2833                         get_mplock();
2834                         kprintf("getblk: Warning, bp %p loff=%jx DELWRI set "
2835                                 "and CACHE clear, b_flags %08x\n",
2836                                 bp, (intmax_t)bp->b_loffset, bp->b_flags);
2837                         bp->b_flags |= B_NOCACHE;
2838                         bwrite(bp);
2839                         rel_mplock();
2840                         goto loop;
2841                 }
2842         } else {
2843                 /*
2844                  * Buffer is not in-core, create new buffer.  The buffer
2845                  * returned by getnewbuf() is locked.  Note that the returned
2846                  * buffer is also considered valid (not marked B_INVAL).
2847                  *
2848                  * Calculating the offset for the I/O requires figuring out
2849                  * the block size.  We use DEV_BSIZE for VBLK or VCHR and
2850                  * the mount's f_iosize otherwise.  If the vnode does not
2851                  * have an associated mount we assume that the passed size is 
2852                  * the block size.  
2853                  *
2854                  * Note that vn_isdisk() cannot be used here since it may
2855                  * return a failure for numerous reasons.   Note that the
2856                  * buffer size may be larger then the block size (the caller
2857                  * will use block numbers with the proper multiple).  Beware
2858                  * of using any v_* fields which are part of unions.  In
2859                  * particular, in DragonFly the mount point overloading 
2860                  * mechanism uses the namecache only and the underlying
2861                  * directory vnode is not a special case.
2862                  */
2863                 int bsize, maxsize;
2864
2865                 if (vp->v_type == VBLK || vp->v_type == VCHR)
2866                         bsize = DEV_BSIZE;
2867                 else if (vp->v_mount)
2868                         bsize = vp->v_mount->mnt_stat.f_iosize;
2869                 else
2870                         bsize = size;
2871
2872                 maxsize = size + (loffset & PAGE_MASK);
2873                 maxsize = imax(maxsize, bsize);
2874
2875                 bp = getnewbuf(blkflags, slptimeo, size, maxsize);
2876                 if (bp == NULL) {
2877                         if (slpflags || slptimeo)
2878                                 return NULL;
2879                         goto loop;
2880                 }
2881
2882                 /*
2883                  * Atomically insert the buffer into the hash, so that it can
2884                  * be found by findblk().
2885                  *
2886                  * If bgetvp() returns non-zero a collision occured, and the
2887                  * bp will not be associated with the vnode.
2888                  *
2889                  * Make sure the translation layer has been cleared.
2890                  */
2891                 bp->b_loffset = loffset;
2892                 bp->b_bio2.bio_offset = NOOFFSET;
2893                 /* bp->b_bio2.bio_next = NULL; */
2894
2895                 if (bgetvp(vp, bp)) {
2896                         bp->b_flags |= B_INVAL;
2897                         brelse(bp);
2898                         goto loop;
2899                 }
2900
2901                 /*
2902                  * All vnode-based buffers must be backed by a VM object.
2903                  */
2904                 KKASSERT(vp->v_object != NULL);
2905                 bp->b_flags |= B_VMIO;
2906                 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2907
2908                 get_mplock();
2909                 allocbuf(bp, size);
2910                 rel_mplock();
2911         }
2912         return (bp);
2913 }
2914
2915 /*
2916  * regetblk(bp)
2917  *
2918  * Reacquire a buffer that was previously released to the locked queue,
2919  * or reacquire a buffer which is interlocked by having bioops->io_deallocate
2920  * set B_LOCKED (which handles the acquisition race).
2921  *
2922  * To this end, either B_LOCKED must be set or the dependancy list must be
2923  * non-empty.
2924  *
2925  * MPSAFE
2926  */
2927 void
2928 regetblk(struct buf *bp)
2929 {
2930         KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
2931         BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
2932         bremfree(bp);
2933 }
2934
2935 /*
2936  * geteblk:
2937  *
2938  *      Get an empty, disassociated buffer of given size.  The buffer is
2939  *      initially set to B_INVAL.
2940  *
2941  *      critical section protection is not required for the allocbuf()
2942  *      call because races are impossible here.
2943  *
2944  * MPALMOSTSAFE
2945  */
2946 struct buf *
2947 geteblk(int size)
2948 {
2949         struct buf *bp;
2950         int maxsize;
2951
2952         maxsize = (size + BKVAMASK) & ~BKVAMASK;
2953
2954         while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2955                 ;
2956         get_mplock();
2957         allocbuf(bp, size);
2958         rel_mplock();
2959         bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2960         return (bp);
2961 }
2962
2963
2964 /*
2965  * allocbuf:
2966  *
2967  *      This code constitutes the buffer memory from either anonymous system
2968  *      memory (in the case of non-VMIO operations) or from an associated
2969  *      VM object (in the case of VMIO operations).  This code is able to
2970  *      resize a buffer up or down.
2971  *
2972  *      Note that this code is tricky, and has many complications to resolve
2973  *      deadlock or inconsistant data situations.  Tread lightly!!! 
2974  *      There are B_CACHE and B_DELWRI interactions that must be dealt with by 
2975  *      the caller.  Calling this code willy nilly can result in the loss of data.
2976  *
2977  *      allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2978  *      B_CACHE for the non-VMIO case.
2979  *
2980  *      This routine does not need to be called from a critical section but you
2981  *      must own the buffer.
2982  *
2983  * NOTMPSAFE
2984  */
2985 int
2986 allocbuf(struct buf *bp, int size)
2987 {
2988         int newbsize, mbsize;
2989         int i;
2990
2991         if (BUF_REFCNT(bp) == 0)
2992                 panic("allocbuf: buffer not busy");
2993
2994         if (bp->b_kvasize < size)
2995                 panic("allocbuf: buffer too small");
2996
2997         if ((bp->b_flags & B_VMIO) == 0) {
2998                 caddr_t origbuf;
2999                 int origbufsize;
3000                 /*
3001                  * Just get anonymous memory from the kernel.  Don't
3002                  * mess with B_CACHE.
3003                  */
3004                 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3005                 if (bp->b_flags & B_MALLOC)
3006                         newbsize = mbsize;
3007                 else
3008                         newbsize = round_page(size);
3009
3010                 if (newbsize < bp->b_bufsize) {
3011                         /*
3012                          * Malloced buffers are not shrunk
3013                          */
3014                         if (bp->b_flags & B_MALLOC) {
3015                                 if (newbsize) {
3016                                         bp->b_bcount = size;
3017                                 } else {
3018                                         kfree(bp->b_data, M_BIOBUF);
3019                                         if (bp->b_bufsize) {
3020                                                 bufmallocspace -= bp->b_bufsize;
3021                                                 bufspacewakeup();
3022                                                 bp->b_bufsize = 0;
3023                                         }
3024                                         bp->b_data = bp->b_kvabase;
3025                                         bp->b_bcount = 0;
3026                                         bp->b_flags &= ~B_MALLOC;
3027                                 }
3028                                 return 1;
3029                         }               
3030                         vm_hold_free_pages(
3031                             bp,
3032                             (vm_offset_t) bp->b_data + newbsize,
3033                             (vm_offset_t) bp->b_data + bp->b_bufsize);
3034                 } else if (newbsize > bp->b_bufsize) {
3035                         /*
3036                          * We only use malloced memory on the first allocation.
3037                          * and revert to page-allocated memory when the buffer
3038                          * grows.
3039                          */
3040                         if ((bufmallocspace < maxbufmallocspace) &&
3041                                 (bp->b_bufsize == 0) &&
3042                                 (mbsize <= PAGE_SIZE/2)) {
3043
3044                                 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
3045                                 bp->b_bufsize = mbsize;
3046                                 bp->b_bcount = size;
3047                                 bp->b_flags |= B_MALLOC;
3048                                 bufmallocspace += mbsize;
3049                                 return 1;
3050                         }
3051                         origbuf = NULL;
3052                         origbufsize = 0;
3053                         /*
3054                          * If the buffer is growing on its other-than-first
3055                          * allocation, then we revert to the page-allocation
3056                          * scheme.
3057                          */
3058                         if (bp->b_flags & B_MALLOC) {
3059                                 origbuf = bp->b_data;
3060                                 origbufsize = bp->b_bufsize;
3061                                 bp->b_data = bp->b_kvabase;
3062                                 if (bp->b_bufsize) {
3063                                         bufmallocspace -= bp->b_bufsize;
3064                                         bufspacewakeup();
3065                                         bp->b_bufsize = 0;
3066                                 }
3067                                 bp->b_flags &= ~B_MALLOC;
3068                                 newbsize = round_page(newbsize);
3069                         }
3070                         vm_hold_load_pages(
3071                             bp,
3072                             (vm_offset_t) bp->b_data + bp->b_bufsize,
3073                             (vm_offset_t) bp->b_data + newbsize);
3074                         if (origbuf) {
3075                                 bcopy(origbuf, bp->b_data, origbufsize);
3076                                 kfree(origbuf, M_BIOBUF);
3077                         }
3078                 }
3079         } else {
3080                 vm_page_t m;
3081                 int desiredpages;
3082
3083                 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3084                 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
3085                                 newbsize + PAGE_MASK) >> PAGE_SHIFT;
3086                 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
3087
3088                 if (bp->b_flags & B_MALLOC)
3089                         panic("allocbuf: VMIO buffer can't be malloced");
3090                 /*
3091                  * Set B_CACHE initially if buffer is 0 length or will become
3092                  * 0-length.
3093                  */
3094                 if (size == 0 || bp->b_bufsize == 0)
3095                         bp->b_flags |= B_CACHE;
3096
3097                 if (newbsize < bp->b_bufsize) {
3098                         /*
3099                          * DEV_BSIZE aligned new buffer size is less then the
3100                          * DEV_BSIZE aligned existing buffer size.  Figure out
3101                          * if we have to remove any pages.
3102                          */
3103                         if (desiredpages < bp->b_xio.xio_npages) {
3104                                 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
3105                                         /*
3106                                          * the page is not freed here -- it
3107                                          * is the responsibility of 
3108                                          * vnode_pager_setsize
3109                                          */
3110                                         m = bp->b_xio.xio_pages[i];
3111                                         KASSERT(m != bogus_page,
3112                                             ("allocbuf: bogus page found"));
3113                                         while (vm_page_sleep_busy(m, TRUE, "biodep"))
3114                                                 ;
3115
3116                                         bp->b_xio.xio_pages[i] = NULL;
3117                                         vm_page_unwire(m, 0);
3118                                 }
3119                                 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
3120                                     (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
3121                                 bp->b_xio.xio_npages = desiredpages;
3122                         }
3123                 } else if (size > bp->b_bcount) {
3124                         /*
3125                          * We are growing the buffer, possibly in a 
3126                          * byte-granular fashion.
3127                          */
3128                         struct vnode *vp;
3129                         vm_object_t obj;
3130                         vm_offset_t toff;
3131                         vm_offset_t tinc;
3132
3133                         /*
3134                          * Step 1, bring in the VM pages from the object, 
3135                          * allocating them if necessary.  We must clear
3136                          * B_CACHE if these pages are not valid for the 
3137                          * range covered by the buffer.
3138                          *
3139                          * critical section protection is required to protect
3140                          * against interrupts unbusying and freeing pages
3141                          * between our vm_page_lookup() and our
3142                          * busycheck/wiring call.
3143                          */
3144                         vp = bp->b_vp;
3145                         obj = vp->v_object;
3146
3147                         crit_enter();
3148                         while (bp->b_xio.xio_npages < desiredpages) {
3149                                 vm_page_t m;
3150                                 vm_pindex_t pi;
3151
3152                                 pi = OFF_TO_IDX(bp->b_loffset) + bp->b_xio.xio_npages;
3153                                 if ((m = vm_page_lookup(obj, pi)) == NULL) {
3154                                         /*
3155                                          * note: must allocate system pages
3156                                          * since blocking here could intefere
3157                                          * with paging I/O, no matter which
3158                                          * process we are.
3159                                          */
3160                                         m = bio_page_alloc(obj, pi, desiredpages - bp->b_xio.xio_npages);
3161                                         if (m) {
3162                                                 vm_page_wire(m);
3163                                                 vm_page_wakeup(m);
3164                                                 bp->b_flags &= ~B_CACHE;
3165                                                 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3166                                                 ++bp->b_xio.xio_npages;
3167                                         }
3168                                         continue;
3169                                 }
3170
3171                                 /*
3172                                  * We found a page.  If we have to sleep on it,
3173                                  * retry because it might have gotten freed out
3174                                  * from under us.
3175                                  *
3176                                  * We can only test PG_BUSY here.  Blocking on
3177                                  * m->busy might lead to a deadlock:
3178                                  *
3179                                  *  vm_fault->getpages->cluster_read->allocbuf
3180                                  *
3181                                  */
3182
3183                                 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
3184                                         continue;
3185                                 vm_page_flag_clear(m, PG_ZERO);
3186                                 vm_page_wire(m);
3187                                 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3188                                 ++bp->b_xio.xio_npages;
3189                                 if (bp->b_act_count < m->act_count)
3190                                         bp->b_act_count = m->act_count;
3191                         }
3192                         crit_exit();
3193
3194                         /*
3195                          * Step 2.  We've loaded the pages into the buffer,
3196                          * we have to figure out if we can still have B_CACHE
3197                          * set.  Note that B_CACHE is set according to the
3198                          * byte-granular range ( bcount and size ), not the
3199                          * aligned range ( newbsize ).
3200                          *
3201                          * The VM test is against m->valid, which is DEV_BSIZE
3202                          * aligned.  Needless to say, the validity of the data
3203                          * needs to also be DEV_BSIZE aligned.  Note that this
3204                          * fails with NFS if the server or some other client
3205                          * extends the file's EOF.  If our buffer is resized, 
3206                          * B_CACHE may remain set! XXX
3207                          */
3208
3209                         toff = bp->b_bcount;
3210                         tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
3211
3212                         while ((bp->b_flags & B_CACHE) && toff < size) {
3213                                 vm_pindex_t pi;
3214
3215                                 if (tinc > (size - toff))
3216                                         tinc = size - toff;
3217
3218                                 pi = ((bp->b_loffset & PAGE_MASK) + toff) >> 
3219                                     PAGE_SHIFT;
3220
3221                                 vfs_buf_test_cache(
3222                                     bp, 
3223                                     bp->b_loffset,
3224                                     toff, 
3225                                     tinc, 
3226                                     bp->b_xio.xio_pages[pi]
3227                                 );
3228                                 toff += tinc;
3229                                 tinc = PAGE_SIZE;
3230                         }
3231
3232                         /*
3233                          * Step 3, fixup the KVM pmap.  Remember that
3234                          * bp->b_data is relative to bp->b_loffset, but 
3235                          * bp->b_loffset may be offset into the first page.
3236                          */
3237
3238                         bp->b_data = (caddr_t)
3239                             trunc_page((vm_offset_t)bp->b_data);
3240                         pmap_qenter(
3241                             (vm_offset_t)bp->b_data,
3242                             bp->b_xio.xio_pages, 
3243                             bp->b_xio.xio_npages
3244                         );
3245                         bp->b_data = (caddr_t)((vm_offset_t)bp->b_data | 
3246                             (vm_offset_t)(bp->b_loffset & PAGE_MASK));
3247                 }
3248         }
3249
3250         /* adjust space use on already-dirty buffer */
3251         if (bp->b_flags & B_DELWRI) {
3252                 dirtybufspace += newbsize - bp->b_bufsize;
3253                 if (bp->b_flags & B_HEAVY)
3254                         dirtybufspacehw += newbsize - bp->b_bufsize;
3255         }
3256         if (newbsize < bp->b_bufsize)
3257                 bufspacewakeup();
3258         bp->b_bufsize = newbsize;       /* actual buffer allocation     */
3259         bp->b_bcount = size;            /* requested buffer size        */
3260         return 1;
3261 }
3262
3263 /*
3264  * biowait:
3265  *
3266  *      Wait for buffer I/O completion, returning error status. B_EINTR
3267  *      is converted into an EINTR error but not cleared (since a chain
3268  *      of biowait() calls may occur).
3269  *
3270  *      On return bpdone() will have been called but the buffer will remain
3271  *      locked and will not have been brelse()'d.
3272  *
3273  *      NOTE!  If a timeout is specified and ETIMEDOUT occurs the I/O is
3274  *      likely still in progress on return.
3275  *
3276  *      NOTE!  This operation is on a BIO, not a BUF.
3277  *
3278  *      NOTE!  BIO_DONE is cleared by vn_strategy()
3279  *
3280  * MPSAFE
3281  */
3282 static __inline int
3283 _biowait(struct bio *bio, const char *wmesg, int to)
3284 {
3285         struct buf *bp = bio->bio_buf;
3286         u_int32_t flags;
3287         u_int32_t nflags;
3288         int error;
3289
3290         KKASSERT(bio == &bp->b_bio1);
3291         for (;;) {
3292                 flags = bio->bio_flags;
3293                 if (flags & BIO_DONE)
3294                         break;
3295                 tsleep_interlock(bio, 0);
3296                 nflags = flags | BIO_WANT;
3297                 tsleep_interlock(bio, 0);
3298                 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3299                         if (wmesg)
3300                                 error = tsleep(bio, PINTERLOCKED, wmesg, to);
3301                         else if (bp->b_cmd == BUF_CMD_READ)
3302                                 error = tsleep(bio, PINTERLOCKED, "biord", to);
3303                         else
3304                                 error = tsleep(bio, PINTERLOCKED, "biowr", to);
3305                         if (error) {
3306                                 kprintf("tsleep error biowait %d\n", error);
3307                                 return (error);
3308                         }
3309                         break;
3310                 }
3311         }
3312
3313         /*
3314          * Finish up.
3315          */
3316         KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3317         bio->bio_flags &= ~(BIO_DONE | BIO_SYNC);
3318         if (bp->b_flags & B_EINTR)
3319                 return (EINTR);
3320         if (bp->b_flags & B_ERROR)
3321                 return (bp->b_error ? bp->b_error : EIO);
3322         return (0);
3323 }
3324
3325 int
3326 biowait(struct bio *bio, const char *wmesg)
3327 {
3328         return(_biowait(bio, wmesg, 0));
3329 }
3330
3331 int
3332 biowait_timeout(struct bio *bio, const char *wmesg, int to)
3333 {
3334         return(_biowait(bio, wmesg, to));
3335 }
3336
3337 /*
3338  * This associates a tracking count with an I/O.  vn_strategy() and
3339  * dev_dstrategy() do this automatically but there are a few cases
3340  * where a vnode or device layer is bypassed when a block translation
3341  * is cached.  In such cases bio_start_transaction() may be called on
3342  * the bypassed layers so the system gets an I/O in progress indication 
3343  * for those higher layers.
3344  */
3345 void
3346 bio_start_transaction(struct bio *bio, struct bio_track *track)
3347 {
3348         bio->bio_track = track;
3349         bio_track_ref(track);
3350 }
3351
3352 /*
3353  * Initiate I/O on a vnode.
3354  */
3355 void
3356 vn_strategy(struct vnode *vp, struct bio *bio)
3357 {
3358         struct bio_track *track;
3359
3360         KKASSERT(bio->bio_buf->b_cmd != BUF_CMD_DONE);
3361         if (bio->bio_buf->b_cmd == BUF_CMD_READ)
3362                 track = &vp->v_track_read;
3363         else
3364                 track = &vp->v_track_write;
3365         KKASSERT((bio->bio_flags & BIO_DONE) == 0);
3366         bio->bio_track = track;
3367         bio_track_ref(track);
3368         vop_strategy(*vp->v_ops, vp, bio);
3369 }
3370
3371 /*
3372  * bpdone:
3373  *
3374  *      Finish I/O on a buffer after all BIOs have been processed.
3375  *      Called when the bio chain is exhausted or by biowait.  If called
3376  *      by biowait, elseit is typically 0.
3377  *
3378  *      bpdone is also responsible for setting B_CACHE in a B_VMIO bp.
3379  *      In a non-VMIO bp, B_CACHE will be set on the next getblk() 
3380  *      assuming B_INVAL is clear.
3381  *
3382  *      For the VMIO case, we set B_CACHE if the op was a read and no
3383  *      read error occured, or if the op was a write.  B_CACHE is never
3384  *      set if the buffer is invalid or otherwise uncacheable.
3385  *
3386  *      bpdone does not mess with B_INVAL, allowing the I/O routine or the
3387  *      initiator to leave B_INVAL set to brelse the buffer out of existance
3388  *      in the biodone routine.
3389  */
3390 void
3391 bpdone(struct buf *bp, int elseit)
3392 {
3393         buf_cmd_t cmd;
3394
3395         KASSERT(BUF_REFCNTNB(bp) > 0, 
3396                 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3397         KASSERT(bp->b_cmd != BUF_CMD_DONE, 
3398                 ("biodone: bp %p already done!", bp));
3399
3400         /*
3401          * No more BIOs are left.  All completion functions have been dealt
3402          * with, now we clean up the buffer.
3403          */
3404         cmd = bp->b_cmd;
3405         bp->b_cmd = BUF_CMD_DONE;
3406
3407         /*
3408          * Only reads and writes are processed past this point.
3409          */
3410         if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3411                 if (cmd == BUF_CMD_FREEBLKS)
3412                         bp->b_flags |= B_NOCACHE;
3413                 if (elseit)
3414                         brelse(bp);
3415                 return;
3416         }
3417
3418         /*
3419          * Warning: softupdates may re-dirty the buffer, and HAMMER can do
3420          * a lot worse.  XXX - move this above the clearing of b_cmd
3421          */
3422         if (LIST_FIRST(&bp->b_dep) != NULL)
3423                 buf_complete(bp);
3424
3425         /*
3426          * A failed write must re-dirty the buffer unless B_INVAL
3427          * was set.  Only applicable to normal buffers (with VPs).
3428          * vinum buffers may not have a vp.
3429          */
3430         if (cmd == BUF_CMD_WRITE &&
3431             (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
3432                 bp->b_flags &= ~B_NOCACHE;
3433                 if (bp->b_vp)
3434                         bdirty(bp);
3435         }
3436
3437         if (bp->b_flags & B_VMIO) {
3438                 int i;
3439                 vm_ooffset_t foff;
3440                 vm_page_t m;
3441                 vm_object_t obj;
3442                 int iosize;
3443                 struct vnode *vp = bp->b_vp;
3444
3445                 obj = vp->v_object;
3446
3447 #if defined(VFS_BIO_DEBUG)
3448                 if (vp->v_auxrefs == 0)
3449                         panic("biodone: zero vnode hold count");
3450                 if ((vp->v_flag & VOBJBUF) == 0)
3451                         panic("biodone: vnode is not setup for merged cache");
3452 #endif
3453
3454                 foff = bp->b_loffset;
3455                 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3456                 KASSERT(obj != NULL, ("biodone: missing VM object"));
3457
3458 #if defined(VFS_BIO_DEBUG)
3459                 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3460                         kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
3461                             obj->paging_in_progress, bp->b_xio.xio_npages);
3462                 }
3463 #endif
3464
3465                 /*
3466                  * Set B_CACHE if the op was a normal read and no error
3467                  * occured.  B_CACHE is set for writes in the b*write()
3468                  * routines.
3469                  */
3470                 iosize = bp->b_bcount - bp->b_resid;
3471                 if (cmd == BUF_CMD_READ &&
3472                     (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3473                         bp->b_flags |= B_CACHE;
3474                 }
3475
3476                 crit_enter();
3477                 get_mplock();
3478                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3479                         int bogusflag = 0;
3480                         int resid;
3481
3482                         resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3483                         if (resid > iosize)
3484                                 resid = iosize;
3485
3486                         /*
3487                          * cleanup bogus pages, restoring the originals.  Since
3488                          * the originals should still be wired, we don't have
3489                          * to worry about interrupt/freeing races destroying
3490                          * the VM object association.
3491                          */
3492                         m = bp->b_xio.xio_pages[i];
3493                         if (m == bogus_page) {
3494                                 bogusflag = 1;
3495                                 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3496                                 if (m == NULL)
3497                                         panic("biodone: page disappeared");
3498                                 bp->b_xio.xio_pages[i] = m;
3499                                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3500                                         bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3501                         }
3502 #if defined(VFS_BIO_DEBUG)
3503                         if (OFF_TO_IDX(foff) != m->pindex) {
3504                                 kprintf("biodone: foff(%lu)/m->pindex(%ld) "
3505                                         "mismatch\n",
3506                                         (unsigned long)foff, (long)m->pindex);
3507                         }
3508 #endif
3509
3510                         /*
3511                          * In the write case, the valid and clean bits are
3512                          * already changed correctly (see bdwrite()), so we
3513                          * only need to do this here in the read case.
3514                          */
3515                         if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3516                                 vfs_clean_one_page(bp, i, m);
3517                         }
3518                         vm_page_flag_clear(m, PG_ZERO);
3519
3520                         /*
3521                          * when debugging new filesystems or buffer I/O
3522                          * methods, this is the most common error that pops
3523                          * up.  if you see this, you have not set the page
3524                          * busy flag correctly!!!
3525                          */
3526                         if (m->busy == 0) {
3527                                 kprintf("biodone: page busy < 0, "
3528                                     "pindex: %d, foff: 0x(%x,%x), "
3529                                     "resid: %d, index: %d\n",
3530                                     (int) m->pindex, (int)(foff >> 32),
3531                                                 (int) foff & 0xffffffff, resid, i);
3532                                 if (!vn_isdisk(vp, NULL))
3533                                         kprintf(" iosize: %ld, loffset: %lld, "
3534                                                 "flags: 0x%08x, npages: %d\n",
3535                                             bp->b_vp->v_mount->mnt_stat.f_iosize,
3536                                             (long long)bp->b_loffset,
3537                                             bp->b_flags, bp->b_xio.xio_npages);
3538                                 else
3539                                         kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3540                                             (long long)bp->b_loffset,
3541                                             bp->b_flags, bp->b_xio.xio_npages);
3542                                 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3543                                     m->valid, m->dirty, m->wire_count);
3544                                 panic("biodone: page busy < 0");
3545                         }
3546                         vm_page_io_finish(m);
3547                         vm_object_pip_subtract(obj, 1);
3548                         foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3549                         iosize -= resid;
3550                 }
3551                 if (obj)
3552                         vm_object_pip_wakeupn(obj, 0);
3553                 rel_mplock();
3554                 crit_exit();
3555         }
3556
3557         /*
3558          * Finish up by releasing the buffer.  There are no more synchronous
3559          * or asynchronous completions, those were handled by bio_done
3560          * callbacks.
3561          */
3562         if (elseit) {
3563                 if (bp->b_flags & (B_NOCACHE|B_INVAL|B_ERROR|B_RELBUF))
3564                         brelse(bp);
3565                 else
3566                         bqrelse(bp);
3567         }
3568 }
3569
3570 /*
3571  * Normal biodone.
3572  */
3573 void
3574 biodone(struct bio *bio)
3575 {
3576         struct buf *bp = bio->bio_buf;
3577
3578         runningbufwakeup(bp);
3579
3580         /*
3581          * Run up the chain of BIO's.   Leave b_cmd intact for the duration.
3582          */
3583         while (bio) {
3584                 biodone_t *done_func;
3585                 struct bio_track *track;
3586
3587                 /*
3588                  * BIO tracking.  Most but not all BIOs are tracked.
3589                  */
3590                 if ((track = bio->bio_track) != NULL) {
3591                         bio_track_rel(track);
3592                         bio->bio_track = NULL;
3593                 }
3594
3595                 /*
3596                  * A bio_done function terminates the loop.  The function
3597                  * will be responsible for any further chaining and/or
3598                  * buffer management.
3599                  *
3600                  * WARNING!  The done function can deallocate the buffer!
3601                  */
3602                 if ((done_func = bio->bio_done) != NULL) {
3603                         bio->bio_done = NULL;
3604                         done_func(bio);
3605                         return;
3606                 }
3607                 bio = bio->bio_prev;
3608         }
3609
3610         /*
3611          * If we've run out of bio's do normal [a]synchronous completion.
3612          */
3613         bpdone(bp, 1);
3614 }
3615
3616 /*
3617  * Synchronous biodone - this terminates a synchronous BIO.
3618  *
3619  * bpdone() is called with elseit=FALSE, leaving the buffer completed
3620  * but still locked.  The caller must brelse() the buffer after waiting
3621  * for completion.
3622  */
3623 void
3624 biodone_sync(struct bio *bio)
3625 {
3626         struct buf *bp = bio->bio_buf;
3627         int flags;
3628         int nflags;
3629
3630         KKASSERT(bio == &bp->b_bio1);
3631         bpdone(bp, 0);
3632
3633         for (;;) {
3634                 flags = bio->bio_flags;
3635                 nflags = (flags | BIO_DONE) & ~BIO_WANT;
3636
3637                 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3638                         if (flags & BIO_WANT)
3639                                 wakeup(bio);
3640                         break;
3641                 }
3642         }
3643 }
3644
3645 /*
3646  * vfs_unbusy_pages:
3647  *
3648  *      This routine is called in lieu of iodone in the case of
3649  *      incomplete I/O.  This keeps the busy status for pages
3650  *      consistant.
3651  */
3652 void
3653 vfs_unbusy_pages(struct buf *bp)
3654 {
3655         int i;
3656
3657         runningbufwakeup(bp);
3658         if (bp->b_flags & B_VMIO) {
3659                 struct vnode *vp = bp->b_vp;
3660                 vm_object_t obj;
3661
3662                 obj = vp->v_object;
3663
3664                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3665                         vm_page_t m = bp->b_xio.xio_pages[i];
3666
3667                         /*
3668                          * When restoring bogus changes the original pages
3669                          * should still be wired, so we are in no danger of
3670                          * losing the object association and do not need
3671                          * critical section protection particularly.
3672                          */
3673                         if (m == bogus_page) {
3674                                 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3675                                 if (!m) {
3676                                         panic("vfs_unbusy_pages: page missing");
3677                                 }
3678                                 bp->b_xio.xio_pages[i] = m;
3679                                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3680                                         bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3681                         }
3682                         vm_object_pip_subtract(obj, 1);
3683                         vm_page_flag_clear(m, PG_ZERO);
3684                         vm_page_io_finish(m);
3685                 }
3686                 vm_object_pip_wakeupn(obj, 0);
3687         }
3688 }
3689
3690 /*
3691  * vfs_busy_pages:
3692  *
3693  *      This routine is called before a device strategy routine.
3694  *      It is used to tell the VM system that paging I/O is in
3695  *      progress, and treat the pages associated with the buffer
3696  *      almost as being PG_BUSY.  Also the object 'paging_in_progress'
3697  *      flag is handled to make sure that the object doesn't become
3698  *      inconsistant.
3699  *
3700  *      Since I/O has not been initiated yet, certain buffer flags
3701  *      such as B_ERROR or B_INVAL may be in an inconsistant state
3702  *      and should be ignored.
3703  */
3704 void
3705 vfs_busy_pages(struct vnode *vp, struct buf *bp)
3706 {
3707         int i, bogus;
3708         struct lwp *lp = curthread->td_lwp;
3709
3710         /*
3711          * The buffer's I/O command must already be set.  If reading,
3712          * B_CACHE must be 0 (double check against callers only doing
3713          * I/O when B_CACHE is 0).
3714          */
3715         KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3716         KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
3717
3718         if (bp->b_flags & B_VMIO) {
3719                 vm_object_t obj;
3720
3721                 obj = vp->v_object;
3722                 KASSERT(bp->b_loffset != NOOFFSET,
3723                         ("vfs_busy_pages: no buffer offset"));
3724
3725                 /*
3726                  * Loop until none of the pages are busy.
3727                  */
3728 retry:
3729                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3730                         vm_page_t m = bp->b_xio.xio_pages[i];
3731
3732                         if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3733                                 goto retry;
3734                 }
3735
3736                 /*
3737                  * Setup for I/O, soft-busy the page right now because
3738                  * the next loop may block.
3739                  */
3740                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3741                         vm_page_t m = bp->b_xio.xio_pages[i];
3742
3743                         vm_page_flag_clear(m, PG_ZERO);
3744                         if ((bp->b_flags & B_CLUSTER) == 0) {
3745                                 vm_object_pip_add(obj, 1);
3746                                 vm_page_io_start(m);
3747                         }
3748                 }
3749
3750                 /*
3751                  * Adjust protections for I/O and do bogus-page mapping.
3752                  * Assume that vm_page_protect() can block (it can block
3753                  * if VM_PROT_NONE, don't take any chances regardless).
3754                  *
3755                  * In particularly note that for writes we must incorporate
3756                  * page dirtyness from the VM system into the buffer's
3757                  * dirty range.
3758                  *
3759                  * For reads we theoretically must incorporate page dirtyness
3760                  * from the VM system to determine if the page needs bogus
3761                  * replacement, but we shortcut the test by simply checking
3762                  * that all m->valid bits are set, indicating that the page
3763                  * is fully valid and does not need to be re-read.  For any
3764                  * VM system dirtyness the page will also be fully valid
3765                  * since it was mapped at one point.
3766                  */
3767                 bogus = 0;
3768                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3769                         vm_page_t m = bp->b_xio.xio_pages[i];
3770
3771                         vm_page_flag_clear(m, PG_ZERO); /* XXX */
3772                         if (bp->b_cmd == BUF_CMD_WRITE) {
3773                                 /*
3774                                  * When readying a vnode-backed buffer for
3775                                  * a write we must zero-fill any invalid
3776                                  * portions of the backing VM pages, mark
3777                                  * it valid and clear related dirty bits.
3778                                  *
3779                                  * vfs_clean_one_page() incorporates any
3780                                  * VM dirtyness and updates the b_dirtyoff
3781                                  * range (after we've made the page RO).
3782                                  *
3783                                  * It is also expected that the pmap modified
3784                                  * bit has already been cleared by the
3785                                  * vm_page_protect().  We may not be able
3786                                  * to clear all dirty bits for a page if it
3787                                  * was also memory mapped (NFS).
3788                                  */
3789                                 vm_page_protect(m, VM_PROT_READ);
3790                                 vfs_clean_one_page(bp, i, m);
3791                         } else if (m->valid == VM_PAGE_BITS_ALL) {
3792                                 /*
3793                                  * When readying a vnode-backed buffer for
3794                                  * read we must replace any dirty pages with
3795                                  * a bogus page so dirty data is not destroyed
3796                                  * when filling gaps.
3797                                  *
3798                                  * To avoid testing whether the page is
3799                                  * dirty we instead test that the page was
3800                                  * at some point mapped (m->valid fully
3801                                  * valid) with the understanding that
3802                                  * this also covers the dirty case.
3803                                  */
3804                                 bp->b_xio.xio_pages[i] = bogus_page;
3805                                 bogus++;
3806                         } else if (m->valid & m->dirty) {
3807                                 /*
3808                                  * This case should not occur as partial
3809                                  * dirtyment can only happen if the buffer
3810                                  * is B_CACHE, and this code is not entered
3811                                  * if the buffer is B_CACHE.
3812                                  */
3813                                 kprintf("Warning: vfs_busy_pages - page not "
3814                                         "fully valid! loff=%jx bpf=%08x "
3815                                         "idx=%d val=%02x dir=%02x\n",
3816                                         (intmax_t)bp->b_loffset, bp->b_flags,
3817                                         i, m->valid, m->dirty);
3818                                 vm_page_protect(m, VM_PROT_NONE);
3819                         } else {
3820                                 /*
3821                                  * The page is not valid and can be made
3822                                  * part of the read.
3823                                  */
3824                                 vm_page_protect(m, VM_PROT_NONE);
3825                         }
3826                 }
3827                 if (bogus) {
3828                         pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3829                                 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3830                 }
3831         }
3832
3833         /*
3834          * This is the easiest place to put the process accounting for the I/O
3835          * for now.
3836          */
3837         if (lp != NULL) {
3838                 if (bp->b_cmd == BUF_CMD_READ)
3839                         lp->lwp_ru.ru_inblock++;
3840                 else
3841                         lp->lwp_ru.ru_oublock++;
3842         }
3843 }
3844
3845 /*
3846  * vfs_clean_pages:
3847  *      
3848  *      Tell the VM system that the pages associated with this buffer
3849  *      are clean.  This is used for delayed writes where the data is
3850  *      going to go to disk eventually without additional VM intevention.
3851  *
3852  *      Note that while we only really need to clean through to b_bcount, we
3853  *      just go ahead and clean through to b_bufsize.
3854  */
3855 static void
3856 vfs_clean_pages(struct buf *bp)
3857 {
3858         vm_page_t m;
3859         int i;
3860
3861         if ((bp->b_flags & B_VMIO) == 0)
3862                 return;
3863
3864         KASSERT(bp->b_loffset != NOOFFSET,
3865                 ("vfs_clean_pages: no buffer offset"));
3866
3867         for (i = 0; i < bp->b_xio.xio_npages; i++) {
3868                 m = bp->b_xio.xio_pages[i];
3869                 vfs_clean_one_page(bp, i, m);
3870         }
3871 }
3872
3873 /*
3874  * vfs_clean_one_page:
3875  *
3876  *      Set the valid bits and clear the dirty bits in a page within a
3877  *      buffer.  The range is restricted to the buffer's size and the
3878  *      buffer's logical offset might index into the first page.
3879  *
3880  *      The caller has busied or soft-busied the page and it is not mapped,
3881  *      test and incorporate the dirty bits into b_dirtyoff/end before
3882  *      clearing them.  Note that we need to clear the pmap modified bits
3883  *      after determining the the page was dirty, vm_page_set_validclean()
3884  *      does not do it for us.
3885  *
3886  *      This routine is typically called after a read completes (dirty should
3887  *      be zero in that case as we are not called on bogus-replace pages),
3888  *      or before a write is initiated.
3889  */
3890 static void
3891 vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m)
3892 {
3893         int bcount;
3894         int xoff;
3895         int soff;
3896         int eoff;
3897
3898         /*
3899          * Calculate offset range within the page but relative to buffer's
3900          * loffset.  loffset might be offset into the first page.
3901          */
3902         xoff = (int)bp->b_loffset & PAGE_MASK;  /* loffset offset into pg 0 */
3903         bcount = bp->b_bcount + xoff;           /* offset adjusted */
3904
3905         if (pageno == 0) {
3906                 soff = xoff;
3907                 eoff = PAGE_SIZE;
3908         } else {
3909                 soff = (pageno << PAGE_SHIFT);
3910                 eoff = soff + PAGE_SIZE;
3911         }
3912         if (eoff > bcount)
3913                 eoff = bcount;
3914         if (soff >= eoff)
3915                 return;
3916
3917         /*
3918          * Test dirty bits and adjust b_dirtyoff/end.
3919          *
3920          * If dirty pages are incorporated into the bp any prior
3921          * B_NEEDCOMMIT state (NFS) must be cleared because the
3922          * caller has not taken into account the new dirty data.
3923          *
3924          * If the page was memory mapped the dirty bits might go beyond the
3925          * end of the buffer, but we can't really make the assumption that
3926          * a file EOF straddles the buffer (even though this is the case for
3927          * NFS if B_NEEDCOMMIT is also set).  So for the purposes of clearing
3928          * B_NEEDCOMMIT we only test the dirty bits covered by the buffer.
3929          * This also saves some console spam.
3930          */
3931         vm_page_test_dirty(m);
3932         if (m->dirty) {
3933                 pmap_clear_modify(m);
3934                 if ((bp->b_flags & B_NEEDCOMMIT) &&
3935                     (m->dirty & vm_page_bits(soff & PAGE_MASK, eoff - soff))) {
3936                         kprintf("Warning: vfs_clean_one_page: bp %p "
3937                                 "loff=%jx,%d flgs=%08x clr B_NEEDCOMMIT\n",
3938                                 bp, (intmax_t)bp->b_loffset, bp->b_bcount,
3939                                 bp->b_flags);
3940                         bp->b_flags &= ~B_NEEDCOMMIT;
3941                 }
3942                 if (bp->b_dirtyoff > soff - xoff)
3943                         bp->b_dirtyoff = soff - xoff;
3944                 if (bp->b_dirtyend < eoff - xoff)
3945                         bp->b_dirtyend = eoff - xoff;
3946         }
3947
3948         /*
3949          * Set related valid bits, clear related dirty bits.
3950          * Does not mess with the pmap modified bit.
3951          *
3952          * WARNING!  We cannot just clear all of m->dirty here as the
3953          *           buffer cache buffers may use a DEV_BSIZE'd aligned
3954          *           block size, or have an odd size (e.g. NFS at file EOF).
3955          *           The putpages code can clear m->dirty to 0.
3956          *
3957          *           If a VOP_WRITE generates a buffer cache buffer which
3958          *           covers the same space as mapped writable pages the
3959          *           buffer flush might not be able to clear all the dirty
3960          *           bits and still require a putpages from the VM system
3961          *           to finish it off.
3962          */
3963         vm_page_set_validclean(m, soff & PAGE_MASK, eoff - soff);
3964 }
3965
3966 /*
3967  * vfs_bio_clrbuf:
3968  *
3969  *      Clear a buffer.  This routine essentially fakes an I/O, so we need
3970  *      to clear B_ERROR and B_INVAL.
3971  *
3972  *      Note that while we only theoretically need to clear through b_bcount,
3973  *      we go ahead and clear through b_bufsize.
3974  */
3975
3976 void
3977 vfs_bio_clrbuf(struct buf *bp)
3978 {
3979         int i, mask = 0;
3980         caddr_t sa, ea;
3981         if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3982                 bp->b_flags &= ~(B_INVAL | B_EINTR | B_ERROR);
3983                 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3984                     (bp->b_loffset & PAGE_MASK) == 0) {
3985                         mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3986                         if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3987                                 bp->b_resid = 0;
3988                                 return;
3989                         }
3990                         if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3991                             ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3992                                 bzero(bp->b_data, bp->b_bufsize);
3993                                 bp->b_xio.xio_pages[0]->valid |= mask;
3994                                 bp->b_resid = 0;
3995                                 return;
3996                         }
3997                 }
3998                 sa = bp->b_data;
3999                 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
4000                         int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
4001                         ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
4002                         ea = (caddr_t)(vm_offset_t)ulmin(
4003                             (u_long)(vm_offset_t)ea,
4004                             (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
4005                         mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4006                         if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
4007                                 continue;
4008                         if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
4009                                 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
4010                                         bzero(sa, ea - sa);
4011                                 }
4012                         } else {
4013                                 for (; sa < ea; sa += DEV_BSIZE, j++) {
4014                                         if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
4015                                                 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
4016                                                 bzero(sa, DEV_BSIZE);
4017                                 }
4018                         }
4019                         bp->b_xio.xio_pages[i]->valid |= mask;
4020                         vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
4021                 }
4022                 bp->b_resid = 0;
4023         } else {
4024                 clrbuf(bp);
4025         }
4026 }
4027
4028 /*
4029  * vm_hold_load_pages:
4030  *
4031  *      Load pages into the buffer's address space.  The pages are
4032  *      allocated from the kernel object in order to reduce interference
4033  *      with the any VM paging I/O activity.  The range of loaded
4034  *      pages will be wired.
4035  *
4036  *      If a page cannot be allocated, the 'pagedaemon' is woken up to
4037  *      retrieve the full range (to - from) of pages.
4038  *
4039  */
4040 void
4041 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4042 {
4043         vm_offset_t pg;
4044         vm_page_t p;
4045         int index;
4046
4047         to = round_page(to);
4048         from = round_page(from);
4049         index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4050
4051         pg = from;
4052         while (pg < to) {
4053                 /*
4054                  * Note: must allocate system pages since blocking here
4055                  * could intefere with paging I/O, no matter which
4056                  * process we are.
4057                  */
4058                 p = bio_page_alloc(&kernel_object, pg >> PAGE_SHIFT,
4059                                    (vm_pindex_t)((to - pg) >> PAGE_SHIFT));
4060                 if (p) {
4061                         vm_page_wire(p);
4062                         p->valid = VM_PAGE_BITS_ALL;
4063                         vm_page_flag_clear(p, PG_ZERO);
4064                         pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
4065                         bp->b_xio.xio_pages[index] = p;
4066                         vm_page_wakeup(p);
4067
4068                         pg += PAGE_SIZE;
4069                         ++index;
4070                 }
4071         }
4072         bp->b_xio.xio_npages = index;
4073 }
4074
4075 /*
4076  * Allocate pages for a buffer cache buffer.
4077  *
4078  * Under extremely severe memory conditions even allocating out of the
4079  * system reserve can fail.  If this occurs we must allocate out of the
4080  * interrupt reserve to avoid a deadlock with the pageout daemon.
4081  *
4082  * The pageout daemon can run (putpages -> VOP_WRITE -> getblk -> allocbuf).
4083  * If the buffer cache's vm_page_alloc() fails a vm_wait() can deadlock
4084  * against the pageout daemon if pages are not freed from other sources.
4085  */
4086 static
4087 vm_page_t
4088 bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit)
4089 {
4090         vm_page_t p;
4091
4092         /*
4093          * Try a normal allocation, allow use of system reserve.
4094          */
4095         p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
4096         if (p)
4097                 return(p);
4098
4099         /*
4100          * The normal allocation failed and we clearly have a page
4101          * deficit.  Try to reclaim some clean VM pages directly
4102          * from the buffer cache.
4103          */
4104         vm_pageout_deficit += deficit;
4105         recoverbufpages();
4106
4107         /*
4108          * We may have blocked, the caller will know what to do if the
4109          * page now exists.
4110          */
4111         if (vm_page_lookup(obj, pg))
4112                 return(NULL);
4113
4114         /*
4115          * Allocate and allow use of the interrupt reserve.
4116          *
4117          * If after all that we still can't allocate a VM page we are
4118          * in real trouble, but we slog on anyway hoping that the system
4119          * won't deadlock.
4120          */
4121         p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
4122                                    VM_ALLOC_INTERRUPT);
4123         if (p) {
4124                 if (vm_page_count_severe()) {
4125                         kprintf("bio_page_alloc: WARNING emergency page "
4126                                 "allocation\n");
4127                         vm_wait(hz / 20);
4128                 }
4129         } else {
4130                 kprintf("bio_page_alloc: WARNING emergency page "
4131                         "allocation failed\n");
4132                 vm_wait(hz * 5);
4133         }
4134         return(p);
4135 }
4136
4137 /*
4138  * vm_hold_free_pages:
4139  *
4140  *      Return pages associated with the buffer back to the VM system.
4141  *
4142  *      The range of pages underlying the buffer's address space will
4143  *      be unmapped and un-wired.
4144  */
4145 void
4146 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4147 {
4148         vm_offset_t pg;
4149         vm_page_t p;
4150         int index, newnpages;
4151
4152         from = round_page(from);
4153         to = round_page(to);
4154         newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4155
4156         for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4157                 p = bp->b_xio.xio_pages[index];
4158                 if (p && (index < bp->b_xio.xio_npages)) {
4159                         if (p->busy) {
4160                                 kprintf("vm_hold_free_pages: doffset: %lld, "
4161                                         "loffset: %lld\n",
4162                                         (long long)bp->b_bio2.bio_offset,
4163                                         (long long)bp->b_loffset);
4164                         }
4165                         bp->b_xio.xio_pages[index] = NULL;
4166                         pmap_kremove(pg);
4167                         vm_page_busy(p);
4168                         vm_page_unwire(p, 0);
4169                         vm_page_free(p);
4170                 }
4171         }
4172         bp->b_xio.xio_npages = newnpages;
4173 }
4174
4175 /*
4176  * vmapbuf:
4177  *
4178  *      Map a user buffer into KVM via a pbuf.  On return the buffer's
4179  *      b_data, b_bufsize, and b_bcount will be set, and its XIO page array
4180  *      initialized.
4181  */
4182 int
4183 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
4184 {
4185         caddr_t addr;
4186         vm_offset_t va;
4187         vm_page_t m;
4188         int vmprot;
4189         int error;
4190         int pidx;
4191         int i;
4192
4193         /* 
4194          * bp had better have a command and it better be a pbuf.
4195          */
4196         KKASSERT(bp->b_cmd != BUF_CMD_DONE);
4197         KKASSERT(bp->b_flags & B_PAGING);
4198
4199         if (bytes < 0)
4200                 return (-1);
4201
4202         /*
4203          * Map the user data into KVM.  Mappings have to be page-aligned.
4204          */
4205         addr = (caddr_t)trunc_page((vm_offset_t)udata);
4206         pidx = 0;
4207
4208         vmprot = VM_PROT_READ;
4209         if (bp->b_cmd == BUF_CMD_READ)
4210                 vmprot |= VM_PROT_WRITE;
4211
4212         while (addr < udata + bytes) {
4213                 /*
4214                  * Do the vm_fault if needed; do the copy-on-write thing
4215                  * when reading stuff off device into memory.
4216                  *
4217                  * vm_fault_page*() returns a held VM page.
4218                  */
4219                 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
4220                 va = trunc_page(va);
4221
4222                 m = vm_fault_page_quick(va, vmprot, &error);
4223                 if (m == NULL) {
4224                         for (i = 0; i < pidx; ++i) {
4225                             vm_page_unhold(bp->b_xio.xio_pages[i]);
4226                             bp->b_xio.xio_pages[i] = NULL;
4227                         }
4228                         return(-1);
4229                 }
4230                 bp->b_xio.xio_pages[pidx] = m;
4231                 addr += PAGE_SIZE;
4232                 ++pidx;
4233         }
4234
4235         /*
4236          * Map the page array and set the buffer fields to point to
4237          * the mapped data buffer.
4238          */
4239         if (pidx > btoc(MAXPHYS))
4240                 panic("vmapbuf: mapped more than MAXPHYS");
4241         pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
4242
4243         bp->b_xio.xio_npages = pidx;
4244         bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
4245         bp->b_bcount = bytes;
4246         bp->b_bufsize = bytes;
4247         return(0);
4248 }
4249
4250 /*
4251  * vunmapbuf:
4252  *
4253  *      Free the io map PTEs associated with this IO operation.
4254  *      We also invalidate the TLB entries and restore the original b_addr.
4255  */
4256 void
4257 vunmapbuf(struct buf *bp)
4258 {
4259         int pidx;
4260         int npages;
4261
4262         KKASSERT(bp->b_flags & B_PAGING);
4263
4264         npages = bp->b_xio.xio_npages;
4265         pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4266         for (pidx = 0; pidx < npages; ++pidx) {
4267                 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
4268                 bp->b_xio.xio_pages[pidx] = NULL;
4269         }
4270         bp->b_xio.xio_npages = 0;
4271         bp->b_data = bp->b_kvabase;
4272 }
4273
4274 /*
4275  * Scan all buffers in the system and issue the callback.
4276  */
4277 int
4278 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
4279 {
4280         int count = 0;
4281         int error;
4282         int n;
4283
4284         for (n = 0; n < nbuf; ++n) {
4285                 if ((error = callback(&buf[n], info)) < 0) {
4286                         count = error;
4287                         break;
4288                 }
4289                 count += error;
4290         }
4291         return (count);
4292 }
4293
4294 /*
4295  * print out statistics from the current status of the buffer pool
4296  * this can be toggeled by the system control option debug.syncprt
4297  */
4298 #ifdef DEBUG
4299 void
4300 vfs_bufstats(void)
4301 {
4302         int i, j, count;
4303         struct buf *bp;
4304         struct bqueues *dp;
4305         int counts[(MAXBSIZE / PAGE_SIZE) + 1];
4306         static char *bname[3] = { "LOCKED", "LRU", "AGE" };
4307
4308         for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
4309                 count = 0;
4310                 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4311                         counts[j] = 0;
4312                 crit_enter();
4313                 TAILQ_FOREACH(bp, dp, b_freelist) {
4314                         counts[bp->b_bufsize/PAGE_SIZE]++;
4315                         count++;
4316                 }
4317                 crit_exit();
4318                 kprintf("%s: total-%d", bname[i], count);
4319                 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4320                         if (counts[j] != 0)
4321                                 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
4322                 kprintf("\n");
4323         }
4324 }
4325 #endif
4326
4327 #ifdef DDB
4328
4329 DB_SHOW_COMMAND(buffer, db_show_buffer)
4330 {
4331         /* get args */
4332         struct buf *bp = (struct buf *)addr;
4333
4334         if (!have_addr) {
4335                 db_printf("usage: show buffer <addr>\n");
4336                 return;
4337         }
4338
4339         db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4340         db_printf("b_cmd = %d\n", bp->b_cmd);
4341         db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
4342                   "b_resid = %d\n, b_data = %p, "
4343                   "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
4344                   bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4345                   bp->b_data,
4346                   (long long)bp->b_bio2.bio_offset,
4347                   (long long)(bp->b_bio2.bio_next ?
4348                                 bp->b_bio2.bio_next->bio_offset : (off_t)-1));
4349         if (bp->b_xio.xio_npages) {
4350                 int i;
4351                 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
4352                         bp->b_xio.xio_npages);
4353                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4354                         vm_page_t m;
4355                         m = bp->b_xio.xio_pages[i];
4356                         db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4357                             (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4358                         if ((i + 1) < bp->b_xio.xio_npages)
4359                                 db_printf(",");
4360                 }
4361                 db_printf("\n");
4362         }
4363 }
4364 #endif /* DDB */