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