FreeBSD/Linux Kernel Cross Reference
sys/kern/vfs_bio.c
1 /*-
2 * Copyright (c) 2004 Poul-Henning Kamp
3 * Copyright (c) 1994,1997 John S. Dyson
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 */
27
28 /*
29 * this file contains a new buffer I/O scheme implementing a coherent
30 * VM object and buffer cache scheme. Pains have been taken to make
31 * sure that the performance degradation associated with schemes such
32 * as this is not realized.
33 *
34 * Author: John S. Dyson
35 * Significant help during the development and debugging phases
36 * had been provided by David Greenman, also of the FreeBSD core team.
37 *
38 * see man buf(9) for more info.
39 */
40
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/bio.h>
47 #include <sys/conf.h>
48 #include <sys/buf.h>
49 #include <sys/devicestat.h>
50 #include <sys/eventhandler.h>
51 #include <sys/fail.h>
52 #include <sys/limits.h>
53 #include <sys/lock.h>
54 #include <sys/malloc.h>
55 #include <sys/mount.h>
56 #include <sys/mutex.h>
57 #include <sys/kernel.h>
58 #include <sys/kthread.h>
59 #include <sys/proc.h>
60 #include <sys/resourcevar.h>
61 #include <sys/sysctl.h>
62 #include <sys/vmmeter.h>
63 #include <sys/vnode.h>
64 #include <geom/geom.h>
65 #include <vm/vm.h>
66 #include <vm/vm_param.h>
67 #include <vm/vm_kern.h>
68 #include <vm/vm_pageout.h>
69 #include <vm/vm_page.h>
70 #include <vm/vm_object.h>
71 #include <vm/vm_extern.h>
72 #include <vm/vm_map.h>
73 #include "opt_directio.h"
74 #include "opt_swap.h"
75
76 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
77
78 struct bio_ops bioops; /* I/O operation notification */
79
80 struct buf_ops buf_ops_bio = {
81 .bop_name = "buf_ops_bio",
82 .bop_write = bufwrite,
83 .bop_strategy = bufstrategy,
84 .bop_sync = bufsync,
85 .bop_bdflush = bufbdflush,
86 };
87
88 /*
89 * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
90 * carnal knowledge of buffers. This knowledge should be moved to vfs_bio.c.
91 */
92 struct buf *buf; /* buffer header pool */
93
94 static struct proc *bufdaemonproc;
95
96 static int inmem(struct vnode *vp, daddr_t blkno);
97 static void vm_hold_free_pages(struct buf *bp, vm_offset_t from,
98 vm_offset_t to);
99 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
100 vm_offset_t to);
101 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
102 int pageno, vm_page_t m);
103 static void vfs_clean_pages(struct buf *bp);
104 static void vfs_setdirty(struct buf *bp);
105 static void vfs_setdirty_locked_object(struct buf *bp);
106 static void vfs_vmio_release(struct buf *bp);
107 static int vfs_bio_clcheck(struct vnode *vp, int size,
108 daddr_t lblkno, daddr_t blkno);
109 static int buf_do_flush(struct vnode *vp);
110 static int flushbufqueues(struct vnode *, int, int);
111 static void buf_daemon(void);
112 static void bremfreel(struct buf *bp);
113 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
114
115 int vmiodirenable = TRUE;
116 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
117 "Use the VM system for directory writes");
118 long runningbufspace;
119 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
120 "Amount of presently outstanding async buffer io");
121 static long bufspace;
122 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
123 &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
124 static long maxbufspace;
125 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
126 "Maximum allowed value of bufspace (including buf_daemon)");
127 static long bufmallocspace;
128 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
129 "Amount of malloced memory for buffers");
130 static long maxbufmallocspace;
131 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
132 "Maximum amount of malloced memory for buffers");
133 static long lobufspace;
134 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
135 "Minimum amount of buffers we want to have");
136 long hibufspace;
137 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
138 "Maximum allowed value of bufspace (excluding buf_daemon)");
139 static int bufreusecnt;
140 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
141 "Number of times we have reused a buffer");
142 static int buffreekvacnt;
143 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
144 "Number of times we have freed the KVA space from some buffer");
145 static int bufdefragcnt;
146 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
147 "Number of times we have had to repeat buffer allocation to defragment");
148 static long lorunningspace;
149 SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
150 "Minimum preferred space used for in-progress I/O");
151 static long hirunningspace;
152 SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
153 "Maximum amount of space to use for in-progress I/O");
154 int dirtybufferflushes;
155 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
156 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
157 int bdwriteskip;
158 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
159 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
160 int altbufferflushes;
161 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
162 0, "Number of fsync flushes to limit dirty buffers");
163 static int recursiveflushes;
164 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
165 0, "Number of flushes skipped due to being recursive");
166 static int numdirtybuffers;
167 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
168 "Number of buffers that are dirty (has unwritten changes) at the moment");
169 static int lodirtybuffers;
170 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
171 "How many buffers we want to have free before bufdaemon can sleep");
172 static int hidirtybuffers;
173 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
174 "When the number of dirty buffers is considered severe");
175 int dirtybufthresh;
176 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
177 0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
178 static int numfreebuffers;
179 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
180 "Number of free buffers");
181 static int lofreebuffers;
182 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
183 "XXX Unused");
184 static int hifreebuffers;
185 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
186 "XXX Complicatedly unused");
187 static int getnewbufcalls;
188 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
189 "Number of calls to getnewbuf");
190 static int getnewbufrestarts;
191 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
192 "Number of times getnewbuf has had to restart a buffer aquisition");
193 static int flushbufqtarget = -1;
194 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
195 "Amount of work to do in flushbufqueues when helping bufdaemon");
196 static long notbufdflashes;
197 SYSCTL_LONG(_vfs, OID_AUTO, notbufdflashes, CTLFLAG_RD, ¬bufdflashes, 0,
198 "Number of dirty buffer flushes done by the bufdaemon helpers");
199
200 /*
201 * Wakeup point for bufdaemon, as well as indicator of whether it is already
202 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
203 * is idling.
204 */
205 static int bd_request;
206
207 /*
208 * This lock synchronizes access to bd_request.
209 */
210 static struct mtx bdlock;
211
212 /*
213 * bogus page -- for I/O to/from partially complete buffers
214 * this is a temporary solution to the problem, but it is not
215 * really that bad. it would be better to split the buffer
216 * for input in the case of buffers partially already in memory,
217 * but the code is intricate enough already.
218 */
219 vm_page_t bogus_page;
220
221 /*
222 * Synchronization (sleep/wakeup) variable for active buffer space requests.
223 * Set when wait starts, cleared prior to wakeup().
224 * Used in runningbufwakeup() and waitrunningbufspace().
225 */
226 static int runningbufreq;
227
228 /*
229 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
230 * waitrunningbufspace().
231 */
232 static struct mtx rbreqlock;
233
234 /*
235 * Synchronization (sleep/wakeup) variable for buffer requests.
236 * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
237 * by and/or.
238 * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
239 * getnewbuf(), and getblk().
240 */
241 static int needsbuffer;
242
243 /*
244 * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
245 */
246 static struct mtx nblock;
247
248 /*
249 * Lock that protects against bwait()/bdone()/B_DONE races.
250 */
251
252 static struct mtx bdonelock;
253
254 /*
255 * Lock that protects against bwait()/bdone()/B_DONE races.
256 */
257 static struct mtx bpinlock;
258
259 /*
260 * Definitions for the buffer free lists.
261 */
262 #define BUFFER_QUEUES 6 /* number of free buffer queues */
263
264 #define QUEUE_NONE 0 /* on no queue */
265 #define QUEUE_CLEAN 1 /* non-B_DELWRI buffers */
266 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
267 #define QUEUE_DIRTY_GIANT 3 /* B_DELWRI buffers that need giant */
268 #define QUEUE_EMPTYKVA 4 /* empty buffer headers w/KVA assignment */
269 #define QUEUE_EMPTY 5 /* empty buffer headers */
270 #define QUEUE_SENTINEL 1024 /* not an queue index, but mark for sentinel */
271
272 /* Queues for free buffers with various properties */
273 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
274
275 /* Lock for the bufqueues */
276 static struct mtx bqlock;
277
278 /*
279 * Single global constant for BUF_WMESG, to avoid getting multiple references.
280 * buf_wmesg is referred from macros.
281 */
282 const char *buf_wmesg = BUF_WMESG;
283
284 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
285 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
286 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
287 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
288
289 static int
290 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
291 {
292 long lvalue;
293 int ivalue;
294
295 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
296 return (sysctl_handle_long(oidp, arg1, arg2, req));
297 lvalue = *(long *)arg1;
298 if (lvalue > INT_MAX)
299 /* On overflow, still write out a long to trigger ENOMEM. */
300 return (sysctl_handle_long(oidp, &lvalue, 0, req));
301 ivalue = lvalue;
302 return (sysctl_handle_int(oidp, &ivalue, 0, req));
303 }
304
305 #ifdef DIRECTIO
306 extern void ffs_rawread_setup(void);
307 #endif /* DIRECTIO */
308 /*
309 * numdirtywakeup:
310 *
311 * If someone is blocked due to there being too many dirty buffers,
312 * and numdirtybuffers is now reasonable, wake them up.
313 */
314
315 static __inline void
316 numdirtywakeup(int level)
317 {
318
319 if (numdirtybuffers <= level) {
320 mtx_lock(&nblock);
321 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
322 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
323 wakeup(&needsbuffer);
324 }
325 mtx_unlock(&nblock);
326 }
327 }
328
329 /*
330 * bufspacewakeup:
331 *
332 * Called when buffer space is potentially available for recovery.
333 * getnewbuf() will block on this flag when it is unable to free
334 * sufficient buffer space. Buffer space becomes recoverable when
335 * bp's get placed back in the queues.
336 */
337
338 static __inline void
339 bufspacewakeup(void)
340 {
341
342 /*
343 * If someone is waiting for BUF space, wake them up. Even
344 * though we haven't freed the kva space yet, the waiting
345 * process will be able to now.
346 */
347 mtx_lock(&nblock);
348 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
349 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
350 wakeup(&needsbuffer);
351 }
352 mtx_unlock(&nblock);
353 }
354
355 /*
356 * runningbufwakeup() - in-progress I/O accounting.
357 *
358 */
359 void
360 runningbufwakeup(struct buf *bp)
361 {
362
363 if (bp->b_runningbufspace) {
364 atomic_subtract_long(&runningbufspace, bp->b_runningbufspace);
365 bp->b_runningbufspace = 0;
366 mtx_lock(&rbreqlock);
367 if (runningbufreq && runningbufspace <= lorunningspace) {
368 runningbufreq = 0;
369 wakeup(&runningbufreq);
370 }
371 mtx_unlock(&rbreqlock);
372 }
373 }
374
375 /*
376 * bufcountwakeup:
377 *
378 * Called when a buffer has been added to one of the free queues to
379 * account for the buffer and to wakeup anyone waiting for free buffers.
380 * This typically occurs when large amounts of metadata are being handled
381 * by the buffer cache ( else buffer space runs out first, usually ).
382 */
383
384 static __inline void
385 bufcountwakeup(void)
386 {
387
388 atomic_add_int(&numfreebuffers, 1);
389 mtx_lock(&nblock);
390 if (needsbuffer) {
391 needsbuffer &= ~VFS_BIO_NEED_ANY;
392 if (numfreebuffers >= hifreebuffers)
393 needsbuffer &= ~VFS_BIO_NEED_FREE;
394 wakeup(&needsbuffer);
395 }
396 mtx_unlock(&nblock);
397 }
398
399 /*
400 * waitrunningbufspace()
401 *
402 * runningbufspace is a measure of the amount of I/O currently
403 * running. This routine is used in async-write situations to
404 * prevent creating huge backups of pending writes to a device.
405 * Only asynchronous writes are governed by this function.
406 *
407 * Reads will adjust runningbufspace, but will not block based on it.
408 * The read load has a side effect of reducing the allowed write load.
409 *
410 * This does NOT turn an async write into a sync write. It waits
411 * for earlier writes to complete and generally returns before the
412 * caller's write has reached the device.
413 */
414 void
415 waitrunningbufspace(void)
416 {
417
418 mtx_lock(&rbreqlock);
419 while (runningbufspace > hirunningspace) {
420 ++runningbufreq;
421 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
422 }
423 mtx_unlock(&rbreqlock);
424 }
425
426
427 /*
428 * vfs_buf_test_cache:
429 *
430 * Called when a buffer is extended. This function clears the B_CACHE
431 * bit if the newly extended portion of the buffer does not contain
432 * valid data.
433 */
434 static __inline
435 void
436 vfs_buf_test_cache(struct buf *bp,
437 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
438 vm_page_t m)
439 {
440
441 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
442 if (bp->b_flags & B_CACHE) {
443 int base = (foff + off) & PAGE_MASK;
444 if (vm_page_is_valid(m, base, size) == 0)
445 bp->b_flags &= ~B_CACHE;
446 }
447 }
448
449 /* Wake up the buffer daemon if necessary */
450 static __inline
451 void
452 bd_wakeup(int dirtybuflevel)
453 {
454
455 mtx_lock(&bdlock);
456 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
457 bd_request = 1;
458 wakeup(&bd_request);
459 }
460 mtx_unlock(&bdlock);
461 }
462
463 /*
464 * bd_speedup - speedup the buffer cache flushing code
465 */
466
467 static __inline
468 void
469 bd_speedup(void)
470 {
471
472 bd_wakeup(1);
473 }
474
475 /*
476 * Calculating buffer cache scaling values and reserve space for buffer
477 * headers. This is called during low level kernel initialization and
478 * may be called more then once. We CANNOT write to the memory area
479 * being reserved at this time.
480 */
481 caddr_t
482 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
483 {
484 int tuned_nbuf;
485 long maxbuf;
486
487 /*
488 * physmem_est is in pages. Convert it to kilobytes (assumes
489 * PAGE_SIZE is >= 1K)
490 */
491 physmem_est = physmem_est * (PAGE_SIZE / 1024);
492
493 /*
494 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
495 * For the first 64MB of ram nominally allocate sufficient buffers to
496 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
497 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
498 * the buffer cache we limit the eventual kva reservation to
499 * maxbcache bytes.
500 *
501 * factor represents the 1/4 x ram conversion.
502 */
503 if (nbuf == 0) {
504 int factor = 4 * BKVASIZE / 1024;
505
506 nbuf = 50;
507 if (physmem_est > 4096)
508 nbuf += min((physmem_est - 4096) / factor,
509 65536 / factor);
510 if (physmem_est > 65536)
511 nbuf += (physmem_est - 65536) * 2 / (factor * 5);
512
513 if (maxbcache && nbuf > maxbcache / BKVASIZE)
514 nbuf = maxbcache / BKVASIZE;
515 tuned_nbuf = 1;
516 } else
517 tuned_nbuf = 0;
518
519 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
520 maxbuf = (LONG_MAX / 3) / BKVASIZE;
521 if (nbuf > maxbuf) {
522 if (!tuned_nbuf)
523 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
524 maxbuf);
525 nbuf = maxbuf;
526 }
527
528 #if 0
529 /*
530 * Do not allow the buffer_map to be more then 1/2 the size of the
531 * kernel_map.
532 */
533 if (nbuf > (kernel_map->max_offset - kernel_map->min_offset) /
534 (BKVASIZE * 2)) {
535 nbuf = (kernel_map->max_offset - kernel_map->min_offset) /
536 (BKVASIZE * 2);
537 printf("Warning: nbufs capped at %d\n", nbuf);
538 }
539 #endif
540
541 /*
542 * swbufs are used as temporary holders for I/O, such as paging I/O.
543 * We have no less then 16 and no more then 256.
544 */
545 nswbuf = max(min(nbuf/4, 256), 16);
546 #ifdef NSWBUF_MIN
547 if (nswbuf < NSWBUF_MIN)
548 nswbuf = NSWBUF_MIN;
549 #endif
550 #ifdef DIRECTIO
551 ffs_rawread_setup();
552 #endif
553
554 /*
555 * Reserve space for the buffer cache buffers
556 */
557 swbuf = (void *)v;
558 v = (caddr_t)(swbuf + nswbuf);
559 buf = (void *)v;
560 v = (caddr_t)(buf + nbuf);
561
562 return(v);
563 }
564
565 /* Initialize the buffer subsystem. Called before use of any buffers. */
566 void
567 bufinit(void)
568 {
569 struct buf *bp;
570 int i;
571
572 mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
573 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
574 mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
575 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
576 mtx_init(&bdonelock, "bdone lock", NULL, MTX_DEF);
577 mtx_init(&bpinlock, "bpin lock", NULL, MTX_DEF);
578
579 /* next, make a null set of free lists */
580 for (i = 0; i < BUFFER_QUEUES; i++)
581 TAILQ_INIT(&bufqueues[i]);
582
583 /* finally, initialize each buffer header and stick on empty q */
584 for (i = 0; i < nbuf; i++) {
585 bp = &buf[i];
586 bzero(bp, sizeof *bp);
587 bp->b_flags = B_INVAL; /* we're just an empty header */
588 bp->b_rcred = NOCRED;
589 bp->b_wcred = NOCRED;
590 bp->b_qindex = QUEUE_EMPTY;
591 bp->b_vflags = 0;
592 bp->b_xflags = 0;
593 LIST_INIT(&bp->b_dep);
594 BUF_LOCKINIT(bp);
595 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
596 }
597
598 /*
599 * maxbufspace is the absolute maximum amount of buffer space we are
600 * allowed to reserve in KVM and in real terms. The absolute maximum
601 * is nominally used by buf_daemon. hibufspace is the nominal maximum
602 * used by most other processes. The differential is required to
603 * ensure that buf_daemon is able to run when other processes might
604 * be blocked waiting for buffer space.
605 *
606 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
607 * this may result in KVM fragmentation which is not handled optimally
608 * by the system.
609 */
610 maxbufspace = (long)nbuf * BKVASIZE;
611 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
612 lobufspace = hibufspace - MAXBSIZE;
613
614 lorunningspace = 512 * 1024;
615 hirunningspace = 1024 * 1024;
616
617 /*
618 * Limit the amount of malloc memory since it is wired permanently into
619 * the kernel space. Even though this is accounted for in the buffer
620 * allocation, we don't want the malloced region to grow uncontrolled.
621 * The malloc scheme improves memory utilization significantly on average
622 * (small) directories.
623 */
624 maxbufmallocspace = hibufspace / 20;
625
626 /*
627 * Reduce the chance of a deadlock occuring by limiting the number
628 * of delayed-write dirty buffers we allow to stack up.
629 */
630 hidirtybuffers = nbuf / 4 + 20;
631 dirtybufthresh = hidirtybuffers * 9 / 10;
632 numdirtybuffers = 0;
633 /*
634 * To support extreme low-memory systems, make sure hidirtybuffers cannot
635 * eat up all available buffer space. This occurs when our minimum cannot
636 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
637 * BKVASIZE'd (8K) buffers.
638 */
639 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
640 hidirtybuffers >>= 1;
641 }
642 lodirtybuffers = hidirtybuffers / 2;
643
644 /*
645 * Try to keep the number of free buffers in the specified range,
646 * and give special processes (e.g. like buf_daemon) access to an
647 * emergency reserve.
648 */
649 lofreebuffers = nbuf / 18 + 5;
650 hifreebuffers = 2 * lofreebuffers;
651 numfreebuffers = nbuf;
652
653 /*
654 * Maximum number of async ops initiated per buf_daemon loop. This is
655 * somewhat of a hack at the moment, we really need to limit ourselves
656 * based on the number of bytes of I/O in-transit that were initiated
657 * from buf_daemon.
658 */
659
660 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
661 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
662 }
663
664 /*
665 * bfreekva() - free the kva allocation for a buffer.
666 *
667 * Since this call frees up buffer space, we call bufspacewakeup().
668 */
669 static void
670 bfreekva(struct buf *bp)
671 {
672
673 if (bp->b_kvasize) {
674 atomic_add_int(&buffreekvacnt, 1);
675 atomic_subtract_long(&bufspace, bp->b_kvasize);
676 vm_map_remove(buffer_map, (vm_offset_t) bp->b_kvabase,
677 (vm_offset_t) bp->b_kvabase + bp->b_kvasize);
678 bp->b_kvasize = 0;
679 bufspacewakeup();
680 }
681 }
682
683 /*
684 * bremfree:
685 *
686 * Mark the buffer for removal from the appropriate free list in brelse.
687 *
688 */
689 void
690 bremfree(struct buf *bp)
691 {
692
693 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
694 KASSERT(BUF_REFCNT(bp), ("bremfree: buf must be locked."));
695 KASSERT((bp->b_flags & B_REMFREE) == 0,
696 ("bremfree: buffer %p already marked for delayed removal.", bp));
697 KASSERT(bp->b_qindex != QUEUE_NONE,
698 ("bremfree: buffer %p not on a queue.", bp));
699
700 bp->b_flags |= B_REMFREE;
701 /* Fixup numfreebuffers count. */
702 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
703 atomic_subtract_int(&numfreebuffers, 1);
704 }
705
706 /*
707 * bremfreef:
708 *
709 * Force an immediate removal from a free list. Used only in nfs when
710 * it abuses the b_freelist pointer.
711 */
712 void
713 bremfreef(struct buf *bp)
714 {
715 mtx_lock(&bqlock);
716 bremfreel(bp);
717 mtx_unlock(&bqlock);
718 }
719
720 /*
721 * bremfreel:
722 *
723 * Removes a buffer from the free list, must be called with the
724 * bqlock held.
725 */
726 static void
727 bremfreel(struct buf *bp)
728 {
729 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
730 bp, bp->b_vp, bp->b_flags);
731 KASSERT(BUF_REFCNT(bp), ("bremfreel: buffer %p not locked.", bp));
732 KASSERT(bp->b_qindex != QUEUE_NONE,
733 ("bremfreel: buffer %p not on a queue.", bp));
734 mtx_assert(&bqlock, MA_OWNED);
735
736 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
737 bp->b_qindex = QUEUE_NONE;
738 /*
739 * If this was a delayed bremfree() we only need to remove the buffer
740 * from the queue and return the stats are already done.
741 */
742 if (bp->b_flags & B_REMFREE) {
743 bp->b_flags &= ~B_REMFREE;
744 return;
745 }
746 /*
747 * Fixup numfreebuffers count. If the buffer is invalid or not
748 * delayed-write, the buffer was free and we must decrement
749 * numfreebuffers.
750 */
751 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
752 atomic_subtract_int(&numfreebuffers, 1);
753 }
754
755
756 /*
757 * Get a buffer with the specified data. Look in the cache first. We
758 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
759 * is set, the buffer is valid and we do not have to do anything ( see
760 * getblk() ). This is really just a special case of breadn().
761 */
762 int
763 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
764 struct buf **bpp)
765 {
766
767 return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp));
768 }
769
770 /*
771 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
772 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
773 * the buffer is valid and we do not have to do anything.
774 */
775 void
776 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
777 int cnt, struct ucred * cred)
778 {
779 struct buf *rabp;
780 int i;
781
782 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
783 if (inmem(vp, *rablkno))
784 continue;
785 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
786
787 if ((rabp->b_flags & B_CACHE) == 0) {
788 if (!TD_IS_IDLETHREAD(curthread))
789 curthread->td_ru.ru_inblock++;
790 rabp->b_flags |= B_ASYNC;
791 rabp->b_flags &= ~B_INVAL;
792 rabp->b_ioflags &= ~BIO_ERROR;
793 rabp->b_iocmd = BIO_READ;
794 if (rabp->b_rcred == NOCRED && cred != NOCRED)
795 rabp->b_rcred = crhold(cred);
796 vfs_busy_pages(rabp, 0);
797 BUF_KERNPROC(rabp);
798 rabp->b_iooffset = dbtob(rabp->b_blkno);
799 bstrategy(rabp);
800 } else {
801 brelse(rabp);
802 }
803 }
804 }
805
806 /*
807 * Operates like bread, but also starts asynchronous I/O on
808 * read-ahead blocks.
809 */
810 int
811 breadn(struct vnode * vp, daddr_t blkno, int size,
812 daddr_t * rablkno, int *rabsize,
813 int cnt, struct ucred * cred, struct buf **bpp)
814 {
815 struct buf *bp;
816 int rv = 0, readwait = 0;
817
818 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
819 *bpp = bp = getblk(vp, blkno, size, 0, 0, 0);
820
821 /* if not found in cache, do some I/O */
822 if ((bp->b_flags & B_CACHE) == 0) {
823 if (!TD_IS_IDLETHREAD(curthread))
824 curthread->td_ru.ru_inblock++;
825 bp->b_iocmd = BIO_READ;
826 bp->b_flags &= ~B_INVAL;
827 bp->b_ioflags &= ~BIO_ERROR;
828 if (bp->b_rcred == NOCRED && cred != NOCRED)
829 bp->b_rcred = crhold(cred);
830 vfs_busy_pages(bp, 0);
831 bp->b_iooffset = dbtob(bp->b_blkno);
832 bstrategy(bp);
833 ++readwait;
834 }
835
836 breada(vp, rablkno, rabsize, cnt, cred);
837
838 if (readwait) {
839 rv = bufwait(bp);
840 }
841 return (rv);
842 }
843
844 /*
845 * Write, release buffer on completion. (Done by iodone
846 * if async). Do not bother writing anything if the buffer
847 * is invalid.
848 *
849 * Note that we set B_CACHE here, indicating that buffer is
850 * fully valid and thus cacheable. This is true even of NFS
851 * now so we set it generally. This could be set either here
852 * or in biodone() since the I/O is synchronous. We put it
853 * here.
854 */
855 int
856 bufwrite(struct buf *bp)
857 {
858 int oldflags;
859 struct vnode *vp;
860 int vp_md;
861
862 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
863 if (bp->b_flags & B_INVAL) {
864 brelse(bp);
865 return (0);
866 }
867
868 oldflags = bp->b_flags;
869
870 if (BUF_REFCNT(bp) == 0)
871 panic("bufwrite: buffer is not busy???");
872
873 if (bp->b_pin_count > 0)
874 bunpin_wait(bp);
875
876 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
877 ("FFS background buffer should not get here %p", bp));
878
879 vp = bp->b_vp;
880 if (vp)
881 vp_md = vp->v_vflag & VV_MD;
882 else
883 vp_md = 0;
884
885 /* Mark the buffer clean */
886 bundirty(bp);
887
888 bp->b_flags &= ~B_DONE;
889 bp->b_ioflags &= ~BIO_ERROR;
890 bp->b_flags |= B_CACHE;
891 bp->b_iocmd = BIO_WRITE;
892
893 bufobj_wref(bp->b_bufobj);
894 vfs_busy_pages(bp, 1);
895
896 /*
897 * Normal bwrites pipeline writes
898 */
899 bp->b_runningbufspace = bp->b_bufsize;
900 atomic_add_long(&runningbufspace, bp->b_runningbufspace);
901
902 if (!TD_IS_IDLETHREAD(curthread))
903 curthread->td_ru.ru_oublock++;
904 if (oldflags & B_ASYNC)
905 BUF_KERNPROC(bp);
906 bp->b_iooffset = dbtob(bp->b_blkno);
907 bstrategy(bp);
908
909 if ((oldflags & B_ASYNC) == 0) {
910 int rtval = bufwait(bp);
911 brelse(bp);
912 return (rtval);
913 } else {
914 /*
915 * don't allow the async write to saturate the I/O
916 * system. We will not deadlock here because
917 * we are blocking waiting for I/O that is already in-progress
918 * to complete. We do not block here if it is the update
919 * or syncer daemon trying to clean up as that can lead
920 * to deadlock.
921 */
922 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
923 waitrunningbufspace();
924 }
925
926 return (0);
927 }
928
929 void
930 bufbdflush(struct bufobj *bo, struct buf *bp)
931 {
932 struct buf *nbp;
933
934 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
935 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
936 altbufferflushes++;
937 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
938 BO_LOCK(bo);
939 /*
940 * Try to find a buffer to flush.
941 */
942 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
943 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
944 BUF_LOCK(nbp,
945 LK_EXCLUSIVE | LK_NOWAIT, NULL))
946 continue;
947 if (bp == nbp)
948 panic("bdwrite: found ourselves");
949 BO_UNLOCK(bo);
950 /* Don't countdeps with the bo lock held. */
951 if (buf_countdeps(nbp, 0)) {
952 BO_LOCK(bo);
953 BUF_UNLOCK(nbp);
954 continue;
955 }
956 if (nbp->b_flags & B_CLUSTEROK) {
957 vfs_bio_awrite(nbp);
958 } else {
959 bremfree(nbp);
960 bawrite(nbp);
961 }
962 dirtybufferflushes++;
963 break;
964 }
965 if (nbp == NULL)
966 BO_UNLOCK(bo);
967 }
968 }
969
970 /*
971 * Delayed write. (Buffer is marked dirty). Do not bother writing
972 * anything if the buffer is marked invalid.
973 *
974 * Note that since the buffer must be completely valid, we can safely
975 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
976 * biodone() in order to prevent getblk from writing the buffer
977 * out synchronously.
978 */
979 void
980 bdwrite(struct buf *bp)
981 {
982 struct thread *td = curthread;
983 struct vnode *vp;
984 struct bufobj *bo;
985
986 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
987 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
988 KASSERT(BUF_REFCNT(bp) != 0, ("bdwrite: buffer is not busy"));
989
990 if (bp->b_flags & B_INVAL) {
991 brelse(bp);
992 return;
993 }
994
995 /*
996 * If we have too many dirty buffers, don't create any more.
997 * If we are wildly over our limit, then force a complete
998 * cleanup. Otherwise, just keep the situation from getting
999 * out of control. Note that we have to avoid a recursive
1000 * disaster and not try to clean up after our own cleanup!
1001 */
1002 vp = bp->b_vp;
1003 bo = bp->b_bufobj;
1004 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1005 td->td_pflags |= TDP_INBDFLUSH;
1006 BO_BDFLUSH(bo, bp);
1007 td->td_pflags &= ~TDP_INBDFLUSH;
1008 } else
1009 recursiveflushes++;
1010
1011 bdirty(bp);
1012 /*
1013 * Set B_CACHE, indicating that the buffer is fully valid. This is
1014 * true even of NFS now.
1015 */
1016 bp->b_flags |= B_CACHE;
1017
1018 /*
1019 * This bmap keeps the system from needing to do the bmap later,
1020 * perhaps when the system is attempting to do a sync. Since it
1021 * is likely that the indirect block -- or whatever other datastructure
1022 * that the filesystem needs is still in memory now, it is a good
1023 * thing to do this. Note also, that if the pageout daemon is
1024 * requesting a sync -- there might not be enough memory to do
1025 * the bmap then... So, this is important to do.
1026 */
1027 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1028 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1029 }
1030
1031 /*
1032 * Set the *dirty* buffer range based upon the VM system dirty pages.
1033 */
1034 vfs_setdirty(bp);
1035
1036 /*
1037 * We need to do this here to satisfy the vnode_pager and the
1038 * pageout daemon, so that it thinks that the pages have been
1039 * "cleaned". Note that since the pages are in a delayed write
1040 * buffer -- the VFS layer "will" see that the pages get written
1041 * out on the next sync, or perhaps the cluster will be completed.
1042 */
1043 vfs_clean_pages(bp);
1044 bqrelse(bp);
1045
1046 /*
1047 * Wakeup the buffer flushing daemon if we have a lot of dirty
1048 * buffers (midpoint between our recovery point and our stall
1049 * point).
1050 */
1051 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1052
1053 /*
1054 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1055 * due to the softdep code.
1056 */
1057 }
1058
1059 /*
1060 * bdirty:
1061 *
1062 * Turn buffer into delayed write request. We must clear BIO_READ and
1063 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
1064 * itself to properly update it in the dirty/clean lists. We mark it
1065 * B_DONE to ensure that any asynchronization of the buffer properly
1066 * clears B_DONE ( else a panic will occur later ).
1067 *
1068 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1069 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
1070 * should only be called if the buffer is known-good.
1071 *
1072 * Since the buffer is not on a queue, we do not update the numfreebuffers
1073 * count.
1074 *
1075 * The buffer must be on QUEUE_NONE.
1076 */
1077 void
1078 bdirty(struct buf *bp)
1079 {
1080
1081 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1082 bp, bp->b_vp, bp->b_flags);
1083 KASSERT(BUF_REFCNT(bp) == 1, ("bdirty: bp %p not locked",bp));
1084 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1085 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1086 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1087 bp->b_flags &= ~(B_RELBUF);
1088 bp->b_iocmd = BIO_WRITE;
1089
1090 if ((bp->b_flags & B_DELWRI) == 0) {
1091 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1092 reassignbuf(bp);
1093 atomic_add_int(&numdirtybuffers, 1);
1094 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1095 }
1096 }
1097
1098 /*
1099 * bundirty:
1100 *
1101 * Clear B_DELWRI for buffer.
1102 *
1103 * Since the buffer is not on a queue, we do not update the numfreebuffers
1104 * count.
1105 *
1106 * The buffer must be on QUEUE_NONE.
1107 */
1108
1109 void
1110 bundirty(struct buf *bp)
1111 {
1112
1113 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1114 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1115 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1116 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1117 KASSERT(BUF_REFCNT(bp) == 1, ("bundirty: bp %p not locked",bp));
1118
1119 if (bp->b_flags & B_DELWRI) {
1120 bp->b_flags &= ~B_DELWRI;
1121 reassignbuf(bp);
1122 atomic_subtract_int(&numdirtybuffers, 1);
1123 numdirtywakeup(lodirtybuffers);
1124 }
1125 /*
1126 * Since it is now being written, we can clear its deferred write flag.
1127 */
1128 bp->b_flags &= ~B_DEFERRED;
1129 }
1130
1131 /*
1132 * bawrite:
1133 *
1134 * Asynchronous write. Start output on a buffer, but do not wait for
1135 * it to complete. The buffer is released when the output completes.
1136 *
1137 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1138 * B_INVAL buffers. Not us.
1139 */
1140 void
1141 bawrite(struct buf *bp)
1142 {
1143
1144 bp->b_flags |= B_ASYNC;
1145 (void) bwrite(bp);
1146 }
1147
1148 /*
1149 * bwillwrite:
1150 *
1151 * Called prior to the locking of any vnodes when we are expecting to
1152 * write. We do not want to starve the buffer cache with too many
1153 * dirty buffers so we block here. By blocking prior to the locking
1154 * of any vnodes we attempt to avoid the situation where a locked vnode
1155 * prevents the various system daemons from flushing related buffers.
1156 */
1157
1158 void
1159 bwillwrite(void)
1160 {
1161
1162 if (numdirtybuffers >= hidirtybuffers) {
1163 mtx_lock(&nblock);
1164 while (numdirtybuffers >= hidirtybuffers) {
1165 bd_wakeup(1);
1166 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1167 msleep(&needsbuffer, &nblock,
1168 (PRIBIO + 4), "flswai", 0);
1169 }
1170 mtx_unlock(&nblock);
1171 }
1172 }
1173
1174 /*
1175 * Return true if we have too many dirty buffers.
1176 */
1177 int
1178 buf_dirty_count_severe(void)
1179 {
1180
1181 return(numdirtybuffers >= hidirtybuffers);
1182 }
1183
1184 static __noinline int
1185 buf_vm_page_count_severe(void)
1186 {
1187
1188 KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1189
1190 return vm_page_count_severe();
1191 }
1192
1193 /*
1194 * brelse:
1195 *
1196 * Release a busy buffer and, if requested, free its resources. The
1197 * buffer will be stashed in the appropriate bufqueue[] allowing it
1198 * to be accessed later as a cache entity or reused for other purposes.
1199 */
1200 void
1201 brelse(struct buf *bp)
1202 {
1203 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1204 bp, bp->b_vp, bp->b_flags);
1205 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1206 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1207
1208 if (bp->b_flags & B_MANAGED) {
1209 bqrelse(bp);
1210 return;
1211 }
1212
1213 if (bp->b_iocmd == BIO_WRITE &&
1214 (bp->b_ioflags & BIO_ERROR) &&
1215 bp->b_error != ENXIO &&
1216 !(bp->b_flags & B_INVAL)) {
1217 /*
1218 * Failed write, redirty. Must clear BIO_ERROR to prevent
1219 * pages from being scrapped. If B_INVAL is set then
1220 * this case is not run and the next case is run to
1221 * destroy the buffer. B_INVAL can occur if the buffer
1222 * is outside the range supported by the underlying device.
1223 * If the error is that the device went away (ENXIO), we
1224 * shouldn't redirty the buffer either, but discard the
1225 * data too.
1226 */
1227 bp->b_ioflags &= ~BIO_ERROR;
1228 bdirty(bp);
1229 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1230 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1231 /*
1232 * Either a failed I/O or we were asked to free or not
1233 * cache the buffer.
1234 */
1235 bp->b_flags |= B_INVAL;
1236 if (!LIST_EMPTY(&bp->b_dep))
1237 buf_deallocate(bp);
1238 if (bp->b_flags & B_DELWRI) {
1239 atomic_subtract_int(&numdirtybuffers, 1);
1240 numdirtywakeup(lodirtybuffers);
1241 }
1242 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1243 if ((bp->b_flags & B_VMIO) == 0) {
1244 if (bp->b_bufsize)
1245 allocbuf(bp, 0);
1246 if (bp->b_vp)
1247 brelvp(bp);
1248 }
1249 }
1250
1251 /*
1252 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1253 * is called with B_DELWRI set, the underlying pages may wind up
1254 * getting freed causing a previous write (bdwrite()) to get 'lost'
1255 * because pages associated with a B_DELWRI bp are marked clean.
1256 *
1257 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1258 * if B_DELWRI is set.
1259 *
1260 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1261 * on pages to return pages to the VM page queues.
1262 */
1263 if (bp->b_flags & B_DELWRI)
1264 bp->b_flags &= ~B_RELBUF;
1265 else if (buf_vm_page_count_severe()) {
1266 /*
1267 * XXX This lock may not be necessary since BKGRDINPROG
1268 * cannot be set while we hold the buf lock, it can only be
1269 * cleared if it is already pending.
1270 */
1271 if (bp->b_vp) {
1272 BO_LOCK(bp->b_bufobj);
1273 if (!(bp->b_vflags & BV_BKGRDINPROG))
1274 bp->b_flags |= B_RELBUF;
1275 BO_UNLOCK(bp->b_bufobj);
1276 } else
1277 bp->b_flags |= B_RELBUF;
1278 }
1279
1280 /*
1281 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1282 * constituted, not even NFS buffers now. Two flags effect this. If
1283 * B_INVAL, the struct buf is invalidated but the VM object is kept
1284 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1285 *
1286 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1287 * invalidated. BIO_ERROR cannot be set for a failed write unless the
1288 * buffer is also B_INVAL because it hits the re-dirtying code above.
1289 *
1290 * Normally we can do this whether a buffer is B_DELWRI or not. If
1291 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1292 * the commit state and we cannot afford to lose the buffer. If the
1293 * buffer has a background write in progress, we need to keep it
1294 * around to prevent it from being reconstituted and starting a second
1295 * background write.
1296 */
1297 if ((bp->b_flags & B_VMIO)
1298 && !(bp->b_vp->v_mount != NULL &&
1299 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1300 !vn_isdisk(bp->b_vp, NULL) &&
1301 (bp->b_flags & B_DELWRI))
1302 ) {
1303
1304 int i, j, resid;
1305 vm_page_t m;
1306 off_t foff;
1307 vm_pindex_t poff;
1308 vm_object_t obj;
1309
1310 obj = bp->b_bufobj->bo_object;
1311
1312 /*
1313 * Get the base offset and length of the buffer. Note that
1314 * in the VMIO case if the buffer block size is not
1315 * page-aligned then b_data pointer may not be page-aligned.
1316 * But our b_pages[] array *IS* page aligned.
1317 *
1318 * block sizes less then DEV_BSIZE (usually 512) are not
1319 * supported due to the page granularity bits (m->valid,
1320 * m->dirty, etc...).
1321 *
1322 * See man buf(9) for more information
1323 */
1324 resid = bp->b_bufsize;
1325 foff = bp->b_offset;
1326 VM_OBJECT_LOCK(obj);
1327 for (i = 0; i < bp->b_npages; i++) {
1328 int had_bogus = 0;
1329
1330 m = bp->b_pages[i];
1331
1332 /*
1333 * If we hit a bogus page, fixup *all* the bogus pages
1334 * now.
1335 */
1336 if (m == bogus_page) {
1337 poff = OFF_TO_IDX(bp->b_offset);
1338 had_bogus = 1;
1339
1340 for (j = i; j < bp->b_npages; j++) {
1341 vm_page_t mtmp;
1342 mtmp = bp->b_pages[j];
1343 if (mtmp == bogus_page) {
1344 mtmp = vm_page_lookup(obj, poff + j);
1345 if (!mtmp) {
1346 panic("brelse: page missing\n");
1347 }
1348 bp->b_pages[j] = mtmp;
1349 }
1350 }
1351
1352 if ((bp->b_flags & B_INVAL) == 0) {
1353 pmap_qenter(
1354 trunc_page((vm_offset_t)bp->b_data),
1355 bp->b_pages, bp->b_npages);
1356 }
1357 m = bp->b_pages[i];
1358 }
1359 if ((bp->b_flags & B_NOCACHE) ||
1360 (bp->b_ioflags & BIO_ERROR &&
1361 bp->b_iocmd == BIO_READ)) {
1362 int poffset = foff & PAGE_MASK;
1363 int presid = resid > (PAGE_SIZE - poffset) ?
1364 (PAGE_SIZE - poffset) : resid;
1365
1366 KASSERT(presid >= 0, ("brelse: extra page"));
1367 vm_page_lock_queues();
1368 vm_page_set_invalid(m, poffset, presid);
1369 vm_page_unlock_queues();
1370 if (had_bogus)
1371 printf("avoided corruption bug in bogus_page/brelse code\n");
1372 }
1373 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1374 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1375 }
1376 VM_OBJECT_UNLOCK(obj);
1377 if (bp->b_flags & (B_INVAL | B_RELBUF))
1378 vfs_vmio_release(bp);
1379
1380 } else if (bp->b_flags & B_VMIO) {
1381
1382 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1383 vfs_vmio_release(bp);
1384 }
1385
1386 } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1387 if (bp->b_bufsize != 0)
1388 allocbuf(bp, 0);
1389 if (bp->b_vp != NULL)
1390 brelvp(bp);
1391 }
1392
1393 if (BUF_REFCNT(bp) > 1) {
1394 /* do not release to free list */
1395 BUF_UNLOCK(bp);
1396 return;
1397 }
1398
1399 /* enqueue */
1400 mtx_lock(&bqlock);
1401 /* Handle delayed bremfree() processing. */
1402 if (bp->b_flags & B_REMFREE)
1403 bremfreel(bp);
1404 if (bp->b_qindex != QUEUE_NONE)
1405 panic("brelse: free buffer onto another queue???");
1406
1407 /* buffers with no memory */
1408 if (bp->b_bufsize == 0) {
1409 bp->b_flags |= B_INVAL;
1410 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1411 if (bp->b_vflags & BV_BKGRDINPROG)
1412 panic("losing buffer 1");
1413 if (bp->b_kvasize) {
1414 bp->b_qindex = QUEUE_EMPTYKVA;
1415 } else {
1416 bp->b_qindex = QUEUE_EMPTY;
1417 }
1418 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1419 /* buffers with junk contents */
1420 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1421 (bp->b_ioflags & BIO_ERROR)) {
1422 bp->b_flags |= B_INVAL;
1423 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1424 if (bp->b_vflags & BV_BKGRDINPROG)
1425 panic("losing buffer 2");
1426 bp->b_qindex = QUEUE_CLEAN;
1427 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1428 /* remaining buffers */
1429 } else {
1430 if ((bp->b_flags & (B_DELWRI|B_NEEDSGIANT)) ==
1431 (B_DELWRI|B_NEEDSGIANT))
1432 bp->b_qindex = QUEUE_DIRTY_GIANT;
1433 else if (bp->b_flags & B_DELWRI)
1434 bp->b_qindex = QUEUE_DIRTY;
1435 else
1436 bp->b_qindex = QUEUE_CLEAN;
1437 if (bp->b_flags & B_AGE)
1438 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1439 else
1440 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1441 }
1442 mtx_unlock(&bqlock);
1443
1444 /*
1445 * If B_INVAL and B_DELWRI is set, clear B_DELWRI. We have already
1446 * placed the buffer on the correct queue. We must also disassociate
1447 * the device and vnode for a B_INVAL buffer so gbincore() doesn't
1448 * find it.
1449 */
1450 if (bp->b_flags & B_INVAL) {
1451 if (bp->b_flags & B_DELWRI)
1452 bundirty(bp);
1453 if (bp->b_vp)
1454 brelvp(bp);
1455 }
1456
1457 /*
1458 * Fixup numfreebuffers count. The bp is on an appropriate queue
1459 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1460 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1461 * if B_INVAL is set ).
1462 */
1463
1464 if (!(bp->b_flags & B_DELWRI))
1465 bufcountwakeup();
1466
1467 /*
1468 * Something we can maybe free or reuse
1469 */
1470 if (bp->b_bufsize || bp->b_kvasize)
1471 bufspacewakeup();
1472
1473 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1474 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1475 panic("brelse: not dirty");
1476 /* unlock */
1477 BUF_UNLOCK(bp);
1478 }
1479
1480 /*
1481 * Release a buffer back to the appropriate queue but do not try to free
1482 * it. The buffer is expected to be used again soon.
1483 *
1484 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1485 * biodone() to requeue an async I/O on completion. It is also used when
1486 * known good buffers need to be requeued but we think we may need the data
1487 * again soon.
1488 *
1489 * XXX we should be able to leave the B_RELBUF hint set on completion.
1490 */
1491 void
1492 bqrelse(struct buf *bp)
1493 {
1494 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1495 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1496 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1497
1498 if (BUF_REFCNT(bp) > 1) {
1499 /* do not release to free list */
1500 BUF_UNLOCK(bp);
1501 return;
1502 }
1503
1504 if (bp->b_flags & B_MANAGED) {
1505 if (bp->b_flags & B_REMFREE) {
1506 mtx_lock(&bqlock);
1507 bremfreel(bp);
1508 mtx_unlock(&bqlock);
1509 }
1510 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1511 BUF_UNLOCK(bp);
1512 return;
1513 }
1514
1515 mtx_lock(&bqlock);
1516 /* Handle delayed bremfree() processing. */
1517 if (bp->b_flags & B_REMFREE)
1518 bremfreel(bp);
1519 if (bp->b_qindex != QUEUE_NONE)
1520 panic("bqrelse: free buffer onto another queue???");
1521 /* buffers with stale but valid contents */
1522 if (bp->b_flags & B_DELWRI) {
1523 if (bp->b_flags & B_NEEDSGIANT)
1524 bp->b_qindex = QUEUE_DIRTY_GIANT;
1525 else
1526 bp->b_qindex = QUEUE_DIRTY;
1527 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1528 } else {
1529 /*
1530 * XXX This lock may not be necessary since BKGRDINPROG
1531 * cannot be set while we hold the buf lock, it can only be
1532 * cleared if it is already pending.
1533 */
1534 BO_LOCK(bp->b_bufobj);
1535 if (!buf_vm_page_count_severe() || bp->b_vflags & BV_BKGRDINPROG) {
1536 BO_UNLOCK(bp->b_bufobj);
1537 bp->b_qindex = QUEUE_CLEAN;
1538 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1539 b_freelist);
1540 } else {
1541 /*
1542 * We are too low on memory, we have to try to free
1543 * the buffer (most importantly: the wired pages
1544 * making up its backing store) *now*.
1545 */
1546 BO_UNLOCK(bp->b_bufobj);
1547 mtx_unlock(&bqlock);
1548 brelse(bp);
1549 return;
1550 }
1551 }
1552 mtx_unlock(&bqlock);
1553
1554 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1555 bufcountwakeup();
1556
1557 /*
1558 * Something we can maybe free or reuse.
1559 */
1560 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1561 bufspacewakeup();
1562
1563 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1564 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1565 panic("bqrelse: not dirty");
1566 /* unlock */
1567 BUF_UNLOCK(bp);
1568 }
1569
1570 /* Give pages used by the bp back to the VM system (where possible) */
1571 static void
1572 vfs_vmio_release(struct buf *bp)
1573 {
1574 int i;
1575 vm_page_t m;
1576
1577 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
1578 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
1579 vm_page_lock_queues();
1580 for (i = 0; i < bp->b_npages; i++) {
1581 m = bp->b_pages[i];
1582 bp->b_pages[i] = NULL;
1583 /*
1584 * In order to keep page LRU ordering consistent, put
1585 * everything on the inactive queue.
1586 */
1587 vm_page_unwire(m, 0);
1588 /*
1589 * We don't mess with busy pages, it is
1590 * the responsibility of the process that
1591 * busied the pages to deal with them.
1592 */
1593 if ((m->oflags & VPO_BUSY) || (m->busy != 0))
1594 continue;
1595
1596 if (m->wire_count == 0) {
1597 /*
1598 * Might as well free the page if we can and it has
1599 * no valid data. We also free the page if the
1600 * buffer was used for direct I/O
1601 */
1602 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1603 m->hold_count == 0) {
1604 vm_page_free(m);
1605 } else if (bp->b_flags & B_DIRECT) {
1606 vm_page_try_to_free(m);
1607 } else if (buf_vm_page_count_severe()) {
1608 vm_page_try_to_cache(m);
1609 }
1610 }
1611 }
1612 vm_page_unlock_queues();
1613 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
1614
1615 if (bp->b_bufsize) {
1616 bufspacewakeup();
1617 bp->b_bufsize = 0;
1618 }
1619 bp->b_npages = 0;
1620 bp->b_flags &= ~B_VMIO;
1621 if (bp->b_vp)
1622 brelvp(bp);
1623 }
1624
1625 /*
1626 * Check to see if a block at a particular lbn is available for a clustered
1627 * write.
1628 */
1629 static int
1630 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1631 {
1632 struct buf *bpa;
1633 int match;
1634
1635 match = 0;
1636
1637 /* If the buf isn't in core skip it */
1638 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1639 return (0);
1640
1641 /* If the buf is busy we don't want to wait for it */
1642 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1643 return (0);
1644
1645 /* Only cluster with valid clusterable delayed write buffers */
1646 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1647 (B_DELWRI | B_CLUSTEROK))
1648 goto done;
1649
1650 if (bpa->b_bufsize != size)
1651 goto done;
1652
1653 /*
1654 * Check to see if it is in the expected place on disk and that the
1655 * block has been mapped.
1656 */
1657 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1658 match = 1;
1659 done:
1660 BUF_UNLOCK(bpa);
1661 return (match);
1662 }
1663
1664 /*
1665 * vfs_bio_awrite:
1666 *
1667 * Implement clustered async writes for clearing out B_DELWRI buffers.
1668 * This is much better then the old way of writing only one buffer at
1669 * a time. Note that we may not be presented with the buffers in the
1670 * correct order, so we search for the cluster in both directions.
1671 */
1672 int
1673 vfs_bio_awrite(struct buf *bp)
1674 {
1675 int i;
1676 int j;
1677 daddr_t lblkno = bp->b_lblkno;
1678 struct vnode *vp = bp->b_vp;
1679 int ncl;
1680 int nwritten;
1681 int size;
1682 int maxcl;
1683
1684 /*
1685 * right now we support clustered writing only to regular files. If
1686 * we find a clusterable block we could be in the middle of a cluster
1687 * rather then at the beginning.
1688 */
1689 if ((vp->v_type == VREG) &&
1690 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1691 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1692
1693 size = vp->v_mount->mnt_stat.f_iosize;
1694 maxcl = MAXPHYS / size;
1695
1696 VI_LOCK(vp);
1697 for (i = 1; i < maxcl; i++)
1698 if (vfs_bio_clcheck(vp, size, lblkno + i,
1699 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1700 break;
1701
1702 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1703 if (vfs_bio_clcheck(vp, size, lblkno - j,
1704 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1705 break;
1706
1707 VI_UNLOCK(vp);
1708 --j;
1709 ncl = i + j;
1710 /*
1711 * this is a possible cluster write
1712 */
1713 if (ncl != 1) {
1714 BUF_UNLOCK(bp);
1715 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1716 return nwritten;
1717 }
1718 }
1719 bremfree(bp);
1720 bp->b_flags |= B_ASYNC;
1721 /*
1722 * default (old) behavior, writing out only one block
1723 *
1724 * XXX returns b_bufsize instead of b_bcount for nwritten?
1725 */
1726 nwritten = bp->b_bufsize;
1727 (void) bwrite(bp);
1728
1729 return nwritten;
1730 }
1731
1732 /*
1733 * getnewbuf:
1734 *
1735 * Find and initialize a new buffer header, freeing up existing buffers
1736 * in the bufqueues as necessary. The new buffer is returned locked.
1737 *
1738 * Important: B_INVAL is not set. If the caller wishes to throw the
1739 * buffer away, the caller must set B_INVAL prior to calling brelse().
1740 *
1741 * We block if:
1742 * We have insufficient buffer headers
1743 * We have insufficient buffer space
1744 * buffer_map is too fragmented ( space reservation fails )
1745 * If we have to flush dirty buffers ( but we try to avoid this )
1746 *
1747 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1748 * Instead we ask the buf daemon to do it for us. We attempt to
1749 * avoid piecemeal wakeups of the pageout daemon.
1750 */
1751
1752 static struct buf *
1753 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
1754 int gbflags)
1755 {
1756 struct thread *td;
1757 struct buf *bp;
1758 struct buf *nbp;
1759 int defrag = 0;
1760 int nqindex;
1761 static int flushingbufs;
1762
1763 td = curthread;
1764 /*
1765 * We can't afford to block since we might be holding a vnode lock,
1766 * which may prevent system daemons from running. We deal with
1767 * low-memory situations by proactively returning memory and running
1768 * async I/O rather then sync I/O.
1769 */
1770 atomic_add_int(&getnewbufcalls, 1);
1771 atomic_subtract_int(&getnewbufrestarts, 1);
1772 restart:
1773 atomic_add_int(&getnewbufrestarts, 1);
1774
1775 /*
1776 * Setup for scan. If we do not have enough free buffers,
1777 * we setup a degenerate case that immediately fails. Note
1778 * that if we are specially marked process, we are allowed to
1779 * dip into our reserves.
1780 *
1781 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1782 *
1783 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1784 * However, there are a number of cases (defragging, reusing, ...)
1785 * where we cannot backup.
1786 */
1787 mtx_lock(&bqlock);
1788 nqindex = QUEUE_EMPTYKVA;
1789 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1790
1791 if (nbp == NULL) {
1792 /*
1793 * If no EMPTYKVA buffers and we are either
1794 * defragging or reusing, locate a CLEAN buffer
1795 * to free or reuse. If bufspace useage is low
1796 * skip this step so we can allocate a new buffer.
1797 */
1798 if (defrag || bufspace >= lobufspace) {
1799 nqindex = QUEUE_CLEAN;
1800 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1801 }
1802
1803 /*
1804 * If we could not find or were not allowed to reuse a
1805 * CLEAN buffer, check to see if it is ok to use an EMPTY
1806 * buffer. We can only use an EMPTY buffer if allocating
1807 * its KVA would not otherwise run us out of buffer space.
1808 */
1809 if (nbp == NULL && defrag == 0 &&
1810 bufspace + maxsize < hibufspace) {
1811 nqindex = QUEUE_EMPTY;
1812 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1813 }
1814 }
1815
1816 /*
1817 * Run scan, possibly freeing data and/or kva mappings on the fly
1818 * depending.
1819 */
1820
1821 while ((bp = nbp) != NULL) {
1822 int qindex = nqindex;
1823
1824 /*
1825 * Calculate next bp ( we can only use it if we do not block
1826 * or do other fancy things ).
1827 */
1828 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1829 switch(qindex) {
1830 case QUEUE_EMPTY:
1831 nqindex = QUEUE_EMPTYKVA;
1832 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1833 break;
1834 /* FALLTHROUGH */
1835 case QUEUE_EMPTYKVA:
1836 nqindex = QUEUE_CLEAN;
1837 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1838 break;
1839 /* FALLTHROUGH */
1840 case QUEUE_CLEAN:
1841 /*
1842 * nbp is NULL.
1843 */
1844 break;
1845 }
1846 }
1847 /*
1848 * If we are defragging then we need a buffer with
1849 * b_kvasize != 0. XXX this situation should no longer
1850 * occur, if defrag is non-zero the buffer's b_kvasize
1851 * should also be non-zero at this point. XXX
1852 */
1853 if (defrag && bp->b_kvasize == 0) {
1854 printf("Warning: defrag empty buffer %p\n", bp);
1855 continue;
1856 }
1857
1858 /*
1859 * Start freeing the bp. This is somewhat involved. nbp
1860 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1861 */
1862 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1863 continue;
1864 if (bp->b_vp) {
1865 BO_LOCK(bp->b_bufobj);
1866 if (bp->b_vflags & BV_BKGRDINPROG) {
1867 BO_UNLOCK(bp->b_bufobj);
1868 BUF_UNLOCK(bp);
1869 continue;
1870 }
1871 BO_UNLOCK(bp->b_bufobj);
1872 }
1873 CTR6(KTR_BUF,
1874 "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
1875 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
1876 bp->b_kvasize, bp->b_bufsize, qindex);
1877
1878 /*
1879 * Sanity Checks
1880 */
1881 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1882
1883 /*
1884 * Note: we no longer distinguish between VMIO and non-VMIO
1885 * buffers.
1886 */
1887
1888 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1889
1890 bremfreel(bp);
1891 mtx_unlock(&bqlock);
1892
1893 if (qindex == QUEUE_CLEAN) {
1894 if (bp->b_flags & B_VMIO) {
1895 bp->b_flags &= ~B_ASYNC;
1896 vfs_vmio_release(bp);
1897 }
1898 if (bp->b_vp)
1899 brelvp(bp);
1900 }
1901
1902 /*
1903 * NOTE: nbp is now entirely invalid. We can only restart
1904 * the scan from this point on.
1905 *
1906 * Get the rest of the buffer freed up. b_kva* is still
1907 * valid after this operation.
1908 */
1909
1910 if (bp->b_rcred != NOCRED) {
1911 crfree(bp->b_rcred);
1912 bp->b_rcred = NOCRED;
1913 }
1914 if (bp->b_wcred != NOCRED) {
1915 crfree(bp->b_wcred);
1916 bp->b_wcred = NOCRED;
1917 }
1918 if (!LIST_EMPTY(&bp->b_dep))
1919 buf_deallocate(bp);
1920 if (bp->b_vflags & BV_BKGRDINPROG)
1921 panic("losing buffer 3");
1922 KASSERT(bp->b_vp == NULL,
1923 ("bp: %p still has vnode %p. qindex: %d",
1924 bp, bp->b_vp, qindex));
1925 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1926 ("bp: %p still on a buffer list. xflags %X",
1927 bp, bp->b_xflags));
1928
1929 if (bp->b_bufsize)
1930 allocbuf(bp, 0);
1931
1932 bp->b_flags = 0;
1933 bp->b_ioflags = 0;
1934 bp->b_xflags = 0;
1935 bp->b_vflags = 0;
1936 bp->b_vp = NULL;
1937 bp->b_blkno = bp->b_lblkno = 0;
1938 bp->b_offset = NOOFFSET;
1939 bp->b_iodone = 0;
1940 bp->b_error = 0;
1941 bp->b_resid = 0;
1942 bp->b_bcount = 0;
1943 bp->b_npages = 0;
1944 bp->b_dirtyoff = bp->b_dirtyend = 0;
1945 bp->b_bufobj = NULL;
1946 bp->b_pin_count = 0;
1947 bp->b_fsprivate1 = NULL;
1948 bp->b_fsprivate2 = NULL;
1949 bp->b_fsprivate3 = NULL;
1950
1951 LIST_INIT(&bp->b_dep);
1952
1953 /*
1954 * If we are defragging then free the buffer.
1955 */
1956 if (defrag) {
1957 bp->b_flags |= B_INVAL;
1958 bfreekva(bp);
1959 brelse(bp);
1960 defrag = 0;
1961 goto restart;
1962 }
1963
1964 /*
1965 * Notify any waiters for the buffer lock about
1966 * identity change by freeing the buffer.
1967 */
1968 if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp) > 0) {
1969 bp->b_flags |= B_INVAL;
1970 bfreekva(bp);
1971 brelse(bp);
1972 goto restart;
1973 }
1974
1975 /*
1976 * If we are overcomitted then recover the buffer and its
1977 * KVM space. This occurs in rare situations when multiple
1978 * processes are blocked in getnewbuf() or allocbuf().
1979 */
1980 if (bufspace >= hibufspace)
1981 flushingbufs = 1;
1982 if (flushingbufs && bp->b_kvasize != 0) {
1983 bp->b_flags |= B_INVAL;
1984 bfreekva(bp);
1985 brelse(bp);
1986 goto restart;
1987 }
1988 if (bufspace < lobufspace)
1989 flushingbufs = 0;
1990 break;
1991 }
1992
1993 /*
1994 * If we exhausted our list, sleep as appropriate. We may have to
1995 * wakeup various daemons and write out some dirty buffers.
1996 *
1997 * Generally we are sleeping due to insufficient buffer space.
1998 */
1999
2000 if (bp == NULL) {
2001 int flags, norunbuf;
2002 char *waitmsg;
2003 int fl;
2004
2005 if (defrag) {
2006 flags = VFS_BIO_NEED_BUFSPACE;
2007 waitmsg = "nbufkv";
2008 } else if (bufspace >= hibufspace) {
2009 waitmsg = "nbufbs";
2010 flags = VFS_BIO_NEED_BUFSPACE;
2011 } else {
2012 waitmsg = "newbuf";
2013 flags = VFS_BIO_NEED_ANY;
2014 }
2015 mtx_lock(&nblock);
2016 needsbuffer |= flags;
2017 mtx_unlock(&nblock);
2018 mtx_unlock(&bqlock);
2019
2020 bd_speedup(); /* heeeelp */
2021 if (gbflags & GB_NOWAIT_BD)
2022 return (NULL);
2023
2024 mtx_lock(&nblock);
2025 while (needsbuffer & flags) {
2026 if (vp != NULL && (td->td_pflags & TDP_BUFNEED) == 0) {
2027 mtx_unlock(&nblock);
2028 /*
2029 * getblk() is called with a vnode
2030 * locked, and some majority of the
2031 * dirty buffers may as well belong to
2032 * the vnode. Flushing the buffers
2033 * there would make a progress that
2034 * cannot be achieved by the
2035 * buf_daemon, that cannot lock the
2036 * vnode.
2037 */
2038 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
2039 (td->td_pflags & TDP_NORUNNINGBUF);
2040 /* play bufdaemon */
2041 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
2042 fl = buf_do_flush(vp);
2043 td->td_pflags &= norunbuf;
2044 mtx_lock(&nblock);
2045 if (fl != 0)
2046 continue;
2047 if ((needsbuffer & flags) == 0)
2048 break;
2049 }
2050 if (msleep(&needsbuffer, &nblock,
2051 (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
2052 mtx_unlock(&nblock);
2053 return (NULL);
2054 }
2055 }
2056 mtx_unlock(&nblock);
2057 } else {
2058 /*
2059 * We finally have a valid bp. We aren't quite out of the
2060 * woods, we still have to reserve kva space. In order
2061 * to keep fragmentation sane we only allocate kva in
2062 * BKVASIZE chunks.
2063 */
2064 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2065
2066 if (maxsize != bp->b_kvasize) {
2067 vm_offset_t addr = 0;
2068
2069 bfreekva(bp);
2070
2071 vm_map_lock(buffer_map);
2072 if (vm_map_findspace(buffer_map,
2073 vm_map_min(buffer_map), maxsize, &addr)) {
2074 /*
2075 * Uh oh. Buffer map is to fragmented. We
2076 * must defragment the map.
2077 */
2078 atomic_add_int(&bufdefragcnt, 1);
2079 vm_map_unlock(buffer_map);
2080 defrag = 1;
2081 bp->b_flags |= B_INVAL;
2082 brelse(bp);
2083 goto restart;
2084 }
2085 if (addr) {
2086 vm_map_insert(buffer_map, NULL, 0,
2087 addr, addr + maxsize,
2088 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
2089
2090 bp->b_kvabase = (caddr_t) addr;
2091 bp->b_kvasize = maxsize;
2092 atomic_add_long(&bufspace, bp->b_kvasize);
2093 atomic_add_int(&bufreusecnt, 1);
2094 }
2095 vm_map_unlock(buffer_map);
2096 }
2097 bp->b_saveaddr = bp->b_kvabase;
2098 bp->b_data = bp->b_saveaddr;
2099 }
2100 return(bp);
2101 }
2102
2103 /*
2104 * buf_daemon:
2105 *
2106 * buffer flushing daemon. Buffers are normally flushed by the
2107 * update daemon but if it cannot keep up this process starts to
2108 * take the load in an attempt to prevent getnewbuf() from blocking.
2109 */
2110
2111 static struct kproc_desc buf_kp = {
2112 "bufdaemon",
2113 buf_daemon,
2114 &bufdaemonproc
2115 };
2116 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2117
2118 static int
2119 buf_do_flush(struct vnode *vp)
2120 {
2121 int flushed;
2122
2123 flushed = flushbufqueues(vp, QUEUE_DIRTY, 0);
2124 /* The list empty check here is slightly racy */
2125 if (!TAILQ_EMPTY(&bufqueues[QUEUE_DIRTY_GIANT])) {
2126 mtx_lock(&Giant);
2127 flushed += flushbufqueues(vp, QUEUE_DIRTY_GIANT, 0);
2128 mtx_unlock(&Giant);
2129 }
2130 if (flushed == 0) {
2131 /*
2132 * Could not find any buffers without rollback
2133 * dependencies, so just write the first one
2134 * in the hopes of eventually making progress.
2135 */
2136 flushbufqueues(vp, QUEUE_DIRTY, 1);
2137 if (!TAILQ_EMPTY(
2138 &bufqueues[QUEUE_DIRTY_GIANT])) {
2139 mtx_lock(&Giant);
2140 flushbufqueues(vp, QUEUE_DIRTY_GIANT, 1);
2141 mtx_unlock(&Giant);
2142 }
2143 }
2144 return (flushed);
2145 }
2146
2147 static void
2148 buf_daemon()
2149 {
2150
2151 /*
2152 * This process needs to be suspended prior to shutdown sync.
2153 */
2154 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2155 SHUTDOWN_PRI_LAST);
2156
2157 /*
2158 * This process is allowed to take the buffer cache to the limit
2159 */
2160 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2161 mtx_lock(&bdlock);
2162 for (;;) {
2163 bd_request = 0;
2164 mtx_unlock(&bdlock);
2165
2166 kthread_suspend_check(bufdaemonproc);
2167
2168 /*
2169 * Do the flush. Limit the amount of in-transit I/O we
2170 * allow to build up, otherwise we would completely saturate
2171 * the I/O system. Wakeup any waiting processes before we
2172 * normally would so they can run in parallel with our drain.
2173 */
2174 while (numdirtybuffers > lodirtybuffers) {
2175 if (buf_do_flush(NULL) == 0)
2176 break;
2177 uio_yield();
2178 }
2179
2180 /*
2181 * Only clear bd_request if we have reached our low water
2182 * mark. The buf_daemon normally waits 1 second and
2183 * then incrementally flushes any dirty buffers that have
2184 * built up, within reason.
2185 *
2186 * If we were unable to hit our low water mark and couldn't
2187 * find any flushable buffers, we sleep half a second.
2188 * Otherwise we loop immediately.
2189 */
2190 mtx_lock(&bdlock);
2191 if (numdirtybuffers <= lodirtybuffers) {
2192 /*
2193 * We reached our low water mark, reset the
2194 * request and sleep until we are needed again.
2195 * The sleep is just so the suspend code works.
2196 */
2197 bd_request = 0;
2198 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2199 } else {
2200 /*
2201 * We couldn't find any flushable dirty buffers but
2202 * still have too many dirty buffers, we
2203 * have to sleep and try again. (rare)
2204 */
2205 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2206 }
2207 }
2208 }
2209
2210 /*
2211 * flushbufqueues:
2212 *
2213 * Try to flush a buffer in the dirty queue. We must be careful to
2214 * free up B_INVAL buffers instead of write them, which NFS is
2215 * particularly sensitive to.
2216 */
2217 static int flushwithdeps = 0;
2218 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2219 0, "Number of buffers flushed with dependecies that require rollbacks");
2220
2221 static int
2222 flushbufqueues(struct vnode *lvp, int queue, int flushdeps)
2223 {
2224 struct thread *td = curthread;
2225 struct buf *sentinel;
2226 struct vnode *vp;
2227 struct mount *mp;
2228 struct buf *bp;
2229 int hasdeps;
2230 int flushed;
2231 int target;
2232
2233 if (lvp == NULL) {
2234 target = numdirtybuffers - lodirtybuffers;
2235 if (flushdeps && target > 2)
2236 target /= 2;
2237 } else
2238 target = flushbufqtarget;
2239 flushed = 0;
2240 bp = NULL;
2241 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2242 sentinel->b_qindex = QUEUE_SENTINEL;
2243 mtx_lock(&bqlock);
2244 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2245 while (flushed != target) {
2246 bp = TAILQ_NEXT(sentinel, b_freelist);
2247 if (bp != NULL) {
2248 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2249 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2250 b_freelist);
2251 } else
2252 break;
2253 /*
2254 * Skip sentinels inserted by other invocations of the
2255 * flushbufqueues(), taking care to not reorder them.
2256 */
2257 if (bp->b_qindex == QUEUE_SENTINEL)
2258 continue;
2259 /*
2260 * Only flush the buffers that belong to the
2261 * vnode locked by the curthread.
2262 */
2263 if (lvp != NULL && bp->b_vp != lvp)
2264 continue;
2265 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2266 continue;
2267 if (bp->b_pin_count > 0) {
2268 BUF_UNLOCK(bp);
2269 continue;
2270 }
2271 BO_LOCK(bp->b_bufobj);
2272 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2273 (bp->b_flags & B_DELWRI) == 0) {
2274 BO_UNLOCK(bp->b_bufobj);
2275 BUF_UNLOCK(bp);
2276 continue;
2277 }
2278 BO_UNLOCK(bp->b_bufobj);
2279 if (bp->b_flags & B_INVAL) {
2280 bremfreel(bp);
2281 mtx_unlock(&bqlock);
2282 brelse(bp);
2283 flushed++;
2284 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2285 mtx_lock(&bqlock);
2286 continue;
2287 }
2288
2289 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2290 if (flushdeps == 0) {
2291 BUF_UNLOCK(bp);
2292 continue;
2293 }
2294 hasdeps = 1;
2295 } else
2296 hasdeps = 0;
2297 /*
2298 * We must hold the lock on a vnode before writing
2299 * one of its buffers. Otherwise we may confuse, or
2300 * in the case of a snapshot vnode, deadlock the
2301 * system.
2302 *
2303 * The lock order here is the reverse of the normal
2304 * of vnode followed by buf lock. This is ok because
2305 * the NOWAIT will prevent deadlock.
2306 */
2307 vp = bp->b_vp;
2308 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2309 BUF_UNLOCK(bp);
2310 continue;
2311 }
2312 if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_CANRECURSE,
2313 td) == 0) {
2314 mtx_unlock(&bqlock);
2315 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2316 bp, bp->b_vp, bp->b_flags);
2317 if (curproc == bufdaemonproc)
2318 vfs_bio_awrite(bp);
2319 else {
2320 bremfree(bp);
2321 bwrite(bp);
2322 notbufdflashes++;
2323 }
2324 vn_finished_write(mp);
2325 VOP_UNLOCK(vp, 0, td);
2326 flushwithdeps += hasdeps;
2327 flushed++;
2328
2329 /*
2330 * Sleeping on runningbufspace while holding
2331 * vnode lock leads to deadlock.
2332 */
2333 if (curproc == bufdaemonproc)
2334 waitrunningbufspace();
2335 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2336 mtx_lock(&bqlock);
2337 continue;
2338 }
2339 vn_finished_write(mp);
2340 BUF_UNLOCK(bp);
2341 }
2342 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2343 mtx_unlock(&bqlock);
2344 free(sentinel, M_TEMP);
2345 return (flushed);
2346 }
2347
2348 /*
2349 * Check to see if a block is currently memory resident.
2350 */
2351 struct buf *
2352 incore(struct bufobj *bo, daddr_t blkno)
2353 {
2354 struct buf *bp;
2355
2356 BO_LOCK(bo);
2357 bp = gbincore(bo, blkno);
2358 BO_UNLOCK(bo);
2359 return (bp);
2360 }
2361
2362 /*
2363 * Returns true if no I/O is needed to access the
2364 * associated VM object. This is like incore except
2365 * it also hunts around in the VM system for the data.
2366 */
2367
2368 static int
2369 inmem(struct vnode * vp, daddr_t blkno)
2370 {
2371 vm_object_t obj;
2372 vm_offset_t toff, tinc, size;
2373 vm_page_t m;
2374 vm_ooffset_t off;
2375
2376 ASSERT_VOP_LOCKED(vp, "inmem");
2377
2378 if (incore(&vp->v_bufobj, blkno))
2379 return 1;
2380 if (vp->v_mount == NULL)
2381 return 0;
2382 obj = vp->v_object;
2383 if (obj == NULL)
2384 return (0);
2385
2386 size = PAGE_SIZE;
2387 if (size > vp->v_mount->mnt_stat.f_iosize)
2388 size = vp->v_mount->mnt_stat.f_iosize;
2389 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2390
2391 VM_OBJECT_LOCK(obj);
2392 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2393 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2394 if (!m)
2395 goto notinmem;
2396 tinc = size;
2397 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2398 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2399 if (vm_page_is_valid(m,
2400 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2401 goto notinmem;
2402 }
2403 VM_OBJECT_UNLOCK(obj);
2404 return 1;
2405
2406 notinmem:
2407 VM_OBJECT_UNLOCK(obj);
2408 return (0);
2409 }
2410
2411 /*
2412 * vfs_setdirty:
2413 *
2414 * Sets the dirty range for a buffer based on the status of the dirty
2415 * bits in the pages comprising the buffer.
2416 *
2417 * The range is limited to the size of the buffer.
2418 *
2419 * This routine is primarily used by NFS, but is generalized for the
2420 * B_VMIO case.
2421 */
2422 static void
2423 vfs_setdirty(struct buf *bp)
2424 {
2425
2426 /*
2427 * Degenerate case - empty buffer
2428 */
2429
2430 if (bp->b_bufsize == 0)
2431 return;
2432
2433 /*
2434 * We qualify the scan for modified pages on whether the
2435 * object has been flushed yet.
2436 */
2437
2438 if ((bp->b_flags & B_VMIO) == 0)
2439 return;
2440
2441 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2442 vfs_setdirty_locked_object(bp);
2443 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2444 }
2445
2446 static void
2447 vfs_setdirty_locked_object(struct buf *bp)
2448 {
2449 vm_object_t object;
2450 int i;
2451
2452 object = bp->b_bufobj->bo_object;
2453 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2454 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2455 vm_offset_t boffset;
2456 vm_offset_t eoffset;
2457
2458 vm_page_lock_queues();
2459 /*
2460 * test the pages to see if they have been modified directly
2461 * by users through the VM system.
2462 */
2463 for (i = 0; i < bp->b_npages; i++)
2464 vm_page_test_dirty(bp->b_pages[i]);
2465
2466 /*
2467 * Calculate the encompassing dirty range, boffset and eoffset,
2468 * (eoffset - boffset) bytes.
2469 */
2470
2471 for (i = 0; i < bp->b_npages; i++) {
2472 if (bp->b_pages[i]->dirty)
2473 break;
2474 }
2475 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2476
2477 for (i = bp->b_npages - 1; i >= 0; --i) {
2478 if (bp->b_pages[i]->dirty) {
2479 break;
2480 }
2481 }
2482 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2483
2484 vm_page_unlock_queues();
2485 /*
2486 * Fit it to the buffer.
2487 */
2488
2489 if (eoffset > bp->b_bcount)
2490 eoffset = bp->b_bcount;
2491
2492 /*
2493 * If we have a good dirty range, merge with the existing
2494 * dirty range.
2495 */
2496
2497 if (boffset < eoffset) {
2498 if (bp->b_dirtyoff > boffset)
2499 bp->b_dirtyoff = boffset;
2500 if (bp->b_dirtyend < eoffset)
2501 bp->b_dirtyend = eoffset;
2502 }
2503 }
2504 }
2505
2506 /*
2507 * getblk:
2508 *
2509 * Get a block given a specified block and offset into a file/device.
2510 * The buffers B_DONE bit will be cleared on return, making it almost
2511 * ready for an I/O initiation. B_INVAL may or may not be set on
2512 * return. The caller should clear B_INVAL prior to initiating a
2513 * READ.
2514 *
2515 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2516 * an existing buffer.
2517 *
2518 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2519 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2520 * and then cleared based on the backing VM. If the previous buffer is
2521 * non-0-sized but invalid, B_CACHE will be cleared.
2522 *
2523 * If getblk() must create a new buffer, the new buffer is returned with
2524 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2525 * case it is returned with B_INVAL clear and B_CACHE set based on the
2526 * backing VM.
2527 *
2528 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2529 * B_CACHE bit is clear.
2530 *
2531 * What this means, basically, is that the caller should use B_CACHE to
2532 * determine whether the buffer is fully valid or not and should clear
2533 * B_INVAL prior to issuing a read. If the caller intends to validate
2534 * the buffer by loading its data area with something, the caller needs
2535 * to clear B_INVAL. If the caller does this without issuing an I/O,
2536 * the caller should set B_CACHE ( as an optimization ), else the caller
2537 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2538 * a write attempt or if it was a successfull read. If the caller
2539 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2540 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2541 */
2542 struct buf *
2543 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2544 int flags)
2545 {
2546 struct buf *bp;
2547 struct bufobj *bo;
2548 int error;
2549
2550 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
2551 ASSERT_VOP_LOCKED(vp, "getblk");
2552 if (size > MAXBSIZE)
2553 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2554
2555 bo = &vp->v_bufobj;
2556 loop:
2557 /*
2558 * Block if we are low on buffers. Certain processes are allowed
2559 * to completely exhaust the buffer cache.
2560 *
2561 * If this check ever becomes a bottleneck it may be better to
2562 * move it into the else, when gbincore() fails. At the moment
2563 * it isn't a problem.
2564 *
2565 * XXX remove if 0 sections (clean this up after its proven)
2566 */
2567 if (numfreebuffers == 0) {
2568 if (TD_IS_IDLETHREAD(curthread))
2569 return NULL;
2570 mtx_lock(&nblock);
2571 needsbuffer |= VFS_BIO_NEED_ANY;
2572 mtx_unlock(&nblock);
2573 }
2574
2575 BO_LOCK(bo);
2576 bp = gbincore(bo, blkno);
2577 if (bp != NULL) {
2578 int lockflags;
2579 /*
2580 * Buffer is in-core. If the buffer is not busy, it must
2581 * be on a queue.
2582 */
2583 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2584
2585 if (flags & GB_LOCK_NOWAIT)
2586 lockflags |= LK_NOWAIT;
2587
2588 error = BUF_TIMELOCK(bp, lockflags,
2589 VI_MTX(vp), "getblk", slpflag, slptimeo);
2590
2591 /*
2592 * If we slept and got the lock we have to restart in case
2593 * the buffer changed identities.
2594 */
2595 if (error == ENOLCK)
2596 goto loop;
2597 /* We timed out or were interrupted. */
2598 else if (error)
2599 return (NULL);
2600
2601 /*
2602 * The buffer is locked. B_CACHE is cleared if the buffer is
2603 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
2604 * and for a VMIO buffer B_CACHE is adjusted according to the
2605 * backing VM cache.
2606 */
2607 if (bp->b_flags & B_INVAL)
2608 bp->b_flags &= ~B_CACHE;
2609 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2610 bp->b_flags |= B_CACHE;
2611 bremfree(bp);
2612
2613 /*
2614 * check for size inconsistancies for non-VMIO case.
2615 */
2616
2617 if (bp->b_bcount != size) {
2618 if ((bp->b_flags & B_VMIO) == 0 ||
2619 (size > bp->b_kvasize)) {
2620 if (bp->b_flags & B_DELWRI) {
2621 /*
2622 * If buffer is pinned and caller does
2623 * not want sleep waiting for it to be
2624 * unpinned, bail out
2625 * */
2626 if (bp->b_pin_count > 0) {
2627 if (flags & GB_LOCK_NOWAIT) {
2628 bqrelse(bp);
2629 return (NULL);
2630 } else {
2631 bunpin_wait(bp);
2632 }
2633 }
2634 bp->b_flags |= B_NOCACHE;
2635 bwrite(bp);
2636 } else {
2637 if (LIST_EMPTY(&bp->b_dep)) {
2638 bp->b_flags |= B_RELBUF;
2639 brelse(bp);
2640 } else {
2641 bp->b_flags |= B_NOCACHE;
2642 bwrite(bp);
2643 }
2644 }
2645 goto loop;
2646 }
2647 }
2648
2649 /*
2650 * If the size is inconsistant in the VMIO case, we can resize
2651 * the buffer. This might lead to B_CACHE getting set or
2652 * cleared. If the size has not changed, B_CACHE remains
2653 * unchanged from its previous state.
2654 */
2655
2656 if (bp->b_bcount != size)
2657 allocbuf(bp, size);
2658
2659 KASSERT(bp->b_offset != NOOFFSET,
2660 ("getblk: no buffer offset"));
2661
2662 /*
2663 * A buffer with B_DELWRI set and B_CACHE clear must
2664 * be committed before we can return the buffer in
2665 * order to prevent the caller from issuing a read
2666 * ( due to B_CACHE not being set ) and overwriting
2667 * it.
2668 *
2669 * Most callers, including NFS and FFS, need this to
2670 * operate properly either because they assume they
2671 * can issue a read if B_CACHE is not set, or because
2672 * ( for example ) an uncached B_DELWRI might loop due
2673 * to softupdates re-dirtying the buffer. In the latter
2674 * case, B_CACHE is set after the first write completes,
2675 * preventing further loops.
2676 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2677 * above while extending the buffer, we cannot allow the
2678 * buffer to remain with B_CACHE set after the write
2679 * completes or it will represent a corrupt state. To
2680 * deal with this we set B_NOCACHE to scrap the buffer
2681 * after the write.
2682 *
2683 * We might be able to do something fancy, like setting
2684 * B_CACHE in bwrite() except if B_DELWRI is already set,
2685 * so the below call doesn't set B_CACHE, but that gets real
2686 * confusing. This is much easier.
2687 */
2688
2689 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2690 bp->b_flags |= B_NOCACHE;
2691 bwrite(bp);
2692 goto loop;
2693 }
2694 bp->b_flags &= ~B_DONE;
2695 } else {
2696 int bsize, maxsize, vmio;
2697 off_t offset;
2698
2699 /*
2700 * Buffer is not in-core, create new buffer. The buffer
2701 * returned by getnewbuf() is locked. Note that the returned
2702 * buffer is also considered valid (not marked B_INVAL).
2703 */
2704 BO_UNLOCK(bo);
2705 /*
2706 * If the user does not want us to create the buffer, bail out
2707 * here.
2708 */
2709 if (flags & GB_NOCREAT)
2710 return NULL;
2711 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
2712 offset = blkno * bsize;
2713 vmio = vp->v_object != NULL;
2714 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2715 maxsize = imax(maxsize, bsize);
2716
2717 bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
2718 if (bp == NULL) {
2719 if (slpflag || slptimeo)
2720 return NULL;
2721 goto loop;
2722 }
2723
2724 /*
2725 * This code is used to make sure that a buffer is not
2726 * created while the getnewbuf routine is blocked.
2727 * This can be a problem whether the vnode is locked or not.
2728 * If the buffer is created out from under us, we have to
2729 * throw away the one we just created.
2730 *
2731 * Note: this must occur before we associate the buffer
2732 * with the vp especially considering limitations in
2733 * the splay tree implementation when dealing with duplicate
2734 * lblkno's.
2735 */
2736 BO_LOCK(bo);
2737 if (gbincore(bo, blkno)) {
2738 BO_UNLOCK(bo);
2739 bp->b_flags |= B_INVAL;
2740 brelse(bp);
2741 goto loop;
2742 }
2743
2744 /*
2745 * Insert the buffer into the hash, so that it can
2746 * be found by incore.
2747 */
2748 bp->b_blkno = bp->b_lblkno = blkno;
2749 bp->b_offset = offset;
2750 bgetvp(vp, bp);
2751 BO_UNLOCK(bo);
2752
2753 /*
2754 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2755 * buffer size starts out as 0, B_CACHE will be set by
2756 * allocbuf() for the VMIO case prior to it testing the
2757 * backing store for validity.
2758 */
2759
2760 if (vmio) {
2761 bp->b_flags |= B_VMIO;
2762 #if defined(VFS_BIO_DEBUG)
2763 if (vn_canvmio(vp) != TRUE)
2764 printf("getblk: VMIO on vnode type %d\n",
2765 vp->v_type);
2766 #endif
2767 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
2768 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
2769 bp, vp->v_object, bp->b_bufobj->bo_object));
2770 } else {
2771 bp->b_flags &= ~B_VMIO;
2772 KASSERT(bp->b_bufobj->bo_object == NULL,
2773 ("ARGH! has b_bufobj->bo_object %p %p\n",
2774 bp, bp->b_bufobj->bo_object));
2775 }
2776
2777 allocbuf(bp, size);
2778 bp->b_flags &= ~B_DONE;
2779 }
2780 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
2781 KASSERT(BUF_REFCNT(bp) == 1, ("getblk: bp %p not locked",bp));
2782 KASSERT(bp->b_bufobj == bo,
2783 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2784 return (bp);
2785 }
2786
2787 /*
2788 * Get an empty, disassociated buffer of given size. The buffer is initially
2789 * set to B_INVAL.
2790 */
2791 struct buf *
2792 geteblk(int size, int flags)
2793 {
2794 struct buf *bp;
2795 int maxsize;
2796
2797 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2798 while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
2799 if ((flags & GB_NOWAIT_BD) &&
2800 (curthread->td_pflags & TDP_BUFNEED) != 0)
2801 return (NULL);
2802 }
2803 allocbuf(bp, size);
2804 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2805 KASSERT(BUF_REFCNT(bp) == 1, ("geteblk: bp %p not locked",bp));
2806 return (bp);
2807 }
2808
2809
2810 /*
2811 * This code constitutes the buffer memory from either anonymous system
2812 * memory (in the case of non-VMIO operations) or from an associated
2813 * VM object (in the case of VMIO operations). This code is able to
2814 * resize a buffer up or down.
2815 *
2816 * Note that this code is tricky, and has many complications to resolve
2817 * deadlock or inconsistant data situations. Tread lightly!!!
2818 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2819 * the caller. Calling this code willy nilly can result in the loss of data.
2820 *
2821 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2822 * B_CACHE for the non-VMIO case.
2823 */
2824
2825 int
2826 allocbuf(struct buf *bp, int size)
2827 {
2828 int newbsize, mbsize;
2829 int i;
2830
2831 if (BUF_REFCNT(bp) == 0)
2832 panic("allocbuf: buffer not busy");
2833
2834 if (bp->b_kvasize < size)
2835 panic("allocbuf: buffer too small");
2836
2837 if ((bp->b_flags & B_VMIO) == 0) {
2838 caddr_t origbuf;
2839 int origbufsize;
2840 /*
2841 * Just get anonymous memory from the kernel. Don't
2842 * mess with B_CACHE.
2843 */
2844 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2845 if (bp->b_flags & B_MALLOC)
2846 newbsize = mbsize;
2847 else
2848 newbsize = round_page(size);
2849
2850 if (newbsize < bp->b_bufsize) {
2851 /*
2852 * malloced buffers are not shrunk
2853 */
2854 if (bp->b_flags & B_MALLOC) {
2855 if (newbsize) {
2856 bp->b_bcount = size;
2857 } else {
2858 free(bp->b_data, M_BIOBUF);
2859 if (bp->b_bufsize) {
2860 atomic_subtract_long(
2861 &bufmallocspace,
2862 bp->b_bufsize);
2863 bufspacewakeup();
2864 bp->b_bufsize = 0;
2865 }
2866 bp->b_saveaddr = bp->b_kvabase;
2867 bp->b_data = bp->b_saveaddr;
2868 bp->b_bcount = 0;
2869 bp->b_flags &= ~B_MALLOC;
2870 }
2871 return 1;
2872 }
2873 vm_hold_free_pages(
2874 bp,
2875 (vm_offset_t) bp->b_data + newbsize,
2876 (vm_offset_t) bp->b_data + bp->b_bufsize);
2877 } else if (newbsize > bp->b_bufsize) {
2878 /*
2879 * We only use malloced memory on the first allocation.
2880 * and revert to page-allocated memory when the buffer
2881 * grows.
2882 */
2883 /*
2884 * There is a potential smp race here that could lead
2885 * to bufmallocspace slightly passing the max. It
2886 * is probably extremely rare and not worth worrying
2887 * over.
2888 */
2889 if ( (bufmallocspace < maxbufmallocspace) &&
2890 (bp->b_bufsize == 0) &&
2891 (mbsize <= PAGE_SIZE/2)) {
2892
2893 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2894 bp->b_bufsize = mbsize;
2895 bp->b_bcount = size;
2896 bp->b_flags |= B_MALLOC;
2897 atomic_add_long(&bufmallocspace, mbsize);
2898 return 1;
2899 }
2900 origbuf = NULL;
2901 origbufsize = 0;
2902 /*
2903 * If the buffer is growing on its other-than-first allocation,
2904 * then we revert to the page-allocation scheme.
2905 */
2906 if (bp->b_flags & B_MALLOC) {
2907 origbuf = bp->b_data;
2908 origbufsize = bp->b_bufsize;
2909 bp->b_data = bp->b_kvabase;
2910 if (bp->b_bufsize) {
2911 atomic_subtract_long(&bufmallocspace,
2912 bp->b_bufsize);
2913 bufspacewakeup();
2914 bp->b_bufsize = 0;
2915 }
2916 bp->b_flags &= ~B_MALLOC;
2917 newbsize = round_page(newbsize);
2918 }
2919 vm_hold_load_pages(
2920 bp,
2921 (vm_offset_t) bp->b_data + bp->b_bufsize,
2922 (vm_offset_t) bp->b_data + newbsize);
2923 if (origbuf) {
2924 bcopy(origbuf, bp->b_data, origbufsize);
2925 free(origbuf, M_BIOBUF);
2926 }
2927 }
2928 } else {
2929 int desiredpages;
2930
2931 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2932 desiredpages = (size == 0) ? 0 :
2933 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2934
2935 if (bp->b_flags & B_MALLOC)
2936 panic("allocbuf: VMIO buffer can't be malloced");
2937 /*
2938 * Set B_CACHE initially if buffer is 0 length or will become
2939 * 0-length.
2940 */
2941 if (size == 0 || bp->b_bufsize == 0)
2942 bp->b_flags |= B_CACHE;
2943
2944 if (newbsize < bp->b_bufsize) {
2945 /*
2946 * DEV_BSIZE aligned new buffer size is less then the
2947 * DEV_BSIZE aligned existing buffer size. Figure out
2948 * if we have to remove any pages.
2949 */
2950 if (desiredpages < bp->b_npages) {
2951 vm_page_t m;
2952
2953 pmap_qremove((vm_offset_t)trunc_page(
2954 (vm_offset_t)bp->b_data) +
2955 (desiredpages << PAGE_SHIFT),
2956 (bp->b_npages - desiredpages));
2957 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2958 vm_page_lock_queues();
2959 for (i = desiredpages; i < bp->b_npages; i++) {
2960 /*
2961 * the page is not freed here -- it
2962 * is the responsibility of
2963 * vnode_pager_setsize
2964 */
2965 m = bp->b_pages[i];
2966 KASSERT(m != bogus_page,
2967 ("allocbuf: bogus page found"));
2968 while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
2969 vm_page_lock_queues();
2970
2971 bp->b_pages[i] = NULL;
2972 vm_page_unwire(m, 0);
2973 }
2974 vm_page_unlock_queues();
2975 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2976 bp->b_npages = desiredpages;
2977 }
2978 } else if (size > bp->b_bcount) {
2979 /*
2980 * We are growing the buffer, possibly in a
2981 * byte-granular fashion.
2982 */
2983 struct vnode *vp;
2984 vm_object_t obj;
2985 vm_offset_t toff;
2986 vm_offset_t tinc;
2987
2988 /*
2989 * Step 1, bring in the VM pages from the object,
2990 * allocating them if necessary. We must clear
2991 * B_CACHE if these pages are not valid for the
2992 * range covered by the buffer.
2993 */
2994
2995 vp = bp->b_vp;
2996 obj = bp->b_bufobj->bo_object;
2997
2998 VM_OBJECT_LOCK(obj);
2999 while (bp->b_npages < desiredpages) {
3000 vm_page_t m;
3001 vm_pindex_t pi;
3002
3003 pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
3004 if ((m = vm_page_lookup(obj, pi)) == NULL) {
3005 /*
3006 * note: must allocate system pages
3007 * since blocking here could intefere
3008 * with paging I/O, no matter which
3009 * process we are.
3010 */
3011 m = vm_page_alloc(obj, pi,
3012 VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM |
3013 VM_ALLOC_WIRED);
3014 if (m == NULL) {
3015 atomic_add_int(&vm_pageout_deficit,
3016 desiredpages - bp->b_npages);
3017 VM_OBJECT_UNLOCK(obj);
3018 VM_WAIT;
3019 VM_OBJECT_LOCK(obj);
3020 } else {
3021 if (m->valid == 0)
3022 bp->b_flags &= ~B_CACHE;
3023 bp->b_pages[bp->b_npages] = m;
3024 ++bp->b_npages;
3025 }
3026 continue;
3027 }
3028
3029 /*
3030 * We found a page. If we have to sleep on it,
3031 * retry because it might have gotten freed out
3032 * from under us.
3033 *
3034 * We can only test VPO_BUSY here. Blocking on
3035 * m->busy might lead to a deadlock:
3036 *
3037 * vm_fault->getpages->cluster_read->allocbuf
3038 *
3039 */
3040 if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
3041 continue;
3042
3043 /*
3044 * We have a good page.
3045 */
3046 vm_page_lock_queues();
3047 vm_page_wire(m);
3048 vm_page_unlock_queues();
3049 bp->b_pages[bp->b_npages] = m;
3050 ++bp->b_npages;
3051 }
3052
3053 /*
3054 * Step 2. We've loaded the pages into the buffer,
3055 * we have to figure out if we can still have B_CACHE
3056 * set. Note that B_CACHE is set according to the
3057 * byte-granular range ( bcount and size ), new the
3058 * aligned range ( newbsize ).
3059 *
3060 * The VM test is against m->valid, which is DEV_BSIZE
3061 * aligned. Needless to say, the validity of the data
3062 * needs to also be DEV_BSIZE aligned. Note that this
3063 * fails with NFS if the server or some other client
3064 * extends the file's EOF. If our buffer is resized,
3065 * B_CACHE may remain set! XXX
3066 */
3067
3068 toff = bp->b_bcount;
3069 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3070
3071 while ((bp->b_flags & B_CACHE) && toff < size) {
3072 vm_pindex_t pi;
3073
3074 if (tinc > (size - toff))
3075 tinc = size - toff;
3076
3077 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3078 PAGE_SHIFT;
3079
3080 vfs_buf_test_cache(
3081 bp,
3082 bp->b_offset,
3083 toff,
3084 tinc,
3085 bp->b_pages[pi]
3086 );
3087 toff += tinc;
3088 tinc = PAGE_SIZE;
3089 }
3090 VM_OBJECT_UNLOCK(obj);
3091
3092 /*
3093 * Step 3, fixup the KVM pmap. Remember that
3094 * bp->b_data is relative to bp->b_offset, but
3095 * bp->b_offset may be offset into the first page.
3096 */
3097
3098 bp->b_data = (caddr_t)
3099 trunc_page((vm_offset_t)bp->b_data);
3100 pmap_qenter(
3101 (vm_offset_t)bp->b_data,
3102 bp->b_pages,
3103 bp->b_npages
3104 );
3105
3106 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3107 (vm_offset_t)(bp->b_offset & PAGE_MASK));
3108 }
3109 }
3110 if (newbsize < bp->b_bufsize)
3111 bufspacewakeup();
3112 bp->b_bufsize = newbsize; /* actual buffer allocation */
3113 bp->b_bcount = size; /* requested buffer size */
3114 return 1;
3115 }
3116
3117 void
3118 biodone(struct bio *bp)
3119 {
3120 void (*done)(struct bio *);
3121
3122 mtx_lock(&bdonelock);
3123 bp->bio_flags |= BIO_DONE;
3124 done = bp->bio_done;
3125 if (done == NULL)
3126 wakeup(bp);
3127 mtx_unlock(&bdonelock);
3128 if (done != NULL)
3129 done(bp);
3130 }
3131
3132 /*
3133 * Wait for a BIO to finish.
3134 *
3135 * XXX: resort to a timeout for now. The optimal locking (if any) for this
3136 * case is not yet clear.
3137 */
3138 int
3139 biowait(struct bio *bp, const char *wchan)
3140 {
3141
3142 mtx_lock(&bdonelock);
3143 while ((bp->bio_flags & BIO_DONE) == 0)
3144 msleep(bp, &bdonelock, PRIBIO, wchan, hz / 10);
3145 mtx_unlock(&bdonelock);
3146 if (bp->bio_error != 0)
3147 return (bp->bio_error);
3148 if (!(bp->bio_flags & BIO_ERROR))
3149 return (0);
3150 return (EIO);
3151 }
3152
3153 void
3154 biofinish(struct bio *bp, struct devstat *stat, int error)
3155 {
3156
3157 if (error) {
3158 bp->bio_error = error;
3159 bp->bio_flags |= BIO_ERROR;
3160 }
3161 if (stat != NULL)
3162 devstat_end_transaction_bio(stat, bp);
3163 biodone(bp);
3164 }
3165
3166 /*
3167 * bufwait:
3168 *
3169 * Wait for buffer I/O completion, returning error status. The buffer
3170 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3171 * error and cleared.
3172 */
3173 int
3174 bufwait(struct buf *bp)
3175 {
3176 if (bp->b_iocmd == BIO_READ)
3177 bwait(bp, PRIBIO, "biord");
3178 else
3179 bwait(bp, PRIBIO, "biowr");
3180 if (bp->b_flags & B_EINTR) {
3181 bp->b_flags &= ~B_EINTR;
3182 return (EINTR);
3183 }
3184 if (bp->b_ioflags & BIO_ERROR) {
3185 return (bp->b_error ? bp->b_error : EIO);
3186 } else {
3187 return (0);
3188 }
3189 }
3190
3191 /*
3192 * Call back function from struct bio back up to struct buf.
3193 */
3194 static void
3195 bufdonebio(struct bio *bip)
3196 {
3197 struct buf *bp;
3198
3199 bp = bip->bio_caller2;
3200 bp->b_resid = bp->b_bcount - bip->bio_completed;
3201 bp->b_resid = bip->bio_resid; /* XXX: remove */
3202 bp->b_ioflags = bip->bio_flags;
3203 bp->b_error = bip->bio_error;
3204 if (bp->b_error)
3205 bp->b_ioflags |= BIO_ERROR;
3206 bufdone(bp);
3207 g_destroy_bio(bip);
3208 }
3209
3210 void
3211 dev_strategy(struct cdev *dev, struct buf *bp)
3212 {
3213 struct cdevsw *csw;
3214 struct bio *bip;
3215
3216 if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
3217 panic("b_iocmd botch");
3218 for (;;) {
3219 bip = g_new_bio();
3220 if (bip != NULL)
3221 break;
3222 /* Try again later */
3223 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3224 }
3225 bip->bio_cmd = bp->b_iocmd;
3226 bip->bio_offset = bp->b_iooffset;
3227 bip->bio_length = bp->b_bcount;
3228 bip->bio_bcount = bp->b_bcount; /* XXX: remove */
3229 bip->bio_data = bp->b_data;
3230 bip->bio_done = bufdonebio;
3231 bip->bio_caller2 = bp;
3232 bip->bio_dev = dev;
3233 KASSERT(dev->si_refcount > 0,
3234 ("dev_strategy on un-referenced struct cdev *(%s)",
3235 devtoname(dev)));
3236 csw = dev_refthread(dev);
3237 if (csw == NULL) {
3238 g_destroy_bio(bip);
3239 bp->b_error = ENXIO;
3240 bp->b_ioflags = BIO_ERROR;
3241 bufdone(bp);
3242 return;
3243 }
3244 (*csw->d_strategy)(bip);
3245 dev_relthread(dev);
3246 }
3247
3248 /*
3249 * bufdone:
3250 *
3251 * Finish I/O on a buffer, optionally calling a completion function.
3252 * This is usually called from an interrupt so process blocking is
3253 * not allowed.
3254 *
3255 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3256 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3257 * assuming B_INVAL is clear.
3258 *
3259 * For the VMIO case, we set B_CACHE if the op was a read and no
3260 * read error occured, or if the op was a write. B_CACHE is never
3261 * set if the buffer is invalid or otherwise uncacheable.
3262 *
3263 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3264 * initiator to leave B_INVAL set to brelse the buffer out of existance
3265 * in the biodone routine.
3266 */
3267 void
3268 bufdone(struct buf *bp)
3269 {
3270 struct bufobj *dropobj;
3271 void (*biodone)(struct buf *);
3272
3273 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3274 dropobj = NULL;
3275
3276 KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp,
3277 BUF_REFCNT(bp)));
3278 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3279
3280 runningbufwakeup(bp);
3281 if (bp->b_iocmd == BIO_WRITE)
3282 dropobj = bp->b_bufobj;
3283 /* call optional completion function if requested */
3284 if (bp->b_iodone != NULL) {
3285 biodone = bp->b_iodone;
3286 bp->b_iodone = NULL;
3287 (*biodone) (bp);
3288 if (dropobj)
3289 bufobj_wdrop(dropobj);
3290 return;
3291 }
3292
3293 bufdone_finish(bp);
3294
3295 if (dropobj)
3296 bufobj_wdrop(dropobj);
3297 }
3298
3299 void
3300 bufdone_finish(struct buf *bp)
3301 {
3302 KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp,
3303 BUF_REFCNT(bp)));
3304
3305 if (!LIST_EMPTY(&bp->b_dep))
3306 buf_complete(bp);
3307
3308 if (bp->b_flags & B_VMIO) {
3309 int i;
3310 vm_ooffset_t foff;
3311 vm_page_t m;
3312 vm_object_t obj;
3313 int iosize;
3314 struct vnode *vp = bp->b_vp;
3315 boolean_t are_queues_locked;
3316
3317 obj = bp->b_bufobj->bo_object;
3318
3319 #if defined(VFS_BIO_DEBUG)
3320 mp_fixme("usecount and vflag accessed without locks.");
3321 if (vp->v_usecount == 0) {
3322 panic("biodone: zero vnode ref count");
3323 }
3324
3325 KASSERT(vp->v_object != NULL,
3326 ("biodone: vnode %p has no vm_object", vp));
3327 #endif
3328
3329 foff = bp->b_offset;
3330 KASSERT(bp->b_offset != NOOFFSET,
3331 ("biodone: no buffer offset"));
3332
3333 VM_OBJECT_LOCK(obj);
3334 #if defined(VFS_BIO_DEBUG)
3335 if (obj->paging_in_progress < bp->b_npages) {
3336 printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3337 obj->paging_in_progress, bp->b_npages);
3338 }
3339 #endif
3340
3341 /*
3342 * Set B_CACHE if the op was a normal read and no error
3343 * occured. B_CACHE is set for writes in the b*write()
3344 * routines.
3345 */
3346 iosize = bp->b_bcount - bp->b_resid;
3347 if (bp->b_iocmd == BIO_READ &&
3348 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3349 !(bp->b_ioflags & BIO_ERROR)) {
3350 bp->b_flags |= B_CACHE;
3351 }
3352 if (bp->b_iocmd == BIO_READ) {
3353 vm_page_lock_queues();
3354 are_queues_locked = TRUE;
3355 } else
3356 are_queues_locked = FALSE;
3357 for (i = 0; i < bp->b_npages; i++) {
3358 int bogusflag = 0;
3359 int resid;
3360
3361 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3362 if (resid > iosize)
3363 resid = iosize;
3364
3365 /*
3366 * cleanup bogus pages, restoring the originals
3367 */
3368 m = bp->b_pages[i];
3369 if (m == bogus_page) {
3370 bogusflag = 1;
3371 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3372 if (m == NULL)
3373 panic("biodone: page disappeared!");
3374 bp->b_pages[i] = m;
3375 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3376 bp->b_pages, bp->b_npages);
3377 }
3378 #if defined(VFS_BIO_DEBUG)
3379 if (OFF_TO_IDX(foff) != m->pindex) {
3380 printf(
3381 "biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3382 (intmax_t)foff, (uintmax_t)m->pindex);
3383 }
3384 #endif
3385
3386 /*
3387 * In the write case, the valid and clean bits are
3388 * already changed correctly ( see bdwrite() ), so we
3389 * only need to do this here in the read case.
3390 */
3391 if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3392 vfs_page_set_valid(bp, foff, i, m);
3393 }
3394
3395 /*
3396 * when debugging new filesystems or buffer I/O methods, this
3397 * is the most common error that pops up. if you see this, you
3398 * have not set the page busy flag correctly!!!
3399 */
3400 if (m->busy == 0) {
3401 printf("biodone: page busy < 0, "
3402 "pindex: %d, foff: 0x(%x,%x), "
3403 "resid: %d, index: %d\n",
3404 (int) m->pindex, (int)(foff >> 32),
3405 (int) foff & 0xffffffff, resid, i);
3406 if (!vn_isdisk(vp, NULL))
3407 printf(" iosize: %jd, lblkno: %jd, flags: 0x%x, npages: %d\n",
3408 (intmax_t)bp->b_vp->v_mount->mnt_stat.f_iosize,
3409 (intmax_t) bp->b_lblkno,
3410 bp->b_flags, bp->b_npages);
3411 else
3412 printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3413 (intmax_t) bp->b_lblkno,
3414 bp->b_flags, bp->b_npages);
3415 printf(" valid: 0x%lx, dirty: 0x%lx, wired: %d\n",
3416 (u_long)m->valid, (u_long)m->dirty,
3417 m->wire_count);
3418 panic("biodone: page busy < 0\n");
3419 }
3420 vm_page_io_finish(m);
3421 vm_object_pip_subtract(obj, 1);
3422 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3423 iosize -= resid;
3424 }
3425 if (are_queues_locked)
3426 vm_page_unlock_queues();
3427 vm_object_pip_wakeupn(obj, 0);
3428 VM_OBJECT_UNLOCK(obj);
3429 }
3430
3431 /*
3432 * For asynchronous completions, release the buffer now. The brelse
3433 * will do a wakeup there if necessary - so no need to do a wakeup
3434 * here in the async case. The sync case always needs to do a wakeup.
3435 */
3436
3437 if (bp->b_flags & B_ASYNC) {
3438 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3439 brelse(bp);
3440 else
3441 bqrelse(bp);
3442 } else
3443 bdone(bp);
3444 }
3445
3446 /*
3447 * This routine is called in lieu of iodone in the case of
3448 * incomplete I/O. This keeps the busy status for pages
3449 * consistant.
3450 */
3451 void
3452 vfs_unbusy_pages(struct buf *bp)
3453 {
3454 int i;
3455 vm_object_t obj;
3456 vm_page_t m;
3457
3458 runningbufwakeup(bp);
3459 if (!(bp->b_flags & B_VMIO))
3460 return;
3461
3462 obj = bp->b_bufobj->bo_object;
3463 VM_OBJECT_LOCK(obj);
3464 for (i = 0; i < bp->b_npages; i++) {
3465 m = bp->b_pages[i];
3466 if (m == bogus_page) {
3467 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3468 if (!m)
3469 panic("vfs_unbusy_pages: page missing\n");
3470 bp->b_pages[i] = m;
3471 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3472 bp->b_pages, bp->b_npages);
3473 }
3474 vm_object_pip_subtract(obj, 1);
3475 vm_page_io_finish(m);
3476 }
3477 vm_object_pip_wakeupn(obj, 0);
3478 VM_OBJECT_UNLOCK(obj);
3479 }
3480
3481 /*
3482 * vfs_page_set_valid:
3483 *
3484 * Set the valid bits in a page based on the supplied offset. The
3485 * range is restricted to the buffer's size.
3486 *
3487 * This routine is typically called after a read completes.
3488 */
3489 static void
3490 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3491 {
3492 vm_ooffset_t soff, eoff;
3493
3494 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3495 /*
3496 * Start and end offsets in buffer. eoff - soff may not cross a
3497 * page boundry or cross the end of the buffer. The end of the
3498 * buffer, in this case, is our file EOF, not the allocation size
3499 * of the buffer.
3500 */
3501 soff = off;
3502 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3503 if (eoff > bp->b_offset + bp->b_bcount)
3504 eoff = bp->b_offset + bp->b_bcount;
3505
3506 /*
3507 * Set valid range. This is typically the entire buffer and thus the
3508 * entire page.
3509 */
3510 if (eoff > soff) {
3511 vm_page_set_validclean(
3512 m,
3513 (vm_offset_t) (soff & PAGE_MASK),
3514 (vm_offset_t) (eoff - soff)
3515 );
3516 }
3517 }
3518
3519 /*
3520 * This routine is called before a device strategy routine.
3521 * It is used to tell the VM system that paging I/O is in
3522 * progress, and treat the pages associated with the buffer
3523 * almost as being VPO_BUSY. Also the object paging_in_progress
3524 * flag is handled to make sure that the object doesn't become
3525 * inconsistant.
3526 *
3527 * Since I/O has not been initiated yet, certain buffer flags
3528 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3529 * and should be ignored.
3530 */
3531 void
3532 vfs_busy_pages(struct buf *bp, int clear_modify)
3533 {
3534 int i, bogus;
3535 vm_object_t obj;
3536 vm_ooffset_t foff;
3537 vm_page_t m;
3538
3539 if (!(bp->b_flags & B_VMIO))
3540 return;
3541
3542 obj = bp->b_bufobj->bo_object;
3543 foff = bp->b_offset;
3544 KASSERT(bp->b_offset != NOOFFSET,
3545 ("vfs_busy_pages: no buffer offset"));
3546 VM_OBJECT_LOCK(obj);
3547 if (bp->b_bufsize != 0)
3548 vfs_setdirty_locked_object(bp);
3549 retry:
3550 for (i = 0; i < bp->b_npages; i++) {
3551 m = bp->b_pages[i];
3552
3553 if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3554 goto retry;
3555 }
3556 bogus = 0;
3557 vm_page_lock_queues();
3558 for (i = 0; i < bp->b_npages; i++) {
3559 m = bp->b_pages[i];
3560
3561 if ((bp->b_flags & B_CLUSTER) == 0) {
3562 vm_object_pip_add(obj, 1);
3563 vm_page_io_start(m);
3564 }
3565 /*
3566 * When readying a buffer for a read ( i.e
3567 * clear_modify == 0 ), it is important to do
3568 * bogus_page replacement for valid pages in
3569 * partially instantiated buffers. Partially
3570 * instantiated buffers can, in turn, occur when
3571 * reconstituting a buffer from its VM backing store
3572 * base. We only have to do this if B_CACHE is
3573 * clear ( which causes the I/O to occur in the
3574 * first place ). The replacement prevents the read
3575 * I/O from overwriting potentially dirty VM-backed
3576 * pages. XXX bogus page replacement is, uh, bogus.
3577 * It may not work properly with small-block devices.
3578 * We need to find a better way.
3579 */
3580 pmap_remove_all(m);
3581 if (clear_modify)
3582 vfs_page_set_valid(bp, foff, i, m);
3583 else if (m->valid == VM_PAGE_BITS_ALL &&
3584 (bp->b_flags & B_CACHE) == 0) {
3585 bp->b_pages[i] = bogus_page;
3586 bogus++;
3587 }
3588 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3589 }
3590 vm_page_unlock_queues();
3591 VM_OBJECT_UNLOCK(obj);
3592 if (bogus)
3593 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3594 bp->b_pages, bp->b_npages);
3595 }
3596
3597 /*
3598 * Tell the VM system that the pages associated with this buffer
3599 * are clean. This is used for delayed writes where the data is
3600 * going to go to disk eventually without additional VM intevention.
3601 *
3602 * Note that while we only really need to clean through to b_bcount, we
3603 * just go ahead and clean through to b_bufsize.
3604 */
3605 static void
3606 vfs_clean_pages(struct buf *bp)
3607 {
3608 int i;
3609 vm_ooffset_t foff, noff, eoff;
3610 vm_page_t m;
3611
3612 if (!(bp->b_flags & B_VMIO))
3613 return;
3614
3615 foff = bp->b_offset;
3616 KASSERT(bp->b_offset != NOOFFSET,
3617 ("vfs_clean_pages: no buffer offset"));
3618 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3619 vm_page_lock_queues();
3620 for (i = 0; i < bp->b_npages; i++) {
3621 m = bp->b_pages[i];
3622 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3623 eoff = noff;
3624
3625 if (eoff > bp->b_offset + bp->b_bufsize)
3626 eoff = bp->b_offset + bp->b_bufsize;
3627 vfs_page_set_valid(bp, foff, i, m);
3628 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3629 foff = noff;
3630 }
3631 vm_page_unlock_queues();
3632 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3633 }
3634
3635 /*
3636 * vfs_bio_set_validclean:
3637 *
3638 * Set the range within the buffer to valid and clean. The range is
3639 * relative to the beginning of the buffer, b_offset. Note that b_offset
3640 * itself may be offset from the beginning of the first page.
3641 *
3642 */
3643
3644 void
3645 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3646 {
3647 int i, n;
3648 vm_page_t m;
3649
3650 if (!(bp->b_flags & B_VMIO))
3651 return;
3652 /*
3653 * Fixup base to be relative to beginning of first page.
3654 * Set initial n to be the maximum number of bytes in the
3655 * first page that can be validated.
3656 */
3657
3658 base += (bp->b_offset & PAGE_MASK);
3659 n = PAGE_SIZE - (base & PAGE_MASK);
3660
3661 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3662 vm_page_lock_queues();
3663 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3664 m = bp->b_pages[i];
3665 if (n > size)
3666 n = size;
3667 vm_page_set_validclean(m, base & PAGE_MASK, n);
3668 base += n;
3669 size -= n;
3670 n = PAGE_SIZE;
3671 }
3672 vm_page_unlock_queues();
3673 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3674 }
3675
3676 /*
3677 * vfs_bio_clrbuf:
3678 *
3679 * clear a buffer. This routine essentially fakes an I/O, so we need
3680 * to clear BIO_ERROR and B_INVAL.
3681 *
3682 * Note that while we only theoretically need to clear through b_bcount,
3683 * we go ahead and clear through b_bufsize.
3684 */
3685
3686 void
3687 vfs_bio_clrbuf(struct buf *bp)
3688 {
3689 int i, j, mask = 0;
3690 caddr_t sa, ea;
3691
3692 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
3693 clrbuf(bp);
3694 return;
3695 }
3696
3697 bp->b_flags &= ~B_INVAL;
3698 bp->b_ioflags &= ~BIO_ERROR;
3699 VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3700 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3701 (bp->b_offset & PAGE_MASK) == 0) {
3702 if (bp->b_pages[0] == bogus_page)
3703 goto unlock;
3704 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3705 VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
3706 if ((bp->b_pages[0]->valid & mask) == mask)
3707 goto unlock;
3708 if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3709 ((bp->b_pages[0]->valid & mask) == 0)) {
3710 bzero(bp->b_data, bp->b_bufsize);
3711 bp->b_pages[0]->valid |= mask;
3712 goto unlock;
3713 }
3714 }
3715 ea = sa = bp->b_data;
3716 for(i = 0; i < bp->b_npages; i++, sa = ea) {
3717 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3718 ea = (caddr_t)(vm_offset_t)ulmin(
3719 (u_long)(vm_offset_t)ea,
3720 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3721 if (bp->b_pages[i] == bogus_page)
3722 continue;
3723 j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3724 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3725 VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
3726 if ((bp->b_pages[i]->valid & mask) == mask)
3727 continue;
3728 if ((bp->b_pages[i]->valid & mask) == 0) {
3729 if ((bp->b_pages[i]->flags & PG_ZERO) == 0)
3730 bzero(sa, ea - sa);
3731 } else {
3732 for (; sa < ea; sa += DEV_BSIZE, j++) {
3733 if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3734 (bp->b_pages[i]->valid & (1 << j)) == 0)
3735 bzero(sa, DEV_BSIZE);
3736 }
3737 }
3738 bp->b_pages[i]->valid |= mask;
3739 }
3740 unlock:
3741 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3742 bp->b_resid = 0;
3743 }
3744
3745 /*
3746 * vm_hold_load_pages and vm_hold_free_pages get pages into
3747 * a buffers address space. The pages are anonymous and are
3748 * not associated with a file object.
3749 */
3750 static void
3751 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3752 {
3753 vm_offset_t pg;
3754 vm_page_t p;
3755 int index;
3756
3757 to = round_page(to);
3758 from = round_page(from);
3759 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3760
3761 VM_OBJECT_LOCK(kernel_object);
3762 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3763 tryagain:
3764 /*
3765 * note: must allocate system pages since blocking here
3766 * could intefere with paging I/O, no matter which
3767 * process we are.
3768 */
3769 p = vm_page_alloc(kernel_object,
3770 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3771 VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3772 if (!p) {
3773 atomic_add_int(&vm_pageout_deficit,
3774 (to - pg) >> PAGE_SHIFT);
3775 VM_OBJECT_UNLOCK(kernel_object);
3776 VM_WAIT;
3777 VM_OBJECT_LOCK(kernel_object);
3778 goto tryagain;
3779 }
3780 p->valid = VM_PAGE_BITS_ALL;
3781 pmap_qenter(pg, &p, 1);
3782 bp->b_pages[index] = p;
3783 }
3784 VM_OBJECT_UNLOCK(kernel_object);
3785 bp->b_npages = index;
3786 }
3787
3788 /* Return pages associated with this buf to the vm system */
3789 static void
3790 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3791 {
3792 vm_offset_t pg;
3793 vm_page_t p;
3794 int index, newnpages;
3795
3796 from = round_page(from);
3797 to = round_page(to);
3798 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3799
3800 VM_OBJECT_LOCK(kernel_object);
3801 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3802 p = bp->b_pages[index];
3803 if (p && (index < bp->b_npages)) {
3804 if (p->busy) {
3805 printf(
3806 "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3807 (intmax_t)bp->b_blkno,
3808 (intmax_t)bp->b_lblkno);
3809 }
3810 bp->b_pages[index] = NULL;
3811 pmap_qremove(pg, 1);
3812 vm_page_lock_queues();
3813 vm_page_unwire(p, 0);
3814 vm_page_free(p);
3815 vm_page_unlock_queues();
3816 }
3817 }
3818 VM_OBJECT_UNLOCK(kernel_object);
3819 bp->b_npages = newnpages;
3820 }
3821
3822 /*
3823 * Map an IO request into kernel virtual address space.
3824 *
3825 * All requests are (re)mapped into kernel VA space.
3826 * Notice that we use b_bufsize for the size of the buffer
3827 * to be mapped. b_bcount might be modified by the driver.
3828 *
3829 * Note that even if the caller determines that the address space should
3830 * be valid, a race or a smaller-file mapped into a larger space may
3831 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3832 * check the return value.
3833 */
3834 int
3835 vmapbuf(struct buf *bp)
3836 {
3837 caddr_t addr, kva;
3838 vm_prot_t prot;
3839 int pidx, i;
3840 struct vm_page *m;
3841 struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3842
3843 if (bp->b_bufsize < 0)
3844 return (-1);
3845 prot = VM_PROT_READ;
3846 if (bp->b_iocmd == BIO_READ)
3847 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
3848 for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3849 addr < bp->b_data + bp->b_bufsize;
3850 addr += PAGE_SIZE, pidx++) {
3851 /*
3852 * Do the vm_fault if needed; do the copy-on-write thing
3853 * when reading stuff off device into memory.
3854 *
3855 * NOTE! Must use pmap_extract() because addr may be in
3856 * the userland address space, and kextract is only guarenteed
3857 * to work for the kernland address space (see: sparc64 port).
3858 */
3859 retry:
3860 if (vm_fault_quick(addr >= bp->b_data ? addr : bp->b_data,
3861 prot) < 0) {
3862 vm_page_lock_queues();
3863 for (i = 0; i < pidx; ++i) {
3864 vm_page_unhold(bp->b_pages[i]);
3865 bp->b_pages[i] = NULL;
3866 }
3867 vm_page_unlock_queues();
3868 return(-1);
3869 }
3870 m = pmap_extract_and_hold(pmap, (vm_offset_t)addr, prot);
3871 if (m == NULL)
3872 goto retry;
3873 bp->b_pages[pidx] = m;
3874 }
3875 if (pidx > btoc(MAXPHYS))
3876 panic("vmapbuf: mapped more than MAXPHYS");
3877 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3878
3879 kva = bp->b_saveaddr;
3880 bp->b_npages = pidx;
3881 bp->b_saveaddr = bp->b_data;
3882 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3883 return(0);
3884 }
3885
3886 /*
3887 * Free the io map PTEs associated with this IO operation.
3888 * We also invalidate the TLB entries and restore the original b_addr.
3889 */
3890 void
3891 vunmapbuf(struct buf *bp)
3892 {
3893 int pidx;
3894 int npages;
3895
3896 npages = bp->b_npages;
3897 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3898 vm_page_lock_queues();
3899 for (pidx = 0; pidx < npages; pidx++)
3900 vm_page_unhold(bp->b_pages[pidx]);
3901 vm_page_unlock_queues();
3902
3903 bp->b_data = bp->b_saveaddr;
3904 }
3905
3906 void
3907 bdone(struct buf *bp)
3908 {
3909
3910 mtx_lock(&bdonelock);
3911 bp->b_flags |= B_DONE;
3912 wakeup(bp);
3913 mtx_unlock(&bdonelock);
3914 }
3915
3916 void
3917 bwait(struct buf *bp, u_char pri, const char *wchan)
3918 {
3919
3920 mtx_lock(&bdonelock);
3921 while ((bp->b_flags & B_DONE) == 0)
3922 msleep(bp, &bdonelock, pri, wchan, 0);
3923 mtx_unlock(&bdonelock);
3924 }
3925
3926 int
3927 bufsync(struct bufobj *bo, int waitfor, struct thread *td)
3928 {
3929
3930 return (VOP_FSYNC(bo->__bo_vnode, waitfor, td));
3931 }
3932
3933 void
3934 bufstrategy(struct bufobj *bo, struct buf *bp)
3935 {
3936 int i = 0;
3937 struct vnode *vp;
3938
3939 vp = bp->b_vp;
3940 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
3941 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
3942 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
3943 i = VOP_STRATEGY(vp, bp);
3944 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
3945 }
3946
3947 void
3948 bufobj_wrefl(struct bufobj *bo)
3949 {
3950
3951 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3952 ASSERT_BO_LOCKED(bo);
3953 bo->bo_numoutput++;
3954 }
3955
3956 void
3957 bufobj_wref(struct bufobj *bo)
3958 {
3959
3960 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3961 BO_LOCK(bo);
3962 bo->bo_numoutput++;
3963 BO_UNLOCK(bo);
3964 }
3965
3966 void
3967 bufobj_wdrop(struct bufobj *bo)
3968 {
3969
3970 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
3971 BO_LOCK(bo);
3972 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
3973 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
3974 bo->bo_flag &= ~BO_WWAIT;
3975 wakeup(&bo->bo_numoutput);
3976 }
3977 BO_UNLOCK(bo);
3978 }
3979
3980 int
3981 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
3982 {
3983 int error;
3984
3985 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
3986 ASSERT_BO_LOCKED(bo);
3987 error = 0;
3988 while (bo->bo_numoutput) {
3989 bo->bo_flag |= BO_WWAIT;
3990 error = msleep(&bo->bo_numoutput, BO_MTX(bo),
3991 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
3992 if (error)
3993 break;
3994 }
3995 return (error);
3996 }
3997
3998 void
3999 bpin(struct buf *bp)
4000 {
4001 mtx_lock(&bpinlock);
4002 bp->b_pin_count++;
4003 mtx_unlock(&bpinlock);
4004 }
4005
4006 void
4007 bunpin(struct buf *bp)
4008 {
4009 mtx_lock(&bpinlock);
4010 if (--bp->b_pin_count == 0)
4011 wakeup(bp);
4012 mtx_unlock(&bpinlock);
4013 }
4014
4015 void
4016 bunpin_wait(struct buf *bp)
4017 {
4018 mtx_lock(&bpinlock);
4019 while (bp->b_pin_count > 0)
4020 msleep(bp, &bpinlock, PRIBIO, "bwunpin", 0);
4021 mtx_unlock(&bpinlock);
4022 }
4023
4024 #include "opt_ddb.h"
4025 #ifdef DDB
4026 #include <ddb/ddb.h>
4027
4028 /* DDB command to show buffer data */
4029 DB_SHOW_COMMAND(buffer, db_show_buffer)
4030 {
4031 /* get args */
4032 struct buf *bp = (struct buf *)addr;
4033
4034 if (!have_addr) {
4035 db_printf("usage: show buffer <addr>\n");
4036 return;
4037 }
4038
4039 db_printf("buf at %p\n", bp);
4040 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4041 db_printf(
4042 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4043 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_dep = %p\n",
4044 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4045 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4046 bp->b_dep.lh_first);
4047 if (bp->b_npages) {
4048 int i;
4049 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4050 for (i = 0; i < bp->b_npages; i++) {
4051 vm_page_t m;
4052 m = bp->b_pages[i];
4053 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4054 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4055 if ((i + 1) < bp->b_npages)
4056 db_printf(",");
4057 }
4058 db_printf("\n");
4059 }
4060 lockmgr_printinfo(&bp->b_lock);
4061 }
4062
4063 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4064 {
4065 struct buf *bp;
4066 int i;
4067
4068 for (i = 0; i < nbuf; i++) {
4069 bp = &buf[i];
4070 if (lockcount(&bp->b_lock)) {
4071 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4072 db_printf("\n");
4073 }
4074 }
4075 }
4076
4077 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4078 {
4079 struct vnode *vp;
4080 struct buf *bp;
4081
4082 if (!have_addr) {
4083 db_printf("usage: show vnodebufs <addr>\n");
4084 return;
4085 }
4086 vp = (struct vnode *)addr;
4087 db_printf("Clean buffers:\n");
4088 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4089 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4090 db_printf("\n");
4091 }
4092 db_printf("Dirty buffers:\n");
4093 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4094 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4095 db_printf("\n");
4096 }
4097 }
4098 #endif /* DDB */
Cache object: 4ecbc8e8cbd51d205d648bd3bc9b3c14
|