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