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