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