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