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