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