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