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