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