kernel - B_IODEBUG -> B_IOISSUED
[dragonfly.git] / sys / kern / vfs_bio.c
CommitLineData
984263bc
MD
1/*
2 * Copyright (c) 1994,1997 John S. Dyson
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice immediately at the beginning of the file, without modification,
10 * this list of conditions, and the following disclaimer.
11 * 2. Absolutely no warranty of function or purpose is made by the author
12 * John S. Dyson.
13 *
14 * $FreeBSD: src/sys/kern/vfs_bio.c,v 1.242.2.20 2003/05/28 18:38:10 alc Exp $
15 */
16
17/*
18 * this file contains a new buffer I/O scheme implementing a coherent
19 * VM object and buffer cache scheme. Pains have been taken to make
20 * sure that the performance degradation associated with schemes such
21 * as this is not realized.
22 *
23 * Author: John S. Dyson
24 * Significant help during the development and debugging phases
25 * had been provided by David Greenman, also of the FreeBSD core team.
26 *
9bbca0fb
TK
27 * see man buf(9) for more info. Note that man buf(9) doesn't reflect
28 * the actual buf/bio implementation in DragonFly.
984263bc
MD
29 */
30
31#include <sys/param.h>
32#include <sys/systm.h>
33#include <sys/buf.h>
34#include <sys/conf.h>
3b48c3c1 35#include <sys/devicestat.h>
984263bc
MD
36#include <sys/eventhandler.h>
37#include <sys/lock.h>
38#include <sys/malloc.h>
39#include <sys/mount.h>
40#include <sys/kernel.h>
41#include <sys/kthread.h>
42#include <sys/proc.h>
43#include <sys/reboot.h>
44#include <sys/resourcevar.h>
45#include <sys/sysctl.h>
46#include <sys/vmmeter.h>
47#include <sys/vnode.h>
8c72e3d5 48#include <sys/dsched.h>
984263bc
MD
49#include <vm/vm.h>
50#include <vm/vm_param.h>
51#include <vm/vm_kern.h>
52#include <vm/vm_pageout.h>
53#include <vm/vm_page.h>
54#include <vm/vm_object.h>
55#include <vm/vm_extern.h>
56#include <vm/vm_map.h>
c504e38e
MD
57#include <vm/vm_pager.h>
58#include <vm/swap_pager.h>
654a39f0 59
3020e3be 60#include <sys/buf2.h>
654a39f0 61#include <sys/thread2.h>
f832287e 62#include <sys/spinlock2.h>
684a93c4 63#include <sys/mplock2.h>
12e4aaff 64#include <vm/vm_page2.h>
984263bc 65
135bd6a8
MD
66#include "opt_ddb.h"
67#ifdef DDB
68#include <ddb/ddb.h>
69#endif
70
b3098c79
HP
71/*
72 * Buffer queues.
73 */
b3098c79
HP
74enum bufq_type {
75 BQUEUE_NONE, /* not on any queue */
76 BQUEUE_LOCKED, /* locked buffers */
77 BQUEUE_CLEAN, /* non-B_DELWRI buffers */
78 BQUEUE_DIRTY, /* B_DELWRI buffers */
4b958e7b 79 BQUEUE_DIRTY_HW, /* B_DELWRI buffers - heavy weight */
b3098c79 80 BQUEUE_EMPTYKVA, /* empty buffer headers with KVA assignment */
4b958e7b
MD
81 BQUEUE_EMPTY, /* empty buffer headers */
82
83 BUFFER_QUEUES /* number of buffer queues */
b3098c79 84};
4b958e7b
MD
85
86typedef enum bufq_type bufq_type_t;
87
79eae878 88#define BD_WAKE_SIZE 16384
c4df9635
MD
89#define BD_WAKE_MASK (BD_WAKE_SIZE - 1)
90
e11efbb3
MD
91TAILQ_HEAD(bqueues, buf);
92
93struct bufpcpu {
94 struct spinlock spin;
95 struct bqueues bufqueues[BUFFER_QUEUES];
96} __cachealign;
97
98struct bufpcpu bufpcpu[MAXCPU];
b3098c79 99
984263bc
MD
100static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
101
984263bc 102struct buf *buf; /* buffer header pool */
984263bc 103
c8e4131d 104static void vfs_clean_pages(struct buf *bp);
cb1cf930 105static void vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m);
9bf025db 106#if 0
0a8aee15 107static void vfs_dirty_one_page(struct buf *bp, int pageno, vm_page_t m);
9bf025db 108#endif
984263bc 109static void vfs_vmio_release(struct buf *bp);
a447ba19 110static int flushbufqueues(struct buf *marker, bufq_type_t q);
a780f922
MD
111static vm_page_t bio_page_alloc(struct buf *bp, vm_object_t obj,
112 vm_pindex_t pg, int deficit);
984263bc 113
eafcc44d 114static void bd_signal(long totalspace);
4b958e7b
MD
115static void buf_daemon(void);
116static void buf_daemon_hw(void);
c4df9635 117
984263bc
MD
118/*
119 * bogus page -- for I/O to/from partially complete buffers
120 * this is a temporary solution to the problem, but it is not
121 * really that bad. it would be better to split the buffer
122 * for input in the case of buffers partially already in memory,
123 * but the code is intricate enough already.
124 */
125vm_page_t bogus_page;
a0c36a34 126
460426e6
MD
127/*
128 * These are all static, but make the ones we export globals so we do
129 * not need to use compiler magic.
130 */
3583bbb4
MD
131long bufspace; /* locked by buffer_map */
132long maxbufspace;
133static long bufmallocspace; /* atomic ops */
134long maxbufmallocspace, lobufspace, hibufspace;
74d62460 135static long bufreusecnt, bufdefragcnt, buffreekvacnt;
3583bbb4
MD
136static long lorunningspace;
137static long hirunningspace;
e11efbb3 138static long dirtykvaspace; /* atomic */
56a5e4ad 139long dirtybufspace; /* atomic (global for systat) */
e11efbb3
MD
140static long dirtybufcount; /* atomic */
141static long dirtybufspacehw; /* atomic */
142static long dirtybufcounthw; /* atomic */
143static long runningbufspace; /* atomic */
144static long runningbufcount; /* atomic */
3583bbb4
MD
145long lodirtybufspace;
146long hidirtybufspace;
984263bc
MD
147static int getnewbufcalls;
148static int getnewbufrestarts;
4ecf7cc9 149static int recoverbufcalls;
e11efbb3
MD
150static int needsbuffer; /* atomic */
151static int runningbufreq; /* atomic */
152static int bd_request; /* atomic */
153static int bd_request_hw; /* atomic */
c4df9635
MD
154static u_int bd_wake_ary[BD_WAKE_SIZE];
155static u_int bd_wake_index;
d300946f 156static u_int vm_cycle_point = 40; /* 23-36 will migrate more act->inact */
8ae5c7e0 157static int debug_commit;
2258af1d 158static int debug_bufbio;
f832287e 159
4ecf7cc9
MD
160static struct thread *bufdaemon_td;
161static struct thread *bufdaemonhw_td;
59a5a4e8
MD
162static u_int lowmempgallocs;
163static u_int lowmempgfails;
4ecf7cc9 164
3f779080
HP
165/*
166 * Sysctls for operational control of the buffer cache.
167 */
3583bbb4 168SYSCTL_LONG(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0,
3f779080 169 "Number of dirty buffers to flush before bufdaemon becomes inactive");
3583bbb4 170SYSCTL_LONG(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0,
bb606263 171 "High watermark used to trigger explicit flushing of dirty buffers");
3583bbb4 172SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
3f779080 173 "Minimum amount of buffer space required for active I/O");
3583bbb4 174SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
3f779080 175 "Maximum amount of buffer space to usable for active I/O");
59a5a4e8
MD
176SYSCTL_UINT(_vfs, OID_AUTO, lowmempgallocs, CTLFLAG_RW, &lowmempgallocs, 0,
177 "Page allocations done during periods of very low free memory");
178SYSCTL_UINT(_vfs, OID_AUTO, lowmempgfails, CTLFLAG_RW, &lowmempgfails, 0,
179 "Page allocations which failed during periods of very low free memory");
0e8bd897
MD
180SYSCTL_UINT(_vfs, OID_AUTO, vm_cycle_point, CTLFLAG_RW, &vm_cycle_point, 0,
181 "Recycle pages to active or inactive queue transition pt 0-64");
3f779080
HP
182/*
183 * Sysctls determining current state of the buffer cache.
184 */
74d62460 185SYSCTL_LONG(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
17cde63e 186 "Total number of buffers in buffer cache");
eafcc44d
MD
187SYSCTL_LONG(_vfs, OID_AUTO, dirtykvaspace, CTLFLAG_RD, &dirtykvaspace, 0,
188 "KVA reserved by dirty buffers (all)");
3583bbb4 189SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0,
70ac7d6c 190 "Pending bytes of dirty buffers (all)");
3583bbb4 191SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0,
70ac7d6c 192 "Pending bytes of dirty buffers (heavy weight)");
74d62460 193SYSCTL_LONG(_vfs, OID_AUTO, dirtybufcount, CTLFLAG_RD, &dirtybufcount, 0,
70ac7d6c 194 "Pending number of dirty buffers");
74d62460 195SYSCTL_LONG(_vfs, OID_AUTO, dirtybufcounthw, CTLFLAG_RD, &dirtybufcounthw, 0,
4b958e7b 196 "Pending number of dirty buffers (heavy weight)");
3583bbb4 197SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
bb606263 198 "I/O bytes currently in progress due to asynchronous writes");
74d62460 199SYSCTL_LONG(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
1b30fbcc 200 "I/O buffers currently in progress due to asynchronous writes");
3583bbb4 201SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
3f779080 202 "Hard limit on maximum amount of memory usable for buffer space");
3583bbb4 203SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
3f779080 204 "Soft limit on maximum amount of memory usable for buffer space");
3583bbb4 205SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
3f779080 206 "Minimum amount of memory to reserve for system buffer space");
3583bbb4 207SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
3f779080 208 "Amount of memory available for buffers");
3583bbb4 209SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
bb606263 210 0, "Maximum amount of memory reserved for buffers using malloc");
3583bbb4 211SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
3f779080
HP
212 "Amount of memory left for buffers using malloc-scheme");
213SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
214 "New buffer header acquisition requests");
215SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
216 0, "New buffer header acquisition restarts");
4ecf7cc9
MD
217SYSCTL_INT(_vfs, OID_AUTO, recoverbufcalls, CTLFLAG_RD, &recoverbufcalls, 0,
218 "Recover VM space in an emergency");
3f779080 219SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
bb606263 220 "Buffer acquisition restarts due to fragmented buffer map");
3f779080
HP
221SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
222 "Amount of time KVA space was deallocated in an arbitrary buffer");
223SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
224 "Amount of time buffer re-use operations were successful");
8ae5c7e0 225SYSCTL_INT(_vfs, OID_AUTO, debug_commit, CTLFLAG_RW, &debug_commit, 0, "");
2258af1d 226SYSCTL_INT(_vfs, OID_AUTO, debug_bufbio, CTLFLAG_RW, &debug_bufbio, 0, "");
306ab3cb
HP
227SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
228 "sizeof(struct buf)");
984263bc 229
984263bc
MD
230char *buf_wmesg = BUF_WMESG;
231
984263bc 232#define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
c4df9635 233#define VFS_BIO_NEED_UNUSED02 0x02
868d24af 234#define VFS_BIO_NEED_UNUSED04 0x04
984263bc
MD
235#define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
236
984263bc 237/*
3f779080 238 * bufspacewakeup:
984263bc
MD
239 *
240 * Called when buffer space is potentially available for recovery.
241 * getnewbuf() will block on this flag when it is unable to free
242 * sufficient buffer space. Buffer space becomes recoverable when
243 * bp's get placed back in the queues.
244 */
984263bc
MD
245static __inline void
246bufspacewakeup(void)
247{
248 /*
249 * If someone is waiting for BUF space, wake them up. Even
250 * though we haven't freed the kva space yet, the waiting
251 * process will be able to now.
252 */
e11efbb3
MD
253 for (;;) {
254 int flags = needsbuffer;
255 cpu_ccfence();
256 if ((flags & VFS_BIO_NEED_BUFSPACE) == 0)
257 break;
258 if (atomic_cmpset_int(&needsbuffer, flags,
259 flags & ~VFS_BIO_NEED_BUFSPACE)) {
260 wakeup(&needsbuffer);
261 break;
262 }
263 /* retry */
984263bc
MD
264 }
265}
266
267/*
3f779080
HP
268 * runningbufwakeup:
269 *
270 * Accounting for I/O in progress.
984263bc
MD
271 *
272 */
273static __inline void
274runningbufwakeup(struct buf *bp)
275{
3583bbb4 276 long totalspace;
e11efbb3 277 long flags;
868d24af
MD
278
279 if ((totalspace = bp->b_runningbufspace) != 0) {
e11efbb3
MD
280 atomic_add_long(&runningbufspace, -totalspace);
281 atomic_add_long(&runningbufcount, -1);
984263bc 282 bp->b_runningbufspace = 0;
4afeea0d
MD
283
284 /*
285 * see waitrunningbufspace() for limit test.
286 */
e11efbb3
MD
287 for (;;) {
288 flags = runningbufreq;
289 cpu_ccfence();
290 if (flags == 0)
291 break;
292 if (atomic_cmpset_int(&runningbufreq, flags, 0)) {
293 wakeup(&runningbufreq);
294 break;
295 }
296 /* retry */
984263bc 297 }
868d24af 298 bd_signal(totalspace);
984263bc
MD
299 }
300}
301
302/*
3f779080 303 * bufcountwakeup:
984263bc
MD
304 *
305 * Called when a buffer has been added to one of the free queues to
306 * account for the buffer and to wakeup anyone waiting for free buffers.
307 * This typically occurs when large amounts of metadata are being handled
308 * by the buffer cache ( else buffer space runs out first, usually ).
309 */
984263bc
MD
310static __inline void
311bufcountwakeup(void)
312{
e11efbb3
MD
313 long flags;
314
315 for (;;) {
316 flags = needsbuffer;
317 if (flags == 0)
318 break;
319 if (atomic_cmpset_int(&needsbuffer, flags,
320 (flags & ~VFS_BIO_NEED_ANY))) {
321 wakeup(&needsbuffer);
322 break;
323 }
324 /* retry */
984263bc
MD
325 }
326}
327
328/*
3f779080 329 * waitrunningbufspace()
984263bc 330 *
3038a8ca
MD
331 * If runningbufspace exceeds 4/6 hirunningspace we block until
332 * runningbufspace drops to 3/6 hirunningspace. We also block if another
333 * thread blocked here in order to be fair, even if runningbufspace
334 * is now lower than the limit.
984263bc 335 *
cd083340 336 * The caller may be using this function to block in a tight loop, we
3038a8ca
MD
337 * must block while runningbufspace is greater than at least
338 * hirunningspace * 3 / 6.
984263bc 339 */
aa1bfd98 340void
4afeea0d 341waitrunningbufspace(void)
984263bc 342{
3583bbb4 343 long limit = hirunningspace * 4 / 6;
e11efbb3 344 long flags;
cd083340 345
e11efbb3
MD
346 while (runningbufspace > limit || runningbufreq) {
347 tsleep_interlock(&runningbufreq, 0);
2b2dd6e6 348 flags = atomic_fetchadd_int(&runningbufreq, 1);
e11efbb3 349 if (runningbufspace > limit || flags)
2b2dd6e6 350 tsleep(&runningbufreq, PINTERLOCKED, "wdrn1", hz);
984263bc
MD
351 }
352}
353
ae8e83e6
MD
354/*
355 * buf_dirty_count_severe:
356 *
357 * Return true if we have too many dirty buffers.
358 */
359int
360buf_dirty_count_severe(void)
361{
eafcc44d 362 return (runningbufspace + dirtykvaspace >= hidirtybufspace ||
ae8e83e6
MD
363 dirtybufcount >= nbuf / 2);
364}
365
4afeea0d
MD
366/*
367 * Return true if the amount of running I/O is severe and BIOQ should
368 * start bursting.
369 */
370int
371buf_runningbufspace_severe(void)
372{
77912481 373 return (runningbufspace >= hirunningspace * 4 / 6);
4afeea0d
MD
374}
375
984263bc 376/*
3f779080 377 * vfs_buf_test_cache:
984263bc 378 *
cb1cf930
MD
379 * Called when a buffer is extended. This function clears the B_CACHE
380 * bit if the newly extended portion of the buffer does not contain
381 * valid data.
382 *
383 * NOTE! Dirty VM pages are not processed into dirty (B_DELWRI) buffer
384 * cache buffers. The VM pages remain dirty, as someone had mmap()'d
385 * them while a clean buffer was present.
984263bc
MD
386 */
387static __inline__
388void
389vfs_buf_test_cache(struct buf *bp,
390 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
391 vm_page_t m)
392{
393 if (bp->b_flags & B_CACHE) {
394 int base = (foff + off) & PAGE_MASK;
395 if (vm_page_is_valid(m, base, size) == 0)
396 bp->b_flags &= ~B_CACHE;
397 }
398}
399
3f779080 400/*
cd083340 401 * bd_speedup()
4b958e7b 402 *
cd083340
MD
403 * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the
404 * low water mark.
3f779080 405 */
984263bc
MD
406static __inline__
407void
c4df9635 408bd_speedup(void)
984263bc 409{
eafcc44d 410 if (dirtykvaspace < lodirtybufspace && dirtybufcount < nbuf / 2)
cd083340
MD
411 return;
412
413 if (bd_request == 0 &&
eafcc44d 414 (dirtykvaspace > lodirtybufspace / 2 ||
70ac7d6c 415 dirtybufcount - dirtybufcounthw >= nbuf / 2)) {
e11efbb3
MD
416 if (atomic_fetchadd_int(&bd_request, 1) == 0)
417 wakeup(&bd_request);
984263bc 418 }
cd083340 419 if (bd_request_hw == 0 &&
eafcc44d 420 (dirtykvaspace > lodirtybufspace / 2 ||
70ac7d6c 421 dirtybufcounthw >= nbuf / 2)) {
e11efbb3
MD
422 if (atomic_fetchadd_int(&bd_request_hw, 1) == 0)
423 wakeup(&bd_request_hw);
4b958e7b 424 }
984263bc
MD
425}
426
427/*
c4df9635 428 * bd_heatup()
3f779080 429 *
c4df9635
MD
430 * Get the buf_daemon heated up when the number of running and dirty
431 * buffers exceeds the mid-point.
b1c20cfa 432 *
79eae878
MD
433 * Return the total number of dirty bytes past the second mid point
434 * as a measure of how much excess dirty data there is in the system.
984263bc 435 */
eafcc44d 436long
c4df9635
MD
437bd_heatup(void)
438{
3583bbb4
MD
439 long mid1;
440 long mid2;
441 long totalspace;
984263bc 442
868d24af 443 mid1 = lodirtybufspace + (hidirtybufspace - lodirtybufspace) / 2;
c4df9635 444
eafcc44d 445 totalspace = runningbufspace + dirtykvaspace;
70ac7d6c 446 if (totalspace >= mid1 || dirtybufcount >= nbuf / 2) {
c4df9635 447 bd_speedup();
868d24af
MD
448 mid2 = mid1 + (hidirtybufspace - mid1) / 2;
449 if (totalspace >= mid2)
450 return(totalspace - mid2);
c4df9635
MD
451 }
452 return(0);
453}
454
455/*
456 * bd_wait()
457 *
868d24af
MD
458 * Wait for the buffer cache to flush (totalspace) bytes worth of
459 * buffers, then return.
c4df9635
MD
460 *
461 * Regardless this function blocks while the number of dirty buffers
868d24af 462 * exceeds hidirtybufspace.
c4df9635 463 */
984263bc 464void
eafcc44d 465bd_wait(long totalspace)
984263bc 466{
c4df9635 467 u_int i;
e11efbb3
MD
468 u_int j;
469 u_int mi;
868d24af 470 int count;
c4df9635 471
4ecf7cc9
MD
472 if (curthread == bufdaemonhw_td || curthread == bufdaemon_td)
473 return;
474
868d24af 475 while (totalspace > 0) {
c4df9635 476 bd_heatup();
e11efbb3
MD
477
478 /*
479 * Order is important. Suppliers adjust bd_wake_index after
480 * updating runningbufspace/dirtykvaspace. We want to fetch
481 * bd_wake_index before accessing. Any error should thus
482 * be in our favor.
483 */
484 i = atomic_fetchadd_int(&bd_wake_index, 0);
eafcc44d
MD
485 if (totalspace > runningbufspace + dirtykvaspace)
486 totalspace = runningbufspace + dirtykvaspace;
868d24af 487 count = totalspace / BKVASIZE;
e11efbb3
MD
488 if (count >= BD_WAKE_SIZE / 2)
489 count = BD_WAKE_SIZE / 2;
490 i = i + count;
491 mi = i & BD_WAKE_MASK;
77912481
MD
492
493 /*
494 * This is not a strict interlock, so we play a bit loose
e11efbb3
MD
495 * with locking access to dirtybufspace*. We have to re-check
496 * bd_wake_index to ensure that it hasn't passed us.
77912481 497 */
e11efbb3
MD
498 tsleep_interlock(&bd_wake_ary[mi], 0);
499 atomic_add_int(&bd_wake_ary[mi], 1);
500 j = atomic_fetchadd_int(&bd_wake_index, 0);
501 if ((int)(i - j) >= 0)
502 tsleep(&bd_wake_ary[mi], PINTERLOCKED, "flstik", hz);
c4df9635 503
eafcc44d 504 totalspace = runningbufspace + dirtykvaspace - hidirtybufspace;
c4df9635
MD
505 }
506}
507
508/*
509 * bd_signal()
510 *
eafcc44d 511 * This function is called whenever runningbufspace or dirtykvaspace
868d24af 512 * is reduced. Track threads waiting for run+dirty buffer I/O
c4df9635
MD
513 * complete.
514 */
515static void
eafcc44d 516bd_signal(long totalspace)
c4df9635
MD
517{
518 u_int i;
519
b1c20cfa
MD
520 if (totalspace > 0) {
521 if (totalspace > BKVASIZE * BD_WAKE_SIZE)
522 totalspace = BKVASIZE * BD_WAKE_SIZE;
b1c20cfa 523 while (totalspace > 0) {
e11efbb3 524 i = atomic_fetchadd_int(&bd_wake_index, 1);
b1c20cfa 525 i &= BD_WAKE_MASK;
e11efbb3 526 if (atomic_readandclear_int(&bd_wake_ary[i]))
b1c20cfa 527 wakeup(&bd_wake_ary[i]);
b1c20cfa 528 totalspace -= BKVASIZE;
868d24af 529 }
c4df9635 530 }
984263bc
MD
531}
532
a9a20f98
MD
533/*
534 * BIO tracking support routines.
535 *
536 * Release a ref on a bio_track. Wakeup requests are atomically released
537 * along with the last reference so bk_active will never wind up set to
538 * only 0x80000000.
a9a20f98
MD
539 */
540static
541void
542bio_track_rel(struct bio_track *track)
543{
544 int active;
545 int desired;
546
547 /*
548 * Shortcut
549 */
550 active = track->bk_active;
551 if (active == 1 && atomic_cmpset_int(&track->bk_active, 1, 0))
552 return;
553
554 /*
555 * Full-on. Note that the wait flag is only atomically released on
556 * the 1->0 count transition.
e7edae1e
MD
557 *
558 * We check for a negative count transition using bit 30 since bit 31
559 * has a different meaning.
a9a20f98
MD
560 */
561 for (;;) {
562 desired = (active & 0x7FFFFFFF) - 1;
563 if (desired)
564 desired |= active & 0x80000000;
565 if (atomic_cmpset_int(&track->bk_active, active, desired)) {
e7edae1e 566 if (desired & 0x40000000)
ed20d0e3 567 panic("bio_track_rel: bad count: %p", track);
a9a20f98
MD
568 if (active & 0x80000000)
569 wakeup(track);
570 break;
571 }
572 active = track->bk_active;
573 }
574}
575
576/*
577 * Wait for the tracking count to reach 0.
578 *
579 * Use atomic ops such that the wait flag is only set atomically when
580 * bk_active is non-zero.
a9a20f98
MD
581 */
582int
583bio_track_wait(struct bio_track *track, int slp_flags, int slp_timo)
584{
585 int active;
586 int desired;
587 int error;
588
589 /*
590 * Shortcut
591 */
592 if (track->bk_active == 0)
593 return(0);
594
595 /*
596 * Full-on. Note that the wait flag may only be atomically set if
597 * the active count is non-zero.
bbdc6499
MD
598 *
599 * NOTE: We cannot optimize active == desired since a wakeup could
600 * clear active prior to our tsleep_interlock().
a9a20f98 601 */
a9a20f98
MD
602 error = 0;
603 while ((active = track->bk_active) != 0) {
8bbb2fba 604 cpu_ccfence();
a9a20f98 605 desired = active | 0x80000000;
ae8e83e6 606 tsleep_interlock(track, slp_flags);
bbdc6499 607 if (atomic_cmpset_int(&track->bk_active, active, desired)) {
d9345d3a 608 error = tsleep(track, slp_flags | PINTERLOCKED,
bbdc6499 609 "trwait", slp_timo);
a9a20f98
MD
610 if (error)
611 break;
612 }
613 }
a9a20f98
MD
614 return (error);
615}
616
3f779080
HP
617/*
618 * bufinit:
619 *
620 * Load time initialisation of the buffer cache, called from machine
621 * dependant initialization code.
622 */
ca667d3c 623static
984263bc 624void
ca667d3c 625bufinit(void *dummy __unused)
984263bc 626{
e11efbb3 627 struct bufpcpu *pcpu;
984263bc 628 struct buf *bp;
b8bb0773 629 vm_offset_t bogus_offset;
e11efbb3
MD
630 int i;
631 int j;
632 long n;
984263bc 633
984263bc 634 /* next, make a null set of free lists */
e11efbb3
MD
635 for (i = 0; i < ncpus; ++i) {
636 pcpu = &bufpcpu[i];
ba87a4ab 637 spin_init(&pcpu->spin, "bufinit");
e11efbb3
MD
638 for (j = 0; j < BUFFER_QUEUES; j++)
639 TAILQ_INIT(&pcpu->bufqueues[j]);
640 }
984263bc
MD
641
642 /* finally, initialize each buffer header and stick on empty q */
e11efbb3
MD
643 i = 0;
644 pcpu = &bufpcpu[i];
645
646 for (n = 0; n < nbuf; n++) {
647 bp = &buf[n];
984263bc
MD
648 bzero(bp, sizeof *bp);
649 bp->b_flags = B_INVAL; /* we're just an empty header */
10f3fee5 650 bp->b_cmd = BUF_CMD_DONE;
b3098c79 651 bp->b_qindex = BQUEUE_EMPTY;
e11efbb3 652 bp->b_qcpu = i;
81b5c339 653 initbufbio(bp);
54f51aeb 654 xio_init(&bp->b_xio);
408357d8 655 buf_dep_init(bp);
e11efbb3
MD
656 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
657 bp, b_freelist);
658
659 i = (i + 1) % ncpus;
660 pcpu = &bufpcpu[i];
984263bc
MD
661 }
662
663 /*
664 * maxbufspace is the absolute maximum amount of buffer space we are
665 * allowed to reserve in KVM and in real terms. The absolute maximum
666 * is nominally used by buf_daemon. hibufspace is the nominal maximum
667 * used by most other processes. The differential is required to
668 * ensure that buf_daemon is able to run when other processes might
669 * be blocked waiting for buffer space.
670 *
671 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
672 * this may result in KVM fragmentation which is not handled optimally
673 * by the system.
674 */
74d62460
MD
675 maxbufspace = nbuf * BKVASIZE;
676 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
984263bc
MD
677 lobufspace = hibufspace - MAXBSIZE;
678
679 lorunningspace = 512 * 1024;
4afeea0d 680 /* hirunningspace -- see below */
984263bc 681
868d24af
MD
682 /*
683 * Limit the amount of malloc memory since it is wired permanently
684 * into the kernel space. Even though this is accounted for in
685 * the buffer allocation, we don't want the malloced region to grow
686 * uncontrolled. The malloc scheme improves memory utilization
687 * significantly on average (small) directories.
688 */
984263bc
MD
689 maxbufmallocspace = hibufspace / 20;
690
868d24af
MD
691 /*
692 * Reduce the chance of a deadlock occuring by limiting the number
693 * of delayed-write dirty buffers we allow to stack up.
4afeea0d
MD
694 *
695 * We don't want too much actually queued to the device at once
696 * (XXX this needs to be per-mount!), because the buffers will
697 * wind up locked for a very long period of time while the I/O
698 * drains.
868d24af 699 */
4afeea0d
MD
700 hidirtybufspace = hibufspace / 2; /* dirty + running */
701 hirunningspace = hibufspace / 16; /* locked & queued to device */
702 if (hirunningspace < 1024 * 1024)
703 hirunningspace = 1024 * 1024;
704
eafcc44d 705 dirtykvaspace = 0;
868d24af
MD
706 dirtybufspace = 0;
707 dirtybufspacehw = 0;
984263bc 708
868d24af 709 lodirtybufspace = hidirtybufspace / 2;
984263bc 710
868d24af
MD
711 /*
712 * Maximum number of async ops initiated per buf_daemon loop. This is
713 * somewhat of a hack at the moment, we really need to limit ourselves
714 * based on the number of bytes of I/O in-transit that were initiated
715 * from buf_daemon.
716 */
984263bc 717
e4846942 718 bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
b12defdc 719 vm_object_hold(&kernel_object);
c439ad8f 720 bogus_page = vm_page_alloc(&kernel_object,
e4846942
MD
721 (bogus_offset >> PAGE_SHIFT),
722 VM_ALLOC_NORMAL);
b12defdc 723 vm_object_drop(&kernel_object);
12e4aaff 724 vmstats.v_wire_count++;
984263bc
MD
725
726}
727
ca667d3c
MD
728SYSINIT(do_bufinit, SI_BOOT2_MACHDEP, SI_ORDER_FIRST, bufinit, NULL);
729
81b5c339 730/*
b5d7061d
MD
731 * Initialize the embedded bio structures, typically used by
732 * deprecated code which tries to allocate its own struct bufs.
81b5c339
MD
733 */
734void
735initbufbio(struct buf *bp)
736{
737 bp->b_bio1.bio_buf = bp;
738 bp->b_bio1.bio_prev = NULL;
81b5c339
MD
739 bp->b_bio1.bio_offset = NOOFFSET;
740 bp->b_bio1.bio_next = &bp->b_bio2;
741 bp->b_bio1.bio_done = NULL;
ae8e83e6 742 bp->b_bio1.bio_flags = 0;
81b5c339
MD
743
744 bp->b_bio2.bio_buf = bp;
745 bp->b_bio2.bio_prev = &bp->b_bio1;
81b5c339
MD
746 bp->b_bio2.bio_offset = NOOFFSET;
747 bp->b_bio2.bio_next = NULL;
748 bp->b_bio2.bio_done = NULL;
ae8e83e6 749 bp->b_bio2.bio_flags = 0;
b5d7061d
MD
750
751 BUF_LOCKINIT(bp);
81b5c339
MD
752}
753
754/*
755 * Reinitialize the embedded bio structures as well as any additional
756 * translation cache layers.
757 */
758void
759reinitbufbio(struct buf *bp)
760{
761 struct bio *bio;
762
763 for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
764 bio->bio_done = NULL;
81b5c339
MD
765 bio->bio_offset = NOOFFSET;
766 }
767}
768
b5d7061d
MD
769/*
770 * Undo the effects of an initbufbio().
771 */
772void
773uninitbufbio(struct buf *bp)
774{
3573cf7b 775 dsched_buf_exit(bp);
b5d7061d
MD
776 BUF_LOCKFREE(bp);
777}
778
81b5c339
MD
779/*
780 * Push another BIO layer onto an existing BIO and return it. The new
781 * BIO layer may already exist, holding cached translation data.
782 */
783struct bio *
784push_bio(struct bio *bio)
785{
786 struct bio *nbio;
787
788 if ((nbio = bio->bio_next) == NULL) {
789 int index = bio - &bio->bio_buf->b_bio_array[0];
bbd44c71 790 if (index >= NBUF_BIO - 1) {
4885d2d6
TK
791 panic("push_bio: too many layers %d for bp %p",
792 index, bio->bio_buf);
81b5c339
MD
793 }
794 nbio = &bio->bio_buf->b_bio_array[index + 1];
795 bio->bio_next = nbio;
796 nbio->bio_prev = bio;
797 nbio->bio_buf = bio->bio_buf;
81b5c339
MD
798 nbio->bio_offset = NOOFFSET;
799 nbio->bio_done = NULL;
800 nbio->bio_next = NULL;
801 }
802 KKASSERT(nbio->bio_done == NULL);
803 return(nbio);
804}
805
b77cfc40
MD
806/*
807 * Pop a BIO translation layer, returning the previous layer. The
808 * must have been previously pushed.
809 */
810struct bio *
81b5c339
MD
811pop_bio(struct bio *bio)
812{
b77cfc40 813 return(bio->bio_prev);
81b5c339
MD
814}
815
816void
817clearbiocache(struct bio *bio)
818{
819 while (bio) {
81b5c339
MD
820 bio->bio_offset = NOOFFSET;
821 bio = bio->bio_next;
822 }
823}
824
984263bc 825/*
3f779080
HP
826 * bfreekva:
827 *
828 * Free the KVA allocation for buffer 'bp'.
984263bc 829 *
e43a034f 830 * Must be called from a critical section as this is the only locking for
984263bc
MD
831 * buffer_map.
832 *
833 * Since this call frees up buffer space, we call bufspacewakeup().
834 */
835static void
312dcd01 836bfreekva(struct buf *bp)
984263bc 837{
a108bf71
MD
838 int count;
839
984263bc
MD
840 if (bp->b_kvasize) {
841 ++buffreekvacnt;
a108bf71 842 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
e4846942 843 vm_map_lock(&buffer_map);
984263bc 844 bufspace -= bp->b_kvasize;
e4846942 845 vm_map_delete(&buffer_map,
984263bc 846 (vm_offset_t) bp->b_kvabase,
a108bf71
MD
847 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
848 &count
984263bc 849 );
e4846942 850 vm_map_unlock(&buffer_map);
a108bf71 851 vm_map_entry_release(count);
984263bc 852 bp->b_kvasize = 0;
9a82e536 853 bp->b_kvabase = NULL;
984263bc
MD
854 bufspacewakeup();
855 }
856}
857
858/*
e11efbb3
MD
859 * Remove the buffer from the appropriate free list.
860 * (caller must be locked)
984263bc 861 */
c3d1e862
MD
862static __inline void
863_bremfree(struct buf *bp)
984263bc 864{
e11efbb3
MD
865 struct bufpcpu *pcpu = &bufpcpu[bp->b_qcpu];
866
b3098c79 867 if (bp->b_qindex != BQUEUE_NONE) {
77bb9400 868 KASSERT(BUF_REFCNTNB(bp) == 1,
e11efbb3
MD
869 ("bremfree: bp %p not locked",bp));
870 TAILQ_REMOVE(&pcpu->bufqueues[bp->b_qindex], bp, b_freelist);
b3098c79 871 bp->b_qindex = BQUEUE_NONE;
984263bc 872 } else {
77bb9400 873 if (BUF_REFCNTNB(bp) <= 1)
984263bc
MD
874 panic("bremfree: removing a buffer not on a queue");
875 }
c3d1e862 876}
984263bc 877
e11efbb3
MD
878/*
879 * bremfree() - must be called with a locked buffer
880 */
c3d1e862
MD
881void
882bremfree(struct buf *bp)
883{
e11efbb3
MD
884 struct bufpcpu *pcpu = &bufpcpu[bp->b_qcpu];
885
886 spin_lock(&pcpu->spin);
c3d1e862 887 _bremfree(bp);
e11efbb3 888 spin_unlock(&pcpu->spin);
984263bc
MD
889}
890
e11efbb3
MD
891/*
892 * bremfree_locked - must be called with pcpu->spin locked
893 */
b1c20cfa 894static void
c3d1e862
MD
895bremfree_locked(struct buf *bp)
896{
897 _bremfree(bp);
898}
984263bc 899
c1c3e862
MD
900/*
901 * This version of bread issues any required I/O asyncnronously and
902 * makes a callback on completion.
903 *
904 * The callback must check whether BIO_DONE is set in the bio and issue
905 * the bpdone(bp, 0) if it isn't. The callback is responsible for clearing
906 * BIO_DONE and disposing of the I/O (bqrelse()ing it).
907 */
908void
909breadcb(struct vnode *vp, off_t loffset, int size,
910 void (*func)(struct bio *), void *arg)
911{
912 struct buf *bp;
913
914 bp = getblk(vp, loffset, size, 0, 0);
915
916 /* if not found in cache, do some I/O */
917 if ((bp->b_flags & B_CACHE) == 0) {
918 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
919 bp->b_cmd = BUF_CMD_READ;
920 bp->b_bio1.bio_done = func;
921 bp->b_bio1.bio_caller_info1.ptr = arg;
922 vfs_busy_pages(vp, bp);
923 BUF_KERNPROC(bp);
924 vn_strategy(vp, &bp->b_bio1);
925 } else if (func) {
386355f1
MD
926 /*
927 * Since we are issuing the callback synchronously it cannot
928 * race the BIO_DONE, so no need for atomic ops here.
929 */
c1c3e862
MD
930 /*bp->b_bio1.bio_done = func;*/
931 bp->b_bio1.bio_caller_info1.ptr = arg;
932 bp->b_bio1.bio_flags |= BIO_DONE;
933 func(&bp->b_bio1);
934 } else {
935 bqrelse(bp);
936 }
937}
938
984263bc 939/*
54341a3b 940 * breadnx() - Terminal function for bread() and breadn().
3f779080 941 *
54341a3b
MD
942 * This function will start asynchronous I/O on read-ahead blocks as well
943 * as satisfy the primary request.
b1c20cfa 944 *
54341a3b
MD
945 * We must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE is
946 * set, the buffer is valid and we do not have to do anything.
984263bc
MD
947 */
948int
54341a3b 949breadnx(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
c8e4131d 950 int *rabsize, int cnt, struct buf **bpp)
984263bc
MD
951{
952 struct buf *bp, *rabp;
953 int i;
954 int rv = 0, readwait = 0;
955
54341a3b
MD
956 if (*bpp)
957 bp = *bpp;
958 else
959 *bpp = bp = getblk(vp, loffset, size, 0, 0);
984263bc
MD
960
961 /* if not found in cache, do some I/O */
962 if ((bp->b_flags & B_CACHE) == 0) {
ae8e83e6 963 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
10f3fee5 964 bp->b_cmd = BUF_CMD_READ;
ae8e83e6
MD
965 bp->b_bio1.bio_done = biodone_sync;
966 bp->b_bio1.bio_flags |= BIO_SYNC;
10f3fee5 967 vfs_busy_pages(vp, bp);
81b5c339 968 vn_strategy(vp, &bp->b_bio1);
984263bc
MD
969 ++readwait;
970 }
971
54078292
MD
972 for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
973 if (inmem(vp, *raoffset))
984263bc 974 continue;
54078292 975 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
984263bc
MD
976
977 if ((rabp->b_flags & B_CACHE) == 0) {
ae8e83e6 978 rabp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
10f3fee5
MD
979 rabp->b_cmd = BUF_CMD_READ;
980 vfs_busy_pages(vp, rabp);
984263bc 981 BUF_KERNPROC(rabp);
81b5c339 982 vn_strategy(vp, &rabp->b_bio1);
984263bc
MD
983 } else {
984 brelse(rabp);
985 }
986 }
b1c20cfa 987 if (readwait)
ae8e83e6 988 rv = biowait(&bp->b_bio1, "biord");
984263bc
MD
989 return (rv);
990}
991
992/*
3f779080
HP
993 * bwrite:
994 *
ae8e83e6
MD
995 * Synchronous write, waits for completion.
996 *
3f779080
HP
997 * Write, release buffer on completion. (Done by iodone
998 * if async). Do not bother writing anything if the buffer
999 * is invalid.
1000 *
1001 * Note that we set B_CACHE here, indicating that buffer is
1002 * fully valid and thus cacheable. This is true even of NFS
1003 * now so we set it generally. This could be set either here
1004 * or in biodone() since the I/O is synchronous. We put it
1005 * here.
984263bc
MD
1006 */
1007int
c8e4131d 1008bwrite(struct buf *bp)
984263bc 1009{
ae8e83e6 1010 int error;
984263bc
MD
1011
1012 if (bp->b_flags & B_INVAL) {
1013 brelse(bp);
1014 return (0);
1015 }
77bb9400 1016 if (BUF_REFCNTNB(bp) == 0)
984263bc 1017 panic("bwrite: buffer is not busy???");
984263bc 1018
ffd3e597
MD
1019 /*
1020 * NOTE: We no longer mark the buffer clear prior to the vn_strategy()
1021 * call because it will remove the buffer from the vnode's
1022 * dirty buffer list prematurely and possibly cause filesystem
1023 * checks to race buffer flushes. This is now handled in
1024 * bpdone().
1025 *
1026 * bundirty(bp); REMOVED
1027 */
984263bc 1028
ae8e83e6 1029 bp->b_flags &= ~(B_ERROR | B_EINTR);
6bae6177 1030 bp->b_flags |= B_CACHE;
10f3fee5 1031 bp->b_cmd = BUF_CMD_WRITE;
ae8e83e6
MD
1032 bp->b_bio1.bio_done = biodone_sync;
1033 bp->b_bio1.bio_flags |= BIO_SYNC;
10f3fee5 1034 vfs_busy_pages(bp->b_vp, bp);
984263bc
MD
1035
1036 /*
9a71d53f
MD
1037 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
1038 * valid for vnode-backed buffers.
984263bc 1039 */
77912481 1040 bsetrunningbufspace(bp, bp->b_bufsize);
81b5c339 1041 vn_strategy(bp->b_vp, &bp->b_bio1);
ae8e83e6
MD
1042 error = biowait(&bp->b_bio1, "biows");
1043 brelse(bp);
77912481 1044
ae8e83e6
MD
1045 return (error);
1046}
984263bc 1047
ae8e83e6
MD
1048/*
1049 * bawrite:
1050 *
1051 * Asynchronous write. Start output on a buffer, but do not wait for
1052 * it to complete. The buffer is released when the output completes.
1053 *
1054 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1055 * B_INVAL buffers. Not us.
1056 */
1057void
1058bawrite(struct buf *bp)
1059{
1060 if (bp->b_flags & B_INVAL) {
984263bc 1061 brelse(bp);
ae8e83e6
MD
1062 return;
1063 }
1064 if (BUF_REFCNTNB(bp) == 0)
f58c1c33 1065 panic("bawrite: buffer is not busy???");
ae8e83e6 1066
ffd3e597
MD
1067 /*
1068 * NOTE: We no longer mark the buffer clear prior to the vn_strategy()
1069 * call because it will remove the buffer from the vnode's
1070 * dirty buffer list prematurely and possibly cause filesystem
1071 * checks to race buffer flushes. This is now handled in
1072 * bpdone().
1073 *
1074 * bundirty(bp); REMOVED
1075 */
ae8e83e6
MD
1076 bp->b_flags &= ~(B_ERROR | B_EINTR);
1077 bp->b_flags |= B_CACHE;
1078 bp->b_cmd = BUF_CMD_WRITE;
1079 KKASSERT(bp->b_bio1.bio_done == NULL);
1080 vfs_busy_pages(bp->b_vp, bp);
1081
1082 /*
1083 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
1084 * valid for vnode-backed buffers.
1085 */
77912481 1086 bsetrunningbufspace(bp, bp->b_bufsize);
ae8e83e6
MD
1087 BUF_KERNPROC(bp);
1088 vn_strategy(bp->b_vp, &bp->b_bio1);
1089}
1090
1091/*
1092 * bowrite:
1093 *
1094 * Ordered write. Start output on a buffer, and flag it so that the
1095 * device will write it in the order it was queued. The buffer is
1096 * released when the output completes. bwrite() ( or the VOP routine
1097 * anyway ) is responsible for handling B_INVAL buffers.
1098 */
1099int
1100bowrite(struct buf *bp)
1101{
1102 bp->b_flags |= B_ORDERED;
1103 bawrite(bp);
984263bc
MD
1104 return (0);
1105}
1106
984263bc 1107/*
3f779080
HP
1108 * bdwrite:
1109 *
1110 * Delayed write. (Buffer is marked dirty). Do not bother writing
1111 * anything if the buffer is marked invalid.
984263bc 1112 *
3f779080
HP
1113 * Note that since the buffer must be completely valid, we can safely
1114 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1115 * biodone() in order to prevent getblk from writing the buffer
1116 * out synchronously.
984263bc
MD
1117 */
1118void
493c516a 1119bdwrite(struct buf *bp)
984263bc 1120{
77bb9400 1121 if (BUF_REFCNTNB(bp) == 0)
984263bc
MD
1122 panic("bdwrite: buffer is not busy");
1123
1124 if (bp->b_flags & B_INVAL) {
1125 brelse(bp);
1126 return;
1127 }
1128 bdirty(bp);
1129
3573cf7b 1130 dsched_buf_enter(bp); /* might stack */
8c72e3d5 1131
984263bc
MD
1132 /*
1133 * Set B_CACHE, indicating that the buffer is fully valid. This is
1134 * true even of NFS now.
1135 */
1136 bp->b_flags |= B_CACHE;
1137
1138 /*
1139 * This bmap keeps the system from needing to do the bmap later,
1140 * perhaps when the system is attempting to do a sync. Since it
1141 * is likely that the indirect block -- or whatever other datastructure
1142 * that the filesystem needs is still in memory now, it is a good
1143 * thing to do this. Note also, that if the pageout daemon is
1144 * requesting a sync -- there might not be enough memory to do
1145 * the bmap then... So, this is important to do.
1146 */
54078292 1147 if (bp->b_bio2.bio_offset == NOOFFSET) {
08daea96 1148 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
e92ca23a 1149 NULL, NULL, BUF_CMD_WRITE);
984263bc
MD
1150 }
1151
1152 /*
cb1cf930
MD
1153 * Because the underlying pages may still be mapped and
1154 * writable trying to set the dirty buffer (b_dirtyoff/end)
1155 * range here will be inaccurate.
1156 *
1157 * However, we must still clean the pages to satisfy the
52e79afa 1158 * vnode_pager and pageout daemon, so they think the pages
cb1cf930
MD
1159 * have been "cleaned". What has really occured is that
1160 * they've been earmarked for later writing by the buffer
1161 * cache.
1162 *
1163 * So we get the b_dirtyoff/end update but will not actually
1164 * depend on it (NFS that is) until the pages are busied for
1165 * writing later on.
984263bc
MD
1166 */
1167 vfs_clean_pages(bp);
1168 bqrelse(bp);
1169
984263bc
MD
1170 /*
1171 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1172 * due to the softdep code.
1173 */
1174}
1175
0a8aee15
MD
1176/*
1177 * Fake write - return pages to VM system as dirty, leave the buffer clean.
1178 * This is used by tmpfs.
1179 *
1180 * It is important for any VFS using this routine to NOT use it for
1181 * IO_SYNC or IO_ASYNC operations which occur when the system really
1182 * wants to flush VM pages to backing store.
1183 */
1184void
1185buwrite(struct buf *bp)
1186{
1187 vm_page_t m;
1188 int i;
1189
1190 /*
1191 * Only works for VMIO buffers. If the buffer is already
1192 * marked for delayed-write we can't avoid the bdwrite().
1193 */
1194 if ((bp->b_flags & B_VMIO) == 0 || (bp->b_flags & B_DELWRI)) {
1195 bdwrite(bp);
1196 return;
1197 }
1198
1199 /*
9bf025db 1200 * Mark as needing a commit.
0a8aee15
MD
1201 */
1202 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1203 m = bp->b_xio.xio_pages[i];
9bf025db 1204 vm_page_need_commit(m);
0a8aee15
MD
1205 }
1206 bqrelse(bp);
1207}
1208
984263bc 1209/*
3f779080 1210 * bdirty:
984263bc 1211 *
10f3fee5
MD
1212 * Turn buffer into delayed write request by marking it B_DELWRI.
1213 * B_RELBUF and B_NOCACHE must be cleared.
984263bc 1214 *
10f3fee5
MD
1215 * We reassign the buffer to itself to properly update it in the
1216 * dirty/clean lists.
984263bc 1217 *
e43a034f 1218 * Must be called from a critical section.
b3098c79 1219 * The buffer must be on BQUEUE_NONE.
984263bc
MD
1220 */
1221void
493c516a 1222bdirty(struct buf *bp)
984263bc 1223{
55b50bd5
MD
1224 KASSERT(bp->b_qindex == BQUEUE_NONE,
1225 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
69f8c926 1226 if (bp->b_flags & B_NOCACHE) {
6ea70f76 1227 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
69f8c926
MD
1228 bp->b_flags &= ~B_NOCACHE;
1229 }
1230 if (bp->b_flags & B_INVAL) {
6ea70f76 1231 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
69f8c926 1232 }
10f3fee5 1233 bp->b_flags &= ~B_RELBUF;
984263bc
MD
1234
1235 if ((bp->b_flags & B_DELWRI) == 0) {
c5724852 1236 lwkt_gettoken(&bp->b_vp->v_token);
10f3fee5 1237 bp->b_flags |= B_DELWRI;
1f1ea522 1238 reassignbuf(bp);
c5724852 1239 lwkt_reltoken(&bp->b_vp->v_token);
77912481 1240
e11efbb3
MD
1241 atomic_add_long(&dirtybufcount, 1);
1242 atomic_add_long(&dirtykvaspace, bp->b_kvasize);
1243 atomic_add_long(&dirtybufspace, bp->b_bufsize);
70ac7d6c 1244 if (bp->b_flags & B_HEAVY) {
e11efbb3
MD
1245 atomic_add_long(&dirtybufcounthw, 1);
1246 atomic_add_long(&dirtybufspacehw, bp->b_bufsize);
70ac7d6c 1247 }
c4df9635 1248 bd_heatup();
984263bc
MD
1249 }
1250}
1251
4b958e7b
MD
1252/*
1253 * Set B_HEAVY, indicating that this is a heavy-weight buffer that
1254 * needs to be flushed with a different buf_daemon thread to avoid
1255 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf().
1256 */
1257void
1258bheavy(struct buf *bp)
1259{
1260 if ((bp->b_flags & B_HEAVY) == 0) {
1261 bp->b_flags |= B_HEAVY;
70ac7d6c 1262 if (bp->b_flags & B_DELWRI) {
e11efbb3
MD
1263 atomic_add_long(&dirtybufcounthw, 1);
1264 atomic_add_long(&dirtybufspacehw, bp->b_bufsize);
70ac7d6c 1265 }
4b958e7b
MD
1266 }
1267}
1268
984263bc 1269/*
3f779080 1270 * bundirty:
984263bc
MD
1271 *
1272 * Clear B_DELWRI for buffer.
1273 *
e43a034f 1274 * Must be called from a critical section.
eaaadca0 1275 *
b3098c79 1276 * The buffer is typically on BQUEUE_NONE but there is one case in
eaaadca0
MD
1277 * brelse() that calls this function after placing the buffer on
1278 * a different queue.
984263bc 1279 */
984263bc 1280void
493c516a 1281bundirty(struct buf *bp)
984263bc 1282{
984263bc 1283 if (bp->b_flags & B_DELWRI) {
c5724852 1284 lwkt_gettoken(&bp->b_vp->v_token);
984263bc 1285 bp->b_flags &= ~B_DELWRI;
1f1ea522 1286 reassignbuf(bp);
c5724852 1287 lwkt_reltoken(&bp->b_vp->v_token);
77912481 1288
e11efbb3
MD
1289 atomic_add_long(&dirtybufcount, -1);
1290 atomic_add_long(&dirtykvaspace, -bp->b_kvasize);
1291 atomic_add_long(&dirtybufspace, -bp->b_bufsize);
70ac7d6c 1292 if (bp->b_flags & B_HEAVY) {
e11efbb3
MD
1293 atomic_add_long(&dirtybufcounthw, -1);
1294 atomic_add_long(&dirtybufspacehw, -bp->b_bufsize);
70ac7d6c 1295 }
868d24af 1296 bd_signal(bp->b_bufsize);
984263bc
MD
1297 }
1298 /*
1299 * Since it is now being written, we can clear its deferred write flag.
1300 */
1301 bp->b_flags &= ~B_DEFERRED;
1302}
1303
77912481
MD
1304/*
1305 * Set the b_runningbufspace field, used to track how much I/O is
1306 * in progress at any given moment.
1307 */
1308void
1309bsetrunningbufspace(struct buf *bp, int bytes)
1310{
1311 bp->b_runningbufspace = bytes;
1312 if (bytes) {
e11efbb3
MD
1313 atomic_add_long(&runningbufspace, bytes);
1314 atomic_add_long(&runningbufcount, 1);
77912481
MD
1315 }
1316}
1317
984263bc 1318/*
3f779080 1319 * brelse:
984263bc
MD
1320 *
1321 * Release a busy buffer and, if requested, free its resources. The
1322 * buffer will be stashed in the appropriate bufqueue[] allowing it
1323 * to be accessed later as a cache entity or reused for other purposes.
1324 */
1325void
c8e4131d 1326brelse(struct buf *bp)
984263bc 1327{
e11efbb3 1328 struct bufpcpu *pcpu;
9188c711
MD
1329#ifdef INVARIANTS
1330 int saved_flags = bp->b_flags;
1331#endif
1332
e11efbb3
MD
1333 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1334 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
984263bc 1335
135bd6a8
MD
1336 /*
1337 * If B_NOCACHE is set we are being asked to destroy the buffer and
1338 * its backing store. Clear B_DELWRI.
1339 *
1340 * B_NOCACHE is set in two cases: (1) when the caller really wants
1341 * to destroy the buffer and backing store and (2) when the caller
1342 * wants to destroy the buffer and backing store after a write
1343 * completes.
1344 */
1345 if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1346 bundirty(bp);
69f8c926
MD
1347 }
1348
78a9b77f 1349 if ((bp->b_flags & (B_INVAL | B_DELWRI)) == B_DELWRI) {
984263bc 1350 /*
78a9b77f
MD
1351 * A re-dirtied buffer is only subject to destruction
1352 * by B_INVAL. B_ERROR and B_NOCACHE are ignored.
984263bc 1353 */
78a9b77f 1354 /* leave buffer intact */
10f3fee5 1355 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
78a9b77f 1356 (bp->b_bufsize <= 0)) {
984263bc 1357 /*
78a9b77f
MD
1358 * Either a failed read or we were asked to free or not
1359 * cache the buffer. This path is reached with B_DELWRI
1360 * set only if B_INVAL is already set. B_NOCACHE governs
1361 * backing store destruction.
408357d8
MD
1362 *
1363 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1364 * buffer cannot be immediately freed.
984263bc
MD
1365 */
1366 bp->b_flags |= B_INVAL;
77912481 1367 if (LIST_FIRST(&bp->b_dep) != NULL)
408357d8 1368 buf_deallocate(bp);
984263bc 1369 if (bp->b_flags & B_DELWRI) {
e11efbb3
MD
1370 atomic_add_long(&dirtybufcount, -1);
1371 atomic_add_long(&dirtykvaspace, -bp->b_kvasize);
1372 atomic_add_long(&dirtybufspace, -bp->b_bufsize);
70ac7d6c 1373 if (bp->b_flags & B_HEAVY) {
e11efbb3
MD
1374 atomic_add_long(&dirtybufcounthw, -1);
1375 atomic_add_long(&dirtybufspacehw,
1376 -bp->b_bufsize);
70ac7d6c 1377 }
868d24af 1378 bd_signal(bp->b_bufsize);
984263bc 1379 }
10f3fee5 1380 bp->b_flags &= ~(B_DELWRI | B_CACHE);
984263bc
MD
1381 }
1382
1383 /*
283b9448
MD
1384 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set,
1385 * or if b_refs is non-zero.
1386 *
408357d8
MD
1387 * If vfs_vmio_release() is called with either bit set, the
1388 * underlying pages may wind up getting freed causing a previous
1389 * write (bdwrite()) to get 'lost' because pages associated with
1390 * a B_DELWRI bp are marked clean. Pages associated with a
1391 * B_LOCKED buffer may be mapped by the filesystem.
4b958e7b
MD
1392 *
1393 * If we want to release the buffer ourselves (rather then the
1394 * originator asking us to release it), give the originator a
1395 * chance to countermand the release by setting B_LOCKED.
984263bc
MD
1396 *
1397 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1398 * if B_DELWRI is set.
1399 *
1400 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1401 * on pages to return pages to the VM page queues.
1402 */
283b9448 1403 if ((bp->b_flags & (B_DELWRI | B_LOCKED)) || bp->b_refs) {
984263bc 1404 bp->b_flags &= ~B_RELBUF;
55b50bd5 1405 } else if (vm_page_count_min(0)) {
77912481 1406 if (LIST_FIRST(&bp->b_dep) != NULL)
78a9b77f 1407 buf_deallocate(bp); /* can set B_LOCKED */
4b958e7b
MD
1408 if (bp->b_flags & (B_DELWRI | B_LOCKED))
1409 bp->b_flags &= ~B_RELBUF;
1410 else
1411 bp->b_flags |= B_RELBUF;
1412 }
984263bc 1413
9188c711 1414 /*
78a9b77f
MD
1415 * Make sure b_cmd is clear. It may have already been cleared by
1416 * biodone().
1417 *
9188c711
MD
1418 * At this point destroying the buffer is governed by the B_INVAL
1419 * or B_RELBUF flags.
1420 */
10f3fee5 1421 bp->b_cmd = BUF_CMD_DONE;
3573cf7b 1422 dsched_buf_exit(bp);
9188c711 1423
984263bc 1424 /*
135bd6a8
MD
1425 * VMIO buffer rundown. Make sure the VM page array is restored
1426 * after an I/O may have replaces some of the pages with bogus pages
1427 * in order to not destroy dirty pages in a fill-in read.
1428 *
1429 * Note that due to the code above, if a buffer is marked B_DELWRI
1430 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1431 * B_INVAL may still be set, however.
984263bc 1432 *
135bd6a8
MD
1433 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1434 * but not the backing store. B_NOCACHE will destroy the backing
1435 * store.
984263bc 1436 *
135bd6a8
MD
1437 * Note that dirty NFS buffers contain byte-granular write ranges
1438 * and should not be destroyed w/ B_INVAL even if the backing store
1439 * is left intact.
984263bc 1440 */
135bd6a8 1441 if (bp->b_flags & B_VMIO) {
9188c711
MD
1442 /*
1443 * Rundown for VMIO buffers which are not dirty NFS buffers.
1444 */
984263bc
MD
1445 int i, j, resid;
1446 vm_page_t m;
1447 off_t foff;
1448 vm_pindex_t poff;
1449 vm_object_t obj;
1450 struct vnode *vp;
1451
1452 vp = bp->b_vp;
1453
1454 /*
1455 * Get the base offset and length of the buffer. Note that
1456 * in the VMIO case if the buffer block size is not
1457 * page-aligned then b_data pointer may not be page-aligned.
236b2b9f 1458 * But our b_xio.xio_pages array *IS* page aligned.
984263bc
MD
1459 *
1460 * block sizes less then DEV_BSIZE (usually 512) are not
1461 * supported due to the page granularity bits (m->valid,
1462 * m->dirty, etc...).
1463 *
1464 * See man buf(9) for more information
1465 */
1466
1467 resid = bp->b_bufsize;
81b5c339 1468 foff = bp->b_loffset;
984263bc 1469
54f51aeb
HP
1470 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1471 m = bp->b_xio.xio_pages[i];
984263bc
MD
1472 vm_page_flag_clear(m, PG_ZERO);
1473 /*
1474 * If we hit a bogus page, fixup *all* of them
06ecca5a
MD
1475 * now. Note that we left these pages wired
1476 * when we removed them so they had better exist,
1477 * and they cannot be ripped out from under us so
e43a034f 1478 * no critical section protection is necessary.
984263bc
MD
1479 */
1480 if (m == bogus_page) {
7540ab49 1481 obj = vp->v_object;
81b5c339 1482 poff = OFF_TO_IDX(bp->b_loffset);
984263bc 1483
b12defdc 1484 vm_object_hold(obj);
54f51aeb 1485 for (j = i; j < bp->b_xio.xio_npages; j++) {
984263bc
MD
1486 vm_page_t mtmp;
1487
54f51aeb 1488 mtmp = bp->b_xio.xio_pages[j];
984263bc
MD
1489 if (mtmp == bogus_page) {
1490 mtmp = vm_page_lookup(obj, poff + j);
1491 if (!mtmp) {
fc92d4aa 1492 panic("brelse: page missing");
984263bc 1493 }
54f51aeb 1494 bp->b_xio.xio_pages[j] = mtmp;
984263bc
MD
1495 }
1496 }
e158420c 1497 bp->b_flags &= ~B_HASBOGUS;
b12defdc 1498 vm_object_drop(obj);
984263bc
MD
1499
1500 if ((bp->b_flags & B_INVAL) == 0) {
54f51aeb
HP
1501 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1502 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
984263bc 1503 }
54f51aeb 1504 m = bp->b_xio.xio_pages[i];
984263bc 1505 }
8d429613
MD
1506
1507 /*
1508 * Invalidate the backing store if B_NOCACHE is set
1509 * (e.g. used with vinvalbuf()). If this is NFS
1510 * we impose a requirement that the block size be
1511 * a multiple of PAGE_SIZE and create a temporary
1512 * hack to basically invalidate the whole page. The
1513 * problem is that NFS uses really odd buffer sizes
1514 * especially when tracking piecemeal writes and
1515 * it also vinvalbuf()'s a lot, which would result
1516 * in only partial page validation and invalidation
1517 * here. If the file page is mmap()'d, however,
1518 * all the valid bits get set so after we invalidate
1519 * here we would end up with weird m->valid values
1520 * like 0xfc. nfs_getpages() can't handle this so
1521 * we clear all the valid bits for the NFS case
1522 * instead of just some of them.
1523 *
1524 * The real bug is the VM system having to set m->valid
1525 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1526 * itself is an artifact of the whole 512-byte
1527 * granular mess that exists to support odd block
1528 * sizes and UFS meta-data block sizes (e.g. 6144).
1529 * A complete rewrite is required.
cb1cf930
MD
1530 *
1531 * XXX
8d429613 1532 */
984263bc
MD
1533 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1534 int poffset = foff & PAGE_MASK;
8d429613
MD
1535 int presid;
1536
1537 presid = PAGE_SIZE - poffset;
1538 if (bp->b_vp->v_tag == VT_NFS &&
1539 bp->b_vp->v_type == VREG) {
1540 ; /* entire page */
1541 } else if (presid > resid) {
1542 presid = resid;
1543 }
984263bc
MD
1544 KASSERT(presid >= 0, ("brelse: extra page"));
1545 vm_page_set_invalid(m, poffset, presid);
c504e38e
MD
1546
1547 /*
1548 * Also make sure any swap cache is removed
1549 * as it is now stale (HAMMER in particular
1550 * uses B_NOCACHE to deal with buffer
1551 * aliasing).
1552 */
1553 swap_pager_unswapped(m);
984263bc
MD
1554 }
1555 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1556 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1557 }
984263bc
MD
1558 if (bp->b_flags & (B_INVAL | B_RELBUF))
1559 vfs_vmio_release(bp);
9188c711
MD
1560 } else {
1561 /*
1562 * Rundown for non-VMIO buffers.
1563 */
1564 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
9188c711
MD
1565 if (bp->b_bufsize)
1566 allocbuf(bp, 0);
f9a11477 1567 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
9188c711
MD
1568 if (bp->b_vp)
1569 brelvp(bp);
1570 }
984263bc
MD
1571 }
1572
b3098c79 1573 if (bp->b_qindex != BQUEUE_NONE)
984263bc 1574 panic("brelse: free buffer onto another queue???");
77bb9400 1575 if (BUF_REFCNTNB(bp) > 1) {
984263bc
MD
1576 /* Temporary panic to verify exclusive locking */
1577 /* This panic goes away when we allow shared refs */
1578 panic("brelse: multiple refs");
b1c20cfa 1579 /* NOT REACHED */
984263bc
MD
1580 return;
1581 }
1582
9188c711
MD
1583 /*
1584 * Figure out the correct queue to place the cleaned up buffer on.
1585 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1586 * disassociated from their vnode.
e11efbb3
MD
1587 *
1588 * Return the buffer to its original pcpu area
9188c711 1589 */
e11efbb3
MD
1590 pcpu = &bufpcpu[bp->b_qcpu];
1591 spin_lock(&pcpu->spin);
1592
408357d8
MD
1593 if (bp->b_flags & B_LOCKED) {
1594 /*
27bc0cb1
MD
1595 * Buffers that are locked are placed in the locked queue
1596 * immediately, regardless of their state.
408357d8 1597 */
27bc0cb1 1598 bp->b_qindex = BQUEUE_LOCKED;
e11efbb3
MD
1599 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1600 bp, b_freelist);
408357d8 1601 } else if (bp->b_bufsize == 0) {
9188c711
MD
1602 /*
1603 * Buffers with no memory. Due to conditionals near the top
1604 * of brelse() such buffers should probably already be
1605 * marked B_INVAL and disassociated from their vnode.
1606 */
984263bc 1607 bp->b_flags |= B_INVAL;
e11efbb3
MD
1608 KASSERT(bp->b_vp == NULL,
1609 ("bp1 %p flags %08x/%08x vnode %p "
1610 "unexpectededly still associated!",
1611 bp, saved_flags, bp->b_flags, bp->b_vp));
1f1ea522 1612 KKASSERT((bp->b_flags & B_HASHED) == 0);
984263bc 1613 if (bp->b_kvasize) {
b3098c79 1614 bp->b_qindex = BQUEUE_EMPTYKVA;
984263bc 1615 } else {
b3098c79 1616 bp->b_qindex = BQUEUE_EMPTY;
984263bc 1617 }
e11efbb3
MD
1618 TAILQ_INSERT_HEAD(&pcpu->bufqueues[bp->b_qindex],
1619 bp, b_freelist);
78a9b77f 1620 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) {
9188c711
MD
1621 /*
1622 * Buffers with junk contents. Again these buffers had better
1623 * already be disassociated from their vnode.
1624 */
e11efbb3
MD
1625 KASSERT(bp->b_vp == NULL,
1626 ("bp2 %p flags %08x/%08x vnode %p unexpectededly "
1627 "still associated!",
1628 bp, saved_flags, bp->b_flags, bp->b_vp));
1f1ea522 1629 KKASSERT((bp->b_flags & B_HASHED) == 0);
984263bc 1630 bp->b_flags |= B_INVAL;
b3098c79 1631 bp->b_qindex = BQUEUE_CLEAN;
e11efbb3
MD
1632 TAILQ_INSERT_HEAD(&pcpu->bufqueues[bp->b_qindex],
1633 bp, b_freelist);
984263bc 1634 } else {
9188c711
MD
1635 /*
1636 * Remaining buffers. These buffers are still associated with
1637 * their vnode.
1638 */
b86460bf 1639 switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
984263bc 1640 case B_DELWRI:
e11efbb3
MD
1641 bp->b_qindex = BQUEUE_DIRTY;
1642 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1643 bp, b_freelist);
1644 break;
4b958e7b 1645 case B_DELWRI | B_HEAVY:
e11efbb3
MD
1646 bp->b_qindex = BQUEUE_DIRTY_HW;
1647 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1648 bp, b_freelist);
1649 break;
984263bc 1650 default:
e11efbb3
MD
1651 /*
1652 * NOTE: Buffers are always placed at the end of the
1653 * queue. If B_AGE is not set the buffer will cycle
1654 * through the queue twice.
1655 */
1656 bp->b_qindex = BQUEUE_CLEAN;
1657 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1658 bp, b_freelist);
1659 break;
984263bc
MD
1660 }
1661 }
e11efbb3 1662 spin_unlock(&pcpu->spin);
984263bc
MD
1663
1664 /*
1665 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
e11efbb3 1666 * on the correct queue but we have not yet unlocked it.
984263bc
MD
1667 */
1668 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1669 bundirty(bp);
1670
1671 /*
868d24af
MD
1672 * The bp is on an appropriate queue unless locked. If it is not
1673 * locked or dirty we can wakeup threads waiting for buffer space.
1674 *
984263bc
MD
1675 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1676 * if B_INVAL is set ).
1677 */
408357d8 1678 if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
984263bc
MD
1679 bufcountwakeup();
1680
1681 /*
1682 * Something we can maybe free or reuse
1683 */
1684 if (bp->b_bufsize || bp->b_kvasize)
1685 bufspacewakeup();
1686
69f8c926
MD
1687 /*
1688 * Clean up temporary flags and unlock the buffer.
1689 */
ae8e83e6 1690 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF | B_DIRECT);
69f8c926 1691 BUF_UNLOCK(bp);
984263bc
MD
1692}
1693
1694/*
3f779080
HP
1695 * bqrelse:
1696 *
1697 * Release a buffer back to the appropriate queue but do not try to free
1698 * it. The buffer is expected to be used again soon.
984263bc 1699 *
3f779080
HP
1700 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1701 * biodone() to requeue an async I/O on completion. It is also used when
1702 * known good buffers need to be requeued but we think we may need the data
1703 * again soon.
984263bc 1704 *
3f779080 1705 * XXX we should be able to leave the B_RELBUF hint set on completion.
984263bc
MD
1706 */
1707void
c8e4131d 1708bqrelse(struct buf *bp)
984263bc 1709{
e11efbb3
MD
1710 struct bufpcpu *pcpu;
1711
1712 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1713 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
984263bc 1714
b3098c79 1715 if (bp->b_qindex != BQUEUE_NONE)
984263bc 1716 panic("bqrelse: free buffer onto another queue???");
77bb9400 1717 if (BUF_REFCNTNB(bp) > 1) {
984263bc
MD
1718 /* do not release to free list */
1719 panic("bqrelse: multiple refs");
984263bc
MD
1720 return;
1721 }
c3d1e862 1722
0e8bd897
MD
1723 buf_act_advance(bp);
1724
e11efbb3
MD
1725 pcpu = &bufpcpu[bp->b_qcpu];
1726 spin_lock(&pcpu->spin);
1727
984263bc 1728 if (bp->b_flags & B_LOCKED) {
5e23ca53
MD
1729 /*
1730 * Locked buffers are released to the locked queue. However,
1731 * if the buffer is dirty it will first go into the dirty
1732 * queue and later on after the I/O completes successfully it
1733 * will be released to the locked queue.
1734 */
27bc0cb1 1735 bp->b_qindex = BQUEUE_LOCKED;
e11efbb3
MD
1736 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1737 bp, b_freelist);
984263bc 1738 } else if (bp->b_flags & B_DELWRI) {
4b958e7b
MD
1739 bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1740 BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
e11efbb3
MD
1741 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1742 bp, b_freelist);
55b50bd5 1743 } else if (vm_page_count_min(0)) {
984263bc
MD
1744 /*
1745 * We are too low on memory, we have to try to free the
1746 * buffer (most importantly: the wired pages making up its
1747 * backing store) *now*.
1748 */
e11efbb3 1749 spin_unlock(&pcpu->spin);
984263bc
MD
1750 brelse(bp);
1751 return;
1752 } else {
b3098c79 1753 bp->b_qindex = BQUEUE_CLEAN;
e11efbb3
MD
1754 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1755 bp, b_freelist);
984263bc 1756 }
e11efbb3 1757 spin_unlock(&pcpu->spin);
984263bc 1758
e11efbb3
MD
1759 /*
1760 * We have now placed the buffer on the proper queue, but have yet
1761 * to unlock it.
1762 */
984263bc 1763 if ((bp->b_flags & B_LOCKED) == 0 &&
408357d8 1764 ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
984263bc
MD
1765 bufcountwakeup();
1766 }
1767
1768 /*
1769 * Something we can maybe free or reuse.
1770 */
1771 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1772 bufspacewakeup();
1773
9188c711
MD
1774 /*
1775 * Final cleanup and unlock. Clear bits that are only used while a
1776 * buffer is actively locked.
1777 */
ae8e83e6 1778 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF);
3573cf7b 1779 dsched_buf_exit(bp);
9188c711 1780 BUF_UNLOCK(bp);
984263bc
MD
1781}
1782
283b9448
MD
1783/*
1784 * Hold a buffer, preventing it from being reused. This will prevent
1785 * normal B_RELBUF operations on the buffer but will not prevent B_INVAL
1786 * operations. If a B_INVAL operation occurs the buffer will remain held
1787 * but the underlying pages may get ripped out.
1788 *
1789 * These functions are typically used in VOP_READ/VOP_WRITE functions
1790 * to hold a buffer during a copyin or copyout, preventing deadlocks
1791 * or recursive lock panics when read()/write() is used over mmap()'d
1792 * space.
1793 *
1794 * NOTE: bqhold() requires that the buffer be locked at the time of the
1795 * hold. bqdrop() has no requirements other than the buffer having
1796 * previously been held.
1797 */
1798void
1799bqhold(struct buf *bp)
1800{
1801 atomic_add_int(&bp->b_refs, 1);
1802}
1803
1804void
1805bqdrop(struct buf *bp)
1806{
1807 KKASSERT(bp->b_refs > 0);
1808 atomic_add_int(&bp->b_refs, -1);
1809}
1810
3f779080 1811/*
55b50bd5
MD
1812 * Return backing pages held by the buffer 'bp' back to the VM system.
1813 * This routine is called when the bp is invalidated, released, or
1814 * reused.
1815 *
1816 * The KVA mapping (b_data) for the underlying pages is removed by
1817 * this function.
1818 *
1819 * WARNING! This routine is integral to the low memory critical path
1820 * when a buffer is B_RELBUF'd. If the system has a severe page
1821 * deficit we need to get the page(s) onto the PQ_FREE or PQ_CACHE
1822 * queues so they can be reused in the current pageout daemon
1823 * pass.
3f779080 1824 */
984263bc 1825static void
493c516a 1826vfs_vmio_release(struct buf *bp)
984263bc 1827{
e43a034f 1828 int i;
984263bc
MD
1829 vm_page_t m;
1830
54f51aeb
HP
1831 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1832 m = bp->b_xio.xio_pages[i];
1833 bp->b_xio.xio_pages[i] = NULL;
0e8bd897 1834
55b50bd5
MD
1835 /*
1836 * We need to own the page in order to safely unwire it.
1837 */
b12defdc
MD
1838 vm_page_busy_wait(m, FALSE, "vmiopg");
1839
b8a41159
MD
1840 /*
1841 * The VFS is telling us this is not a meta-data buffer
1842 * even if it is backed by a block device.
1843 */
1844 if (bp->b_flags & B_NOTMETA)
1845 vm_page_flag_set(m, PG_NOTMETA);
1846
984263bc 1847 /*
0e8bd897
MD
1848 * This is a very important bit of code. We try to track
1849 * VM page use whether the pages are wired into the buffer
1850 * cache or not. While wired into the buffer cache the
1851 * bp tracks the act_count.
1852 *
1853 * We can choose to place unwired pages on the inactive
1854 * queue (0) or active queue (1). If we place too many
1855 * on the active queue the queue will cycle the act_count
1856 * on pages we'd like to keep, just from single-use pages
1857 * (such as when doing a tar-up or file scan).
984263bc 1858 */
0e8bd897
MD
1859 if (bp->b_act_count < vm_cycle_point)
1860 vm_page_unwire(m, 0);
1861 else
1862 vm_page_unwire(m, 1);
1863
984263bc 1864 /*
55b50bd5 1865 * If the wire_count has dropped to 0 we may need to take
9bf025db
MD
1866 * further action before unbusying the page.
1867 *
1868 * WARNING: vm_page_try_*() also checks PG_NEED_COMMIT for us.
984263bc 1869 */
984263bc
MD
1870 if (m->wire_count == 0) {
1871 vm_page_flag_clear(m, PG_ZERO);
55b50bd5 1872
ae8e83e6 1873 if (bp->b_flags & B_DIRECT) {
55b50bd5
MD
1874 /*
1875 * Attempt to free the page if B_DIRECT is
1876 * set, the caller does not desire the page
1877 * to be cached.
1878 */
b12defdc 1879 vm_page_wakeup(m);
984263bc 1880 vm_page_try_to_free(m);
17c8b5ef 1881 } else if ((bp->b_flags & B_NOTMETA) ||
55b50bd5
MD
1882 vm_page_count_min(0)) {
1883 /*
1884 * Attempt to move the page to PQ_CACHE
1885 * if B_NOTMETA is set. This flag is set
1886 * by HAMMER to remove one of the two pages
1887 * present when double buffering is enabled.
1888 *
1889 * Attempt to move the page to PQ_CACHE
1890 * If we have a severe page deficit. This
1891 * will cause buffer cache operations related
1892 * to pageouts to recycle the related pages
1893 * in order to avoid a low memory deadlock.
1894 */
0e8bd897 1895 m->act_count = bp->b_act_count;
b12defdc 1896 vm_page_wakeup(m);
984263bc 1897 vm_page_try_to_cache(m);
0e8bd897 1898 } else {
55b50bd5
MD
1899 /*
1900 * Nominal case, leave the page on the
1901 * queue the original unwiring placed it on
1902 * (active or inactive).
1903 */
0e8bd897 1904 m->act_count = bp->b_act_count;
b12defdc 1905 vm_page_wakeup(m);
984263bc 1906 }
b12defdc
MD
1907 } else {
1908 vm_page_wakeup(m);
984263bc
MD
1909 }
1910 }
77912481
MD
1911
1912 pmap_qremove(trunc_page((vm_offset_t) bp->b_data),
1913 bp->b_xio.xio_npages);
984263bc
MD
1914 if (bp->b_bufsize) {
1915 bufspacewakeup();
1916 bp->b_bufsize = 0;
1917 }
54f51aeb 1918 bp->b_xio.xio_npages = 0;
984263bc 1919 bp->b_flags &= ~B_VMIO;
f9a11477 1920 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
77912481 1921 if (bp->b_vp)
984263bc
MD
1922 brelvp(bp);
1923}
1924
984263bc 1925/*
e11efbb3
MD
1926 * Find and initialize a new buffer header, freeing up existing buffers
1927 * in the bufqueues as necessary. The new buffer is returned locked.
984263bc 1928 *
e11efbb3
MD
1929 * Important: B_INVAL is not set. If the caller wishes to throw the
1930 * buffer away, the caller must set B_INVAL prior to calling brelse().
984263bc 1931 *
e11efbb3
MD
1932 * We block if:
1933 * We have insufficient buffer headers
1934 * We have insufficient buffer space
1935 * buffer_map is too fragmented ( space reservation fails )
1936 * If we have to flush dirty buffers ( but we try to avoid this )
b1c20cfa 1937 *
e11efbb3
MD
1938 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1939 * Instead we ask the buf daemon to do it for us. We attempt to
1940 * avoid piecemeal wakeups of the pageout daemon.
984263bc 1941 */
e0fb398b 1942struct buf *
4b958e7b 1943getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
984263bc 1944{
e11efbb3 1945 struct bufpcpu *pcpu;
984263bc
MD
1946 struct buf *bp;
1947 struct buf *nbp;
1948 int defrag = 0;
1949 int nqindex;
e11efbb3 1950 int nqcpu;
4b958e7b 1951 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2258af1d
MD
1952 int maxloops = 200000;
1953 int restart_reason = 0;
1954 struct buf *restart_bp = NULL;
984263bc
MD
1955 static int flushingbufs;
1956
1957 /*
1958 * We can't afford to block since we might be holding a vnode lock,
1959 * which may prevent system daemons from running. We deal with
1960 * low-memory situations by proactively returning memory and running
1961 * async I/O rather then sync I/O.
1962 */
1963
1964 ++getnewbufcalls;
1965 --getnewbufrestarts;
e11efbb3 1966 nqcpu = mycpu->gd_cpuid;
984263bc
MD
1967restart:
1968 ++getnewbufrestarts;
1969
2258af1d
MD
1970 if (debug_bufbio && --maxloops == 0)
1971 panic("getnewbuf, excessive loops on cpu %d restart %d (%p)",
1972 mycpu->gd_cpuid, restart_reason, restart_bp);
1973
984263bc
MD
1974 /*
1975 * Setup for scan. If we do not have enough free buffers,
1976 * we setup a degenerate case that immediately fails. Note
1977 * that if we are specially marked process, we are allowed to
1978 * dip into our reserves.
1979 *
1980 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1981 *
1982 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1983 * However, there are a number of cases (defragging, reusing, ...)
1984 * where we cannot backup.
1985 */
e11efbb3 1986 pcpu = &bufpcpu[nqcpu];
b3098c79 1987 nqindex = BQUEUE_EMPTYKVA;
e11efbb3
MD
1988 spin_lock(&pcpu->spin);
1989
1990 nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_EMPTYKVA]);
984263bc
MD
1991
1992 if (nbp == NULL) {
1993 /*
1994 * If no EMPTYKVA buffers and we are either
1995 * defragging or reusing, locate a CLEAN buffer
1996 * to free or reuse. If bufspace useage is low
1997 * skip this step so we can allocate a new buffer.
1998 */
1999 if (defrag || bufspace >= lobufspace) {
b3098c79 2000 nqindex = BQUEUE_CLEAN;
e11efbb3 2001 nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_CLEAN]);
984263bc
MD
2002 }
2003
2004 /*
2005 * If we could not find or were not allowed to reuse a
2006 * CLEAN buffer, check to see if it is ok to use an EMPTY
2007 * buffer. We can only use an EMPTY buffer if allocating
2008 * its KVA would not otherwise run us out of buffer space.
2009 */
2010 if (nbp == NULL && defrag == 0 &&
2011 bufspace + maxsize < hibufspace) {
b3098c79 2012 nqindex = BQUEUE_EMPTY;
e11efbb3 2013 nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_EMPTY]);
984263bc
MD
2014 }
2015 }
2016
2017 /*
2018 * Run scan, possibly freeing data and/or kva mappings on the fly
2019 * depending.
c3d1e862 2020 *
e11efbb3 2021 * WARNING! spin is held!
984263bc 2022 */
984263bc
MD
2023 while ((bp = nbp) != NULL) {
2024 int qindex = nqindex;
2025
b86460bf
MD
2026 nbp = TAILQ_NEXT(bp, b_freelist);
2027
2028 /*
2029 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
2030 * cycles through the queue twice before being selected.
2031 */
2032 if (qindex == BQUEUE_CLEAN &&
2033 (bp->b_flags & B_AGE) == 0 && nbp) {
2034 bp->b_flags |= B_AGE;
e11efbb3
MD
2035 TAILQ_REMOVE(&pcpu->bufqueues[qindex],
2036 bp, b_freelist);
2037 TAILQ_INSERT_TAIL(&pcpu->bufqueues[qindex],
2038 bp, b_freelist);
b86460bf
MD
2039 continue;
2040 }
2041
984263bc
MD
2042 /*
2043 * Calculate next bp ( we can only use it if we do not block
2044 * or do other fancy things ).
2045 */
b86460bf 2046 if (nbp == NULL) {
984263bc 2047 switch(qindex) {
b3098c79
HP
2048 case BQUEUE_EMPTY:
2049 nqindex = BQUEUE_EMPTYKVA;
e11efbb3 2050 if ((nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_EMPTYKVA])))
984263bc
MD
2051 break;
2052 /* fall through */
b3098c79
HP
2053 case BQUEUE_EMPTYKVA:
2054 nqindex = BQUEUE_CLEAN;
e11efbb3 2055 if ((nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_CLEAN])))
984263bc
MD
2056 break;
2057 /* fall through */
b3098c79 2058 case BQUEUE_CLEAN:
984263bc
MD
2059 /*
2060 * nbp is NULL.
2061 */
2062 break;
2063 }
2064 }
2065
2066 /*
2067 * Sanity Checks
2068 */
7e8888ce
MD
2069 KASSERT(bp->b_qindex == qindex,
2070 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
984263bc
MD
2071
2072 /*
2073 * Note: we no longer distinguish between VMIO and non-VMIO
2074 * buffers.
2075 */
77912481
MD
2076 KASSERT((bp->b_flags & B_DELWRI) == 0,
2077 ("delwri buffer %p found in queue %d", bp, qindex));
984263bc 2078
77912481
MD
2079 /*
2080 * Do not try to reuse a buffer with a non-zero b_refs.
2081 * This is an unsynchronized test. A synchronized test
2082 * is also performed after we lock the buffer.
2083 */
2084 if (bp->b_refs)
2085 continue;
984263bc
MD
2086
2087 /*
2088 * If we are defragging then we need a buffer with
2089 * b_kvasize != 0. XXX this situation should no longer
2090 * occur, if defrag is non-zero the buffer's b_kvasize
2091 * should also be non-zero at this point. XXX
2092 */
2093 if (defrag && bp->b_kvasize == 0) {
6ea70f76 2094 kprintf("Warning: defrag empty buffer %p\n", bp);
984263bc
MD
2095 continue;
2096 }
2097
2098 /*
2099 * Start freeing the bp. This is somewhat involved. nbp
b3098c79 2100 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
9188c711
MD
2101 * on the clean list must be disassociated from their
2102 * current vnode. Buffers on the empty[kva] lists have
2103 * already been disassociated.
283b9448
MD
2104 *
2105 * b_refs is checked after locking along with queue changes.
2106 * We must check here to deal with zero->nonzero transitions
2107 * made by the owner of the buffer lock, which is used by
2108 * VFS's to hold the buffer while issuing an unlocked
2109 * uiomove()s. We cannot invalidate the buffer's pages
2110 * for this case. Once we successfully lock a buffer the
2111 * only 0->1 transitions of b_refs will occur via findblk().
2112 *
2113 * We must also check for queue changes after successful
2114 * locking as the current lock holder may dispose of the
2115 * buffer and change its queue.
984263bc 2116 */
d9dba6f6 2117 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
e11efbb3 2118 spin_unlock(&pcpu->spin);
7e8888ce 2119 tsleep(&bd_request, 0, "gnbxxx", (hz + 99) / 100);
2258af1d
MD
2120 restart_reason = 1;
2121 restart_bp = bp;
d9dba6f6
MD
2122 goto restart;
2123 }
283b9448 2124 if (bp->b_qindex != qindex || bp->b_refs) {
e11efbb3 2125 spin_unlock(&pcpu->spin);
d9dba6f6 2126 BUF_UNLOCK(bp);
2258af1d
MD
2127 restart_reason = 2;
2128 restart_bp = bp;
d9dba6f6
MD
2129 goto restart;
2130 }
c3d1e862 2131 bremfree_locked(bp);
e11efbb3 2132 spin_unlock(&pcpu->spin);
984263bc 2133
408357d8
MD
2134 /*
2135 * Dependancies must be handled before we disassociate the
2136 * vnode.
2137 *
2138 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2139 * be immediately disassociated. HAMMER then becomes
2140 * responsible for releasing the buffer.
c3d1e862 2141 *
e11efbb3 2142 * NOTE: spin is UNLOCKED now.
408357d8
MD
2143 */
2144 if (LIST_FIRST(&bp->b_dep) != NULL) {
2145 buf_deallocate(bp);
2146 if (bp->b_flags & B_LOCKED) {
2147 bqrelse(bp);
2258af1d
MD
2148 restart_reason = 3;
2149 restart_bp = bp;
408357d8
MD
2150 goto restart;
2151 }
4b958e7b 2152 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
408357d8
MD
2153 }
2154
b3098c79 2155 if (qindex == BQUEUE_CLEAN) {
77912481 2156 if (bp->b_flags & B_VMIO)
984263bc 2157 vfs_vmio_release(bp);
984263bc
MD
2158 if (bp->b_vp)
2159 brelvp(bp);
2160 }
2161
2162 /*
2163 * NOTE: nbp is now entirely invalid. We can only restart
2164 * the scan from this point on.
2165 *
2166 * Get the rest of the buffer freed up. b_kva* is still
2167 * valid after this operation.
2168 */
283b9448
MD
2169 KASSERT(bp->b_vp == NULL,
2170 ("bp3 %p flags %08x vnode %p qindex %d "
2171 "unexpectededly still associated!",
2172 bp, bp->b_flags, bp->b_vp, qindex));
1f1ea522 2173 KKASSERT((bp->b_flags & B_HASHED) == 0);
984263bc 2174
06ecca5a 2175 /*
e43a034f
MD
2176 * critical section protection is not required when
2177 * scrapping a buffer's contents because it is already
2178 * wired.
06ecca5a 2179 */
77912481 2180 if (bp->b_bufsize)
984263bc
MD
2181 allocbuf(bp, 0);
2182
cd3cfe0a
MD
2183 if (bp->b_flags & (B_VNDIRTY | B_VNCLEAN | B_HASHED)) {
2184 kprintf("getnewbuf: caught bug vp queue "
2185 "%p/%08x qidx %d\n",
2186 bp, bp->b_flags, qindex);
2187 brelvp(bp);
2188 }
4414f2c9 2189 bp->b_flags = B_BNOCLIP;
10f3fee5 2190 bp->b_cmd = BUF_CMD_DONE;
984263bc 2191 bp->b_vp = NULL;
984263bc
MD
2192 bp->b_error = 0;
2193 bp->b_resid = 0;
2194 bp->b_bcount = 0;
54f51aeb 2195 bp->b_xio.xio_npages = 0;
984263bc 2196 bp->b_dirtyoff = bp->b_dirtyend = 0;
0e8bd897 2197 bp->b_act_count = ACT_INIT;
81b5c339 2198 reinitbufbio(bp);
b86460bf 2199 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
408357d8 2200 buf_dep_init(bp);
4b958e7b
MD
2201 if (blkflags & GETBLK_BHEAVY)
2202 bp->b_flags |= B_HEAVY;
984263bc
MD
2203
2204 /*
2205 * If we are defragging then free the buffer.
2206 */
2207 if (defrag) {
2208 bp->b_flags |= B_INVAL;
2209 bfreekva(bp);
2210 brelse(bp);
2211 defrag = 0;
2258af1d
MD
2212 restart_reason = 4;
2213 restart_bp = bp;
984263bc
MD
2214 goto restart;
2215 }
2216
2217 /*
2218 * If we are overcomitted then recover the buffer and its
2219 * KVM space. This occurs in rare situations when multiple
2220 * processes are blocked in getnewbuf() or allocbuf().
80e89abc 2221 *
2258af1d
MD
2222 * On 64-bit systems BKVASIZE == MAXBSIZE and overcommit
2223 * should not be possible.
984263bc
MD
2224 */
2225 if (bufspace >= hibufspace)
2226 flushingbufs = 1;
2258af1d
MD
2227 if (BKVASIZE != MAXBSIZE) {
2228 if (flushingbufs && bp->b_kvasize != 0) {
2229 bp->b_flags |= B_INVAL;
80e89abc 2230 bfreekva(bp);
2258af1d
MD
2231 brelse(bp);
2232 restart_reason = 5;
2233 restart_bp = bp;
2234 goto restart;
2235 }
984263bc
MD
2236 }
2237 if (bufspace < lobufspace)
2238 flushingbufs = 0;
77912481
MD
2239
2240 /*
283b9448
MD
2241 * b_refs can transition to a non-zero value while we hold
2242 * the buffer locked due to a findblk(). Our brelvp() above
2243 * interlocked any future possible transitions due to
2244 * findblk()s.
2245 *
2246 * If we find b_refs to be non-zero we can destroy the
2247 * buffer's contents but we cannot yet reuse the buffer.
77912481
MD
2248 */
2249 if (bp->b_refs) {
2250 bp->b_flags |= B_INVAL;
80e89abc
MD
2251 if (BKVASIZE != MAXBSIZE)
2252 bfreekva(bp);
77912481 2253 brelse(bp);
2258af1d
MD
2254 restart_reason = 6;
2255 restart_bp = bp;
77912481
MD
2256 goto restart;
2257 }
984263bc 2258 break;
e11efbb3 2259 /* NOT REACHED, spin not held */
984263bc
MD
2260 }
2261
2262 /*
e11efbb3
MD
2263 * If we exhausted our list, iterate other cpus. If that fails,
2264 * sleep as appropriate. We may have to wakeup various daemons
2265 * and write out some dirty buffers.
984263bc
MD
2266 *
2267 * Generally we are sleeping due to insufficient buffer space.
c3d1e862 2268 *
e11efbb3 2269 * NOTE: spin is held if bp is NULL, else it is not held.
984263bc 2270 */
984263bc
MD
2271 if (bp == NULL) {
2272 int flags;
2273 char *waitmsg;
2274
e11efbb3
MD
2275 spin_unlock(&pcpu->spin);
2276
2277 nqcpu = (nqcpu + 1) % ncpus;
2258af1d
MD
2278 if (nqcpu != mycpu->gd_cpuid) {
2279 restart_reason = 7;
2280 restart_bp = bp;
e11efbb3 2281 goto restart;
2258af1d 2282 }
e11efbb3 2283
984263bc
MD
2284 if (defrag) {
2285 flags = VFS_BIO_NEED_BUFSPACE;
2286 waitmsg = "nbufkv";
2287 } else if (bufspace >= hibufspace) {
2288 waitmsg = "nbufbs";
2289 flags = VFS_BIO_NEED_BUFSPACE;
2290 } else {
2291 waitmsg = "newbuf";
2292 flags = VFS_BIO_NEED_ANY;
2293 }
2294
4b958e7b 2295 bd_speedup(); /* heeeelp */
e11efbb3 2296 atomic_set_int(&needsbuffer, flags);
984263bc 2297 while (needsbuffer & flags) {
e11efbb3
MD
2298 int value;
2299
2300 tsleep_interlock(&needsbuffer, 0);
2301 value = atomic_fetchadd_int(&needsbuffer, 0);
2302 if (value & flags) {
2303 if (tsleep(&needsbuffer, PINTERLOCKED|slpflags,
2304 waitmsg, slptimeo)) {
2305 return (NULL);
2306 }
77912481 2307 }
984263bc
MD
2308 }
2309 } else {
2310 /*
2311 * We finally have a valid bp. We aren't quite out of the
2312 * woods, we still have to reserve kva space. In order
2313 * to keep fragmentation sane we only allocate kva in
2314 * BKVASIZE chunks.
c3d1e862 2315 *
e11efbb3 2316 * (spin is not held)
984263bc
MD
2317 */
2318 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2319
2320 if (maxsize != bp->b_kvasize) {
2321 vm_offset_t addr = 0;
a108bf71 2322 int count;
984263bc
MD
2323
2324 bfreekva(bp);
2325
a108bf71 2326 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
e4846942 2327 vm_map_lock(&buffer_map);
984263bc 2328
e4846942
MD
2329 if (vm_map_findspace(&buffer_map,
2330 vm_map_min(&buffer_map), maxsize,
c809941b 2331 maxsize, 0, &addr)) {
984263bc 2332 /*
3f779080 2333 * Uh oh. Buffer map is too fragmented. We
984263bc
MD
2334 * must defragment the map.
2335 */
e4846942 2336 vm_map_unlock(&buffer_map);
a108bf71 2337 vm_map_entry_release(count);
984263bc
MD
2338 ++bufdefragcnt;
2339 defrag = 1;
2340 bp->b_flags |= B_INVAL;
2341 brelse(bp);
2258af1d
MD
2342 restart_reason = 8;
2343 restart_bp = bp;
984263bc
MD
2344 goto restart;
2345 }
2346 if (addr) {
e4846942 2347 vm_map_insert(&buffer_map, &count,
0adbcbd6
MD
2348 NULL, NULL,
2349 0, addr, addr + maxsize,
1b874851
MD
2350 VM_MAPTYPE_NORMAL,
2351 VM_PROT_ALL, VM_PROT_ALL,
2352 MAP_NOFAULT);
984263bc
MD
2353
2354 bp->b_kvabase = (caddr_t) addr;
2355 bp->b_kvasize = maxsize;
2356 bufspace += bp->b_kvasize;
2357 ++bufreusecnt;
2358 }
e4846942 2359 vm_map_unlock(&buffer_map);
a108bf71 2360 vm_map_entry_release(count);
984263bc
MD
2361 }
2362 bp->b_data = bp->b_kvabase;
2363 }
2364 return(bp);
2365}
2366
2367/*
3f779080 2368 * buf_daemon:
984263bc 2369 *
3f779080 2370 * Buffer flushing daemon. Buffers are normally flushed by the
984263bc
MD
2371 * update daemon but if it cannot keep up this process starts to
2372 * take the load in an attempt to prevent getnewbuf() from blocking.
4b958e7b
MD
2373 *
2374 * Once a flush is initiated it does not stop until the number
2375 * of buffers falls below lodirtybuffers, but we will wake up anyone
2376 * waiting at the mid-point.
984263bc 2377 */
984263bc
MD
2378static struct kproc_desc buf_kp = {
2379 "bufdaemon",
2380 buf_daemon,
4b958e7b
MD
2381 &bufdaemon_td
2382};
2383SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
f3f3eadb 2384 kproc_start, &buf_kp);
4b958e7b
MD
2385
2386static struct kproc_desc bufhw_kp = {
2387 "bufdaemon_hw",
2388 buf_daemon_hw,
2389 &bufdaemonhw_td
984263bc 2390};
4b958e7b 2391SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
f3f3eadb 2392 kproc_start, &bufhw_kp);
984263bc
MD
2393
2394static void
dca23730
VS
2395buf_daemon1(struct thread *td, int queue, int (*buf_limit_fn)(long),
2396 int *bd_req)
984263bc 2397{
3583bbb4 2398 long limit;
a447ba19
MD
2399 struct buf *marker;
2400
2401 marker = kmalloc(sizeof(*marker), M_BIOBUF, M_WAITOK | M_ZERO);
2402 marker->b_flags |= B_MARKER;
2403 marker->b_qindex = BQUEUE_NONE;
e11efbb3 2404 marker->b_qcpu = 0;
cd083340 2405
984263bc
MD
2406 /*
2407 * This process needs to be suspended prior to shutdown sync.
2408 */
bc6dffab 2409 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
dca23730 2410 td, SHUTDOWN_PRI_LAST);
4ecf7cc9 2411 curthread->td_flags |= TDF_SYSTHREAD;
984263bc
MD
2412
2413 /*
2414 * This process is allowed to take the buffer cache to the limit
2415 */
984263bc 2416 for (;;) {
0cfcada1 2417 kproc_suspend_loop();
984263bc
MD
2418
2419 /*
4afeea0d
MD
2420 * Do the flush as long as the number of dirty buffers
2421 * (including those running) exceeds lodirtybufspace.
2422 *
2423 * When flushing limit running I/O to hirunningspace
984263bc
MD
2424 * Do the flush. Limit the amount of in-transit I/O we
2425 * allow to build up, otherwise we would completely saturate
2426 * the I/O system. Wakeup any waiting processes before we
2427 * normally would so they can run in parallel with our drain.
cd083340
MD
2428 *
2429 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2430 * but because we split the operation into two threads we
2431 * have to cut it in half for each thread.
984263bc 2432 */
4afeea0d 2433 waitrunningbufspace();
cd083340 2434 limit = lodirtybufspace / 2;
dca23730 2435 while (buf_limit_fn(limit)) {
a447ba19 2436 if (flushbufqueues(marker, queue) == 0)
984263bc 2437 break;
4afeea0d
MD
2438 if (runningbufspace < hirunningspace)
2439 continue;
2440 waitrunningbufspace();
1b30fbcc 2441 }
984263bc
MD
2442
2443 /*
cd083340
MD
2444 * We reached our low water mark, reset the
2445 * request and sleep until we are needed again.
2446 * The sleep is just so the suspend code works.
984263bc 2447 */
8dc56d28
MD
2448 tsleep_interlock(bd_req, 0);
2449 if (atomic_swap_int(bd_req, 0) == 0)
2450 tsleep(bd_req, PINTERLOCKED, "psleep", hz);
984263bc 2451 }
a447ba19
MD
2452 /* NOT REACHED */
2453 /*kfree(marker, M_BIOBUF);*/
984263bc
MD
2454}
2455
dca23730
VS
2456static int
2457buf_daemon_limit(long limit)
4b958e7b 2458{
eafcc44d 2459 return (runningbufspace + dirtykvaspace > limit ||
dca23730
VS
2460 dirtybufcount - dirtybufcounthw >= nbuf / 2);
2461}
4b958e7b 2462
dca23730
VS
2463static int
2464buf_daemon_hw_limit(long limit)
2465{
eafcc44d 2466 return (runningbufspace + dirtykvaspace > limit ||
dca23730
VS
2467 dirtybufcounthw >= nbuf / 2);
2468}
4b958e7b 2469
dca23730
VS
2470static void
2471buf_daemon(void)
2472{
2473 buf_daemon1(bufdaemon_td, BQUEUE_DIRTY, buf_daemon_limit,
2474 &bd_request);
2475}
4b958e7b 2476
dca23730
VS
2477static void
2478buf_daemon_hw(void)
2479{
2480 buf_daemon1(bufdaemonhw_td, BQUEUE_DIRTY_HW, buf_daemon_hw_limit,
2481 &bd_request_hw);
4b958e7b
MD
2482}
2483
984263bc 2484/*
3f779080 2485 * flushbufqueues:
984263bc
MD
2486 *
2487 * Try to flush a buffer in the dirty queue. We must be careful to
2488 * free up B_INVAL buffers instead of write them, which NFS is
2489 * particularly sensitive to.
b86460bf
MD
2490 *
2491 * B_RELBUF may only be set by VFSs. We do set B_AGE to indicate
2492 * that we really want to try to get the buffer out and reuse it
2493 * due to the write load on the machine.
c5724852
MD
2494 *
2495 * We must lock the buffer in order to check its validity before we
e11efbb3 2496 * can mess with its contents. spin isn't enough.
984263bc 2497 */
984263bc 2498static int
a447ba19 2499flushbufqueues(struct buf *marker, bufq_type_t q)
984263bc 2500{
e11efbb3 2501 struct bufpcpu *pcpu;
984263bc
MD
2502 struct buf *bp;
2503 int r = 0;
e11efbb3 2504 int lcpu = marker->b_qcpu;
c3d1e862 2505
a447ba19
MD
2506 KKASSERT(marker->b_qindex == BQUEUE_NONE);
2507 KKASSERT(marker->b_flags & B_MARKER);
2508
e11efbb3 2509again:
a447ba19
MD
2510 /*
2511 * Spinlock needed to perform operations on the queue and may be
2512 * held through a non-blocking BUF_LOCK(), but cannot be held when
2513 * BUF_UNLOCK()ing or through any other major operation.
2514 */
e11efbb3
MD
2515 pcpu = &bufpcpu[marker->b_qcpu];
2516 spin_lock(&pcpu->spin);
a447ba19 2517 marker->b_qindex = q;
e11efbb3 2518 TAILQ_INSERT_HEAD(&pcpu->bufqueues[q], marker, b_freelist);
a447ba19 2519 bp = marker;
984263bc 2520
a447ba19
MD
2521 while ((bp = TAILQ_NEXT(bp, b_freelist)) != NULL) {
2522 /*
2523 * NOTE: spinlock is always held at the top of the loop
2524 */
2525 if (bp->b_flags & B_MARKER)
2526 continue;
c5724852
MD
2527 if ((bp->b_flags & B_DELWRI) == 0) {
2528 kprintf("Unexpected clean buffer %p\n", bp);
c5724852
MD
2529 continue;
2530 }
a447ba19 2531 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
c5724852 2532 continue;
e11efbb3 2533 KKASSERT(bp->b_qcpu == marker->b_qcpu && bp->b_qindex == q);
b86460bf 2534
a447ba19
MD
2535 /*
2536 * Once the buffer is locked we will have no choice but to
2537 * unlock the spinlock around a later BUF_UNLOCK and re-set
2538 * bp = marker when looping. Move the marker now to make
2539 * things easier.
2540 */
e11efbb3
MD
2541 TAILQ_REMOVE(&pcpu->bufqueues[q], marker, b_freelist);
2542 TAILQ_INSERT_AFTER(&pcpu->bufqueues[q], bp, marker, b_freelist);
a447ba19 2543
c5724852
MD
2544 /*
2545 * Must recheck B_DELWRI after successfully locking
2546 * the buffer.
2547 */
2548 if ((bp->b_flags & B_DELWRI) == 0) {
e11efbb3 2549 spin_unlock(&pcpu->spin);
c5724852 2550 BUF_UNLOCK(bp);
e11efbb3 2551 spin_lock(&pcpu->spin);
a447ba19 2552 bp = marker;
c5724852
MD
2553 continue;
2554 }
6f68d895 2555
a447ba19
MD
2556 /*
2557 * Remove the buffer from its queue. We still own the
2558 * spinlock here.
2559 */
2560 _bremfree(bp);
2561
2562 /*
2563 * Disposing of an invalid buffer counts as a flush op
2564 */
c5724852 2565 if (bp->b_flags & B_INVAL) {
e11efbb3 2566 spin_unlock(&pcpu->spin);
c5724852 2567 brelse(bp);
e11efbb3 2568 spin_lock(&pcpu->spin);
c5724852
MD
2569 ++r;
2570 break;
984263bc 2571 }
c5724852 2572
a447ba19
MD
2573 /*
2574 * Release the spinlock for the more complex ops we
2575 * are now going to do.
2576 */
e11efbb3 2577 spin_unlock(&pcpu->spin);
fc9ed34d 2578 lwkt_yield();
8bbb2fba 2579
a447ba19
MD
2580 /*
2581 * This is a bit messy
2582 */
c5724852
MD
2583 if (LIST_FIRST(&bp->b_dep) != NULL &&
2584 (bp->b_flags & B_DEFERRED) == 0 &&
2585 buf_countdeps(bp, 0)) {
e11efbb3
MD
2586 spin_lock(&pcpu->spin);
2587 TAILQ_INSERT_TAIL(&pcpu->bufqueues[q], bp, b_freelist);
a447ba19 2588 bp->b_qindex = q;
c5724852 2589 bp->b_flags |= B_DEFERRED;
e11efbb3 2590 spin_unlock(&pcpu->spin);
c5724852 2591 BUF_UNLOCK(bp);
e11efbb3 2592 spin_lock(&pcpu->spin);
a447ba19 2593 bp = marker;
c5724852
MD
2594 continue;
2595 }
2596
2597 /*
a447ba19
MD
2598 * spinlock not held here.
2599 *
c5724852
MD
2600 * If the buffer has a dependancy, buf_checkwrite() must
2601 * also return 0 for us to be able to initate the write.
2602 *
2603 * If the buffer is flagged B_ERROR it may be requeued
2604 * over and over again, we try to avoid a live lock.
c5724852 2605 */
c5724852 2606 if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
c5724852
MD
2607 brelse(bp);
2608 } else if (bp->b_flags & B_ERROR) {
2609 tsleep(bp, 0, "bioer", 1);
2610 bp->b_flags &= ~B_AGE;
9de13b88 2611 cluster_awrite(bp);
c5724852
MD
2612 } else {
2613 bp->b_flags |= B_AGE;
9de13b88 2614 cluster_awrite(bp);
c5724852 2615 }
e11efbb3 2616 spin_lock(&pcpu->spin);
c5724852
MD
2617 ++r;
2618 break;
984263bc 2619 }
e11efbb3
MD
2620
2621 TAILQ_REMOVE(&pcpu->bufqueues[q], marker, b_freelist);
a447ba19 2622 marker->b_qindex = BQUEUE_NONE;
e11efbb3
MD
2623 spin_unlock(&pcpu->spin);
2624
2625 /*
2626 * Advance the marker to be fair.
2627 */
2628 marker->b_qcpu = (marker->b_qcpu + 1) % ncpus;
2629 if (bp == NULL) {
2630 if (marker->b_qcpu != lcpu)
2631 goto again;
2632 }
a447ba19 2633
984263bc
MD
2634 return (r);
2635}
2636
984263bc 2637/*
3f779080
HP
2638 * inmem:
2639 *
2640 * Returns true if no I/O is needed to access the associated VM object.
1f1ea522 2641 * This is like findblk except it also hunts around in the VM system for
3f779080 2642 * the data.
06ecca5a 2643 *
3f779080
HP
2644 * Note that we ignore vm_page_free() races from interrupts against our
2645 * lookup, since if the caller is not protected our return value will not
2646 * be any more valid then otherwise once we exit the critical section.
984263bc 2647 */
984263bc 2648int
54078292 2649inmem(struct vnode *vp, off_t loffset)
984263bc
MD
2650{
2651 vm_object_t obj;
2652 vm_offset_t toff, tinc, size;
2653 vm_page_t m;
b12defdc 2654 int res = 1;
984263bc 2655
b1c20cfa 2656 if (findblk(vp, loffset, FINDBLK_TEST))
984263bc
MD
2657 return 1;
2658 if (vp->v_mount == NULL)
2659 return 0;
7540ab49
MD
2660 if ((obj = vp->v_object) == NULL)
2661 return 0;
984263bc
MD
2662
2663 size = PAGE_SIZE;
2664 if (size > vp->v_mount->mnt_stat.f_iosize)
2665 size = vp->v_mount->mnt_stat.f_iosize;
984263bc 2666
b12defdc 2667 vm_object_hold(obj);
984263bc 2668 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
54078292 2669 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
b12defdc
MD
2670 if (m == NULL) {
2671 res = 0;
2672 break;
2673 }
984263bc 2674 tinc = size;
54078292
MD
2675 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2676 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
984263bc 2677 if (vm_page_is_valid(m,
b12defdc
MD
2678 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0) {
2679 res = 0;
2680 break;
2681 }
984263bc 2682 }
b12defdc
MD
2683 vm_object_drop(obj);
2684 return (res);
984263bc
MD
2685}
2686
1f1ea522
MD
2687/*
2688 * findblk:
2689 *
b1c20cfa
MD
2690 * Locate and return the specified buffer. Unless flagged otherwise,
2691 * a locked buffer will be returned if it exists or NULL if it does not.
0202303b 2692 *
ae8e83e6
MD
2693 * findblk()'d buffers are still on the bufqueues and if you intend
2694 * to use your (locked NON-TEST) buffer you need to bremfree(bp)
2695 * and possibly do other stuff to it.
2696 *
b1c20cfa
MD
2697 * FINDBLK_TEST - Do not lock the buffer. The caller is responsible
2698 * for locking the buffer and ensuring that it remains
2699 * the desired buffer after locking.
0202303b 2700 *
b1c20cfa
MD
2701 * FINDBLK_NBLOCK - Lock the buffer non-blocking. If we are unable
2702 * to acquire the lock we return NULL, even if the
2703 * buffer exists.
2704 *
283b9448
MD
2705 * FINDBLK_REF - Returns the buffer ref'd, which prevents normal
2706 * reuse by getnewbuf() but does not prevent
2707 * disassociation (B_INVAL). Used to avoid deadlocks
77912481
MD
2708 * against random (vp,loffset)s due to reassignment.
2709 *
c0885fab 2710 * (0) - Lock the buffer blocking.
1f1ea522
MD
2711 */
2712struct buf *
b1c20cfa 2713findblk(struct vnode *vp, off_t loffset, int flags)
1f1ea522
MD
2714{
2715 struct buf *bp;
b1c20cfa
MD
2716 int lkflags;
2717
2718 lkflags = LK_EXCLUSIVE;
2719 if (flags & FINDBLK_NBLOCK)
2720 lkflags |= LK_NOWAIT;
1f1ea522 2721
b1c20cfa 2722 for (;;) {
77912481
MD
2723 /*
2724 * Lookup. Ref the buf while holding v_token to prevent
2725 * reuse (but does not prevent diassociation).
2726 */
54341a3b 2727 lwkt_gettoken_shared(&vp->v_token);
b1c20cfa 2728 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
77912481
MD
2729 if (bp == NULL) {
2730 lwkt_reltoken(&vp->v_token);
2731 return(NULL);
2732 }
283b9448 2733 bqhold(bp);
3b998fa9 2734 lwkt_reltoken(&vp->v_token);
77912481
MD
2735
2736 /*
2737 * If testing only break and return bp, do not lock.
2738 */
2739 if (flags & FINDBLK_TEST)
b1c20cfa 2740 break;
77912481
MD
2741
2742 /*
2743 * Lock the buffer, return an error if the lock fails.
2744 * (only FINDBLK_NBLOCK can cause the lock to fail).
2745 */
c0885fab 2746 if (BUF_LOCK(bp, lkflags)) {
77912481
MD
2747 atomic_subtract_int(&bp->b_refs, 1);
2748 /* bp = NULL; not needed */
2749 return(NULL);
b1c20cfa 2750 }
77912481
MD
2751
2752 /*
2753 * Revalidate the locked buf before allowing it to be
2754 * returned.
2755 */
b1c20cfa
MD
2756 if (bp->b_vp == vp && bp->b_loffset == loffset)
2757 break;
77912481 2758 atomic_subtract_int(&bp->b_refs, 1);
b1c20cfa
MD
2759 BUF_UNLOCK(bp);
2760 }
77912481
MD
2761
2762 /*
2763 * Success
2764 */
2765 if ((flags & FINDBLK_REF) == 0)
2766 atomic_subtract_int(&bp->b_refs, 1);
1f1ea522
MD
2767 return(bp);
2768}
2769
c0885fab
MD
2770/*
2771 * getcacheblk:
2772 *
2773 * Similar to getblk() except only returns the buffer if it is
2774 * B_CACHE and requires no other manipulation. Otherwise NULL
65ec5030
MD
2775 * is returned. NULL is also returned if GETBLK_NOWAIT is set
2776 * and the getblk() would block.
c0885fab
MD
2777 *
2778 * If B_RAM is set the buffer might be just fine, but we return
2779 * NULL anyway because we want the code to fall through to the
cb1fa82f 2780 * cluster read to issue more read-aheads. Otherwise read-ahead breaks.
72d6a027
MD
2781 *
2782 * If blksize is 0 the buffer cache buffer must already be fully
2783 * cached.
2784 *
2785 * If blksize is non-zero getblk() will be used, allowing a buffer
2786 * to be reinstantiated from its VM backing store. The buffer must
2787 * still be fully cached after reinstantiation to be returned.
c0885fab
MD
2788 */
2789struct buf *
9de13b88 2790getcacheblk(struct vnode *vp, off_t loffset, int blksize, int blkflags)
c0885fab
MD
2791{
2792 struct buf *bp;
9de13b88 2793 int fndflags = (blkflags & GETBLK_NOWAIT) ? FINDBLK_NBLOCK : 0;
c0885fab 2794
72d6a027 2795 if (blksize) {
9de13b88 2796 bp = getblk(vp, loffset, blksize, blkflags, 0);
72d6a027 2797 if (bp) {
cb1fa82f 2798 if ((bp->b_flags & (B_INVAL | B_CACHE)) == B_CACHE) {
72d6a027 2799 bp->b_flags &= ~B_AGE;
cb1fa82f
MD
2800 if (bp->b_flags & B_RAM) {
2801 bqrelse(bp);
2802 bp = NULL;
2803 }
72d6a027
MD
2804 } else {
2805 brelse(bp);
2806 bp = NULL;
2807 }
2808 }
2809 } else {
9de13b88 2810 bp = findblk(vp, loffset, fndflags);
72d6a027
MD
2811 if (bp) {
2812 if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) ==
2813 B_CACHE) {
2814 bp->b_flags &= ~B_AGE;
2815 bremfree(bp);
2816 } else {
2817 BUF_UNLOCK(bp);
2818 bp = NULL;
2819 }
c0885fab
MD
2820 }
2821 }
2822 return (bp);
2823}
2824
984263bc 2825/*
3f779080 2826 * getblk:
984263bc
MD
2827 *
2828 * Get a block given a specified block and offset into a file/device.
10f3fee5
MD
2829 * B_INVAL may or may not be set on return. The caller should clear
2830 * B_INVAL prior to initiating a READ.
984263bc 2831 *
77bb9400
MD
2832 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2833 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2834 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2835 * without doing any of those things the system will likely believe
2836 * the buffer to be valid (especially if it is not B_VMIO), and the
2837 * next getblk() will return the buffer with B_CACHE set.
2838 *
984263bc
MD
2839 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2840 * an existing buffer.
2841 *
2842 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2843 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2844 * and then cleared based on the backing VM. If the previous buffer is
2845 * non-0-sized but invalid, B_CACHE will be cleared.
2846 *
2847 * If getblk() must create a new buffer, the new buffer is returned with
2848 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2849 * case it is returned with B_INVAL clear and B_CACHE set based on the
2850 * backing VM.
2851 *
62cfda27 2852 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
984263bc
MD
2853 * B_CACHE bit is clear.
2854 *
2855 * What this means, basically, is that the caller should use B_CACHE to
2856 * determine whether the buffer is fully valid or not and should clear
2857 * B_INVAL prior to issuing a read. If the caller intends to validate
2858 * the buffer by loading its data area with something, the caller needs
2859 * to clear B_INVAL. If the caller does this without issuing an I/O,
2860 * the caller should set B_CACHE ( as an optimization ), else the caller
2861 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2862 * a write attempt or if it was a successfull read. If the caller
2863 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2864 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
4b958e7b
MD
2865 *
2866 * getblk flags:
2867 *
2868 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2869 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
984263bc
MD
2870 */
2871struct buf *
4b958e7b 2872getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
984263bc
MD
2873{
2874 struct buf *bp;
4b958e7b 2875 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
e92ca23a 2876 int error;
b1c20cfa 2877 int lkflags;
984263bc
MD
2878
2879 if (size > MAXBSIZE)
fc92d4aa 2880 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
7540ab49
MD
2881 if (vp->v_object == NULL)
2882 panic("getblk: vnode %p has no object!", vp);
984263bc 2883
984263bc 2884loop:
77912481 2885 if ((bp = findblk(vp, loffset, FINDBLK_REF | FINDBLK_TEST)) != NULL) {
984263bc 2886 /*
a0da602d 2887 * The buffer was found in the cache, but we need to lock it.
77912481
MD
2888 * We must acquire a ref on the bp to prevent reuse, but
2889 * this will not prevent disassociation (brelvp()) so we
2890 * must recheck (vp,loffset) after acquiring the lock.
2891 *
2892 * Without the ref the buffer could potentially be reused
2893 * before we acquire the lock and create a deadlock
2894 * situation between the thread trying to reuse the buffer
2895 * and us due to the fact that we would wind up blocking
2896 * on a random (vp,loffset).
984263bc 2897 */
984263bc 2898 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
77912481 2899 if (blkflags & GETBLK_NOWAIT) {
283b9448 2900 bqdrop(bp);
b77cfc40 2901 return(NULL);
77912481 2902 }
b1c20cfa 2903 lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
4b958e7b 2904 if (blkflags & GETBLK_PCATCH)
f2770c70 2905 lkflags |= LK_PCATCH;
e92ca23a
MD
2906 error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2907 if (error) {
283b9448 2908 bqdrop(bp);
e92ca23a
MD
2909 if (error == ENOLCK)
2910 goto loop;
e92ca23a 2911 return (NULL);
f2770c70 2912 }
b1c20cfa 2913 /* buffer may have changed on us */
984263bc 2914 }
283b9448 2915 bqdrop(bp);
984263bc 2916
a0da602d
MD
2917 /*
2918 * Once the buffer has been locked, make sure we didn't race
2919 * a buffer recyclement. Buffers that are no longer hashed
2920 * will have b_vp == NULL, so this takes care of that check
2921 * as well.
2922 */
54078292 2923 if (bp->b_vp != vp || bp->b_loffset != loffset) {
b1969588 2924#if 0
973c11b9
MD
2925 kprintf("Warning buffer %p (vp %p loffset %lld) "
2926 "was recycled\n",
2927 bp, vp, (long long)loffset);
b1969588 2928#endif
a9518ecf 2929 BUF_UNLOCK(bp);
a0da602d
MD
2930 goto loop;
2931 }
2932
b77cfc40
MD
2933 /*
2934 * If SZMATCH any pre-existing buffer must be of the requested
2935 * size or NULL is returned. The caller absolutely does not
2936 * want getblk() to bwrite() the buffer on a size mismatch.
2937 */
2938 if ((blkflags & GETBLK_SZMATCH) && size != bp->b_bcount) {
2939 BUF_UNLOCK(bp);
b77cfc40
MD
2940 return(NULL);
2941 }
2942
4baec531
MD
2943 /*
2944 * All vnode-based buffers must be backed by a VM object.
2945 */
2946 KKASSERT(bp->b_flags & B_VMIO);
10f3fee5 2947 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
b86460bf 2948 bp->b_flags &= ~B_AGE;
4baec531 2949
a0da602d
MD
2950 /*
2951 * Make sure that B_INVAL buffers do not have a cached
2952 * block number translation.
2953 */
54078292 2954 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
973c11b9
MD
2955 kprintf("Warning invalid buffer %p (vp %p loffset %lld)"
2956 " did not have cleared bio_offset cache\n",
2957 bp, vp, (long long)loffset);
81b5c339 2958 clearbiocache(&bp->b_bio2);
a0da602d
MD
2959 }
2960
984263bc
MD
2961 /*
2962 * The buffer is locked. B_CACHE is cleared if the buffer is
4baec531 2963 * invalid.
984263bc
MD
2964 */
2965 if (bp->b_flags & B_INVAL)
2966 bp->b_flags &= ~B_CACHE;
984263bc
MD
2967 bremfree(bp);
2968
2969 /*
4baec531
MD
2970 * Any size inconsistancy with a dirty buffer or a buffer
2971 * with a softupdates dependancy must be resolved. Resizing
2972 * the buffer in such circumstances can lead to problems.
cb1cf930
MD
2973 *
2974 * Dirty or dependant buffers are written synchronously.
2975 * Other types of buffers are simply released and
2976 * reconstituted as they may be backed by valid, dirty VM
2977 * pages (but not marked B_DELWRI).
2978 *
2979 * NFS NOTE: NFS buffers which straddle EOF are oddly-sized
2980 * and may be left over from a prior truncation (and thus
2981 * no longer represent the actual EOF point), so we
2982 * definitely do not want to B_NOCACHE the backing store.
984263bc 2983 */
4baec531
MD
2984 if (size != bp->b_bcount) {
2985 if (bp->b_flags & B_DELWRI) {
cb1cf930 2986 bp->b_flags |= B_RELBUF;
62cfda27 2987 bwrite(bp);
4baec531 2988 } else if (LIST_FIRST(&bp->b_dep)) {
cb1cf930 2989 bp->b_flags |= B_RELBUF;
62cfda27 2990 bwrite(bp);
4baec531
MD
2991 } else {
2992 bp->b_flags |= B_RELBUF;
2993 brelse(bp);
984263bc 2994 }
4baec531 2995 goto loop;
984263bc 2996 }
4baec531 2997 KKASSERT(size <= bp->b_kvasize);
81b5c339
MD
2998 KASSERT(bp->b_loffset != NOOFFSET,
2999 ("getblk: no buffer offset"));
984263bc
MD
3000
3001 /*
3002 * A buffer with B_DELWRI set and B_CACHE clear must
3003 * be committed before we can return the buffer in
3004 * order to prevent the caller from issuing a read
3005 * ( due to B_CACHE not being set ) and overwriting
3006 * it.
3007 *
3008 * Most callers, including NFS and FFS, need this to
3009 * operate properly either because they assume they
3010 * can issue a read if B_CACHE is not set, or because
3011 * ( for example ) an uncached B_DELWRI might loop due
3012 * to softupdates re-dirtying the buffer. In the latter
3013 * case, B_CACHE is set after the first write completes,
3014 * preventing further loops.
3015 *
3016 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3017 * above while extending the buffer, we cannot allow the
3018 * buffer to remain with B_CACHE set after the write
3019 * completes or it will represent a corrupt state. To
3020 * deal with this we set B_NOCACHE to scrap the buffer
3021 * after the write.
3022 *
cb1cf930
MD
3023 * XXX Should this be B_RELBUF instead of B_NOCACHE?
3024 * I'm not even sure this state is still possible
3025 * now that getblk() writes out any dirty buffers
3026 * on size changes.
3027 *
984263bc
MD
3028 * We might be able to do something fancy, like setting
3029 * B_CACHE in bwrite() except if B_DELWRI is already set,
3030 * so the below call doesn't set B_CACHE, but that gets real
3031 * confusing. This is much easier.
3032 */
3033
3034 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
cb1cf930
MD
3035 kprintf("getblk: Warning, bp %p loff=%jx DELWRI set "
3036 "and CACHE clear, b_flags %08x\n",
1b17efad 3037 bp, (uintmax_t)bp->b_loffset, bp->b_flags);
984263bc 3038 bp->b_flags |= B_NOCACHE;
62cfda27 3039 bwrite(bp);
984263bc
MD
3040 goto loop;
3041 }
984263bc
MD
3042 } else {
3043 /*
3044 * Buffer is not in-core, create new buffer. The buffer
3045 * returned by getnewbuf() is locked. Note that the returned
3046 * buffer is also considered valid (not marked B_INVAL).
21ab32bd
MD
3047 *
3048 * Calculating the offset for the I/O requires figuring out
3049 * the block size. We use DEV_BSIZE for VBLK or VCHR and
3050 * the mount's f_iosize otherwise. If the vnode does not
3051 * have an associated mount we assume that the passed size is
3052 * the block size.
3053 *
3054 * Note that vn_isdisk() cannot be used here since it may
3055 * return a failure for numerous reasons. Note that the
3056 * buffer size may be larger then the block size (the caller
3057 * will use block numbers with the proper multiple). Beware
3058 * of using any v_* fields which are part of unions. In
3059 * particular, in DragonFly the mount point overloading
1d505369
MD
3060 * mechanism uses the namecache only and the underlying
3061 * directory vnode is not a special case.
984263bc 3062 */
7540ab49 3063 int bsize, maxsize;
984263bc 3064
21ab32bd 3065 if (vp->v_type == VBLK || vp->v_type == VCHR)
984263bc 3066 bsize = DEV_BSIZE;
984263bc
MD
3067 else if (vp->v_mount)
3068 bsize = vp->v_mount->mnt_stat.f_iosize;
3069 else
3070 bsize = size;
3071
7540ab49 3072 maxsize = size + (loffset & PAGE_MASK);
984263bc
MD
3073 maxsize = imax(maxsize, bsize);
3074
b1c20cfa
MD
3075 bp = getnewbuf(blkflags, slptimeo, size, maxsize);
3076 if (bp == NULL) {
3077 if (slpflags || slptimeo)
984263bc 3078 return NULL;
984263bc
MD
3079 goto loop;
3080 }
3081
3082 /*
b1c20cfa
MD
3083 * Atomically insert the buffer into the hash, so that it can
3084 * be found by findblk().
3085 *
3086 * If bgetvp() returns non-zero a collision occured, and the
3087 * bp will not be associated with the vnode.
1f1ea522
MD
3088 *
3089 * Make sure the translation layer has been cleared.
984263bc 3090 */
54078292
MD
3091 bp->b_loffset = loffset;
3092 bp->b_bio2.bio_offset = NOOFFSET;
1f1ea522 3093 /* bp->b_bio2.bio_next = NULL; */
984263bc 3094
7608650f 3095 if (bgetvp(vp, bp, size)) {
b1c20cfa
MD
3096 bp->b_flags |= B_INVAL;
3097 brelse(bp);
3098 goto loop;
3099 }
984263bc
MD
3100
3101 /*
4baec531 3102 * All vnode-based buffers must be backed by a VM object.
984263bc 3103 */
4baec531
MD
3104 KKASSERT(vp->v_object != NULL);
3105 bp->b_flags |= B_VMIO;
10f3fee5 3106 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
984263bc
MD
3107
3108 allocbuf(bp, size);
984263bc
MD
3109 }
3110 return (bp);
3111}
3112
5e23ca53
MD
3113/*
3114 * regetblk(bp)
3115 *
27bc0cb1
MD
3116 * Reacquire a buffer that was previously released to the locked queue,
3117 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
3118 * set B_LOCKED (which handles the acquisition race).
5e23ca53 3119 *
27bc0cb1
MD
3120 * To this end, either B_LOCKED must be set or the dependancy list must be
3121 * non-empty.
5e23ca53
MD
3122 */
3123void
3124regetblk(struct buf *bp)
3125{
27bc0cb1 3126 KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
5e23ca53 3127 BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
5e23ca53 3128 bremfree(bp);
5e23ca53
MD
3129}
3130
984263bc 3131/*
3f779080
HP
3132 * geteblk:
3133 *
3134 * Get an empty, disassociated buffer of given size. The buffer is
3135 * initially set to B_INVAL.
06ecca5a 3136 *
3f779080
HP
3137 * critical section protection is not required for the allocbuf()
3138 * call because races are impossible here.
984263bc
MD
3139 */
3140struct buf *
3141geteblk(int size)
3142{
3143 struct buf *bp;
984263bc
MD
3144 int maxsize;
3145
3146 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3147
4090d6ff 3148 while ((bp = getnewbuf(0, 0, size, maxsize)) == NULL)
e43a034f 3149 ;
984263bc
MD
3150 allocbuf(bp, size);
3151 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3152 return (bp);
3153}
3154
3155
3156/*
3f779080 3157 * allocbuf:
984263bc 3158 *
3f779080
HP
3159 * This code constitutes the buffer memory from either anonymous system
3160 * memory (in the case of non-VMIO operations) or from an associated
3161 * VM object (in the case of VMIO operations). This code is able to
3162 * resize a buffer up or down.
984263bc 3163 *
3f779080
HP
3164 * Note that this code is tricky, and has many complications to resolve
3165 * deadlock or inconsistant data situations. Tread lightly!!!
3166 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
77912481
MD
3167 * the caller. Calling this code willy nilly can result in the loss of
3168 * data.
06ecca5a 3169 *
3f779080
HP
3170 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3171 * B_CACHE for the non-VMIO case.
3172 *
3173 * This routine does not need to be called from a critical section but you
3174 * must own the buffer.
984263bc 3175 */
984263bc
MD
3176int
3177allocbuf(struct buf *bp, int size)
3178{
3179 int newbsize, mbsize;
3180 int i;
3181
3182 if (BUF_REFCNT(bp) == 0)
3183 panic("allocbuf: buffer not busy");
3184
3185 if (bp->b_kvasize < size)
3186 panic("allocbuf: buffer too small");
3187
3188 if ((bp->b_flags & B_VMIO) == 0) {
3189 caddr_t origbuf;
3190 int origbufsize;
3191 /*
3192 * Just get anonymous memory from the kernel. Don't
3193 * mess with B_CACHE.
3194 */
965b839f 3195 mbsize = roundup2(size, DEV_BSIZE);
984263bc
MD
3196 if (bp->b_flags & B_MALLOC)
3197 newbsize = mbsize;
3198 else
984263bc
MD
3199 newbsize = round_page(size);
3200
3201 if (newbsize < bp->b_bufsize) {
984263bc 3202 /*
312dcd01 3203 * Malloced buffers are not shrunk
984263bc
MD
3204 */
3205 if (bp->b_flags & B_MALLOC) {
3206 if (newbsize) {
3207 bp->b_bcount = size;
3208 } else {
efda3bd0 3209 kfree(bp->b_data, M_BIOBUF);
984263bc 3210 if (bp->b_bufsize) {
3583bbb4 3211 atomic_subtract_long(&bufmallocspace, bp->b_bufsize);
984263bc
MD
3212 bufspacewakeup();
3213 bp->b_bufsize = 0;
3214 }
3215 bp->b_data = bp->b_kvabase;
3216 bp->b_bcount = 0;
3217 bp->b_flags &= ~B_MALLOC;
3218 }
3219 return 1;
3220 }
984263bc
MD
3221 vm_hold_free_pages(
3222 bp,
3223 (vm_offset_t) bp->b_data + newbsize,
3224 (vm_offset_t) bp->b_data + bp->b_bufsize);
3225 } else if (newbsize > bp->b_bufsize) {
984263bc
MD
3226 /*
3227 * We only use malloced memory on the first allocation.
3228 * and revert to page-allocated memory when the buffer
3229 * grows.
3230 */
4baec531 3231 if ((bufmallocspace < maxbufmallocspace) &&
984263bc
MD
3232 (bp->b_bufsize == 0) &&
3233 (mbsize <= PAGE_SIZE/2)) {
3234
efda3bd0 3235 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
984263bc
MD
3236 bp->b_bufsize = mbsize;
3237 bp->b_bcount = size;
3238 bp->b_flags |= B_MALLOC;
3583bbb4 3239 atomic_add_long(&bufmallocspace, mbsize);
984263bc
MD
3240 return 1;
3241 }
984263bc
MD
3242 origbuf = NULL;
3243 origbufsize = 0;
984263bc 3244 /*
4baec531
MD
3245 * If the buffer is growing on its other-than-first
3246 * allocation, then we revert to the page-allocation
3247 * scheme.
984263bc
MD
3248 */
3249 if (bp->b_flags & B_MALLOC) {
3250 origbuf = bp->b_data;
3251 origbufsize = bp->b_bufsize;
3252 bp->b_data = bp->b_kvabase;
3253 if (bp->b_bufsize) {
3583bbb4
MD
3254 atomic_subtract_long(&bufmallocspace,
3255 bp->b_bufsize);
984263bc
MD
3256 bufspacewakeup();
3257 bp->b_bufsize = 0;
3258 }
3259 bp->b_flags &= ~B_MALLOC;
3260 newbsize = round_page(newbsize);
3261 }
984263bc
MD
3262 vm_hold_load_pages(
3263 bp,
3264 (vm_offset_t) bp->b_data + bp->b_bufsize,
3265 (vm_offset_t) bp->b_data + newbsize);
984263bc
MD
3266 if (origbuf) {
3267 bcopy(origbuf, bp->b_data, origbufsize);
efda3bd0 3268 kfree(origbuf, M_BIOBUF);
984263bc 3269 }
984263bc
MD
3270 }
3271 } else {
3272 vm_page_t m;
3273 int desiredpages;
3274
965b839f 3275 newbsize = roundup2(size, DEV_BSIZE);
4baec531
MD
3276 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
3277 newbsize + PAGE_MASK) >> PAGE_SHIFT;
3278 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
984263bc 3279
984263bc
MD
3280 if (bp->b_flags & B_MALLOC)
3281 panic("allocbuf: VMIO buffer can't be malloced");
984263bc
MD
3282 /*
3283 * Set B_CACHE initially if buffer is 0 length or will become
3284 * 0-length.
3285 */
3286 if (size == 0 || bp->b_bufsize == 0)
3287 bp->b_flags |= B_CACHE;
3288
3289 if (newbsize < bp->b_bufsize) {
3290 /*
3291 * DEV_BSIZE aligned new buffer size is less then the
3292 * DEV_BSIZE aligned existing buffer size. Figure out
3293 * if we have to remove any pages.
3294 */
54f51aeb
HP
3295 if (desiredpages < bp->b_xio.xio_npages) {
3296 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
984263bc
MD
3297 /*
3298 * the page is not freed here -- it
3299 * is the responsibility of
3300 * vnode_pager_setsize
3301 */
54f51aeb 3302 m = bp->b_xio.xio_pages[i];
984263bc
MD
3303 KASSERT(m != bogus_page,
3304 ("allocbuf: bogus page found"));
b12defdc 3305 vm_page_busy_wait(m, TRUE, "biodep");
54f51aeb 3306 bp->b_xio.xio_pages[i] = NULL;
984263bc 3307 vm_page_unwire(m, 0);
b12defdc 3308 vm_page_wakeup(m);
984263bc
MD
3309 }
3310 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
54f51aeb
HP
3311 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
3312 bp->b_xio.xio_npages = desiredpages;
984263bc
MD
3313 }
3314 } else if (size > bp->b_bcount) {
3315 /*
3316 * We are growing the buffer, possibly in a
3317 * byte-granular fashion.
3318 */
3319 struct vnode *vp;
3320 vm_object_t obj;
3321 vm_offset_t toff;
3322 vm_offset_t tinc;
3323
3324 /*
3325 * Step 1, bring in the VM pages from the object,
3326 * allocating them if necessary. We must clear
3327 * B_CACHE if these pages are not valid for the
3328 * range covered by the buffer.
06ecca5a 3329 *
e43a034f
MD
3330 * critical section protection is required to protect
3331 * against interrupts unbusying and freeing pages
3332 * between our vm_page_lookup() and our
3333 * busycheck/wiring call.
984263bc 3334 */