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