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