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