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