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