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