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