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