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