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