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