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