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