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