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