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