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