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