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