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