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