1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 2004 Poul-Henning Kamp
5 * Copyright (c) 1994,1997 John S. Dyson
6 * Copyright (c) 2013 The FreeBSD Foundation
7 * All rights reserved.
8 *
9 * Portions of this software were developed by Konstantin Belousov
10 * under sponsorship from the FreeBSD Foundation.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34 /*
35 * this file contains a new buffer I/O scheme implementing a coherent
36 * VM object and buffer cache scheme. Pains have been taken to make
37 * sure that the performance degradation associated with schemes such
38 * as this is not realized.
39 *
40 * Author: John S. Dyson
41 * Significant help during the development and debugging phases
42 * had been provided by David Greenman, also of the FreeBSD core team.
43 *
44 * see man buf(9) for more info.
45 */
46
47 #include <sys/cdefs.h>
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/asan.h>
51 #include <sys/bio.h>
52 #include <sys/bitset.h>
53 #include <sys/boottrace.h>
54 #include <sys/buf.h>
55 #include <sys/conf.h>
56 #include <sys/counter.h>
57 #include <sys/devicestat.h>
58 #include <sys/eventhandler.h>
59 #include <sys/fail.h>
60 #include <sys/ktr.h>
61 #include <sys/limits.h>
62 #include <sys/lock.h>
63 #include <sys/malloc.h>
64 #include <sys/memdesc.h>
65 #include <sys/mount.h>
66 #include <sys/mutex.h>
67 #include <sys/kernel.h>
68 #include <sys/kthread.h>
69 #include <sys/pctrie.h>
70 #include <sys/proc.h>
71 #include <sys/racct.h>
72 #include <sys/refcount.h>
73 #include <sys/resourcevar.h>
74 #include <sys/rwlock.h>
75 #include <sys/sched.h>
76 #include <sys/smp.h>
77 #include <sys/sysctl.h>
78 #include <sys/syscallsubr.h>
79 #include <sys/vmem.h>
80 #include <sys/vmmeter.h>
81 #include <sys/vnode.h>
82 #include <sys/watchdog.h>
83 #include <geom/geom.h>
84 #include <vm/vm.h>
85 #include <vm/vm_param.h>
86 #include <vm/vm_kern.h>
87 #include <vm/vm_object.h>
88 #include <vm/vm_page.h>
89 #include <vm/vm_pageout.h>
90 #include <vm/vm_pager.h>
91 #include <vm/vm_extern.h>
92 #include <vm/vm_map.h>
93 #include <vm/swap_pager.h>
94
95 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
96
97 struct bio_ops bioops; /* I/O operation notification */
98
99 struct buf_ops buf_ops_bio = {
100 .bop_name = "buf_ops_bio",
101 .bop_write = bufwrite,
102 .bop_strategy = bufstrategy,
103 .bop_sync = bufsync,
104 .bop_bdflush = bufbdflush,
105 };
106
107 struct bufqueue {
108 struct mtx_padalign bq_lock;
109 TAILQ_HEAD(, buf) bq_queue;
110 uint8_t bq_index;
111 uint16_t bq_subqueue;
112 int bq_len;
113 } __aligned(CACHE_LINE_SIZE);
114
115 #define BQ_LOCKPTR(bq) (&(bq)->bq_lock)
116 #define BQ_LOCK(bq) mtx_lock(BQ_LOCKPTR((bq)))
117 #define BQ_UNLOCK(bq) mtx_unlock(BQ_LOCKPTR((bq)))
118 #define BQ_ASSERT_LOCKED(bq) mtx_assert(BQ_LOCKPTR((bq)), MA_OWNED)
119
120 struct bufdomain {
121 struct bufqueue *bd_subq;
122 struct bufqueue bd_dirtyq;
123 struct bufqueue *bd_cleanq;
124 struct mtx_padalign bd_run_lock;
125 /* Constants */
126 long bd_maxbufspace;
127 long bd_hibufspace;
128 long bd_lobufspace;
129 long bd_bufspacethresh;
130 int bd_hifreebuffers;
131 int bd_lofreebuffers;
132 int bd_hidirtybuffers;
133 int bd_lodirtybuffers;
134 int bd_dirtybufthresh;
135 int bd_lim;
136 /* atomics */
137 int bd_wanted;
138 bool bd_shutdown;
139 int __aligned(CACHE_LINE_SIZE) bd_numdirtybuffers;
140 int __aligned(CACHE_LINE_SIZE) bd_running;
141 long __aligned(CACHE_LINE_SIZE) bd_bufspace;
142 int __aligned(CACHE_LINE_SIZE) bd_freebuffers;
143 } __aligned(CACHE_LINE_SIZE);
144
145 #define BD_LOCKPTR(bd) (&(bd)->bd_cleanq->bq_lock)
146 #define BD_LOCK(bd) mtx_lock(BD_LOCKPTR((bd)))
147 #define BD_UNLOCK(bd) mtx_unlock(BD_LOCKPTR((bd)))
148 #define BD_ASSERT_LOCKED(bd) mtx_assert(BD_LOCKPTR((bd)), MA_OWNED)
149 #define BD_RUN_LOCKPTR(bd) (&(bd)->bd_run_lock)
150 #define BD_RUN_LOCK(bd) mtx_lock(BD_RUN_LOCKPTR((bd)))
151 #define BD_RUN_UNLOCK(bd) mtx_unlock(BD_RUN_LOCKPTR((bd)))
152 #define BD_DOMAIN(bd) (bd - bdomain)
153
154 static char *buf; /* buffer header pool */
155 static struct buf *
nbufp(unsigned i)156 nbufp(unsigned i)
157 {
158 return ((struct buf *)(buf + (sizeof(struct buf) +
159 sizeof(vm_page_t) * atop(maxbcachebuf)) * i));
160 }
161
162 caddr_t __read_mostly unmapped_buf;
163
164 /* Used below and for softdep flushing threads in ufs/ffs/ffs_softdep.c */
165 struct proc *bufdaemonproc;
166
167 static void vm_hold_free_pages(struct buf *bp, int newbsize);
168 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
169 vm_offset_t to);
170 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
171 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
172 vm_page_t m);
173 static void vfs_clean_pages_dirty_buf(struct buf *bp);
174 static void vfs_setdirty_range(struct buf *bp);
175 static void vfs_vmio_invalidate(struct buf *bp);
176 static void vfs_vmio_truncate(struct buf *bp, int npages);
177 static void vfs_vmio_extend(struct buf *bp, int npages, int size);
178 static int vfs_bio_clcheck(struct vnode *vp, int size,
179 daddr_t lblkno, daddr_t blkno);
180 static void breada(struct vnode *, daddr_t *, int *, int, struct ucred *, int,
181 void (*)(struct buf *));
182 static int buf_flush(struct vnode *vp, struct bufdomain *, int);
183 static int flushbufqueues(struct vnode *, struct bufdomain *, int, int);
184 static void buf_daemon(void);
185 static __inline void bd_wakeup(void);
186 static int sysctl_runningspace(SYSCTL_HANDLER_ARGS);
187 static void bufkva_reclaim(vmem_t *, int);
188 static void bufkva_free(struct buf *);
189 static int buf_import(void *, void **, int, int, int);
190 static void buf_release(void *, void **, int);
191 static void maxbcachebuf_adjust(void);
192 static inline struct bufdomain *bufdomain(struct buf *);
193 static void bq_remove(struct bufqueue *bq, struct buf *bp);
194 static void bq_insert(struct bufqueue *bq, struct buf *bp, bool unlock);
195 static int buf_recycle(struct bufdomain *, bool kva);
196 static void bq_init(struct bufqueue *bq, int qindex, int cpu,
197 const char *lockname);
198 static void bd_init(struct bufdomain *bd);
199 static int bd_flushall(struct bufdomain *bd);
200 static int sysctl_bufdomain_long(SYSCTL_HANDLER_ARGS);
201 static int sysctl_bufdomain_int(SYSCTL_HANDLER_ARGS);
202
203 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
204 int vmiodirenable = TRUE;
205 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
206 "Use the VM system for directory writes");
207 static long runningbufspace;
208 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
209 "Amount of presently outstanding async buffer io");
210 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
211 NULL, 0, sysctl_bufspace, "L", "Physical memory used for buffers");
212 static counter_u64_t bufkvaspace;
213 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, bufkvaspace, CTLFLAG_RD, &bufkvaspace,
214 "Kernel virtual memory used for buffers");
215 static long maxbufspace;
216 SYSCTL_PROC(_vfs, OID_AUTO, maxbufspace,
217 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &maxbufspace,
218 __offsetof(struct bufdomain, bd_maxbufspace), sysctl_bufdomain_long, "L",
219 "Maximum allowed value of bufspace (including metadata)");
220 static long bufmallocspace;
221 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
222 "Amount of malloced memory for buffers");
223 static long maxbufmallocspace;
224 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace,
225 0, "Maximum amount of malloced memory for buffers");
226 static long lobufspace;
227 SYSCTL_PROC(_vfs, OID_AUTO, lobufspace,
228 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &lobufspace,
229 __offsetof(struct bufdomain, bd_lobufspace), sysctl_bufdomain_long, "L",
230 "Minimum amount of buffers we want to have");
231 long hibufspace;
232 SYSCTL_PROC(_vfs, OID_AUTO, hibufspace,
233 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &hibufspace,
234 __offsetof(struct bufdomain, bd_hibufspace), sysctl_bufdomain_long, "L",
235 "Maximum allowed value of bufspace (excluding metadata)");
236 long bufspacethresh;
237 SYSCTL_PROC(_vfs, OID_AUTO, bufspacethresh,
238 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &bufspacethresh,
239 __offsetof(struct bufdomain, bd_bufspacethresh), sysctl_bufdomain_long, "L",
240 "Bufspace consumed before waking the daemon to free some");
241 static counter_u64_t buffreekvacnt;
242 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt,
243 "Number of times we have freed the KVA space from some buffer");
244 static counter_u64_t bufdefragcnt;
245 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt,
246 "Number of times we have had to repeat buffer allocation to defragment");
247 static long lorunningspace;
248 SYSCTL_PROC(_vfs, OID_AUTO, lorunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
249 CTLFLAG_RW, &lorunningspace, 0, sysctl_runningspace, "L",
250 "Minimum preferred space used for in-progress I/O");
251 static long hirunningspace;
252 SYSCTL_PROC(_vfs, OID_AUTO, hirunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
253 CTLFLAG_RW, &hirunningspace, 0, sysctl_runningspace, "L",
254 "Maximum amount of space to use for in-progress I/O");
255 int dirtybufferflushes;
256 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
257 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
258 int bdwriteskip;
259 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
260 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
261 int altbufferflushes;
262 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW | CTLFLAG_STATS,
263 &altbufferflushes, 0, "Number of fsync flushes to limit dirty buffers");
264 static int recursiveflushes;
265 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW | CTLFLAG_STATS,
266 &recursiveflushes, 0, "Number of flushes skipped due to being recursive");
267 static int sysctl_numdirtybuffers(SYSCTL_HANDLER_ARGS);
268 SYSCTL_PROC(_vfs, OID_AUTO, numdirtybuffers,
269 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RD, NULL, 0, sysctl_numdirtybuffers, "I",
270 "Number of buffers that are dirty (has unwritten changes) at the moment");
271 static int lodirtybuffers;
272 SYSCTL_PROC(_vfs, OID_AUTO, lodirtybuffers,
273 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &lodirtybuffers,
274 __offsetof(struct bufdomain, bd_lodirtybuffers), sysctl_bufdomain_int, "I",
275 "How many buffers we want to have free before bufdaemon can sleep");
276 static int hidirtybuffers;
277 SYSCTL_PROC(_vfs, OID_AUTO, hidirtybuffers,
278 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &hidirtybuffers,
279 __offsetof(struct bufdomain, bd_hidirtybuffers), sysctl_bufdomain_int, "I",
280 "When the number of dirty buffers is considered severe");
281 int dirtybufthresh;
282 SYSCTL_PROC(_vfs, OID_AUTO, dirtybufthresh,
283 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &dirtybufthresh,
284 __offsetof(struct bufdomain, bd_dirtybufthresh), sysctl_bufdomain_int, "I",
285 "Number of bdwrite to bawrite conversions to clear dirty buffers");
286 static int numfreebuffers;
287 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
288 "Number of free buffers");
289 static int lofreebuffers;
290 SYSCTL_PROC(_vfs, OID_AUTO, lofreebuffers,
291 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &lofreebuffers,
292 __offsetof(struct bufdomain, bd_lofreebuffers), sysctl_bufdomain_int, "I",
293 "Target number of free buffers");
294 static int hifreebuffers;
295 SYSCTL_PROC(_vfs, OID_AUTO, hifreebuffers,
296 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &hifreebuffers,
297 __offsetof(struct bufdomain, bd_hifreebuffers), sysctl_bufdomain_int, "I",
298 "Threshold for clean buffer recycling");
299 static counter_u64_t getnewbufcalls;
300 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD,
301 &getnewbufcalls, "Number of calls to getnewbuf");
302 static counter_u64_t getnewbufrestarts;
303 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD,
304 &getnewbufrestarts,
305 "Number of times getnewbuf has had to restart a buffer acquisition");
306 static counter_u64_t mappingrestarts;
307 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RD,
308 &mappingrestarts,
309 "Number of times getblk has had to restart a buffer mapping for "
310 "unmapped buffer");
311 static counter_u64_t numbufallocfails;
312 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, numbufallocfails, CTLFLAG_RW,
313 &numbufallocfails, "Number of times buffer allocations failed");
314 static int flushbufqtarget = 100;
315 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
316 "Amount of work to do in flushbufqueues when helping bufdaemon");
317 static counter_u64_t notbufdflushes;
318 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, notbufdflushes, CTLFLAG_RD, ¬bufdflushes,
319 "Number of dirty buffer flushes done by the bufdaemon helpers");
320 static long barrierwrites;
321 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW | CTLFLAG_STATS,
322 &barrierwrites, 0, "Number of barrier writes");
323 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed,
324 CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
325 &unmapped_buf_allowed, 0,
326 "Permit the use of the unmapped i/o");
327 int maxbcachebuf = MAXBCACHEBUF;
328 SYSCTL_INT(_vfs, OID_AUTO, maxbcachebuf, CTLFLAG_RDTUN, &maxbcachebuf, 0,
329 "Maximum size of a buffer cache block");
330
331 /*
332 * This lock synchronizes access to bd_request.
333 */
334 static struct mtx_padalign __exclusive_cache_line bdlock;
335
336 /*
337 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
338 * waitrunningbufspace().
339 */
340 static struct mtx_padalign __exclusive_cache_line rbreqlock;
341
342 /*
343 * Lock that protects bdirtywait.
344 */
345 static struct mtx_padalign __exclusive_cache_line bdirtylock;
346
347 /*
348 * bufdaemon shutdown request and sleep channel.
349 */
350 static bool bd_shutdown;
351
352 /*
353 * Wakeup point for bufdaemon, as well as indicator of whether it is already
354 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
355 * is idling.
356 */
357 static int bd_request;
358
359 /*
360 * Request for the buf daemon to write more buffers than is indicated by
361 * lodirtybuf. This may be necessary to push out excess dependencies or
362 * defragment the address space where a simple count of the number of dirty
363 * buffers is insufficient to characterize the demand for flushing them.
364 */
365 static int bd_speedupreq;
366
367 /*
368 * Synchronization (sleep/wakeup) variable for active buffer space requests.
369 * Set when wait starts, cleared prior to wakeup().
370 * Used in runningbufwakeup() and waitrunningbufspace().
371 */
372 static int runningbufreq;
373
374 /*
375 * Synchronization for bwillwrite() waiters.
376 */
377 static int bdirtywait;
378
379 /*
380 * Definitions for the buffer free lists.
381 */
382 #define QUEUE_NONE 0 /* on no queue */
383 #define QUEUE_EMPTY 1 /* empty buffer headers */
384 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
385 #define QUEUE_CLEAN 3 /* non-B_DELWRI buffers */
386 #define QUEUE_SENTINEL 4 /* not an queue index, but mark for sentinel */
387
388 /* Maximum number of buffer domains. */
389 #define BUF_DOMAINS 8
390
391 struct bufdomainset bdlodirty; /* Domains > lodirty */
392 struct bufdomainset bdhidirty; /* Domains > hidirty */
393
394 /* Configured number of clean queues. */
395 static int __read_mostly buf_domains;
396
397 BITSET_DEFINE(bufdomainset, BUF_DOMAINS);
398 struct bufdomain __exclusive_cache_line bdomain[BUF_DOMAINS];
399 struct bufqueue __exclusive_cache_line bqempty;
400
401 /*
402 * per-cpu empty buffer cache.
403 */
404 uma_zone_t buf_zone;
405
406 static int
sysctl_runningspace(SYSCTL_HANDLER_ARGS)407 sysctl_runningspace(SYSCTL_HANDLER_ARGS)
408 {
409 long value;
410 int error;
411
412 value = *(long *)arg1;
413 error = sysctl_handle_long(oidp, &value, 0, req);
414 if (error != 0 || req->newptr == NULL)
415 return (error);
416 mtx_lock(&rbreqlock);
417 if (arg1 == &hirunningspace) {
418 if (value < lorunningspace)
419 error = EINVAL;
420 else
421 hirunningspace = value;
422 } else {
423 KASSERT(arg1 == &lorunningspace,
424 ("%s: unknown arg1", __func__));
425 if (value > hirunningspace)
426 error = EINVAL;
427 else
428 lorunningspace = value;
429 }
430 mtx_unlock(&rbreqlock);
431 return (error);
432 }
433
434 static int
sysctl_bufdomain_int(SYSCTL_HANDLER_ARGS)435 sysctl_bufdomain_int(SYSCTL_HANDLER_ARGS)
436 {
437 int error;
438 int value;
439 int i;
440
441 value = *(int *)arg1;
442 error = sysctl_handle_int(oidp, &value, 0, req);
443 if (error != 0 || req->newptr == NULL)
444 return (error);
445 *(int *)arg1 = value;
446 for (i = 0; i < buf_domains; i++)
447 *(int *)(uintptr_t)(((uintptr_t)&bdomain[i]) + arg2) =
448 value / buf_domains;
449
450 return (error);
451 }
452
453 static int
sysctl_bufdomain_long(SYSCTL_HANDLER_ARGS)454 sysctl_bufdomain_long(SYSCTL_HANDLER_ARGS)
455 {
456 long value;
457 int error;
458 int i;
459
460 value = *(long *)arg1;
461 error = sysctl_handle_long(oidp, &value, 0, req);
462 if (error != 0 || req->newptr == NULL)
463 return (error);
464 *(long *)arg1 = value;
465 for (i = 0; i < buf_domains; i++)
466 *(long *)(uintptr_t)(((uintptr_t)&bdomain[i]) + arg2) =
467 value / buf_domains;
468
469 return (error);
470 }
471
472 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
473 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
474 static int
sysctl_bufspace(SYSCTL_HANDLER_ARGS)475 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
476 {
477 long lvalue;
478 int ivalue;
479 int i;
480
481 lvalue = 0;
482 for (i = 0; i < buf_domains; i++)
483 lvalue += bdomain[i].bd_bufspace;
484 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
485 return (sysctl_handle_long(oidp, &lvalue, 0, req));
486 if (lvalue > INT_MAX)
487 /* On overflow, still write out a long to trigger ENOMEM. */
488 return (sysctl_handle_long(oidp, &lvalue, 0, req));
489 ivalue = lvalue;
490 return (sysctl_handle_int(oidp, &ivalue, 0, req));
491 }
492 #else
493 static int
sysctl_bufspace(SYSCTL_HANDLER_ARGS)494 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
495 {
496 long lvalue;
497 int i;
498
499 lvalue = 0;
500 for (i = 0; i < buf_domains; i++)
501 lvalue += bdomain[i].bd_bufspace;
502 return (sysctl_handle_long(oidp, &lvalue, 0, req));
503 }
504 #endif
505
506 static int
sysctl_numdirtybuffers(SYSCTL_HANDLER_ARGS)507 sysctl_numdirtybuffers(SYSCTL_HANDLER_ARGS)
508 {
509 int value;
510 int i;
511
512 value = 0;
513 for (i = 0; i < buf_domains; i++)
514 value += bdomain[i].bd_numdirtybuffers;
515 return (sysctl_handle_int(oidp, &value, 0, req));
516 }
517
518 /*
519 * bdirtywakeup:
520 *
521 * Wakeup any bwillwrite() waiters.
522 */
523 static void
bdirtywakeup(void)524 bdirtywakeup(void)
525 {
526 mtx_lock(&bdirtylock);
527 if (bdirtywait) {
528 bdirtywait = 0;
529 wakeup(&bdirtywait);
530 }
531 mtx_unlock(&bdirtylock);
532 }
533
534 /*
535 * bd_clear:
536 *
537 * Clear a domain from the appropriate bitsets when dirtybuffers
538 * is decremented.
539 */
540 static void
bd_clear(struct bufdomain * bd)541 bd_clear(struct bufdomain *bd)
542 {
543
544 mtx_lock(&bdirtylock);
545 if (bd->bd_numdirtybuffers <= bd->bd_lodirtybuffers)
546 BIT_CLR(BUF_DOMAINS, BD_DOMAIN(bd), &bdlodirty);
547 if (bd->bd_numdirtybuffers <= bd->bd_hidirtybuffers)
548 BIT_CLR(BUF_DOMAINS, BD_DOMAIN(bd), &bdhidirty);
549 mtx_unlock(&bdirtylock);
550 }
551
552 /*
553 * bd_set:
554 *
555 * Set a domain in the appropriate bitsets when dirtybuffers
556 * is incremented.
557 */
558 static void
bd_set(struct bufdomain * bd)559 bd_set(struct bufdomain *bd)
560 {
561
562 mtx_lock(&bdirtylock);
563 if (bd->bd_numdirtybuffers > bd->bd_lodirtybuffers)
564 BIT_SET(BUF_DOMAINS, BD_DOMAIN(bd), &bdlodirty);
565 if (bd->bd_numdirtybuffers > bd->bd_hidirtybuffers)
566 BIT_SET(BUF_DOMAINS, BD_DOMAIN(bd), &bdhidirty);
567 mtx_unlock(&bdirtylock);
568 }
569
570 /*
571 * bdirtysub:
572 *
573 * Decrement the numdirtybuffers count by one and wakeup any
574 * threads blocked in bwillwrite().
575 */
576 static void
bdirtysub(struct buf * bp)577 bdirtysub(struct buf *bp)
578 {
579 struct bufdomain *bd;
580 int num;
581
582 bd = bufdomain(bp);
583 num = atomic_fetchadd_int(&bd->bd_numdirtybuffers, -1);
584 if (num == (bd->bd_lodirtybuffers + bd->bd_hidirtybuffers) / 2)
585 bdirtywakeup();
586 if (num == bd->bd_lodirtybuffers || num == bd->bd_hidirtybuffers)
587 bd_clear(bd);
588 }
589
590 /*
591 * bdirtyadd:
592 *
593 * Increment the numdirtybuffers count by one and wakeup the buf
594 * daemon if needed.
595 */
596 static void
bdirtyadd(struct buf * bp)597 bdirtyadd(struct buf *bp)
598 {
599 struct bufdomain *bd;
600 int num;
601
602 /*
603 * Only do the wakeup once as we cross the boundary. The
604 * buf daemon will keep running until the condition clears.
605 */
606 bd = bufdomain(bp);
607 num = atomic_fetchadd_int(&bd->bd_numdirtybuffers, 1);
608 if (num == (bd->bd_lodirtybuffers + bd->bd_hidirtybuffers) / 2)
609 bd_wakeup();
610 if (num == bd->bd_lodirtybuffers || num == bd->bd_hidirtybuffers)
611 bd_set(bd);
612 }
613
614 /*
615 * bufspace_daemon_wakeup:
616 *
617 * Wakeup the daemons responsible for freeing clean bufs.
618 */
619 static void
bufspace_daemon_wakeup(struct bufdomain * bd)620 bufspace_daemon_wakeup(struct bufdomain *bd)
621 {
622
623 /*
624 * avoid the lock if the daemon is running.
625 */
626 if (atomic_fetchadd_int(&bd->bd_running, 1) == 0) {
627 BD_RUN_LOCK(bd);
628 atomic_store_int(&bd->bd_running, 1);
629 wakeup(&bd->bd_running);
630 BD_RUN_UNLOCK(bd);
631 }
632 }
633
634 /*
635 * bufspace_adjust:
636 *
637 * Adjust the reported bufspace for a KVA managed buffer, possibly
638 * waking any waiters.
639 */
640 static void
bufspace_adjust(struct buf * bp,int bufsize)641 bufspace_adjust(struct buf *bp, int bufsize)
642 {
643 struct bufdomain *bd;
644 long space;
645 int diff;
646
647 KASSERT((bp->b_flags & B_MALLOC) == 0,
648 ("bufspace_adjust: malloc buf %p", bp));
649 bd = bufdomain(bp);
650 diff = bufsize - bp->b_bufsize;
651 if (diff < 0) {
652 atomic_subtract_long(&bd->bd_bufspace, -diff);
653 } else if (diff > 0) {
654 space = atomic_fetchadd_long(&bd->bd_bufspace, diff);
655 /* Wake up the daemon on the transition. */
656 if (space < bd->bd_bufspacethresh &&
657 space + diff >= bd->bd_bufspacethresh)
658 bufspace_daemon_wakeup(bd);
659 }
660 bp->b_bufsize = bufsize;
661 }
662
663 /*
664 * bufspace_reserve:
665 *
666 * Reserve bufspace before calling allocbuf(). metadata has a
667 * different space limit than data.
668 */
669 static int
bufspace_reserve(struct bufdomain * bd,int size,bool metadata)670 bufspace_reserve(struct bufdomain *bd, int size, bool metadata)
671 {
672 long limit, new;
673 long space;
674
675 if (metadata)
676 limit = bd->bd_maxbufspace;
677 else
678 limit = bd->bd_hibufspace;
679 space = atomic_fetchadd_long(&bd->bd_bufspace, size);
680 new = space + size;
681 if (new > limit) {
682 atomic_subtract_long(&bd->bd_bufspace, size);
683 return (ENOSPC);
684 }
685
686 /* Wake up the daemon on the transition. */
687 if (space < bd->bd_bufspacethresh && new >= bd->bd_bufspacethresh)
688 bufspace_daemon_wakeup(bd);
689
690 return (0);
691 }
692
693 /*
694 * bufspace_release:
695 *
696 * Release reserved bufspace after bufspace_adjust() has consumed it.
697 */
698 static void
bufspace_release(struct bufdomain * bd,int size)699 bufspace_release(struct bufdomain *bd, int size)
700 {
701
702 atomic_subtract_long(&bd->bd_bufspace, size);
703 }
704
705 /*
706 * bufspace_wait:
707 *
708 * Wait for bufspace, acting as the buf daemon if a locked vnode is
709 * supplied. bd_wanted must be set prior to polling for space. The
710 * operation must be re-tried on return.
711 */
712 static void
bufspace_wait(struct bufdomain * bd,struct vnode * vp,int gbflags,int slpflag,int slptimeo)713 bufspace_wait(struct bufdomain *bd, struct vnode *vp, int gbflags,
714 int slpflag, int slptimeo)
715 {
716 struct thread *td;
717 int error, fl, norunbuf;
718
719 if ((gbflags & GB_NOWAIT_BD) != 0)
720 return;
721
722 td = curthread;
723 BD_LOCK(bd);
724 while (bd->bd_wanted) {
725 if (vp != NULL && vp->v_type != VCHR &&
726 (td->td_pflags & TDP_BUFNEED) == 0) {
727 BD_UNLOCK(bd);
728 /*
729 * getblk() is called with a vnode locked, and
730 * some majority of the dirty buffers may as
731 * well belong to the vnode. Flushing the
732 * buffers there would make a progress that
733 * cannot be achieved by the buf_daemon, that
734 * cannot lock the vnode.
735 */
736 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
737 (td->td_pflags & TDP_NORUNNINGBUF);
738
739 /*
740 * Play bufdaemon. The getnewbuf() function
741 * may be called while the thread owns lock
742 * for another dirty buffer for the same
743 * vnode, which makes it impossible to use
744 * VOP_FSYNC() there, due to the buffer lock
745 * recursion.
746 */
747 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
748 fl = buf_flush(vp, bd, flushbufqtarget);
749 td->td_pflags &= norunbuf;
750 BD_LOCK(bd);
751 if (fl != 0)
752 continue;
753 if (bd->bd_wanted == 0)
754 break;
755 }
756 error = msleep(&bd->bd_wanted, BD_LOCKPTR(bd),
757 (PRIBIO + 4) | slpflag, "newbuf", slptimeo);
758 if (error != 0)
759 break;
760 }
761 BD_UNLOCK(bd);
762 }
763
764 static void
bufspace_daemon_shutdown(void * arg,int howto __unused)765 bufspace_daemon_shutdown(void *arg, int howto __unused)
766 {
767 struct bufdomain *bd = arg;
768 int error;
769
770 if (KERNEL_PANICKED())
771 return;
772
773 BD_RUN_LOCK(bd);
774 bd->bd_shutdown = true;
775 wakeup(&bd->bd_running);
776 error = msleep(&bd->bd_shutdown, BD_RUN_LOCKPTR(bd), 0,
777 "bufspace_shutdown", 60 * hz);
778 BD_RUN_UNLOCK(bd);
779 if (error != 0)
780 printf("bufspacedaemon wait error: %d\n", error);
781 }
782
783 /*
784 * bufspace_daemon:
785 *
786 * buffer space management daemon. Tries to maintain some marginal
787 * amount of free buffer space so that requesting processes neither
788 * block nor work to reclaim buffers.
789 */
790 static void
bufspace_daemon(void * arg)791 bufspace_daemon(void *arg)
792 {
793 struct bufdomain *bd = arg;
794
795 EVENTHANDLER_REGISTER(shutdown_pre_sync, bufspace_daemon_shutdown, bd,
796 SHUTDOWN_PRI_LAST + 100);
797
798 BD_RUN_LOCK(bd);
799 while (!bd->bd_shutdown) {
800 BD_RUN_UNLOCK(bd);
801
802 /*
803 * Free buffers from the clean queue until we meet our
804 * targets.
805 *
806 * Theory of operation: The buffer cache is most efficient
807 * when some free buffer headers and space are always
808 * available to getnewbuf(). This daemon attempts to prevent
809 * the excessive blocking and synchronization associated
810 * with shortfall. It goes through three phases according
811 * demand:
812 *
813 * 1) The daemon wakes up voluntarily once per-second
814 * during idle periods when the counters are below
815 * the wakeup thresholds (bufspacethresh, lofreebuffers).
816 *
817 * 2) The daemon wakes up as we cross the thresholds
818 * ahead of any potential blocking. This may bounce
819 * slightly according to the rate of consumption and
820 * release.
821 *
822 * 3) The daemon and consumers are starved for working
823 * clean buffers. This is the 'bufspace' sleep below
824 * which will inefficiently trade bufs with bqrelse
825 * until we return to condition 2.
826 */
827 while (bd->bd_bufspace > bd->bd_lobufspace ||
828 bd->bd_freebuffers < bd->bd_hifreebuffers) {
829 if (buf_recycle(bd, false) != 0) {
830 if (bd_flushall(bd))
831 continue;
832 /*
833 * Speedup dirty if we've run out of clean
834 * buffers. This is possible in particular
835 * because softdep may held many bufs locked
836 * pending writes to other bufs which are
837 * marked for delayed write, exhausting
838 * clean space until they are written.
839 */
840 bd_speedup();
841 BD_LOCK(bd);
842 if (bd->bd_wanted) {
843 msleep(&bd->bd_wanted, BD_LOCKPTR(bd),
844 PRIBIO|PDROP, "bufspace", hz/10);
845 } else
846 BD_UNLOCK(bd);
847 }
848 maybe_yield();
849 }
850
851 /*
852 * Re-check our limits and sleep. bd_running must be
853 * cleared prior to checking the limits to avoid missed
854 * wakeups. The waker will adjust one of bufspace or
855 * freebuffers prior to checking bd_running.
856 */
857 BD_RUN_LOCK(bd);
858 if (bd->bd_shutdown)
859 break;
860 atomic_store_int(&bd->bd_running, 0);
861 if (bd->bd_bufspace < bd->bd_bufspacethresh &&
862 bd->bd_freebuffers > bd->bd_lofreebuffers) {
863 msleep(&bd->bd_running, BD_RUN_LOCKPTR(bd),
864 PRIBIO, "-", hz);
865 } else {
866 /* Avoid spurious wakeups while running. */
867 atomic_store_int(&bd->bd_running, 1);
868 }
869 }
870 wakeup(&bd->bd_shutdown);
871 BD_RUN_UNLOCK(bd);
872 kthread_exit();
873 }
874
875 /*
876 * bufmallocadjust:
877 *
878 * Adjust the reported bufspace for a malloc managed buffer, possibly
879 * waking any waiters.
880 */
881 static void
bufmallocadjust(struct buf * bp,int bufsize)882 bufmallocadjust(struct buf *bp, int bufsize)
883 {
884 int diff;
885
886 KASSERT((bp->b_flags & B_MALLOC) != 0,
887 ("bufmallocadjust: non-malloc buf %p", bp));
888 diff = bufsize - bp->b_bufsize;
889 if (diff < 0)
890 atomic_subtract_long(&bufmallocspace, -diff);
891 else
892 atomic_add_long(&bufmallocspace, diff);
893 bp->b_bufsize = bufsize;
894 }
895
896 /*
897 * runningwakeup:
898 *
899 * Wake up processes that are waiting on asynchronous writes to fall
900 * below lorunningspace.
901 */
902 static void
runningwakeup(void)903 runningwakeup(void)
904 {
905
906 mtx_lock(&rbreqlock);
907 if (runningbufreq) {
908 runningbufreq = 0;
909 wakeup(&runningbufreq);
910 }
911 mtx_unlock(&rbreqlock);
912 }
913
914 /*
915 * runningbufwakeup:
916 *
917 * Decrement the outstanding write count according.
918 */
919 void
runningbufwakeup(struct buf * bp)920 runningbufwakeup(struct buf *bp)
921 {
922 long space, bspace;
923
924 bspace = bp->b_runningbufspace;
925 if (bspace == 0)
926 return;
927 space = atomic_fetchadd_long(&runningbufspace, -bspace);
928 KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
929 space, bspace));
930 bp->b_runningbufspace = 0;
931 /*
932 * Only acquire the lock and wakeup on the transition from exceeding
933 * the threshold to falling below it.
934 */
935 if (space < lorunningspace)
936 return;
937 if (space - bspace > lorunningspace)
938 return;
939 runningwakeup();
940 }
941
942 long
runningbufclaim(struct buf * bp,int space)943 runningbufclaim(struct buf *bp, int space)
944 {
945 long old;
946
947 old = atomic_fetchadd_long(&runningbufspace, space);
948 bp->b_runningbufspace = space;
949 return (old);
950 }
951
952 /*
953 * waitrunningbufspace()
954 *
955 * runningbufspace is a measure of the amount of I/O currently
956 * running. This routine is used in async-write situations to
957 * prevent creating huge backups of pending writes to a device.
958 * Only asynchronous writes are governed by this function.
959 *
960 * This does NOT turn an async write into a sync write. It waits
961 * for earlier writes to complete and generally returns before the
962 * caller's write has reached the device.
963 */
964 void
waitrunningbufspace(void)965 waitrunningbufspace(void)
966 {
967
968 mtx_lock(&rbreqlock);
969 while (runningbufspace > hirunningspace) {
970 runningbufreq = 1;
971 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
972 }
973 mtx_unlock(&rbreqlock);
974 }
975
976 /*
977 * vfs_buf_test_cache:
978 *
979 * Called when a buffer is extended. This function clears the B_CACHE
980 * bit if the newly extended portion of the buffer does not contain
981 * valid data.
982 */
983 static __inline void
vfs_buf_test_cache(struct buf * bp,vm_ooffset_t foff,vm_offset_t off,vm_offset_t size,vm_page_t m)984 vfs_buf_test_cache(struct buf *bp, vm_ooffset_t foff, vm_offset_t off,
985 vm_offset_t size, vm_page_t m)
986 {
987
988 /*
989 * This function and its results are protected by higher level
990 * synchronization requiring vnode and buf locks to page in and
991 * validate pages.
992 */
993 if (bp->b_flags & B_CACHE) {
994 int base = (foff + off) & PAGE_MASK;
995 if (vm_page_is_valid(m, base, size) == 0)
996 bp->b_flags &= ~B_CACHE;
997 }
998 }
999
1000 /* Wake up the buffer daemon if necessary */
1001 static void
bd_wakeup(void)1002 bd_wakeup(void)
1003 {
1004
1005 mtx_lock(&bdlock);
1006 if (bd_request == 0) {
1007 bd_request = 1;
1008 wakeup(&bd_request);
1009 }
1010 mtx_unlock(&bdlock);
1011 }
1012
1013 /*
1014 * Adjust the maxbcachbuf tunable.
1015 */
1016 static void
maxbcachebuf_adjust(void)1017 maxbcachebuf_adjust(void)
1018 {
1019 int i;
1020
1021 /*
1022 * maxbcachebuf must be a power of 2 >= MAXBSIZE.
1023 */
1024 i = 2;
1025 while (i * 2 <= maxbcachebuf)
1026 i *= 2;
1027 maxbcachebuf = i;
1028 if (maxbcachebuf < MAXBSIZE)
1029 maxbcachebuf = MAXBSIZE;
1030 if (maxbcachebuf > maxphys)
1031 maxbcachebuf = maxphys;
1032 if (bootverbose != 0 && maxbcachebuf != MAXBCACHEBUF)
1033 printf("maxbcachebuf=%d\n", maxbcachebuf);
1034 }
1035
1036 /*
1037 * bd_speedup - speedup the buffer cache flushing code
1038 */
1039 void
bd_speedup(void)1040 bd_speedup(void)
1041 {
1042 int needwake;
1043
1044 mtx_lock(&bdlock);
1045 needwake = 0;
1046 if (bd_speedupreq == 0 || bd_request == 0)
1047 needwake = 1;
1048 bd_speedupreq = 1;
1049 bd_request = 1;
1050 if (needwake)
1051 wakeup(&bd_request);
1052 mtx_unlock(&bdlock);
1053 }
1054
1055 #ifdef __i386__
1056 #define TRANSIENT_DENOM 5
1057 #else
1058 #define TRANSIENT_DENOM 10
1059 #endif
1060
1061 /*
1062 * Calculating buffer cache scaling values and reserve space for buffer
1063 * headers. This is called during low level kernel initialization and
1064 * may be called more then once. We CANNOT write to the memory area
1065 * being reserved at this time.
1066 */
1067 caddr_t
kern_vfs_bio_buffer_alloc(caddr_t v,long physmem_est)1068 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
1069 {
1070 int tuned_nbuf;
1071 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
1072
1073 /*
1074 * With KASAN or KMSAN enabled, the kernel map is shadowed. Account for
1075 * this when sizing maps based on the amount of physical memory
1076 * available.
1077 */
1078 #if defined(KASAN)
1079 physmem_est = (physmem_est * KASAN_SHADOW_SCALE) /
1080 (KASAN_SHADOW_SCALE + 1);
1081 #elif defined(KMSAN)
1082 physmem_est /= 3;
1083
1084 /*
1085 * KMSAN cannot reliably determine whether buffer data is initialized
1086 * unless it is updated through a KVA mapping.
1087 */
1088 unmapped_buf_allowed = 0;
1089 #endif
1090
1091 /*
1092 * physmem_est is in pages. Convert it to kilobytes (assumes
1093 * PAGE_SIZE is >= 1K)
1094 */
1095 physmem_est = physmem_est * (PAGE_SIZE / 1024);
1096
1097 maxbcachebuf_adjust();
1098 /*
1099 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
1100 * For the first 64MB of ram nominally allocate sufficient buffers to
1101 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
1102 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
1103 * the buffer cache we limit the eventual kva reservation to
1104 * maxbcache bytes.
1105 *
1106 * factor represents the 1/4 x ram conversion.
1107 */
1108 if (nbuf == 0) {
1109 int factor = 4 * BKVASIZE / 1024;
1110
1111 nbuf = 50;
1112 if (physmem_est > 4096)
1113 nbuf += min((physmem_est - 4096) / factor,
1114 65536 / factor);
1115 if (physmem_est > 65536)
1116 nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
1117 32 * 1024 * 1024 / (factor * 5));
1118
1119 if (maxbcache && nbuf > maxbcache / BKVASIZE)
1120 nbuf = maxbcache / BKVASIZE;
1121 tuned_nbuf = 1;
1122 } else
1123 tuned_nbuf = 0;
1124
1125 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
1126 maxbuf = (LONG_MAX / 3) / BKVASIZE;
1127 if (nbuf > maxbuf) {
1128 if (!tuned_nbuf)
1129 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
1130 maxbuf);
1131 nbuf = maxbuf;
1132 }
1133
1134 /*
1135 * Ideal allocation size for the transient bio submap is 10%
1136 * of the maximal space buffer map. This roughly corresponds
1137 * to the amount of the buffer mapped for typical UFS load.
1138 *
1139 * Clip the buffer map to reserve space for the transient
1140 * BIOs, if its extent is bigger than 90% (80% on i386) of the
1141 * maximum buffer map extent on the platform.
1142 *
1143 * The fall-back to the maxbuf in case of maxbcache unset,
1144 * allows to not trim the buffer KVA for the architectures
1145 * with ample KVA space.
1146 */
1147 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
1148 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
1149 buf_sz = (long)nbuf * BKVASIZE;
1150 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
1151 (TRANSIENT_DENOM - 1)) {
1152 /*
1153 * There is more KVA than memory. Do not
1154 * adjust buffer map size, and assign the rest
1155 * of maxbuf to transient map.
1156 */
1157 biotmap_sz = maxbuf_sz - buf_sz;
1158 } else {
1159 /*
1160 * Buffer map spans all KVA we could afford on
1161 * this platform. Give 10% (20% on i386) of
1162 * the buffer map to the transient bio map.
1163 */
1164 biotmap_sz = buf_sz / TRANSIENT_DENOM;
1165 buf_sz -= biotmap_sz;
1166 }
1167 if (biotmap_sz / INT_MAX > maxphys)
1168 bio_transient_maxcnt = INT_MAX;
1169 else
1170 bio_transient_maxcnt = biotmap_sz / maxphys;
1171 /*
1172 * Artificially limit to 1024 simultaneous in-flight I/Os
1173 * using the transient mapping.
1174 */
1175 if (bio_transient_maxcnt > 1024)
1176 bio_transient_maxcnt = 1024;
1177 if (tuned_nbuf)
1178 nbuf = buf_sz / BKVASIZE;
1179 }
1180
1181 if (nswbuf == 0) {
1182 /*
1183 * Pager buffers are allocated for short periods, so scale the
1184 * number of reserved buffers based on the number of CPUs rather
1185 * than amount of memory.
1186 */
1187 nswbuf = min(nbuf / 4, 32 * mp_ncpus);
1188 if (nswbuf < NSWBUF_MIN)
1189 nswbuf = NSWBUF_MIN;
1190 }
1191
1192 /*
1193 * Reserve space for the buffer cache buffers
1194 */
1195 buf = (char *)v;
1196 v = (caddr_t)buf + (sizeof(struct buf) + sizeof(vm_page_t) *
1197 atop(maxbcachebuf)) * nbuf;
1198
1199 return (v);
1200 }
1201
1202 /*
1203 * Single global constant for BUF_WMESG, to avoid getting multiple
1204 * references.
1205 */
1206 static const char buf_wmesg[] = "bufwait";
1207
1208 /* Initialize the buffer subsystem. Called before use of any buffers. */
1209 void
bufinit(void)1210 bufinit(void)
1211 {
1212 struct buf *bp;
1213 int i;
1214
1215 TSENTER();
1216 KASSERT(maxbcachebuf >= MAXBSIZE,
1217 ("maxbcachebuf (%d) must be >= MAXBSIZE (%d)\n", maxbcachebuf,
1218 MAXBSIZE));
1219 bq_init(&bqempty, QUEUE_EMPTY, -1, "bufq empty lock");
1220 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
1221 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
1222 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
1223
1224 unmapped_buf = (caddr_t)kva_alloc(maxphys);
1225
1226 /* finally, initialize each buffer header and stick on empty q */
1227 for (i = 0; i < nbuf; i++) {
1228 bp = nbufp(i);
1229 bzero(bp, sizeof(*bp) + sizeof(vm_page_t) * atop(maxbcachebuf));
1230 bp->b_flags = B_INVAL;
1231 bp->b_rcred = NOCRED;
1232 bp->b_wcred = NOCRED;
1233 bp->b_qindex = QUEUE_NONE;
1234 bp->b_domain = -1;
1235 bp->b_subqueue = mp_maxid + 1;
1236 bp->b_xflags = 0;
1237 bp->b_data = bp->b_kvabase = unmapped_buf;
1238 LIST_INIT(&bp->b_dep);
1239 BUF_LOCKINIT(bp, buf_wmesg);
1240 bq_insert(&bqempty, bp, false);
1241 }
1242
1243 /*
1244 * maxbufspace is the absolute maximum amount of buffer space we are
1245 * allowed to reserve in KVM and in real terms. The absolute maximum
1246 * is nominally used by metadata. hibufspace is the nominal maximum
1247 * used by most other requests. The differential is required to
1248 * ensure that metadata deadlocks don't occur.
1249 *
1250 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
1251 * this may result in KVM fragmentation which is not handled optimally
1252 * by the system. XXX This is less true with vmem. We could use
1253 * PAGE_SIZE.
1254 */
1255 maxbufspace = (long)nbuf * BKVASIZE;
1256 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - maxbcachebuf * 10);
1257 lobufspace = (hibufspace / 20) * 19; /* 95% */
1258 bufspacethresh = lobufspace + (hibufspace - lobufspace) / 2;
1259
1260 /*
1261 * Note: The 16 MiB upper limit for hirunningspace was chosen
1262 * arbitrarily and may need further tuning. It corresponds to
1263 * 128 outstanding write IO requests (if IO size is 128 KiB),
1264 * which fits with many RAID controllers' tagged queuing limits.
1265 * The lower 1 MiB limit is the historical upper limit for
1266 * hirunningspace.
1267 */
1268 hirunningspace = lmax(lmin(roundup(hibufspace / 64, maxbcachebuf),
1269 16 * 1024 * 1024), 1024 * 1024);
1270 lorunningspace = roundup((hirunningspace * 2) / 3, maxbcachebuf);
1271
1272 /*
1273 * Limit the amount of malloc memory since it is wired permanently into
1274 * the kernel space. Even though this is accounted for in the buffer
1275 * allocation, we don't want the malloced region to grow uncontrolled.
1276 * The malloc scheme improves memory utilization significantly on
1277 * average (small) directories.
1278 */
1279 maxbufmallocspace = hibufspace / 20;
1280
1281 /*
1282 * Reduce the chance of a deadlock occurring by limiting the number
1283 * of delayed-write dirty buffers we allow to stack up.
1284 */
1285 hidirtybuffers = nbuf / 4 + 20;
1286 dirtybufthresh = hidirtybuffers * 9 / 10;
1287 /*
1288 * To support extreme low-memory systems, make sure hidirtybuffers
1289 * cannot eat up all available buffer space. This occurs when our
1290 * minimum cannot be met. We try to size hidirtybuffers to 3/4 our
1291 * buffer space assuming BKVASIZE'd buffers.
1292 */
1293 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
1294 hidirtybuffers >>= 1;
1295 }
1296 lodirtybuffers = hidirtybuffers / 2;
1297
1298 /*
1299 * lofreebuffers should be sufficient to avoid stalling waiting on
1300 * buf headers under heavy utilization. The bufs in per-cpu caches
1301 * are counted as free but will be unavailable to threads executing
1302 * on other cpus.
1303 *
1304 * hifreebuffers is the free target for the bufspace daemon. This
1305 * should be set appropriately to limit work per-iteration.
1306 */
1307 lofreebuffers = MIN((nbuf / 25) + (20 * mp_ncpus), 128 * mp_ncpus);
1308 hifreebuffers = (3 * lofreebuffers) / 2;
1309 numfreebuffers = nbuf;
1310
1311 /* Setup the kva and free list allocators. */
1312 vmem_set_reclaim(buffer_arena, bufkva_reclaim);
1313 buf_zone = uma_zcache_create("buf free cache",
1314 sizeof(struct buf) + sizeof(vm_page_t) * atop(maxbcachebuf),
1315 NULL, NULL, NULL, NULL, buf_import, buf_release, NULL, 0);
1316
1317 /*
1318 * Size the clean queue according to the amount of buffer space.
1319 * One queue per-256mb up to the max. More queues gives better
1320 * concurrency but less accurate LRU.
1321 */
1322 buf_domains = MIN(howmany(maxbufspace, 256*1024*1024), BUF_DOMAINS);
1323 for (i = 0 ; i < buf_domains; i++) {
1324 struct bufdomain *bd;
1325
1326 bd = &bdomain[i];
1327 bd_init(bd);
1328 bd->bd_freebuffers = nbuf / buf_domains;
1329 bd->bd_hifreebuffers = hifreebuffers / buf_domains;
1330 bd->bd_lofreebuffers = lofreebuffers / buf_domains;
1331 bd->bd_bufspace = 0;
1332 bd->bd_maxbufspace = maxbufspace / buf_domains;
1333 bd->bd_hibufspace = hibufspace / buf_domains;
1334 bd->bd_lobufspace = lobufspace / buf_domains;
1335 bd->bd_bufspacethresh = bufspacethresh / buf_domains;
1336 bd->bd_numdirtybuffers = 0;
1337 bd->bd_hidirtybuffers = hidirtybuffers / buf_domains;
1338 bd->bd_lodirtybuffers = lodirtybuffers / buf_domains;
1339 bd->bd_dirtybufthresh = dirtybufthresh / buf_domains;
1340 /* Don't allow more than 2% of bufs in the per-cpu caches. */
1341 bd->bd_lim = nbuf / buf_domains / 50 / mp_ncpus;
1342 }
1343 getnewbufcalls = counter_u64_alloc(M_WAITOK);
1344 getnewbufrestarts = counter_u64_alloc(M_WAITOK);
1345 mappingrestarts = counter_u64_alloc(M_WAITOK);
1346 numbufallocfails = counter_u64_alloc(M_WAITOK);
1347 notbufdflushes = counter_u64_alloc(M_WAITOK);
1348 buffreekvacnt = counter_u64_alloc(M_WAITOK);
1349 bufdefragcnt = counter_u64_alloc(M_WAITOK);
1350 bufkvaspace = counter_u64_alloc(M_WAITOK);
1351 TSEXIT();
1352 }
1353
1354 #ifdef INVARIANTS
1355 static inline void
vfs_buf_check_mapped(struct buf * bp)1356 vfs_buf_check_mapped(struct buf *bp)
1357 {
1358
1359 KASSERT(bp->b_kvabase != unmapped_buf,
1360 ("mapped buf: b_kvabase was not updated %p", bp));
1361 KASSERT(bp->b_data != unmapped_buf,
1362 ("mapped buf: b_data was not updated %p", bp));
1363 KASSERT(bp->b_data < unmapped_buf || bp->b_data >= unmapped_buf +
1364 maxphys, ("b_data + b_offset unmapped %p", bp));
1365 }
1366
1367 static inline void
vfs_buf_check_unmapped(struct buf * bp)1368 vfs_buf_check_unmapped(struct buf *bp)
1369 {
1370
1371 KASSERT(bp->b_data == unmapped_buf,
1372 ("unmapped buf: corrupted b_data %p", bp));
1373 }
1374
1375 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
1376 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
1377 #else
1378 #define BUF_CHECK_MAPPED(bp) do {} while (0)
1379 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
1380 #endif
1381
1382 static int
isbufbusy(struct buf * bp)1383 isbufbusy(struct buf *bp)
1384 {
1385 if (((bp->b_flags & B_INVAL) == 0 && BUF_ISLOCKED(bp)) ||
1386 ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI))
1387 return (1);
1388 return (0);
1389 }
1390
1391 /*
1392 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
1393 */
1394 void
bufshutdown(int show_busybufs)1395 bufshutdown(int show_busybufs)
1396 {
1397 static int first_buf_printf = 1;
1398 struct buf *bp;
1399 int i, iter, nbusy, pbusy;
1400 #ifndef PREEMPTION
1401 int subiter;
1402 #endif
1403
1404 /*
1405 * Sync filesystems for shutdown
1406 */
1407 wdog_kern_pat(WD_LASTVAL);
1408 kern_sync(curthread);
1409
1410 /*
1411 * With soft updates, some buffers that are
1412 * written will be remarked as dirty until other
1413 * buffers are written.
1414 */
1415 for (iter = pbusy = 0; iter < 20; iter++) {
1416 nbusy = 0;
1417 for (i = nbuf - 1; i >= 0; i--) {
1418 bp = nbufp(i);
1419 if (isbufbusy(bp))
1420 nbusy++;
1421 }
1422 if (nbusy == 0) {
1423 if (first_buf_printf)
1424 printf("All buffers synced.");
1425 break;
1426 }
1427 if (first_buf_printf) {
1428 printf("Syncing disks, buffers remaining... ");
1429 first_buf_printf = 0;
1430 }
1431 printf("%d ", nbusy);
1432 if (nbusy < pbusy)
1433 iter = 0;
1434 pbusy = nbusy;
1435
1436 wdog_kern_pat(WD_LASTVAL);
1437 kern_sync(curthread);
1438
1439 #ifdef PREEMPTION
1440 /*
1441 * Spin for a while to allow interrupt threads to run.
1442 */
1443 DELAY(50000 * iter);
1444 #else
1445 /*
1446 * Context switch several times to allow interrupt
1447 * threads to run.
1448 */
1449 for (subiter = 0; subiter < 50 * iter; subiter++) {
1450 sched_relinquish(curthread);
1451 DELAY(1000);
1452 }
1453 #endif
1454 }
1455 printf("\n");
1456 /*
1457 * Count only busy local buffers to prevent forcing
1458 * a fsck if we're just a client of a wedged NFS server
1459 */
1460 nbusy = 0;
1461 for (i = nbuf - 1; i >= 0; i--) {
1462 bp = nbufp(i);
1463 if (isbufbusy(bp)) {
1464 #if 0
1465 /* XXX: This is bogus. We should probably have a BO_REMOTE flag instead */
1466 if (bp->b_dev == NULL) {
1467 TAILQ_REMOVE(&mountlist,
1468 bp->b_vp->v_mount, mnt_list);
1469 continue;
1470 }
1471 #endif
1472 nbusy++;
1473 if (show_busybufs > 0) {
1474 printf(
1475 "%d: buf:%p, vnode:%p, flags:%0x, blkno:%jd, lblkno:%jd, buflock:",
1476 nbusy, bp, bp->b_vp, bp->b_flags,
1477 (intmax_t)bp->b_blkno,
1478 (intmax_t)bp->b_lblkno);
1479 BUF_LOCKPRINTINFO(bp);
1480 if (show_busybufs > 1)
1481 vn_printf(bp->b_vp,
1482 "vnode content: ");
1483 }
1484 }
1485 }
1486 if (nbusy) {
1487 /*
1488 * Failed to sync all blocks. Indicate this and don't
1489 * unmount filesystems (thus forcing an fsck on reboot).
1490 */
1491 BOOTTRACE("shutdown failed to sync buffers");
1492 printf("Giving up on %d buffers\n", nbusy);
1493 DELAY(5000000); /* 5 seconds */
1494 swapoff_all();
1495 } else {
1496 BOOTTRACE("shutdown sync complete");
1497 if (!first_buf_printf)
1498 printf("Final sync complete\n");
1499
1500 /*
1501 * Unmount filesystems and perform swapoff, to quiesce
1502 * the system as much as possible. In particular, no
1503 * I/O should be initiated from top levels since it
1504 * might be abruptly terminated by reset, or otherwise
1505 * erronously handled because other parts of the
1506 * system are disabled.
1507 *
1508 * Swapoff before unmount, because file-backed swap is
1509 * non-operational after unmount of the underlying
1510 * filesystem.
1511 */
1512 if (!KERNEL_PANICKED()) {
1513 swapoff_all();
1514 vfs_unmountall();
1515 BOOTTRACE("shutdown unmounted all filesystems");
1516 }
1517 }
1518 DELAY(100000); /* wait for console output to finish */
1519 }
1520
1521 static void
bpmap_qenter(struct buf * bp)1522 bpmap_qenter(struct buf *bp)
1523 {
1524
1525 BUF_CHECK_MAPPED(bp);
1526
1527 /*
1528 * bp->b_data is relative to bp->b_offset, but
1529 * bp->b_offset may be offset into the first page.
1530 */
1531 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
1532 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
1533 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
1534 (vm_offset_t)(bp->b_offset & PAGE_MASK));
1535 }
1536
1537 static inline struct bufdomain *
bufdomain(struct buf * bp)1538 bufdomain(struct buf *bp)
1539 {
1540
1541 return (&bdomain[bp->b_domain]);
1542 }
1543
1544 static struct bufqueue *
bufqueue(struct buf * bp)1545 bufqueue(struct buf *bp)
1546 {
1547
1548 switch (bp->b_qindex) {
1549 case QUEUE_NONE:
1550 /* FALLTHROUGH */
1551 case QUEUE_SENTINEL:
1552 return (NULL);
1553 case QUEUE_EMPTY:
1554 return (&bqempty);
1555 case QUEUE_DIRTY:
1556 return (&bufdomain(bp)->bd_dirtyq);
1557 case QUEUE_CLEAN:
1558 return (&bufdomain(bp)->bd_subq[bp->b_subqueue]);
1559 default:
1560 break;
1561 }
1562 panic("bufqueue(%p): Unhandled type %d\n", bp, bp->b_qindex);
1563 }
1564
1565 /*
1566 * Return the locked bufqueue that bp is a member of.
1567 */
1568 static struct bufqueue *
bufqueue_acquire(struct buf * bp)1569 bufqueue_acquire(struct buf *bp)
1570 {
1571 struct bufqueue *bq, *nbq;
1572
1573 /*
1574 * bp can be pushed from a per-cpu queue to the
1575 * cleanq while we're waiting on the lock. Retry
1576 * if the queues don't match.
1577 */
1578 bq = bufqueue(bp);
1579 BQ_LOCK(bq);
1580 for (;;) {
1581 nbq = bufqueue(bp);
1582 if (bq == nbq)
1583 break;
1584 BQ_UNLOCK(bq);
1585 BQ_LOCK(nbq);
1586 bq = nbq;
1587 }
1588 return (bq);
1589 }
1590
1591 /*
1592 * binsfree:
1593 *
1594 * Insert the buffer into the appropriate free list. Requires a
1595 * locked buffer on entry and buffer is unlocked before return.
1596 */
1597 static void
binsfree(struct buf * bp,int qindex)1598 binsfree(struct buf *bp, int qindex)
1599 {
1600 struct bufdomain *bd;
1601 struct bufqueue *bq;
1602
1603 KASSERT(qindex == QUEUE_CLEAN || qindex == QUEUE_DIRTY,
1604 ("binsfree: Invalid qindex %d", qindex));
1605 BUF_ASSERT_XLOCKED(bp);
1606
1607 /*
1608 * Handle delayed bremfree() processing.
1609 */
1610 if (bp->b_flags & B_REMFREE) {
1611 if (bp->b_qindex == qindex) {
1612 bp->b_flags |= B_REUSE;
1613 bp->b_flags &= ~B_REMFREE;
1614 BUF_UNLOCK(bp);
1615 return;
1616 }
1617 bq = bufqueue_acquire(bp);
1618 bq_remove(bq, bp);
1619 BQ_UNLOCK(bq);
1620 }
1621 bd = bufdomain(bp);
1622 if (qindex == QUEUE_CLEAN) {
1623 if (bd->bd_lim != 0)
1624 bq = &bd->bd_subq[PCPU_GET(cpuid)];
1625 else
1626 bq = bd->bd_cleanq;
1627 } else
1628 bq = &bd->bd_dirtyq;
1629 bq_insert(bq, bp, true);
1630 }
1631
1632 /*
1633 * buf_free:
1634 *
1635 * Free a buffer to the buf zone once it no longer has valid contents.
1636 */
1637 static void
buf_free(struct buf * bp)1638 buf_free(struct buf *bp)
1639 {
1640
1641 if (bp->b_flags & B_REMFREE)
1642 bremfreef(bp);
1643 if (bp->b_vflags & BV_BKGRDINPROG)
1644 panic("losing buffer 1");
1645 if (bp->b_rcred != NOCRED) {
1646 crfree(bp->b_rcred);
1647 bp->b_rcred = NOCRED;
1648 }
1649 if (bp->b_wcred != NOCRED) {
1650 crfree(bp->b_wcred);
1651 bp->b_wcred = NOCRED;
1652 }
1653 if (!LIST_EMPTY(&bp->b_dep))
1654 buf_deallocate(bp);
1655 bufkva_free(bp);
1656 atomic_add_int(&bufdomain(bp)->bd_freebuffers, 1);
1657 MPASS((bp->b_flags & B_MAXPHYS) == 0);
1658 BUF_UNLOCK(bp);
1659 uma_zfree(buf_zone, bp);
1660 }
1661
1662 /*
1663 * buf_import:
1664 *
1665 * Import bufs into the uma cache from the buf list. The system still
1666 * expects a static array of bufs and much of the synchronization
1667 * around bufs assumes type stable storage. As a result, UMA is used
1668 * only as a per-cpu cache of bufs still maintained on a global list.
1669 */
1670 static int
buf_import(void * arg,void ** store,int cnt,int domain,int flags)1671 buf_import(void *arg, void **store, int cnt, int domain, int flags)
1672 {
1673 struct buf *bp;
1674 int i;
1675
1676 BQ_LOCK(&bqempty);
1677 for (i = 0; i < cnt; i++) {
1678 bp = TAILQ_FIRST(&bqempty.bq_queue);
1679 if (bp == NULL)
1680 break;
1681 bq_remove(&bqempty, bp);
1682 store[i] = bp;
1683 }
1684 BQ_UNLOCK(&bqempty);
1685
1686 return (i);
1687 }
1688
1689 /*
1690 * buf_release:
1691 *
1692 * Release bufs from the uma cache back to the buffer queues.
1693 */
1694 static void
buf_release(void * arg,void ** store,int cnt)1695 buf_release(void *arg, void **store, int cnt)
1696 {
1697 struct bufqueue *bq;
1698 struct buf *bp;
1699 int i;
1700
1701 bq = &bqempty;
1702 BQ_LOCK(bq);
1703 for (i = 0; i < cnt; i++) {
1704 bp = store[i];
1705 /* Inline bq_insert() to batch locking. */
1706 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist);
1707 bp->b_flags &= ~(B_AGE | B_REUSE);
1708 bq->bq_len++;
1709 bp->b_qindex = bq->bq_index;
1710 }
1711 BQ_UNLOCK(bq);
1712 }
1713
1714 /*
1715 * buf_alloc:
1716 *
1717 * Allocate an empty buffer header.
1718 */
1719 static struct buf *
buf_alloc(struct bufdomain * bd)1720 buf_alloc(struct bufdomain *bd)
1721 {
1722 struct buf *bp;
1723 int freebufs, error;
1724
1725 /*
1726 * We can only run out of bufs in the buf zone if the average buf
1727 * is less than BKVASIZE. In this case the actual wait/block will
1728 * come from buf_reycle() failing to flush one of these small bufs.
1729 */
1730 bp = NULL;
1731 freebufs = atomic_fetchadd_int(&bd->bd_freebuffers, -1);
1732 if (freebufs > 0)
1733 bp = uma_zalloc(buf_zone, M_NOWAIT);
1734 if (bp == NULL) {
1735 atomic_add_int(&bd->bd_freebuffers, 1);
1736 bufspace_daemon_wakeup(bd);
1737 counter_u64_add(numbufallocfails, 1);
1738 return (NULL);
1739 }
1740 /*
1741 * Wake-up the bufspace daemon on transition below threshold.
1742 */
1743 if (freebufs == bd->bd_lofreebuffers)
1744 bufspace_daemon_wakeup(bd);
1745
1746 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWITNESS, NULL);
1747 KASSERT(error == 0, ("%s: BUF_LOCK on free buf %p: %d.", __func__, bp,
1748 error));
1749 (void)error;
1750
1751 KASSERT(bp->b_vp == NULL,
1752 ("bp: %p still has vnode %p.", bp, bp->b_vp));
1753 KASSERT((bp->b_flags & (B_DELWRI | B_NOREUSE)) == 0,
1754 ("invalid buffer %p flags %#x", bp, bp->b_flags));
1755 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1756 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
1757 KASSERT(bp->b_npages == 0,
1758 ("bp: %p still has %d vm pages\n", bp, bp->b_npages));
1759 KASSERT(bp->b_kvasize == 0, ("bp: %p still has kva\n", bp));
1760 KASSERT(bp->b_bufsize == 0, ("bp: %p still has bufspace\n", bp));
1761 MPASS((bp->b_flags & B_MAXPHYS) == 0);
1762
1763 bp->b_domain = BD_DOMAIN(bd);
1764 bp->b_flags = 0;
1765 bp->b_ioflags = 0;
1766 bp->b_xflags = 0;
1767 bp->b_vflags = 0;
1768 bp->b_vp = NULL;
1769 bp->b_blkno = bp->b_lblkno = 0;
1770 bp->b_offset = NOOFFSET;
1771 bp->b_iodone = 0;
1772 bp->b_error = 0;
1773 bp->b_resid = 0;
1774 bp->b_bcount = 0;
1775 bp->b_npages = 0;
1776 bp->b_dirtyoff = bp->b_dirtyend = 0;
1777 bp->b_bufobj = NULL;
1778 bp->b_data = bp->b_kvabase = unmapped_buf;
1779 bp->b_fsprivate1 = NULL;
1780 bp->b_fsprivate2 = NULL;
1781 bp->b_fsprivate3 = NULL;
1782 LIST_INIT(&bp->b_dep);
1783
1784 return (bp);
1785 }
1786
1787 /*
1788 * buf_recycle:
1789 *
1790 * Free a buffer from the given bufqueue. kva controls whether the
1791 * freed buf must own some kva resources. This is used for
1792 * defragmenting.
1793 */
1794 static int
buf_recycle(struct bufdomain * bd,bool kva)1795 buf_recycle(struct bufdomain *bd, bool kva)
1796 {
1797 struct bufqueue *bq;
1798 struct buf *bp, *nbp;
1799
1800 if (kva)
1801 counter_u64_add(bufdefragcnt, 1);
1802 nbp = NULL;
1803 bq = bd->bd_cleanq;
1804 BQ_LOCK(bq);
1805 KASSERT(BQ_LOCKPTR(bq) == BD_LOCKPTR(bd),
1806 ("buf_recycle: Locks don't match"));
1807 nbp = TAILQ_FIRST(&bq->bq_queue);
1808
1809 /*
1810 * Run scan, possibly freeing data and/or kva mappings on the fly
1811 * depending.
1812 */
1813 while ((bp = nbp) != NULL) {
1814 /*
1815 * Calculate next bp (we can only use it if we do not
1816 * release the bqlock).
1817 */
1818 nbp = TAILQ_NEXT(bp, b_freelist);
1819
1820 /*
1821 * If we are defragging then we need a buffer with
1822 * some kva to reclaim.
1823 */
1824 if (kva && bp->b_kvasize == 0)
1825 continue;
1826
1827 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1828 continue;
1829
1830 /*
1831 * Implement a second chance algorithm for frequently
1832 * accessed buffers.
1833 */
1834 if ((bp->b_flags & B_REUSE) != 0) {
1835 TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist);
1836 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist);
1837 bp->b_flags &= ~B_REUSE;
1838 BUF_UNLOCK(bp);
1839 continue;
1840 }
1841
1842 /*
1843 * Skip buffers with background writes in progress.
1844 */
1845 if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
1846 BUF_UNLOCK(bp);
1847 continue;
1848 }
1849
1850 KASSERT(bp->b_qindex == QUEUE_CLEAN,
1851 ("buf_recycle: inconsistent queue %d bp %p",
1852 bp->b_qindex, bp));
1853 KASSERT(bp->b_domain == BD_DOMAIN(bd),
1854 ("getnewbuf: queue domain %d doesn't match request %d",
1855 bp->b_domain, (int)BD_DOMAIN(bd)));
1856 /*
1857 * NOTE: nbp is now entirely invalid. We can only restart
1858 * the scan from this point on.
1859 */
1860 bq_remove(bq, bp);
1861 BQ_UNLOCK(bq);
1862
1863 /*
1864 * Requeue the background write buffer with error and
1865 * restart the scan.
1866 */
1867 if ((bp->b_vflags & BV_BKGRDERR) != 0) {
1868 bqrelse(bp);
1869 BQ_LOCK(bq);
1870 nbp = TAILQ_FIRST(&bq->bq_queue);
1871 continue;
1872 }
1873 bp->b_flags |= B_INVAL;
1874 brelse(bp);
1875 return (0);
1876 }
1877 bd->bd_wanted = 1;
1878 BQ_UNLOCK(bq);
1879
1880 return (ENOBUFS);
1881 }
1882
1883 /*
1884 * bremfree:
1885 *
1886 * Mark the buffer for removal from the appropriate free list.
1887 *
1888 */
1889 void
bremfree(struct buf * bp)1890 bremfree(struct buf *bp)
1891 {
1892
1893 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1894 KASSERT((bp->b_flags & B_REMFREE) == 0,
1895 ("bremfree: buffer %p already marked for delayed removal.", bp));
1896 KASSERT(bp->b_qindex != QUEUE_NONE,
1897 ("bremfree: buffer %p not on a queue.", bp));
1898 BUF_ASSERT_XLOCKED(bp);
1899
1900 bp->b_flags |= B_REMFREE;
1901 }
1902
1903 /*
1904 * bremfreef:
1905 *
1906 * Force an immediate removal from a free list. Used only in nfs when
1907 * it abuses the b_freelist pointer.
1908 */
1909 void
bremfreef(struct buf * bp)1910 bremfreef(struct buf *bp)
1911 {
1912 struct bufqueue *bq;
1913
1914 bq = bufqueue_acquire(bp);
1915 bq_remove(bq, bp);
1916 BQ_UNLOCK(bq);
1917 }
1918
1919 static void
bq_init(struct bufqueue * bq,int qindex,int subqueue,const char * lockname)1920 bq_init(struct bufqueue *bq, int qindex, int subqueue, const char *lockname)
1921 {
1922
1923 mtx_init(&bq->bq_lock, lockname, NULL, MTX_DEF);
1924 TAILQ_INIT(&bq->bq_queue);
1925 bq->bq_len = 0;
1926 bq->bq_index = qindex;
1927 bq->bq_subqueue = subqueue;
1928 }
1929
1930 static void
bd_init(struct bufdomain * bd)1931 bd_init(struct bufdomain *bd)
1932 {
1933 int i;
1934
1935 /* Per-CPU clean buf queues, plus one global queue. */
1936 bd->bd_subq = mallocarray(mp_maxid + 2, sizeof(struct bufqueue),
1937 M_BIOBUF, M_WAITOK | M_ZERO);
1938 bd->bd_cleanq = &bd->bd_subq[mp_maxid + 1];
1939 bq_init(bd->bd_cleanq, QUEUE_CLEAN, mp_maxid + 1, "bufq clean lock");
1940 bq_init(&bd->bd_dirtyq, QUEUE_DIRTY, -1, "bufq dirty lock");
1941 for (i = 0; i <= mp_maxid; i++)
1942 bq_init(&bd->bd_subq[i], QUEUE_CLEAN, i,
1943 "bufq clean subqueue lock");
1944 mtx_init(&bd->bd_run_lock, "bufspace daemon run lock", NULL, MTX_DEF);
1945 }
1946
1947 /*
1948 * bq_remove:
1949 *
1950 * Removes a buffer from the free list, must be called with the
1951 * correct qlock held.
1952 */
1953 static void
bq_remove(struct bufqueue * bq,struct buf * bp)1954 bq_remove(struct bufqueue *bq, struct buf *bp)
1955 {
1956
1957 CTR3(KTR_BUF, "bq_remove(%p) vp %p flags %X",
1958 bp, bp->b_vp, bp->b_flags);
1959 KASSERT(bp->b_qindex != QUEUE_NONE,
1960 ("bq_remove: buffer %p not on a queue.", bp));
1961 KASSERT(bufqueue(bp) == bq,
1962 ("bq_remove: Remove buffer %p from wrong queue.", bp));
1963
1964 BQ_ASSERT_LOCKED(bq);
1965 if (bp->b_qindex != QUEUE_EMPTY) {
1966 BUF_ASSERT_XLOCKED(bp);
1967 }
1968 KASSERT(bq->bq_len >= 1,
1969 ("queue %d underflow", bp->b_qindex));
1970 TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist);
1971 bq->bq_len--;
1972 bp->b_qindex = QUEUE_NONE;
1973 bp->b_flags &= ~(B_REMFREE | B_REUSE);
1974 }
1975
1976 static void
bd_flush(struct bufdomain * bd,struct bufqueue * bq)1977 bd_flush(struct bufdomain *bd, struct bufqueue *bq)
1978 {
1979 struct buf *bp;
1980
1981 BQ_ASSERT_LOCKED(bq);
1982 if (bq != bd->bd_cleanq) {
1983 BD_LOCK(bd);
1984 while ((bp = TAILQ_FIRST(&bq->bq_queue)) != NULL) {
1985 TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist);
1986 TAILQ_INSERT_TAIL(&bd->bd_cleanq->bq_queue, bp,
1987 b_freelist);
1988 bp->b_subqueue = bd->bd_cleanq->bq_subqueue;
1989 }
1990 bd->bd_cleanq->bq_len += bq->bq_len;
1991 bq->bq_len = 0;
1992 }
1993 if (bd->bd_wanted) {
1994 bd->bd_wanted = 0;
1995 wakeup(&bd->bd_wanted);
1996 }
1997 if (bq != bd->bd_cleanq)
1998 BD_UNLOCK(bd);
1999 }
2000
2001 static int
bd_flushall(struct bufdomain * bd)2002 bd_flushall(struct bufdomain *bd)
2003 {
2004 struct bufqueue *bq;
2005 int flushed;
2006 int i;
2007
2008 if (bd->bd_lim == 0)
2009 return (0);
2010 flushed = 0;
2011 for (i = 0; i <= mp_maxid; i++) {
2012 bq = &bd->bd_subq[i];
2013 if (bq->bq_len == 0)
2014 continue;
2015 BQ_LOCK(bq);
2016 bd_flush(bd, bq);
2017 BQ_UNLOCK(bq);
2018 flushed++;
2019 }
2020
2021 return (flushed);
2022 }
2023
2024 static void
bq_insert(struct bufqueue * bq,struct buf * bp,bool unlock)2025 bq_insert(struct bufqueue *bq, struct buf *bp, bool unlock)
2026 {
2027 struct bufdomain *bd;
2028
2029 if (bp->b_qindex != QUEUE_NONE)
2030 panic("bq_insert: free buffer %p onto another queue?", bp);
2031
2032 bd = bufdomain(bp);
2033 if (bp->b_flags & B_AGE) {
2034 /* Place this buf directly on the real queue. */
2035 if (bq->bq_index == QUEUE_CLEAN)
2036 bq = bd->bd_cleanq;
2037 BQ_LOCK(bq);
2038 TAILQ_INSERT_HEAD(&bq->bq_queue, bp, b_freelist);
2039 } else {
2040 BQ_LOCK(bq);
2041 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist);
2042 }
2043 bp->b_flags &= ~(B_AGE | B_REUSE);
2044 bq->bq_len++;
2045 bp->b_qindex = bq->bq_index;
2046 bp->b_subqueue = bq->bq_subqueue;
2047
2048 /*
2049 * Unlock before we notify so that we don't wakeup a waiter that
2050 * fails a trylock on the buf and sleeps again.
2051 */
2052 if (unlock)
2053 BUF_UNLOCK(bp);
2054
2055 if (bp->b_qindex == QUEUE_CLEAN) {
2056 /*
2057 * Flush the per-cpu queue and notify any waiters.
2058 */
2059 if (bd->bd_wanted || (bq != bd->bd_cleanq &&
2060 bq->bq_len >= bd->bd_lim))
2061 bd_flush(bd, bq);
2062 }
2063 BQ_UNLOCK(bq);
2064 }
2065
2066 /*
2067 * bufkva_free:
2068 *
2069 * Free the kva allocation for a buffer.
2070 *
2071 */
2072 static void
bufkva_free(struct buf * bp)2073 bufkva_free(struct buf *bp)
2074 {
2075
2076 #ifdef INVARIANTS
2077 if (bp->b_kvasize == 0) {
2078 KASSERT(bp->b_kvabase == unmapped_buf &&
2079 bp->b_data == unmapped_buf,
2080 ("Leaked KVA space on %p", bp));
2081 } else if (buf_mapped(bp))
2082 BUF_CHECK_MAPPED(bp);
2083 else
2084 BUF_CHECK_UNMAPPED(bp);
2085 #endif
2086 if (bp->b_kvasize == 0)
2087 return;
2088
2089 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase, bp->b_kvasize);
2090 counter_u64_add(bufkvaspace, -bp->b_kvasize);
2091 counter_u64_add(buffreekvacnt, 1);
2092 bp->b_data = bp->b_kvabase = unmapped_buf;
2093 bp->b_kvasize = 0;
2094 }
2095
2096 /*
2097 * bufkva_alloc:
2098 *
2099 * Allocate the buffer KVA and set b_kvasize and b_kvabase.
2100 */
2101 static int
bufkva_alloc(struct buf * bp,int maxsize,int gbflags)2102 bufkva_alloc(struct buf *bp, int maxsize, int gbflags)
2103 {
2104 vm_offset_t addr;
2105 int error;
2106
2107 KASSERT((gbflags & GB_UNMAPPED) == 0 || (gbflags & GB_KVAALLOC) != 0,
2108 ("Invalid gbflags 0x%x in %s", gbflags, __func__));
2109 MPASS((bp->b_flags & B_MAXPHYS) == 0);
2110 KASSERT(maxsize <= maxbcachebuf,
2111 ("bufkva_alloc kva too large %d %u", maxsize, maxbcachebuf));
2112
2113 bufkva_free(bp);
2114
2115 addr = 0;
2116 error = vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr);
2117 if (error != 0) {
2118 /*
2119 * Buffer map is too fragmented. Request the caller
2120 * to defragment the map.
2121 */
2122 return (error);
2123 }
2124 bp->b_kvabase = (caddr_t)addr;
2125 bp->b_kvasize = maxsize;
2126 counter_u64_add(bufkvaspace, bp->b_kvasize);
2127 if ((gbflags & GB_UNMAPPED) != 0) {
2128 bp->b_data = unmapped_buf;
2129 BUF_CHECK_UNMAPPED(bp);
2130 } else {
2131 bp->b_data = bp->b_kvabase;
2132 BUF_CHECK_MAPPED(bp);
2133 }
2134 return (0);
2135 }
2136
2137 /*
2138 * bufkva_reclaim:
2139 *
2140 * Reclaim buffer kva by freeing buffers holding kva. This is a vmem
2141 * callback that fires to avoid returning failure.
2142 */
2143 static void
bufkva_reclaim(vmem_t * vmem,int flags)2144 bufkva_reclaim(vmem_t *vmem, int flags)
2145 {
2146 bool done;
2147 int q;
2148 int i;
2149
2150 done = false;
2151 for (i = 0; i < 5; i++) {
2152 for (q = 0; q < buf_domains; q++)
2153 if (buf_recycle(&bdomain[q], true) != 0)
2154 done = true;
2155 if (done)
2156 break;
2157 }
2158 return;
2159 }
2160
2161 /*
2162 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
2163 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
2164 * the buffer is valid and we do not have to do anything.
2165 */
2166 static void
breada(struct vnode * vp,daddr_t * rablkno,int * rabsize,int cnt,struct ucred * cred,int flags,void (* ckhashfunc)(struct buf *))2167 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize, int cnt,
2168 struct ucred * cred, int flags, void (*ckhashfunc)(struct buf *))
2169 {
2170 struct buf *rabp;
2171 struct thread *td;
2172 int i;
2173
2174 td = curthread;
2175
2176 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
2177 if (inmem(vp, *rablkno))
2178 continue;
2179 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
2180 if ((rabp->b_flags & B_CACHE) != 0) {
2181 brelse(rabp);
2182 continue;
2183 }
2184 #ifdef RACCT
2185 if (racct_enable) {
2186 PROC_LOCK(curproc);
2187 racct_add_buf(curproc, rabp, 0);
2188 PROC_UNLOCK(curproc);
2189 }
2190 #endif /* RACCT */
2191 td->td_ru.ru_inblock++;
2192 rabp->b_flags |= B_ASYNC;
2193 rabp->b_flags &= ~B_INVAL;
2194 if ((flags & GB_CKHASH) != 0) {
2195 rabp->b_flags |= B_CKHASH;
2196 rabp->b_ckhashcalc = ckhashfunc;
2197 }
2198 rabp->b_ioflags &= ~BIO_ERROR;
2199 rabp->b_iocmd = BIO_READ;
2200 if (rabp->b_rcred == NOCRED && cred != NOCRED)
2201 rabp->b_rcred = crhold(cred);
2202 vfs_busy_pages(rabp, 0);
2203 BUF_KERNPROC(rabp);
2204 rabp->b_iooffset = dbtob(rabp->b_blkno);
2205 bstrategy(rabp);
2206 }
2207 }
2208
2209 /*
2210 * Entry point for bread() and breadn() via #defines in sys/buf.h.
2211 *
2212 * Get a buffer with the specified data. Look in the cache first. We
2213 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
2214 * is set, the buffer is valid and we do not have to do anything, see
2215 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
2216 *
2217 * Always return a NULL buffer pointer (in bpp) when returning an error.
2218 *
2219 * The blkno parameter is the logical block being requested. Normally
2220 * the mapping of logical block number to disk block address is done
2221 * by calling VOP_BMAP(). However, if the mapping is already known, the
2222 * disk block address can be passed using the dblkno parameter. If the
2223 * disk block address is not known, then the same value should be passed
2224 * for blkno and dblkno.
2225 */
2226 int
breadn_flags(struct vnode * vp,daddr_t blkno,daddr_t dblkno,int size,daddr_t * rablkno,int * rabsize,int cnt,struct ucred * cred,int flags,void (* ckhashfunc)(struct buf *),struct buf ** bpp)2227 breadn_flags(struct vnode *vp, daddr_t blkno, daddr_t dblkno, int size,
2228 daddr_t *rablkno, int *rabsize, int cnt, struct ucred *cred, int flags,
2229 void (*ckhashfunc)(struct buf *), struct buf **bpp)
2230 {
2231 struct buf *bp;
2232 struct thread *td;
2233 int error, readwait, rv;
2234
2235 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
2236 td = curthread;
2237 /*
2238 * Can only return NULL if GB_LOCK_NOWAIT or GB_SPARSE flags
2239 * are specified.
2240 */
2241 error = getblkx(vp, blkno, dblkno, size, 0, 0, flags, &bp);
2242 if (error != 0) {
2243 *bpp = NULL;
2244 return (error);
2245 }
2246 KASSERT(blkno == bp->b_lblkno,
2247 ("getblkx returned buffer for blkno %jd instead of blkno %jd",
2248 (intmax_t)bp->b_lblkno, (intmax_t)blkno));
2249 flags &= ~GB_NOSPARSE;
2250 *bpp = bp;
2251
2252 /*
2253 * If not found in cache, do some I/O
2254 */
2255 readwait = 0;
2256 if ((bp->b_flags & B_CACHE) == 0) {
2257 #ifdef RACCT
2258 if (racct_enable) {
2259 PROC_LOCK(td->td_proc);
2260 racct_add_buf(td->td_proc, bp, 0);
2261 PROC_UNLOCK(td->td_proc);
2262 }
2263 #endif /* RACCT */
2264 td->td_ru.ru_inblock++;
2265 bp->b_iocmd = BIO_READ;
2266 bp->b_flags &= ~B_INVAL;
2267 if ((flags & GB_CKHASH) != 0) {
2268 bp->b_flags |= B_CKHASH;
2269 bp->b_ckhashcalc = ckhashfunc;
2270 }
2271 if ((flags & GB_CVTENXIO) != 0)
2272 bp->b_xflags |= BX_CVTENXIO;
2273 bp->b_ioflags &= ~BIO_ERROR;
2274 if (bp->b_rcred == NOCRED && cred != NOCRED)
2275 bp->b_rcred = crhold(cred);
2276 vfs_busy_pages(bp, 0);
2277 bp->b_iooffset = dbtob(bp->b_blkno);
2278 bstrategy(bp);
2279 ++readwait;
2280 }
2281
2282 /*
2283 * Attempt to initiate asynchronous I/O on read-ahead blocks.
2284 */
2285 breada(vp, rablkno, rabsize, cnt, cred, flags, ckhashfunc);
2286
2287 rv = 0;
2288 if (readwait) {
2289 rv = bufwait(bp);
2290 if (rv != 0) {
2291 brelse(bp);
2292 *bpp = NULL;
2293 }
2294 }
2295 return (rv);
2296 }
2297
2298 /*
2299 * Write, release buffer on completion. (Done by iodone
2300 * if async). Do not bother writing anything if the buffer
2301 * is invalid.
2302 *
2303 * Note that we set B_CACHE here, indicating that buffer is
2304 * fully valid and thus cacheable. This is true even of NFS
2305 * now so we set it generally. This could be set either here
2306 * or in biodone() since the I/O is synchronous. We put it
2307 * here.
2308 */
2309 int
bufwrite(struct buf * bp)2310 bufwrite(struct buf *bp)
2311 {
2312 struct vnode *vp;
2313 long space;
2314 int oldflags, retval;
2315 bool vp_md;
2316
2317 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2318 if ((bp->b_bufobj->bo_flag & BO_DEAD) != 0) {
2319 bp->b_flags |= B_INVAL | B_RELBUF;
2320 bp->b_flags &= ~B_CACHE;
2321 brelse(bp);
2322 return (ENXIO);
2323 }
2324 if ((bp->b_flags & B_INVAL) != 0) {
2325 brelse(bp);
2326 return (0);
2327 }
2328
2329 if ((bp->b_flags & B_BARRIER) != 0)
2330 atomic_add_long(&barrierwrites, 1);
2331
2332 oldflags = bp->b_flags;
2333
2334 KASSERT((bp->b_vflags & BV_BKGRDINPROG) == 0,
2335 ("FFS background buffer should not get here %p", bp));
2336
2337 vp = bp->b_vp;
2338 vp_md = vp != NULL && (vp->v_vflag & VV_MD) != 0;
2339
2340 /*
2341 * Mark the buffer clean. Increment the bufobj write count
2342 * before bundirty() call, to prevent other thread from seeing
2343 * empty dirty list and zero counter for writes in progress,
2344 * falsely indicating that the bufobj is clean.
2345 */
2346 bufobj_wref(bp->b_bufobj);
2347 bundirty(bp);
2348
2349 bp->b_flags &= ~B_DONE;
2350 bp->b_ioflags &= ~BIO_ERROR;
2351 bp->b_flags |= B_CACHE;
2352 bp->b_iocmd = BIO_WRITE;
2353
2354 vfs_busy_pages(bp, 1);
2355
2356 /*
2357 * Normal bwrites pipeline writes
2358 */
2359 space = runningbufclaim(bp, bp->b_bufsize);
2360
2361 #ifdef RACCT
2362 if (racct_enable) {
2363 PROC_LOCK(curproc);
2364 racct_add_buf(curproc, bp, 1);
2365 PROC_UNLOCK(curproc);
2366 }
2367 #endif /* RACCT */
2368 curthread->td_ru.ru_oublock++;
2369 if ((oldflags & B_ASYNC) != 0)
2370 BUF_KERNPROC(bp);
2371 bp->b_iooffset = dbtob(bp->b_blkno);
2372 buf_track(bp, __func__);
2373 bstrategy(bp);
2374
2375 if ((oldflags & B_ASYNC) == 0) {
2376 retval = bufwait(bp);
2377 brelse(bp);
2378 return (retval);
2379 } else if (space > hirunningspace) {
2380 /*
2381 * Don't allow the async write to saturate the I/O
2382 * system. We do not block here if it is the update
2383 * or syncer daemon trying to clean up as that can
2384 * lead to deadlock.
2385 */
2386 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
2387 waitrunningbufspace();
2388 }
2389
2390 return (0);
2391 }
2392
2393 void
bufbdflush(struct bufobj * bo,struct buf * bp)2394 bufbdflush(struct bufobj *bo, struct buf *bp)
2395 {
2396 struct buf *nbp;
2397 struct bufdomain *bd;
2398
2399 bd = &bdomain[bo->bo_domain];
2400 if (bo->bo_dirty.bv_cnt > bd->bd_dirtybufthresh + 10) {
2401 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
2402 altbufferflushes++;
2403 } else if (bo->bo_dirty.bv_cnt > bd->bd_dirtybufthresh) {
2404 BO_LOCK(bo);
2405 /*
2406 * Try to find a buffer to flush.
2407 */
2408 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
2409 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
2410 BUF_LOCK(nbp,
2411 LK_EXCLUSIVE | LK_NOWAIT, NULL))
2412 continue;
2413 if (bp == nbp)
2414 panic("bdwrite: found ourselves");
2415 BO_UNLOCK(bo);
2416 /* Don't countdeps with the bo lock held. */
2417 if (buf_countdeps(nbp, 0)) {
2418 BO_LOCK(bo);
2419 BUF_UNLOCK(nbp);
2420 continue;
2421 }
2422 if (nbp->b_flags & B_CLUSTEROK) {
2423 vfs_bio_awrite(nbp);
2424 } else {
2425 bremfree(nbp);
2426 bawrite(nbp);
2427 }
2428 dirtybufferflushes++;
2429 break;
2430 }
2431 if (nbp == NULL)
2432 BO_UNLOCK(bo);
2433 }
2434 }
2435
2436 /*
2437 * Delayed write. (Buffer is marked dirty). Do not bother writing
2438 * anything if the buffer is marked invalid.
2439 *
2440 * Note that since the buffer must be completely valid, we can safely
2441 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
2442 * biodone() in order to prevent getblk from writing the buffer
2443 * out synchronously.
2444 */
2445 void
bdwrite(struct buf * bp)2446 bdwrite(struct buf *bp)
2447 {
2448 struct thread *td = curthread;
2449 struct vnode *vp;
2450 struct bufobj *bo;
2451
2452 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2453 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2454 KASSERT((bp->b_flags & B_BARRIER) == 0,
2455 ("Barrier request in delayed write %p", bp));
2456
2457 if (bp->b_flags & B_INVAL) {
2458 brelse(bp);
2459 return;
2460 }
2461
2462 /*
2463 * If we have too many dirty buffers, don't create any more.
2464 * If we are wildly over our limit, then force a complete
2465 * cleanup. Otherwise, just keep the situation from getting
2466 * out of control. Note that we have to avoid a recursive
2467 * disaster and not try to clean up after our own cleanup!
2468 */
2469 vp = bp->b_vp;
2470 bo = bp->b_bufobj;
2471 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
2472 td->td_pflags |= TDP_INBDFLUSH;
2473 BO_BDFLUSH(bo, bp);
2474 td->td_pflags &= ~TDP_INBDFLUSH;
2475 } else
2476 recursiveflushes++;
2477
2478 bdirty(bp);
2479 /*
2480 * Set B_CACHE, indicating that the buffer is fully valid. This is
2481 * true even of NFS now.
2482 */
2483 bp->b_flags |= B_CACHE;
2484
2485 /*
2486 * This bmap keeps the system from needing to do the bmap later,
2487 * perhaps when the system is attempting to do a sync. Since it
2488 * is likely that the indirect block -- or whatever other datastructure
2489 * that the filesystem needs is still in memory now, it is a good
2490 * thing to do this. Note also, that if the pageout daemon is
2491 * requesting a sync -- there might not be enough memory to do
2492 * the bmap then... So, this is important to do.
2493 */
2494 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
2495 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
2496 }
2497
2498 buf_track(bp, __func__);
2499
2500 /*
2501 * Set the *dirty* buffer range based upon the VM system dirty
2502 * pages.
2503 *
2504 * Mark the buffer pages as clean. We need to do this here to
2505 * satisfy the vnode_pager and the pageout daemon, so that it
2506 * thinks that the pages have been "cleaned". Note that since
2507 * the pages are in a delayed write buffer -- the VFS layer
2508 * "will" see that the pages get written out on the next sync,
2509 * or perhaps the cluster will be completed.
2510 */
2511 vfs_clean_pages_dirty_buf(bp);
2512 bqrelse(bp);
2513
2514 /*
2515 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
2516 * due to the softdep code.
2517 */
2518 }
2519
2520 /*
2521 * bdirty:
2522 *
2523 * Turn buffer into delayed write request. We must clear BIO_READ and
2524 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
2525 * itself to properly update it in the dirty/clean lists. We mark it
2526 * B_DONE to ensure that any asynchronization of the buffer properly
2527 * clears B_DONE ( else a panic will occur later ).
2528 *
2529 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
2530 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
2531 * should only be called if the buffer is known-good.
2532 *
2533 * Since the buffer is not on a queue, we do not update the numfreebuffers
2534 * count.
2535 *
2536 * The buffer must be on QUEUE_NONE.
2537 */
2538 void
bdirty(struct buf * bp)2539 bdirty(struct buf *bp)
2540 {
2541
2542 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
2543 bp, bp->b_vp, bp->b_flags);
2544 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2545 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2546 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
2547 bp->b_flags &= ~(B_RELBUF);
2548 bp->b_iocmd = BIO_WRITE;
2549
2550 if ((bp->b_flags & B_DELWRI) == 0) {
2551 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
2552 reassignbuf(bp);
2553 bdirtyadd(bp);
2554 }
2555 }
2556
2557 /*
2558 * bundirty:
2559 *
2560 * Clear B_DELWRI for buffer.
2561 *
2562 * Since the buffer is not on a queue, we do not update the numfreebuffers
2563 * count.
2564 *
2565 * The buffer must be on QUEUE_NONE.
2566 */
2567
2568 void
bundirty(struct buf * bp)2569 bundirty(struct buf *bp)
2570 {
2571
2572 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2573 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2574 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2575 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
2576
2577 if (bp->b_flags & B_DELWRI) {
2578 bp->b_flags &= ~B_DELWRI;
2579 reassignbuf(bp);
2580 bdirtysub(bp);
2581 }
2582 /*
2583 * Since it is now being written, we can clear its deferred write flag.
2584 */
2585 bp->b_flags &= ~B_DEFERRED;
2586 }
2587
2588 /*
2589 * bawrite:
2590 *
2591 * Asynchronous write. Start output on a buffer, but do not wait for
2592 * it to complete. The buffer is released when the output completes.
2593 *
2594 * bwrite() ( or the VOP routine anyway ) is responsible for handling
2595 * B_INVAL buffers. Not us.
2596 */
2597 void
bawrite(struct buf * bp)2598 bawrite(struct buf *bp)
2599 {
2600
2601 bp->b_flags |= B_ASYNC;
2602 (void) bwrite(bp);
2603 }
2604
2605 /*
2606 * babarrierwrite:
2607 *
2608 * Asynchronous barrier write. Start output on a buffer, but do not
2609 * wait for it to complete. Place a write barrier after this write so
2610 * that this buffer and all buffers written before it are committed to
2611 * the disk before any buffers written after this write are committed
2612 * to the disk. The buffer is released when the output completes.
2613 */
2614 void
babarrierwrite(struct buf * bp)2615 babarrierwrite(struct buf *bp)
2616 {
2617
2618 bp->b_flags |= B_ASYNC | B_BARRIER;
2619 (void) bwrite(bp);
2620 }
2621
2622 /*
2623 * bbarrierwrite:
2624 *
2625 * Synchronous barrier write. Start output on a buffer and wait for
2626 * it to complete. Place a write barrier after this write so that
2627 * this buffer and all buffers written before it are committed to
2628 * the disk before any buffers written after this write are committed
2629 * to the disk. The buffer is released when the output completes.
2630 */
2631 int
bbarrierwrite(struct buf * bp)2632 bbarrierwrite(struct buf *bp)
2633 {
2634
2635 bp->b_flags |= B_BARRIER;
2636 return (bwrite(bp));
2637 }
2638
2639 /*
2640 * bwillwrite:
2641 *
2642 * Called prior to the locking of any vnodes when we are expecting to
2643 * write. We do not want to starve the buffer cache with too many
2644 * dirty buffers so we block here. By blocking prior to the locking
2645 * of any vnodes we attempt to avoid the situation where a locked vnode
2646 * prevents the various system daemons from flushing related buffers.
2647 */
2648 void
bwillwrite(void)2649 bwillwrite(void)
2650 {
2651
2652 if (buf_dirty_count_severe()) {
2653 mtx_lock(&bdirtylock);
2654 while (buf_dirty_count_severe()) {
2655 bdirtywait = 1;
2656 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
2657 "flswai", 0);
2658 }
2659 mtx_unlock(&bdirtylock);
2660 }
2661 }
2662
2663 /*
2664 * Return true if we have too many dirty buffers.
2665 */
2666 int
buf_dirty_count_severe(void)2667 buf_dirty_count_severe(void)
2668 {
2669
2670 return (!BIT_EMPTY(BUF_DOMAINS, &bdhidirty));
2671 }
2672
2673 /*
2674 * brelse:
2675 *
2676 * Release a busy buffer and, if requested, free its resources. The
2677 * buffer will be stashed in the appropriate bufqueue[] allowing it
2678 * to be accessed later as a cache entity or reused for other purposes.
2679 */
2680 void
brelse(struct buf * bp)2681 brelse(struct buf *bp)
2682 {
2683 struct mount *v_mnt;
2684 int qindex;
2685
2686 /*
2687 * Many functions erroneously call brelse with a NULL bp under rare
2688 * error conditions. Simply return when called with a NULL bp.
2689 */
2690 if (bp == NULL)
2691 return;
2692 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
2693 bp, bp->b_vp, bp->b_flags);
2694 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2695 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2696 KASSERT((bp->b_flags & B_VMIO) != 0 || (bp->b_flags & B_NOREUSE) == 0,
2697 ("brelse: non-VMIO buffer marked NOREUSE"));
2698
2699 if (BUF_LOCKRECURSED(bp)) {
2700 /*
2701 * Do not process, in particular, do not handle the
2702 * B_INVAL/B_RELBUF and do not release to free list.
2703 */
2704 BUF_UNLOCK(bp);
2705 return;
2706 }
2707
2708 if (bp->b_flags & B_MANAGED) {
2709 bqrelse(bp);
2710 return;
2711 }
2712
2713 if (LIST_EMPTY(&bp->b_dep)) {
2714 bp->b_flags &= ~B_IOSTARTED;
2715 } else {
2716 KASSERT((bp->b_flags & B_IOSTARTED) == 0,
2717 ("brelse: SU io not finished bp %p", bp));
2718 }
2719
2720 if ((bp->b_vflags & (BV_BKGRDINPROG | BV_BKGRDERR)) == BV_BKGRDERR) {
2721 BO_LOCK(bp->b_bufobj);
2722 bp->b_vflags &= ~BV_BKGRDERR;
2723 BO_UNLOCK(bp->b_bufobj);
2724 bdirty(bp);
2725 }
2726
2727 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
2728 (bp->b_flags & B_INVALONERR)) {
2729 /*
2730 * Forced invalidation of dirty buffer contents, to be used
2731 * after a failed write in the rare case that the loss of the
2732 * contents is acceptable. The buffer is invalidated and
2733 * freed.
2734 */
2735 bp->b_flags |= B_INVAL | B_RELBUF | B_NOCACHE;
2736 bp->b_flags &= ~(B_ASYNC | B_CACHE);
2737 }
2738
2739 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
2740 (bp->b_error != ENXIO || !LIST_EMPTY(&bp->b_dep)) &&
2741 !(bp->b_flags & B_INVAL)) {
2742 /*
2743 * Failed write, redirty. All errors except ENXIO (which
2744 * means the device is gone) are treated as being
2745 * transient.
2746 *
2747 * XXX Treating EIO as transient is not correct; the
2748 * contract with the local storage device drivers is that
2749 * they will only return EIO once the I/O is no longer
2750 * retriable. Network I/O also respects this through the
2751 * guarantees of TCP and/or the internal retries of NFS.
2752 * ENOMEM might be transient, but we also have no way of
2753 * knowing when its ok to retry/reschedule. In general,
2754 * this entire case should be made obsolete through better
2755 * error handling/recovery and resource scheduling.
2756 *
2757 * Do this also for buffers that failed with ENXIO, but have
2758 * non-empty dependencies - the soft updates code might need
2759 * to access the buffer to untangle them.
2760 *
2761 * Must clear BIO_ERROR to prevent pages from being scrapped.
2762 */
2763 bp->b_ioflags &= ~BIO_ERROR;
2764 bdirty(bp);
2765 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
2766 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
2767 /*
2768 * Either a failed read I/O, or we were asked to free or not
2769 * cache the buffer, or we failed to write to a device that's
2770 * no longer present.
2771 */
2772 bp->b_flags |= B_INVAL;
2773 if (!LIST_EMPTY(&bp->b_dep))
2774 buf_deallocate(bp);
2775 if (bp->b_flags & B_DELWRI)
2776 bdirtysub(bp);
2777 bp->b_flags &= ~(B_DELWRI | B_CACHE);
2778 if ((bp->b_flags & B_VMIO) == 0) {
2779 allocbuf(bp, 0);
2780 if (bp->b_vp)
2781 brelvp(bp);
2782 }
2783 }
2784
2785 /*
2786 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_truncate()
2787 * is called with B_DELWRI set, the underlying pages may wind up
2788 * getting freed causing a previous write (bdwrite()) to get 'lost'
2789 * because pages associated with a B_DELWRI bp are marked clean.
2790 *
2791 * We still allow the B_INVAL case to call vfs_vmio_truncate(), even
2792 * if B_DELWRI is set.
2793 */
2794 if (bp->b_flags & B_DELWRI)
2795 bp->b_flags &= ~B_RELBUF;
2796
2797 /*
2798 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
2799 * constituted, not even NFS buffers now. Two flags effect this. If
2800 * B_INVAL, the struct buf is invalidated but the VM object is kept
2801 * around ( i.e. so it is trivial to reconstitute the buffer later ).
2802 *
2803 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
2804 * invalidated. BIO_ERROR cannot be set for a failed write unless the
2805 * buffer is also B_INVAL because it hits the re-dirtying code above.
2806 *
2807 * Normally we can do this whether a buffer is B_DELWRI or not. If
2808 * the buffer is an NFS buffer, it is tracking piecemeal writes or
2809 * the commit state and we cannot afford to lose the buffer. If the
2810 * buffer has a background write in progress, we need to keep it
2811 * around to prevent it from being reconstituted and starting a second
2812 * background write.
2813 */
2814
2815 v_mnt = bp->b_vp != NULL ? bp->b_vp->v_mount : NULL;
2816
2817 if ((bp->b_flags & B_VMIO) && (bp->b_flags & B_NOCACHE ||
2818 (bp->b_ioflags & BIO_ERROR && bp->b_iocmd == BIO_READ)) &&
2819 (v_mnt == NULL || (v_mnt->mnt_vfc->vfc_flags & VFCF_NETWORK) == 0 ||
2820 vn_isdisk(bp->b_vp) || (bp->b_flags & B_DELWRI) == 0)) {
2821 vfs_vmio_invalidate(bp);
2822 allocbuf(bp, 0);
2823 }
2824
2825 if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0 ||
2826 (bp->b_flags & (B_DELWRI | B_NOREUSE)) == B_NOREUSE) {
2827 allocbuf(bp, 0);
2828 bp->b_flags &= ~B_NOREUSE;
2829 if (bp->b_vp != NULL)
2830 brelvp(bp);
2831 }
2832
2833 /*
2834 * If the buffer has junk contents signal it and eventually
2835 * clean up B_DELWRI and diassociate the vnode so that gbincore()
2836 * doesn't find it.
2837 */
2838 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
2839 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
2840 bp->b_flags |= B_INVAL;
2841 if (bp->b_flags & B_INVAL) {
2842 if (bp->b_flags & B_DELWRI)
2843 bundirty(bp);
2844 if (bp->b_vp)
2845 brelvp(bp);
2846 }
2847
2848 buf_track(bp, __func__);
2849
2850 /* buffers with no memory */
2851 if (bp->b_bufsize == 0) {
2852 buf_free(bp);
2853 return;
2854 }
2855 /* buffers with junk contents */
2856 if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
2857 (bp->b_ioflags & BIO_ERROR)) {
2858 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
2859 if (bp->b_vflags & BV_BKGRDINPROG)
2860 panic("losing buffer 2");
2861 qindex = QUEUE_CLEAN;
2862 bp->b_flags |= B_AGE;
2863 /* remaining buffers */
2864 } else if (bp->b_flags & B_DELWRI)
2865 qindex = QUEUE_DIRTY;
2866 else
2867 qindex = QUEUE_CLEAN;
2868
2869 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
2870 panic("brelse: not dirty");
2871
2872 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_RELBUF | B_DIRECT);
2873 bp->b_xflags &= ~(BX_CVTENXIO);
2874 /* binsfree unlocks bp. */
2875 binsfree(bp, qindex);
2876 }
2877
2878 /*
2879 * Release a buffer back to the appropriate queue but do not try to free
2880 * it. The buffer is expected to be used again soon.
2881 *
2882 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
2883 * biodone() to requeue an async I/O on completion. It is also used when
2884 * known good buffers need to be requeued but we think we may need the data
2885 * again soon.
2886 *
2887 * XXX we should be able to leave the B_RELBUF hint set on completion.
2888 */
2889 void
bqrelse(struct buf * bp)2890 bqrelse(struct buf *bp)
2891 {
2892 int qindex;
2893
2894 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2895 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2896 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2897
2898 qindex = QUEUE_NONE;
2899 if (BUF_LOCKRECURSED(bp)) {
2900 /* do not release to free list */
2901 BUF_UNLOCK(bp);
2902 return;
2903 }
2904 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
2905 bp->b_xflags &= ~(BX_CVTENXIO);
2906
2907 if (LIST_EMPTY(&bp->b_dep)) {
2908 bp->b_flags &= ~B_IOSTARTED;
2909 } else {
2910 KASSERT((bp->b_flags & B_IOSTARTED) == 0,
2911 ("bqrelse: SU io not finished bp %p", bp));
2912 }
2913
2914 if (bp->b_flags & B_MANAGED) {
2915 if (bp->b_flags & B_REMFREE)
2916 bremfreef(bp);
2917 goto out;
2918 }
2919
2920 /* buffers with stale but valid contents */
2921 if ((bp->b_flags & B_DELWRI) != 0 || (bp->b_vflags & (BV_BKGRDINPROG |
2922 BV_BKGRDERR)) == BV_BKGRDERR) {
2923 BO_LOCK(bp->b_bufobj);
2924 bp->b_vflags &= ~BV_BKGRDERR;
2925 BO_UNLOCK(bp->b_bufobj);
2926 qindex = QUEUE_DIRTY;
2927 } else {
2928 if ((bp->b_flags & B_DELWRI) == 0 &&
2929 (bp->b_xflags & BX_VNDIRTY))
2930 panic("bqrelse: not dirty");
2931 if ((bp->b_flags & B_NOREUSE) != 0) {
2932 brelse(bp);
2933 return;
2934 }
2935 qindex = QUEUE_CLEAN;
2936 }
2937 buf_track(bp, __func__);
2938 /* binsfree unlocks bp. */
2939 binsfree(bp, qindex);
2940 return;
2941
2942 out:
2943 buf_track(bp, __func__);
2944 /* unlock */
2945 BUF_UNLOCK(bp);
2946 }
2947
2948 /*
2949 * Complete I/O to a VMIO backed page. Validate the pages as appropriate,
2950 * restore bogus pages.
2951 */
2952 static void
vfs_vmio_iodone(struct buf * bp)2953 vfs_vmio_iodone(struct buf *bp)
2954 {
2955 vm_ooffset_t foff;
2956 vm_page_t m;
2957 vm_object_t obj;
2958 struct vnode *vp __unused;
2959 int i, iosize, resid;
2960 bool bogus;
2961
2962 obj = bp->b_bufobj->bo_object;
2963 KASSERT(blockcount_read(&obj->paging_in_progress) >= bp->b_npages,
2964 ("vfs_vmio_iodone: paging in progress(%d) < b_npages(%d)",
2965 blockcount_read(&obj->paging_in_progress), bp->b_npages));
2966
2967 vp = bp->b_vp;
2968 VNPASS(vp->v_holdcnt > 0, vp);
2969 VNPASS(vp->v_object != NULL, vp);
2970
2971 foff = bp->b_offset;
2972 KASSERT(bp->b_offset != NOOFFSET,
2973 ("vfs_vmio_iodone: bp %p has no buffer offset", bp));
2974
2975 bogus = false;
2976 iosize = bp->b_bcount - bp->b_resid;
2977 for (i = 0; i < bp->b_npages; i++) {
2978 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2979 if (resid > iosize)
2980 resid = iosize;
2981
2982 /*
2983 * cleanup bogus pages, restoring the originals
2984 */
2985 m = bp->b_pages[i];
2986 if (m == bogus_page) {
2987 bogus = true;
2988 m = vm_page_relookup(obj, OFF_TO_IDX(foff));
2989 if (m == NULL)
2990 panic("biodone: page disappeared!");
2991 bp->b_pages[i] = m;
2992 } else if ((bp->b_iocmd == BIO_READ) && resid > 0) {
2993 /*
2994 * In the write case, the valid and clean bits are
2995 * already changed correctly ( see bdwrite() ), so we
2996 * only need to do this here in the read case.
2997 */
2998 KASSERT((m->dirty & vm_page_bits(foff & PAGE_MASK,
2999 resid)) == 0, ("vfs_vmio_iodone: page %p "
3000 "has unexpected dirty bits", m));
3001 vfs_page_set_valid(bp, foff, m);
3002 }
3003 KASSERT(OFF_TO_IDX(foff) == m->pindex,
3004 ("vfs_vmio_iodone: foff(%jd)/pindex(%ju) mismatch",
3005 (intmax_t)foff, (uintmax_t)m->pindex));
3006
3007 vm_page_sunbusy(m);
3008 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3009 iosize -= resid;
3010 }
3011 vm_object_pip_wakeupn(obj, bp->b_npages);
3012 if (bogus && buf_mapped(bp)) {
3013 BUF_CHECK_MAPPED(bp);
3014 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3015 bp->b_pages, bp->b_npages);
3016 }
3017 }
3018
3019 /*
3020 * Perform page invalidation when a buffer is released. The fully invalid
3021 * pages will be reclaimed later in vfs_vmio_truncate().
3022 */
3023 static void
vfs_vmio_invalidate(struct buf * bp)3024 vfs_vmio_invalidate(struct buf *bp)
3025 {
3026 vm_object_t obj;
3027 vm_page_t m;
3028 int flags, i, resid, poffset, presid;
3029
3030 if (buf_mapped(bp)) {
3031 BUF_CHECK_MAPPED(bp);
3032 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
3033 } else
3034 BUF_CHECK_UNMAPPED(bp);
3035 /*
3036 * Get the base offset and length of the buffer. Note that
3037 * in the VMIO case if the buffer block size is not
3038 * page-aligned then b_data pointer may not be page-aligned.
3039 * But our b_pages[] array *IS* page aligned.
3040 *
3041 * block sizes less then DEV_BSIZE (usually 512) are not
3042 * supported due to the page granularity bits (m->valid,
3043 * m->dirty, etc...).
3044 *
3045 * See man buf(9) for more information
3046 */
3047 flags = (bp->b_flags & B_NOREUSE) != 0 ? VPR_NOREUSE : 0;
3048 obj = bp->b_bufobj->bo_object;
3049 resid = bp->b_bufsize;
3050 poffset = bp->b_offset & PAGE_MASK;
3051 VM_OBJECT_WLOCK(obj);
3052 for (i = 0; i < bp->b_npages; i++) {
3053 m = bp->b_pages[i];
3054 if (m == bogus_page)
3055 panic("vfs_vmio_invalidate: Unexpected bogus page.");
3056 bp->b_pages[i] = NULL;
3057
3058 presid = resid > (PAGE_SIZE - poffset) ?
3059 (PAGE_SIZE - poffset) : resid;
3060 KASSERT(presid >= 0, ("brelse: extra page"));
3061 vm_page_busy_acquire(m, VM_ALLOC_SBUSY);
3062 if (pmap_page_wired_mappings(m) == 0)
3063 vm_page_set_invalid(m, poffset, presid);
3064 vm_page_sunbusy(m);
3065 vm_page_release_locked(m, flags);
3066 resid -= presid;
3067 poffset = 0;
3068 }
3069 VM_OBJECT_WUNLOCK(obj);
3070 bp->b_npages = 0;
3071 }
3072
3073 /*
3074 * Page-granular truncation of an existing VMIO buffer.
3075 */
3076 static void
vfs_vmio_truncate(struct buf * bp,int desiredpages)3077 vfs_vmio_truncate(struct buf *bp, int desiredpages)
3078 {
3079 vm_object_t obj;
3080 vm_page_t m;
3081 int flags, i;
3082
3083 if (bp->b_npages == desiredpages)
3084 return;
3085
3086 if (buf_mapped(bp)) {
3087 BUF_CHECK_MAPPED(bp);
3088 pmap_qremove((vm_offset_t)trunc_page((vm_offset_t)bp->b_data) +
3089 (desiredpages << PAGE_SHIFT), bp->b_npages - desiredpages);
3090 } else
3091 BUF_CHECK_UNMAPPED(bp);
3092
3093 /*
3094 * The object lock is needed only if we will attempt to free pages.
3095 */
3096 flags = (bp->b_flags & B_NOREUSE) != 0 ? VPR_NOREUSE : 0;
3097 if ((bp->b_flags & B_DIRECT) != 0) {
3098 flags |= VPR_TRYFREE;
3099 obj = bp->b_bufobj->bo_object;
3100 VM_OBJECT_WLOCK(obj);
3101 } else {
3102 obj = NULL;
3103 }
3104 for (i = desiredpages; i < bp->b_npages; i++) {
3105 m = bp->b_pages[i];
3106 KASSERT(m != bogus_page, ("allocbuf: bogus page found"));
3107 bp->b_pages[i] = NULL;
3108 if (obj != NULL)
3109 vm_page_release_locked(m, flags);
3110 else
3111 vm_page_release(m, flags);
3112 }
3113 if (obj != NULL)
3114 VM_OBJECT_WUNLOCK(obj);
3115 bp->b_npages = desiredpages;
3116 }
3117
3118 /*
3119 * Byte granular extension of VMIO buffers.
3120 */
3121 static void
vfs_vmio_extend(struct buf * bp,int desiredpages,int size)3122 vfs_vmio_extend(struct buf *bp, int desiredpages, int size)
3123 {
3124 /*
3125 * We are growing the buffer, possibly in a
3126 * byte-granular fashion.
3127 */
3128 vm_object_t obj;
3129 vm_offset_t toff;
3130 vm_offset_t tinc;
3131 vm_page_t m;
3132
3133 /*
3134 * Step 1, bring in the VM pages from the object, allocating
3135 * them if necessary. We must clear B_CACHE if these pages
3136 * are not valid for the range covered by the buffer.
3137 */
3138 obj = bp->b_bufobj->bo_object;
3139 if (bp->b_npages < desiredpages) {
3140 KASSERT(desiredpages <= atop(maxbcachebuf),
3141 ("vfs_vmio_extend past maxbcachebuf %p %d %u",
3142 bp, desiredpages, maxbcachebuf));
3143
3144 /*
3145 * We must allocate system pages since blocking
3146 * here could interfere with paging I/O, no
3147 * matter which process we are.
3148 *
3149 * Only exclusive busy can be tested here.
3150 * Blocking on shared busy might lead to
3151 * deadlocks once allocbuf() is called after
3152 * pages are vfs_busy_pages().
3153 */
3154 (void)vm_page_grab_pages_unlocked(obj,
3155 OFF_TO_IDX(bp->b_offset) + bp->b_npages,
3156 VM_ALLOC_SYSTEM | VM_ALLOC_IGN_SBUSY |
3157 VM_ALLOC_NOBUSY | VM_ALLOC_WIRED,
3158 &bp->b_pages[bp->b_npages], desiredpages - bp->b_npages);
3159 bp->b_npages = desiredpages;
3160 }
3161
3162 /*
3163 * Step 2. We've loaded the pages into the buffer,
3164 * we have to figure out if we can still have B_CACHE
3165 * set. Note that B_CACHE is set according to the
3166 * byte-granular range ( bcount and size ), not the
3167 * aligned range ( newbsize ).
3168 *
3169 * The VM test is against m->valid, which is DEV_BSIZE
3170 * aligned. Needless to say, the validity of the data
3171 * needs to also be DEV_BSIZE aligned. Note that this
3172 * fails with NFS if the server or some other client
3173 * extends the file's EOF. If our buffer is resized,
3174 * B_CACHE may remain set! XXX
3175 */
3176 toff = bp->b_bcount;
3177 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3178 while ((bp->b_flags & B_CACHE) && toff < size) {
3179 vm_pindex_t pi;
3180
3181 if (tinc > (size - toff))
3182 tinc = size - toff;
3183 pi = ((bp->b_offset & PAGE_MASK) + toff) >> PAGE_SHIFT;
3184 m = bp->b_pages[pi];
3185 vfs_buf_test_cache(bp, bp->b_offset, toff, tinc, m);
3186 toff += tinc;
3187 tinc = PAGE_SIZE;
3188 }
3189
3190 /*
3191 * Step 3, fixup the KVA pmap.
3192 */
3193 if (buf_mapped(bp))
3194 bpmap_qenter(bp);
3195 else
3196 BUF_CHECK_UNMAPPED(bp);
3197 }
3198
3199 /*
3200 * Check to see if a block at a particular lbn is available for a clustered
3201 * write.
3202 */
3203 static int
vfs_bio_clcheck(struct vnode * vp,int size,daddr_t lblkno,daddr_t blkno)3204 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
3205 {
3206 struct buf *bpa;
3207 int match;
3208
3209 match = 0;
3210
3211 /* If the buf isn't in core skip it */
3212 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
3213 return (0);
3214
3215 /* If the buf is busy we don't want to wait for it */
3216 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
3217 return (0);
3218
3219 /* Only cluster with valid clusterable delayed write buffers */
3220 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
3221 (B_DELWRI | B_CLUSTEROK))
3222 goto done;
3223
3224 if (bpa->b_bufsize != size)
3225 goto done;
3226
3227 /*
3228 * Check to see if it is in the expected place on disk and that the
3229 * block has been mapped.
3230 */
3231 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
3232 match = 1;
3233 done:
3234 BUF_UNLOCK(bpa);
3235 return (match);
3236 }
3237
3238 /*
3239 * vfs_bio_awrite:
3240 *
3241 * Implement clustered async writes for clearing out B_DELWRI buffers.
3242 * This is much better then the old way of writing only one buffer at
3243 * a time. Note that we may not be presented with the buffers in the
3244 * correct order, so we search for the cluster in both directions.
3245 */
3246 int
vfs_bio_awrite(struct buf * bp)3247 vfs_bio_awrite(struct buf *bp)
3248 {
3249 struct bufobj *bo;
3250 int i;
3251 int j;
3252 daddr_t lblkno = bp->b_lblkno;
3253 struct vnode *vp = bp->b_vp;
3254 int ncl;
3255 int nwritten;
3256 int size;
3257 int maxcl;
3258 int gbflags;
3259
3260 bo = &vp->v_bufobj;
3261 gbflags = (bp->b_data == unmapped_buf) ? GB_UNMAPPED : 0;
3262 /*
3263 * right now we support clustered writing only to regular files. If
3264 * we find a clusterable block we could be in the middle of a cluster
3265 * rather then at the beginning.
3266 */
3267 if ((vp->v_type == VREG) &&
3268 (vp->v_mount != 0) && /* Only on nodes that have the size info */
3269 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
3270 size = vp->v_mount->mnt_stat.f_iosize;
3271 maxcl = maxphys / size;
3272
3273 BO_RLOCK(bo);
3274 for (i = 1; i < maxcl; i++)
3275 if (vfs_bio_clcheck(vp, size, lblkno + i,
3276 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
3277 break;
3278
3279 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
3280 if (vfs_bio_clcheck(vp, size, lblkno - j,
3281 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
3282 break;
3283 BO_RUNLOCK(bo);
3284 --j;
3285 ncl = i + j;
3286 /*
3287 * this is a possible cluster write
3288 */
3289 if (ncl != 1) {
3290 BUF_UNLOCK(bp);
3291 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
3292 gbflags);
3293 return (nwritten);
3294 }
3295 }
3296 bremfree(bp);
3297 bp->b_flags |= B_ASYNC;
3298 /*
3299 * default (old) behavior, writing out only one block
3300 *
3301 * XXX returns b_bufsize instead of b_bcount for nwritten?
3302 */
3303 nwritten = bp->b_bufsize;
3304 (void) bwrite(bp);
3305
3306 return (nwritten);
3307 }
3308
3309 /*
3310 * getnewbuf_kva:
3311 *
3312 * Allocate KVA for an empty buf header according to gbflags.
3313 */
3314 static int
getnewbuf_kva(struct buf * bp,int gbflags,int maxsize)3315 getnewbuf_kva(struct buf *bp, int gbflags, int maxsize)
3316 {
3317
3318 if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_UNMAPPED) {
3319 /*
3320 * In order to keep fragmentation sane we only allocate kva
3321 * in BKVASIZE chunks. XXX with vmem we can do page size.
3322 */
3323 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
3324
3325 if (maxsize != bp->b_kvasize &&
3326 bufkva_alloc(bp, maxsize, gbflags))
3327 return (ENOSPC);
3328 }
3329 return (0);
3330 }
3331
3332 /*
3333 * getnewbuf:
3334 *
3335 * Find and initialize a new buffer header, freeing up existing buffers
3336 * in the bufqueues as necessary. The new buffer is returned locked.
3337 *
3338 * We block if:
3339 * We have insufficient buffer headers
3340 * We have insufficient buffer space
3341 * buffer_arena is too fragmented ( space reservation fails )
3342 * If we have to flush dirty buffers ( but we try to avoid this )
3343 *
3344 * The caller is responsible for releasing the reserved bufspace after
3345 * allocbuf() is called.
3346 */
3347 static struct buf *
getnewbuf(struct vnode * vp,int slpflag,int slptimeo,int maxsize,int gbflags)3348 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int maxsize, int gbflags)
3349 {
3350 struct bufdomain *bd;
3351 struct buf *bp;
3352 bool metadata, reserved;
3353
3354 bp = NULL;
3355 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3356 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3357 if (!unmapped_buf_allowed)
3358 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3359
3360 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
3361 vp->v_type == VCHR)
3362 metadata = true;
3363 else
3364 metadata = false;
3365 if (vp == NULL)
3366 bd = &bdomain[0];
3367 else
3368 bd = &bdomain[vp->v_bufobj.bo_domain];
3369
3370 counter_u64_add(getnewbufcalls, 1);
3371 reserved = false;
3372 do {
3373 if (reserved == false &&
3374 bufspace_reserve(bd, maxsize, metadata) != 0) {
3375 counter_u64_add(getnewbufrestarts, 1);
3376 continue;
3377 }
3378 reserved = true;
3379 if ((bp = buf_alloc(bd)) == NULL) {
3380 counter_u64_add(getnewbufrestarts, 1);
3381 continue;
3382 }
3383 if (getnewbuf_kva(bp, gbflags, maxsize) == 0)
3384 return (bp);
3385 break;
3386 } while (buf_recycle(bd, false) == 0);
3387
3388 if (reserved)
3389 bufspace_release(bd, maxsize);
3390 if (bp != NULL) {
3391 bp->b_flags |= B_INVAL;
3392 brelse(bp);
3393 }
3394 bufspace_wait(bd, vp, gbflags, slpflag, slptimeo);
3395
3396 return (NULL);
3397 }
3398
3399 /*
3400 * buf_daemon:
3401 *
3402 * buffer flushing daemon. Buffers are normally flushed by the
3403 * update daemon but if it cannot keep up this process starts to
3404 * take the load in an attempt to prevent getnewbuf() from blocking.
3405 */
3406 static struct kproc_desc buf_kp = {
3407 "bufdaemon",
3408 buf_daemon,
3409 &bufdaemonproc
3410 };
3411 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
3412
3413 static int
buf_flush(struct vnode * vp,struct bufdomain * bd,int target)3414 buf_flush(struct vnode *vp, struct bufdomain *bd, int target)
3415 {
3416 int flushed;
3417
3418 flushed = flushbufqueues(vp, bd, target, 0);
3419 if (flushed == 0) {
3420 /*
3421 * Could not find any buffers without rollback
3422 * dependencies, so just write the first one
3423 * in the hopes of eventually making progress.
3424 */
3425 if (vp != NULL && target > 2)
3426 target /= 2;
3427 flushbufqueues(vp, bd, target, 1);
3428 }
3429 return (flushed);
3430 }
3431
3432 static void
buf_daemon_shutdown(void * arg __unused,int howto __unused)3433 buf_daemon_shutdown(void *arg __unused, int howto __unused)
3434 {
3435 int error;
3436
3437 if (KERNEL_PANICKED())
3438 return;
3439
3440 mtx_lock(&bdlock);
3441 bd_shutdown = true;
3442 wakeup(&bd_request);
3443 error = msleep(&bd_shutdown, &bdlock, 0, "buf_daemon_shutdown",
3444 60 * hz);
3445 mtx_unlock(&bdlock);
3446 if (error != 0)
3447 printf("bufdaemon wait error: %d\n", error);
3448 }
3449
3450 static void
buf_daemon(void)3451 buf_daemon(void)
3452 {
3453 struct bufdomain *bd;
3454 int speedupreq;
3455 int lodirty;
3456 int i;
3457
3458 /*
3459 * This process needs to be suspended prior to shutdown sync.
3460 */
3461 EVENTHANDLER_REGISTER(shutdown_pre_sync, buf_daemon_shutdown, NULL,
3462 SHUTDOWN_PRI_LAST + 100);
3463
3464 /*
3465 * Start the buf clean daemons as children threads.
3466 */
3467 for (i = 0 ; i < buf_domains; i++) {
3468 int error;
3469
3470 error = kthread_add((void (*)(void *))bufspace_daemon,
3471 &bdomain[i], curproc, NULL, 0, 0, "bufspacedaemon-%d", i);
3472 if (error)
3473 panic("error %d spawning bufspace daemon", error);
3474 }
3475
3476 /*
3477 * This process is allowed to take the buffer cache to the limit
3478 */
3479 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
3480 mtx_lock(&bdlock);
3481 while (!bd_shutdown) {
3482 bd_request = 0;
3483 mtx_unlock(&bdlock);
3484
3485 /*
3486 * Save speedupreq for this pass and reset to capture new
3487 * requests.
3488 */
3489 speedupreq = bd_speedupreq;
3490 bd_speedupreq = 0;
3491
3492 /*
3493 * Flush each domain sequentially according to its level and
3494 * the speedup request.
3495 */
3496 for (i = 0; i < buf_domains; i++) {
3497 bd = &bdomain[i];
3498 if (speedupreq)
3499 lodirty = bd->bd_numdirtybuffers / 2;
3500 else
3501 lodirty = bd->bd_lodirtybuffers;
3502 while (bd->bd_numdirtybuffers > lodirty) {
3503 if (buf_flush(NULL, bd,
3504 bd->bd_numdirtybuffers - lodirty) == 0)
3505 break;
3506 kern_yield(PRI_USER);
3507 }
3508 }
3509
3510 /*
3511 * Only clear bd_request if we have reached our low water
3512 * mark. The buf_daemon normally waits 1 second and
3513 * then incrementally flushes any dirty buffers that have
3514 * built up, within reason.
3515 *
3516 * If we were unable to hit our low water mark and couldn't
3517 * find any flushable buffers, we sleep for a short period
3518 * to avoid endless loops on unlockable buffers.
3519 */
3520 mtx_lock(&bdlock);
3521 if (bd_shutdown)
3522 break;
3523 if (BIT_EMPTY(BUF_DOMAINS, &bdlodirty)) {
3524 /*
3525 * We reached our low water mark, reset the
3526 * request and sleep until we are needed again.
3527 * The sleep is just so the suspend code works.
3528 */
3529 bd_request = 0;
3530 /*
3531 * Do an extra wakeup in case dirty threshold
3532 * changed via sysctl and the explicit transition
3533 * out of shortfall was missed.
3534 */
3535 bdirtywakeup();
3536 if (runningbufspace <= lorunningspace)
3537 runningwakeup();
3538 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
3539 } else {
3540 /*
3541 * We couldn't find any flushable dirty buffers but
3542 * still have too many dirty buffers, we
3543 * have to sleep and try again. (rare)
3544 */
3545 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
3546 }
3547 }
3548 wakeup(&bd_shutdown);
3549 mtx_unlock(&bdlock);
3550 kthread_exit();
3551 }
3552
3553 /*
3554 * flushbufqueues:
3555 *
3556 * Try to flush a buffer in the dirty queue. We must be careful to
3557 * free up B_INVAL buffers instead of write them, which NFS is
3558 * particularly sensitive to.
3559 */
3560 static int flushwithdeps = 0;
3561 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW | CTLFLAG_STATS,
3562 &flushwithdeps, 0,
3563 "Number of buffers flushed with dependencies that require rollbacks");
3564
3565 static int
flushbufqueues(struct vnode * lvp,struct bufdomain * bd,int target,int flushdeps)3566 flushbufqueues(struct vnode *lvp, struct bufdomain *bd, int target,
3567 int flushdeps)
3568 {
3569 struct bufqueue *bq;
3570 struct buf *sentinel;
3571 struct vnode *vp;
3572 struct mount *mp;
3573 struct buf *bp;
3574 int hasdeps;
3575 int flushed;
3576 int error;
3577 bool unlock;
3578
3579 flushed = 0;
3580 bq = &bd->bd_dirtyq;
3581 bp = NULL;
3582 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
3583 sentinel->b_qindex = QUEUE_SENTINEL;
3584 BQ_LOCK(bq);
3585 TAILQ_INSERT_HEAD(&bq->bq_queue, sentinel, b_freelist);
3586 BQ_UNLOCK(bq);
3587 while (flushed != target) {
3588 maybe_yield();
3589 BQ_LOCK(bq);
3590 bp = TAILQ_NEXT(sentinel, b_freelist);
3591 if (bp != NULL) {
3592 TAILQ_REMOVE(&bq->bq_queue, sentinel, b_freelist);
3593 TAILQ_INSERT_AFTER(&bq->bq_queue, bp, sentinel,
3594 b_freelist);
3595 } else {
3596 BQ_UNLOCK(bq);
3597 break;
3598 }
3599 /*
3600 * Skip sentinels inserted by other invocations of the
3601 * flushbufqueues(), taking care to not reorder them.
3602 *
3603 * Only flush the buffers that belong to the
3604 * vnode locked by the curthread.
3605 */
3606 if (bp->b_qindex == QUEUE_SENTINEL || (lvp != NULL &&
3607 bp->b_vp != lvp)) {
3608 BQ_UNLOCK(bq);
3609 continue;
3610 }
3611 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
3612 BQ_UNLOCK(bq);
3613 if (error != 0)
3614 continue;
3615
3616 /*
3617 * BKGRDINPROG can only be set with the buf and bufobj
3618 * locks both held. We tolerate a race to clear it here.
3619 */
3620 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
3621 (bp->b_flags & B_DELWRI) == 0) {
3622 BUF_UNLOCK(bp);
3623 continue;
3624 }
3625 if (bp->b_flags & B_INVAL) {
3626 bremfreef(bp);
3627 brelse(bp);
3628 flushed++;
3629 continue;
3630 }
3631
3632 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
3633 if (flushdeps == 0) {
3634 BUF_UNLOCK(bp);
3635 continue;
3636 }
3637 hasdeps = 1;
3638 } else
3639 hasdeps = 0;
3640 /*
3641 * We must hold the lock on a vnode before writing
3642 * one of its buffers. Otherwise we may confuse, or
3643 * in the case of a snapshot vnode, deadlock the
3644 * system.
3645 *
3646 * The lock order here is the reverse of the normal
3647 * of vnode followed by buf lock. This is ok because
3648 * the NOWAIT will prevent deadlock.
3649 */
3650 vp = bp->b_vp;
3651 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
3652 BUF_UNLOCK(bp);
3653 continue;
3654 }
3655 if (lvp == NULL) {
3656 unlock = true;
3657 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
3658 } else {
3659 ASSERT_VOP_LOCKED(vp, "getbuf");
3660 unlock = false;
3661 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
3662 vn_lock(vp, LK_TRYUPGRADE);
3663 }
3664 if (error == 0) {
3665 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
3666 bp, bp->b_vp, bp->b_flags);
3667 if (curproc == bufdaemonproc) {
3668 vfs_bio_awrite(bp);
3669 } else {
3670 bremfree(bp);
3671 bwrite(bp);
3672 counter_u64_add(notbufdflushes, 1);
3673 }
3674 vn_finished_write(mp);
3675 if (unlock)
3676 VOP_UNLOCK(vp);
3677 flushwithdeps += hasdeps;
3678 flushed++;
3679
3680 /*
3681 * Sleeping on runningbufspace while holding
3682 * vnode lock leads to deadlock.
3683 */
3684 if (curproc == bufdaemonproc &&
3685 runningbufspace > hirunningspace)
3686 waitrunningbufspace();
3687 continue;
3688 }
3689 vn_finished_write(mp);
3690 BUF_UNLOCK(bp);
3691 }
3692 BQ_LOCK(bq);
3693 TAILQ_REMOVE(&bq->bq_queue, sentinel, b_freelist);
3694 BQ_UNLOCK(bq);
3695 free(sentinel, M_TEMP);
3696 return (flushed);
3697 }
3698
3699 /*
3700 * Check to see if a block is currently memory resident.
3701 */
3702 struct buf *
incore(struct bufobj * bo,daddr_t blkno)3703 incore(struct bufobj *bo, daddr_t blkno)
3704 {
3705 return (gbincore_unlocked(bo, blkno));
3706 }
3707
3708 /*
3709 * Returns true if no I/O is needed to access the
3710 * associated VM object. This is like incore except
3711 * it also hunts around in the VM system for the data.
3712 */
3713 bool
inmem(struct vnode * vp,daddr_t blkno)3714 inmem(struct vnode * vp, daddr_t blkno)
3715 {
3716 vm_object_t obj;
3717 vm_offset_t toff, tinc, size;
3718 vm_page_t m, n;
3719 vm_ooffset_t off;
3720 int valid;
3721
3722 ASSERT_VOP_LOCKED(vp, "inmem");
3723
3724 if (incore(&vp->v_bufobj, blkno))
3725 return (true);
3726 if (vp->v_mount == NULL)
3727 return (false);
3728 obj = vp->v_object;
3729 if (obj == NULL)
3730 return (false);
3731
3732 size = PAGE_SIZE;
3733 if (size > vp->v_mount->mnt_stat.f_iosize)
3734 size = vp->v_mount->mnt_stat.f_iosize;
3735 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
3736
3737 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
3738 m = vm_page_lookup_unlocked(obj, OFF_TO_IDX(off + toff));
3739 recheck:
3740 if (m == NULL)
3741 return (false);
3742
3743 tinc = size;
3744 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
3745 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
3746 /*
3747 * Consider page validity only if page mapping didn't change
3748 * during the check.
3749 */
3750 valid = vm_page_is_valid(m,
3751 (vm_offset_t)((toff + off) & PAGE_MASK), tinc);
3752 n = vm_page_lookup_unlocked(obj, OFF_TO_IDX(off + toff));
3753 if (m != n) {
3754 m = n;
3755 goto recheck;
3756 }
3757 if (!valid)
3758 return (false);
3759 }
3760 return (true);
3761 }
3762
3763 /*
3764 * Set the dirty range for a buffer based on the status of the dirty
3765 * bits in the pages comprising the buffer. The range is limited
3766 * to the size of the buffer.
3767 *
3768 * Tell the VM system that the pages associated with this buffer
3769 * are clean. This is used for delayed writes where the data is
3770 * going to go to disk eventually without additional VM intevention.
3771 *
3772 * Note that while we only really need to clean through to b_bcount, we
3773 * just go ahead and clean through to b_bufsize.
3774 */
3775 static void
vfs_clean_pages_dirty_buf(struct buf * bp)3776 vfs_clean_pages_dirty_buf(struct buf *bp)
3777 {
3778 vm_ooffset_t foff, noff, eoff;
3779 vm_page_t m;
3780 int i;
3781
3782 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
3783 return;
3784
3785 foff = bp->b_offset;
3786 KASSERT(bp->b_offset != NOOFFSET,
3787 ("vfs_clean_pages_dirty_buf: no buffer offset"));
3788
3789 vfs_busy_pages_acquire(bp);
3790 vfs_setdirty_range(bp);
3791 for (i = 0; i < bp->b_npages; i++) {
3792 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3793 eoff = noff;
3794 if (eoff > bp->b_offset + bp->b_bufsize)
3795 eoff = bp->b_offset + bp->b_bufsize;
3796 m = bp->b_pages[i];
3797 vfs_page_set_validclean(bp, foff, m);
3798 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3799 foff = noff;
3800 }
3801 vfs_busy_pages_release(bp);
3802 }
3803
3804 static void
vfs_setdirty_range(struct buf * bp)3805 vfs_setdirty_range(struct buf *bp)
3806 {
3807 vm_offset_t boffset;
3808 vm_offset_t eoffset;
3809 int i;
3810
3811 /*
3812 * test the pages to see if they have been modified directly
3813 * by users through the VM system.
3814 */
3815 for (i = 0; i < bp->b_npages; i++)
3816 vm_page_test_dirty(bp->b_pages[i]);
3817
3818 /*
3819 * Calculate the encompassing dirty range, boffset and eoffset,
3820 * (eoffset - boffset) bytes.
3821 */
3822
3823 for (i = 0; i < bp->b_npages; i++) {
3824 if (bp->b_pages[i]->dirty)
3825 break;
3826 }
3827 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3828
3829 for (i = bp->b_npages - 1; i >= 0; --i) {
3830 if (bp->b_pages[i]->dirty) {
3831 break;
3832 }
3833 }
3834 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3835
3836 /*
3837 * Fit it to the buffer.
3838 */
3839
3840 if (eoffset > bp->b_bcount)
3841 eoffset = bp->b_bcount;
3842
3843 /*
3844 * If we have a good dirty range, merge with the existing
3845 * dirty range.
3846 */
3847
3848 if (boffset < eoffset) {
3849 if (bp->b_dirtyoff > boffset)
3850 bp->b_dirtyoff = boffset;
3851 if (bp->b_dirtyend < eoffset)
3852 bp->b_dirtyend = eoffset;
3853 }
3854 }
3855
3856 /*
3857 * Allocate the KVA mapping for an existing buffer.
3858 * If an unmapped buffer is provided but a mapped buffer is requested, take
3859 * also care to properly setup mappings between pages and KVA.
3860 */
3861 static void
bp_unmapped_get_kva(struct buf * bp,daddr_t blkno,int size,int gbflags)3862 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
3863 {
3864 int bsize, maxsize, need_mapping, need_kva;
3865 off_t offset;
3866
3867 need_mapping = bp->b_data == unmapped_buf &&
3868 (gbflags & GB_UNMAPPED) == 0;
3869 need_kva = bp->b_kvabase == unmapped_buf &&
3870 bp->b_data == unmapped_buf &&
3871 (gbflags & GB_KVAALLOC) != 0;
3872 if (!need_mapping && !need_kva)
3873 return;
3874
3875 BUF_CHECK_UNMAPPED(bp);
3876
3877 if (need_mapping && bp->b_kvabase != unmapped_buf) {
3878 /*
3879 * Buffer is not mapped, but the KVA was already
3880 * reserved at the time of the instantiation. Use the
3881 * allocated space.
3882 */
3883 goto has_addr;
3884 }
3885
3886 /*
3887 * Calculate the amount of the address space we would reserve
3888 * if the buffer was mapped.
3889 */
3890 bsize = vn_isdisk(bp->b_vp) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
3891 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3892 offset = blkno * bsize;
3893 maxsize = size + (offset & PAGE_MASK);
3894 maxsize = imax(maxsize, bsize);
3895
3896 while (bufkva_alloc(bp, maxsize, gbflags) != 0) {
3897 if ((gbflags & GB_NOWAIT_BD) != 0) {
3898 /*
3899 * XXXKIB: defragmentation cannot
3900 * succeed, not sure what else to do.
3901 */
3902 panic("GB_NOWAIT_BD and GB_UNMAPPED %p", bp);
3903 }
3904 counter_u64_add(mappingrestarts, 1);
3905 bufspace_wait(bufdomain(bp), bp->b_vp, gbflags, 0, 0);
3906 }
3907 has_addr:
3908 if (need_mapping) {
3909 /* b_offset is handled by bpmap_qenter. */
3910 bp->b_data = bp->b_kvabase;
3911 BUF_CHECK_MAPPED(bp);
3912 bpmap_qenter(bp);
3913 }
3914 }
3915
3916 struct buf *
getblk(struct vnode * vp,daddr_t blkno,int size,int slpflag,int slptimeo,int flags)3917 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3918 int flags)
3919 {
3920 struct buf *bp;
3921 int error;
3922
3923 error = getblkx(vp, blkno, blkno, size, slpflag, slptimeo, flags, &bp);
3924 if (error != 0)
3925 return (NULL);
3926 return (bp);
3927 }
3928
3929 /*
3930 * getblkx:
3931 *
3932 * Get a block given a specified block and offset into a file/device.
3933 * The buffers B_DONE bit will be cleared on return, making it almost
3934 * ready for an I/O initiation. B_INVAL may or may not be set on
3935 * return. The caller should clear B_INVAL prior to initiating a
3936 * READ.
3937 *
3938 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3939 * an existing buffer.
3940 *
3941 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
3942 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3943 * and then cleared based on the backing VM. If the previous buffer is
3944 * non-0-sized but invalid, B_CACHE will be cleared.
3945 *
3946 * If getblk() must create a new buffer, the new buffer is returned with
3947 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3948 * case it is returned with B_INVAL clear and B_CACHE set based on the
3949 * backing VM.
3950 *
3951 * getblk() also forces a bwrite() for any B_DELWRI buffer whose
3952 * B_CACHE bit is clear.
3953 *
3954 * What this means, basically, is that the caller should use B_CACHE to
3955 * determine whether the buffer is fully valid or not and should clear
3956 * B_INVAL prior to issuing a read. If the caller intends to validate
3957 * the buffer by loading its data area with something, the caller needs
3958 * to clear B_INVAL. If the caller does this without issuing an I/O,
3959 * the caller should set B_CACHE ( as an optimization ), else the caller
3960 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3961 * a write attempt or if it was a successful read. If the caller
3962 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3963 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3964 *
3965 * The blkno parameter is the logical block being requested. Normally
3966 * the mapping of logical block number to disk block address is done
3967 * by calling VOP_BMAP(). However, if the mapping is already known, the
3968 * disk block address can be passed using the dblkno parameter. If the
3969 * disk block address is not known, then the same value should be passed
3970 * for blkno and dblkno.
3971 */
3972 int
getblkx(struct vnode * vp,daddr_t blkno,daddr_t dblkno,int size,int slpflag,int slptimeo,int flags,struct buf ** bpp)3973 getblkx(struct vnode *vp, daddr_t blkno, daddr_t dblkno, int size, int slpflag,
3974 int slptimeo, int flags, struct buf **bpp)
3975 {
3976 struct buf *bp;
3977 struct bufobj *bo;
3978 daddr_t d_blkno;
3979 int bsize, error, maxsize, vmio;
3980 off_t offset;
3981
3982 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3983 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3984 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3985 if (vp->v_type != VCHR)
3986 ASSERT_VOP_LOCKED(vp, "getblk");
3987 if (size > maxbcachebuf) {
3988 printf("getblkx: size(%d) > maxbcachebuf(%d)\n", size,
3989 maxbcachebuf);
3990 return (EIO);
3991 }
3992 if (!unmapped_buf_allowed)
3993 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3994
3995 bo = &vp->v_bufobj;
3996 d_blkno = dblkno;
3997
3998 /* Attempt lockless lookup first. */
3999 bp = gbincore_unlocked(bo, blkno);
4000 if (bp == NULL) {
4001 /*
4002 * With GB_NOCREAT we must be sure about not finding the buffer
4003 * as it may have been reassigned during unlocked lookup.
4004 */
4005 if ((flags & GB_NOCREAT) != 0)
4006 goto loop;
4007 goto newbuf_unlocked;
4008 }
4009
4010 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL, "getblku", 0,
4011 0);
4012 if (error != 0)
4013 goto loop;
4014
4015 /* Verify buf identify has not changed since lookup. */
4016 if (bp->b_bufobj == bo && bp->b_lblkno == blkno)
4017 goto foundbuf_fastpath;
4018
4019 /* It changed, fallback to locked lookup. */
4020 BUF_UNLOCK_RAW(bp);
4021
4022 loop:
4023 BO_RLOCK(bo);
4024 bp = gbincore(bo, blkno);
4025 if (bp != NULL) {
4026 int lockflags;
4027
4028 /*
4029 * Buffer is in-core. If the buffer is not busy nor managed,
4030 * it must be on a queue.
4031 */
4032 lockflags = LK_EXCLUSIVE | LK_INTERLOCK |
4033 ((flags & GB_LOCK_NOWAIT) != 0 ? LK_NOWAIT : LK_SLEEPFAIL);
4034 #ifdef WITNESS
4035 lockflags |= (flags & GB_NOWITNESS) != 0 ? LK_NOWITNESS : 0;
4036 #endif
4037
4038 error = BUF_TIMELOCK(bp, lockflags,
4039 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
4040
4041 /*
4042 * If we slept and got the lock we have to restart in case
4043 * the buffer changed identities.
4044 */
4045 if (error == ENOLCK)
4046 goto loop;
4047 /* We timed out or were interrupted. */
4048 else if (error != 0)
4049 return (error);
4050
4051 foundbuf_fastpath:
4052 /* If recursed, assume caller knows the rules. */
4053 if (BUF_LOCKRECURSED(bp))
4054 goto end;
4055
4056 /*
4057 * The buffer is locked. B_CACHE is cleared if the buffer is
4058 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
4059 * and for a VMIO buffer B_CACHE is adjusted according to the
4060 * backing VM cache.
4061 */
4062 if (bp->b_flags & B_INVAL)
4063 bp->b_flags &= ~B_CACHE;
4064 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
4065 bp->b_flags |= B_CACHE;
4066 if (bp->b_flags & B_MANAGED)
4067 MPASS(bp->b_qindex == QUEUE_NONE);
4068 else
4069 bremfree(bp);
4070
4071 /*
4072 * check for size inconsistencies for non-VMIO case.
4073 */
4074 if (bp->b_bcount != size) {
4075 if ((bp->b_flags & B_VMIO) == 0 ||
4076 (size > bp->b_kvasize)) {
4077 if (bp->b_flags & B_DELWRI) {
4078 bp->b_flags |= B_NOCACHE;
4079 bwrite(bp);
4080 } else {
4081 if (LIST_EMPTY(&bp->b_dep)) {
4082 bp->b_flags |= B_RELBUF;
4083 brelse(bp);
4084 } else {
4085 bp->b_flags |= B_NOCACHE;
4086 bwrite(bp);
4087 }
4088 }
4089 goto loop;
4090 }
4091 }
4092
4093 /*
4094 * Handle the case of unmapped buffer which should
4095 * become mapped, or the buffer for which KVA
4096 * reservation is requested.
4097 */
4098 bp_unmapped_get_kva(bp, blkno, size, flags);
4099
4100 /*
4101 * If the size is inconsistent in the VMIO case, we can resize
4102 * the buffer. This might lead to B_CACHE getting set or
4103 * cleared. If the size has not changed, B_CACHE remains
4104 * unchanged from its previous state.
4105 */
4106 allocbuf(bp, size);
4107
4108 KASSERT(bp->b_offset != NOOFFSET,
4109 ("getblk: no buffer offset"));
4110
4111 /*
4112 * A buffer with B_DELWRI set and B_CACHE clear must
4113 * be committed before we can return the buffer in
4114 * order to prevent the caller from issuing a read
4115 * ( due to B_CACHE not being set ) and overwriting
4116 * it.
4117 *
4118 * Most callers, including NFS and FFS, need this to
4119 * operate properly either because they assume they
4120 * can issue a read if B_CACHE is not set, or because
4121 * ( for example ) an uncached B_DELWRI might loop due
4122 * to softupdates re-dirtying the buffer. In the latter
4123 * case, B_CACHE is set after the first write completes,
4124 * preventing further loops.
4125 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
4126 * above while extending the buffer, we cannot allow the
4127 * buffer to remain with B_CACHE set after the write
4128 * completes or it will represent a corrupt state. To
4129 * deal with this we set B_NOCACHE to scrap the buffer
4130 * after the write.
4131 *
4132 * We might be able to do something fancy, like setting
4133 * B_CACHE in bwrite() except if B_DELWRI is already set,
4134 * so the below call doesn't set B_CACHE, but that gets real
4135 * confusing. This is much easier.
4136 */
4137
4138 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
4139 bp->b_flags |= B_NOCACHE;
4140 bwrite(bp);
4141 goto loop;
4142 }
4143 bp->b_flags &= ~B_DONE;
4144 } else {
4145 /*
4146 * Buffer is not in-core, create new buffer. The buffer
4147 * returned by getnewbuf() is locked. Note that the returned
4148 * buffer is also considered valid (not marked B_INVAL).
4149 */
4150 BO_RUNLOCK(bo);
4151 newbuf_unlocked:
4152 /*
4153 * If the user does not want us to create the buffer, bail out
4154 * here.
4155 */
4156 if (flags & GB_NOCREAT)
4157 return (EEXIST);
4158
4159 bsize = vn_isdisk(vp) ? DEV_BSIZE : bo->bo_bsize;
4160 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
4161 offset = blkno * bsize;
4162 vmio = vp->v_object != NULL;
4163 if (vmio) {
4164 maxsize = size + (offset & PAGE_MASK);
4165 if (maxsize > maxbcachebuf) {
4166 printf(
4167 "getblkx: maxsize(%d) > maxbcachebuf(%d)\n",
4168 maxsize, maxbcachebuf);
4169 return (EIO);
4170 }
4171 } else {
4172 maxsize = size;
4173 /* Do not allow non-VMIO notmapped buffers. */
4174 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
4175 }
4176 maxsize = imax(maxsize, bsize);
4177 if ((flags & GB_NOSPARSE) != 0 && vmio &&
4178 !vn_isdisk(vp)) {
4179 error = VOP_BMAP(vp, blkno, NULL, &d_blkno, 0, 0);
4180 KASSERT(error != EOPNOTSUPP,
4181 ("GB_NOSPARSE from fs not supporting bmap, vp %p",
4182 vp));
4183 if (error != 0)
4184 return (error);
4185 if (d_blkno == -1)
4186 return (EJUSTRETURN);
4187 }
4188
4189 bp = getnewbuf(vp, slpflag, slptimeo, maxsize, flags);
4190 if (bp == NULL) {
4191 if (slpflag || slptimeo)
4192 return (ETIMEDOUT);
4193 /*
4194 * XXX This is here until the sleep path is diagnosed
4195 * enough to work under very low memory conditions.
4196 *
4197 * There's an issue on low memory, 4BSD+non-preempt
4198 * systems (eg MIPS routers with 32MB RAM) where buffer
4199 * exhaustion occurs without sleeping for buffer
4200 * reclaimation. This just sticks in a loop and
4201 * constantly attempts to allocate a buffer, which
4202 * hits exhaustion and tries to wakeup bufdaemon.
4203 * This never happens because we never yield.
4204 *
4205 * The real solution is to identify and fix these cases
4206 * so we aren't effectively busy-waiting in a loop
4207 * until the reclaimation path has cycles to run.
4208 */
4209 kern_yield(PRI_USER);
4210 goto loop;
4211 }
4212
4213 /*
4214 * This code is used to make sure that a buffer is not
4215 * created while the getnewbuf routine is blocked.
4216 * This can be a problem whether the vnode is locked or not.
4217 * If the buffer is created out from under us, we have to
4218 * throw away the one we just created.
4219 *
4220 * Note: this must occur before we associate the buffer
4221 * with the vp especially considering limitations in
4222 * the splay tree implementation when dealing with duplicate
4223 * lblkno's.
4224 */
4225 BO_LOCK(bo);
4226 if (gbincore(bo, blkno)) {
4227 BO_UNLOCK(bo);
4228 bp->b_flags |= B_INVAL;
4229 bufspace_release(bufdomain(bp), maxsize);
4230 brelse(bp);
4231 goto loop;
4232 }
4233
4234 /*
4235 * Insert the buffer into the hash, so that it can
4236 * be found by incore.
4237 */
4238 bp->b_lblkno = blkno;
4239 bp->b_blkno = d_blkno;
4240 bp->b_offset = offset;
4241 bgetvp(vp, bp);
4242 BO_UNLOCK(bo);
4243
4244 /*
4245 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
4246 * buffer size starts out as 0, B_CACHE will be set by
4247 * allocbuf() for the VMIO case prior to it testing the
4248 * backing store for validity.
4249 */
4250
4251 if (vmio) {
4252 bp->b_flags |= B_VMIO;
4253 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
4254 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
4255 bp, vp->v_object, bp->b_bufobj->bo_object));
4256 } else {
4257 bp->b_flags &= ~B_VMIO;
4258 KASSERT(bp->b_bufobj->bo_object == NULL,
4259 ("ARGH! has b_bufobj->bo_object %p %p\n",
4260 bp, bp->b_bufobj->bo_object));
4261 BUF_CHECK_MAPPED(bp);
4262 }
4263
4264 allocbuf(bp, size);
4265 bufspace_release(bufdomain(bp), maxsize);
4266 bp->b_flags &= ~B_DONE;
4267 }
4268 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
4269 end:
4270 buf_track(bp, __func__);
4271 KASSERT(bp->b_bufobj == bo,
4272 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
4273 *bpp = bp;
4274 return (0);
4275 }
4276
4277 /*
4278 * Get an empty, disassociated buffer of given size. The buffer is initially
4279 * set to B_INVAL.
4280 */
4281 struct buf *
geteblk(int size,int flags)4282 geteblk(int size, int flags)
4283 {
4284 struct buf *bp;
4285 int maxsize;
4286
4287 maxsize = (size + BKVAMASK) & ~BKVAMASK;
4288 while ((bp = getnewbuf(NULL, 0, 0, maxsize, flags)) == NULL) {
4289 if ((flags & GB_NOWAIT_BD) &&
4290 (curthread->td_pflags & TDP_BUFNEED) != 0)
4291 return (NULL);
4292 }
4293 allocbuf(bp, size);
4294 bufspace_release(bufdomain(bp), maxsize);
4295 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
4296 return (bp);
4297 }
4298
4299 /*
4300 * Truncate the backing store for a non-vmio buffer.
4301 */
4302 static void
vfs_nonvmio_truncate(struct buf * bp,int newbsize)4303 vfs_nonvmio_truncate(struct buf *bp, int newbsize)
4304 {
4305
4306 if (bp->b_flags & B_MALLOC) {
4307 /*
4308 * malloced buffers are not shrunk
4309 */
4310 if (newbsize == 0) {
4311 bufmallocadjust(bp, 0);
4312 free(bp->b_data, M_BIOBUF);
4313 bp->b_data = bp->b_kvabase;
4314 bp->b_flags &= ~B_MALLOC;
4315 }
4316 return;
4317 }
4318 vm_hold_free_pages(bp, newbsize);
4319 bufspace_adjust(bp, newbsize);
4320 }
4321
4322 /*
4323 * Extend the backing for a non-VMIO buffer.
4324 */
4325 static void
vfs_nonvmio_extend(struct buf * bp,int newbsize)4326 vfs_nonvmio_extend(struct buf *bp, int newbsize)
4327 {
4328 caddr_t origbuf;
4329 int origbufsize;
4330
4331 /*
4332 * We only use malloced memory on the first allocation.
4333 * and revert to page-allocated memory when the buffer
4334 * grows.
4335 *
4336 * There is a potential smp race here that could lead
4337 * to bufmallocspace slightly passing the max. It
4338 * is probably extremely rare and not worth worrying
4339 * over.
4340 */
4341 if (bp->b_bufsize == 0 && newbsize <= PAGE_SIZE/2 &&
4342 bufmallocspace < maxbufmallocspace) {
4343 bp->b_data = malloc(newbsize, M_BIOBUF, M_WAITOK);
4344 bp->b_flags |= B_MALLOC;
4345 bufmallocadjust(bp, newbsize);
4346 return;
4347 }
4348
4349 /*
4350 * If the buffer is growing on its other-than-first
4351 * allocation then we revert to the page-allocation
4352 * scheme.
4353 */
4354 origbuf = NULL;
4355 origbufsize = 0;
4356 if (bp->b_flags & B_MALLOC) {
4357 origbuf = bp->b_data;
4358 origbufsize = bp->b_bufsize;
4359 bp->b_data = bp->b_kvabase;
4360 bufmallocadjust(bp, 0);
4361 bp->b_flags &= ~B_MALLOC;
4362 newbsize = round_page(newbsize);
4363 }
4364 vm_hold_load_pages(bp, (vm_offset_t) bp->b_data + bp->b_bufsize,
4365 (vm_offset_t) bp->b_data + newbsize);
4366 if (origbuf != NULL) {
4367 bcopy(origbuf, bp->b_data, origbufsize);
4368 free(origbuf, M_BIOBUF);
4369 }
4370 bufspace_adjust(bp, newbsize);
4371 }
4372
4373 /*
4374 * This code constitutes the buffer memory from either anonymous system
4375 * memory (in the case of non-VMIO operations) or from an associated
4376 * VM object (in the case of VMIO operations). This code is able to
4377 * resize a buffer up or down.
4378 *
4379 * Note that this code is tricky, and has many complications to resolve
4380 * deadlock or inconsistent data situations. Tread lightly!!!
4381 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
4382 * the caller. Calling this code willy nilly can result in the loss of data.
4383 *
4384 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
4385 * B_CACHE for the non-VMIO case.
4386 */
4387 int
allocbuf(struct buf * bp,int size)4388 allocbuf(struct buf *bp, int size)
4389 {
4390 int newbsize;
4391
4392 if (bp->b_bcount == size)
4393 return (1);
4394
4395 KASSERT(bp->b_kvasize == 0 || bp->b_kvasize >= size,
4396 ("allocbuf: buffer too small %p %#x %#x",
4397 bp, bp->b_kvasize, size));
4398
4399 newbsize = roundup2(size, DEV_BSIZE);
4400 if ((bp->b_flags & B_VMIO) == 0) {
4401 if ((bp->b_flags & B_MALLOC) == 0)
4402 newbsize = round_page(newbsize);
4403 /*
4404 * Just get anonymous memory from the kernel. Don't
4405 * mess with B_CACHE.
4406 */
4407 if (newbsize < bp->b_bufsize)
4408 vfs_nonvmio_truncate(bp, newbsize);
4409 else if (newbsize > bp->b_bufsize)
4410 vfs_nonvmio_extend(bp, newbsize);
4411 } else {
4412 int desiredpages;
4413
4414 desiredpages = size == 0 ? 0 :
4415 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
4416
4417 KASSERT((bp->b_flags & B_MALLOC) == 0,
4418 ("allocbuf: VMIO buffer can't be malloced %p", bp));
4419
4420 /*
4421 * Set B_CACHE initially if buffer is 0 length or will become
4422 * 0-length.
4423 */
4424 if (size == 0 || bp->b_bufsize == 0)
4425 bp->b_flags |= B_CACHE;
4426
4427 if (newbsize < bp->b_bufsize)
4428 vfs_vmio_truncate(bp, desiredpages);
4429 /* XXX This looks as if it should be newbsize > b_bufsize */
4430 else if (size > bp->b_bcount)
4431 vfs_vmio_extend(bp, desiredpages, size);
4432 bufspace_adjust(bp, newbsize);
4433 }
4434 bp->b_bcount = size; /* requested buffer size. */
4435 return (1);
4436 }
4437
4438 extern int inflight_transient_maps;
4439
4440 static struct bio_queue nondump_bios;
4441
4442 void
biodone(struct bio * bp)4443 biodone(struct bio *bp)
4444 {
4445 struct mtx *mtxp;
4446 void (*done)(struct bio *);
4447 vm_offset_t start, end;
4448
4449 biotrack(bp, __func__);
4450
4451 /*
4452 * Avoid completing I/O when dumping after a panic since that may
4453 * result in a deadlock in the filesystem or pager code. Note that
4454 * this doesn't affect dumps that were started manually since we aim
4455 * to keep the system usable after it has been resumed.
4456 */
4457 if (__predict_false(dumping && SCHEDULER_STOPPED())) {
4458 TAILQ_INSERT_HEAD(&nondump_bios, bp, bio_queue);
4459 return;
4460 }
4461 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
4462 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
4463 bp->bio_flags |= BIO_UNMAPPED;
4464 start = trunc_page((vm_offset_t)bp->bio_data);
4465 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
4466 bp->bio_data = unmapped_buf;
4467 pmap_qremove(start, atop(end - start));
4468 vmem_free(transient_arena, start, end - start);
4469 atomic_add_int(&inflight_transient_maps, -1);
4470 }
4471 done = bp->bio_done;
4472 /*
4473 * The check for done == biodone is to allow biodone to be
4474 * used as a bio_done routine.
4475 */
4476 if (done == NULL || done == biodone) {
4477 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4478 mtx_lock(mtxp);
4479 bp->bio_flags |= BIO_DONE;
4480 wakeup(bp);
4481 mtx_unlock(mtxp);
4482 } else
4483 done(bp);
4484 }
4485
4486 /*
4487 * Wait for a BIO to finish.
4488 */
4489 int
biowait(struct bio * bp,const char * wmesg)4490 biowait(struct bio *bp, const char *wmesg)
4491 {
4492 struct mtx *mtxp;
4493
4494 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4495 mtx_lock(mtxp);
4496 while ((bp->bio_flags & BIO_DONE) == 0)
4497 msleep(bp, mtxp, PRIBIO, wmesg, 0);
4498 mtx_unlock(mtxp);
4499 if (bp->bio_error != 0)
4500 return (bp->bio_error);
4501 if (!(bp->bio_flags & BIO_ERROR))
4502 return (0);
4503 return (EIO);
4504 }
4505
4506 void
biofinish(struct bio * bp,struct devstat * stat,int error)4507 biofinish(struct bio *bp, struct devstat *stat, int error)
4508 {
4509
4510 if (error) {
4511 bp->bio_error = error;
4512 bp->bio_flags |= BIO_ERROR;
4513 }
4514 if (stat != NULL)
4515 devstat_end_transaction_bio(stat, bp);
4516 biodone(bp);
4517 }
4518
4519 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
4520 void
biotrack_buf(struct bio * bp,const char * location)4521 biotrack_buf(struct bio *bp, const char *location)
4522 {
4523
4524 buf_track(bp->bio_track_bp, location);
4525 }
4526 #endif
4527
4528 /*
4529 * bufwait:
4530 *
4531 * Wait for buffer I/O completion, returning error status. The buffer
4532 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
4533 * error and cleared.
4534 */
4535 int
bufwait(struct buf * bp)4536 bufwait(struct buf *bp)
4537 {
4538 if (bp->b_iocmd == BIO_READ)
4539 bwait(bp, PRIBIO, "biord");
4540 else
4541 bwait(bp, PRIBIO, "biowr");
4542 if (bp->b_flags & B_EINTR) {
4543 bp->b_flags &= ~B_EINTR;
4544 return (EINTR);
4545 }
4546 if (bp->b_ioflags & BIO_ERROR) {
4547 return (bp->b_error ? bp->b_error : EIO);
4548 } else {
4549 return (0);
4550 }
4551 }
4552
4553 /*
4554 * bufdone:
4555 *
4556 * Finish I/O on a buffer, optionally calling a completion function.
4557 * This is usually called from an interrupt so process blocking is
4558 * not allowed.
4559 *
4560 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
4561 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
4562 * assuming B_INVAL is clear.
4563 *
4564 * For the VMIO case, we set B_CACHE if the op was a read and no
4565 * read error occurred, or if the op was a write. B_CACHE is never
4566 * set if the buffer is invalid or otherwise uncacheable.
4567 *
4568 * bufdone does not mess with B_INVAL, allowing the I/O routine or the
4569 * initiator to leave B_INVAL set to brelse the buffer out of existence
4570 * in the biodone routine.
4571 */
4572 void
bufdone(struct buf * bp)4573 bufdone(struct buf *bp)
4574 {
4575 struct bufobj *dropobj;
4576 void (*biodone)(struct buf *);
4577
4578 buf_track(bp, __func__);
4579 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
4580 dropobj = NULL;
4581
4582 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
4583
4584 runningbufwakeup(bp);
4585 if (bp->b_iocmd == BIO_WRITE)
4586 dropobj = bp->b_bufobj;
4587 /* call optional completion function if requested */
4588 if (bp->b_iodone != NULL) {
4589 biodone = bp->b_iodone;
4590 bp->b_iodone = NULL;
4591 (*biodone) (bp);
4592 if (dropobj)
4593 bufobj_wdrop(dropobj);
4594 return;
4595 }
4596 if (bp->b_flags & B_VMIO) {
4597 /*
4598 * Set B_CACHE if the op was a normal read and no error
4599 * occurred. B_CACHE is set for writes in the b*write()
4600 * routines.
4601 */
4602 if (bp->b_iocmd == BIO_READ &&
4603 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
4604 !(bp->b_ioflags & BIO_ERROR))
4605 bp->b_flags |= B_CACHE;
4606 vfs_vmio_iodone(bp);
4607 }
4608 if (!LIST_EMPTY(&bp->b_dep))
4609 buf_complete(bp);
4610 if ((bp->b_flags & B_CKHASH) != 0) {
4611 KASSERT(bp->b_iocmd == BIO_READ,
4612 ("bufdone: b_iocmd %d not BIO_READ", bp->b_iocmd));
4613 KASSERT(buf_mapped(bp), ("bufdone: bp %p not mapped", bp));
4614 (*bp->b_ckhashcalc)(bp);
4615 }
4616 /*
4617 * For asynchronous completions, release the buffer now. The brelse
4618 * will do a wakeup there if necessary - so no need to do a wakeup
4619 * here in the async case. The sync case always needs to do a wakeup.
4620 */
4621 if (bp->b_flags & B_ASYNC) {
4622 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) ||
4623 (bp->b_ioflags & BIO_ERROR))
4624 brelse(bp);
4625 else
4626 bqrelse(bp);
4627 } else
4628 bdone(bp);
4629 if (dropobj)
4630 bufobj_wdrop(dropobj);
4631 }
4632
4633 /*
4634 * This routine is called in lieu of iodone in the case of
4635 * incomplete I/O. This keeps the busy status for pages
4636 * consistent.
4637 */
4638 void
vfs_unbusy_pages(struct buf * bp)4639 vfs_unbusy_pages(struct buf *bp)
4640 {
4641 int i;
4642 vm_object_t obj;
4643 vm_page_t m;
4644
4645 runningbufwakeup(bp);
4646 if (!(bp->b_flags & B_VMIO))
4647 return;
4648
4649 obj = bp->b_bufobj->bo_object;
4650 for (i = 0; i < bp->b_npages; i++) {
4651 m = bp->b_pages[i];
4652 if (m == bogus_page) {
4653 m = vm_page_relookup(obj, OFF_TO_IDX(bp->b_offset) + i);
4654 if (!m)
4655 panic("vfs_unbusy_pages: page missing\n");
4656 bp->b_pages[i] = m;
4657 if (buf_mapped(bp)) {
4658 BUF_CHECK_MAPPED(bp);
4659 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4660 bp->b_pages, bp->b_npages);
4661 } else
4662 BUF_CHECK_UNMAPPED(bp);
4663 }
4664 vm_page_sunbusy(m);
4665 }
4666 vm_object_pip_wakeupn(obj, bp->b_npages);
4667 }
4668
4669 /*
4670 * vfs_page_set_valid:
4671 *
4672 * Set the valid bits in a page based on the supplied offset. The
4673 * range is restricted to the buffer's size.
4674 *
4675 * This routine is typically called after a read completes.
4676 */
4677 static void
vfs_page_set_valid(struct buf * bp,vm_ooffset_t off,vm_page_t m)4678 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4679 {
4680 vm_ooffset_t eoff;
4681
4682 /*
4683 * Compute the end offset, eoff, such that [off, eoff) does not span a
4684 * page boundary and eoff is not greater than the end of the buffer.
4685 * The end of the buffer, in this case, is our file EOF, not the
4686 * allocation size of the buffer.
4687 */
4688 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
4689 if (eoff > bp->b_offset + bp->b_bcount)
4690 eoff = bp->b_offset + bp->b_bcount;
4691
4692 /*
4693 * Set valid range. This is typically the entire buffer and thus the
4694 * entire page.
4695 */
4696 if (eoff > off)
4697 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
4698 }
4699
4700 /*
4701 * vfs_page_set_validclean:
4702 *
4703 * Set the valid bits and clear the dirty bits in a page based on the
4704 * supplied offset. The range is restricted to the buffer's size.
4705 */
4706 static void
vfs_page_set_validclean(struct buf * bp,vm_ooffset_t off,vm_page_t m)4707 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4708 {
4709 vm_ooffset_t soff, eoff;
4710
4711 /*
4712 * Start and end offsets in buffer. eoff - soff may not cross a
4713 * page boundary or cross the end of the buffer. The end of the
4714 * buffer, in this case, is our file EOF, not the allocation size
4715 * of the buffer.
4716 */
4717 soff = off;
4718 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4719 if (eoff > bp->b_offset + bp->b_bcount)
4720 eoff = bp->b_offset + bp->b_bcount;
4721
4722 /*
4723 * Set valid range. This is typically the entire buffer and thus the
4724 * entire page.
4725 */
4726 if (eoff > soff) {
4727 vm_page_set_validclean(
4728 m,
4729 (vm_offset_t) (soff & PAGE_MASK),
4730 (vm_offset_t) (eoff - soff)
4731 );
4732 }
4733 }
4734
4735 /*
4736 * Acquire a shared busy on all pages in the buf.
4737 */
4738 void
vfs_busy_pages_acquire(struct buf * bp)4739 vfs_busy_pages_acquire(struct buf *bp)
4740 {
4741 int i;
4742
4743 for (i = 0; i < bp->b_npages; i++)
4744 vm_page_busy_acquire(bp->b_pages[i], VM_ALLOC_SBUSY);
4745 }
4746
4747 void
vfs_busy_pages_release(struct buf * bp)4748 vfs_busy_pages_release(struct buf *bp)
4749 {
4750 int i;
4751
4752 for (i = 0; i < bp->b_npages; i++)
4753 vm_page_sunbusy(bp->b_pages[i]);
4754 }
4755
4756 /*
4757 * This routine is called before a device strategy routine.
4758 * It is used to tell the VM system that paging I/O is in
4759 * progress, and treat the pages associated with the buffer
4760 * almost as being exclusive busy. Also the object paging_in_progress
4761 * flag is handled to make sure that the object doesn't become
4762 * inconsistent.
4763 *
4764 * Since I/O has not been initiated yet, certain buffer flags
4765 * such as BIO_ERROR or B_INVAL may be in an inconsistent state
4766 * and should be ignored.
4767 */
4768 void
vfs_busy_pages(struct buf * bp,int clear_modify)4769 vfs_busy_pages(struct buf *bp, int clear_modify)
4770 {
4771 vm_object_t obj;
4772 vm_ooffset_t foff;
4773 vm_page_t m;
4774 int i;
4775 bool bogus;
4776
4777 if (!(bp->b_flags & B_VMIO))
4778 return;
4779
4780 obj = bp->b_bufobj->bo_object;
4781 foff = bp->b_offset;
4782 KASSERT(bp->b_offset != NOOFFSET,
4783 ("vfs_busy_pages: no buffer offset"));
4784 if ((bp->b_flags & B_CLUSTER) == 0) {
4785 vm_object_pip_add(obj, bp->b_npages);
4786 vfs_busy_pages_acquire(bp);
4787 }
4788 if (bp->b_bufsize != 0)
4789 vfs_setdirty_range(bp);
4790 bogus = false;
4791 for (i = 0; i < bp->b_npages; i++) {
4792 m = bp->b_pages[i];
4793 vm_page_assert_sbusied(m);
4794
4795 /*
4796 * When readying a buffer for a read ( i.e
4797 * clear_modify == 0 ), it is important to do
4798 * bogus_page replacement for valid pages in
4799 * partially instantiated buffers. Partially
4800 * instantiated buffers can, in turn, occur when
4801 * reconstituting a buffer from its VM backing store
4802 * base. We only have to do this if B_CACHE is
4803 * clear ( which causes the I/O to occur in the
4804 * first place ). The replacement prevents the read
4805 * I/O from overwriting potentially dirty VM-backed
4806 * pages. XXX bogus page replacement is, uh, bogus.
4807 * It may not work properly with small-block devices.
4808 * We need to find a better way.
4809 */
4810 if (clear_modify) {
4811 pmap_remove_write(m);
4812 vfs_page_set_validclean(bp, foff, m);
4813 } else if (vm_page_all_valid(m) &&
4814 (bp->b_flags & B_CACHE) == 0) {
4815 bp->b_pages[i] = bogus_page;
4816 bogus = true;
4817 }
4818 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4819 }
4820 if (bogus && buf_mapped(bp)) {
4821 BUF_CHECK_MAPPED(bp);
4822 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4823 bp->b_pages, bp->b_npages);
4824 }
4825 }
4826
4827 /*
4828 * vfs_bio_set_valid:
4829 *
4830 * Set the range within the buffer to valid. The range is
4831 * relative to the beginning of the buffer, b_offset. Note that
4832 * b_offset itself may be offset from the beginning of the first
4833 * page.
4834 */
4835 void
vfs_bio_set_valid(struct buf * bp,int base,int size)4836 vfs_bio_set_valid(struct buf *bp, int base, int size)
4837 {
4838 int i, n;
4839 vm_page_t m;
4840
4841 if (!(bp->b_flags & B_VMIO))
4842 return;
4843
4844 /*
4845 * Fixup base to be relative to beginning of first page.
4846 * Set initial n to be the maximum number of bytes in the
4847 * first page that can be validated.
4848 */
4849 base += (bp->b_offset & PAGE_MASK);
4850 n = PAGE_SIZE - (base & PAGE_MASK);
4851
4852 /*
4853 * Busy may not be strictly necessary here because the pages are
4854 * unlikely to be fully valid and the vnode lock will synchronize
4855 * their access via getpages. It is grabbed for consistency with
4856 * other page validation.
4857 */
4858 vfs_busy_pages_acquire(bp);
4859 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4860 m = bp->b_pages[i];
4861 if (n > size)
4862 n = size;
4863 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4864 base += n;
4865 size -= n;
4866 n = PAGE_SIZE;
4867 }
4868 vfs_busy_pages_release(bp);
4869 }
4870
4871 /*
4872 * vfs_bio_clrbuf:
4873 *
4874 * If the specified buffer is a non-VMIO buffer, clear the entire
4875 * buffer. If the specified buffer is a VMIO buffer, clear and
4876 * validate only the previously invalid portions of the buffer.
4877 * This routine essentially fakes an I/O, so we need to clear
4878 * BIO_ERROR and B_INVAL.
4879 *
4880 * Note that while we only theoretically need to clear through b_bcount,
4881 * we go ahead and clear through b_bufsize.
4882 */
4883 void
vfs_bio_clrbuf(struct buf * bp)4884 vfs_bio_clrbuf(struct buf *bp)
4885 {
4886 int i, j, sa, ea, slide, zbits;
4887 vm_page_bits_t mask;
4888
4889 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4890 clrbuf(bp);
4891 return;
4892 }
4893 bp->b_flags &= ~B_INVAL;
4894 bp->b_ioflags &= ~BIO_ERROR;
4895 vfs_busy_pages_acquire(bp);
4896 sa = bp->b_offset & PAGE_MASK;
4897 slide = 0;
4898 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4899 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4900 ea = slide & PAGE_MASK;
4901 if (ea == 0)
4902 ea = PAGE_SIZE;
4903 if (bp->b_pages[i] == bogus_page)
4904 continue;
4905 j = sa / DEV_BSIZE;
4906 zbits = (sizeof(vm_page_bits_t) * NBBY) -
4907 (ea - sa) / DEV_BSIZE;
4908 mask = (VM_PAGE_BITS_ALL >> zbits) << j;
4909 if ((bp->b_pages[i]->valid & mask) == mask)
4910 continue;
4911 if ((bp->b_pages[i]->valid & mask) == 0)
4912 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4913 else {
4914 for (; sa < ea; sa += DEV_BSIZE, j++) {
4915 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4916 pmap_zero_page_area(bp->b_pages[i],
4917 sa, DEV_BSIZE);
4918 }
4919 }
4920 }
4921 vm_page_set_valid_range(bp->b_pages[i], j * DEV_BSIZE,
4922 roundup2(ea - sa, DEV_BSIZE));
4923 }
4924 vfs_busy_pages_release(bp);
4925 bp->b_resid = 0;
4926 }
4927
4928 void
vfs_bio_bzero_buf(struct buf * bp,int base,int size)4929 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4930 {
4931 vm_page_t m;
4932 int i, n;
4933
4934 if (buf_mapped(bp)) {
4935 BUF_CHECK_MAPPED(bp);
4936 bzero(bp->b_data + base, size);
4937 } else {
4938 BUF_CHECK_UNMAPPED(bp);
4939 n = PAGE_SIZE - (base & PAGE_MASK);
4940 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4941 m = bp->b_pages[i];
4942 if (n > size)
4943 n = size;
4944 pmap_zero_page_area(m, base & PAGE_MASK, n);
4945 base += n;
4946 size -= n;
4947 n = PAGE_SIZE;
4948 }
4949 }
4950 }
4951
4952 /*
4953 * Update buffer flags based on I/O request parameters, optionally releasing the
4954 * buffer. If it's VMIO or direct I/O, the buffer pages are released to the VM,
4955 * where they may be placed on a page queue (VMIO) or freed immediately (direct
4956 * I/O). Otherwise the buffer is released to the cache.
4957 */
4958 static void
b_io_dismiss(struct buf * bp,int ioflag,bool release)4959 b_io_dismiss(struct buf *bp, int ioflag, bool release)
4960 {
4961
4962 KASSERT((ioflag & IO_NOREUSE) == 0 || (ioflag & IO_VMIO) != 0,
4963 ("buf %p non-VMIO noreuse", bp));
4964
4965 if ((ioflag & IO_DIRECT) != 0)
4966 bp->b_flags |= B_DIRECT;
4967 if ((ioflag & IO_EXT) != 0)
4968 bp->b_xflags |= BX_ALTDATA;
4969 if ((ioflag & (IO_VMIO | IO_DIRECT)) != 0 && LIST_EMPTY(&bp->b_dep)) {
4970 bp->b_flags |= B_RELBUF;
4971 if ((ioflag & IO_NOREUSE) != 0)
4972 bp->b_flags |= B_NOREUSE;
4973 if (release)
4974 brelse(bp);
4975 } else if (release)
4976 bqrelse(bp);
4977 }
4978
4979 void
vfs_bio_brelse(struct buf * bp,int ioflag)4980 vfs_bio_brelse(struct buf *bp, int ioflag)
4981 {
4982
4983 b_io_dismiss(bp, ioflag, true);
4984 }
4985
4986 void
vfs_bio_set_flags(struct buf * bp,int ioflag)4987 vfs_bio_set_flags(struct buf *bp, int ioflag)
4988 {
4989
4990 b_io_dismiss(bp, ioflag, false);
4991 }
4992
4993 /*
4994 * vm_hold_load_pages and vm_hold_free_pages get pages into
4995 * a buffers address space. The pages are anonymous and are
4996 * not associated with a file object.
4997 */
4998 static void
vm_hold_load_pages(struct buf * bp,vm_offset_t from,vm_offset_t to)4999 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
5000 {
5001 vm_offset_t pg;
5002 vm_page_t p;
5003 int index;
5004
5005 BUF_CHECK_MAPPED(bp);
5006
5007 to = round_page(to);
5008 from = round_page(from);
5009 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
5010 MPASS((bp->b_flags & B_MAXPHYS) == 0);
5011 KASSERT(to - from <= maxbcachebuf,
5012 ("vm_hold_load_pages too large %p %#jx %#jx %u",
5013 bp, (uintmax_t)from, (uintmax_t)to, maxbcachebuf));
5014
5015 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
5016 /*
5017 * note: must allocate system pages since blocking here
5018 * could interfere with paging I/O, no matter which
5019 * process we are.
5020 */
5021 p = vm_page_alloc_noobj(VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
5022 VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT) | VM_ALLOC_WAITOK);
5023 pmap_qenter(pg, &p, 1);
5024 bp->b_pages[index] = p;
5025 }
5026 bp->b_npages = index;
5027 }
5028
5029 /* Return pages associated with this buf to the vm system */
5030 static void
vm_hold_free_pages(struct buf * bp,int newbsize)5031 vm_hold_free_pages(struct buf *bp, int newbsize)
5032 {
5033 vm_offset_t from;
5034 vm_page_t p;
5035 int index, newnpages;
5036
5037 BUF_CHECK_MAPPED(bp);
5038
5039 from = round_page((vm_offset_t)bp->b_data + newbsize);
5040 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
5041 if (bp->b_npages > newnpages)
5042 pmap_qremove(from, bp->b_npages - newnpages);
5043 for (index = newnpages; index < bp->b_npages; index++) {
5044 p = bp->b_pages[index];
5045 bp->b_pages[index] = NULL;
5046 vm_page_unwire_noq(p);
5047 vm_page_free(p);
5048 }
5049 bp->b_npages = newnpages;
5050 }
5051
5052 /*
5053 * Map an IO request into kernel virtual address space.
5054 *
5055 * All requests are (re)mapped into kernel VA space.
5056 * Notice that we use b_bufsize for the size of the buffer
5057 * to be mapped. b_bcount might be modified by the driver.
5058 *
5059 * Note that even if the caller determines that the address space should
5060 * be valid, a race or a smaller-file mapped into a larger space may
5061 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
5062 * check the return value.
5063 *
5064 * This function only works with pager buffers.
5065 */
5066 int
vmapbuf(struct buf * bp,void * uaddr,size_t len,int mapbuf)5067 vmapbuf(struct buf *bp, void *uaddr, size_t len, int mapbuf)
5068 {
5069 vm_prot_t prot;
5070 int pidx;
5071
5072 MPASS((bp->b_flags & B_MAXPHYS) != 0);
5073 prot = VM_PROT_READ;
5074 if (bp->b_iocmd == BIO_READ)
5075 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
5076 pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
5077 (vm_offset_t)uaddr, len, prot, bp->b_pages, PBUF_PAGES);
5078 if (pidx < 0)
5079 return (-1);
5080 bp->b_bufsize = len;
5081 bp->b_npages = pidx;
5082 bp->b_offset = ((vm_offset_t)uaddr) & PAGE_MASK;
5083 if (mapbuf || !unmapped_buf_allowed) {
5084 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_pages, pidx);
5085 bp->b_data = bp->b_kvabase + bp->b_offset;
5086 } else
5087 bp->b_data = unmapped_buf;
5088 return (0);
5089 }
5090
5091 /*
5092 * Free the io map PTEs associated with this IO operation.
5093 * We also invalidate the TLB entries and restore the original b_addr.
5094 *
5095 * This function only works with pager buffers.
5096 */
5097 void
vunmapbuf(struct buf * bp)5098 vunmapbuf(struct buf *bp)
5099 {
5100 int npages;
5101
5102 npages = bp->b_npages;
5103 if (buf_mapped(bp))
5104 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
5105 vm_page_unhold_pages(bp->b_pages, npages);
5106
5107 bp->b_data = unmapped_buf;
5108 }
5109
5110 void
bdone(struct buf * bp)5111 bdone(struct buf *bp)
5112 {
5113 struct mtx *mtxp;
5114
5115 mtxp = mtx_pool_find(mtxpool_sleep, bp);
5116 mtx_lock(mtxp);
5117 bp->b_flags |= B_DONE;
5118 wakeup(bp);
5119 mtx_unlock(mtxp);
5120 }
5121
5122 void
bwait(struct buf * bp,u_char pri,const char * wchan)5123 bwait(struct buf *bp, u_char pri, const char *wchan)
5124 {
5125 struct mtx *mtxp;
5126
5127 mtxp = mtx_pool_find(mtxpool_sleep, bp);
5128 mtx_lock(mtxp);
5129 while ((bp->b_flags & B_DONE) == 0)
5130 msleep(bp, mtxp, pri, wchan, 0);
5131 mtx_unlock(mtxp);
5132 }
5133
5134 int
bufsync(struct bufobj * bo,int waitfor)5135 bufsync(struct bufobj *bo, int waitfor)
5136 {
5137
5138 return (VOP_FSYNC(bo2vnode(bo), waitfor, curthread));
5139 }
5140
5141 void
bufstrategy(struct bufobj * bo,struct buf * bp)5142 bufstrategy(struct bufobj *bo, struct buf *bp)
5143 {
5144 int i __unused;
5145 struct vnode *vp;
5146
5147 vp = bp->b_vp;
5148 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
5149 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
5150 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
5151 i = VOP_STRATEGY(vp, bp);
5152 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
5153 }
5154
5155 /*
5156 * Initialize a struct bufobj before use. Memory is assumed zero filled.
5157 */
5158 void
bufobj_init(struct bufobj * bo,void * private)5159 bufobj_init(struct bufobj *bo, void *private)
5160 {
5161 static volatile int bufobj_cleanq;
5162
5163 bo->bo_domain =
5164 atomic_fetchadd_int(&bufobj_cleanq, 1) % buf_domains;
5165 rw_init(BO_LOCKPTR(bo), "bufobj interlock");
5166 bo->bo_private = private;
5167 TAILQ_INIT(&bo->bo_clean.bv_hd);
5168 pctrie_init(&bo->bo_clean.bv_root);
5169 TAILQ_INIT(&bo->bo_dirty.bv_hd);
5170 pctrie_init(&bo->bo_dirty.bv_root);
5171 }
5172
5173 void
bufobj_wrefl(struct bufobj * bo)5174 bufobj_wrefl(struct bufobj *bo)
5175 {
5176
5177 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
5178 ASSERT_BO_WLOCKED(bo);
5179 bo->bo_numoutput++;
5180 }
5181
5182 void
bufobj_wref(struct bufobj * bo)5183 bufobj_wref(struct bufobj *bo)
5184 {
5185
5186 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
5187 BO_LOCK(bo);
5188 bo->bo_numoutput++;
5189 BO_UNLOCK(bo);
5190 }
5191
5192 void
bufobj_wdrop(struct bufobj * bo)5193 bufobj_wdrop(struct bufobj *bo)
5194 {
5195
5196 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
5197 BO_LOCK(bo);
5198 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
5199 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
5200 bo->bo_flag &= ~BO_WWAIT;
5201 wakeup(&bo->bo_numoutput);
5202 }
5203 BO_UNLOCK(bo);
5204 }
5205
5206 int
bufobj_wwait(struct bufobj * bo,int slpflag,int timeo)5207 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
5208 {
5209 int error;
5210
5211 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
5212 ASSERT_BO_WLOCKED(bo);
5213 error = 0;
5214 while (bo->bo_numoutput) {
5215 bo->bo_flag |= BO_WWAIT;
5216 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
5217 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
5218 if (error)
5219 break;
5220 }
5221 return (error);
5222 }
5223
5224 /*
5225 * Set bio_data or bio_ma for struct bio from the struct buf.
5226 */
5227 void
bdata2bio(struct buf * bp,struct bio * bip)5228 bdata2bio(struct buf *bp, struct bio *bip)
5229 {
5230
5231 if (!buf_mapped(bp)) {
5232 KASSERT(unmapped_buf_allowed, ("unmapped"));
5233 bip->bio_ma = bp->b_pages;
5234 bip->bio_ma_n = bp->b_npages;
5235 bip->bio_data = unmapped_buf;
5236 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
5237 bip->bio_flags |= BIO_UNMAPPED;
5238 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
5239 PAGE_SIZE == bp->b_npages,
5240 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
5241 (long long)bip->bio_length, bip->bio_ma_n));
5242 } else {
5243 bip->bio_data = bp->b_data;
5244 bip->bio_ma = NULL;
5245 }
5246 }
5247
5248 struct memdesc
memdesc_bio(struct bio * bio)5249 memdesc_bio(struct bio *bio)
5250 {
5251 if ((bio->bio_flags & BIO_VLIST) != 0)
5252 return (memdesc_vlist((struct bus_dma_segment *)bio->bio_data,
5253 bio->bio_ma_n));
5254
5255 if ((bio->bio_flags & BIO_UNMAPPED) != 0)
5256 return (memdesc_vmpages(bio->bio_ma, bio->bio_bcount,
5257 bio->bio_ma_offset));
5258
5259 return (memdesc_vaddr(bio->bio_data, bio->bio_bcount));
5260 }
5261
5262 static int buf_pager_relbuf;
5263 SYSCTL_INT(_vfs, OID_AUTO, buf_pager_relbuf, CTLFLAG_RWTUN,
5264 &buf_pager_relbuf, 0,
5265 "Make buffer pager release buffers after reading");
5266
5267 /*
5268 * The buffer pager. It uses buffer reads to validate pages.
5269 *
5270 * In contrast to the generic local pager from vm/vnode_pager.c, this
5271 * pager correctly and easily handles volumes where the underlying
5272 * device block size is greater than the machine page size. The
5273 * buffer cache transparently extends the requested page run to be
5274 * aligned at the block boundary, and does the necessary bogus page
5275 * replacements in the addends to avoid obliterating already valid
5276 * pages.
5277 *
5278 * The only non-trivial issue is that the exclusive busy state for
5279 * pages, which is assumed by the vm_pager_getpages() interface, is
5280 * incompatible with the VMIO buffer cache's desire to share-busy the
5281 * pages. This function performs a trivial downgrade of the pages'
5282 * state before reading buffers, and a less trivial upgrade from the
5283 * shared-busy to excl-busy state after the read.
5284 */
5285 int
vfs_bio_getpages(struct vnode * vp,vm_page_t * ma,int count,int * rbehind,int * rahead,vbg_get_lblkno_t get_lblkno,vbg_get_blksize_t get_blksize)5286 vfs_bio_getpages(struct vnode *vp, vm_page_t *ma, int count,
5287 int *rbehind, int *rahead, vbg_get_lblkno_t get_lblkno,
5288 vbg_get_blksize_t get_blksize)
5289 {
5290 vm_page_t m;
5291 vm_object_t object;
5292 struct buf *bp;
5293 struct mount *mp;
5294 daddr_t lbn, lbnp;
5295 vm_ooffset_t la, lb, poff, poffe;
5296 long bo_bs, bsize;
5297 int br_flags, error, i, pgsin, pgsin_a, pgsin_b;
5298 bool redo, lpart;
5299
5300 object = vp->v_object;
5301 mp = vp->v_mount;
5302 error = 0;
5303 la = IDX_TO_OFF(ma[count - 1]->pindex);
5304 if (la >= object->un_pager.vnp.vnp_size)
5305 return (VM_PAGER_BAD);
5306
5307 /*
5308 * Change the meaning of la from where the last requested page starts
5309 * to where it ends, because that's the end of the requested region
5310 * and the start of the potential read-ahead region.
5311 */
5312 la += PAGE_SIZE;
5313 lpart = la > object->un_pager.vnp.vnp_size;
5314 error = get_blksize(vp, get_lblkno(vp, IDX_TO_OFF(ma[0]->pindex)),
5315 &bo_bs);
5316 if (error != 0)
5317 return (VM_PAGER_ERROR);
5318
5319 /*
5320 * Calculate read-ahead, behind and total pages.
5321 */
5322 pgsin = count;
5323 lb = IDX_TO_OFF(ma[0]->pindex);
5324 pgsin_b = OFF_TO_IDX(lb - rounddown2(lb, bo_bs));
5325 pgsin += pgsin_b;
5326 if (rbehind != NULL)
5327 *rbehind = pgsin_b;
5328 pgsin_a = OFF_TO_IDX(roundup2(la, bo_bs) - la);
5329 if (la + IDX_TO_OFF(pgsin_a) >= object->un_pager.vnp.vnp_size)
5330 pgsin_a = OFF_TO_IDX(roundup2(object->un_pager.vnp.vnp_size,
5331 PAGE_SIZE) - la);
5332 pgsin += pgsin_a;
5333 if (rahead != NULL)
5334 *rahead = pgsin_a;
5335 VM_CNT_INC(v_vnodein);
5336 VM_CNT_ADD(v_vnodepgsin, pgsin);
5337
5338 br_flags = (mp != NULL && (mp->mnt_kern_flag & MNTK_UNMAPPED_BUFS)
5339 != 0) ? GB_UNMAPPED : 0;
5340 again:
5341 for (i = 0; i < count; i++) {
5342 if (ma[i] != bogus_page)
5343 vm_page_busy_downgrade(ma[i]);
5344 }
5345
5346 lbnp = -1;
5347 for (i = 0; i < count; i++) {
5348 m = ma[i];
5349 if (m == bogus_page)
5350 continue;
5351
5352 /*
5353 * Pages are shared busy and the object lock is not
5354 * owned, which together allow for the pages'
5355 * invalidation. The racy test for validity avoids
5356 * useless creation of the buffer for the most typical
5357 * case when invalidation is not used in redo or for
5358 * parallel read. The shared->excl upgrade loop at
5359 * the end of the function catches the race in a
5360 * reliable way (protected by the object lock).
5361 */
5362 if (vm_page_all_valid(m))
5363 continue;
5364
5365 poff = IDX_TO_OFF(m->pindex);
5366 poffe = MIN(poff + PAGE_SIZE, object->un_pager.vnp.vnp_size);
5367 for (; poff < poffe; poff += bsize) {
5368 lbn = get_lblkno(vp, poff);
5369 if (lbn == lbnp)
5370 goto next_page;
5371 lbnp = lbn;
5372
5373 error = get_blksize(vp, lbn, &bsize);
5374 if (error == 0)
5375 error = bread_gb(vp, lbn, bsize,
5376 curthread->td_ucred, br_flags, &bp);
5377 if (error != 0)
5378 goto end_pages;
5379 if (bp->b_rcred == curthread->td_ucred) {
5380 crfree(bp->b_rcred);
5381 bp->b_rcred = NOCRED;
5382 }
5383 if (LIST_EMPTY(&bp->b_dep)) {
5384 /*
5385 * Invalidation clears m->valid, but
5386 * may leave B_CACHE flag if the
5387 * buffer existed at the invalidation
5388 * time. In this case, recycle the
5389 * buffer to do real read on next
5390 * bread() after redo.
5391 *
5392 * Otherwise B_RELBUF is not strictly
5393 * necessary, enable to reduce buf
5394 * cache pressure.
5395 */
5396 if (buf_pager_relbuf ||
5397 !vm_page_all_valid(m))
5398 bp->b_flags |= B_RELBUF;
5399
5400 bp->b_flags &= ~B_NOCACHE;
5401 brelse(bp);
5402 } else {
5403 bqrelse(bp);
5404 }
5405 }
5406 KASSERT(1 /* racy, enable for debugging */ ||
5407 vm_page_all_valid(m) || i == count - 1,
5408 ("buf %d %p invalid", i, m));
5409 if (i == count - 1 && lpart) {
5410 if (!vm_page_none_valid(m) &&
5411 !vm_page_all_valid(m))
5412 vm_page_zero_invalid(m, TRUE);
5413 }
5414 next_page:;
5415 }
5416 end_pages:
5417
5418 redo = false;
5419 for (i = 0; i < count; i++) {
5420 if (ma[i] == bogus_page)
5421 continue;
5422 if (vm_page_busy_tryupgrade(ma[i]) == 0) {
5423 vm_page_sunbusy(ma[i]);
5424 ma[i] = vm_page_grab_unlocked(object, ma[i]->pindex,
5425 VM_ALLOC_NORMAL);
5426 }
5427
5428 /*
5429 * Since the pages were only sbusy while neither the
5430 * buffer nor the object lock was held by us, or
5431 * reallocated while vm_page_grab() slept for busy
5432 * relinguish, they could have been invalidated.
5433 * Recheck the valid bits and re-read as needed.
5434 *
5435 * Note that the last page is made fully valid in the
5436 * read loop, and partial validity for the page at
5437 * index count - 1 could mean that the page was
5438 * invalidated or removed, so we must restart for
5439 * safety as well.
5440 */
5441 if (!vm_page_all_valid(ma[i]))
5442 redo = true;
5443 }
5444 if (redo && error == 0)
5445 goto again;
5446 return (error != 0 ? VM_PAGER_ERROR : VM_PAGER_OK);
5447 }
5448
5449 #include "opt_ddb.h"
5450 #ifdef DDB
5451 #include <ddb/ddb.h>
5452
5453 /* DDB command to show buffer data */
DB_SHOW_COMMAND(buffer,db_show_buffer)5454 DB_SHOW_COMMAND(buffer, db_show_buffer)
5455 {
5456 /* get args */
5457 struct buf *bp = (struct buf *)addr;
5458 #ifdef FULL_BUF_TRACKING
5459 uint32_t i, j;
5460 #endif
5461
5462 if (!have_addr) {
5463 db_printf("usage: show buffer <addr>\n");
5464 return;
5465 }
5466
5467 db_printf("buf at %p\n", bp);
5468 db_printf("b_flags = 0x%b, b_xflags=0x%b\n",
5469 (u_int)bp->b_flags, PRINT_BUF_FLAGS,
5470 (u_int)bp->b_xflags, PRINT_BUF_XFLAGS);
5471 db_printf("b_vflags=0x%b b_ioflags0x%b\n",
5472 (u_int)bp->b_vflags, PRINT_BUF_VFLAGS,
5473 (u_int)bp->b_ioflags, PRINT_BIO_FLAGS);
5474 db_printf(
5475 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
5476 "b_bufobj = (%p), b_data = %p\n, b_blkno = %jd, b_lblkno = %jd, "
5477 "b_vp = %p, b_dep = %p\n",
5478 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
5479 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
5480 (intmax_t)bp->b_lblkno, bp->b_vp, bp->b_dep.lh_first);
5481 db_printf("b_kvabase = %p, b_kvasize = %d\n",
5482 bp->b_kvabase, bp->b_kvasize);
5483 if (bp->b_npages) {
5484 int i;
5485 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
5486 for (i = 0; i < bp->b_npages; i++) {
5487 vm_page_t m;
5488 m = bp->b_pages[i];
5489 if (m != NULL)
5490 db_printf("(%p, 0x%lx, 0x%lx)", m->object,
5491 (u_long)m->pindex,
5492 (u_long)VM_PAGE_TO_PHYS(m));
5493 else
5494 db_printf("( ??? )");
5495 if ((i + 1) < bp->b_npages)
5496 db_printf(",");
5497 }
5498 db_printf("\n");
5499 }
5500 BUF_LOCKPRINTINFO(bp);
5501 #if defined(FULL_BUF_TRACKING)
5502 db_printf("b_io_tracking: b_io_tcnt = %u\n", bp->b_io_tcnt);
5503
5504 i = bp->b_io_tcnt % BUF_TRACKING_SIZE;
5505 for (j = 1; j <= BUF_TRACKING_SIZE; j++) {
5506 if (bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)] == NULL)
5507 continue;
5508 db_printf(" %2u: %s\n", j,
5509 bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)]);
5510 }
5511 #elif defined(BUF_TRACKING)
5512 db_printf("b_io_tracking: %s\n", bp->b_io_tracking);
5513 #endif
5514 db_printf(" ");
5515 }
5516
DB_SHOW_COMMAND_FLAGS(bufqueues,bufqueues,DB_CMD_MEMSAFE)5517 DB_SHOW_COMMAND_FLAGS(bufqueues, bufqueues, DB_CMD_MEMSAFE)
5518 {
5519 struct bufdomain *bd;
5520 struct buf *bp;
5521 long total;
5522 int i, j, cnt;
5523
5524 db_printf("bqempty: %d\n", bqempty.bq_len);
5525
5526 for (i = 0; i < buf_domains; i++) {
5527 bd = &bdomain[i];
5528 db_printf("Buf domain %d\n", i);
5529 db_printf("\tfreebufs\t%d\n", bd->bd_freebuffers);
5530 db_printf("\tlofreebufs\t%d\n", bd->bd_lofreebuffers);
5531 db_printf("\thifreebufs\t%d\n", bd->bd_hifreebuffers);
5532 db_printf("\n");
5533 db_printf("\tbufspace\t%ld\n", bd->bd_bufspace);
5534 db_printf("\tmaxbufspace\t%ld\n", bd->bd_maxbufspace);
5535 db_printf("\thibufspace\t%ld\n", bd->bd_hibufspace);
5536 db_printf("\tlobufspace\t%ld\n", bd->bd_lobufspace);
5537 db_printf("\tbufspacethresh\t%ld\n", bd->bd_bufspacethresh);
5538 db_printf("\n");
5539 db_printf("\tnumdirtybuffers\t%d\n", bd->bd_numdirtybuffers);
5540 db_printf("\tlodirtybuffers\t%d\n", bd->bd_lodirtybuffers);
5541 db_printf("\thidirtybuffers\t%d\n", bd->bd_hidirtybuffers);
5542 db_printf("\tdirtybufthresh\t%d\n", bd->bd_dirtybufthresh);
5543 db_printf("\n");
5544 total = 0;
5545 TAILQ_FOREACH(bp, &bd->bd_cleanq->bq_queue, b_freelist)
5546 total += bp->b_bufsize;
5547 db_printf("\tcleanq count\t%d (%ld)\n",
5548 bd->bd_cleanq->bq_len, total);
5549 total = 0;
5550 TAILQ_FOREACH(bp, &bd->bd_dirtyq.bq_queue, b_freelist)
5551 total += bp->b_bufsize;
5552 db_printf("\tdirtyq count\t%d (%ld)\n",
5553 bd->bd_dirtyq.bq_len, total);
5554 db_printf("\twakeup\t\t%d\n", bd->bd_wanted);
5555 db_printf("\tlim\t\t%d\n", bd->bd_lim);
5556 db_printf("\tCPU ");
5557 for (j = 0; j <= mp_maxid; j++)
5558 db_printf("%d, ", bd->bd_subq[j].bq_len);
5559 db_printf("\n");
5560 cnt = 0;
5561 total = 0;
5562 for (j = 0; j < nbuf; j++) {
5563 bp = nbufp(j);
5564 if (bp->b_domain == i && BUF_ISLOCKED(bp)) {
5565 cnt++;
5566 total += bp->b_bufsize;
5567 }
5568 }
5569 db_printf("\tLocked buffers: %d space %ld\n", cnt, total);
5570 cnt = 0;
5571 total = 0;
5572 for (j = 0; j < nbuf; j++) {
5573 bp = nbufp(j);
5574 if (bp->b_domain == i) {
5575 cnt++;
5576 total += bp->b_bufsize;
5577 }
5578 }
5579 db_printf("\tTotal buffers: %d space %ld\n", cnt, total);
5580 }
5581 }
5582
DB_SHOW_COMMAND_FLAGS(lockedbufs,lockedbufs,DB_CMD_MEMSAFE)5583 DB_SHOW_COMMAND_FLAGS(lockedbufs, lockedbufs, DB_CMD_MEMSAFE)
5584 {
5585 struct buf *bp;
5586 int i;
5587
5588 for (i = 0; i < nbuf; i++) {
5589 bp = nbufp(i);
5590 if (BUF_ISLOCKED(bp)) {
5591 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5592 db_printf("\n");
5593 if (db_pager_quit)
5594 break;
5595 }
5596 }
5597 }
5598
DB_SHOW_COMMAND(vnodebufs,db_show_vnodebufs)5599 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
5600 {
5601 struct vnode *vp;
5602 struct buf *bp;
5603
5604 if (!have_addr) {
5605 db_printf("usage: show vnodebufs <addr>\n");
5606 return;
5607 }
5608 vp = (struct vnode *)addr;
5609 db_printf("Clean buffers:\n");
5610 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
5611 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5612 db_printf("\n");
5613 }
5614 db_printf("Dirty buffers:\n");
5615 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
5616 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5617 db_printf("\n");
5618 }
5619 }
5620
DB_COMMAND_FLAGS(countfreebufs,db_coundfreebufs,DB_CMD_MEMSAFE)5621 DB_COMMAND_FLAGS(countfreebufs, db_coundfreebufs, DB_CMD_MEMSAFE)
5622 {
5623 struct buf *bp;
5624 int i, used = 0, nfree = 0;
5625
5626 if (have_addr) {
5627 db_printf("usage: countfreebufs\n");
5628 return;
5629 }
5630
5631 for (i = 0; i < nbuf; i++) {
5632 bp = nbufp(i);
5633 if (bp->b_qindex == QUEUE_EMPTY)
5634 nfree++;
5635 else
5636 used++;
5637 }
5638
5639 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
5640 nfree + used);
5641 db_printf("numfreebuffers is %d\n", numfreebuffers);
5642 }
5643 #endif /* DDB */
5644