Merge branch 'master' of ssh://crater.dragonflybsd.org/repository/git/dragonfly
[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                  * This is a very important bit of code.  We try to track
1650                  * VM page use whether the pages are wired into the buffer
1651                  * cache or not.  While wired into the buffer cache the
1652                  * bp tracks the act_count.
1653                  *
1654                  * We can choose to place unwired pages on the inactive
1655                  * queue (0) or active queue (1).  If we place too many
1656                  * on the active queue the queue will cycle the act_count
1657                  * on pages we'd like to keep, just from single-use pages
1658                  * (such as when doing a tar-up or file scan).
1659                  */
1660                 if (bp->b_act_count < vm_cycle_point)
1661                         vm_page_unwire(m, 0);
1662                 else
1663                         vm_page_unwire(m, 1);
1664
1665                 /*
1666                  * We don't mess with busy pages, it is
1667                  * the responsibility of the process that
1668                  * busied the pages to deal with them.
1669                  */
1670                 if ((m->flags & PG_BUSY) || (m->busy != 0))
1671                         continue;
1672                         
1673                 if (m->wire_count == 0) {
1674                         vm_page_flag_clear(m, PG_ZERO);
1675                         /*
1676                          * Might as well free the page if we can and it has
1677                          * no valid data.  We also free the page if the
1678                          * buffer was used for direct I/O.
1679                          */
1680 #if 0
1681                         if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1682                                         m->hold_count == 0) {
1683                                 vm_page_busy(m);
1684                                 vm_page_protect(m, VM_PROT_NONE);
1685                                 vm_page_free(m);
1686                         } else
1687 #endif
1688                         if (bp->b_flags & B_DIRECT) {
1689                                 vm_page_try_to_free(m);
1690                         } else if (vm_page_count_severe()) {
1691                                 m->act_count = bp->b_act_count;
1692                                 vm_page_try_to_cache(m);
1693                         } else {
1694                                 m->act_count = bp->b_act_count;
1695                         }
1696                 }
1697         }
1698         crit_exit();
1699         pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1700         if (bp->b_bufsize) {
1701                 bufspacewakeup();
1702                 bp->b_bufsize = 0;
1703         }
1704         bp->b_xio.xio_npages = 0;
1705         bp->b_flags &= ~B_VMIO;
1706         KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1707         if (bp->b_vp) {
1708                 get_mplock();
1709                 brelvp(bp);
1710                 rel_mplock();
1711         }
1712 }
1713
1714 /*
1715  * vfs_bio_awrite:
1716  *
1717  *      Implement clustered async writes for clearing out B_DELWRI buffers.
1718  *      This is much better then the old way of writing only one buffer at
1719  *      a time.  Note that we may not be presented with the buffers in the 
1720  *      correct order, so we search for the cluster in both directions.
1721  *
1722  *      The buffer is locked on call.
1723  */
1724 int
1725 vfs_bio_awrite(struct buf *bp)
1726 {
1727         int i;
1728         int j;
1729         off_t loffset = bp->b_loffset;
1730         struct vnode *vp = bp->b_vp;
1731         int nbytes;
1732         struct buf *bpa;
1733         int nwritten;
1734         int size;
1735
1736         /*
1737          * right now we support clustered writing only to regular files.  If
1738          * we find a clusterable block we could be in the middle of a cluster
1739          * rather then at the beginning.
1740          *
1741          * NOTE: b_bio1 contains the logical loffset and is aliased
1742          * to b_loffset.  b_bio2 contains the translated block number.
1743          */
1744         if ((vp->v_type == VREG) && 
1745             (vp->v_mount != 0) && /* Only on nodes that have the size info */
1746             (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1747
1748                 size = vp->v_mount->mnt_stat.f_iosize;
1749
1750                 for (i = size; i < MAXPHYS; i += size) {
1751                         if ((bpa = findblk(vp, loffset + i, FINDBLK_TEST)) &&
1752                             BUF_REFCNT(bpa) == 0 &&
1753                             ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1754                             (B_DELWRI | B_CLUSTEROK)) &&
1755                             (bpa->b_bufsize == size)) {
1756                                 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1757                                     (bpa->b_bio2.bio_offset !=
1758                                      bp->b_bio2.bio_offset + i))
1759                                         break;
1760                         } else {
1761                                 break;
1762                         }
1763                 }
1764                 for (j = size; i + j <= MAXPHYS && j <= loffset; j += size) {
1765                         if ((bpa = findblk(vp, loffset - j, FINDBLK_TEST)) &&
1766                             BUF_REFCNT(bpa) == 0 &&
1767                             ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1768                             (B_DELWRI | B_CLUSTEROK)) &&
1769                             (bpa->b_bufsize == size)) {
1770                                 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1771                                     (bpa->b_bio2.bio_offset !=
1772                                      bp->b_bio2.bio_offset - j))
1773                                         break;
1774                         } else {
1775                                 break;
1776                         }
1777                 }
1778                 j -= size;
1779                 nbytes = (i + j);
1780
1781                 /*
1782                  * this is a possible cluster write
1783                  */
1784                 if (nbytes != size) {
1785                         BUF_UNLOCK(bp);
1786                         nwritten = cluster_wbuild(vp, size,
1787                                                   loffset - j, nbytes);
1788                         return nwritten;
1789                 }
1790         }
1791
1792         /*
1793          * default (old) behavior, writing out only one block
1794          *
1795          * XXX returns b_bufsize instead of b_bcount for nwritten?
1796          */
1797         nwritten = bp->b_bufsize;
1798         bremfree(bp);
1799         bawrite(bp);
1800
1801         return nwritten;
1802 }
1803
1804 /*
1805  * getnewbuf:
1806  *
1807  *      Find and initialize a new buffer header, freeing up existing buffers 
1808  *      in the bufqueues as necessary.  The new buffer is returned locked.
1809  *
1810  *      Important:  B_INVAL is not set.  If the caller wishes to throw the
1811  *      buffer away, the caller must set B_INVAL prior to calling brelse().
1812  *
1813  *      We block if:
1814  *              We have insufficient buffer headers
1815  *              We have insufficient buffer space
1816  *              buffer_map is too fragmented ( space reservation fails )
1817  *              If we have to flush dirty buffers ( but we try to avoid this )
1818  *
1819  *      To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1820  *      Instead we ask the buf daemon to do it for us.  We attempt to
1821  *      avoid piecemeal wakeups of the pageout daemon.
1822  *
1823  * MPALMOSTSAFE
1824  */
1825 static struct buf *
1826 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1827 {
1828         struct buf *bp;
1829         struct buf *nbp;
1830         int defrag = 0;
1831         int nqindex;
1832         int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1833         static int flushingbufs;
1834
1835         /*
1836          * We can't afford to block since we might be holding a vnode lock,
1837          * which may prevent system daemons from running.  We deal with
1838          * low-memory situations by proactively returning memory and running
1839          * async I/O rather then sync I/O.
1840          */
1841         
1842         ++getnewbufcalls;
1843         --getnewbufrestarts;
1844 restart:
1845         ++getnewbufrestarts;
1846
1847         /*
1848          * Setup for scan.  If we do not have enough free buffers,
1849          * we setup a degenerate case that immediately fails.  Note
1850          * that if we are specially marked process, we are allowed to
1851          * dip into our reserves.
1852          *
1853          * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1854          *
1855          * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1856          * However, there are a number of cases (defragging, reusing, ...)
1857          * where we cannot backup.
1858          */
1859         nqindex = BQUEUE_EMPTYKVA;
1860         spin_lock_wr(&bufspin);
1861         nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1862
1863         if (nbp == NULL) {
1864                 /*
1865                  * If no EMPTYKVA buffers and we are either
1866                  * defragging or reusing, locate a CLEAN buffer
1867                  * to free or reuse.  If bufspace useage is low
1868                  * skip this step so we can allocate a new buffer.
1869                  */
1870                 if (defrag || bufspace >= lobufspace) {
1871                         nqindex = BQUEUE_CLEAN;
1872                         nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1873                 }
1874
1875                 /*
1876                  * If we could not find or were not allowed to reuse a
1877                  * CLEAN buffer, check to see if it is ok to use an EMPTY
1878                  * buffer.  We can only use an EMPTY buffer if allocating
1879                  * its KVA would not otherwise run us out of buffer space.
1880                  */
1881                 if (nbp == NULL && defrag == 0 &&
1882                     bufspace + maxsize < hibufspace) {
1883                         nqindex = BQUEUE_EMPTY;
1884                         nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1885                 }
1886         }
1887
1888         /*
1889          * Run scan, possibly freeing data and/or kva mappings on the fly
1890          * depending.
1891          *
1892          * WARNING!  bufspin is held!
1893          */
1894         while ((bp = nbp) != NULL) {
1895                 int qindex = nqindex;
1896
1897                 nbp = TAILQ_NEXT(bp, b_freelist);
1898
1899                 /*
1900                  * BQUEUE_CLEAN - B_AGE special case.  If not set the bp
1901                  * cycles through the queue twice before being selected.
1902                  */
1903                 if (qindex == BQUEUE_CLEAN && 
1904                     (bp->b_flags & B_AGE) == 0 && nbp) {
1905                         bp->b_flags |= B_AGE;
1906                         TAILQ_REMOVE(&bufqueues[qindex], bp, b_freelist);
1907                         TAILQ_INSERT_TAIL(&bufqueues[qindex], bp, b_freelist);
1908                         continue;
1909                 }
1910
1911                 /*
1912                  * Calculate next bp ( we can only use it if we do not block
1913                  * or do other fancy things ).
1914                  */
1915                 if (nbp == NULL) {
1916                         switch(qindex) {
1917                         case BQUEUE_EMPTY:
1918                                 nqindex = BQUEUE_EMPTYKVA;
1919                                 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1920                                         break;
1921                                 /* fall through */
1922                         case BQUEUE_EMPTYKVA:
1923                                 nqindex = BQUEUE_CLEAN;
1924                                 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1925                                         break;
1926                                 /* fall through */
1927                         case BQUEUE_CLEAN:
1928                                 /*
1929                                  * nbp is NULL. 
1930                                  */
1931                                 break;
1932                         }
1933                 }
1934
1935                 /*
1936                  * Sanity Checks
1937                  */
1938                 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1939
1940                 /*
1941                  * Note: we no longer distinguish between VMIO and non-VMIO
1942                  * buffers.
1943                  */
1944
1945                 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1946
1947                 /*
1948                  * If we are defragging then we need a buffer with 
1949                  * b_kvasize != 0.  XXX this situation should no longer
1950                  * occur, if defrag is non-zero the buffer's b_kvasize
1951                  * should also be non-zero at this point.  XXX
1952                  */
1953                 if (defrag && bp->b_kvasize == 0) {
1954                         kprintf("Warning: defrag empty buffer %p\n", bp);
1955                         continue;
1956                 }
1957
1958                 /*
1959                  * Start freeing the bp.  This is somewhat involved.  nbp
1960                  * remains valid only for BQUEUE_EMPTY[KVA] bp's.  Buffers
1961                  * on the clean list must be disassociated from their 
1962                  * current vnode.  Buffers on the empty[kva] lists have
1963                  * already been disassociated.
1964                  */
1965
1966                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1967                         spin_unlock_wr(&bufspin);
1968                         kprintf("getnewbuf: warning, locked buf %p, race corrected\n", bp);
1969                         tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1970                         goto restart;
1971                 }
1972                 if (bp->b_qindex != qindex) {
1973                         spin_unlock_wr(&bufspin);
1974                         kprintf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp, qindex, bp->b_qindex);
1975                         BUF_UNLOCK(bp);
1976                         goto restart;
1977                 }
1978                 bremfree_locked(bp);
1979                 spin_unlock_wr(&bufspin);
1980
1981                 /*
1982                  * Dependancies must be handled before we disassociate the
1983                  * vnode.
1984                  *
1985                  * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1986                  * be immediately disassociated.  HAMMER then becomes
1987                  * responsible for releasing the buffer.
1988                  *
1989                  * NOTE: bufspin is UNLOCKED now.
1990                  */
1991                 if (LIST_FIRST(&bp->b_dep) != NULL) {
1992                         get_mplock();
1993                         buf_deallocate(bp);
1994                         rel_mplock();
1995                         if (bp->b_flags & B_LOCKED) {
1996                                 bqrelse(bp);
1997                                 goto restart;
1998                         }
1999                         KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2000                 }
2001
2002                 if (qindex == BQUEUE_CLEAN) {
2003                         get_mplock();
2004                         if (bp->b_flags & B_VMIO) {
2005                                 get_mplock();
2006                                 vfs_vmio_release(bp);
2007                                 rel_mplock();
2008                         }
2009                         if (bp->b_vp)
2010                                 brelvp(bp);
2011                         rel_mplock();
2012                 }
2013
2014                 /*
2015                  * NOTE:  nbp is now entirely invalid.  We can only restart
2016                  * the scan from this point on.
2017                  *
2018                  * Get the rest of the buffer freed up.  b_kva* is still
2019                  * valid after this operation.
2020                  */
2021
2022                 KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
2023                 KKASSERT((bp->b_flags & B_HASHED) == 0);
2024
2025                 /*
2026                  * critical section protection is not required when
2027                  * scrapping a buffer's contents because it is already 
2028                  * wired.
2029                  */
2030                 if (bp->b_bufsize) {
2031                         get_mplock();
2032                         allocbuf(bp, 0);
2033                         rel_mplock();
2034                 }
2035
2036                 bp->b_flags = B_BNOCLIP;
2037                 bp->b_cmd = BUF_CMD_DONE;
2038                 bp->b_vp = NULL;
2039                 bp->b_error = 0;
2040                 bp->b_resid = 0;
2041                 bp->b_bcount = 0;
2042                 bp->b_xio.xio_npages = 0;
2043                 bp->b_dirtyoff = bp->b_dirtyend = 0;
2044                 bp->b_act_count = ACT_INIT;
2045                 reinitbufbio(bp);
2046                 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2047                 buf_dep_init(bp);
2048                 if (blkflags & GETBLK_BHEAVY)
2049                         bp->b_flags |= B_HEAVY;
2050
2051                 /*
2052                  * If we are defragging then free the buffer.
2053                  */
2054                 if (defrag) {
2055                         bp->b_flags |= B_INVAL;
2056                         bfreekva(bp);
2057                         brelse(bp);
2058                         defrag = 0;
2059                         goto restart;
2060                 }
2061
2062                 /*
2063                  * If we are overcomitted then recover the buffer and its
2064                  * KVM space.  This occurs in rare situations when multiple
2065                  * processes are blocked in getnewbuf() or allocbuf().
2066                  */
2067                 if (bufspace >= hibufspace)
2068                         flushingbufs = 1;
2069                 if (flushingbufs && bp->b_kvasize != 0) {
2070                         bp->b_flags |= B_INVAL;
2071                         bfreekva(bp);
2072                         brelse(bp);
2073                         goto restart;
2074                 }
2075                 if (bufspace < lobufspace)
2076                         flushingbufs = 0;
2077                 break;
2078                 /* NOT REACHED, bufspin not held */
2079         }
2080
2081         /*
2082          * If we exhausted our list, sleep as appropriate.  We may have to
2083          * wakeup various daemons and write out some dirty buffers.
2084          *
2085          * Generally we are sleeping due to insufficient buffer space.
2086          *
2087          * NOTE: bufspin is held if bp is NULL, else it is not held.
2088          */
2089         if (bp == NULL) {
2090                 int flags;
2091                 char *waitmsg;
2092
2093                 spin_unlock_wr(&bufspin);
2094                 if (defrag) {
2095                         flags = VFS_BIO_NEED_BUFSPACE;
2096                         waitmsg = "nbufkv";
2097                 } else if (bufspace >= hibufspace) {
2098                         waitmsg = "nbufbs";
2099                         flags = VFS_BIO_NEED_BUFSPACE;
2100                 } else {
2101                         waitmsg = "newbuf";
2102                         flags = VFS_BIO_NEED_ANY;
2103                 }
2104
2105                 needsbuffer |= flags;
2106                 bd_speedup();   /* heeeelp */
2107                 while (needsbuffer & flags) {
2108                         if (tsleep(&needsbuffer, slpflags, waitmsg, slptimeo))
2109                                 return (NULL);
2110                 }
2111         } else {
2112                 /*
2113                  * We finally have a valid bp.  We aren't quite out of the
2114                  * woods, we still have to reserve kva space.  In order
2115                  * to keep fragmentation sane we only allocate kva in
2116                  * BKVASIZE chunks.
2117                  *
2118                  * (bufspin is not held)
2119                  */
2120                 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2121
2122                 if (maxsize != bp->b_kvasize) {
2123                         vm_offset_t addr = 0;
2124                         int count;
2125
2126                         bfreekva(bp);
2127
2128                         get_mplock();
2129                         count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2130                         vm_map_lock(&buffer_map);
2131
2132                         if (vm_map_findspace(&buffer_map,
2133                                     vm_map_min(&buffer_map), maxsize,
2134                                     maxsize, 0, &addr)) {
2135                                 /*
2136                                  * Uh oh.  Buffer map is too fragmented.  We
2137                                  * must defragment the map.
2138                                  */
2139                                 vm_map_unlock(&buffer_map);
2140                                 vm_map_entry_release(count);
2141                                 ++bufdefragcnt;
2142                                 defrag = 1;
2143                                 bp->b_flags |= B_INVAL;
2144                                 rel_mplock();
2145                                 brelse(bp);
2146                                 goto restart;
2147                         }
2148                         if (addr) {
2149                                 vm_map_insert(&buffer_map, &count,
2150                                         NULL, 0,
2151                                         addr, addr + maxsize,
2152                                         VM_MAPTYPE_NORMAL,
2153                                         VM_PROT_ALL, VM_PROT_ALL,
2154                                         MAP_NOFAULT);
2155
2156                                 bp->b_kvabase = (caddr_t) addr;
2157                                 bp->b_kvasize = maxsize;
2158                                 bufspace += bp->b_kvasize;
2159                                 ++bufreusecnt;
2160                         }
2161                         vm_map_unlock(&buffer_map);
2162                         vm_map_entry_release(count);
2163                         rel_mplock();
2164                 }
2165                 bp->b_data = bp->b_kvabase;
2166         }
2167         return(bp);
2168 }
2169
2170 /*
2171  * This routine is called in an emergency to recover VM pages from the
2172  * buffer cache by cashing in clean buffers.  The idea is to recover
2173  * enough pages to be able to satisfy a stuck bio_page_alloc().
2174  */
2175 static int
2176 recoverbufpages(void)
2177 {
2178         struct buf *bp;
2179         int bytes = 0;
2180
2181         ++recoverbufcalls;
2182
2183         spin_lock_wr(&bufspin);
2184         while (bytes < MAXBSIZE) {
2185                 bp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
2186                 if (bp == NULL)
2187                         break;
2188
2189                 /*
2190                  * BQUEUE_CLEAN - B_AGE special case.  If not set the bp
2191                  * cycles through the queue twice before being selected.
2192                  */
2193                 if ((bp->b_flags & B_AGE) == 0 && TAILQ_NEXT(bp, b_freelist)) {
2194                         bp->b_flags |= B_AGE;
2195                         TAILQ_REMOVE(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
2196                         TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN],
2197                                           bp, b_freelist);
2198                         continue;
2199                 }
2200
2201                 /*
2202                  * Sanity Checks
2203                  */
2204                 KKASSERT(bp->b_qindex == BQUEUE_CLEAN);
2205                 KKASSERT((bp->b_flags & B_DELWRI) == 0);
2206
2207                 /*
2208                  * Start freeing the bp.  This is somewhat involved.
2209                  *
2210                  * Buffers on the clean list must be disassociated from
2211                  * their current vnode
2212                  */
2213
2214                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
2215                         kprintf("recoverbufpages: warning, locked buf %p, race corrected\n", bp);
2216                         tsleep(&bd_request, 0, "gnbxxx", hz / 100);
2217                         continue;
2218                 }
2219                 if (bp->b_qindex != BQUEUE_CLEAN) {
2220                         kprintf("recoverbufpages: warning, BUF_LOCK blocked unexpectedly on buf %p index %d, race corrected\n", bp, bp->b_qindex);
2221                         BUF_UNLOCK(bp);
2222                         continue;
2223                 }
2224                 bremfree_locked(bp);
2225                 spin_unlock_wr(&bufspin);
2226
2227                 /*
2228                  * Dependancies must be handled before we disassociate the
2229                  * vnode.
2230                  *
2231                  * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2232                  * be immediately disassociated.  HAMMER then becomes
2233                  * responsible for releasing the buffer.
2234                  */
2235                 if (LIST_FIRST(&bp->b_dep) != NULL) {
2236                         buf_deallocate(bp);
2237                         if (bp->b_flags & B_LOCKED) {
2238                                 bqrelse(bp);
2239                                 spin_lock_wr(&bufspin);
2240                                 continue;
2241                         }
2242                         KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2243                 }
2244
2245                 bytes += bp->b_bufsize;
2246
2247                 get_mplock();
2248                 if (bp->b_flags & B_VMIO) {
2249                         bp->b_flags |= B_DIRECT;    /* try to free pages */
2250                         vfs_vmio_release(bp);
2251                 }
2252                 if (bp->b_vp)
2253                         brelvp(bp);
2254
2255                 KKASSERT(bp->b_vp == NULL);
2256                 KKASSERT((bp->b_flags & B_HASHED) == 0);
2257
2258                 /*
2259                  * critical section protection is not required when
2260                  * scrapping a buffer's contents because it is already 
2261                  * wired.
2262                  */
2263                 if (bp->b_bufsize)
2264                         allocbuf(bp, 0);
2265                 rel_mplock();
2266
2267                 bp->b_flags = B_BNOCLIP;
2268                 bp->b_cmd = BUF_CMD_DONE;
2269                 bp->b_vp = NULL;
2270                 bp->b_error = 0;
2271                 bp->b_resid = 0;
2272                 bp->b_bcount = 0;
2273                 bp->b_xio.xio_npages = 0;
2274                 bp->b_dirtyoff = bp->b_dirtyend = 0;
2275                 reinitbufbio(bp);
2276                 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2277                 buf_dep_init(bp);
2278                 bp->b_flags |= B_INVAL;
2279                 /* bfreekva(bp); */
2280                 brelse(bp);
2281                 spin_lock_wr(&bufspin);
2282         }
2283         spin_unlock_wr(&bufspin);
2284         return(bytes);
2285 }
2286
2287 /*
2288  * buf_daemon:
2289  *
2290  *      Buffer flushing daemon.  Buffers are normally flushed by the
2291  *      update daemon but if it cannot keep up this process starts to
2292  *      take the load in an attempt to prevent getnewbuf() from blocking.
2293  *
2294  *      Once a flush is initiated it does not stop until the number
2295  *      of buffers falls below lodirtybuffers, but we will wake up anyone
2296  *      waiting at the mid-point.
2297  */
2298
2299 static struct kproc_desc buf_kp = {
2300         "bufdaemon",
2301         buf_daemon,
2302         &bufdaemon_td
2303 };
2304 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2305         kproc_start, &buf_kp)
2306
2307 static struct kproc_desc bufhw_kp = {
2308         "bufdaemon_hw",
2309         buf_daemon_hw,
2310         &bufdaemonhw_td
2311 };
2312 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2313         kproc_start, &bufhw_kp)
2314
2315 static void
2316 buf_daemon(void)
2317 {
2318         int limit;
2319
2320         /*
2321          * This process needs to be suspended prior to shutdown sync.
2322          */
2323         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2324                               bufdaemon_td, SHUTDOWN_PRI_LAST);
2325         curthread->td_flags |= TDF_SYSTHREAD;
2326
2327         /*
2328          * This process is allowed to take the buffer cache to the limit
2329          */
2330         crit_enter();
2331
2332         for (;;) {
2333                 kproc_suspend_loop();
2334
2335                 /*
2336                  * Do the flush as long as the number of dirty buffers
2337                  * (including those running) exceeds lodirtybufspace.
2338                  *
2339                  * When flushing limit running I/O to hirunningspace
2340                  * Do the flush.  Limit the amount of in-transit I/O we
2341                  * allow to build up, otherwise we would completely saturate
2342                  * the I/O system.  Wakeup any waiting processes before we
2343                  * normally would so they can run in parallel with our drain.
2344                  *
2345                  * Our aggregate normal+HW lo water mark is lodirtybufspace,
2346                  * but because we split the operation into two threads we
2347                  * have to cut it in half for each thread.
2348                  */
2349                 waitrunningbufspace();
2350                 limit = lodirtybufspace / 2;
2351                 while (runningbufspace + dirtybufspace > limit ||
2352                        dirtybufcount - dirtybufcounthw >= nbuf / 2) {
2353                         if (flushbufqueues(BQUEUE_DIRTY) == 0)
2354                                 break;
2355                         if (runningbufspace < hirunningspace)
2356                                 continue;
2357                         waitrunningbufspace();
2358                 }
2359
2360                 /*
2361                  * We reached our low water mark, reset the
2362                  * request and sleep until we are needed again.
2363                  * The sleep is just so the suspend code works.
2364                  */
2365                 spin_lock_wr(&needsbuffer_spin);
2366                 if (bd_request == 0) {
2367                         ssleep(&bd_request, &needsbuffer_spin, 0,
2368                                "psleep", hz);
2369                 }
2370                 bd_request = 0;
2371                 spin_unlock_wr(&needsbuffer_spin);
2372         }
2373 }
2374
2375 static void
2376 buf_daemon_hw(void)
2377 {
2378         int limit;
2379
2380         /*
2381          * This process needs to be suspended prior to shutdown sync.
2382          */
2383         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2384                               bufdaemonhw_td, SHUTDOWN_PRI_LAST);
2385         curthread->td_flags |= TDF_SYSTHREAD;
2386
2387         /*
2388          * This process is allowed to take the buffer cache to the limit
2389          */
2390         crit_enter();
2391
2392         for (;;) {
2393                 kproc_suspend_loop();
2394
2395                 /*
2396                  * Do the flush.  Limit the amount of in-transit I/O we
2397                  * allow to build up, otherwise we would completely saturate
2398                  * the I/O system.  Wakeup any waiting processes before we
2399                  * normally would so they can run in parallel with our drain.
2400                  *
2401                  * Once we decide to flush push the queued I/O up to
2402                  * hirunningspace in order to trigger bursting by the bioq
2403                  * subsystem.
2404                  *
2405                  * Our aggregate normal+HW lo water mark is lodirtybufspace,
2406                  * but because we split the operation into two threads we
2407                  * have to cut it in half for each thread.
2408                  */
2409                 waitrunningbufspace();
2410                 limit = lodirtybufspace / 2;
2411                 while (runningbufspace + dirtybufspacehw > limit ||
2412                        dirtybufcounthw >= nbuf / 2) {
2413                         if (flushbufqueues(BQUEUE_DIRTY_HW) == 0)
2414                                 break;
2415                         if (runningbufspace < hirunningspace)
2416                                 continue;
2417                         waitrunningbufspace();
2418                 }
2419
2420                 /*
2421                  * We reached our low water mark, reset the
2422                  * request and sleep until we are needed again.
2423                  * The sleep is just so the suspend code works.
2424                  */
2425                 spin_lock_wr(&needsbuffer_spin);
2426                 if (bd_request_hw == 0) {
2427                         ssleep(&bd_request_hw, &needsbuffer_spin, 0,
2428                                "psleep", hz);
2429                 }
2430                 bd_request_hw = 0;
2431                 spin_unlock_wr(&needsbuffer_spin);
2432         }
2433 }
2434
2435 /*
2436  * flushbufqueues:
2437  *
2438  *      Try to flush a buffer in the dirty queue.  We must be careful to
2439  *      free up B_INVAL buffers instead of write them, which NFS is 
2440  *      particularly sensitive to.
2441  *
2442  *      B_RELBUF may only be set by VFSs.  We do set B_AGE to indicate
2443  *      that we really want to try to get the buffer out and reuse it
2444  *      due to the write load on the machine.
2445  */
2446 static int
2447 flushbufqueues(bufq_type_t q)
2448 {
2449         struct buf *bp;
2450         int r = 0;
2451         int spun;
2452
2453         spin_lock_wr(&bufspin);
2454         spun = 1;
2455
2456         bp = TAILQ_FIRST(&bufqueues[q]);
2457         while (bp) {
2458                 KASSERT((bp->b_flags & B_DELWRI),
2459                         ("unexpected clean buffer %p", bp));
2460
2461                 if (bp->b_flags & B_DELWRI) {
2462                         if (bp->b_flags & B_INVAL) {
2463                                 spin_unlock_wr(&bufspin);
2464                                 spun = 0;
2465                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2466                                         panic("flushbufqueues: locked buf");
2467                                 bremfree(bp);
2468                                 brelse(bp);
2469                                 ++r;
2470                                 break;
2471                         }
2472                         if (LIST_FIRST(&bp->b_dep) != NULL &&
2473                             (bp->b_flags & B_DEFERRED) == 0 &&
2474                             buf_countdeps(bp, 0)) {
2475                                 TAILQ_REMOVE(&bufqueues[q], bp, b_freelist);
2476                                 TAILQ_INSERT_TAIL(&bufqueues[q], bp,
2477                                                   b_freelist);
2478                                 bp->b_flags |= B_DEFERRED;
2479                                 bp = TAILQ_FIRST(&bufqueues[q]);
2480                                 continue;
2481                         }
2482
2483                         /*
2484                          * Only write it out if we can successfully lock
2485                          * it.  If the buffer has a dependancy,
2486                          * buf_checkwrite must also return 0 for us to
2487                          * be able to initate the write.
2488                          *
2489                          * If the buffer is flagged B_ERROR it may be
2490                          * requeued over and over again, we try to
2491                          * avoid a live lock.
2492                          */
2493                         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
2494                                 spin_unlock_wr(&bufspin);
2495                                 spun = 0;
2496                                 if (LIST_FIRST(&bp->b_dep) != NULL &&
2497                                     buf_checkwrite(bp)) {
2498                                         bremfree(bp);
2499                                         brelse(bp);
2500                                 } else if (bp->b_flags & B_ERROR) {
2501                                         tsleep(bp, 0, "bioer", 1);
2502                                         bp->b_flags &= ~B_AGE;
2503                                         vfs_bio_awrite(bp);
2504                                 } else {
2505                                         bp->b_flags |= B_AGE;
2506                                         vfs_bio_awrite(bp);
2507                                 }
2508                                 ++r;
2509                                 break;
2510                         }
2511                 }
2512                 bp = TAILQ_NEXT(bp, b_freelist);
2513         }
2514         if (spun)
2515                 spin_unlock_wr(&bufspin);
2516         return (r);
2517 }
2518
2519 /*
2520  * inmem:
2521  *
2522  *      Returns true if no I/O is needed to access the associated VM object.
2523  *      This is like findblk except it also hunts around in the VM system for
2524  *      the data.
2525  *
2526  *      Note that we ignore vm_page_free() races from interrupts against our
2527  *      lookup, since if the caller is not protected our return value will not
2528  *      be any more valid then otherwise once we exit the critical section.
2529  */
2530 int
2531 inmem(struct vnode *vp, off_t loffset)
2532 {
2533         vm_object_t obj;
2534         vm_offset_t toff, tinc, size;
2535         vm_page_t m;
2536
2537         if (findblk(vp, loffset, FINDBLK_TEST))
2538                 return 1;
2539         if (vp->v_mount == NULL)
2540                 return 0;
2541         if ((obj = vp->v_object) == NULL)
2542                 return 0;
2543
2544         size = PAGE_SIZE;
2545         if (size > vp->v_mount->mnt_stat.f_iosize)
2546                 size = vp->v_mount->mnt_stat.f_iosize;
2547
2548         for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2549                 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2550                 if (m == NULL)
2551                         return 0;
2552                 tinc = size;
2553                 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2554                         tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2555                 if (vm_page_is_valid(m,
2556                     (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0)
2557                         return 0;
2558         }
2559         return 1;
2560 }
2561
2562 /*
2563  * findblk:
2564  *
2565  *      Locate and return the specified buffer.  Unless flagged otherwise,
2566  *      a locked buffer will be returned if it exists or NULL if it does not.
2567  *
2568  *      findblk()'d buffers are still on the bufqueues and if you intend
2569  *      to use your (locked NON-TEST) buffer you need to bremfree(bp)
2570  *      and possibly do other stuff to it.
2571  *
2572  *      FINDBLK_TEST    - Do not lock the buffer.  The caller is responsible
2573  *                        for locking the buffer and ensuring that it remains
2574  *                        the desired buffer after locking.
2575  *
2576  *      FINDBLK_NBLOCK  - Lock the buffer non-blocking.  If we are unable
2577  *                        to acquire the lock we return NULL, even if the
2578  *                        buffer exists.
2579  *
2580  *      (0)             - Lock the buffer blocking.
2581  *
2582  * MPSAFE
2583  */
2584 struct buf *
2585 findblk(struct vnode *vp, off_t loffset, int flags)
2586 {
2587         lwkt_tokref vlock;
2588         struct buf *bp;
2589         int lkflags;
2590
2591         lkflags = LK_EXCLUSIVE;
2592         if (flags & FINDBLK_NBLOCK)
2593                 lkflags |= LK_NOWAIT;
2594
2595         for (;;) {
2596                 lwkt_gettoken(&vlock, &vp->v_token);
2597                 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2598                 lwkt_reltoken(&vlock);
2599                 if (bp == NULL || (flags & FINDBLK_TEST))
2600                         break;
2601                 if (BUF_LOCK(bp, lkflags)) {
2602                         bp = NULL;
2603                         break;
2604                 }
2605                 if (bp->b_vp == vp && bp->b_loffset == loffset)
2606                         break;
2607                 BUF_UNLOCK(bp);
2608         }
2609         return(bp);
2610 }
2611
2612 /*
2613  * getcacheblk:
2614  *
2615  *      Similar to getblk() except only returns the buffer if it is
2616  *      B_CACHE and requires no other manipulation.  Otherwise NULL
2617  *      is returned.
2618  *
2619  *      If B_RAM is set the buffer might be just fine, but we return
2620  *      NULL anyway because we want the code to fall through to the
2621  *      cluster read.  Otherwise read-ahead breaks.
2622  */
2623 struct buf *
2624 getcacheblk(struct vnode *vp, off_t loffset)
2625 {
2626         struct buf *bp;
2627
2628         bp = findblk(vp, loffset, 0);
2629         if (bp) {
2630                 if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) == B_CACHE) {
2631                         bp->b_flags &= ~B_AGE;
2632                         bremfree(bp);
2633                 } else {
2634                         BUF_UNLOCK(bp);
2635                         bp = NULL;
2636                 }
2637         }
2638         return (bp);
2639 }
2640
2641 /*
2642  * getblk:
2643  *
2644  *      Get a block given a specified block and offset into a file/device.
2645  *      B_INVAL may or may not be set on return.  The caller should clear
2646  *      B_INVAL prior to initiating a READ.
2647  *
2648  *      IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2649  *      IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2650  *      OR SET B_INVAL BEFORE RETIRING IT.  If you retire a getblk'd buffer
2651  *      without doing any of those things the system will likely believe
2652  *      the buffer to be valid (especially if it is not B_VMIO), and the
2653  *      next getblk() will return the buffer with B_CACHE set.
2654  *
2655  *      For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2656  *      an existing buffer.
2657  *
2658  *      For a VMIO buffer, B_CACHE is modified according to the backing VM.
2659  *      If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2660  *      and then cleared based on the backing VM.  If the previous buffer is
2661  *      non-0-sized but invalid, B_CACHE will be cleared.
2662  *
2663  *      If getblk() must create a new buffer, the new buffer is returned with
2664  *      both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2665  *      case it is returned with B_INVAL clear and B_CACHE set based on the
2666  *      backing VM.
2667  *
2668  *      getblk() also forces a bwrite() for any B_DELWRI buffer whos
2669  *      B_CACHE bit is clear.
2670  *      
2671  *      What this means, basically, is that the caller should use B_CACHE to
2672  *      determine whether the buffer is fully valid or not and should clear
2673  *      B_INVAL prior to issuing a read.  If the caller intends to validate
2674  *      the buffer by loading its data area with something, the caller needs
2675  *      to clear B_INVAL.  If the caller does this without issuing an I/O, 
2676  *      the caller should set B_CACHE ( as an optimization ), else the caller
2677  *      should issue the I/O and biodone() will set B_CACHE if the I/O was
2678  *      a write attempt or if it was a successfull read.  If the caller 
2679  *      intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2680  *      prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2681  *
2682  *      getblk flags:
2683  *
2684  *      GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2685  *      GETBLK_BHEAVY - heavy-weight buffer cache buffer
2686  *
2687  * MPALMOSTSAFE
2688  */
2689 struct buf *
2690 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2691 {
2692         struct buf *bp;
2693         int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2694         int error;
2695         int lkflags;
2696
2697         if (size > MAXBSIZE)
2698                 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2699         if (vp->v_object == NULL)
2700                 panic("getblk: vnode %p has no object!", vp);
2701
2702 loop:
2703         if ((bp = findblk(vp, loffset, FINDBLK_TEST)) != NULL) {
2704                 /*
2705                  * The buffer was found in the cache, but we need to lock it.
2706                  * Even with LK_NOWAIT the lockmgr may break our critical
2707                  * section, so double-check the validity of the buffer
2708                  * once the lock has been obtained.
2709                  */
2710                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2711                         if (blkflags & GETBLK_NOWAIT)
2712                                 return(NULL);
2713                         lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2714                         if (blkflags & GETBLK_PCATCH)
2715                                 lkflags |= LK_PCATCH;
2716                         error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2717                         if (error) {
2718                                 if (error == ENOLCK)
2719                                         goto loop;
2720                                 return (NULL);
2721                         }
2722                         /* buffer may have changed on us */
2723                 }
2724
2725                 /*
2726                  * Once the buffer has been locked, make sure we didn't race
2727                  * a buffer recyclement.  Buffers that are no longer hashed
2728                  * will have b_vp == NULL, so this takes care of that check
2729                  * as well.
2730                  */
2731                 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2732                         kprintf("Warning buffer %p (vp %p loffset %lld) "
2733                                 "was recycled\n",
2734                                 bp, vp, (long long)loffset);
2735                         BUF_UNLOCK(bp);
2736                         goto loop;
2737                 }
2738
2739                 /*
2740                  * If SZMATCH any pre-existing buffer must be of the requested
2741                  * size or NULL is returned.  The caller absolutely does not
2742                  * want getblk() to bwrite() the buffer on a size mismatch.
2743                  */
2744                 if ((blkflags & GETBLK_SZMATCH) && size != bp->b_bcount) {
2745                         BUF_UNLOCK(bp);
2746                         return(NULL);
2747                 }
2748
2749                 /*
2750                  * All vnode-based buffers must be backed by a VM object.
2751                  */
2752                 KKASSERT(bp->b_flags & B_VMIO);
2753                 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2754                 bp->b_flags &= ~B_AGE;
2755
2756                 /*
2757                  * Make sure that B_INVAL buffers do not have a cached
2758                  * block number translation.
2759                  */
2760                 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2761                         kprintf("Warning invalid buffer %p (vp %p loffset %lld)"
2762                                 " did not have cleared bio_offset cache\n",
2763                                 bp, vp, (long long)loffset);
2764                         clearbiocache(&bp->b_bio2);
2765                 }
2766
2767                 /*
2768                  * The buffer is locked.  B_CACHE is cleared if the buffer is 
2769                  * invalid.
2770                  */
2771                 if (bp->b_flags & B_INVAL)
2772                         bp->b_flags &= ~B_CACHE;
2773                 bremfree(bp);
2774
2775                 /*
2776                  * Any size inconsistancy with a dirty buffer or a buffer
2777                  * with a softupdates dependancy must be resolved.  Resizing
2778                  * the buffer in such circumstances can lead to problems.
2779                  *
2780                  * Dirty or dependant buffers are written synchronously.
2781                  * Other types of buffers are simply released and
2782                  * reconstituted as they may be backed by valid, dirty VM
2783                  * pages (but not marked B_DELWRI).
2784                  *
2785                  * NFS NOTE: NFS buffers which straddle EOF are oddly-sized
2786                  * and may be left over from a prior truncation (and thus
2787                  * no longer represent the actual EOF point), so we
2788                  * definitely do not want to B_NOCACHE the backing store.
2789                  */
2790                 if (size != bp->b_bcount) {
2791                         get_mplock();
2792                         if (bp->b_flags & B_DELWRI) {
2793                                 bp->b_flags |= B_RELBUF;
2794                                 bwrite(bp);
2795                         } else if (LIST_FIRST(&bp->b_dep)) {
2796                                 bp->b_flags |= B_RELBUF;
2797                                 bwrite(bp);
2798                         } else {
2799                                 bp->b_flags |= B_RELBUF;
2800                                 brelse(bp);
2801                         }
2802                         rel_mplock();
2803                         goto loop;
2804                 }
2805                 KKASSERT(size <= bp->b_kvasize);
2806                 KASSERT(bp->b_loffset != NOOFFSET, 
2807                         ("getblk: no buffer offset"));
2808
2809                 /*
2810                  * A buffer with B_DELWRI set and B_CACHE clear must
2811                  * be committed before we can return the buffer in
2812                  * order to prevent the caller from issuing a read
2813                  * ( due to B_CACHE not being set ) and overwriting
2814                  * it.
2815                  *
2816                  * Most callers, including NFS and FFS, need this to
2817                  * operate properly either because they assume they
2818                  * can issue a read if B_CACHE is not set, or because
2819                  * ( for example ) an uncached B_DELWRI might loop due 
2820                  * to softupdates re-dirtying the buffer.  In the latter
2821                  * case, B_CACHE is set after the first write completes,
2822                  * preventing further loops.
2823                  *
2824                  * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2825                  * above while extending the buffer, we cannot allow the
2826                  * buffer to remain with B_CACHE set after the write
2827                  * completes or it will represent a corrupt state.  To
2828                  * deal with this we set B_NOCACHE to scrap the buffer
2829                  * after the write.
2830                  *
2831                  * XXX Should this be B_RELBUF instead of B_NOCACHE?
2832                  *     I'm not even sure this state is still possible
2833                  *     now that getblk() writes out any dirty buffers
2834                  *     on size changes.
2835                  *
2836                  * We might be able to do something fancy, like setting
2837                  * B_CACHE in bwrite() except if B_DELWRI is already set,
2838                  * so the below call doesn't set B_CACHE, but that gets real
2839                  * confusing.  This is much easier.
2840                  */
2841
2842                 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2843                         get_mplock();
2844                         kprintf("getblk: Warning, bp %p loff=%jx DELWRI set "
2845                                 "and CACHE clear, b_flags %08x\n",
2846                                 bp, (intmax_t)bp->b_loffset, bp->b_flags);
2847                         bp->b_flags |= B_NOCACHE;
2848                         bwrite(bp);
2849                         rel_mplock();
2850                         goto loop;
2851                 }
2852         } else {
2853                 /*
2854                  * Buffer is not in-core, create new buffer.  The buffer
2855                  * returned by getnewbuf() is locked.  Note that the returned
2856                  * buffer is also considered valid (not marked B_INVAL).
2857                  *
2858                  * Calculating the offset for the I/O requires figuring out
2859                  * the block size.  We use DEV_BSIZE for VBLK or VCHR and
2860                  * the mount's f_iosize otherwise.  If the vnode does not
2861                  * have an associated mount we assume that the passed size is 
2862                  * the block size.  
2863                  *
2864                  * Note that vn_isdisk() cannot be used here since it may
2865                  * return a failure for numerous reasons.   Note that the
2866                  * buffer size may be larger then the block size (the caller
2867                  * will use block numbers with the proper multiple).  Beware
2868                  * of using any v_* fields which are part of unions.  In
2869                  * particular, in DragonFly the mount point overloading 
2870                  * mechanism uses the namecache only and the underlying
2871                  * directory vnode is not a special case.
2872                  */
2873                 int bsize, maxsize;
2874
2875                 if (vp->v_type == VBLK || vp->v_type == VCHR)
2876                         bsize = DEV_BSIZE;
2877                 else if (vp->v_mount)
2878                         bsize = vp->v_mount->mnt_stat.f_iosize;
2879                 else
2880                         bsize = size;
2881
2882                 maxsize = size + (loffset & PAGE_MASK);
2883                 maxsize = imax(maxsize, bsize);
2884
2885                 bp = getnewbuf(blkflags, slptimeo, size, maxsize);
2886                 if (bp == NULL) {
2887                         if (slpflags || slptimeo)
2888                                 return NULL;
2889                         goto loop;
2890                 }
2891
2892                 /*
2893                  * Atomically insert the buffer into the hash, so that it can
2894                  * be found by findblk().
2895                  *
2896                  * If bgetvp() returns non-zero a collision occured, and the
2897                  * bp will not be associated with the vnode.
2898                  *
2899                  * Make sure the translation layer has been cleared.
2900                  */
2901                 bp->b_loffset = loffset;
2902                 bp->b_bio2.bio_offset = NOOFFSET;
2903                 /* bp->b_bio2.bio_next = NULL; */
2904
2905                 if (bgetvp(vp, bp)) {
2906                         bp->b_flags |= B_INVAL;
2907                         brelse(bp);
2908                         goto loop;
2909                 }
2910
2911                 /*
2912                  * All vnode-based buffers must be backed by a VM object.
2913                  */
2914                 KKASSERT(vp->v_object != NULL);
2915                 bp->b_flags |= B_VMIO;
2916                 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2917
2918                 get_mplock();
2919                 allocbuf(bp, size);
2920                 rel_mplock();
2921         }
2922         return (bp);
2923 }
2924
2925 /*
2926  * regetblk(bp)
2927  *
2928  * Reacquire a buffer that was previously released to the locked queue,
2929  * or reacquire a buffer which is interlocked by having bioops->io_deallocate
2930  * set B_LOCKED (which handles the acquisition race).
2931  *
2932  * To this end, either B_LOCKED must be set or the dependancy list must be
2933  * non-empty.
2934  *
2935  * MPSAFE
2936  */
2937 void
2938 regetblk(struct buf *bp)
2939 {
2940         KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
2941         BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
2942         bremfree(bp);
2943 }
2944
2945 /*
2946  * geteblk:
2947  *
2948  *      Get an empty, disassociated buffer of given size.  The buffer is
2949  *      initially set to B_INVAL.
2950  *
2951  *      critical section protection is not required for the allocbuf()
2952  *      call because races are impossible here.
2953  *
2954  * MPALMOSTSAFE
2955  */
2956 struct buf *
2957 geteblk(int size)
2958 {
2959         struct buf *bp;
2960         int maxsize;
2961
2962         maxsize = (size + BKVAMASK) & ~BKVAMASK;
2963
2964         while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2965                 ;
2966         get_mplock();
2967         allocbuf(bp, size);
2968         rel_mplock();
2969         bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2970         return (bp);
2971 }
2972
2973
2974 /*
2975  * allocbuf:
2976  *
2977  *      This code constitutes the buffer memory from either anonymous system
2978  *      memory (in the case of non-VMIO operations) or from an associated
2979  *      VM object (in the case of VMIO operations).  This code is able to
2980  *      resize a buffer up or down.
2981  *
2982  *      Note that this code is tricky, and has many complications to resolve
2983  *      deadlock or inconsistant data situations.  Tread lightly!!! 
2984  *      There are B_CACHE and B_DELWRI interactions that must be dealt with by 
2985  *      the caller.  Calling this code willy nilly can result in the loss of data.
2986  *
2987  *      allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2988  *      B_CACHE for the non-VMIO case.
2989  *
2990  *      This routine does not need to be called from a critical section but you
2991  *      must own the buffer.
2992  *
2993  * NOTMPSAFE
2994  */
2995 int
2996 allocbuf(struct buf *bp, int size)
2997 {
2998         int newbsize, mbsize;
2999         int i;
3000
3001         if (BUF_REFCNT(bp) == 0)
3002                 panic("allocbuf: buffer not busy");
3003
3004         if (bp->b_kvasize < size)
3005                 panic("allocbuf: buffer too small");
3006
3007         if ((bp->b_flags & B_VMIO) == 0) {
3008                 caddr_t origbuf;
3009                 int origbufsize;
3010                 /*
3011                  * Just get anonymous memory from the kernel.  Don't
3012                  * mess with B_CACHE.
3013                  */
3014                 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3015                 if (bp->b_flags & B_MALLOC)
3016                         newbsize = mbsize;
3017                 else
3018                         newbsize = round_page(size);
3019
3020                 if (newbsize < bp->b_bufsize) {
3021                         /*
3022                          * Malloced buffers are not shrunk
3023                          */
3024                         if (bp->b_flags & B_MALLOC) {
3025                                 if (newbsize) {
3026                                         bp->b_bcount = size;
3027                                 } else {
3028                                         kfree(bp->b_data, M_BIOBUF);
3029                                         if (bp->b_bufsize) {
3030                                                 bufmallocspace -= bp->b_bufsize;
3031                                                 bufspacewakeup();
3032                                                 bp->b_bufsize = 0;
3033                                         }
3034                                         bp->b_data = bp->b_kvabase;
3035                                         bp->b_bcount = 0;
3036                                         bp->b_flags &= ~B_MALLOC;
3037                                 }
3038                                 return 1;
3039                         }               
3040                         vm_hold_free_pages(
3041                             bp,
3042                             (vm_offset_t) bp->b_data + newbsize,
3043                             (vm_offset_t) bp->b_data + bp->b_bufsize);
3044                 } else if (newbsize > bp->b_bufsize) {
3045                         /*
3046                          * We only use malloced memory on the first allocation.
3047                          * and revert to page-allocated memory when the buffer
3048                          * grows.
3049                          */
3050                         if ((bufmallocspace < maxbufmallocspace) &&
3051                                 (bp->b_bufsize == 0) &&
3052                                 (mbsize <= PAGE_SIZE/2)) {
3053
3054                                 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
3055                                 bp->b_bufsize = mbsize;
3056                                 bp->b_bcount = size;
3057                                 bp->b_flags |= B_MALLOC;
3058                                 bufmallocspace += mbsize;
3059                                 return 1;
3060                         }
3061                         origbuf = NULL;
3062                         origbufsize = 0;
3063                         /*
3064                          * If the buffer is growing on its other-than-first
3065                          * allocation, then we revert to the page-allocation
3066                          * scheme.
3067                          */
3068                         if (bp->b_flags & B_MALLOC) {
3069                                 origbuf = bp->b_data;
3070                                 origbufsize = bp->b_bufsize;
3071                                 bp->b_data = bp->b_kvabase;
3072                                 if (bp->b_bufsize) {
3073                                         bufmallocspace -= bp->b_bufsize;
3074                                         bufspacewakeup();
3075                                         bp->b_bufsize = 0;
3076                                 }
3077                                 bp->b_flags &= ~B_MALLOC;
3078                                 newbsize = round_page(newbsize);
3079                         }
3080                         vm_hold_load_pages(
3081                             bp,
3082                             (vm_offset_t) bp->b_data + bp->b_bufsize,
3083                             (vm_offset_t) bp->b_data + newbsize);
3084                         if (origbuf) {
3085                                 bcopy(origbuf, bp->b_data, origbufsize);
3086                                 kfree(origbuf, M_BIOBUF);
3087                         }
3088                 }
3089         } else {
3090                 vm_page_t m;
3091                 int desiredpages;
3092
3093                 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3094                 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
3095                                 newbsize + PAGE_MASK) >> PAGE_SHIFT;
3096                 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
3097
3098                 if (bp->b_flags & B_MALLOC)
3099                         panic("allocbuf: VMIO buffer can't be malloced");
3100                 /*
3101                  * Set B_CACHE initially if buffer is 0 length or will become
3102                  * 0-length.
3103                  */
3104                 if (size == 0 || bp->b_bufsize == 0)
3105                         bp->b_flags |= B_CACHE;
3106
3107                 if (newbsize < bp->b_bufsize) {
3108                         /*
3109                          * DEV_BSIZE aligned new buffer size is less then the
3110                          * DEV_BSIZE aligned existing buffer size.  Figure out
3111                          * if we have to remove any pages.
3112                          */
3113                         if (desiredpages < bp->b_xio.xio_npages) {
3114                                 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
3115                                         /*
3116                                          * the page is not freed here -- it
3117                                          * is the responsibility of 
3118                                          * vnode_pager_setsize
3119                                          */
3120                                         m = bp->b_xio.xio_pages[i];
3121                                         KASSERT(m != bogus_page,
3122                                             ("allocbuf: bogus page found"));
3123                                         while (vm_page_sleep_busy(m, TRUE, "biodep"))
3124                                                 ;
3125
3126                                         bp->b_xio.xio_pages[i] = NULL;
3127                                         vm_page_unwire(m, 0);
3128                                 }
3129                                 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
3130                                     (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
3131                                 bp->b_xio.xio_npages = desiredpages;
3132                         }
3133                 } else if (size > bp->b_bcount) {
3134                         /*
3135                          * We are growing the buffer, possibly in a 
3136                          * byte-granular fashion.
3137                          */
3138                         struct vnode *vp;
3139                         vm_object_t obj;
3140                         vm_offset_t toff;
3141                         vm_offset_t tinc;
3142
3143                         /*
3144                          * Step 1, bring in the VM pages from the object, 
3145                          * allocating them if necessary.  We must clear
3146                          * B_CACHE if these pages are not valid for the 
3147                          * range covered by the buffer.
3148                          *
3149                          * critical section protection is required to protect
3150                          * against interrupts unbusying and freeing pages
3151                          * between our vm_page_lookup() and our
3152                          * busycheck/wiring call.
3153                          */
3154                         vp = bp->b_vp;
3155                         obj = vp->v_object;
3156
3157                         crit_enter();
3158                         while (bp->b_xio.xio_npages < desiredpages) {
3159                                 vm_page_t m;
3160                                 vm_pindex_t pi;
3161
3162                                 pi = OFF_TO_IDX(bp->b_loffset) + bp->b_xio.xio_npages;
3163                                 if ((m = vm_page_lookup(obj, pi)) == NULL) {
3164                                         /*
3165                                          * note: must allocate system pages
3166                                          * since blocking here could intefere
3167                                          * with paging I/O, no matter which
3168                                          * process we are.
3169                                          */
3170                                         m = bio_page_alloc(obj, pi, desiredpages - bp->b_xio.xio_npages);
3171                                         if (m) {
3172                                                 vm_page_wire(m);
3173                                                 vm_page_wakeup(m);
3174                                                 vm_page_flag_clear(m, PG_ZERO);
3175                                                 bp->b_flags &= ~B_CACHE;
3176                                                 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3177                                                 ++bp->b_xio.xio_npages;
3178                                         }
3179                                         continue;
3180                                 }
3181
3182                                 /*
3183                                  * We found a page.  If we have to sleep on it,
3184                                  * retry because it might have gotten freed out
3185                                  * from under us.
3186                                  *
3187                                  * We can only test PG_BUSY here.  Blocking on
3188                                  * m->busy might lead to a deadlock:
3189                                  *
3190                                  *  vm_fault->getpages->cluster_read->allocbuf
3191                                  *
3192                                  */
3193
3194                                 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
3195                                         continue;
3196                                 vm_page_flag_clear(m, PG_ZERO);
3197                                 vm_page_wire(m);
3198                                 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3199                                 ++bp->b_xio.xio_npages;
3200                                 if (bp->b_act_count < m->act_count)
3201                                         bp->b_act_count = m->act_count;
3202                         }
3203                         crit_exit();
3204
3205                         /*
3206                          * Step 2.  We've loaded the pages into the buffer,
3207                          * we have to figure out if we can still have B_CACHE
3208                          * set.  Note that B_CACHE is set according to the
3209                          * byte-granular range ( bcount and size ), not the
3210                          * aligned range ( newbsize ).
3211                          *
3212                          * The VM test is against m->valid, which is DEV_BSIZE
3213                          * aligned.  Needless to say, the validity of the data
3214                          * needs to also be DEV_BSIZE aligned.  Note that this
3215                          * fails with NFS if the server or some other client
3216                          * extends the file's EOF.  If our buffer is resized, 
3217                          * B_CACHE may remain set! XXX
3218                          */
3219
3220                         toff = bp->b_bcount;
3221                         tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
3222
3223                         while ((bp->b_flags & B_CACHE) && toff < size) {
3224                                 vm_pindex_t pi;
3225
3226                                 if (tinc > (size - toff))
3227                                         tinc = size - toff;
3228
3229                                 pi = ((bp->b_loffset & PAGE_MASK) + toff) >> 
3230                                     PAGE_SHIFT;
3231
3232                                 vfs_buf_test_cache(
3233                                     bp, 
3234                                     bp->b_loffset,
3235                                     toff, 
3236                                     tinc, 
3237                                     bp->b_xio.xio_pages[pi]
3238                                 );
3239                                 toff += tinc;
3240                                 tinc = PAGE_SIZE;
3241                         }
3242
3243                         /*
3244                          * Step 3, fixup the KVM pmap.  Remember that
3245                          * bp->b_data is relative to bp->b_loffset, but 
3246                          * bp->b_loffset may be offset into the first page.
3247                          */
3248
3249                         bp->b_data = (caddr_t)
3250                             trunc_page((vm_offset_t)bp->b_data);
3251                         pmap_qenter(
3252                             (vm_offset_t)bp->b_data,
3253                             bp->b_xio.xio_pages, 
3254                             bp->b_xio.xio_npages
3255                         );
3256                         bp->b_data = (caddr_t)((vm_offset_t)bp->b_data | 
3257                             (vm_offset_t)(bp->b_loffset & PAGE_MASK));
3258                 }
3259         }
3260
3261         /* adjust space use on already-dirty buffer */
3262         if (bp->b_flags & B_DELWRI) {
3263                 dirtybufspace += newbsize - bp->b_bufsize;
3264                 if (bp->b_flags & B_HEAVY)
3265                         dirtybufspacehw += newbsize - bp->b_bufsize;
3266         }
3267         if (newbsize < bp->b_bufsize)
3268                 bufspacewakeup();
3269         bp->b_bufsize = newbsize;       /* actual buffer allocation     */
3270         bp->b_bcount = size;            /* requested buffer size        */
3271         return 1;
3272 }
3273
3274 /*
3275  * biowait:
3276  *
3277  *      Wait for buffer I/O completion, returning error status. B_EINTR
3278  *      is converted into an EINTR error but not cleared (since a chain
3279  *      of biowait() calls may occur).
3280  *
3281  *      On return bpdone() will have been called but the buffer will remain
3282  *      locked and will not have been brelse()'d.
3283  *
3284  *      NOTE!  If a timeout is specified and ETIMEDOUT occurs the I/O is
3285  *      likely still in progress on return.
3286  *
3287  *      NOTE!  This operation is on a BIO, not a BUF.
3288  *
3289  *      NOTE!  BIO_DONE is cleared by vn_strategy()
3290  *
3291  * MPSAFE
3292  */
3293 static __inline int
3294 _biowait(struct bio *bio, const char *wmesg, int to)
3295 {
3296         struct buf *bp = bio->bio_buf;
3297         u_int32_t flags;
3298         u_int32_t nflags;
3299         int error;
3300
3301         KKASSERT(bio == &bp->b_bio1);
3302         for (;;) {
3303                 flags = bio->bio_flags;
3304                 if (flags & BIO_DONE)
3305                         break;
3306                 tsleep_interlock(bio, 0);
3307                 nflags = flags | BIO_WANT;
3308                 tsleep_interlock(bio, 0);
3309                 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3310                         if (wmesg)
3311                                 error = tsleep(bio, PINTERLOCKED, wmesg, to);
3312                         else if (bp->b_cmd == BUF_CMD_READ)
3313                                 error = tsleep(bio, PINTERLOCKED, "biord", to);
3314                         else
3315                                 error = tsleep(bio, PINTERLOCKED, "biowr", to);
3316                         if (error) {
3317                                 kprintf("tsleep error biowait %d\n", error);
3318                                 return (error);
3319                         }
3320                         break;
3321                 }
3322         }
3323
3324         /*
3325          * Finish up.
3326          */
3327         KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3328         bio->bio_flags &= ~(BIO_DONE | BIO_SYNC);
3329         if (bp->b_flags & B_EINTR)
3330                 return (EINTR);
3331         if (bp->b_flags & B_ERROR)
3332                 return (bp->b_error ? bp->b_error : EIO);
3333         return (0);
3334 }
3335
3336 int
3337 biowait(struct bio *bio, const char *wmesg)
3338 {
3339         return(_biowait(bio, wmesg, 0));
3340 }
3341
3342 int
3343 biowait_timeout(struct bio *bio, const char *wmesg, int to)
3344 {
3345         return(_biowait(bio, wmesg, to));
3346 }
3347
3348 /*
3349  * This associates a tracking count with an I/O.  vn_strategy() and
3350  * dev_dstrategy() do this automatically but there are a few cases
3351  * where a vnode or device layer is bypassed when a block translation
3352  * is cached.  In such cases bio_start_transaction() may be called on
3353  * the bypassed layers so the system gets an I/O in progress indication 
3354  * for those higher layers.
3355  */
3356 void
3357 bio_start_transaction(struct bio *bio, struct bio_track *track)
3358 {
3359         bio->bio_track = track;
3360         bio_track_ref(track);
3361 }
3362
3363 /*
3364  * Initiate I/O on a vnode.
3365  *
3366  * SWAPCACHE OPERATION:
3367  *
3368  *      Real buffer cache buffers have a non-NULL bp->b_vp.  Unfortunately
3369  *      devfs also uses b_vp for fake buffers so we also have to check
3370  *      that B_PAGING is 0.  In this case the passed 'vp' is probably the
3371  *      underlying block device.  The swap assignments are related to the
3372  *      buffer cache buffer's b_vp, not the passed vp.
3373  *
3374  *      The passed vp == bp->b_vp only in the case where the strategy call
3375  *      is made on the vp itself for its own buffers (a regular file or
3376  *      block device vp).  The filesystem usually then re-calls vn_strategy()
3377  *      after translating the request to an underlying device.
3378  *
3379  *      Cluster buffers set B_CLUSTER and the passed vp is the vp of the
3380  *      underlying buffer cache buffers.
3381  *
3382  *      We can only deal with page-aligned buffers at the moment, because
3383  *      we can't tell what the real dirty state for pages straddling a buffer
3384  *      are.
3385  *
3386  *      In order to call swap_pager_strategy() we must provide the VM object
3387  *      and base offset for the underlying buffer cache pages so it can find
3388  *      the swap blocks.
3389  */
3390 void
3391 vn_strategy(struct vnode *vp, struct bio *bio)
3392 {
3393         struct bio_track *track;
3394         struct buf *bp = bio->bio_buf;
3395
3396         KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3397
3398         /*
3399          * Handle the swap cache intercept.
3400          */
3401         if (vn_cache_strategy(vp, bio))
3402                 return;
3403
3404         /*
3405          * Otherwise do the operation through the filesystem
3406          */
3407         if (bp->b_cmd == BUF_CMD_READ)
3408                 track = &vp->v_track_read;
3409         else
3410                 track = &vp->v_track_write;
3411         KKASSERT((bio->bio_flags & BIO_DONE) == 0);
3412         bio->bio_track = track;
3413         bio_track_ref(track);
3414         vop_strategy(*vp->v_ops, vp, bio);
3415 }
3416
3417 int
3418 vn_cache_strategy(struct vnode *vp, struct bio *bio)
3419 {
3420         struct buf *bp = bio->bio_buf;
3421         struct bio *nbio;
3422         vm_object_t object;
3423         vm_page_t m;
3424         int i;
3425
3426         /*
3427          * Is this buffer cache buffer suitable for reading from
3428          * the swap cache?
3429          */
3430         if (vm_swapcache_read_enable == 0 ||
3431             bp->b_cmd != BUF_CMD_READ ||
3432             ((bp->b_flags & B_CLUSTER) == 0 &&
3433              (bp->b_vp == NULL || (bp->b_flags & B_PAGING))) ||
3434             ((int)bp->b_loffset & PAGE_MASK) != 0 ||
3435             (bp->b_bcount & PAGE_MASK) != 0) {
3436                 return(0);
3437         }
3438
3439         /*
3440          * Figure out the original VM object (it will match the underlying
3441          * VM pages).  Note that swap cached data uses page indices relative
3442          * to that object, not relative to bio->bio_offset.
3443          */
3444         if (bp->b_flags & B_CLUSTER)
3445                 object = vp->v_object;
3446         else
3447                 object = bp->b_vp->v_object;
3448
3449         /*
3450          * In order to be able to use the swap cache all underlying VM
3451          * pages must be marked as such, and we can't have any bogus pages.
3452          */
3453         for (i = 0; i < bp->b_xio.xio_npages; ++i) {
3454                 m = bp->b_xio.xio_pages[i];
3455                 if ((m->flags & PG_SWAPPED) == 0)
3456                         break;
3457                 if (m == bogus_page)
3458                         break;
3459         }
3460
3461         /*
3462          * If we are good then issue the I/O using swap_pager_strategy()
3463          */
3464         if (i == bp->b_xio.xio_npages) {
3465                 m = bp->b_xio.xio_pages[0];
3466                 nbio = push_bio(bio);
3467                 nbio->bio_offset = ptoa(m->pindex);
3468                 KKASSERT(m->object == object);
3469                 swap_pager_strategy(object, nbio);
3470                 return(1);
3471         }
3472         return(0);
3473 }
3474
3475 /*
3476  * bpdone:
3477  *
3478  *      Finish I/O on a buffer after all BIOs have been processed.
3479  *      Called when the bio chain is exhausted or by biowait.  If called
3480  *      by biowait, elseit is typically 0.
3481  *
3482  *      bpdone is also responsible for setting B_CACHE in a B_VMIO bp.
3483  *      In a non-VMIO bp, B_CACHE will be set on the next getblk() 
3484  *      assuming B_INVAL is clear.
3485  *
3486  *      For the VMIO case, we set B_CACHE if the op was a read and no
3487  *      read error occured, or if the op was a write.  B_CACHE is never
3488  *      set if the buffer is invalid or otherwise uncacheable.
3489  *
3490  *      bpdone does not mess with B_INVAL, allowing the I/O routine or the
3491  *      initiator to leave B_INVAL set to brelse the buffer out of existance
3492  *      in the biodone routine.
3493  */
3494 void
3495 bpdone(struct buf *bp, int elseit)
3496 {
3497         buf_cmd_t cmd;
3498
3499         KASSERT(BUF_REFCNTNB(bp) > 0, 
3500                 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3501         KASSERT(bp->b_cmd != BUF_CMD_DONE, 
3502                 ("biodone: bp %p already done!", bp));
3503
3504         /*
3505          * No more BIOs are left.  All completion functions have been dealt
3506          * with, now we clean up the buffer.
3507          */
3508         cmd = bp->b_cmd;
3509         bp->b_cmd = BUF_CMD_DONE;
3510
3511         /*
3512          * Only reads and writes are processed past this point.
3513          */
3514         if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3515                 if (cmd == BUF_CMD_FREEBLKS)
3516                         bp->b_flags |= B_NOCACHE;
3517                 if (elseit)
3518                         brelse(bp);
3519                 return;
3520         }
3521
3522         /*
3523          * Warning: softupdates may re-dirty the buffer, and HAMMER can do
3524          * a lot worse.  XXX - move this above the clearing of b_cmd
3525          */
3526         if (LIST_FIRST(&bp->b_dep) != NULL)
3527                 buf_complete(bp);
3528
3529         /*
3530          * A failed write must re-dirty the buffer unless B_INVAL
3531          * was set.  Only applicable to normal buffers (with VPs).
3532          * vinum buffers may not have a vp.
3533          */
3534         if (cmd == BUF_CMD_WRITE &&
3535             (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
3536                 bp->b_flags &= ~B_NOCACHE;
3537                 if (bp->b_vp)
3538                         bdirty(bp);
3539         }
3540
3541         if (bp->b_flags & B_VMIO) {
3542                 int i;
3543                 vm_ooffset_t foff;
3544                 vm_page_t m;
3545                 vm_object_t obj;
3546                 int iosize;
3547                 struct vnode *vp = bp->b_vp;
3548
3549                 obj = vp->v_object;
3550
3551 #if defined(VFS_BIO_DEBUG)
3552                 if (vp->v_auxrefs == 0)
3553                         panic("biodone: zero vnode hold count");
3554                 if ((vp->v_flag & VOBJBUF) == 0)
3555                         panic("biodone: vnode is not setup for merged cache");
3556 #endif
3557
3558                 foff = bp->b_loffset;
3559                 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3560                 KASSERT(obj != NULL, ("biodone: missing VM object"));
3561
3562 #if defined(VFS_BIO_DEBUG)
3563                 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3564                         kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
3565                             obj->paging_in_progress, bp->b_xio.xio_npages);
3566                 }
3567 #endif
3568
3569                 /*
3570                  * Set B_CACHE if the op was a normal read and no error
3571                  * occured.  B_CACHE is set for writes in the b*write()
3572                  * routines.
3573                  */
3574                 iosize = bp->b_bcount - bp->b_resid;
3575                 if (cmd == BUF_CMD_READ &&
3576                     (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3577                         bp->b_flags |= B_CACHE;
3578                 }
3579
3580                 crit_enter();
3581                 get_mplock();
3582                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3583                         int bogusflag = 0;
3584                         int resid;
3585
3586                         resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3587                         if (resid > iosize)
3588                                 resid = iosize;
3589
3590                         /*
3591                          * cleanup bogus pages, restoring the originals.  Since
3592                          * the originals should still be wired, we don't have
3593                          * to worry about interrupt/freeing races destroying
3594                          * the VM object association.
3595                          */
3596                         m = bp->b_xio.xio_pages[i];
3597                         if (m == bogus_page) {
3598                                 bogusflag = 1;
3599                                 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3600                                 if (m == NULL)
3601                                         panic("biodone: page disappeared");
3602                                 bp->b_xio.xio_pages[i] = m;
3603                                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3604                                         bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3605                         }
3606 #if defined(VFS_BIO_DEBUG)
3607                         if (OFF_TO_IDX(foff) != m->pindex) {
3608                                 kprintf("biodone: foff(%lu)/m->pindex(%ld) "
3609                                         "mismatch\n",
3610                                         (unsigned long)foff, (long)m->pindex);
3611                         }
3612 #endif
3613
3614                         /*
3615                          * In the write case, the valid and clean bits are
3616                          * already changed correctly (see bdwrite()), so we
3617                          * only need to do this here in the read case.
3618                          */
3619                         if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3620                                 vfs_clean_one_page(bp, i, m);
3621                         }
3622                         vm_page_flag_clear(m, PG_ZERO);
3623
3624                         /*
3625                          * when debugging new filesystems or buffer I/O
3626                          * methods, this is the most common error that pops
3627                          * up.  if you see this, you have not set the page
3628                          * busy flag correctly!!!
3629                          */
3630                         if (m->busy == 0) {
3631                                 kprintf("biodone: page busy < 0, "
3632                                     "pindex: %d, foff: 0x(%x,%x), "
3633                                     "resid: %d, index: %d\n",
3634                                     (int) m->pindex, (int)(foff >> 32),
3635                                                 (int) foff & 0xffffffff, resid, i);
3636                                 if (!vn_isdisk(vp, NULL))
3637                                         kprintf(" iosize: %ld, loffset: %lld, "
3638                                                 "flags: 0x%08x, npages: %d\n",
3639                                             bp->b_vp->v_mount->mnt_stat.f_iosize,
3640                                             (long long)bp->b_loffset,
3641                                             bp->b_flags, bp->b_xio.xio_npages);
3642                                 else
3643                                         kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3644                                             (long long)bp->b_loffset,
3645                                             bp->b_flags, bp->b_xio.xio_npages);
3646                                 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3647                                     m->valid, m->dirty, m->wire_count);
3648                                 panic("biodone: page busy < 0");
3649                         }
3650                         vm_page_io_finish(m);
3651                         vm_object_pip_subtract(obj, 1);
3652                         foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3653                         iosize -= resid;
3654                 }
3655                 if (obj)
3656                         vm_object_pip_wakeupn(obj, 0);
3657                 rel_mplock();
3658                 crit_exit();
3659         }
3660
3661         /*
3662          * Finish up by releasing the buffer.  There are no more synchronous
3663          * or asynchronous completions, those were handled by bio_done
3664          * callbacks.
3665          */
3666         if (elseit) {
3667                 if (bp->b_flags & (B_NOCACHE|B_INVAL|B_ERROR|B_RELBUF))
3668                         brelse(bp);
3669                 else
3670                         bqrelse(bp);
3671         }
3672 }
3673
3674 /*
3675  * Normal biodone.
3676  */
3677 void
3678 biodone(struct bio *bio)
3679 {
3680         struct buf *bp = bio->bio_buf;
3681
3682         runningbufwakeup(bp);
3683
3684         /*
3685          * Run up the chain of BIO's.   Leave b_cmd intact for the duration.
3686          */
3687         while (bio) {
3688                 biodone_t *done_func;
3689                 struct bio_track *track;
3690
3691                 /*
3692                  * BIO tracking.  Most but not all BIOs are tracked.
3693                  */
3694                 if ((track = bio->bio_track) != NULL) {
3695                         bio_track_rel(track);
3696                         bio->bio_track = NULL;
3697                 }
3698
3699                 /*
3700                  * A bio_done function terminates the loop.  The function
3701                  * will be responsible for any further chaining and/or
3702                  * buffer management.
3703                  *
3704                  * WARNING!  The done function can deallocate the buffer!
3705                  */
3706                 if ((done_func = bio->bio_done) != NULL) {
3707                         bio->bio_done = NULL;
3708                         done_func(bio);
3709                         return;
3710                 }
3711                 bio = bio->bio_prev;
3712         }
3713
3714         /*
3715          * If we've run out of bio's do normal [a]synchronous completion.
3716          */
3717         bpdone(bp, 1);
3718 }
3719
3720 /*
3721  * Synchronous biodone - this terminates a synchronous BIO.
3722  *
3723  * bpdone() is called with elseit=FALSE, leaving the buffer completed
3724  * but still locked.  The caller must brelse() the buffer after waiting
3725  * for completion.
3726  */
3727 void
3728 biodone_sync(struct bio *bio)
3729 {
3730         struct buf *bp = bio->bio_buf;
3731         int flags;
3732         int nflags;
3733
3734         KKASSERT(bio == &bp->b_bio1);
3735         bpdone(bp, 0);
3736
3737         for (;;) {
3738                 flags = bio->bio_flags;
3739                 nflags = (flags | BIO_DONE) & ~BIO_WANT;
3740
3741                 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3742                         if (flags & BIO_WANT)
3743                                 wakeup(bio);
3744                         break;
3745                 }
3746         }
3747 }
3748
3749 /*
3750  * vfs_unbusy_pages:
3751  *
3752  *      This routine is called in lieu of iodone in the case of
3753  *      incomplete I/O.  This keeps the busy status for pages
3754  *      consistant.
3755  */
3756 void
3757 vfs_unbusy_pages(struct buf *bp)
3758 {
3759         int i;
3760
3761         runningbufwakeup(bp);
3762         if (bp->b_flags & B_VMIO) {
3763                 struct vnode *vp = bp->b_vp;
3764                 vm_object_t obj;
3765
3766                 obj = vp->v_object;
3767
3768                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3769                         vm_page_t m = bp->b_xio.xio_pages[i];
3770
3771                         /*
3772                          * When restoring bogus changes the original pages
3773                          * should still be wired, so we are in no danger of
3774                          * losing the object association and do not need
3775                          * critical section protection particularly.
3776                          */
3777                         if (m == bogus_page) {
3778                                 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3779                                 if (!m) {
3780                                         panic("vfs_unbusy_pages: page missing");
3781                                 }
3782                                 bp->b_xio.xio_pages[i] = m;
3783                                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3784                                         bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3785                         }
3786                         vm_object_pip_subtract(obj, 1);
3787                         vm_page_flag_clear(m, PG_ZERO);
3788                         vm_page_io_finish(m);
3789                 }
3790                 vm_object_pip_wakeupn(obj, 0);
3791         }
3792 }
3793
3794 /*
3795  * vfs_busy_pages:
3796  *
3797  *      This routine is called before a device strategy routine.
3798  *      It is used to tell the VM system that paging I/O is in
3799  *      progress, and treat the pages associated with the buffer
3800  *      almost as being PG_BUSY.  Also the object 'paging_in_progress'
3801  *      flag is handled to make sure that the object doesn't become
3802  *      inconsistant.
3803  *
3804  *      Since I/O has not been initiated yet, certain buffer flags
3805  *      such as B_ERROR or B_INVAL may be in an inconsistant state
3806  *      and should be ignored.
3807  */
3808 void
3809 vfs_busy_pages(struct vnode *vp, struct buf *bp)
3810 {
3811         int i, bogus;
3812         struct lwp *lp = curthread->td_lwp;
3813
3814         /*
3815          * The buffer's I/O command must already be set.  If reading,
3816          * B_CACHE must be 0 (double check against callers only doing
3817          * I/O when B_CACHE is 0).
3818          */
3819         KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3820         KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
3821
3822         if (bp->b_flags & B_VMIO) {
3823                 vm_object_t obj;
3824
3825                 obj = vp->v_object;
3826                 KASSERT(bp->b_loffset != NOOFFSET,
3827                         ("vfs_busy_pages: no buffer offset"));
3828
3829                 /*
3830                  * Loop until none of the pages are busy.
3831                  */
3832 retry:
3833                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3834                         vm_page_t m = bp->b_xio.xio_pages[i];
3835
3836                         if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3837                                 goto retry;
3838                 }
3839
3840                 /*
3841                  * Setup for I/O, soft-busy the page right now because
3842                  * the next loop may block.
3843                  */
3844                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3845                         vm_page_t m = bp->b_xio.xio_pages[i];
3846
3847                         vm_page_flag_clear(m, PG_ZERO);
3848                         if ((bp->b_flags & B_CLUSTER) == 0) {
3849                                 vm_object_pip_add(obj, 1);
3850                                 vm_page_io_start(m);
3851                         }
3852                 }
3853
3854                 /*
3855                  * Adjust protections for I/O and do bogus-page mapping.
3856                  * Assume that vm_page_protect() can block (it can block
3857                  * if VM_PROT_NONE, don't take any chances regardless).
3858                  *
3859                  * In particular note that for writes we must incorporate
3860                  * page dirtyness from the VM system into the buffer's
3861                  * dirty range.
3862                  *
3863                  * For reads we theoretically must incorporate page dirtyness
3864                  * from the VM system to determine if the page needs bogus
3865                  * replacement, but we shortcut the test by simply checking
3866                  * that all m->valid bits are set, indicating that the page
3867                  * is fully valid and does not need to be re-read.  For any
3868                  * VM system dirtyness the page will also be fully valid
3869                  * since it was mapped at one point.
3870                  */
3871                 bogus = 0;
3872                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3873                         vm_page_t m = bp->b_xio.xio_pages[i];
3874
3875                         vm_page_flag_clear(m, PG_ZERO); /* XXX */
3876                         if (bp->b_cmd == BUF_CMD_WRITE) {
3877                                 /*
3878                                  * When readying a vnode-backed buffer for
3879                                  * a write we must zero-fill any invalid
3880                                  * portions of the backing VM pages, mark
3881                                  * it valid and clear related dirty bits.
3882                                  *
3883                                  * vfs_clean_one_page() incorporates any
3884                                  * VM dirtyness and updates the b_dirtyoff
3885                                  * range (after we've made the page RO).
3886                                  *
3887                                  * It is also expected that the pmap modified
3888                                  * bit has already been cleared by the
3889                                  * vm_page_protect().  We may not be able
3890                                  * to clear all dirty bits for a page if it
3891                                  * was also memory mapped (NFS).
3892                                  *
3893                                  * Finally be sure to unassign any swap-cache
3894                                  * backing store as it is now stale.
3895                                  */
3896                                 vm_page_protect(m, VM_PROT_READ);
3897                                 vfs_clean_one_page(bp, i, m);
3898                                 swap_pager_unswapped(m);
3899                         } else if (m->valid == VM_PAGE_BITS_ALL) {
3900                                 /*
3901                                  * When readying a vnode-backed buffer for
3902                                  * read we must replace any dirty pages with
3903                                  * a bogus page so dirty data is not destroyed
3904                                  * when filling gaps.
3905                                  *
3906                                  * To avoid testing whether the page is
3907                                  * dirty we instead test that the page was
3908                                  * at some point mapped (m->valid fully
3909                                  * valid) with the understanding that
3910                                  * this also covers the dirty case.
3911                                  */
3912                                 bp->b_xio.xio_pages[i] = bogus_page;
3913                                 bogus++;
3914                         } else if (m->valid & m->dirty) {
3915                                 /*
3916                                  * This case should not occur as partial
3917                                  * dirtyment can only happen if the buffer
3918                                  * is B_CACHE, and this code is not entered
3919                                  * if the buffer is B_CACHE.
3920                                  */
3921                                 kprintf("Warning: vfs_busy_pages - page not "
3922                                         "fully valid! loff=%jx bpf=%08x "
3923                                         "idx=%d val=%02x dir=%02x\n",
3924                                         (intmax_t)bp->b_loffset, bp->b_flags,
3925                                         i, m->valid, m->dirty);
3926                                 vm_page_protect(m, VM_PROT_NONE);
3927                         } else {
3928                                 /*
3929                                  * The page is not valid and can be made
3930                                  * part of the read.
3931                                  */
3932                                 vm_page_protect(m, VM_PROT_NONE);
3933                         }
3934                 }
3935                 if (bogus) {
3936                         pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3937                                 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3938                 }
3939         }
3940
3941         /*
3942          * This is the easiest place to put the process accounting for the I/O
3943          * for now.
3944          */
3945         if (lp != NULL) {
3946                 if (bp->b_cmd == BUF_CMD_READ)
3947                         lp->lwp_ru.ru_inblock++;
3948                 else
3949                         lp->lwp_ru.ru_oublock++;
3950         }
3951 }
3952
3953 /*
3954  * vfs_clean_pages:
3955  *      
3956  *      Tell the VM system that the pages associated with this buffer
3957  *      are clean.  This is used for delayed writes where the data is
3958  *      going to go to disk eventually without additional VM intevention.
3959  *
3960  *      Note that while we only really need to clean through to b_bcount, we
3961  *      just go ahead and clean through to b_bufsize.
3962  */
3963 static void
3964 vfs_clean_pages(struct buf *bp)
3965 {
3966         vm_page_t m;
3967         int i;
3968
3969         if ((bp->b_flags & B_VMIO) == 0)
3970                 return;
3971
3972         KASSERT(bp->b_loffset != NOOFFSET,
3973                 ("vfs_clean_pages: no buffer offset"));
3974
3975         for (i = 0; i < bp->b_xio.xio_npages; i++) {
3976                 m = bp->b_xio.xio_pages[i];
3977                 vfs_clean_one_page(bp, i, m);
3978         }
3979 }
3980
3981 /*
3982  * vfs_clean_one_page:
3983  *
3984  *      Set the valid bits and clear the dirty bits in a page within a
3985  *      buffer.  The range is restricted to the buffer's size and the
3986  *      buffer's logical offset might index into the first page.
3987  *
3988  *      The caller has busied or soft-busied the page and it is not mapped,
3989  *      test and incorporate the dirty bits into b_dirtyoff/end before
3990  *      clearing them.  Note that we need to clear the pmap modified bits
3991  *      after determining the the page was dirty, vm_page_set_validclean()
3992  *      does not do it for us.
3993  *
3994  *      This routine is typically called after a read completes (dirty should
3995  *      be zero in that case as we are not called on bogus-replace pages),
3996  *      or before a write is initiated.
3997  */
3998 static void
3999 vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m)
4000 {
4001         int bcount;
4002         int xoff;
4003         int soff;
4004         int eoff;
4005
4006         /*
4007          * Calculate offset range within the page but relative to buffer's
4008          * loffset.  loffset might be offset into the first page.
4009          */
4010         xoff = (int)bp->b_loffset & PAGE_MASK;  /* loffset offset into pg 0 */
4011         bcount = bp->b_bcount + xoff;           /* offset adjusted */
4012
4013         if (pageno == 0) {
4014                 soff = xoff;
4015                 eoff = PAGE_SIZE;
4016         } else {
4017                 soff = (pageno << PAGE_SHIFT);
4018                 eoff = soff + PAGE_SIZE;
4019         }
4020         if (eoff > bcount)
4021                 eoff = bcount;
4022         if (soff >= eoff)
4023                 return;
4024
4025         /*
4026          * Test dirty bits and adjust b_dirtyoff/end.
4027          *
4028          * If dirty pages are incorporated into the bp any prior
4029          * B_NEEDCOMMIT state (NFS) must be cleared because the
4030          * caller has not taken into account the new dirty data.
4031          *
4032          * If the page was memory mapped the dirty bits might go beyond the
4033          * end of the buffer, but we can't really make the assumption that
4034          * a file EOF straddles the buffer (even though this is the case for
4035          * NFS if B_NEEDCOMMIT is also set).  So for the purposes of clearing
4036          * B_NEEDCOMMIT we only test the dirty bits covered by the buffer.
4037          * This also saves some console spam.
4038          *
4039          * When clearing B_NEEDCOMMIT we must also clear B_CLUSTEROK,
4040          * NFS can handle huge commits but not huge writes.
4041          */
4042         vm_page_test_dirty(m);
4043         if (m->dirty) {
4044                 if ((bp->b_flags & B_NEEDCOMMIT) &&
4045                     (m->dirty & vm_page_bits(soff & PAGE_MASK, eoff - soff))) {
4046                         if (debug_commit)
4047                         kprintf("Warning: vfs_clean_one_page: bp %p "
4048                                 "loff=%jx,%d flgs=%08x clr B_NEEDCOMMIT"
4049                                 " cmd %d vd %02x/%02x x/s/e %d %d %d "
4050                                 "doff/end %d %d\n",
4051                                 bp, (intmax_t)bp->b_loffset, bp->b_bcount,
4052                                 bp->b_flags, bp->b_cmd,
4053                                 m->valid, m->dirty, xoff, soff, eoff,
4054                                 bp->b_dirtyoff, bp->b_dirtyend);
4055                         bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
4056                         if (debug_commit)
4057                                 print_backtrace();
4058                 }
4059                 /*
4060                  * Only clear the pmap modified bits if ALL the dirty bits
4061                  * are set, otherwise the system might mis-clear portions
4062                  * of a page.
4063                  */
4064                 if (m->dirty == VM_PAGE_BITS_ALL &&
4065                     (bp->b_flags & B_NEEDCOMMIT) == 0) {
4066                         pmap_clear_modify(m);
4067                 }
4068                 if (bp->b_dirtyoff > soff - xoff)
4069                         bp->b_dirtyoff = soff - xoff;
4070                 if (bp->b_dirtyend < eoff - xoff)
4071                         bp->b_dirtyend = eoff - xoff;
4072         }
4073
4074         /*
4075          * Set related valid bits, clear related dirty bits.
4076          * Does not mess with the pmap modified bit.
4077          *
4078          * WARNING!  We cannot just clear all of m->dirty here as the
4079          *           buffer cache buffers may use a DEV_BSIZE'd aligned
4080          *           block size, or have an odd size (e.g. NFS at file EOF).
4081          *           The putpages code can clear m->dirty to 0.
4082          *
4083          *           If a VOP_WRITE generates a buffer cache buffer which
4084          *           covers the same space as mapped writable pages the
4085          *           buffer flush might not be able to clear all the dirty
4086          *           bits and still require a putpages from the VM system
4087          *           to finish it off.
4088          */
4089         vm_page_set_validclean(m, soff & PAGE_MASK, eoff - soff);
4090 }
4091
4092 /*
4093  * vfs_bio_clrbuf:
4094  *
4095  *      Clear a buffer.  This routine essentially fakes an I/O, so we need
4096  *      to clear B_ERROR and B_INVAL.
4097  *
4098  *      Note that while we only theoretically need to clear through b_bcount,
4099  *      we go ahead and clear through b_bufsize.
4100  */
4101
4102 void
4103 vfs_bio_clrbuf(struct buf *bp)
4104 {
4105         int i, mask = 0;
4106         caddr_t sa, ea;
4107         if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
4108                 bp->b_flags &= ~(B_INVAL | B_EINTR | B_ERROR);
4109                 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4110                     (bp->b_loffset & PAGE_MASK) == 0) {
4111                         mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4112                         if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
4113                                 bp->b_resid = 0;
4114                                 return;
4115                         }
4116                         if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
4117                             ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
4118                                 bzero(bp->b_data, bp->b_bufsize);
4119                                 bp->b_xio.xio_pages[0]->valid |= mask;
4120                                 bp->b_resid = 0;
4121                                 return;
4122                         }
4123                 }
4124                 sa = bp->b_data;
4125                 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
4126                         int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
4127                         ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
4128                         ea = (caddr_t)(vm_offset_t)ulmin(
4129                             (u_long)(vm_offset_t)ea,
4130                             (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
4131                         mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4132                         if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
4133                                 continue;
4134                         if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
4135                                 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
4136                                         bzero(sa, ea - sa);
4137                                 }
4138                         } else {
4139                                 for (; sa < ea; sa += DEV_BSIZE, j++) {
4140                                         if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
4141                                                 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
4142                                                 bzero(sa, DEV_BSIZE);
4143                                 }
4144                         }
4145                         bp->b_xio.xio_pages[i]->valid |= mask;
4146                         vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
4147                 }
4148                 bp->b_resid = 0;
4149         } else {
4150                 clrbuf(bp);
4151         }
4152 }
4153
4154 /*
4155  * vm_hold_load_pages:
4156  *
4157  *      Load pages into the buffer's address space.  The pages are
4158  *      allocated from the kernel object in order to reduce interference
4159  *      with the any VM paging I/O activity.  The range of loaded
4160  *      pages will be wired.
4161  *
4162  *      If a page cannot be allocated, the 'pagedaemon' is woken up to
4163  *      retrieve the full range (to - from) of pages.
4164  *
4165  */
4166 void
4167 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4168 {
4169         vm_offset_t pg;
4170         vm_page_t p;
4171         int index;
4172
4173         to = round_page(to);
4174         from = round_page(from);
4175         index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4176
4177         pg = from;
4178         while (pg < to) {
4179                 /*
4180                  * Note: must allocate system pages since blocking here
4181                  * could intefere with paging I/O, no matter which
4182                  * process we are.
4183                  */
4184                 p = bio_page_alloc(&kernel_object, pg >> PAGE_SHIFT,
4185                                    (vm_pindex_t)((to - pg) >> PAGE_SHIFT));
4186                 if (p) {
4187                         vm_page_wire(p);
4188                         p->valid = VM_PAGE_BITS_ALL;
4189                         vm_page_flag_clear(p, PG_ZERO);
4190                         pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
4191                         bp->b_xio.xio_pages[index] = p;
4192                         vm_page_wakeup(p);
4193
4194                         pg += PAGE_SIZE;
4195                         ++index;
4196                 }
4197         }
4198         bp->b_xio.xio_npages = index;
4199 }
4200
4201 /*
4202  * Allocate pages for a buffer cache buffer.
4203  *
4204  * Under extremely severe memory conditions even allocating out of the
4205  * system reserve can fail.  If this occurs we must allocate out of the
4206  * interrupt reserve to avoid a deadlock with the pageout daemon.
4207  *
4208  * The pageout daemon can run (putpages -> VOP_WRITE -> getblk -> allocbuf).
4209  * If the buffer cache's vm_page_alloc() fails a vm_wait() can deadlock
4210  * against the pageout daemon if pages are not freed from other sources.
4211  */
4212 static
4213 vm_page_t
4214 bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit)
4215 {
4216         vm_page_t p;
4217
4218         /*
4219          * Try a normal allocation, allow use of system reserve.
4220          */
4221         p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
4222         if (p)
4223                 return(p);
4224
4225         /*
4226          * The normal allocation failed and we clearly have a page
4227          * deficit.  Try to reclaim some clean VM pages directly
4228          * from the buffer cache.
4229          */
4230         vm_pageout_deficit += deficit;
4231         recoverbufpages();
4232
4233         /*
4234          * We may have blocked, the caller will know what to do if the
4235          * page now exists.
4236          */
4237         if (vm_page_lookup(obj, pg))
4238                 return(NULL);
4239
4240         /*
4241          * Allocate and allow use of the interrupt reserve.
4242          *
4243          * If after all that we still can't allocate a VM page we are
4244          * in real trouble, but we slog on anyway hoping that the system
4245          * won't deadlock.
4246          */
4247         p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
4248                                    VM_ALLOC_INTERRUPT);
4249         if (p) {
4250                 if (vm_page_count_severe()) {
4251                         kprintf("bio_page_alloc: WARNING emergency page "
4252                                 "allocation\n");
4253                         vm_wait(hz / 20);
4254                 }
4255         } else {
4256                 kprintf("bio_page_alloc: WARNING emergency page "
4257                         "allocation failed\n");
4258                 vm_wait(hz * 5);
4259         }
4260         return(p);
4261 }
4262
4263 /*
4264  * vm_hold_free_pages:
4265  *
4266  *      Return pages associated with the buffer back to the VM system.
4267  *
4268  *      The range of pages underlying the buffer's address space will
4269  *      be unmapped and un-wired.
4270  */
4271 void
4272 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4273 {
4274         vm_offset_t pg;
4275         vm_page_t p;
4276         int index, newnpages;
4277
4278         from = round_page(from);
4279         to = round_page(to);
4280         newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4281
4282         for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4283                 p = bp->b_xio.xio_pages[index];
4284                 if (p && (index < bp->b_xio.xio_npages)) {
4285                         if (p->busy) {
4286                                 kprintf("vm_hold_free_pages: doffset: %lld, "
4287                                         "loffset: %lld\n",
4288                                         (long long)bp->b_bio2.bio_offset,
4289                                         (long long)bp->b_loffset);
4290                         }
4291                         bp->b_xio.xio_pages[index] = NULL;
4292                         pmap_kremove(pg);
4293                         vm_page_busy(p);
4294                         vm_page_unwire(p, 0);
4295                         vm_page_free(p);
4296                 }
4297         }
4298         bp->b_xio.xio_npages = newnpages;
4299 }
4300
4301 /*
4302  * vmapbuf:
4303  *
4304  *      Map a user buffer into KVM via a pbuf.  On return the buffer's
4305  *      b_data, b_bufsize, and b_bcount will be set, and its XIO page array
4306  *      initialized.
4307  */
4308 int
4309 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
4310 {
4311         caddr_t addr;
4312         vm_offset_t va;
4313         vm_page_t m;
4314         int vmprot;
4315         int error;
4316         int pidx;
4317         int i;
4318
4319         /* 
4320          * bp had better have a command and it better be a pbuf.
4321          */
4322         KKASSERT(bp->b_cmd != BUF_CMD_DONE);
4323         KKASSERT(bp->b_flags & B_PAGING);
4324
4325         if (bytes < 0)
4326                 return (-1);
4327
4328         /*
4329          * Map the user data into KVM.  Mappings have to be page-aligned.
4330          */
4331         addr = (caddr_t)trunc_page((vm_offset_t)udata);
4332         pidx = 0;
4333
4334         vmprot = VM_PROT_READ;
4335         if (bp->b_cmd == BUF_CMD_READ)
4336                 vmprot |= VM_PROT_WRITE;
4337
4338         while (addr < udata + bytes) {
4339                 /*
4340                  * Do the vm_fault if needed; do the copy-on-write thing
4341                  * when reading stuff off device into memory.
4342                  *
4343                  * vm_fault_page*() returns a held VM page.
4344                  */
4345                 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
4346                 va = trunc_page(va);
4347
4348                 m = vm_fault_page_quick(va, vmprot, &error);
4349                 if (m == NULL) {
4350                         for (i = 0; i < pidx; ++i) {
4351                             vm_page_unhold(bp->b_xio.xio_pages[i]);
4352                             bp->b_xio.xio_pages[i] = NULL;
4353                         }
4354                         return(-1);
4355                 }
4356                 bp->b_xio.xio_pages[pidx] = m;
4357                 addr += PAGE_SIZE;
4358                 ++pidx;
4359         }
4360
4361         /*
4362          * Map the page array and set the buffer fields to point to
4363          * the mapped data buffer.
4364          */
4365         if (pidx > btoc(MAXPHYS))
4366                 panic("vmapbuf: mapped more than MAXPHYS");
4367         pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
4368
4369         bp->b_xio.xio_npages = pidx;
4370         bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
4371         bp->b_bcount = bytes;
4372         bp->b_bufsize = bytes;
4373         return(0);
4374 }
4375
4376 /*
4377  * vunmapbuf:
4378  *
4379  *      Free the io map PTEs associated with this IO operation.
4380  *      We also invalidate the TLB entries and restore the original b_addr.
4381  */
4382 void
4383 vunmapbuf(struct buf *bp)
4384 {
4385         int pidx;
4386         int npages;
4387
4388         KKASSERT(bp->b_flags & B_PAGING);
4389
4390         npages = bp->b_xio.xio_npages;
4391         pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4392         for (pidx = 0; pidx < npages; ++pidx) {
4393                 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
4394                 bp->b_xio.xio_pages[pidx] = NULL;
4395         }
4396         bp->b_xio.xio_npages = 0;
4397         bp->b_data = bp->b_kvabase;
4398 }
4399
4400 /*
4401  * Scan all buffers in the system and issue the callback.
4402  */
4403 int
4404 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
4405 {
4406         int count = 0;
4407         int error;
4408         int n;
4409
4410         for (n = 0; n < nbuf; ++n) {
4411                 if ((error = callback(&buf[n], info)) < 0) {
4412                         count = error;
4413                         break;
4414                 }
4415                 count += error;
4416         }
4417         return (count);
4418 }
4419
4420 /*
4421  * print out statistics from the current status of the buffer pool
4422  * this can be toggeled by the system control option debug.syncprt
4423  */
4424 #ifdef DEBUG
4425 void
4426 vfs_bufstats(void)
4427 {
4428         int i, j, count;
4429         struct buf *bp;
4430         struct bqueues *dp;
4431         int counts[(MAXBSIZE / PAGE_SIZE) + 1];
4432         static char *bname[3] = { "LOCKED", "LRU", "AGE" };
4433
4434         for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
4435                 count = 0;
4436                 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4437                         counts[j] = 0;
4438                 crit_enter();
4439                 TAILQ_FOREACH(bp, dp, b_freelist) {
4440                         counts[bp->b_bufsize/PAGE_SIZE]++;
4441                         count++;
4442                 }
4443                 crit_exit();
4444                 kprintf("%s: total-%d", bname[i], count);
4445                 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4446                         if (counts[j] != 0)
4447                                 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
4448                 kprintf("\n");
4449         }
4450 }
4451 #endif
4452
4453 #ifdef DDB
4454
4455 DB_SHOW_COMMAND(buffer, db_show_buffer)
4456 {
4457         /* get args */
4458         struct buf *bp = (struct buf *)addr;
4459
4460         if (!have_addr) {
4461                 db_printf("usage: show buffer <addr>\n");
4462                 return;
4463         }
4464
4465         db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4466         db_printf("b_cmd = %d\n", bp->b_cmd);
4467         db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
4468                   "b_resid = %d\n, b_data = %p, "
4469                   "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
4470                   bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4471                   bp->b_data,
4472                   (long long)bp->b_bio2.bio_offset,
4473                   (long long)(bp->b_bio2.bio_next ?
4474                                 bp->b_bio2.bio_next->bio_offset : (off_t)-1));
4475         if (bp->b_xio.xio_npages) {
4476                 int i;
4477                 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
4478                         bp->b_xio.xio_npages);
4479                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4480                         vm_page_t m;
4481                         m = bp->b_xio.xio_pages[i];
4482                         db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4483                             (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4484                         if ((i + 1) < bp->b_xio.xio_npages)
4485                                 db_printf(",");
4486                 }
4487                 db_printf("\n");
4488         }
4489 }
4490 #endif /* DDB */