vfs_bio.c revision 1.95 1 /* $NetBSD: vfs_bio.c,v 1.95 2003/09/07 11:59:40 yamt Exp $ */
2
3 /*-
4 * Copyright (c) 1982, 1986, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 * @(#)vfs_bio.c 8.6 (Berkeley) 1/11/94
37 */
38
39 /*-
40 * Copyright (c) 1994 Christopher G. Demetriou
41 *
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
44 * are met:
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
50 * 3. All advertising materials mentioning features or use of this software
51 * must display the following acknowledgement:
52 * This product includes software developed by the University of
53 * California, Berkeley and its contributors.
54 * 4. Neither the name of the University nor the names of its contributors
55 * may be used to endorse or promote products derived from this software
56 * without specific prior written permission.
57 *
58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * SUCH DAMAGE.
69 *
70 * @(#)vfs_bio.c 8.6 (Berkeley) 1/11/94
71 */
72
73 /*
74 * Some references:
75 * Bach: The Design of the UNIX Operating System (Prentice Hall, 1986)
76 * Leffler, et al.: The Design and Implementation of the 4.3BSD
77 * UNIX Operating System (Addison Welley, 1989)
78 */
79
80 #include "opt_softdep.h"
81
82 #include <sys/cdefs.h>
83 __KERNEL_RCSID(0, "$NetBSD: vfs_bio.c,v 1.95 2003/09/07 11:59:40 yamt Exp $");
84
85 #include <sys/param.h>
86 #include <sys/systm.h>
87 #include <sys/proc.h>
88 #include <sys/buf.h>
89 #include <sys/vnode.h>
90 #include <sys/mount.h>
91 #include <sys/malloc.h>
92 #include <sys/resourcevar.h>
93 #include <sys/conf.h>
94
95 #include <uvm/uvm.h>
96
97 #include <miscfs/specfs/specdev.h>
98
99 /* Macros to clear/set/test flags. */
100 #define SET(t, f) (t) |= (f)
101 #define CLR(t, f) (t) &= ~(f)
102 #define ISSET(t, f) ((t) & (f))
103
104 /*
105 * Definitions for the buffer hash lists.
106 */
107 #define BUFHASH(dvp, lbn) \
108 (&bufhashtbl[(((long)(dvp) >> 8) + (int)(lbn)) & bufhash])
109 LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
110 u_long bufhash;
111 #ifndef SOFTDEP
112 struct bio_ops bioops; /* I/O operation notification */
113 #endif
114
115 /*
116 * Insq/Remq for the buffer hash lists.
117 */
118 #define binshash(bp, dp) LIST_INSERT_HEAD(dp, bp, b_hash)
119 #define bremhash(bp) LIST_REMOVE(bp, b_hash)
120
121 /*
122 * Definitions for the buffer free lists.
123 */
124 #define BQUEUES 4 /* number of free buffer queues */
125
126 #define BQ_LOCKED 0 /* super-blocks &c */
127 #define BQ_LRU 1 /* lru, useful buffers */
128 #define BQ_AGE 2 /* rubbish */
129 #define BQ_EMPTY 3 /* buffer headers with no memory */
130
131 TAILQ_HEAD(bqueues, buf) bufqueues[BQUEUES];
132 int needbuffer;
133
134 /*
135 * Buffer queue lock.
136 * Take this lock first if also taking some buffer's b_interlock.
137 */
138 struct simplelock bqueue_slock = SIMPLELOCK_INITIALIZER;
139
140 /*
141 * Buffer pool for I/O buffers.
142 */
143 struct pool bufpool;
144
145 /*
146 * bread()/breadn() helper.
147 */
148 static __inline struct buf *bio_doread(struct vnode *, daddr_t, int,
149 struct ucred *, int);
150 int count_lock_queue(void);
151
152 /*
153 * Insq/Remq for the buffer free lists.
154 * Call with buffer queue locked.
155 */
156 #define binsheadfree(bp, dp) TAILQ_INSERT_HEAD(dp, bp, b_freelist)
157 #define binstailfree(bp, dp) TAILQ_INSERT_TAIL(dp, bp, b_freelist)
158
159 void
160 bremfree(bp)
161 struct buf *bp;
162 {
163 struct bqueues *dp = NULL;
164
165 LOCK_ASSERT(simple_lock_held(&bqueue_slock));
166
167 /*
168 * We only calculate the head of the freelist when removing
169 * the last element of the list as that is the only time that
170 * it is needed (e.g. to reset the tail pointer).
171 *
172 * NB: This makes an assumption about how tailq's are implemented.
173 */
174 if (TAILQ_NEXT(bp, b_freelist) == NULL) {
175 for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++)
176 if (dp->tqh_last == &bp->b_freelist.tqe_next)
177 break;
178 if (dp == &bufqueues[BQUEUES])
179 panic("bremfree: lost tail");
180 }
181 TAILQ_REMOVE(dp, bp, b_freelist);
182 }
183
184 /*
185 * Initialize buffers and hash links for buffers.
186 */
187 void
188 bufinit()
189 {
190 struct buf *bp;
191 struct bqueues *dp;
192 u_int i, base, residual;
193
194 /*
195 * Initialize the buffer pool. This pool is used for buffers
196 * which are strictly I/O control blocks, not buffer cache
197 * buffers.
198 */
199 pool_init(&bufpool, sizeof(struct buf), 0, 0, 0, "bufpl", NULL);
200
201 for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++)
202 TAILQ_INIT(dp);
203 bufhashtbl = hashinit(nbuf, HASH_LIST, M_CACHE, M_WAITOK, &bufhash);
204 base = bufpages / nbuf;
205 residual = bufpages % nbuf;
206 for (i = 0; i < nbuf; i++) {
207 bp = &buf[i];
208 memset((char *)bp, 0, sizeof(*bp));
209 BUF_INIT(bp);
210 bp->b_dev = NODEV;
211 bp->b_vnbufs.le_next = NOLIST;
212 bp->b_data = buffers + i * MAXBSIZE;
213 if (i < residual)
214 bp->b_bufsize = (base + 1) * PAGE_SIZE;
215 else
216 bp->b_bufsize = base * PAGE_SIZE;
217 bp->b_flags = B_INVAL;
218 dp = bp->b_bufsize ? &bufqueues[BQ_AGE] : &bufqueues[BQ_EMPTY];
219 binsheadfree(bp, dp);
220 binshash(bp, &invalhash);
221 }
222 }
223
224 static __inline struct buf *
225 bio_doread(vp, blkno, size, cred, async)
226 struct vnode *vp;
227 daddr_t blkno;
228 int size;
229 struct ucred *cred;
230 int async;
231 {
232 struct buf *bp;
233 struct lwp *l = (curlwp != NULL ? curlwp : &lwp0); /* XXX */
234 struct proc *p = l->l_proc;
235
236 bp = getblk(vp, blkno, size, 0, 0);
237
238 #ifdef DIAGNOSTIC
239 if (bp == NULL) {
240 panic("bio_doread: no such buf");
241 }
242 #endif
243
244 /*
245 * If buffer does not have data valid, start a read.
246 * Note that if buffer is B_INVAL, getblk() won't return it.
247 * Therefore, it's valid if its I/O has completed or been delayed.
248 */
249 if (!ISSET(bp->b_flags, (B_DONE | B_DELWRI))) {
250 /* Start I/O for the buffer. */
251 SET(bp->b_flags, B_READ | async);
252 VOP_STRATEGY(bp);
253
254 /* Pay for the read. */
255 p->p_stats->p_ru.ru_inblock++;
256 } else if (async) {
257 brelse(bp);
258 }
259
260 return (bp);
261 }
262
263 /*
264 * Read a disk block.
265 * This algorithm described in Bach (p.54).
266 */
267 int
268 bread(vp, blkno, size, cred, bpp)
269 struct vnode *vp;
270 daddr_t blkno;
271 int size;
272 struct ucred *cred;
273 struct buf **bpp;
274 {
275 struct buf *bp;
276
277 /* Get buffer for block. */
278 bp = *bpp = bio_doread(vp, blkno, size, cred, 0);
279
280 /* Wait for the read to complete, and return result. */
281 return (biowait(bp));
282 }
283
284 /*
285 * Read-ahead multiple disk blocks. The first is sync, the rest async.
286 * Trivial modification to the breada algorithm presented in Bach (p.55).
287 */
288 int
289 breadn(vp, blkno, size, rablks, rasizes, nrablks, cred, bpp)
290 struct vnode *vp;
291 daddr_t blkno; int size;
292 daddr_t rablks[]; int rasizes[];
293 int nrablks;
294 struct ucred *cred;
295 struct buf **bpp;
296 {
297 struct buf *bp;
298 int i;
299
300 bp = *bpp = bio_doread(vp, blkno, size, cred, 0);
301
302 /*
303 * For each of the read-ahead blocks, start a read, if necessary.
304 */
305 for (i = 0; i < nrablks; i++) {
306 /* If it's in the cache, just go on to next one. */
307 if (incore(vp, rablks[i]))
308 continue;
309
310 /* Get a buffer for the read-ahead block */
311 (void) bio_doread(vp, rablks[i], rasizes[i], cred, B_ASYNC);
312 }
313
314 /* Otherwise, we had to start a read for it; wait until it's valid. */
315 return (biowait(bp));
316 }
317
318 /*
319 * Read with single-block read-ahead. Defined in Bach (p.55), but
320 * implemented as a call to breadn().
321 * XXX for compatibility with old file systems.
322 */
323 int
324 breada(vp, blkno, size, rablkno, rabsize, cred, bpp)
325 struct vnode *vp;
326 daddr_t blkno; int size;
327 daddr_t rablkno; int rabsize;
328 struct ucred *cred;
329 struct buf **bpp;
330 {
331
332 return (breadn(vp, blkno, size, &rablkno, &rabsize, 1, cred, bpp));
333 }
334
335 /*
336 * Block write. Described in Bach (p.56)
337 */
338 int
339 bwrite(bp)
340 struct buf *bp;
341 {
342 int rv, sync, wasdelayed, s;
343 struct lwp *l = (curlwp != NULL ? curlwp : &lwp0); /* XXX */
344 struct proc *p = l->l_proc;
345 struct vnode *vp;
346 struct mount *mp;
347
348 KASSERT(ISSET(bp->b_flags, B_BUSY));
349
350 vp = bp->b_vp;
351 if (vp != NULL) {
352 if (vp->v_type == VBLK)
353 mp = vp->v_specmountpoint;
354 else
355 mp = vp->v_mount;
356 } else {
357 mp = NULL;
358 }
359
360 /*
361 * Remember buffer type, to switch on it later. If the write was
362 * synchronous, but the file system was mounted with MNT_ASYNC,
363 * convert it to a delayed write.
364 * XXX note that this relies on delayed tape writes being converted
365 * to async, not sync writes (which is safe, but ugly).
366 */
367 sync = !ISSET(bp->b_flags, B_ASYNC);
368 if (sync && mp != NULL && ISSET(mp->mnt_flag, MNT_ASYNC)) {
369 bdwrite(bp);
370 return (0);
371 }
372
373 /*
374 * Collect statistics on synchronous and asynchronous writes.
375 * Writes to block devices are charged to their associated
376 * filesystem (if any).
377 */
378 if (mp != NULL) {
379 if (sync)
380 mp->mnt_stat.f_syncwrites++;
381 else
382 mp->mnt_stat.f_asyncwrites++;
383 }
384
385 wasdelayed = ISSET(bp->b_flags, B_DELWRI);
386
387 s = splbio();
388 simple_lock(&bp->b_interlock);
389
390 CLR(bp->b_flags, (B_READ | B_DONE | B_ERROR | B_DELWRI));
391
392 /*
393 * Pay for the I/O operation and make sure the buf is on the correct
394 * vnode queue.
395 */
396 if (wasdelayed)
397 reassignbuf(bp, bp->b_vp);
398 else
399 p->p_stats->p_ru.ru_oublock++;
400
401 /* Initiate disk write. Make sure the appropriate party is charged. */
402 V_INCR_NUMOUTPUT(bp->b_vp);
403 simple_unlock(&bp->b_interlock);
404 splx(s);
405
406 VOP_STRATEGY(bp);
407
408 if (sync) {
409 /* If I/O was synchronous, wait for it to complete. */
410 rv = biowait(bp);
411
412 /* Release the buffer. */
413 brelse(bp);
414
415 return (rv);
416 } else {
417 return (0);
418 }
419 }
420
421 int
422 vn_bwrite(v)
423 void *v;
424 {
425 struct vop_bwrite_args *ap = v;
426
427 return (bwrite(ap->a_bp));
428 }
429
430 /*
431 * Delayed write.
432 *
433 * The buffer is marked dirty, but is not queued for I/O.
434 * This routine should be used when the buffer is expected
435 * to be modified again soon, typically a small write that
436 * partially fills a buffer.
437 *
438 * NB: magnetic tapes cannot be delayed; they must be
439 * written in the order that the writes are requested.
440 *
441 * Described in Leffler, et al. (pp. 208-213).
442 */
443 void
444 bdwrite(bp)
445 struct buf *bp;
446 {
447 struct lwp *l = (curlwp != NULL ? curlwp : &lwp0); /* XXX */
448 struct proc *p = l->l_proc;
449 const struct bdevsw *bdev;
450 int s;
451
452 KASSERT(ISSET(bp->b_flags, B_BUSY));
453
454 /* If this is a tape block, write the block now. */
455 bdev = bdevsw_lookup(bp->b_dev);
456 if (bdev != NULL && bdev->d_type == D_TAPE) {
457 bawrite(bp);
458 return;
459 }
460
461 /*
462 * If the block hasn't been seen before:
463 * (1) Mark it as having been seen,
464 * (2) Charge for the write,
465 * (3) Make sure it's on its vnode's correct block list.
466 */
467 s = splbio();
468 simple_lock(&bp->b_interlock);
469
470 if (!ISSET(bp->b_flags, B_DELWRI)) {
471 SET(bp->b_flags, B_DELWRI);
472 p->p_stats->p_ru.ru_oublock++;
473 reassignbuf(bp, bp->b_vp);
474 }
475
476 /* Otherwise, the "write" is done, so mark and release the buffer. */
477 CLR(bp->b_flags, B_DONE);
478 simple_unlock(&bp->b_interlock);
479 splx(s);
480
481 brelse(bp);
482 }
483
484 /*
485 * Asynchronous block write; just an asynchronous bwrite().
486 */
487 void
488 bawrite(bp)
489 struct buf *bp;
490 {
491 int s;
492
493 KASSERT(ISSET(bp->b_flags, B_BUSY));
494
495 s = splbio();
496 simple_lock(&bp->b_interlock);
497 SET(bp->b_flags, B_ASYNC);
498 simple_unlock(&bp->b_interlock);
499 splx(s);
500 VOP_BWRITE(bp);
501 }
502
503 /*
504 * Same as first half of bdwrite, mark buffer dirty, but do not release it.
505 * Call at splbio() and with the buffer interlock locked.
506 * Note: called only from biodone() through ffs softdep's bioops.io_complete()
507 */
508 void
509 bdirty(bp)
510 struct buf *bp;
511 {
512 struct lwp *l = (curlwp != NULL ? curlwp : &lwp0); /* XXX */
513 struct proc *p = l->l_proc;
514
515 KASSERT(ISSET(bp->b_flags, B_BUSY));
516 LOCK_ASSERT(simple_lock_held(&bp->b_interlock));
517
518 CLR(bp->b_flags, B_AGE);
519
520 if (!ISSET(bp->b_flags, B_DELWRI)) {
521 SET(bp->b_flags, B_DELWRI);
522 p->p_stats->p_ru.ru_oublock++;
523 reassignbuf(bp, bp->b_vp);
524 }
525 }
526
527 /*
528 * Release a buffer on to the free lists.
529 * Described in Bach (p. 46).
530 */
531 void
532 brelse(bp)
533 struct buf *bp;
534 {
535 struct bqueues *bufq;
536 int s;
537
538 KASSERT(ISSET(bp->b_flags, B_BUSY));
539 KASSERT(!ISSET(bp->b_flags, B_CALL));
540
541 /* Block disk interrupts. */
542 s = splbio();
543 simple_lock(&bqueue_slock);
544 simple_lock(&bp->b_interlock);
545
546 /* Wake up any processes waiting for any buffer to become free. */
547 if (needbuffer) {
548 needbuffer = 0;
549 wakeup(&needbuffer);
550 }
551
552 /* Wake up any proceeses waiting for _this_ buffer to become free. */
553 if (ISSET(bp->b_flags, B_WANTED)) {
554 CLR(bp->b_flags, B_WANTED|B_AGE);
555 wakeup(bp);
556 }
557
558 /*
559 * Determine which queue the buffer should be on, then put it there.
560 */
561
562 /* If it's locked, don't report an error; try again later. */
563 if (ISSET(bp->b_flags, (B_LOCKED|B_ERROR)) == (B_LOCKED|B_ERROR))
564 CLR(bp->b_flags, B_ERROR);
565
566 /* If it's not cacheable, or an error, mark it invalid. */
567 if (ISSET(bp->b_flags, (B_NOCACHE|B_ERROR)))
568 SET(bp->b_flags, B_INVAL);
569
570 if (ISSET(bp->b_flags, B_VFLUSH)) {
571 /*
572 * This is a delayed write buffer that was just flushed to
573 * disk. It is still on the LRU queue. If it's become
574 * invalid, then we need to move it to a different queue;
575 * otherwise leave it in its current position.
576 */
577 CLR(bp->b_flags, B_VFLUSH);
578 if (!ISSET(bp->b_flags, B_ERROR|B_INVAL|B_LOCKED|B_AGE))
579 goto already_queued;
580 else
581 bremfree(bp);
582 }
583
584 if ((bp->b_bufsize <= 0) || ISSET(bp->b_flags, B_INVAL)) {
585 /*
586 * If it's invalid or empty, dissociate it from its vnode
587 * and put on the head of the appropriate queue.
588 */
589 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
590 (*bioops.io_deallocate)(bp);
591 CLR(bp->b_flags, B_DONE|B_DELWRI);
592 if (bp->b_vp) {
593 reassignbuf(bp, bp->b_vp);
594 brelvp(bp);
595 }
596 if (bp->b_bufsize <= 0)
597 /* no data */
598 bufq = &bufqueues[BQ_EMPTY];
599 else
600 /* invalid data */
601 bufq = &bufqueues[BQ_AGE];
602 binsheadfree(bp, bufq);
603 } else {
604 /*
605 * It has valid data. Put it on the end of the appropriate
606 * queue, so that it'll stick around for as long as possible.
607 * If buf is AGE, but has dependencies, must put it on last
608 * bufqueue to be scanned, ie LRU. This protects against the
609 * livelock where BQ_AGE only has buffers with dependencies,
610 * and we thus never get to the dependent buffers in BQ_LRU.
611 */
612 if (ISSET(bp->b_flags, B_LOCKED))
613 /* locked in core */
614 bufq = &bufqueues[BQ_LOCKED];
615 else if (!ISSET(bp->b_flags, B_AGE))
616 /* valid data */
617 bufq = &bufqueues[BQ_LRU];
618 else {
619 /* stale but valid data */
620 int has_deps;
621
622 if (LIST_FIRST(&bp->b_dep) != NULL &&
623 bioops.io_countdeps)
624 has_deps = (*bioops.io_countdeps)(bp, 0);
625 else
626 has_deps = 0;
627 bufq = has_deps ? &bufqueues[BQ_LRU] :
628 &bufqueues[BQ_AGE];
629 }
630 binstailfree(bp, bufq);
631 }
632
633 already_queued:
634 /* Unlock the buffer. */
635 CLR(bp->b_flags, B_AGE|B_ASYNC|B_BUSY|B_NOCACHE);
636 SET(bp->b_flags, B_CACHE);
637
638 /* Allow disk interrupts. */
639 simple_unlock(&bp->b_interlock);
640 simple_unlock(&bqueue_slock);
641 splx(s);
642 }
643
644 /*
645 * Determine if a block is in the cache.
646 * Just look on what would be its hash chain. If it's there, return
647 * a pointer to it, unless it's marked invalid. If it's marked invalid,
648 * we normally don't return the buffer, unless the caller explicitly
649 * wants us to.
650 */
651 struct buf *
652 incore(vp, blkno)
653 struct vnode *vp;
654 daddr_t blkno;
655 {
656 struct buf *bp;
657
658 /* Search hash chain */
659 LIST_FOREACH(bp, BUFHASH(vp, blkno), b_hash) {
660 if (bp->b_lblkno == blkno && bp->b_vp == vp &&
661 !ISSET(bp->b_flags, B_INVAL))
662 return (bp);
663 }
664
665 return (NULL);
666 }
667
668 /*
669 * Get a block of requested size that is associated with
670 * a given vnode and block offset. If it is found in the
671 * block cache, mark it as having been found, make it busy
672 * and return it. Otherwise, return an empty block of the
673 * correct size. It is up to the caller to insure that the
674 * cached blocks be of the correct size.
675 */
676 struct buf *
677 getblk(vp, blkno, size, slpflag, slptimeo)
678 struct vnode *vp;
679 daddr_t blkno;
680 int size, slpflag, slptimeo;
681 {
682 struct buf *bp;
683 int s, err;
684
685 start:
686 s = splbio();
687 simple_lock(&bqueue_slock);
688 bp = incore(vp, blkno);
689 if (bp != NULL) {
690 simple_lock(&bp->b_interlock);
691 if (ISSET(bp->b_flags, B_BUSY)) {
692 simple_unlock(&bqueue_slock);
693 if (curproc == uvm.pagedaemon_proc) {
694 simple_unlock(&bp->b_interlock);
695 splx(s);
696 return NULL;
697 }
698 SET(bp->b_flags, B_WANTED);
699 err = ltsleep(bp, slpflag | (PRIBIO + 1) | PNORELOCK,
700 "getblk", slptimeo, &bp->b_interlock);
701 splx(s);
702 if (err)
703 return (NULL);
704 goto start;
705 }
706 #ifdef DIAGNOSTIC
707 if (ISSET(bp->b_flags, B_DONE|B_DELWRI) &&
708 bp->b_bcount < size && vp->v_type != VBLK)
709 panic("getblk: block size invariant failed");
710 #endif
711 SET(bp->b_flags, B_BUSY);
712 bremfree(bp);
713 } else {
714 if ((bp = getnewbuf(slpflag, slptimeo)) == NULL) {
715 simple_unlock(&bqueue_slock);
716 splx(s);
717 goto start;
718 }
719
720 binshash(bp, BUFHASH(vp, blkno));
721 bp->b_blkno = bp->b_lblkno = bp->b_rawblkno = blkno;
722 bgetvp(vp, bp);
723 }
724 simple_unlock(&bp->b_interlock);
725 simple_unlock(&bqueue_slock);
726 splx(s);
727 allocbuf(bp, size);
728 return (bp);
729 }
730
731 /*
732 * Get an empty, disassociated buffer of given size.
733 */
734 struct buf *
735 geteblk(size)
736 int size;
737 {
738 struct buf *bp;
739 int s;
740
741 s = splbio();
742 simple_lock(&bqueue_slock);
743 while ((bp = getnewbuf(0, 0)) == 0)
744 ;
745
746 SET(bp->b_flags, B_INVAL);
747 binshash(bp, &invalhash);
748 simple_unlock(&bqueue_slock);
749 simple_unlock(&bp->b_interlock);
750 splx(s);
751 allocbuf(bp, size);
752 return (bp);
753 }
754
755 /*
756 * Expand or contract the actual memory allocated to a buffer.
757 *
758 * If the buffer shrinks, data is lost, so it's up to the
759 * caller to have written it out *first*; this routine will not
760 * start a write. If the buffer grows, it's the callers
761 * responsibility to fill out the buffer's additional contents.
762 */
763 void
764 allocbuf(bp, size)
765 struct buf *bp;
766 int size;
767 {
768 struct buf *nbp;
769 vsize_t desired_size;
770 int s;
771
772 desired_size = round_page((vsize_t)size);
773 if (desired_size > MAXBSIZE)
774 panic("allocbuf: buffer larger than MAXBSIZE requested");
775
776 if (bp->b_bufsize == desired_size)
777 goto out;
778
779 /*
780 * If the buffer is smaller than the desired size, we need to snarf
781 * it from other buffers. Get buffers (via getnewbuf()), and
782 * steal their pages.
783 */
784 while (bp->b_bufsize < desired_size) {
785 int amt;
786
787 /* find a buffer */
788 s = splbio();
789 simple_lock(&bqueue_slock);
790 while ((nbp = getnewbuf(0, 0)) == NULL)
791 ;
792
793 SET(nbp->b_flags, B_INVAL);
794 binshash(nbp, &invalhash);
795
796 simple_unlock(&nbp->b_interlock);
797 simple_unlock(&bqueue_slock);
798 splx(s);
799
800 /* and steal its pages, up to the amount we need */
801 amt = min(nbp->b_bufsize, (desired_size - bp->b_bufsize));
802 pagemove((nbp->b_data + nbp->b_bufsize - amt),
803 bp->b_data + bp->b_bufsize, amt);
804 bp->b_bufsize += amt;
805 nbp->b_bufsize -= amt;
806
807 /* reduce transfer count if we stole some data */
808 if (nbp->b_bcount > nbp->b_bufsize)
809 nbp->b_bcount = nbp->b_bufsize;
810
811 #ifdef DIAGNOSTIC
812 if (nbp->b_bufsize < 0)
813 panic("allocbuf: negative bufsize");
814 #endif
815 brelse(nbp);
816 }
817
818 /*
819 * If we want a buffer smaller than the current size,
820 * shrink this buffer. Grab a buf head from the EMPTY queue,
821 * move a page onto it, and put it on front of the AGE queue.
822 * If there are no free buffer headers, leave the buffer alone.
823 */
824 if (bp->b_bufsize > desired_size) {
825 s = splbio();
826 simple_lock(&bqueue_slock);
827 if ((nbp = TAILQ_FIRST(&bufqueues[BQ_EMPTY])) == NULL) {
828 /* No free buffer head */
829 simple_unlock(&bqueue_slock);
830 splx(s);
831 goto out;
832 }
833 /* No need to lock nbp since it came from the empty queue */
834 bremfree(nbp);
835 SET(nbp->b_flags, B_BUSY | B_INVAL);
836 simple_unlock(&bqueue_slock);
837 splx(s);
838
839 /* move the page to it and note this change */
840 pagemove(bp->b_data + desired_size,
841 nbp->b_data, bp->b_bufsize - desired_size);
842 nbp->b_bufsize = bp->b_bufsize - desired_size;
843 bp->b_bufsize = desired_size;
844 nbp->b_bcount = 0;
845
846 /* release the newly-filled buffer and leave */
847 brelse(nbp);
848 }
849
850 out:
851 bp->b_bcount = size;
852 }
853
854 /*
855 * Find a buffer which is available for use.
856 * Select something from a free list.
857 * Preference is to AGE list, then LRU list.
858 *
859 * Called with buffer queues locked.
860 * Return buffer locked.
861 */
862 struct buf *
863 getnewbuf(slpflag, slptimeo)
864 int slpflag, slptimeo;
865 {
866 struct buf *bp;
867
868 start:
869 LOCK_ASSERT(simple_lock_held(&bqueue_slock));
870
871 if ((bp = TAILQ_FIRST(&bufqueues[BQ_AGE])) != NULL ||
872 (bp = TAILQ_FIRST(&bufqueues[BQ_LRU])) != NULL) {
873 simple_lock(&bp->b_interlock);
874 bremfree(bp);
875 } else {
876 /* wait for a free buffer of any kind */
877 needbuffer = 1;
878 ltsleep(&needbuffer, slpflag|(PRIBIO+1),
879 "getnewbuf", slptimeo, &bqueue_slock);
880 return (NULL);
881 }
882
883 if (ISSET(bp->b_flags, B_VFLUSH)) {
884 /*
885 * This is a delayed write buffer being flushed to disk. Make
886 * sure it gets aged out of the queue when it's finished, and
887 * leave it off the LRU queue.
888 */
889 CLR(bp->b_flags, B_VFLUSH);
890 SET(bp->b_flags, B_AGE);
891 simple_unlock(&bp->b_interlock);
892 goto start;
893 }
894
895 /* Buffer is no longer on free lists. */
896 SET(bp->b_flags, B_BUSY);
897
898 /*
899 * If buffer was a delayed write, start it and return NULL
900 * (since we might sleep while starting the write).
901 */
902 if (ISSET(bp->b_flags, B_DELWRI)) {
903 /*
904 * This buffer has gone through the LRU, so make sure it gets
905 * reused ASAP.
906 */
907 SET(bp->b_flags, B_AGE);
908 simple_unlock(&bp->b_interlock);
909 simple_unlock(&bqueue_slock);
910 bawrite(bp);
911 simple_lock(&bqueue_slock);
912 return (NULL);
913 }
914
915 /* disassociate us from our vnode, if we had one... */
916 if (bp->b_vp)
917 brelvp(bp);
918
919 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
920 (*bioops.io_deallocate)(bp);
921
922 /* clear out various other fields */
923 bp->b_flags = B_BUSY;
924 bp->b_dev = NODEV;
925 bp->b_blkno = bp->b_lblkno = bp->b_rawblkno = 0;
926 bp->b_iodone = 0;
927 bp->b_error = 0;
928 bp->b_resid = 0;
929 bp->b_bcount = 0;
930
931 bremhash(bp);
932 return (bp);
933 }
934
935 /*
936 * Wait for operations on the buffer to complete.
937 * When they do, extract and return the I/O's error value.
938 */
939 int
940 biowait(bp)
941 struct buf *bp;
942 {
943 int s, error;
944
945 s = splbio();
946 simple_lock(&bp->b_interlock);
947 while (!ISSET(bp->b_flags, B_DONE | B_DELWRI))
948 ltsleep(bp, PRIBIO + 1, "biowait", 0, &bp->b_interlock);
949
950 /* check for interruption of I/O (e.g. via NFS), then errors. */
951 if (ISSET(bp->b_flags, B_EINTR)) {
952 CLR(bp->b_flags, B_EINTR);
953 error = EINTR;
954 } else if (ISSET(bp->b_flags, B_ERROR))
955 error = bp->b_error ? bp->b_error : EIO;
956 else
957 error = 0;
958
959 simple_unlock(&bp->b_interlock);
960 splx(s);
961 return (error);
962 }
963
964 /*
965 * Mark I/O complete on a buffer.
966 *
967 * If a callback has been requested, e.g. the pageout
968 * daemon, do so. Otherwise, awaken waiting processes.
969 *
970 * [ Leffler, et al., says on p.247:
971 * "This routine wakes up the blocked process, frees the buffer
972 * for an asynchronous write, or, for a request by the pagedaemon
973 * process, invokes a procedure specified in the buffer structure" ]
974 *
975 * In real life, the pagedaemon (or other system processes) wants
976 * to do async stuff to, and doesn't want the buffer brelse()'d.
977 * (for swap pager, that puts swap buffers on the free lists (!!!),
978 * for the vn device, that puts malloc'd buffers on the free lists!)
979 */
980 void
981 biodone(bp)
982 struct buf *bp;
983 {
984 int s = splbio();
985
986 simple_lock(&bp->b_interlock);
987 if (ISSET(bp->b_flags, B_DONE))
988 panic("biodone already");
989 SET(bp->b_flags, B_DONE); /* note that it's done */
990
991 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
992 (*bioops.io_complete)(bp);
993
994 if (!ISSET(bp->b_flags, B_READ)) /* wake up reader */
995 vwakeup(bp);
996
997 /*
998 * If necessary, call out. Unlock the buffer before calling
999 * iodone() as the buffer isn't valid any more when it return.
1000 */
1001 if (ISSET(bp->b_flags, B_CALL)) {
1002 CLR(bp->b_flags, B_CALL); /* but note callout done */
1003 simple_unlock(&bp->b_interlock);
1004 (*bp->b_iodone)(bp);
1005 } else {
1006 if (ISSET(bp->b_flags, B_ASYNC)) { /* if async, release */
1007 simple_unlock(&bp->b_interlock);
1008 brelse(bp);
1009 } else { /* or just wakeup the buffer */
1010 CLR(bp->b_flags, B_WANTED);
1011 wakeup(bp);
1012 simple_unlock(&bp->b_interlock);
1013 }
1014 }
1015
1016 splx(s);
1017 }
1018
1019 /*
1020 * Return a count of buffers on the "locked" queue.
1021 */
1022 int
1023 count_lock_queue()
1024 {
1025 struct buf *bp;
1026 int n = 0;
1027
1028 simple_lock(&bqueue_slock);
1029 TAILQ_FOREACH(bp, &bufqueues[BQ_LOCKED], b_freelist)
1030 n++;
1031 simple_unlock(&bqueue_slock);
1032 return (n);
1033 }
1034
1035 #ifdef DEBUG
1036 /*
1037 * Print out statistics on the current allocation of the buffer pool.
1038 * Can be enabled to print out on every ``sync'' by setting "syncprt"
1039 * in vfs_syscalls.c using sysctl.
1040 */
1041 void
1042 vfs_bufstats()
1043 {
1044 int s, i, j, count;
1045 struct buf *bp;
1046 struct bqueues *dp;
1047 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
1048 static char *bname[BQUEUES] = { "LOCKED", "LRU", "AGE", "EMPTY" };
1049
1050 for (dp = bufqueues, i = 0; dp < &bufqueues[BQUEUES]; dp++, i++) {
1051 count = 0;
1052 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
1053 counts[j] = 0;
1054 s = splbio();
1055 TAILQ_FOREACH(bp, dp, b_freelist) {
1056 counts[bp->b_bufsize/PAGE_SIZE]++;
1057 count++;
1058 }
1059 splx(s);
1060 printf("%s: total-%d", bname[i], count);
1061 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
1062 if (counts[j] != 0)
1063 printf(", %d-%d", j * PAGE_SIZE, counts[j]);
1064 printf("\n");
1065 }
1066 }
1067 #endif /* DEBUG */
1068