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