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