vfs_bio.c revision 1.96 1 /* $NetBSD: vfs_bio.c,v 1.96 2003/09/24 10:44:44 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.96 2003/09/24 10:44:44 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 /*
728 * LFS can't track total size of B_LOCKED buffer (locked_queue_bytes)
729 * if we re-size buffers here.
730 */
731 if (ISSET(bp->b_flags, B_LOCKED)) {
732 KASSERT(bp->b_bufsize >= size);
733 } else {
734 allocbuf(bp, size);
735 }
736 return (bp);
737 }
738
739 /*
740 * Get an empty, disassociated buffer of given size.
741 */
742 struct buf *
743 geteblk(size)
744 int size;
745 {
746 struct buf *bp;
747 int s;
748
749 s = splbio();
750 simple_lock(&bqueue_slock);
751 while ((bp = getnewbuf(0, 0)) == 0)
752 ;
753
754 SET(bp->b_flags, B_INVAL);
755 binshash(bp, &invalhash);
756 simple_unlock(&bqueue_slock);
757 simple_unlock(&bp->b_interlock);
758 splx(s);
759 allocbuf(bp, size);
760 return (bp);
761 }
762
763 /*
764 * Expand or contract the actual memory allocated to a buffer.
765 *
766 * If the buffer shrinks, data is lost, so it's up to the
767 * caller to have written it out *first*; this routine will not
768 * start a write. If the buffer grows, it's the callers
769 * responsibility to fill out the buffer's additional contents.
770 */
771 void
772 allocbuf(bp, size)
773 struct buf *bp;
774 int size;
775 {
776 struct buf *nbp;
777 vsize_t desired_size;
778 int s;
779
780 desired_size = round_page((vsize_t)size);
781 if (desired_size > MAXBSIZE)
782 panic("allocbuf: buffer larger than MAXBSIZE requested");
783
784 if (bp->b_bufsize == desired_size)
785 goto out;
786
787 /*
788 * If the buffer is smaller than the desired size, we need to snarf
789 * it from other buffers. Get buffers (via getnewbuf()), and
790 * steal their pages.
791 */
792 while (bp->b_bufsize < desired_size) {
793 int amt;
794
795 /* find a buffer */
796 s = splbio();
797 simple_lock(&bqueue_slock);
798 while ((nbp = getnewbuf(0, 0)) == NULL)
799 ;
800
801 SET(nbp->b_flags, B_INVAL);
802 binshash(nbp, &invalhash);
803
804 simple_unlock(&nbp->b_interlock);
805 simple_unlock(&bqueue_slock);
806 splx(s);
807
808 /* and steal its pages, up to the amount we need */
809 amt = min(nbp->b_bufsize, (desired_size - bp->b_bufsize));
810 pagemove((nbp->b_data + nbp->b_bufsize - amt),
811 bp->b_data + bp->b_bufsize, amt);
812 bp->b_bufsize += amt;
813 nbp->b_bufsize -= amt;
814
815 /* reduce transfer count if we stole some data */
816 if (nbp->b_bcount > nbp->b_bufsize)
817 nbp->b_bcount = nbp->b_bufsize;
818
819 #ifdef DIAGNOSTIC
820 if (nbp->b_bufsize < 0)
821 panic("allocbuf: negative bufsize");
822 #endif
823 brelse(nbp);
824 }
825
826 /*
827 * If we want a buffer smaller than the current size,
828 * shrink this buffer. Grab a buf head from the EMPTY queue,
829 * move a page onto it, and put it on front of the AGE queue.
830 * If there are no free buffer headers, leave the buffer alone.
831 */
832 if (bp->b_bufsize > desired_size) {
833 s = splbio();
834 simple_lock(&bqueue_slock);
835 if ((nbp = TAILQ_FIRST(&bufqueues[BQ_EMPTY])) == NULL) {
836 /* No free buffer head */
837 simple_unlock(&bqueue_slock);
838 splx(s);
839 goto out;
840 }
841 /* No need to lock nbp since it came from the empty queue */
842 bremfree(nbp);
843 SET(nbp->b_flags, B_BUSY | B_INVAL);
844 simple_unlock(&bqueue_slock);
845 splx(s);
846
847 /* move the page to it and note this change */
848 pagemove(bp->b_data + desired_size,
849 nbp->b_data, bp->b_bufsize - desired_size);
850 nbp->b_bufsize = bp->b_bufsize - desired_size;
851 bp->b_bufsize = desired_size;
852 nbp->b_bcount = 0;
853
854 /* release the newly-filled buffer and leave */
855 brelse(nbp);
856 }
857
858 out:
859 bp->b_bcount = size;
860 }
861
862 /*
863 * Find a buffer which is available for use.
864 * Select something from a free list.
865 * Preference is to AGE list, then LRU list.
866 *
867 * Called with buffer queues locked.
868 * Return buffer locked.
869 */
870 struct buf *
871 getnewbuf(slpflag, slptimeo)
872 int slpflag, slptimeo;
873 {
874 struct buf *bp;
875
876 start:
877 LOCK_ASSERT(simple_lock_held(&bqueue_slock));
878
879 if ((bp = TAILQ_FIRST(&bufqueues[BQ_AGE])) != NULL ||
880 (bp = TAILQ_FIRST(&bufqueues[BQ_LRU])) != NULL) {
881 simple_lock(&bp->b_interlock);
882 bremfree(bp);
883 } else {
884 /* wait for a free buffer of any kind */
885 needbuffer = 1;
886 ltsleep(&needbuffer, slpflag|(PRIBIO+1),
887 "getnewbuf", slptimeo, &bqueue_slock);
888 return (NULL);
889 }
890
891 if (ISSET(bp->b_flags, B_VFLUSH)) {
892 /*
893 * This is a delayed write buffer being flushed to disk. Make
894 * sure it gets aged out of the queue when it's finished, and
895 * leave it off the LRU queue.
896 */
897 CLR(bp->b_flags, B_VFLUSH);
898 SET(bp->b_flags, B_AGE);
899 simple_unlock(&bp->b_interlock);
900 goto start;
901 }
902
903 /* Buffer is no longer on free lists. */
904 SET(bp->b_flags, B_BUSY);
905
906 /*
907 * If buffer was a delayed write, start it and return NULL
908 * (since we might sleep while starting the write).
909 */
910 if (ISSET(bp->b_flags, B_DELWRI)) {
911 /*
912 * This buffer has gone through the LRU, so make sure it gets
913 * reused ASAP.
914 */
915 SET(bp->b_flags, B_AGE);
916 simple_unlock(&bp->b_interlock);
917 simple_unlock(&bqueue_slock);
918 bawrite(bp);
919 simple_lock(&bqueue_slock);
920 return (NULL);
921 }
922
923 /* disassociate us from our vnode, if we had one... */
924 if (bp->b_vp)
925 brelvp(bp);
926
927 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
928 (*bioops.io_deallocate)(bp);
929
930 /* clear out various other fields */
931 bp->b_flags = B_BUSY;
932 bp->b_dev = NODEV;
933 bp->b_blkno = bp->b_lblkno = bp->b_rawblkno = 0;
934 bp->b_iodone = 0;
935 bp->b_error = 0;
936 bp->b_resid = 0;
937 bp->b_bcount = 0;
938
939 bremhash(bp);
940 return (bp);
941 }
942
943 /*
944 * Wait for operations on the buffer to complete.
945 * When they do, extract and return the I/O's error value.
946 */
947 int
948 biowait(bp)
949 struct buf *bp;
950 {
951 int s, error;
952
953 s = splbio();
954 simple_lock(&bp->b_interlock);
955 while (!ISSET(bp->b_flags, B_DONE | B_DELWRI))
956 ltsleep(bp, PRIBIO + 1, "biowait", 0, &bp->b_interlock);
957
958 /* check for interruption of I/O (e.g. via NFS), then errors. */
959 if (ISSET(bp->b_flags, B_EINTR)) {
960 CLR(bp->b_flags, B_EINTR);
961 error = EINTR;
962 } else if (ISSET(bp->b_flags, B_ERROR))
963 error = bp->b_error ? bp->b_error : EIO;
964 else
965 error = 0;
966
967 simple_unlock(&bp->b_interlock);
968 splx(s);
969 return (error);
970 }
971
972 /*
973 * Mark I/O complete on a buffer.
974 *
975 * If a callback has been requested, e.g. the pageout
976 * daemon, do so. Otherwise, awaken waiting processes.
977 *
978 * [ Leffler, et al., says on p.247:
979 * "This routine wakes up the blocked process, frees the buffer
980 * for an asynchronous write, or, for a request by the pagedaemon
981 * process, invokes a procedure specified in the buffer structure" ]
982 *
983 * In real life, the pagedaemon (or other system processes) wants
984 * to do async stuff to, and doesn't want the buffer brelse()'d.
985 * (for swap pager, that puts swap buffers on the free lists (!!!),
986 * for the vn device, that puts malloc'd buffers on the free lists!)
987 */
988 void
989 biodone(bp)
990 struct buf *bp;
991 {
992 int s = splbio();
993
994 simple_lock(&bp->b_interlock);
995 if (ISSET(bp->b_flags, B_DONE))
996 panic("biodone already");
997 SET(bp->b_flags, B_DONE); /* note that it's done */
998
999 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
1000 (*bioops.io_complete)(bp);
1001
1002 if (!ISSET(bp->b_flags, B_READ)) /* wake up reader */
1003 vwakeup(bp);
1004
1005 /*
1006 * If necessary, call out. Unlock the buffer before calling
1007 * iodone() as the buffer isn't valid any more when it return.
1008 */
1009 if (ISSET(bp->b_flags, B_CALL)) {
1010 CLR(bp->b_flags, B_CALL); /* but note callout done */
1011 simple_unlock(&bp->b_interlock);
1012 (*bp->b_iodone)(bp);
1013 } else {
1014 if (ISSET(bp->b_flags, B_ASYNC)) { /* if async, release */
1015 simple_unlock(&bp->b_interlock);
1016 brelse(bp);
1017 } else { /* or just wakeup the buffer */
1018 CLR(bp->b_flags, B_WANTED);
1019 wakeup(bp);
1020 simple_unlock(&bp->b_interlock);
1021 }
1022 }
1023
1024 splx(s);
1025 }
1026
1027 /*
1028 * Return a count of buffers on the "locked" queue.
1029 */
1030 int
1031 count_lock_queue()
1032 {
1033 struct buf *bp;
1034 int n = 0;
1035
1036 simple_lock(&bqueue_slock);
1037 TAILQ_FOREACH(bp, &bufqueues[BQ_LOCKED], b_freelist)
1038 n++;
1039 simple_unlock(&bqueue_slock);
1040 return (n);
1041 }
1042
1043 #ifdef DEBUG
1044 /*
1045 * Print out statistics on the current allocation of the buffer pool.
1046 * Can be enabled to print out on every ``sync'' by setting "syncprt"
1047 * in vfs_syscalls.c using sysctl.
1048 */
1049 void
1050 vfs_bufstats()
1051 {
1052 int s, i, j, count;
1053 struct buf *bp;
1054 struct bqueues *dp;
1055 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
1056 static char *bname[BQUEUES] = { "LOCKED", "LRU", "AGE", "EMPTY" };
1057
1058 for (dp = bufqueues, i = 0; dp < &bufqueues[BQUEUES]; dp++, i++) {
1059 count = 0;
1060 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
1061 counts[j] = 0;
1062 s = splbio();
1063 TAILQ_FOREACH(bp, dp, b_freelist) {
1064 counts[bp->b_bufsize/PAGE_SIZE]++;
1065 count++;
1066 }
1067 splx(s);
1068 printf("%s: total-%d", bname[i], count);
1069 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
1070 if (counts[j] != 0)
1071 printf(", %d-%d", j * PAGE_SIZE, counts[j]);
1072 printf("\n");
1073 }
1074 }
1075 #endif /* DEBUG */
1076