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