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