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