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