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