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