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