Fix hopefully all possible deadlocks that can occur when mixed block sizes
[dragonfly.git] / sys / kern / vfs_bio.c
blob86906381673dfb7a47a4a36140f13cfb1d141e0e
1 /*
2 * Copyright (c) 1994,1997 John S. Dyson
3 * All rights reserved.
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.
14 * $FreeBSD: src/sys/kern/vfs_bio.c,v 1.242.2.20 2003/05/28 18:38:10 alc Exp $
15 * $DragonFly: src/sys/kern/vfs_bio.c,v 1.107 2008/06/28 23:45:18 dillon Exp $
19 * this file contains a new buffer I/O scheme implementing a coherent
20 * VM object and buffer cache scheme. Pains have been taken to make
21 * sure that the performance degradation associated with schemes such
22 * as this is not realized.
24 * Author: John S. Dyson
25 * Significant help during the development and debugging phases
26 * had been provided by David Greenman, also of the FreeBSD core team.
28 * see man buf(9) for more info.
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/buf.h>
34 #include <sys/conf.h>
35 #include <sys/eventhandler.h>
36 #include <sys/lock.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
41 #include <sys/proc.h>
42 #include <sys/reboot.h>
43 #include <sys/resourcevar.h>
44 #include <sys/sysctl.h>
45 #include <sys/vmmeter.h>
46 #include <sys/vnode.h>
47 #include <sys/proc.h>
48 #include <vm/vm.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_pageout.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_map.h>
57 #include <sys/buf2.h>
58 #include <sys/thread2.h>
59 #include <sys/spinlock2.h>
60 #include <vm/vm_page2.h>
62 #include "opt_ddb.h"
63 #ifdef DDB
64 #include <ddb/ddb.h>
65 #endif
68 * Buffer queues.
70 enum bufq_type {
71 BQUEUE_NONE, /* not on any queue */
72 BQUEUE_LOCKED, /* locked buffers */
73 BQUEUE_CLEAN, /* non-B_DELWRI buffers */
74 BQUEUE_DIRTY, /* B_DELWRI buffers */
75 BQUEUE_DIRTY_HW, /* B_DELWRI buffers - heavy weight */
76 BQUEUE_EMPTYKVA, /* empty buffer headers with KVA assignment */
77 BQUEUE_EMPTY, /* empty buffer headers */
79 BUFFER_QUEUES /* number of buffer queues */
82 typedef enum bufq_type bufq_type_t;
84 #define BD_WAKE_SIZE 128
85 #define BD_WAKE_MASK (BD_WAKE_SIZE - 1)
87 TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES];
89 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
91 struct buf *buf; /* buffer header pool */
93 static void vm_hold_free_pages(struct buf *bp, vm_offset_t from,
94 vm_offset_t to);
95 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
96 vm_offset_t to);
97 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
98 int pageno, vm_page_t m);
99 static void vfs_clean_pages(struct buf *bp);
100 static void vfs_setdirty(struct buf *bp);
101 static void vfs_vmio_release(struct buf *bp);
102 static int flushbufqueues(bufq_type_t q);
104 static void bd_signal(int totalspace);
105 static void buf_daemon(void);
106 static void buf_daemon_hw(void);
109 * bogus page -- for I/O to/from partially complete buffers
110 * this is a temporary solution to the problem, but it is not
111 * really that bad. it would be better to split the buffer
112 * for input in the case of buffers partially already in memory,
113 * but the code is intricate enough already.
115 vm_page_t bogus_page;
118 * These are all static, but make the ones we export globals so we do
119 * not need to use compiler magic.
121 int bufspace, maxbufspace,
122 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
123 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
124 static int lorunningspace, hirunningspace, runningbufreq;
125 int dirtybufspace, dirtybufspacehw, lodirtybufspace, hidirtybufspace;
126 int runningbufspace, runningbufcount;
127 static int getnewbufcalls;
128 static int getnewbufrestarts;
129 static int needsbuffer; /* locked by needsbuffer_spin */
130 static int bd_request; /* locked by needsbuffer_spin */
131 static int bd_request_hw; /* locked by needsbuffer_spin */
132 static u_int bd_wake_ary[BD_WAKE_SIZE];
133 static u_int bd_wake_index;
134 static struct spinlock needsbuffer_spin;
137 * Sysctls for operational control of the buffer cache.
139 SYSCTL_INT(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0,
140 "Number of dirty buffers to flush before bufdaemon becomes inactive");
141 SYSCTL_INT(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0,
142 "High watermark used to trigger explicit flushing of dirty buffers");
143 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
144 "Minimum amount of buffer space required for active I/O");
145 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
146 "Maximum amount of buffer space to usable for active I/O");
148 * Sysctls determining current state of the buffer cache.
150 SYSCTL_INT(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
151 "Total number of buffers in buffer cache");
152 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0,
153 "Pending number of dirty buffers (all)");
154 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0,
155 "Pending number of dirty buffers (heavy weight)");
156 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
157 "I/O bytes currently in progress due to asynchronous writes");
158 SYSCTL_INT(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
159 "I/O buffers currently in progress due to asynchronous writes");
160 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
161 "Hard limit on maximum amount of memory usable for buffer space");
162 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
163 "Soft limit on maximum amount of memory usable for buffer space");
164 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
165 "Minimum amount of memory to reserve for system buffer space");
166 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
167 "Amount of memory available for buffers");
168 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
169 0, "Maximum amount of memory reserved for buffers using malloc");
170 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
171 "Amount of memory left for buffers using malloc-scheme");
172 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
173 "New buffer header acquisition requests");
174 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
175 0, "New buffer header acquisition restarts");
176 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
177 "Buffer acquisition restarts due to fragmented buffer map");
178 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
179 "Amount of time KVA space was deallocated in an arbitrary buffer");
180 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
181 "Amount of time buffer re-use operations were successful");
182 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
183 "sizeof(struct buf)");
185 char *buf_wmesg = BUF_WMESG;
187 extern int vm_swap_size;
189 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
190 #define VFS_BIO_NEED_UNUSED02 0x02
191 #define VFS_BIO_NEED_UNUSED04 0x04
192 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
195 * bufspacewakeup:
197 * Called when buffer space is potentially available for recovery.
198 * getnewbuf() will block on this flag when it is unable to free
199 * sufficient buffer space. Buffer space becomes recoverable when
200 * bp's get placed back in the queues.
203 static __inline void
204 bufspacewakeup(void)
207 * If someone is waiting for BUF space, wake them up. Even
208 * though we haven't freed the kva space yet, the waiting
209 * process will be able to now.
211 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
212 spin_lock_wr(&needsbuffer_spin);
213 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
214 spin_unlock_wr(&needsbuffer_spin);
215 wakeup(&needsbuffer);
220 * runningbufwakeup:
222 * Accounting for I/O in progress.
225 static __inline void
226 runningbufwakeup(struct buf *bp)
228 int totalspace;
230 if ((totalspace = bp->b_runningbufspace) != 0) {
231 runningbufspace -= totalspace;
232 --runningbufcount;
233 bp->b_runningbufspace = 0;
234 if (runningbufreq && runningbufspace <= lorunningspace) {
235 runningbufreq = 0;
236 wakeup(&runningbufreq);
238 bd_signal(totalspace);
243 * bufcountwakeup:
245 * Called when a buffer has been added to one of the free queues to
246 * account for the buffer and to wakeup anyone waiting for free buffers.
247 * This typically occurs when large amounts of metadata are being handled
248 * by the buffer cache ( else buffer space runs out first, usually ).
251 static __inline void
252 bufcountwakeup(void)
254 if (needsbuffer) {
255 spin_lock_wr(&needsbuffer_spin);
256 needsbuffer &= ~VFS_BIO_NEED_ANY;
257 spin_unlock_wr(&needsbuffer_spin);
258 wakeup(&needsbuffer);
263 * waitrunningbufspace()
265 * runningbufspace is a measure of the amount of I/O currently
266 * running. This routine is used in async-write situations to
267 * prevent creating huge backups of pending writes to a device.
268 * Only asynchronous writes are governed by this function.
270 * Reads will adjust runningbufspace, but will not block based on it.
271 * The read load has a side effect of reducing the allowed write load.
273 * This does NOT turn an async write into a sync write. It waits
274 * for earlier writes to complete and generally returns before the
275 * caller's write has reached the device.
277 static __inline void
278 waitrunningbufspace(void)
280 if (runningbufspace > hirunningspace) {
281 crit_enter();
282 while (runningbufspace > hirunningspace) {
283 ++runningbufreq;
284 tsleep(&runningbufreq, 0, "wdrain", 0);
286 crit_exit();
291 * vfs_buf_test_cache:
293 * Called when a buffer is extended. This function clears the B_CACHE
294 * bit if the newly extended portion of the buffer does not contain
295 * valid data.
297 static __inline__
298 void
299 vfs_buf_test_cache(struct buf *bp,
300 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
301 vm_page_t m)
303 if (bp->b_flags & B_CACHE) {
304 int base = (foff + off) & PAGE_MASK;
305 if (vm_page_is_valid(m, base, size) == 0)
306 bp->b_flags &= ~B_CACHE;
311 * bd_speedup:
313 * Unconditionally speed-up the buf_daemon
315 static __inline__
316 void
317 bd_speedup(void)
319 if (bd_request == 0 && dirtybufspace) {
320 spin_lock_wr(&needsbuffer_spin);
321 bd_request = 1;
322 spin_unlock_wr(&needsbuffer_spin);
323 wakeup(&bd_request);
325 if (bd_request_hw == 0 && dirtybufspacehw) {
326 spin_lock_wr(&needsbuffer_spin);
327 bd_request_hw = 1;
328 spin_unlock_wr(&needsbuffer_spin);
329 wakeup(&bd_request_hw);
334 * bd_heatup()
336 * Get the buf_daemon heated up when the number of running and dirty
337 * buffers exceeds the mid-point.
340 bd_heatup(void)
342 int mid1;
343 int mid2;
344 int totalspace;
346 mid1 = lodirtybufspace + (hidirtybufspace - lodirtybufspace) / 2;
348 totalspace = runningbufspace + dirtybufspace;
349 if (totalspace >= mid1) {
350 bd_speedup();
351 mid2 = mid1 + (hidirtybufspace - mid1) / 2;
352 if (totalspace >= mid2)
353 return(totalspace - mid2);
355 return(0);
359 * bd_wait()
361 * Wait for the buffer cache to flush (totalspace) bytes worth of
362 * buffers, then return.
364 * Regardless this function blocks while the number of dirty buffers
365 * exceeds hidirtybufspace.
367 void
368 bd_wait(int totalspace)
370 u_int i;
371 int count;
373 while (totalspace > 0) {
374 bd_heatup();
375 crit_enter();
376 if (totalspace > runningbufspace + dirtybufspace)
377 totalspace = runningbufspace + dirtybufspace;
378 count = totalspace / BKVASIZE;
379 if (count >= BD_WAKE_SIZE)
380 count = BD_WAKE_SIZE - 1;
381 i = (bd_wake_index + count) & BD_WAKE_MASK;
382 ++bd_wake_ary[i];
383 tsleep(&bd_wake_ary[i], 0, "flstik", hz);
384 crit_exit();
386 totalspace = runningbufspace + dirtybufspace - hidirtybufspace;
391 * bd_signal()
393 * This function is called whenever runningbufspace or dirtybufspace
394 * is reduced. Track threads waiting for run+dirty buffer I/O
395 * complete.
397 static void
398 bd_signal(int totalspace)
400 u_int i;
402 while (totalspace > 0) {
403 i = atomic_fetchadd_int(&bd_wake_index, 1);
404 i &= BD_WAKE_MASK;
405 if (bd_wake_ary[i]) {
406 bd_wake_ary[i] = 0;
407 wakeup(&bd_wake_ary[i]);
409 totalspace -= BKVASIZE;
414 * bufinit:
416 * Load time initialisation of the buffer cache, called from machine
417 * dependant initialization code.
419 void
420 bufinit(void)
422 struct buf *bp;
423 vm_offset_t bogus_offset;
424 int i;
426 spin_init(&needsbuffer_spin);
428 /* next, make a null set of free lists */
429 for (i = 0; i < BUFFER_QUEUES; i++)
430 TAILQ_INIT(&bufqueues[i]);
432 /* finally, initialize each buffer header and stick on empty q */
433 for (i = 0; i < nbuf; i++) {
434 bp = &buf[i];
435 bzero(bp, sizeof *bp);
436 bp->b_flags = B_INVAL; /* we're just an empty header */
437 bp->b_cmd = BUF_CMD_DONE;
438 bp->b_qindex = BQUEUE_EMPTY;
439 initbufbio(bp);
440 xio_init(&bp->b_xio);
441 buf_dep_init(bp);
442 BUF_LOCKINIT(bp);
443 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
447 * maxbufspace is the absolute maximum amount of buffer space we are
448 * allowed to reserve in KVM and in real terms. The absolute maximum
449 * is nominally used by buf_daemon. hibufspace is the nominal maximum
450 * used by most other processes. The differential is required to
451 * ensure that buf_daemon is able to run when other processes might
452 * be blocked waiting for buffer space.
454 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
455 * this may result in KVM fragmentation which is not handled optimally
456 * by the system.
458 maxbufspace = nbuf * BKVASIZE;
459 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
460 lobufspace = hibufspace - MAXBSIZE;
462 lorunningspace = 512 * 1024;
463 hirunningspace = 1024 * 1024;
466 * Limit the amount of malloc memory since it is wired permanently
467 * into the kernel space. Even though this is accounted for in
468 * the buffer allocation, we don't want the malloced region to grow
469 * uncontrolled. The malloc scheme improves memory utilization
470 * significantly on average (small) directories.
472 maxbufmallocspace = hibufspace / 20;
475 * Reduce the chance of a deadlock occuring by limiting the number
476 * of delayed-write dirty buffers we allow to stack up.
478 hidirtybufspace = hibufspace / 2;
479 dirtybufspace = 0;
480 dirtybufspacehw = 0;
482 lodirtybufspace = hidirtybufspace / 2;
485 * Maximum number of async ops initiated per buf_daemon loop. This is
486 * somewhat of a hack at the moment, we really need to limit ourselves
487 * based on the number of bytes of I/O in-transit that were initiated
488 * from buf_daemon.
491 bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
492 bogus_page = vm_page_alloc(&kernel_object,
493 (bogus_offset >> PAGE_SHIFT),
494 VM_ALLOC_NORMAL);
495 vmstats.v_wire_count++;
500 * Initialize the embedded bio structures
502 void
503 initbufbio(struct buf *bp)
505 bp->b_bio1.bio_buf = bp;
506 bp->b_bio1.bio_prev = NULL;
507 bp->b_bio1.bio_offset = NOOFFSET;
508 bp->b_bio1.bio_next = &bp->b_bio2;
509 bp->b_bio1.bio_done = NULL;
511 bp->b_bio2.bio_buf = bp;
512 bp->b_bio2.bio_prev = &bp->b_bio1;
513 bp->b_bio2.bio_offset = NOOFFSET;
514 bp->b_bio2.bio_next = NULL;
515 bp->b_bio2.bio_done = NULL;
519 * Reinitialize the embedded bio structures as well as any additional
520 * translation cache layers.
522 void
523 reinitbufbio(struct buf *bp)
525 struct bio *bio;
527 for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
528 bio->bio_done = NULL;
529 bio->bio_offset = NOOFFSET;
534 * Push another BIO layer onto an existing BIO and return it. The new
535 * BIO layer may already exist, holding cached translation data.
537 struct bio *
538 push_bio(struct bio *bio)
540 struct bio *nbio;
542 if ((nbio = bio->bio_next) == NULL) {
543 int index = bio - &bio->bio_buf->b_bio_array[0];
544 if (index >= NBUF_BIO - 1) {
545 panic("push_bio: too many layers bp %p\n",
546 bio->bio_buf);
548 nbio = &bio->bio_buf->b_bio_array[index + 1];
549 bio->bio_next = nbio;
550 nbio->bio_prev = bio;
551 nbio->bio_buf = bio->bio_buf;
552 nbio->bio_offset = NOOFFSET;
553 nbio->bio_done = NULL;
554 nbio->bio_next = NULL;
556 KKASSERT(nbio->bio_done == NULL);
557 return(nbio);
560 void
561 pop_bio(struct bio *bio)
563 /* NOP */
566 void
567 clearbiocache(struct bio *bio)
569 while (bio) {
570 bio->bio_offset = NOOFFSET;
571 bio = bio->bio_next;
576 * bfreekva:
578 * Free the KVA allocation for buffer 'bp'.
580 * Must be called from a critical section as this is the only locking for
581 * buffer_map.
583 * Since this call frees up buffer space, we call bufspacewakeup().
585 static void
586 bfreekva(struct buf *bp)
588 int count;
590 if (bp->b_kvasize) {
591 ++buffreekvacnt;
592 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
593 vm_map_lock(&buffer_map);
594 bufspace -= bp->b_kvasize;
595 vm_map_delete(&buffer_map,
596 (vm_offset_t) bp->b_kvabase,
597 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
598 &count
600 vm_map_unlock(&buffer_map);
601 vm_map_entry_release(count);
602 bp->b_kvasize = 0;
603 bufspacewakeup();
608 * bremfree:
610 * Remove the buffer from the appropriate free list.
612 void
613 bremfree(struct buf *bp)
615 int old_qindex;
617 crit_enter();
618 old_qindex = bp->b_qindex;
620 if (bp->b_qindex != BQUEUE_NONE) {
621 KASSERT(BUF_REFCNTNB(bp) == 1,
622 ("bremfree: bp %p not locked",bp));
623 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
624 bp->b_qindex = BQUEUE_NONE;
625 } else {
626 if (BUF_REFCNTNB(bp) <= 1)
627 panic("bremfree: removing a buffer not on a queue");
630 crit_exit();
635 * bread:
637 * Get a buffer with the specified data. Look in the cache first. We
638 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
639 * is set, the buffer is valid and we do not have to do anything ( see
640 * getblk() ).
643 bread(struct vnode *vp, off_t loffset, int size, struct buf **bpp)
645 struct buf *bp;
647 bp = getblk(vp, loffset, size, 0, 0);
648 *bpp = bp;
650 /* if not found in cache, do some I/O */
651 if ((bp->b_flags & B_CACHE) == 0) {
652 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
653 bp->b_flags &= ~(B_ERROR | B_INVAL);
654 bp->b_cmd = BUF_CMD_READ;
655 vfs_busy_pages(vp, bp);
656 vn_strategy(vp, &bp->b_bio1);
657 return (biowait(bp));
659 return (0);
663 * breadn:
665 * Operates like bread, but also starts asynchronous I/O on
666 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
667 * to initiating I/O . If B_CACHE is set, the buffer is valid
668 * and we do not have to do anything.
671 breadn(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
672 int *rabsize, int cnt, struct buf **bpp)
674 struct buf *bp, *rabp;
675 int i;
676 int rv = 0, readwait = 0;
678 *bpp = bp = getblk(vp, loffset, size, 0, 0);
680 /* if not found in cache, do some I/O */
681 if ((bp->b_flags & B_CACHE) == 0) {
682 bp->b_flags &= ~(B_ERROR | B_INVAL);
683 bp->b_cmd = BUF_CMD_READ;
684 vfs_busy_pages(vp, bp);
685 vn_strategy(vp, &bp->b_bio1);
686 ++readwait;
689 for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
690 if (inmem(vp, *raoffset))
691 continue;
692 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
694 if ((rabp->b_flags & B_CACHE) == 0) {
695 rabp->b_flags |= B_ASYNC;
696 rabp->b_flags &= ~(B_ERROR | B_INVAL);
697 rabp->b_cmd = BUF_CMD_READ;
698 vfs_busy_pages(vp, rabp);
699 BUF_KERNPROC(rabp);
700 vn_strategy(vp, &rabp->b_bio1);
701 } else {
702 brelse(rabp);
706 if (readwait) {
707 rv = biowait(bp);
709 return (rv);
713 * bwrite:
715 * Write, release buffer on completion. (Done by iodone
716 * if async). Do not bother writing anything if the buffer
717 * is invalid.
719 * Note that we set B_CACHE here, indicating that buffer is
720 * fully valid and thus cacheable. This is true even of NFS
721 * now so we set it generally. This could be set either here
722 * or in biodone() since the I/O is synchronous. We put it
723 * here.
726 bwrite(struct buf *bp)
728 int oldflags;
730 if (bp->b_flags & B_INVAL) {
731 brelse(bp);
732 return (0);
735 oldflags = bp->b_flags;
737 if (BUF_REFCNTNB(bp) == 0)
738 panic("bwrite: buffer is not busy???");
739 crit_enter();
741 /* Mark the buffer clean */
742 bundirty(bp);
744 bp->b_flags &= ~B_ERROR;
745 bp->b_flags |= B_CACHE;
746 bp->b_cmd = BUF_CMD_WRITE;
747 vfs_busy_pages(bp->b_vp, bp);
750 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
751 * valid for vnode-backed buffers.
753 bp->b_runningbufspace = bp->b_bufsize;
754 if (bp->b_runningbufspace) {
755 runningbufspace += bp->b_runningbufspace;
756 ++runningbufcount;
759 crit_exit();
760 if (oldflags & B_ASYNC)
761 BUF_KERNPROC(bp);
762 vn_strategy(bp->b_vp, &bp->b_bio1);
764 if ((oldflags & B_ASYNC) == 0) {
765 int rtval = biowait(bp);
766 brelse(bp);
767 return (rtval);
769 return (0);
773 * bdwrite:
775 * Delayed write. (Buffer is marked dirty). Do not bother writing
776 * anything if the buffer is marked invalid.
778 * Note that since the buffer must be completely valid, we can safely
779 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
780 * biodone() in order to prevent getblk from writing the buffer
781 * out synchronously.
783 void
784 bdwrite(struct buf *bp)
786 if (BUF_REFCNTNB(bp) == 0)
787 panic("bdwrite: buffer is not busy");
789 if (bp->b_flags & B_INVAL) {
790 brelse(bp);
791 return;
793 bdirty(bp);
796 * Set B_CACHE, indicating that the buffer is fully valid. This is
797 * true even of NFS now.
799 bp->b_flags |= B_CACHE;
802 * This bmap keeps the system from needing to do the bmap later,
803 * perhaps when the system is attempting to do a sync. Since it
804 * is likely that the indirect block -- or whatever other datastructure
805 * that the filesystem needs is still in memory now, it is a good
806 * thing to do this. Note also, that if the pageout daemon is
807 * requesting a sync -- there might not be enough memory to do
808 * the bmap then... So, this is important to do.
810 if (bp->b_bio2.bio_offset == NOOFFSET) {
811 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
812 NULL, NULL, BUF_CMD_WRITE);
816 * Set the *dirty* buffer range based upon the VM system dirty pages.
818 vfs_setdirty(bp);
821 * We need to do this here to satisfy the vnode_pager and the
822 * pageout daemon, so that it thinks that the pages have been
823 * "cleaned". Note that since the pages are in a delayed write
824 * buffer -- the VFS layer "will" see that the pages get written
825 * out on the next sync, or perhaps the cluster will be completed.
827 vfs_clean_pages(bp);
828 bqrelse(bp);
831 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
832 * due to the softdep code.
837 * bdirty:
839 * Turn buffer into delayed write request by marking it B_DELWRI.
840 * B_RELBUF and B_NOCACHE must be cleared.
842 * We reassign the buffer to itself to properly update it in the
843 * dirty/clean lists.
845 * Must be called from a critical section.
846 * The buffer must be on BQUEUE_NONE.
848 void
849 bdirty(struct buf *bp)
851 KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
852 if (bp->b_flags & B_NOCACHE) {
853 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
854 bp->b_flags &= ~B_NOCACHE;
856 if (bp->b_flags & B_INVAL) {
857 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
859 bp->b_flags &= ~B_RELBUF;
861 if ((bp->b_flags & B_DELWRI) == 0) {
862 bp->b_flags |= B_DELWRI;
863 reassignbuf(bp);
864 dirtybufspace += bp->b_bufsize;
865 if (bp->b_flags & B_HEAVY)
866 dirtybufspacehw += bp->b_bufsize;
867 bd_heatup();
872 * Set B_HEAVY, indicating that this is a heavy-weight buffer that
873 * needs to be flushed with a different buf_daemon thread to avoid
874 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf().
876 void
877 bheavy(struct buf *bp)
879 if ((bp->b_flags & B_HEAVY) == 0) {
880 bp->b_flags |= B_HEAVY;
881 if (bp->b_flags & B_DELWRI)
882 dirtybufspacehw += bp->b_bufsize;
887 * bundirty:
889 * Clear B_DELWRI for buffer.
891 * Must be called from a critical section.
893 * The buffer is typically on BQUEUE_NONE but there is one case in
894 * brelse() that calls this function after placing the buffer on
895 * a different queue.
898 void
899 bundirty(struct buf *bp)
901 if (bp->b_flags & B_DELWRI) {
902 bp->b_flags &= ~B_DELWRI;
903 reassignbuf(bp);
904 dirtybufspace -= bp->b_bufsize;
905 if (bp->b_flags & B_HEAVY)
906 dirtybufspacehw -= bp->b_bufsize;
907 bd_signal(bp->b_bufsize);
910 * Since it is now being written, we can clear its deferred write flag.
912 bp->b_flags &= ~B_DEFERRED;
916 * bawrite:
918 * Asynchronous write. Start output on a buffer, but do not wait for
919 * it to complete. The buffer is released when the output completes.
921 * bwrite() ( or the VOP routine anyway ) is responsible for handling
922 * B_INVAL buffers. Not us.
924 void
925 bawrite(struct buf *bp)
927 bp->b_flags |= B_ASYNC;
928 bwrite(bp);
932 * bowrite:
934 * Ordered write. Start output on a buffer, and flag it so that the
935 * device will write it in the order it was queued. The buffer is
936 * released when the output completes. bwrite() ( or the VOP routine
937 * anyway ) is responsible for handling B_INVAL buffers.
940 bowrite(struct buf *bp)
942 bp->b_flags |= B_ORDERED | B_ASYNC;
943 return (bwrite(bp));
947 * buf_dirty_count_severe:
949 * Return true if we have too many dirty buffers.
952 buf_dirty_count_severe(void)
954 return(runningbufspace + dirtybufspace >= hidirtybufspace);
958 * brelse:
960 * Release a busy buffer and, if requested, free its resources. The
961 * buffer will be stashed in the appropriate bufqueue[] allowing it
962 * to be accessed later as a cache entity or reused for other purposes.
964 void
965 brelse(struct buf *bp)
967 #ifdef INVARIANTS
968 int saved_flags = bp->b_flags;
969 #endif
971 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
973 crit_enter();
976 * If B_NOCACHE is set we are being asked to destroy the buffer and
977 * its backing store. Clear B_DELWRI.
979 * B_NOCACHE is set in two cases: (1) when the caller really wants
980 * to destroy the buffer and backing store and (2) when the caller
981 * wants to destroy the buffer and backing store after a write
982 * completes.
984 if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
985 bundirty(bp);
988 if (bp->b_flags & B_LOCKED)
989 bp->b_flags &= ~B_ERROR;
992 * If a write error occurs and the caller does not want to throw
993 * away the buffer, redirty the buffer. This will also clear
994 * B_NOCACHE.
996 if (bp->b_cmd == BUF_CMD_WRITE &&
997 (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
999 * Failed write, redirty. Must clear B_ERROR to prevent
1000 * pages from being scrapped. If B_INVAL is set then
1001 * this case is not run and the next case is run to
1002 * destroy the buffer. B_INVAL can occur if the buffer
1003 * is outside the range supported by the underlying device.
1005 bp->b_flags &= ~B_ERROR;
1006 bdirty(bp);
1007 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1008 (bp->b_bufsize <= 0) || bp->b_cmd == BUF_CMD_FREEBLKS) {
1010 * Either a failed I/O or we were asked to free or not
1011 * cache the buffer.
1013 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1014 * buffer cannot be immediately freed.
1016 bp->b_flags |= B_INVAL;
1017 if (LIST_FIRST(&bp->b_dep) != NULL)
1018 buf_deallocate(bp);
1019 if (bp->b_flags & B_DELWRI) {
1020 dirtybufspace -= bp->b_bufsize;
1021 if (bp->b_flags & B_HEAVY)
1022 dirtybufspacehw -= bp->b_bufsize;
1023 bd_signal(bp->b_bufsize);
1025 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1029 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set.
1030 * If vfs_vmio_release() is called with either bit set, the
1031 * underlying pages may wind up getting freed causing a previous
1032 * write (bdwrite()) to get 'lost' because pages associated with
1033 * a B_DELWRI bp are marked clean. Pages associated with a
1034 * B_LOCKED buffer may be mapped by the filesystem.
1036 * If we want to release the buffer ourselves (rather then the
1037 * originator asking us to release it), give the originator a
1038 * chance to countermand the release by setting B_LOCKED.
1040 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1041 * if B_DELWRI is set.
1043 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1044 * on pages to return pages to the VM page queues.
1046 if (bp->b_flags & (B_DELWRI | B_LOCKED)) {
1047 bp->b_flags &= ~B_RELBUF;
1048 } else if (vm_page_count_severe()) {
1049 if (LIST_FIRST(&bp->b_dep) != NULL)
1050 buf_deallocate(bp);
1051 if (bp->b_flags & (B_DELWRI | B_LOCKED))
1052 bp->b_flags &= ~B_RELBUF;
1053 else
1054 bp->b_flags |= B_RELBUF;
1058 * At this point destroying the buffer is governed by the B_INVAL
1059 * or B_RELBUF flags.
1061 bp->b_cmd = BUF_CMD_DONE;
1064 * VMIO buffer rundown. Make sure the VM page array is restored
1065 * after an I/O may have replaces some of the pages with bogus pages
1066 * in order to not destroy dirty pages in a fill-in read.
1068 * Note that due to the code above, if a buffer is marked B_DELWRI
1069 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1070 * B_INVAL may still be set, however.
1072 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1073 * but not the backing store. B_NOCACHE will destroy the backing
1074 * store.
1076 * Note that dirty NFS buffers contain byte-granular write ranges
1077 * and should not be destroyed w/ B_INVAL even if the backing store
1078 * is left intact.
1080 if (bp->b_flags & B_VMIO) {
1082 * Rundown for VMIO buffers which are not dirty NFS buffers.
1084 int i, j, resid;
1085 vm_page_t m;
1086 off_t foff;
1087 vm_pindex_t poff;
1088 vm_object_t obj;
1089 struct vnode *vp;
1091 vp = bp->b_vp;
1094 * Get the base offset and length of the buffer. Note that
1095 * in the VMIO case if the buffer block size is not
1096 * page-aligned then b_data pointer may not be page-aligned.
1097 * But our b_xio.xio_pages array *IS* page aligned.
1099 * block sizes less then DEV_BSIZE (usually 512) are not
1100 * supported due to the page granularity bits (m->valid,
1101 * m->dirty, etc...).
1103 * See man buf(9) for more information
1106 resid = bp->b_bufsize;
1107 foff = bp->b_loffset;
1109 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1110 m = bp->b_xio.xio_pages[i];
1111 vm_page_flag_clear(m, PG_ZERO);
1113 * If we hit a bogus page, fixup *all* of them
1114 * now. Note that we left these pages wired
1115 * when we removed them so they had better exist,
1116 * and they cannot be ripped out from under us so
1117 * no critical section protection is necessary.
1119 if (m == bogus_page) {
1120 obj = vp->v_object;
1121 poff = OFF_TO_IDX(bp->b_loffset);
1123 for (j = i; j < bp->b_xio.xio_npages; j++) {
1124 vm_page_t mtmp;
1126 mtmp = bp->b_xio.xio_pages[j];
1127 if (mtmp == bogus_page) {
1128 mtmp = vm_page_lookup(obj, poff + j);
1129 if (!mtmp) {
1130 panic("brelse: page missing");
1132 bp->b_xio.xio_pages[j] = mtmp;
1136 if ((bp->b_flags & B_INVAL) == 0) {
1137 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1138 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1140 m = bp->b_xio.xio_pages[i];
1144 * Invalidate the backing store if B_NOCACHE is set
1145 * (e.g. used with vinvalbuf()). If this is NFS
1146 * we impose a requirement that the block size be
1147 * a multiple of PAGE_SIZE and create a temporary
1148 * hack to basically invalidate the whole page. The
1149 * problem is that NFS uses really odd buffer sizes
1150 * especially when tracking piecemeal writes and
1151 * it also vinvalbuf()'s a lot, which would result
1152 * in only partial page validation and invalidation
1153 * here. If the file page is mmap()'d, however,
1154 * all the valid bits get set so after we invalidate
1155 * here we would end up with weird m->valid values
1156 * like 0xfc. nfs_getpages() can't handle this so
1157 * we clear all the valid bits for the NFS case
1158 * instead of just some of them.
1160 * The real bug is the VM system having to set m->valid
1161 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1162 * itself is an artifact of the whole 512-byte
1163 * granular mess that exists to support odd block
1164 * sizes and UFS meta-data block sizes (e.g. 6144).
1165 * A complete rewrite is required.
1167 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1168 int poffset = foff & PAGE_MASK;
1169 int presid;
1171 presid = PAGE_SIZE - poffset;
1172 if (bp->b_vp->v_tag == VT_NFS &&
1173 bp->b_vp->v_type == VREG) {
1174 ; /* entire page */
1175 } else if (presid > resid) {
1176 presid = resid;
1178 KASSERT(presid >= 0, ("brelse: extra page"));
1179 vm_page_set_invalid(m, poffset, presid);
1181 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1182 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1184 if (bp->b_flags & (B_INVAL | B_RELBUF))
1185 vfs_vmio_release(bp);
1186 } else {
1188 * Rundown for non-VMIO buffers.
1190 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1191 #if 0
1192 if (bp->b_vp)
1193 kprintf("brelse bp %p %08x/%08x: Warning, caught and fixed brelvp bug\n", bp, saved_flags, bp->b_flags);
1194 #endif
1195 if (bp->b_bufsize)
1196 allocbuf(bp, 0);
1197 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1198 if (bp->b_vp)
1199 brelvp(bp);
1203 if (bp->b_qindex != BQUEUE_NONE)
1204 panic("brelse: free buffer onto another queue???");
1205 if (BUF_REFCNTNB(bp) > 1) {
1206 /* Temporary panic to verify exclusive locking */
1207 /* This panic goes away when we allow shared refs */
1208 panic("brelse: multiple refs");
1209 /* do not release to free list */
1210 BUF_UNLOCK(bp);
1211 crit_exit();
1212 return;
1216 * Figure out the correct queue to place the cleaned up buffer on.
1217 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1218 * disassociated from their vnode.
1220 if (bp->b_flags & B_LOCKED) {
1222 * Buffers that are locked are placed in the locked queue
1223 * immediately, regardless of their state.
1225 bp->b_qindex = BQUEUE_LOCKED;
1226 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1227 } else if (bp->b_bufsize == 0) {
1229 * Buffers with no memory. Due to conditionals near the top
1230 * of brelse() such buffers should probably already be
1231 * marked B_INVAL and disassociated from their vnode.
1233 bp->b_flags |= B_INVAL;
1234 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1235 KKASSERT((bp->b_flags & B_HASHED) == 0);
1236 if (bp->b_kvasize) {
1237 bp->b_qindex = BQUEUE_EMPTYKVA;
1238 } else {
1239 bp->b_qindex = BQUEUE_EMPTY;
1241 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1242 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1244 * Buffers with junk contents. Again these buffers had better
1245 * already be disassociated from their vnode.
1247 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1248 KKASSERT((bp->b_flags & B_HASHED) == 0);
1249 bp->b_flags |= B_INVAL;
1250 bp->b_qindex = BQUEUE_CLEAN;
1251 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1252 } else {
1254 * Remaining buffers. These buffers are still associated with
1255 * their vnode.
1257 switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
1258 case B_DELWRI:
1259 bp->b_qindex = BQUEUE_DIRTY;
1260 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1261 break;
1262 case B_DELWRI | B_HEAVY:
1263 bp->b_qindex = BQUEUE_DIRTY_HW;
1264 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY_HW], bp,
1265 b_freelist);
1266 break;
1267 default:
1269 * NOTE: Buffers are always placed at the end of the
1270 * queue. If B_AGE is not set the buffer will cycle
1271 * through the queue twice.
1273 bp->b_qindex = BQUEUE_CLEAN;
1274 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1275 break;
1280 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1281 * on the correct queue.
1283 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1284 bundirty(bp);
1287 * The bp is on an appropriate queue unless locked. If it is not
1288 * locked or dirty we can wakeup threads waiting for buffer space.
1290 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1291 * if B_INVAL is set ).
1293 if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1294 bufcountwakeup();
1297 * Something we can maybe free or reuse
1299 if (bp->b_bufsize || bp->b_kvasize)
1300 bufspacewakeup();
1303 * Clean up temporary flags and unlock the buffer.
1305 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_RELBUF | B_DIRECT);
1306 BUF_UNLOCK(bp);
1307 crit_exit();
1311 * bqrelse:
1313 * Release a buffer back to the appropriate queue but do not try to free
1314 * it. The buffer is expected to be used again soon.
1316 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1317 * biodone() to requeue an async I/O on completion. It is also used when
1318 * known good buffers need to be requeued but we think we may need the data
1319 * again soon.
1321 * XXX we should be able to leave the B_RELBUF hint set on completion.
1323 void
1324 bqrelse(struct buf *bp)
1326 crit_enter();
1328 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1330 if (bp->b_qindex != BQUEUE_NONE)
1331 panic("bqrelse: free buffer onto another queue???");
1332 if (BUF_REFCNTNB(bp) > 1) {
1333 /* do not release to free list */
1334 panic("bqrelse: multiple refs");
1335 BUF_UNLOCK(bp);
1336 crit_exit();
1337 return;
1339 if (bp->b_flags & B_LOCKED) {
1341 * Locked buffers are released to the locked queue. However,
1342 * if the buffer is dirty it will first go into the dirty
1343 * queue and later on after the I/O completes successfully it
1344 * will be released to the locked queue.
1346 bp->b_flags &= ~B_ERROR;
1347 bp->b_qindex = BQUEUE_LOCKED;
1348 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1349 } else if (bp->b_flags & B_DELWRI) {
1350 bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1351 BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1352 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1353 } else if (vm_page_count_severe()) {
1355 * We are too low on memory, we have to try to free the
1356 * buffer (most importantly: the wired pages making up its
1357 * backing store) *now*.
1359 crit_exit();
1360 brelse(bp);
1361 return;
1362 } else {
1363 bp->b_qindex = BQUEUE_CLEAN;
1364 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1367 if ((bp->b_flags & B_LOCKED) == 0 &&
1368 ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1369 bufcountwakeup();
1373 * Something we can maybe free or reuse.
1375 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1376 bufspacewakeup();
1379 * Final cleanup and unlock. Clear bits that are only used while a
1380 * buffer is actively locked.
1382 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_RELBUF);
1383 BUF_UNLOCK(bp);
1384 crit_exit();
1388 * vfs_vmio_release:
1390 * Return backing pages held by the buffer 'bp' back to the VM system
1391 * if possible. The pages are freed if they are no longer valid or
1392 * attempt to free if it was used for direct I/O otherwise they are
1393 * sent to the page cache.
1395 * Pages that were marked busy are left alone and skipped.
1397 * The KVA mapping (b_data) for the underlying pages is removed by
1398 * this function.
1400 static void
1401 vfs_vmio_release(struct buf *bp)
1403 int i;
1404 vm_page_t m;
1406 crit_enter();
1407 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1408 m = bp->b_xio.xio_pages[i];
1409 bp->b_xio.xio_pages[i] = NULL;
1411 * In order to keep page LRU ordering consistent, put
1412 * everything on the inactive queue.
1414 vm_page_unwire(m, 0);
1416 * We don't mess with busy pages, it is
1417 * the responsibility of the process that
1418 * busied the pages to deal with them.
1420 if ((m->flags & PG_BUSY) || (m->busy != 0))
1421 continue;
1423 if (m->wire_count == 0) {
1424 vm_page_flag_clear(m, PG_ZERO);
1426 * Might as well free the page if we can and it has
1427 * no valid data. We also free the page if the
1428 * buffer was used for direct I/O.
1430 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1431 m->hold_count == 0) {
1432 vm_page_busy(m);
1433 vm_page_protect(m, VM_PROT_NONE);
1434 vm_page_free(m);
1435 } else if (bp->b_flags & B_DIRECT) {
1436 vm_page_try_to_free(m);
1437 } else if (vm_page_count_severe()) {
1438 vm_page_try_to_cache(m);
1442 crit_exit();
1443 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1444 if (bp->b_bufsize) {
1445 bufspacewakeup();
1446 bp->b_bufsize = 0;
1448 bp->b_xio.xio_npages = 0;
1449 bp->b_flags &= ~B_VMIO;
1450 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1451 if (bp->b_vp)
1452 brelvp(bp);
1456 * vfs_bio_awrite:
1458 * Implement clustered async writes for clearing out B_DELWRI buffers.
1459 * This is much better then the old way of writing only one buffer at
1460 * a time. Note that we may not be presented with the buffers in the
1461 * correct order, so we search for the cluster in both directions.
1463 * The buffer is locked on call.
1466 vfs_bio_awrite(struct buf *bp)
1468 int i;
1469 int j;
1470 off_t loffset = bp->b_loffset;
1471 struct vnode *vp = bp->b_vp;
1472 int nbytes;
1473 struct buf *bpa;
1474 int nwritten;
1475 int size;
1477 crit_enter();
1479 * right now we support clustered writing only to regular files. If
1480 * we find a clusterable block we could be in the middle of a cluster
1481 * rather then at the beginning.
1483 * NOTE: b_bio1 contains the logical loffset and is aliased
1484 * to b_loffset. b_bio2 contains the translated block number.
1486 if ((vp->v_type == VREG) &&
1487 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1488 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1490 size = vp->v_mount->mnt_stat.f_iosize;
1492 for (i = size; i < MAXPHYS; i += size) {
1493 if ((bpa = findblk(vp, loffset + i)) &&
1494 BUF_REFCNT(bpa) == 0 &&
1495 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1496 (B_DELWRI | B_CLUSTEROK)) &&
1497 (bpa->b_bufsize == size)) {
1498 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1499 (bpa->b_bio2.bio_offset !=
1500 bp->b_bio2.bio_offset + i))
1501 break;
1502 } else {
1503 break;
1506 for (j = size; i + j <= MAXPHYS && j <= loffset; j += size) {
1507 if ((bpa = findblk(vp, loffset - j)) &&
1508 BUF_REFCNT(bpa) == 0 &&
1509 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1510 (B_DELWRI | B_CLUSTEROK)) &&
1511 (bpa->b_bufsize == size)) {
1512 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1513 (bpa->b_bio2.bio_offset !=
1514 bp->b_bio2.bio_offset - j))
1515 break;
1516 } else {
1517 break;
1520 j -= size;
1521 nbytes = (i + j);
1523 * this is a possible cluster write
1525 if (nbytes != size) {
1526 BUF_UNLOCK(bp);
1527 nwritten = cluster_wbuild(vp, size,
1528 loffset - j, nbytes);
1529 crit_exit();
1530 return nwritten;
1534 bremfree(bp);
1535 bp->b_flags |= B_ASYNC;
1537 crit_exit();
1539 * default (old) behavior, writing out only one block
1541 * XXX returns b_bufsize instead of b_bcount for nwritten?
1543 nwritten = bp->b_bufsize;
1544 bwrite(bp);
1546 return nwritten;
1550 * getnewbuf:
1552 * Find and initialize a new buffer header, freeing up existing buffers
1553 * in the bufqueues as necessary. The new buffer is returned locked.
1555 * Important: B_INVAL is not set. If the caller wishes to throw the
1556 * buffer away, the caller must set B_INVAL prior to calling brelse().
1558 * We block if:
1559 * We have insufficient buffer headers
1560 * We have insufficient buffer space
1561 * buffer_map is too fragmented ( space reservation fails )
1562 * If we have to flush dirty buffers ( but we try to avoid this )
1564 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1565 * Instead we ask the buf daemon to do it for us. We attempt to
1566 * avoid piecemeal wakeups of the pageout daemon.
1569 static struct buf *
1570 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1572 struct buf *bp;
1573 struct buf *nbp;
1574 int defrag = 0;
1575 int nqindex;
1576 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1577 static int flushingbufs;
1580 * We can't afford to block since we might be holding a vnode lock,
1581 * which may prevent system daemons from running. We deal with
1582 * low-memory situations by proactively returning memory and running
1583 * async I/O rather then sync I/O.
1586 ++getnewbufcalls;
1587 --getnewbufrestarts;
1588 restart:
1589 ++getnewbufrestarts;
1592 * Setup for scan. If we do not have enough free buffers,
1593 * we setup a degenerate case that immediately fails. Note
1594 * that if we are specially marked process, we are allowed to
1595 * dip into our reserves.
1597 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1599 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1600 * However, there are a number of cases (defragging, reusing, ...)
1601 * where we cannot backup.
1603 nqindex = BQUEUE_EMPTYKVA;
1604 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1606 if (nbp == NULL) {
1608 * If no EMPTYKVA buffers and we are either
1609 * defragging or reusing, locate a CLEAN buffer
1610 * to free or reuse. If bufspace useage is low
1611 * skip this step so we can allocate a new buffer.
1613 if (defrag || bufspace >= lobufspace) {
1614 nqindex = BQUEUE_CLEAN;
1615 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1619 * If we could not find or were not allowed to reuse a
1620 * CLEAN buffer, check to see if it is ok to use an EMPTY
1621 * buffer. We can only use an EMPTY buffer if allocating
1622 * its KVA would not otherwise run us out of buffer space.
1624 if (nbp == NULL && defrag == 0 &&
1625 bufspace + maxsize < hibufspace) {
1626 nqindex = BQUEUE_EMPTY;
1627 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1632 * Run scan, possibly freeing data and/or kva mappings on the fly
1633 * depending.
1636 while ((bp = nbp) != NULL) {
1637 int qindex = nqindex;
1639 nbp = TAILQ_NEXT(bp, b_freelist);
1642 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
1643 * cycles through the queue twice before being selected.
1645 if (qindex == BQUEUE_CLEAN &&
1646 (bp->b_flags & B_AGE) == 0 && nbp) {
1647 bp->b_flags |= B_AGE;
1648 TAILQ_REMOVE(&bufqueues[qindex], bp, b_freelist);
1649 TAILQ_INSERT_TAIL(&bufqueues[qindex], bp, b_freelist);
1650 continue;
1654 * Calculate next bp ( we can only use it if we do not block
1655 * or do other fancy things ).
1657 if (nbp == NULL) {
1658 switch(qindex) {
1659 case BQUEUE_EMPTY:
1660 nqindex = BQUEUE_EMPTYKVA;
1661 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1662 break;
1663 /* fall through */
1664 case BQUEUE_EMPTYKVA:
1665 nqindex = BQUEUE_CLEAN;
1666 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1667 break;
1668 /* fall through */
1669 case BQUEUE_CLEAN:
1671 * nbp is NULL.
1673 break;
1678 * Sanity Checks
1680 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1683 * Note: we no longer distinguish between VMIO and non-VMIO
1684 * buffers.
1687 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1690 * If we are defragging then we need a buffer with
1691 * b_kvasize != 0. XXX this situation should no longer
1692 * occur, if defrag is non-zero the buffer's b_kvasize
1693 * should also be non-zero at this point. XXX
1695 if (defrag && bp->b_kvasize == 0) {
1696 kprintf("Warning: defrag empty buffer %p\n", bp);
1697 continue;
1701 * Start freeing the bp. This is somewhat involved. nbp
1702 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
1703 * on the clean list must be disassociated from their
1704 * current vnode. Buffers on the empty[kva] lists have
1705 * already been disassociated.
1708 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1709 kprintf("getnewbuf: warning, locked buf %p, race corrected\n", bp);
1710 tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1711 goto restart;
1713 if (bp->b_qindex != qindex) {
1714 kprintf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp, qindex, bp->b_qindex);
1715 BUF_UNLOCK(bp);
1716 goto restart;
1718 bremfree(bp);
1721 * Dependancies must be handled before we disassociate the
1722 * vnode.
1724 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1725 * be immediately disassociated. HAMMER then becomes
1726 * responsible for releasing the buffer.
1728 if (LIST_FIRST(&bp->b_dep) != NULL) {
1729 buf_deallocate(bp);
1730 if (bp->b_flags & B_LOCKED) {
1731 bqrelse(bp);
1732 goto restart;
1734 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
1737 if (qindex == BQUEUE_CLEAN) {
1738 if (bp->b_flags & B_VMIO) {
1739 bp->b_flags &= ~B_ASYNC;
1740 vfs_vmio_release(bp);
1742 if (bp->b_vp)
1743 brelvp(bp);
1747 * NOTE: nbp is now entirely invalid. We can only restart
1748 * the scan from this point on.
1750 * Get the rest of the buffer freed up. b_kva* is still
1751 * valid after this operation.
1754 KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
1755 KKASSERT((bp->b_flags & B_HASHED) == 0);
1758 * critical section protection is not required when
1759 * scrapping a buffer's contents because it is already
1760 * wired.
1762 if (bp->b_bufsize)
1763 allocbuf(bp, 0);
1765 bp->b_flags = B_BNOCLIP;
1766 bp->b_cmd = BUF_CMD_DONE;
1767 bp->b_vp = NULL;
1768 bp->b_error = 0;
1769 bp->b_resid = 0;
1770 bp->b_bcount = 0;
1771 bp->b_xio.xio_npages = 0;
1772 bp->b_dirtyoff = bp->b_dirtyend = 0;
1773 reinitbufbio(bp);
1774 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
1775 buf_dep_init(bp);
1776 if (blkflags & GETBLK_BHEAVY)
1777 bp->b_flags |= B_HEAVY;
1780 * If we are defragging then free the buffer.
1782 if (defrag) {
1783 bp->b_flags |= B_INVAL;
1784 bfreekva(bp);
1785 brelse(bp);
1786 defrag = 0;
1787 goto restart;
1791 * If we are overcomitted then recover the buffer and its
1792 * KVM space. This occurs in rare situations when multiple
1793 * processes are blocked in getnewbuf() or allocbuf().
1795 if (bufspace >= hibufspace)
1796 flushingbufs = 1;
1797 if (flushingbufs && bp->b_kvasize != 0) {
1798 bp->b_flags |= B_INVAL;
1799 bfreekva(bp);
1800 brelse(bp);
1801 goto restart;
1803 if (bufspace < lobufspace)
1804 flushingbufs = 0;
1805 break;
1809 * If we exhausted our list, sleep as appropriate. We may have to
1810 * wakeup various daemons and write out some dirty buffers.
1812 * Generally we are sleeping due to insufficient buffer space.
1815 if (bp == NULL) {
1816 int flags;
1817 char *waitmsg;
1819 if (defrag) {
1820 flags = VFS_BIO_NEED_BUFSPACE;
1821 waitmsg = "nbufkv";
1822 } else if (bufspace >= hibufspace) {
1823 waitmsg = "nbufbs";
1824 flags = VFS_BIO_NEED_BUFSPACE;
1825 } else {
1826 waitmsg = "newbuf";
1827 flags = VFS_BIO_NEED_ANY;
1830 needsbuffer |= flags;
1831 bd_speedup(); /* heeeelp */
1832 while (needsbuffer & flags) {
1833 if (tsleep(&needsbuffer, slpflags, waitmsg, slptimeo))
1834 return (NULL);
1836 } else {
1838 * We finally have a valid bp. We aren't quite out of the
1839 * woods, we still have to reserve kva space. In order
1840 * to keep fragmentation sane we only allocate kva in
1841 * BKVASIZE chunks.
1843 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1845 if (maxsize != bp->b_kvasize) {
1846 vm_offset_t addr = 0;
1847 int count;
1849 bfreekva(bp);
1851 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1852 vm_map_lock(&buffer_map);
1854 if (vm_map_findspace(&buffer_map,
1855 vm_map_min(&buffer_map), maxsize,
1856 maxsize, &addr)) {
1858 * Uh oh. Buffer map is too fragmented. We
1859 * must defragment the map.
1861 vm_map_unlock(&buffer_map);
1862 vm_map_entry_release(count);
1863 ++bufdefragcnt;
1864 defrag = 1;
1865 bp->b_flags |= B_INVAL;
1866 brelse(bp);
1867 goto restart;
1869 if (addr) {
1870 vm_map_insert(&buffer_map, &count,
1871 NULL, 0,
1872 addr, addr + maxsize,
1873 VM_MAPTYPE_NORMAL,
1874 VM_PROT_ALL, VM_PROT_ALL,
1875 MAP_NOFAULT);
1877 bp->b_kvabase = (caddr_t) addr;
1878 bp->b_kvasize = maxsize;
1879 bufspace += bp->b_kvasize;
1880 ++bufreusecnt;
1882 vm_map_unlock(&buffer_map);
1883 vm_map_entry_release(count);
1885 bp->b_data = bp->b_kvabase;
1887 return(bp);
1891 * buf_daemon:
1893 * Buffer flushing daemon. Buffers are normally flushed by the
1894 * update daemon but if it cannot keep up this process starts to
1895 * take the load in an attempt to prevent getnewbuf() from blocking.
1897 * Once a flush is initiated it does not stop until the number
1898 * of buffers falls below lodirtybuffers, but we will wake up anyone
1899 * waiting at the mid-point.
1902 static struct thread *bufdaemon_td;
1903 static struct thread *bufdaemonhw_td;
1905 static struct kproc_desc buf_kp = {
1906 "bufdaemon",
1907 buf_daemon,
1908 &bufdaemon_td
1910 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
1911 kproc_start, &buf_kp)
1913 static struct kproc_desc bufhw_kp = {
1914 "bufdaemon_hw",
1915 buf_daemon_hw,
1916 &bufdaemonhw_td
1918 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
1919 kproc_start, &bufhw_kp)
1921 static void
1922 buf_daemon(void)
1925 * This process needs to be suspended prior to shutdown sync.
1927 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
1928 bufdaemon_td, SHUTDOWN_PRI_LAST);
1931 * This process is allowed to take the buffer cache to the limit
1933 crit_enter();
1935 for (;;) {
1936 kproc_suspend_loop();
1939 * Do the flush. Limit the amount of in-transit I/O we
1940 * allow to build up, otherwise we would completely saturate
1941 * the I/O system. Wakeup any waiting processes before we
1942 * normally would so they can run in parallel with our drain.
1944 while (dirtybufspace > lodirtybufspace) {
1945 if (flushbufqueues(BQUEUE_DIRTY) == 0)
1946 break;
1947 waitrunningbufspace();
1949 if (runningbufspace + dirtybufspace > lodirtybufspace) {
1950 waitrunningbufspace();
1954 * Only clear bd_request if we have reached our low water
1955 * mark. The buf_daemon normally waits 5 seconds and
1956 * then incrementally flushes any dirty buffers that have
1957 * built up, within reason.
1959 * If we were unable to hit our low water mark and couldn't
1960 * find any flushable buffers, we sleep half a second.
1961 * Otherwise we loop immediately.
1963 if (runningbufspace + dirtybufspace <= lodirtybufspace) {
1965 * We reached our low water mark, reset the
1966 * request and sleep until we are needed again.
1967 * The sleep is just so the suspend code works.
1969 spin_lock_wr(&needsbuffer_spin);
1970 bd_request = 0;
1971 msleep(&bd_request, &needsbuffer_spin, 0,
1972 "psleep", hz);
1973 spin_unlock_wr(&needsbuffer_spin);
1974 } else {
1976 * We couldn't find any flushable dirty buffers but
1977 * still have too many dirty buffers, we
1978 * have to sleep and try again. (rare)
1980 tsleep(&bd_request, 0, "qsleep", hz / 2);
1985 static void
1986 buf_daemon_hw(void)
1989 * This process needs to be suspended prior to shutdown sync.
1991 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
1992 bufdaemonhw_td, SHUTDOWN_PRI_LAST);
1995 * This process is allowed to take the buffer cache to the limit
1997 crit_enter();
1999 for (;;) {
2000 kproc_suspend_loop();
2003 * Do the flush. Limit the amount of in-transit I/O we
2004 * allow to build up, otherwise we would completely saturate
2005 * the I/O system. Wakeup any waiting processes before we
2006 * normally would so they can run in parallel with our drain.
2008 while (dirtybufspacehw > lodirtybufspace) {
2009 if (flushbufqueues(BQUEUE_DIRTY_HW) == 0)
2010 break;
2011 waitrunningbufspace();
2013 if (runningbufspace + dirtybufspacehw > lodirtybufspace) {
2014 waitrunningbufspace();
2018 * Only clear bd_request if we have reached our low water
2019 * mark. The buf_daemon normally waits 5 seconds and
2020 * then incrementally flushes any dirty buffers that have
2021 * built up, within reason.
2023 * If we were unable to hit our low water mark and couldn't
2024 * find any flushable buffers, we sleep half a second.
2025 * Otherwise we loop immediately.
2027 if (runningbufspace + dirtybufspacehw <= lodirtybufspace) {
2029 * We reached our low water mark, reset the
2030 * request and sleep until we are needed again.
2031 * The sleep is just so the suspend code works.
2033 spin_lock_wr(&needsbuffer_spin);
2034 bd_request_hw = 0;
2035 msleep(&bd_request_hw, &needsbuffer_spin, 0,
2036 "psleep", hz);
2037 spin_unlock_wr(&needsbuffer_spin);
2038 } else {
2040 * We couldn't find any flushable dirty buffers but
2041 * still have too many dirty buffers, we
2042 * have to sleep and try again. (rare)
2044 tsleep(&bd_request_hw, 0, "qsleep", hz / 2);
2050 * flushbufqueues:
2052 * Try to flush a buffer in the dirty queue. We must be careful to
2053 * free up B_INVAL buffers instead of write them, which NFS is
2054 * particularly sensitive to.
2056 * B_RELBUF may only be set by VFSs. We do set B_AGE to indicate
2057 * that we really want to try to get the buffer out and reuse it
2058 * due to the write load on the machine.
2061 static int
2062 flushbufqueues(bufq_type_t q)
2064 struct buf *bp;
2065 int r = 0;
2067 bp = TAILQ_FIRST(&bufqueues[q]);
2069 while (bp) {
2070 KASSERT((bp->b_flags & B_DELWRI),
2071 ("unexpected clean buffer %p", bp));
2073 if (bp->b_flags & B_DELWRI) {
2074 if (bp->b_flags & B_INVAL) {
2075 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2076 panic("flushbufqueues: locked buf");
2077 bremfree(bp);
2078 brelse(bp);
2079 ++r;
2080 break;
2082 if (LIST_FIRST(&bp->b_dep) != NULL &&
2083 (bp->b_flags & B_DEFERRED) == 0 &&
2084 buf_countdeps(bp, 0)) {
2085 TAILQ_REMOVE(&bufqueues[q], bp, b_freelist);
2086 TAILQ_INSERT_TAIL(&bufqueues[q], bp,
2087 b_freelist);
2088 bp->b_flags |= B_DEFERRED;
2089 bp = TAILQ_FIRST(&bufqueues[q]);
2090 continue;
2094 * Only write it out if we can successfully lock
2095 * it. If the buffer has a dependancy,
2096 * buf_checkwrite must also return 0.
2098 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
2099 if (LIST_FIRST(&bp->b_dep) != NULL &&
2100 buf_checkwrite(bp)) {
2101 bremfree(bp);
2102 brelse(bp);
2103 } else {
2104 bp->b_flags |= B_AGE;
2105 vfs_bio_awrite(bp);
2107 ++r;
2108 break;
2111 bp = TAILQ_NEXT(bp, b_freelist);
2113 return (r);
2117 * inmem:
2119 * Returns true if no I/O is needed to access the associated VM object.
2120 * This is like findblk except it also hunts around in the VM system for
2121 * the data.
2123 * Note that we ignore vm_page_free() races from interrupts against our
2124 * lookup, since if the caller is not protected our return value will not
2125 * be any more valid then otherwise once we exit the critical section.
2128 inmem(struct vnode *vp, off_t loffset)
2130 vm_object_t obj;
2131 vm_offset_t toff, tinc, size;
2132 vm_page_t m;
2134 if (findblk(vp, loffset))
2135 return 1;
2136 if (vp->v_mount == NULL)
2137 return 0;
2138 if ((obj = vp->v_object) == NULL)
2139 return 0;
2141 size = PAGE_SIZE;
2142 if (size > vp->v_mount->mnt_stat.f_iosize)
2143 size = vp->v_mount->mnt_stat.f_iosize;
2145 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2146 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2147 if (m == NULL)
2148 return 0;
2149 tinc = size;
2150 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2151 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2152 if (vm_page_is_valid(m,
2153 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0)
2154 return 0;
2156 return 1;
2160 * vfs_setdirty:
2162 * Sets the dirty range for a buffer based on the status of the dirty
2163 * bits in the pages comprising the buffer.
2165 * The range is limited to the size of the buffer.
2167 * This routine is primarily used by NFS, but is generalized for the
2168 * B_VMIO case.
2170 static void
2171 vfs_setdirty(struct buf *bp)
2173 int i;
2174 vm_object_t object;
2177 * Degenerate case - empty buffer
2180 if (bp->b_bufsize == 0)
2181 return;
2184 * We qualify the scan for modified pages on whether the
2185 * object has been flushed yet. The OBJ_WRITEABLE flag
2186 * is not cleared simply by protecting pages off.
2189 if ((bp->b_flags & B_VMIO) == 0)
2190 return;
2192 object = bp->b_xio.xio_pages[0]->object;
2194 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2195 kprintf("Warning: object %p writeable but not mightbedirty\n", object);
2196 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2197 kprintf("Warning: object %p mightbedirty but not writeable\n", object);
2199 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2200 vm_offset_t boffset;
2201 vm_offset_t eoffset;
2204 * test the pages to see if they have been modified directly
2205 * by users through the VM system.
2207 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2208 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2209 vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2213 * Calculate the encompassing dirty range, boffset and eoffset,
2214 * (eoffset - boffset) bytes.
2217 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2218 if (bp->b_xio.xio_pages[i]->dirty)
2219 break;
2221 boffset = (i << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2223 for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2224 if (bp->b_xio.xio_pages[i]->dirty) {
2225 break;
2228 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2231 * Fit it to the buffer.
2234 if (eoffset > bp->b_bcount)
2235 eoffset = bp->b_bcount;
2238 * If we have a good dirty range, merge with the existing
2239 * dirty range.
2242 if (boffset < eoffset) {
2243 if (bp->b_dirtyoff > boffset)
2244 bp->b_dirtyoff = boffset;
2245 if (bp->b_dirtyend < eoffset)
2246 bp->b_dirtyend = eoffset;
2252 * findblk:
2254 * Locate and return the specified buffer, or NULL if the buffer does
2255 * not exist. Do not attempt to lock the buffer or manipulate it in
2256 * any way. The caller must validate that the correct buffer has been
2257 * obtain after locking it.
2259 struct buf *
2260 findblk(struct vnode *vp, off_t loffset)
2262 struct buf *bp;
2264 crit_enter();
2265 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2266 crit_exit();
2267 return(bp);
2271 * getblk:
2273 * Get a block given a specified block and offset into a file/device.
2274 * B_INVAL may or may not be set on return. The caller should clear
2275 * B_INVAL prior to initiating a READ.
2277 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2278 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2279 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2280 * without doing any of those things the system will likely believe
2281 * the buffer to be valid (especially if it is not B_VMIO), and the
2282 * next getblk() will return the buffer with B_CACHE set.
2284 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2285 * an existing buffer.
2287 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2288 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2289 * and then cleared based on the backing VM. If the previous buffer is
2290 * non-0-sized but invalid, B_CACHE will be cleared.
2292 * If getblk() must create a new buffer, the new buffer is returned with
2293 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2294 * case it is returned with B_INVAL clear and B_CACHE set based on the
2295 * backing VM.
2297 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2298 * B_CACHE bit is clear.
2300 * What this means, basically, is that the caller should use B_CACHE to
2301 * determine whether the buffer is fully valid or not and should clear
2302 * B_INVAL prior to issuing a read. If the caller intends to validate
2303 * the buffer by loading its data area with something, the caller needs
2304 * to clear B_INVAL. If the caller does this without issuing an I/O,
2305 * the caller should set B_CACHE ( as an optimization ), else the caller
2306 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2307 * a write attempt or if it was a successfull read. If the caller
2308 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2309 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2311 * getblk flags:
2313 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2314 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
2316 struct buf *
2317 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2319 struct buf *bp;
2320 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2321 int error;
2323 if (size > MAXBSIZE)
2324 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2325 if (vp->v_object == NULL)
2326 panic("getblk: vnode %p has no object!", vp);
2328 crit_enter();
2329 loop:
2330 if ((bp = findblk(vp, loffset))) {
2332 * The buffer was found in the cache, but we need to lock it.
2333 * Even with LK_NOWAIT the lockmgr may break our critical
2334 * section, so double-check the validity of the buffer
2335 * once the lock has been obtained.
2337 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2338 int lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2339 if (blkflags & GETBLK_PCATCH)
2340 lkflags |= LK_PCATCH;
2341 error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2342 if (error) {
2343 if (error == ENOLCK)
2344 goto loop;
2345 crit_exit();
2346 return (NULL);
2351 * Once the buffer has been locked, make sure we didn't race
2352 * a buffer recyclement. Buffers that are no longer hashed
2353 * will have b_vp == NULL, so this takes care of that check
2354 * as well.
2356 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2357 kprintf("Warning buffer %p (vp %p loffset %lld) was recycled\n", bp, vp, loffset);
2358 BUF_UNLOCK(bp);
2359 goto loop;
2363 * All vnode-based buffers must be backed by a VM object.
2365 KKASSERT(bp->b_flags & B_VMIO);
2366 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2367 bp->b_flags &= ~B_AGE;
2370 * Make sure that B_INVAL buffers do not have a cached
2371 * block number translation.
2373 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2374 kprintf("Warning invalid buffer %p (vp %p loffset %lld) did not have cleared bio_offset cache\n", bp, vp, loffset);
2375 clearbiocache(&bp->b_bio2);
2379 * The buffer is locked. B_CACHE is cleared if the buffer is
2380 * invalid.
2382 if (bp->b_flags & B_INVAL)
2383 bp->b_flags &= ~B_CACHE;
2384 bremfree(bp);
2387 * Any size inconsistancy with a dirty buffer or a buffer
2388 * with a softupdates dependancy must be resolved. Resizing
2389 * the buffer in such circumstances can lead to problems.
2391 if (size != bp->b_bcount) {
2392 if (bp->b_flags & B_DELWRI) {
2393 bp->b_flags |= B_NOCACHE;
2394 bwrite(bp);
2395 } else if (LIST_FIRST(&bp->b_dep)) {
2396 bp->b_flags |= B_NOCACHE;
2397 bwrite(bp);
2398 } else {
2399 bp->b_flags |= B_RELBUF;
2400 brelse(bp);
2402 goto loop;
2404 KKASSERT(size <= bp->b_kvasize);
2405 KASSERT(bp->b_loffset != NOOFFSET,
2406 ("getblk: no buffer offset"));
2409 * A buffer with B_DELWRI set and B_CACHE clear must
2410 * be committed before we can return the buffer in
2411 * order to prevent the caller from issuing a read
2412 * ( due to B_CACHE not being set ) and overwriting
2413 * it.
2415 * Most callers, including NFS and FFS, need this to
2416 * operate properly either because they assume they
2417 * can issue a read if B_CACHE is not set, or because
2418 * ( for example ) an uncached B_DELWRI might loop due
2419 * to softupdates re-dirtying the buffer. In the latter
2420 * case, B_CACHE is set after the first write completes,
2421 * preventing further loops.
2423 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2424 * above while extending the buffer, we cannot allow the
2425 * buffer to remain with B_CACHE set after the write
2426 * completes or it will represent a corrupt state. To
2427 * deal with this we set B_NOCACHE to scrap the buffer
2428 * after the write.
2430 * We might be able to do something fancy, like setting
2431 * B_CACHE in bwrite() except if B_DELWRI is already set,
2432 * so the below call doesn't set B_CACHE, but that gets real
2433 * confusing. This is much easier.
2436 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2437 bp->b_flags |= B_NOCACHE;
2438 bwrite(bp);
2439 goto loop;
2441 crit_exit();
2442 } else {
2444 * Buffer is not in-core, create new buffer. The buffer
2445 * returned by getnewbuf() is locked. Note that the returned
2446 * buffer is also considered valid (not marked B_INVAL).
2448 * Calculating the offset for the I/O requires figuring out
2449 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2450 * the mount's f_iosize otherwise. If the vnode does not
2451 * have an associated mount we assume that the passed size is
2452 * the block size.
2454 * Note that vn_isdisk() cannot be used here since it may
2455 * return a failure for numerous reasons. Note that the
2456 * buffer size may be larger then the block size (the caller
2457 * will use block numbers with the proper multiple). Beware
2458 * of using any v_* fields which are part of unions. In
2459 * particular, in DragonFly the mount point overloading
2460 * mechanism uses the namecache only and the underlying
2461 * directory vnode is not a special case.
2463 int bsize, maxsize;
2465 if (vp->v_type == VBLK || vp->v_type == VCHR)
2466 bsize = DEV_BSIZE;
2467 else if (vp->v_mount)
2468 bsize = vp->v_mount->mnt_stat.f_iosize;
2469 else
2470 bsize = size;
2472 maxsize = size + (loffset & PAGE_MASK);
2473 maxsize = imax(maxsize, bsize);
2475 if ((bp = getnewbuf(blkflags, slptimeo, size, maxsize)) == NULL) {
2476 if (slpflags || slptimeo) {
2477 crit_exit();
2478 return NULL;
2480 goto loop;
2484 * This code is used to make sure that a buffer is not
2485 * created while the getnewbuf routine is blocked.
2486 * This can be a problem whether the vnode is locked or not.
2487 * If the buffer is created out from under us, we have to
2488 * throw away the one we just created. There is no window
2489 * race because we are safely running in a critical section
2490 * from the point of the duplicate buffer creation through
2491 * to here, and we've locked the buffer.
2493 if (findblk(vp, loffset)) {
2494 bp->b_flags |= B_INVAL;
2495 brelse(bp);
2496 goto loop;
2500 * Insert the buffer into the hash, so that it can
2501 * be found by findblk().
2503 * Make sure the translation layer has been cleared.
2505 bp->b_loffset = loffset;
2506 bp->b_bio2.bio_offset = NOOFFSET;
2507 /* bp->b_bio2.bio_next = NULL; */
2509 bgetvp(vp, bp);
2512 * All vnode-based buffers must be backed by a VM object.
2514 KKASSERT(vp->v_object != NULL);
2515 bp->b_flags |= B_VMIO;
2516 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2518 allocbuf(bp, size);
2520 crit_exit();
2522 return (bp);
2526 * regetblk(bp)
2528 * Reacquire a buffer that was previously released to the locked queue,
2529 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
2530 * set B_LOCKED (which handles the acquisition race).
2532 * To this end, either B_LOCKED must be set or the dependancy list must be
2533 * non-empty.
2535 void
2536 regetblk(struct buf *bp)
2538 KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
2539 BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
2540 crit_enter();
2541 bremfree(bp);
2542 crit_exit();
2546 * geteblk:
2548 * Get an empty, disassociated buffer of given size. The buffer is
2549 * initially set to B_INVAL.
2551 * critical section protection is not required for the allocbuf()
2552 * call because races are impossible here.
2554 struct buf *
2555 geteblk(int size)
2557 struct buf *bp;
2558 int maxsize;
2560 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2562 crit_enter();
2563 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2565 crit_exit();
2566 allocbuf(bp, size);
2567 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2568 return (bp);
2573 * allocbuf:
2575 * This code constitutes the buffer memory from either anonymous system
2576 * memory (in the case of non-VMIO operations) or from an associated
2577 * VM object (in the case of VMIO operations). This code is able to
2578 * resize a buffer up or down.
2580 * Note that this code is tricky, and has many complications to resolve
2581 * deadlock or inconsistant data situations. Tread lightly!!!
2582 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2583 * the caller. Calling this code willy nilly can result in the loss of data.
2585 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2586 * B_CACHE for the non-VMIO case.
2588 * This routine does not need to be called from a critical section but you
2589 * must own the buffer.
2592 allocbuf(struct buf *bp, int size)
2594 int newbsize, mbsize;
2595 int i;
2597 if (BUF_REFCNT(bp) == 0)
2598 panic("allocbuf: buffer not busy");
2600 if (bp->b_kvasize < size)
2601 panic("allocbuf: buffer too small");
2603 if ((bp->b_flags & B_VMIO) == 0) {
2604 caddr_t origbuf;
2605 int origbufsize;
2607 * Just get anonymous memory from the kernel. Don't
2608 * mess with B_CACHE.
2610 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2611 if (bp->b_flags & B_MALLOC)
2612 newbsize = mbsize;
2613 else
2614 newbsize = round_page(size);
2616 if (newbsize < bp->b_bufsize) {
2618 * Malloced buffers are not shrunk
2620 if (bp->b_flags & B_MALLOC) {
2621 if (newbsize) {
2622 bp->b_bcount = size;
2623 } else {
2624 kfree(bp->b_data, M_BIOBUF);
2625 if (bp->b_bufsize) {
2626 bufmallocspace -= bp->b_bufsize;
2627 bufspacewakeup();
2628 bp->b_bufsize = 0;
2630 bp->b_data = bp->b_kvabase;
2631 bp->b_bcount = 0;
2632 bp->b_flags &= ~B_MALLOC;
2634 return 1;
2636 vm_hold_free_pages(
2638 (vm_offset_t) bp->b_data + newbsize,
2639 (vm_offset_t) bp->b_data + bp->b_bufsize);
2640 } else if (newbsize > bp->b_bufsize) {
2642 * We only use malloced memory on the first allocation.
2643 * and revert to page-allocated memory when the buffer
2644 * grows.
2646 if ((bufmallocspace < maxbufmallocspace) &&
2647 (bp->b_bufsize == 0) &&
2648 (mbsize <= PAGE_SIZE/2)) {
2650 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
2651 bp->b_bufsize = mbsize;
2652 bp->b_bcount = size;
2653 bp->b_flags |= B_MALLOC;
2654 bufmallocspace += mbsize;
2655 return 1;
2657 origbuf = NULL;
2658 origbufsize = 0;
2660 * If the buffer is growing on its other-than-first
2661 * allocation, then we revert to the page-allocation
2662 * scheme.
2664 if (bp->b_flags & B_MALLOC) {
2665 origbuf = bp->b_data;
2666 origbufsize = bp->b_bufsize;
2667 bp->b_data = bp->b_kvabase;
2668 if (bp->b_bufsize) {
2669 bufmallocspace -= bp->b_bufsize;
2670 bufspacewakeup();
2671 bp->b_bufsize = 0;
2673 bp->b_flags &= ~B_MALLOC;
2674 newbsize = round_page(newbsize);
2676 vm_hold_load_pages(
2678 (vm_offset_t) bp->b_data + bp->b_bufsize,
2679 (vm_offset_t) bp->b_data + newbsize);
2680 if (origbuf) {
2681 bcopy(origbuf, bp->b_data, origbufsize);
2682 kfree(origbuf, M_BIOBUF);
2685 } else {
2686 vm_page_t m;
2687 int desiredpages;
2689 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2690 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
2691 newbsize + PAGE_MASK) >> PAGE_SHIFT;
2692 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
2694 if (bp->b_flags & B_MALLOC)
2695 panic("allocbuf: VMIO buffer can't be malloced");
2697 * Set B_CACHE initially if buffer is 0 length or will become
2698 * 0-length.
2700 if (size == 0 || bp->b_bufsize == 0)
2701 bp->b_flags |= B_CACHE;
2703 if (newbsize < bp->b_bufsize) {
2705 * DEV_BSIZE aligned new buffer size is less then the
2706 * DEV_BSIZE aligned existing buffer size. Figure out
2707 * if we have to remove any pages.
2709 if (desiredpages < bp->b_xio.xio_npages) {
2710 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2712 * the page is not freed here -- it
2713 * is the responsibility of
2714 * vnode_pager_setsize
2716 m = bp->b_xio.xio_pages[i];
2717 KASSERT(m != bogus_page,
2718 ("allocbuf: bogus page found"));
2719 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2722 bp->b_xio.xio_pages[i] = NULL;
2723 vm_page_unwire(m, 0);
2725 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2726 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2727 bp->b_xio.xio_npages = desiredpages;
2729 } else if (size > bp->b_bcount) {
2731 * We are growing the buffer, possibly in a
2732 * byte-granular fashion.
2734 struct vnode *vp;
2735 vm_object_t obj;
2736 vm_offset_t toff;
2737 vm_offset_t tinc;
2740 * Step 1, bring in the VM pages from the object,
2741 * allocating them if necessary. We must clear
2742 * B_CACHE if these pages are not valid for the
2743 * range covered by the buffer.
2745 * critical section protection is required to protect
2746 * against interrupts unbusying and freeing pages
2747 * between our vm_page_lookup() and our
2748 * busycheck/wiring call.
2750 vp = bp->b_vp;
2751 obj = vp->v_object;
2753 crit_enter();
2754 while (bp->b_xio.xio_npages < desiredpages) {
2755 vm_page_t m;
2756 vm_pindex_t pi;
2758 pi = OFF_TO_IDX(bp->b_loffset) + bp->b_xio.xio_npages;
2759 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2761 * note: must allocate system pages
2762 * since blocking here could intefere
2763 * with paging I/O, no matter which
2764 * process we are.
2766 m = vm_page_alloc(obj, pi, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
2767 if (m == NULL) {
2768 vm_wait();
2769 vm_pageout_deficit += desiredpages -
2770 bp->b_xio.xio_npages;
2771 } else {
2772 vm_page_wire(m);
2773 vm_page_wakeup(m);
2774 bp->b_flags &= ~B_CACHE;
2775 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2776 ++bp->b_xio.xio_npages;
2778 continue;
2782 * We found a page. If we have to sleep on it,
2783 * retry because it might have gotten freed out
2784 * from under us.
2786 * We can only test PG_BUSY here. Blocking on
2787 * m->busy might lead to a deadlock:
2789 * vm_fault->getpages->cluster_read->allocbuf
2793 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2794 continue;
2797 * We have a good page. Should we wakeup the
2798 * page daemon?
2800 if ((curthread != pagethread) &&
2801 ((m->queue - m->pc) == PQ_CACHE) &&
2802 ((vmstats.v_free_count + vmstats.v_cache_count) <
2803 (vmstats.v_free_min + vmstats.v_cache_min))) {
2804 pagedaemon_wakeup();
2806 vm_page_flag_clear(m, PG_ZERO);
2807 vm_page_wire(m);
2808 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2809 ++bp->b_xio.xio_npages;
2811 crit_exit();
2814 * Step 2. We've loaded the pages into the buffer,
2815 * we have to figure out if we can still have B_CACHE
2816 * set. Note that B_CACHE is set according to the
2817 * byte-granular range ( bcount and size ), not the
2818 * aligned range ( newbsize ).
2820 * The VM test is against m->valid, which is DEV_BSIZE
2821 * aligned. Needless to say, the validity of the data
2822 * needs to also be DEV_BSIZE aligned. Note that this
2823 * fails with NFS if the server or some other client
2824 * extends the file's EOF. If our buffer is resized,
2825 * B_CACHE may remain set! XXX
2828 toff = bp->b_bcount;
2829 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
2831 while ((bp->b_flags & B_CACHE) && toff < size) {
2832 vm_pindex_t pi;
2834 if (tinc > (size - toff))
2835 tinc = size - toff;
2837 pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
2838 PAGE_SHIFT;
2840 vfs_buf_test_cache(
2841 bp,
2842 bp->b_loffset,
2843 toff,
2844 tinc,
2845 bp->b_xio.xio_pages[pi]
2847 toff += tinc;
2848 tinc = PAGE_SIZE;
2852 * Step 3, fixup the KVM pmap. Remember that
2853 * bp->b_data is relative to bp->b_loffset, but
2854 * bp->b_loffset may be offset into the first page.
2857 bp->b_data = (caddr_t)
2858 trunc_page((vm_offset_t)bp->b_data);
2859 pmap_qenter(
2860 (vm_offset_t)bp->b_data,
2861 bp->b_xio.xio_pages,
2862 bp->b_xio.xio_npages
2864 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2865 (vm_offset_t)(bp->b_loffset & PAGE_MASK));
2868 if (bp->b_flags & B_DELWRI) {
2869 dirtybufspace += newbsize - bp->b_bufsize;
2870 if (bp->b_flags & B_HEAVY)
2871 dirtybufspacehw += newbsize - bp->b_bufsize;
2873 if (newbsize < bp->b_bufsize)
2874 bufspacewakeup();
2875 bp->b_bufsize = newbsize; /* actual buffer allocation */
2876 bp->b_bcount = size; /* requested buffer size */
2877 return 1;
2881 * biowait:
2883 * Wait for buffer I/O completion, returning error status. The buffer
2884 * is left locked on return. B_EINTR is converted into an EINTR error
2885 * and cleared.
2887 * NOTE! The original b_cmd is lost on return, since b_cmd will be
2888 * set to BUF_CMD_DONE.
2891 biowait(struct buf *bp)
2893 crit_enter();
2894 while (bp->b_cmd != BUF_CMD_DONE) {
2895 if (bp->b_cmd == BUF_CMD_READ)
2896 tsleep(bp, 0, "biord", 0);
2897 else
2898 tsleep(bp, 0, "biowr", 0);
2900 crit_exit();
2901 if (bp->b_flags & B_EINTR) {
2902 bp->b_flags &= ~B_EINTR;
2903 return (EINTR);
2905 if (bp->b_flags & B_ERROR) {
2906 return (bp->b_error ? bp->b_error : EIO);
2907 } else {
2908 return (0);
2913 * This associates a tracking count with an I/O. vn_strategy() and
2914 * dev_dstrategy() do this automatically but there are a few cases
2915 * where a vnode or device layer is bypassed when a block translation
2916 * is cached. In such cases bio_start_transaction() may be called on
2917 * the bypassed layers so the system gets an I/O in progress indication
2918 * for those higher layers.
2920 void
2921 bio_start_transaction(struct bio *bio, struct bio_track *track)
2923 bio->bio_track = track;
2924 atomic_add_int(&track->bk_active, 1);
2928 * Initiate I/O on a vnode.
2930 void
2931 vn_strategy(struct vnode *vp, struct bio *bio)
2933 struct bio_track *track;
2935 KKASSERT(bio->bio_buf->b_cmd != BUF_CMD_DONE);
2936 if (bio->bio_buf->b_cmd == BUF_CMD_READ)
2937 track = &vp->v_track_read;
2938 else
2939 track = &vp->v_track_write;
2940 bio->bio_track = track;
2941 atomic_add_int(&track->bk_active, 1);
2942 vop_strategy(*vp->v_ops, vp, bio);
2947 * biodone:
2949 * Finish I/O on a buffer, optionally calling a completion function.
2950 * This is usually called from an interrupt so process blocking is
2951 * not allowed.
2953 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2954 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2955 * assuming B_INVAL is clear.
2957 * For the VMIO case, we set B_CACHE if the op was a read and no
2958 * read error occured, or if the op was a write. B_CACHE is never
2959 * set if the buffer is invalid or otherwise uncacheable.
2961 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2962 * initiator to leave B_INVAL set to brelse the buffer out of existance
2963 * in the biodone routine.
2965 void
2966 biodone(struct bio *bio)
2968 struct buf *bp = bio->bio_buf;
2969 buf_cmd_t cmd;
2971 crit_enter();
2973 KASSERT(BUF_REFCNTNB(bp) > 0,
2974 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
2975 KASSERT(bp->b_cmd != BUF_CMD_DONE,
2976 ("biodone: bp %p already done!", bp));
2978 runningbufwakeup(bp);
2981 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
2983 while (bio) {
2984 biodone_t *done_func;
2985 struct bio_track *track;
2988 * BIO tracking. Most but not all BIOs are tracked.
2990 if ((track = bio->bio_track) != NULL) {
2991 atomic_subtract_int(&track->bk_active, 1);
2992 if (track->bk_active < 0) {
2993 panic("biodone: bad active count bio %p\n",
2994 bio);
2996 if (track->bk_waitflag) {
2997 track->bk_waitflag = 0;
2998 wakeup(track);
3000 bio->bio_track = NULL;
3004 * A bio_done function terminates the loop. The function
3005 * will be responsible for any further chaining and/or
3006 * buffer management.
3008 * WARNING! The done function can deallocate the buffer!
3010 if ((done_func = bio->bio_done) != NULL) {
3011 bio->bio_done = NULL;
3012 done_func(bio);
3013 crit_exit();
3014 return;
3016 bio = bio->bio_prev;
3019 cmd = bp->b_cmd;
3020 bp->b_cmd = BUF_CMD_DONE;
3023 * Only reads and writes are processed past this point.
3025 if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3026 brelse(bp);
3027 crit_exit();
3028 return;
3032 * Warning: softupdates may re-dirty the buffer.
3034 if (LIST_FIRST(&bp->b_dep) != NULL)
3035 buf_complete(bp);
3037 if (bp->b_flags & B_VMIO) {
3038 int i;
3039 vm_ooffset_t foff;
3040 vm_page_t m;
3041 vm_object_t obj;
3042 int iosize;
3043 struct vnode *vp = bp->b_vp;
3045 obj = vp->v_object;
3047 #if defined(VFS_BIO_DEBUG)
3048 if (vp->v_auxrefs == 0)
3049 panic("biodone: zero vnode hold count");
3050 if ((vp->v_flag & VOBJBUF) == 0)
3051 panic("biodone: vnode is not setup for merged cache");
3052 #endif
3054 foff = bp->b_loffset;
3055 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3056 KASSERT(obj != NULL, ("biodone: missing VM object"));
3058 #if defined(VFS_BIO_DEBUG)
3059 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3060 kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
3061 obj->paging_in_progress, bp->b_xio.xio_npages);
3063 #endif
3066 * Set B_CACHE if the op was a normal read and no error
3067 * occured. B_CACHE is set for writes in the b*write()
3068 * routines.
3070 iosize = bp->b_bcount - bp->b_resid;
3071 if (cmd == BUF_CMD_READ && (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3072 bp->b_flags |= B_CACHE;
3075 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3076 int bogusflag = 0;
3077 int resid;
3079 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3080 if (resid > iosize)
3081 resid = iosize;
3084 * cleanup bogus pages, restoring the originals. Since
3085 * the originals should still be wired, we don't have
3086 * to worry about interrupt/freeing races destroying
3087 * the VM object association.
3089 m = bp->b_xio.xio_pages[i];
3090 if (m == bogus_page) {
3091 bogusflag = 1;
3092 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3093 if (m == NULL)
3094 panic("biodone: page disappeared");
3095 bp->b_xio.xio_pages[i] = m;
3096 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3097 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3099 #if defined(VFS_BIO_DEBUG)
3100 if (OFF_TO_IDX(foff) != m->pindex) {
3101 kprintf(
3102 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
3103 (unsigned long)foff, m->pindex);
3105 #endif
3108 * In the write case, the valid and clean bits are
3109 * already changed correctly ( see bdwrite() ), so we
3110 * only need to do this here in the read case.
3112 if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3113 vfs_page_set_valid(bp, foff, i, m);
3115 vm_page_flag_clear(m, PG_ZERO);
3118 * when debugging new filesystems or buffer I/O methods, this
3119 * is the most common error that pops up. if you see this, you
3120 * have not set the page busy flag correctly!!!
3122 if (m->busy == 0) {
3123 kprintf("biodone: page busy < 0, "
3124 "pindex: %d, foff: 0x(%x,%x), "
3125 "resid: %d, index: %d\n",
3126 (int) m->pindex, (int)(foff >> 32),
3127 (int) foff & 0xffffffff, resid, i);
3128 if (!vn_isdisk(vp, NULL))
3129 kprintf(" iosize: %ld, loffset: %lld, flags: 0x%08x, npages: %d\n",
3130 bp->b_vp->v_mount->mnt_stat.f_iosize,
3131 bp->b_loffset,
3132 bp->b_flags, bp->b_xio.xio_npages);
3133 else
3134 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3135 bp->b_loffset,
3136 bp->b_flags, bp->b_xio.xio_npages);
3137 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3138 m->valid, m->dirty, m->wire_count);
3139 panic("biodone: page busy < 0");
3141 vm_page_io_finish(m);
3142 vm_object_pip_subtract(obj, 1);
3143 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3144 iosize -= resid;
3146 if (obj)
3147 vm_object_pip_wakeupn(obj, 0);
3151 * For asynchronous completions, release the buffer now. The brelse
3152 * will do a wakeup there if necessary - so no need to do a wakeup
3153 * here in the async case. The sync case always needs to do a wakeup.
3156 if (bp->b_flags & B_ASYNC) {
3157 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
3158 brelse(bp);
3159 else
3160 bqrelse(bp);
3161 } else {
3162 wakeup(bp);
3164 crit_exit();
3168 * vfs_unbusy_pages:
3170 * This routine is called in lieu of iodone in the case of
3171 * incomplete I/O. This keeps the busy status for pages
3172 * consistant.
3174 void
3175 vfs_unbusy_pages(struct buf *bp)
3177 int i;
3179 runningbufwakeup(bp);
3180 if (bp->b_flags & B_VMIO) {
3181 struct vnode *vp = bp->b_vp;
3182 vm_object_t obj;
3184 obj = vp->v_object;
3186 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3187 vm_page_t m = bp->b_xio.xio_pages[i];
3190 * When restoring bogus changes the original pages
3191 * should still be wired, so we are in no danger of
3192 * losing the object association and do not need
3193 * critical section protection particularly.
3195 if (m == bogus_page) {
3196 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3197 if (!m) {
3198 panic("vfs_unbusy_pages: page missing");
3200 bp->b_xio.xio_pages[i] = m;
3201 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3202 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3204 vm_object_pip_subtract(obj, 1);
3205 vm_page_flag_clear(m, PG_ZERO);
3206 vm_page_io_finish(m);
3208 vm_object_pip_wakeupn(obj, 0);
3213 * vfs_page_set_valid:
3215 * Set the valid bits in a page based on the supplied offset. The
3216 * range is restricted to the buffer's size.
3218 * This routine is typically called after a read completes.
3220 static void
3221 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3223 vm_ooffset_t soff, eoff;
3226 * Start and end offsets in buffer. eoff - soff may not cross a
3227 * page boundry or cross the end of the buffer. The end of the
3228 * buffer, in this case, is our file EOF, not the allocation size
3229 * of the buffer.
3231 soff = off;
3232 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3233 if (eoff > bp->b_loffset + bp->b_bcount)
3234 eoff = bp->b_loffset + bp->b_bcount;
3237 * Set valid range. This is typically the entire buffer and thus the
3238 * entire page.
3240 if (eoff > soff) {
3241 vm_page_set_validclean(
3243 (vm_offset_t) (soff & PAGE_MASK),
3244 (vm_offset_t) (eoff - soff)
3250 * vfs_busy_pages:
3252 * This routine is called before a device strategy routine.
3253 * It is used to tell the VM system that paging I/O is in
3254 * progress, and treat the pages associated with the buffer
3255 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3256 * flag is handled to make sure that the object doesn't become
3257 * inconsistant.
3259 * Since I/O has not been initiated yet, certain buffer flags
3260 * such as B_ERROR or B_INVAL may be in an inconsistant state
3261 * and should be ignored.
3263 void
3264 vfs_busy_pages(struct vnode *vp, struct buf *bp)
3266 int i, bogus;
3267 struct lwp *lp = curthread->td_lwp;
3270 * The buffer's I/O command must already be set. If reading,
3271 * B_CACHE must be 0 (double check against callers only doing
3272 * I/O when B_CACHE is 0).
3274 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3275 KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
3277 if (bp->b_flags & B_VMIO) {
3278 vm_object_t obj;
3279 vm_ooffset_t foff;
3281 obj = vp->v_object;
3282 foff = bp->b_loffset;
3283 KASSERT(bp->b_loffset != NOOFFSET,
3284 ("vfs_busy_pages: no buffer offset"));
3285 vfs_setdirty(bp);
3288 * Loop until none of the pages are busy.
3290 retry:
3291 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3292 vm_page_t m = bp->b_xio.xio_pages[i];
3294 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3295 goto retry;
3299 * Setup for I/O, soft-busy the page right now because
3300 * the next loop may block.
3302 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3303 vm_page_t m = bp->b_xio.xio_pages[i];
3305 vm_page_flag_clear(m, PG_ZERO);
3306 if ((bp->b_flags & B_CLUSTER) == 0) {
3307 vm_object_pip_add(obj, 1);
3308 vm_page_io_start(m);
3313 * Adjust protections for I/O and do bogus-page mapping.
3314 * Assume that vm_page_protect() can block (it can block
3315 * if VM_PROT_NONE, don't take any chances regardless).
3317 bogus = 0;
3318 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3319 vm_page_t m = bp->b_xio.xio_pages[i];
3322 * When readying a vnode-backed buffer for a write
3323 * we must zero-fill any invalid portions of the
3324 * backing VM pages.
3326 * When readying a vnode-backed buffer for a read
3327 * we must replace any dirty pages with a bogus
3328 * page so we do not destroy dirty data when
3329 * filling in gaps. Dirty pages might not
3330 * necessarily be marked dirty yet, so use m->valid
3331 * as a reasonable test.
3333 * Bogus page replacement is, uh, bogus. We need
3334 * to find a better way.
3336 if (bp->b_cmd == BUF_CMD_WRITE) {
3337 vm_page_protect(m, VM_PROT_READ);
3338 vfs_page_set_valid(bp, foff, i, m);
3339 } else if (m->valid == VM_PAGE_BITS_ALL) {
3340 bp->b_xio.xio_pages[i] = bogus_page;
3341 bogus++;
3342 } else {
3343 vm_page_protect(m, VM_PROT_NONE);
3345 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3347 if (bogus)
3348 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3349 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3353 * This is the easiest place to put the process accounting for the I/O
3354 * for now.
3356 if (lp != NULL) {
3357 if (bp->b_cmd == BUF_CMD_READ)
3358 lp->lwp_ru.ru_inblock++;
3359 else
3360 lp->lwp_ru.ru_oublock++;
3365 * vfs_clean_pages:
3367 * Tell the VM system that the pages associated with this buffer
3368 * are clean. This is used for delayed writes where the data is
3369 * going to go to disk eventually without additional VM intevention.
3371 * Note that while we only really need to clean through to b_bcount, we
3372 * just go ahead and clean through to b_bufsize.
3374 static void
3375 vfs_clean_pages(struct buf *bp)
3377 int i;
3379 if (bp->b_flags & B_VMIO) {
3380 vm_ooffset_t foff;
3382 foff = bp->b_loffset;
3383 KASSERT(foff != NOOFFSET, ("vfs_clean_pages: no buffer offset"));
3384 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3385 vm_page_t m = bp->b_xio.xio_pages[i];
3386 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3387 vm_ooffset_t eoff = noff;
3389 if (eoff > bp->b_loffset + bp->b_bufsize)
3390 eoff = bp->b_loffset + bp->b_bufsize;
3391 vfs_page_set_valid(bp, foff, i, m);
3392 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3393 foff = noff;
3399 * vfs_bio_set_validclean:
3401 * Set the range within the buffer to valid and clean. The range is
3402 * relative to the beginning of the buffer, b_loffset. Note that
3403 * b_loffset itself may be offset from the beginning of the first page.
3406 void
3407 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3409 if (bp->b_flags & B_VMIO) {
3410 int i;
3411 int n;
3414 * Fixup base to be relative to beginning of first page.
3415 * Set initial n to be the maximum number of bytes in the
3416 * first page that can be validated.
3419 base += (bp->b_loffset & PAGE_MASK);
3420 n = PAGE_SIZE - (base & PAGE_MASK);
3422 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3423 vm_page_t m = bp->b_xio.xio_pages[i];
3425 if (n > size)
3426 n = size;
3428 vm_page_set_validclean(m, base & PAGE_MASK, n);
3429 base += n;
3430 size -= n;
3431 n = PAGE_SIZE;
3437 * vfs_bio_clrbuf:
3439 * Clear a buffer. This routine essentially fakes an I/O, so we need
3440 * to clear B_ERROR and B_INVAL.
3442 * Note that while we only theoretically need to clear through b_bcount,
3443 * we go ahead and clear through b_bufsize.
3446 void
3447 vfs_bio_clrbuf(struct buf *bp)
3449 int i, mask = 0;
3450 caddr_t sa, ea;
3451 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3452 bp->b_flags &= ~(B_INVAL|B_ERROR);
3453 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3454 (bp->b_loffset & PAGE_MASK) == 0) {
3455 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3456 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3457 bp->b_resid = 0;
3458 return;
3460 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3461 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3462 bzero(bp->b_data, bp->b_bufsize);
3463 bp->b_xio.xio_pages[0]->valid |= mask;
3464 bp->b_resid = 0;
3465 return;
3468 ea = sa = bp->b_data;
3469 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3470 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3471 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3472 ea = (caddr_t)(vm_offset_t)ulmin(
3473 (u_long)(vm_offset_t)ea,
3474 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3475 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3476 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3477 continue;
3478 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3479 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3480 bzero(sa, ea - sa);
3482 } else {
3483 for (; sa < ea; sa += DEV_BSIZE, j++) {
3484 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3485 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3486 bzero(sa, DEV_BSIZE);
3489 bp->b_xio.xio_pages[i]->valid |= mask;
3490 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3492 bp->b_resid = 0;
3493 } else {
3494 clrbuf(bp);
3499 * vm_hold_load_pages:
3501 * Load pages into the buffer's address space. The pages are
3502 * allocated from the kernel object in order to reduce interference
3503 * with the any VM paging I/O activity. The range of loaded
3504 * pages will be wired.
3506 * If a page cannot be allocated, the 'pagedaemon' is woken up to
3507 * retrieve the full range (to - from) of pages.
3510 void
3511 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3513 vm_offset_t pg;
3514 vm_page_t p;
3515 int index;
3517 to = round_page(to);
3518 from = round_page(from);
3519 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3521 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3523 tryagain:
3526 * Note: must allocate system pages since blocking here
3527 * could intefere with paging I/O, no matter which
3528 * process we are.
3530 p = vm_page_alloc(&kernel_object,
3531 (pg >> PAGE_SHIFT),
3532 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3533 if (!p) {
3534 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3535 vm_wait();
3536 goto tryagain;
3538 vm_page_wire(p);
3539 p->valid = VM_PAGE_BITS_ALL;
3540 vm_page_flag_clear(p, PG_ZERO);
3541 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3542 bp->b_xio.xio_pages[index] = p;
3543 vm_page_wakeup(p);
3545 bp->b_xio.xio_npages = index;
3549 * vm_hold_free_pages:
3551 * Return pages associated with the buffer back to the VM system.
3553 * The range of pages underlying the buffer's address space will
3554 * be unmapped and un-wired.
3556 void
3557 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3559 vm_offset_t pg;
3560 vm_page_t p;
3561 int index, newnpages;
3563 from = round_page(from);
3564 to = round_page(to);
3565 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3567 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3568 p = bp->b_xio.xio_pages[index];
3569 if (p && (index < bp->b_xio.xio_npages)) {
3570 if (p->busy) {
3571 kprintf("vm_hold_free_pages: doffset: %lld, loffset: %lld\n",
3572 bp->b_bio2.bio_offset, bp->b_loffset);
3574 bp->b_xio.xio_pages[index] = NULL;
3575 pmap_kremove(pg);
3576 vm_page_busy(p);
3577 vm_page_unwire(p, 0);
3578 vm_page_free(p);
3581 bp->b_xio.xio_npages = newnpages;
3585 * vmapbuf:
3587 * Map a user buffer into KVM via a pbuf. On return the buffer's
3588 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array
3589 * initialized.
3592 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
3594 caddr_t addr;
3595 vm_offset_t va;
3596 vm_page_t m;
3597 int vmprot;
3598 int error;
3599 int pidx;
3600 int i;
3603 * bp had better have a command and it better be a pbuf.
3605 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3606 KKASSERT(bp->b_flags & B_PAGING);
3608 if (bytes < 0)
3609 return (-1);
3612 * Map the user data into KVM. Mappings have to be page-aligned.
3614 addr = (caddr_t)trunc_page((vm_offset_t)udata);
3615 pidx = 0;
3617 vmprot = VM_PROT_READ;
3618 if (bp->b_cmd == BUF_CMD_READ)
3619 vmprot |= VM_PROT_WRITE;
3621 while (addr < udata + bytes) {
3623 * Do the vm_fault if needed; do the copy-on-write thing
3624 * when reading stuff off device into memory.
3626 * vm_fault_page*() returns a held VM page.
3628 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
3629 va = trunc_page(va);
3631 m = vm_fault_page_quick(va, vmprot, &error);
3632 if (m == NULL) {
3633 for (i = 0; i < pidx; ++i) {
3634 vm_page_unhold(bp->b_xio.xio_pages[i]);
3635 bp->b_xio.xio_pages[i] = NULL;
3637 return(-1);
3639 bp->b_xio.xio_pages[pidx] = m;
3640 addr += PAGE_SIZE;
3641 ++pidx;
3645 * Map the page array and set the buffer fields to point to
3646 * the mapped data buffer.
3648 if (pidx > btoc(MAXPHYS))
3649 panic("vmapbuf: mapped more than MAXPHYS");
3650 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
3652 bp->b_xio.xio_npages = pidx;
3653 bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
3654 bp->b_bcount = bytes;
3655 bp->b_bufsize = bytes;
3656 return(0);
3660 * vunmapbuf:
3662 * Free the io map PTEs associated with this IO operation.
3663 * We also invalidate the TLB entries and restore the original b_addr.
3665 void
3666 vunmapbuf(struct buf *bp)
3668 int pidx;
3669 int npages;
3671 KKASSERT(bp->b_flags & B_PAGING);
3673 npages = bp->b_xio.xio_npages;
3674 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3675 for (pidx = 0; pidx < npages; ++pidx) {
3676 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
3677 bp->b_xio.xio_pages[pidx] = NULL;
3679 bp->b_xio.xio_npages = 0;
3680 bp->b_data = bp->b_kvabase;
3684 * Scan all buffers in the system and issue the callback.
3687 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
3689 int count = 0;
3690 int error;
3691 int n;
3693 for (n = 0; n < nbuf; ++n) {
3694 if ((error = callback(&buf[n], info)) < 0) {
3695 count = error;
3696 break;
3698 count += error;
3700 return (count);
3704 * print out statistics from the current status of the buffer pool
3705 * this can be toggeled by the system control option debug.syncprt
3707 #ifdef DEBUG
3708 void
3709 vfs_bufstats(void)
3711 int i, j, count;
3712 struct buf *bp;
3713 struct bqueues *dp;
3714 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
3715 static char *bname[3] = { "LOCKED", "LRU", "AGE" };
3717 for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
3718 count = 0;
3719 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3720 counts[j] = 0;
3721 crit_enter();
3722 TAILQ_FOREACH(bp, dp, b_freelist) {
3723 counts[bp->b_bufsize/PAGE_SIZE]++;
3724 count++;
3726 crit_exit();
3727 kprintf("%s: total-%d", bname[i], count);
3728 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3729 if (counts[j] != 0)
3730 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
3731 kprintf("\n");
3734 #endif
3736 #ifdef DDB
3738 DB_SHOW_COMMAND(buffer, db_show_buffer)
3740 /* get args */
3741 struct buf *bp = (struct buf *)addr;
3743 if (!have_addr) {
3744 db_printf("usage: show buffer <addr>\n");
3745 return;
3748 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3749 db_printf("b_cmd = %d\n", bp->b_cmd);
3750 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
3751 "b_resid = %d\n, b_data = %p, "
3752 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
3753 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3754 bp->b_data, bp->b_bio2.bio_offset, (bp->b_bio2.bio_next ? bp->b_bio2.bio_next->bio_offset : (off_t)-1));
3755 if (bp->b_xio.xio_npages) {
3756 int i;
3757 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3758 bp->b_xio.xio_npages);
3759 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3760 vm_page_t m;
3761 m = bp->b_xio.xio_pages[i];
3762 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3763 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3764 if ((i + 1) < bp->b_xio.xio_npages)
3765 db_printf(",");
3767 db_printf("\n");
3770 #endif /* DDB */