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