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