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