xref: /dflybsd-src/sys/kern/vfs_bio.c (revision 9b42cabedff59ea3b351e8eccb2da9bab5cefe7e)
1 /*
2  * Copyright (c) 1994,1997 John S. Dyson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice immediately at the beginning of the file, without modification,
10  *    this list of conditions, and the following disclaimer.
11  * 2. Absolutely no warranty of function or purpose is made by the author
12  *		John S. Dyson.
13  *
14  * $FreeBSD: src/sys/kern/vfs_bio.c,v 1.242.2.20 2003/05/28 18:38:10 alc Exp $
15  * $DragonFly: src/sys/kern/vfs_bio.c,v 1.110 2008/07/07 17:31:07 dillon Exp $
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>
35 #include <sys/eventhandler.h>
36 #include <sys/lock.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
41 #include <sys/proc.h>
42 #include <sys/reboot.h>
43 #include <sys/resourcevar.h>
44 #include <sys/sysctl.h>
45 #include <sys/vmmeter.h>
46 #include <sys/vnode.h>
47 #include <sys/proc.h>
48 #include <vm/vm.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_pageout.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_map.h>
56 
57 #include <sys/buf2.h>
58 #include <sys/thread2.h>
59 #include <sys/spinlock2.h>
60 #include <vm/vm_page2.h>
61 
62 #include "opt_ddb.h"
63 #ifdef DDB
64 #include <ddb/ddb.h>
65 #endif
66 
67 /*
68  * Buffer queues.
69  */
70 enum bufq_type {
71 	BQUEUE_NONE,    	/* not on any queue */
72 	BQUEUE_LOCKED,  	/* locked buffers */
73 	BQUEUE_CLEAN,   	/* non-B_DELWRI buffers */
74 	BQUEUE_DIRTY,   	/* B_DELWRI buffers */
75 	BQUEUE_DIRTY_HW,   	/* B_DELWRI buffers - heavy weight */
76 	BQUEUE_EMPTYKVA, 	/* empty buffer headers with KVA assignment */
77 	BQUEUE_EMPTY,    	/* empty buffer headers */
78 
79 	BUFFER_QUEUES		/* number of buffer queues */
80 };
81 
82 typedef enum bufq_type bufq_type_t;
83 
84 #define BD_WAKE_SIZE	128
85 #define BD_WAKE_MASK	(BD_WAKE_SIZE - 1)
86 
87 TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES];
88 
89 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
90 
91 struct buf *buf;		/* buffer header pool */
92 
93 static void vm_hold_free_pages(struct buf *bp, vm_offset_t from,
94 		vm_offset_t to);
95 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
96 		vm_offset_t to);
97 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
98 			       int pageno, vm_page_t m);
99 static void vfs_clean_pages(struct buf *bp);
100 static void vfs_setdirty(struct buf *bp);
101 static void vfs_vmio_release(struct buf *bp);
102 static int flushbufqueues(bufq_type_t q);
103 static vm_page_t bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit);
104 
105 static void bd_signal(int totalspace);
106 static void buf_daemon(void);
107 static void buf_daemon_hw(void);
108 
109 /*
110  * bogus page -- for I/O to/from partially complete buffers
111  * this is a temporary solution to the problem, but it is not
112  * really that bad.  it would be better to split the buffer
113  * for input in the case of buffers partially already in memory,
114  * but the code is intricate enough already.
115  */
116 vm_page_t bogus_page;
117 
118 /*
119  * These are all static, but make the ones we export globals so we do
120  * not need to use compiler magic.
121  */
122 int bufspace, maxbufspace,
123 	bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
124 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
125 static int lorunningspace, hirunningspace, runningbufreq;
126 int dirtybufspace, dirtybufspacehw, lodirtybufspace, hidirtybufspace;
127 int dirtybufcount, dirtybufcounthw;
128 int runningbufspace, runningbufcount;
129 static int getnewbufcalls;
130 static int getnewbufrestarts;
131 static int recoverbufcalls;
132 static int needsbuffer;		/* locked by needsbuffer_spin */
133 static int bd_request;		/* locked by needsbuffer_spin */
134 static int bd_request_hw;	/* locked by needsbuffer_spin */
135 static u_int bd_wake_ary[BD_WAKE_SIZE];
136 static u_int bd_wake_index;
137 static struct spinlock needsbuffer_spin;
138 
139 static struct thread *bufdaemon_td;
140 static struct thread *bufdaemonhw_td;
141 
142 
143 /*
144  * Sysctls for operational control of the buffer cache.
145  */
146 SYSCTL_INT(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0,
147 	"Number of dirty buffers to flush before bufdaemon becomes inactive");
148 SYSCTL_INT(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0,
149 	"High watermark used to trigger explicit flushing of dirty buffers");
150 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
151 	"Minimum amount of buffer space required for active I/O");
152 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
153 	"Maximum amount of buffer space to usable for active I/O");
154 /*
155  * Sysctls determining current state of the buffer cache.
156  */
157 SYSCTL_INT(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
158 	"Total number of buffers in buffer cache");
159 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0,
160 	"Pending bytes of dirty buffers (all)");
161 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0,
162 	"Pending bytes of dirty buffers (heavy weight)");
163 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcount, CTLFLAG_RD, &dirtybufcount, 0,
164 	"Pending number of dirty buffers");
165 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcounthw, CTLFLAG_RD, &dirtybufcounthw, 0,
166 	"Pending number of dirty buffers (heavy weight)");
167 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
168 	"I/O bytes currently in progress due to asynchronous writes");
169 SYSCTL_INT(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
170 	"I/O buffers currently in progress due to asynchronous writes");
171 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
172 	"Hard limit on maximum amount of memory usable for buffer space");
173 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
174 	"Soft limit on maximum amount of memory usable for buffer space");
175 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
176 	"Minimum amount of memory to reserve for system buffer space");
177 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
178 	"Amount of memory available for buffers");
179 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
180 	0, "Maximum amount of memory reserved for buffers using malloc");
181 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
182 	"Amount of memory left for buffers using malloc-scheme");
183 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
184 	"New buffer header acquisition requests");
185 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
186 	0, "New buffer header acquisition restarts");
187 SYSCTL_INT(_vfs, OID_AUTO, recoverbufcalls, CTLFLAG_RD, &recoverbufcalls, 0,
188 	"Recover VM space in an emergency");
189 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
190 	"Buffer acquisition restarts due to fragmented buffer map");
191 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
192 	"Amount of time KVA space was deallocated in an arbitrary buffer");
193 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
194 	"Amount of time buffer re-use operations were successful");
195 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
196 	"sizeof(struct buf)");
197 
198 char *buf_wmesg = BUF_WMESG;
199 
200 extern int vm_swap_size;
201 
202 #define VFS_BIO_NEED_ANY	0x01	/* any freeable buffer */
203 #define VFS_BIO_NEED_UNUSED02	0x02
204 #define VFS_BIO_NEED_UNUSED04	0x04
205 #define VFS_BIO_NEED_BUFSPACE	0x08	/* wait for buf space, lo hysteresis */
206 
207 /*
208  * bufspacewakeup:
209  *
210  *	Called when buffer space is potentially available for recovery.
211  *	getnewbuf() will block on this flag when it is unable to free
212  *	sufficient buffer space.  Buffer space becomes recoverable when
213  *	bp's get placed back in the queues.
214  */
215 
216 static __inline void
217 bufspacewakeup(void)
218 {
219 	/*
220 	 * If someone is waiting for BUF space, wake them up.  Even
221 	 * though we haven't freed the kva space yet, the waiting
222 	 * process will be able to now.
223 	 */
224 	if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
225 		spin_lock_wr(&needsbuffer_spin);
226 		needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
227 		spin_unlock_wr(&needsbuffer_spin);
228 		wakeup(&needsbuffer);
229 	}
230 }
231 
232 /*
233  * runningbufwakeup:
234  *
235  *	Accounting for I/O in progress.
236  *
237  */
238 static __inline void
239 runningbufwakeup(struct buf *bp)
240 {
241 	int totalspace;
242 
243 	if ((totalspace = bp->b_runningbufspace) != 0) {
244 		runningbufspace -= totalspace;
245 		--runningbufcount;
246 		bp->b_runningbufspace = 0;
247 		if (runningbufreq && runningbufspace <= lorunningspace) {
248 			runningbufreq = 0;
249 			wakeup(&runningbufreq);
250 		}
251 		bd_signal(totalspace);
252 	}
253 }
254 
255 /*
256  * bufcountwakeup:
257  *
258  *	Called when a buffer has been added to one of the free queues to
259  *	account for the buffer and to wakeup anyone waiting for free buffers.
260  *	This typically occurs when large amounts of metadata are being handled
261  *	by the buffer cache ( else buffer space runs out first, usually ).
262  */
263 
264 static __inline void
265 bufcountwakeup(void)
266 {
267 	if (needsbuffer) {
268 		spin_lock_wr(&needsbuffer_spin);
269 		needsbuffer &= ~VFS_BIO_NEED_ANY;
270 		spin_unlock_wr(&needsbuffer_spin);
271 		wakeup(&needsbuffer);
272 	}
273 }
274 
275 /*
276  * waitrunningbufspace()
277  *
278  * Wait for the amount of running I/O to drop to a reasonable level.
279  *
280  * The caller may be using this function to block in a tight loop, we
281  * must block of runningbufspace is greater then the passed limit.
282  * And even with that it may not be enough, due to the presence of
283  * B_LOCKED dirty buffers, so also wait for at least one running buffer
284  * to complete.
285  */
286 static __inline void
287 waitrunningbufspace(int limit)
288 {
289 	int lorun;
290 
291 	if (lorunningspace < limit)
292 		lorun = lorunningspace;
293 	else
294 		lorun = limit;
295 
296 	crit_enter();
297 	if (runningbufspace > lorun) {
298 		while (runningbufspace > lorun) {
299 			++runningbufreq;
300 			tsleep(&runningbufreq, 0, "wdrain", 0);
301 		}
302 	} else if (runningbufspace) {
303 		++runningbufreq;
304 		tsleep(&runningbufreq, 0, "wdrain2", 1);
305 	}
306 	crit_exit();
307 }
308 
309 /*
310  * vfs_buf_test_cache:
311  *
312  *	Called when a buffer is extended.  This function clears the B_CACHE
313  *	bit if the newly extended portion of the buffer does not contain
314  *	valid data.
315  */
316 static __inline__
317 void
318 vfs_buf_test_cache(struct buf *bp,
319 		  vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
320 		  vm_page_t m)
321 {
322 	if (bp->b_flags & B_CACHE) {
323 		int base = (foff + off) & PAGE_MASK;
324 		if (vm_page_is_valid(m, base, size) == 0)
325 			bp->b_flags &= ~B_CACHE;
326 	}
327 }
328 
329 /*
330  * bd_speedup()
331  *
332  * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the
333  * low water mark.
334  */
335 static __inline__
336 void
337 bd_speedup(void)
338 {
339 	if (dirtybufspace < lodirtybufspace && dirtybufcount < nbuf / 2)
340 		return;
341 
342 	if (bd_request == 0 &&
343 	    (dirtybufspace - dirtybufspacehw > lodirtybufspace / 2 ||
344 	     dirtybufcount - dirtybufcounthw >= nbuf / 2)) {
345 		spin_lock_wr(&needsbuffer_spin);
346 		bd_request = 1;
347 		spin_unlock_wr(&needsbuffer_spin);
348 		wakeup(&bd_request);
349 	}
350 	if (bd_request_hw == 0 &&
351 	    (dirtybufspacehw > lodirtybufspace / 2 ||
352 	     dirtybufcounthw >= nbuf / 2)) {
353 		spin_lock_wr(&needsbuffer_spin);
354 		bd_request_hw = 1;
355 		spin_unlock_wr(&needsbuffer_spin);
356 		wakeup(&bd_request_hw);
357 	}
358 }
359 
360 /*
361  * bd_heatup()
362  *
363  *	Get the buf_daemon heated up when the number of running and dirty
364  *	buffers exceeds the mid-point.
365  */
366 int
367 bd_heatup(void)
368 {
369 	int mid1;
370 	int mid2;
371 	int totalspace;
372 
373 	mid1 = lodirtybufspace + (hidirtybufspace - lodirtybufspace) / 2;
374 
375 	totalspace = runningbufspace + dirtybufspace;
376 	if (totalspace >= mid1 || dirtybufcount >= nbuf / 2) {
377 		bd_speedup();
378 		mid2 = mid1 + (hidirtybufspace - mid1) / 2;
379 		if (totalspace >= mid2)
380 			return(totalspace - mid2);
381 	}
382 	return(0);
383 }
384 
385 /*
386  * bd_wait()
387  *
388  *	Wait for the buffer cache to flush (totalspace) bytes worth of
389  *	buffers, then return.
390  *
391  *	Regardless this function blocks while the number of dirty buffers
392  *	exceeds hidirtybufspace.
393  */
394 void
395 bd_wait(int totalspace)
396 {
397 	u_int i;
398 	int count;
399 
400 	if (curthread == bufdaemonhw_td || curthread == bufdaemon_td)
401 		return;
402 
403 	while (totalspace > 0) {
404 		bd_heatup();
405 		crit_enter();
406 		if (totalspace > runningbufspace + dirtybufspace)
407 			totalspace = runningbufspace + dirtybufspace;
408 		count = totalspace / BKVASIZE;
409 		if (count >= BD_WAKE_SIZE)
410 			count = BD_WAKE_SIZE - 1;
411 		i = (bd_wake_index + count) & BD_WAKE_MASK;
412 		++bd_wake_ary[i];
413 		tsleep(&bd_wake_ary[i], 0, "flstik", hz);
414 		crit_exit();
415 
416 		totalspace = runningbufspace + dirtybufspace - hidirtybufspace;
417 	}
418 }
419 
420 /*
421  * bd_signal()
422  *
423  *	This function is called whenever runningbufspace or dirtybufspace
424  *	is reduced.  Track threads waiting for run+dirty buffer I/O
425  *	complete.
426  */
427 static void
428 bd_signal(int totalspace)
429 {
430 	u_int i;
431 
432 	while (totalspace > 0) {
433 		i = atomic_fetchadd_int(&bd_wake_index, 1);
434 		i &= BD_WAKE_MASK;
435 		if (bd_wake_ary[i]) {
436 			bd_wake_ary[i] = 0;
437 			wakeup(&bd_wake_ary[i]);
438 		}
439 		totalspace -= BKVASIZE;
440 	}
441 }
442 
443 /*
444  * bufinit:
445  *
446  *	Load time initialisation of the buffer cache, called from machine
447  *	dependant initialization code.
448  */
449 void
450 bufinit(void)
451 {
452 	struct buf *bp;
453 	vm_offset_t bogus_offset;
454 	int i;
455 
456 	spin_init(&needsbuffer_spin);
457 
458 	/* next, make a null set of free lists */
459 	for (i = 0; i < BUFFER_QUEUES; i++)
460 		TAILQ_INIT(&bufqueues[i]);
461 
462 	/* finally, initialize each buffer header and stick on empty q */
463 	for (i = 0; i < nbuf; i++) {
464 		bp = &buf[i];
465 		bzero(bp, sizeof *bp);
466 		bp->b_flags = B_INVAL;	/* we're just an empty header */
467 		bp->b_cmd = BUF_CMD_DONE;
468 		bp->b_qindex = BQUEUE_EMPTY;
469 		initbufbio(bp);
470 		xio_init(&bp->b_xio);
471 		buf_dep_init(bp);
472 		BUF_LOCKINIT(bp);
473 		TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
474 	}
475 
476 	/*
477 	 * maxbufspace is the absolute maximum amount of buffer space we are
478 	 * allowed to reserve in KVM and in real terms.  The absolute maximum
479 	 * is nominally used by buf_daemon.  hibufspace is the nominal maximum
480 	 * used by most other processes.  The differential is required to
481 	 * ensure that buf_daemon is able to run when other processes might
482 	 * be blocked waiting for buffer space.
483 	 *
484 	 * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
485 	 * this may result in KVM fragmentation which is not handled optimally
486 	 * by the system.
487 	 */
488 	maxbufspace = nbuf * BKVASIZE;
489 	hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
490 	lobufspace = hibufspace - MAXBSIZE;
491 
492 	lorunningspace = 512 * 1024;
493 	hirunningspace = 1024 * 1024;
494 
495 	/*
496 	 * Limit the amount of malloc memory since it is wired permanently
497 	 * into the kernel space.  Even though this is accounted for in
498 	 * the buffer allocation, we don't want the malloced region to grow
499 	 * uncontrolled.  The malloc scheme improves memory utilization
500 	 * significantly on average (small) directories.
501 	 */
502 	maxbufmallocspace = hibufspace / 20;
503 
504 	/*
505 	 * Reduce the chance of a deadlock occuring by limiting the number
506 	 * of delayed-write dirty buffers we allow to stack up.
507 	 */
508 	hidirtybufspace = hibufspace / 2;
509 	dirtybufspace = 0;
510 	dirtybufspacehw = 0;
511 
512 	lodirtybufspace = hidirtybufspace / 2;
513 
514 	/*
515 	 * Maximum number of async ops initiated per buf_daemon loop.  This is
516 	 * somewhat of a hack at the moment, we really need to limit ourselves
517 	 * based on the number of bytes of I/O in-transit that were initiated
518 	 * from buf_daemon.
519 	 */
520 
521 	bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
522 	bogus_page = vm_page_alloc(&kernel_object,
523 				   (bogus_offset >> PAGE_SHIFT),
524 				   VM_ALLOC_NORMAL);
525 	vmstats.v_wire_count++;
526 
527 }
528 
529 /*
530  * Initialize the embedded bio structures
531  */
532 void
533 initbufbio(struct buf *bp)
534 {
535 	bp->b_bio1.bio_buf = bp;
536 	bp->b_bio1.bio_prev = NULL;
537 	bp->b_bio1.bio_offset = NOOFFSET;
538 	bp->b_bio1.bio_next = &bp->b_bio2;
539 	bp->b_bio1.bio_done = NULL;
540 
541 	bp->b_bio2.bio_buf = bp;
542 	bp->b_bio2.bio_prev = &bp->b_bio1;
543 	bp->b_bio2.bio_offset = NOOFFSET;
544 	bp->b_bio2.bio_next = NULL;
545 	bp->b_bio2.bio_done = NULL;
546 }
547 
548 /*
549  * Reinitialize the embedded bio structures as well as any additional
550  * translation cache layers.
551  */
552 void
553 reinitbufbio(struct buf *bp)
554 {
555 	struct bio *bio;
556 
557 	for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
558 		bio->bio_done = NULL;
559 		bio->bio_offset = NOOFFSET;
560 	}
561 }
562 
563 /*
564  * Push another BIO layer onto an existing BIO and return it.  The new
565  * BIO layer may already exist, holding cached translation data.
566  */
567 struct bio *
568 push_bio(struct bio *bio)
569 {
570 	struct bio *nbio;
571 
572 	if ((nbio = bio->bio_next) == NULL) {
573 		int index = bio - &bio->bio_buf->b_bio_array[0];
574 		if (index >= NBUF_BIO - 1) {
575 			panic("push_bio: too many layers bp %p\n",
576 				bio->bio_buf);
577 		}
578 		nbio = &bio->bio_buf->b_bio_array[index + 1];
579 		bio->bio_next = nbio;
580 		nbio->bio_prev = bio;
581 		nbio->bio_buf = bio->bio_buf;
582 		nbio->bio_offset = NOOFFSET;
583 		nbio->bio_done = NULL;
584 		nbio->bio_next = NULL;
585 	}
586 	KKASSERT(nbio->bio_done == NULL);
587 	return(nbio);
588 }
589 
590 void
591 pop_bio(struct bio *bio)
592 {
593 	/* NOP */
594 }
595 
596 void
597 clearbiocache(struct bio *bio)
598 {
599 	while (bio) {
600 		bio->bio_offset = NOOFFSET;
601 		bio = bio->bio_next;
602 	}
603 }
604 
605 /*
606  * bfreekva:
607  *
608  *	Free the KVA allocation for buffer 'bp'.
609  *
610  *	Must be called from a critical section as this is the only locking for
611  *	buffer_map.
612  *
613  *	Since this call frees up buffer space, we call bufspacewakeup().
614  */
615 static void
616 bfreekva(struct buf *bp)
617 {
618 	int count;
619 
620 	if (bp->b_kvasize) {
621 		++buffreekvacnt;
622 		count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
623 		vm_map_lock(&buffer_map);
624 		bufspace -= bp->b_kvasize;
625 		vm_map_delete(&buffer_map,
626 		    (vm_offset_t) bp->b_kvabase,
627 		    (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
628 		    &count
629 		);
630 		vm_map_unlock(&buffer_map);
631 		vm_map_entry_release(count);
632 		bp->b_kvasize = 0;
633 		bufspacewakeup();
634 	}
635 }
636 
637 /*
638  * bremfree:
639  *
640  *	Remove the buffer from the appropriate free list.
641  */
642 void
643 bremfree(struct buf *bp)
644 {
645 	int old_qindex;
646 
647 	crit_enter();
648 	old_qindex = bp->b_qindex;
649 
650 	if (bp->b_qindex != BQUEUE_NONE) {
651 		KASSERT(BUF_REFCNTNB(bp) == 1,
652 				("bremfree: bp %p not locked",bp));
653 		TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
654 		bp->b_qindex = BQUEUE_NONE;
655 	} else {
656 		if (BUF_REFCNTNB(bp) <= 1)
657 			panic("bremfree: removing a buffer not on a queue");
658 	}
659 
660 	crit_exit();
661 }
662 
663 
664 /*
665  * bread:
666  *
667  *	Get a buffer with the specified data.  Look in the cache first.  We
668  *	must clear B_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
669  *	is set, the buffer is valid and we do not have to do anything ( see
670  *	getblk() ).
671  */
672 int
673 bread(struct vnode *vp, off_t loffset, int size, struct buf **bpp)
674 {
675 	struct buf *bp;
676 
677 	bp = getblk(vp, loffset, size, 0, 0);
678 	*bpp = bp;
679 
680 	/* if not found in cache, do some I/O */
681 	if ((bp->b_flags & B_CACHE) == 0) {
682 		KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
683 		bp->b_flags &= ~(B_ERROR | B_INVAL);
684 		bp->b_cmd = BUF_CMD_READ;
685 		vfs_busy_pages(vp, bp);
686 		vn_strategy(vp, &bp->b_bio1);
687 		return (biowait(bp));
688 	}
689 	return (0);
690 }
691 
692 /*
693  * breadn:
694  *
695  *	Operates like bread, but also starts asynchronous I/O on
696  *	read-ahead blocks.  We must clear B_ERROR and B_INVAL prior
697  *	to initiating I/O . If B_CACHE is set, the buffer is valid
698  *	and we do not have to do anything.
699  */
700 int
701 breadn(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
702 	int *rabsize, int cnt, struct buf **bpp)
703 {
704 	struct buf *bp, *rabp;
705 	int i;
706 	int rv = 0, readwait = 0;
707 
708 	*bpp = bp = getblk(vp, loffset, size, 0, 0);
709 
710 	/* if not found in cache, do some I/O */
711 	if ((bp->b_flags & B_CACHE) == 0) {
712 		bp->b_flags &= ~(B_ERROR | B_INVAL);
713 		bp->b_cmd = BUF_CMD_READ;
714 		vfs_busy_pages(vp, bp);
715 		vn_strategy(vp, &bp->b_bio1);
716 		++readwait;
717 	}
718 
719 	for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
720 		if (inmem(vp, *raoffset))
721 			continue;
722 		rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
723 
724 		if ((rabp->b_flags & B_CACHE) == 0) {
725 			rabp->b_flags |= B_ASYNC;
726 			rabp->b_flags &= ~(B_ERROR | B_INVAL);
727 			rabp->b_cmd = BUF_CMD_READ;
728 			vfs_busy_pages(vp, rabp);
729 			BUF_KERNPROC(rabp);
730 			vn_strategy(vp, &rabp->b_bio1);
731 		} else {
732 			brelse(rabp);
733 		}
734 	}
735 
736 	if (readwait) {
737 		rv = biowait(bp);
738 	}
739 	return (rv);
740 }
741 
742 /*
743  * bwrite:
744  *
745  *	Write, release buffer on completion.  (Done by iodone
746  *	if async).  Do not bother writing anything if the buffer
747  *	is invalid.
748  *
749  *	Note that we set B_CACHE here, indicating that buffer is
750  *	fully valid and thus cacheable.  This is true even of NFS
751  *	now so we set it generally.  This could be set either here
752  *	or in biodone() since the I/O is synchronous.  We put it
753  *	here.
754  */
755 int
756 bwrite(struct buf *bp)
757 {
758 	int oldflags;
759 
760 	if (bp->b_flags & B_INVAL) {
761 		brelse(bp);
762 		return (0);
763 	}
764 
765 	oldflags = bp->b_flags;
766 
767 	if (BUF_REFCNTNB(bp) == 0)
768 		panic("bwrite: buffer is not busy???");
769 	crit_enter();
770 
771 	/* Mark the buffer clean */
772 	bundirty(bp);
773 
774 	bp->b_flags &= ~B_ERROR;
775 	bp->b_flags |= B_CACHE;
776 	bp->b_cmd = BUF_CMD_WRITE;
777 	vfs_busy_pages(bp->b_vp, bp);
778 
779 	/*
780 	 * Normal bwrites pipeline writes.  NOTE: b_bufsize is only
781 	 * valid for vnode-backed buffers.
782 	 */
783 	bp->b_runningbufspace = bp->b_bufsize;
784 	if (bp->b_runningbufspace) {
785 		runningbufspace += bp->b_runningbufspace;
786 		++runningbufcount;
787 	}
788 
789 	crit_exit();
790 	if (oldflags & B_ASYNC)
791 		BUF_KERNPROC(bp);
792 	vn_strategy(bp->b_vp, &bp->b_bio1);
793 
794 	if ((oldflags & B_ASYNC) == 0) {
795 		int rtval = biowait(bp);
796 		brelse(bp);
797 		return (rtval);
798 	}
799 	return (0);
800 }
801 
802 /*
803  * bdwrite:
804  *
805  *	Delayed write. (Buffer is marked dirty).  Do not bother writing
806  *	anything if the buffer is marked invalid.
807  *
808  *	Note that since the buffer must be completely valid, we can safely
809  *	set B_CACHE.  In fact, we have to set B_CACHE here rather then in
810  *	biodone() in order to prevent getblk from writing the buffer
811  *	out synchronously.
812  */
813 void
814 bdwrite(struct buf *bp)
815 {
816 	if (BUF_REFCNTNB(bp) == 0)
817 		panic("bdwrite: buffer is not busy");
818 
819 	if (bp->b_flags & B_INVAL) {
820 		brelse(bp);
821 		return;
822 	}
823 	bdirty(bp);
824 
825 	/*
826 	 * Set B_CACHE, indicating that the buffer is fully valid.  This is
827 	 * true even of NFS now.
828 	 */
829 	bp->b_flags |= B_CACHE;
830 
831 	/*
832 	 * This bmap keeps the system from needing to do the bmap later,
833 	 * perhaps when the system is attempting to do a sync.  Since it
834 	 * is likely that the indirect block -- or whatever other datastructure
835 	 * that the filesystem needs is still in memory now, it is a good
836 	 * thing to do this.  Note also, that if the pageout daemon is
837 	 * requesting a sync -- there might not be enough memory to do
838 	 * the bmap then...  So, this is important to do.
839 	 */
840 	if (bp->b_bio2.bio_offset == NOOFFSET) {
841 		VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
842 			 NULL, NULL, BUF_CMD_WRITE);
843 	}
844 
845 	/*
846 	 * Set the *dirty* buffer range based upon the VM system dirty pages.
847 	 */
848 	vfs_setdirty(bp);
849 
850 	/*
851 	 * We need to do this here to satisfy the vnode_pager and the
852 	 * pageout daemon, so that it thinks that the pages have been
853 	 * "cleaned".  Note that since the pages are in a delayed write
854 	 * buffer -- the VFS layer "will" see that the pages get written
855 	 * out on the next sync, or perhaps the cluster will be completed.
856 	 */
857 	vfs_clean_pages(bp);
858 	bqrelse(bp);
859 
860 	/*
861 	 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
862 	 * due to the softdep code.
863 	 */
864 }
865 
866 /*
867  * bdirty:
868  *
869  *	Turn buffer into delayed write request by marking it B_DELWRI.
870  *	B_RELBUF and B_NOCACHE must be cleared.
871  *
872  *	We reassign the buffer to itself to properly update it in the
873  *	dirty/clean lists.
874  *
875  *	Must be called from a critical section.
876  *	The buffer must be on BQUEUE_NONE.
877  */
878 void
879 bdirty(struct buf *bp)
880 {
881 	KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
882 	if (bp->b_flags & B_NOCACHE) {
883 		kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
884 		bp->b_flags &= ~B_NOCACHE;
885 	}
886 	if (bp->b_flags & B_INVAL) {
887 		kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
888 	}
889 	bp->b_flags &= ~B_RELBUF;
890 
891 	if ((bp->b_flags & B_DELWRI) == 0) {
892 		bp->b_flags |= B_DELWRI;
893 		reassignbuf(bp);
894 		++dirtybufcount;
895 		dirtybufspace += bp->b_bufsize;
896 		if (bp->b_flags & B_HEAVY) {
897 			++dirtybufcounthw;
898 			dirtybufspacehw += bp->b_bufsize;
899 		}
900 		bd_heatup();
901 	}
902 }
903 
904 /*
905  * Set B_HEAVY, indicating that this is a heavy-weight buffer that
906  * needs to be flushed with a different buf_daemon thread to avoid
907  * deadlocks.  B_HEAVY also imposes restrictions in getnewbuf().
908  */
909 void
910 bheavy(struct buf *bp)
911 {
912 	if ((bp->b_flags & B_HEAVY) == 0) {
913 		bp->b_flags |= B_HEAVY;
914 		if (bp->b_flags & B_DELWRI) {
915 			++dirtybufcounthw;
916 			dirtybufspacehw += bp->b_bufsize;
917 		}
918 	}
919 }
920 
921 /*
922  * bundirty:
923  *
924  *	Clear B_DELWRI for buffer.
925  *
926  *	Must be called from a critical section.
927  *
928  *	The buffer is typically on BQUEUE_NONE but there is one case in
929  *	brelse() that calls this function after placing the buffer on
930  *	a different queue.
931  */
932 
933 void
934 bundirty(struct buf *bp)
935 {
936 	if (bp->b_flags & B_DELWRI) {
937 		bp->b_flags &= ~B_DELWRI;
938 		reassignbuf(bp);
939 		--dirtybufcount;
940 		dirtybufspace -= bp->b_bufsize;
941 		if (bp->b_flags & B_HEAVY) {
942 			--dirtybufcounthw;
943 			dirtybufspacehw -= bp->b_bufsize;
944 		}
945 		bd_signal(bp->b_bufsize);
946 	}
947 	/*
948 	 * Since it is now being written, we can clear its deferred write flag.
949 	 */
950 	bp->b_flags &= ~B_DEFERRED;
951 }
952 
953 /*
954  * bawrite:
955  *
956  *	Asynchronous write.  Start output on a buffer, but do not wait for
957  *	it to complete.  The buffer is released when the output completes.
958  *
959  *	bwrite() ( or the VOP routine anyway ) is responsible for handling
960  *	B_INVAL buffers.  Not us.
961  */
962 void
963 bawrite(struct buf *bp)
964 {
965 	bp->b_flags |= B_ASYNC;
966 	bwrite(bp);
967 }
968 
969 /*
970  * bowrite:
971  *
972  *	Ordered write.  Start output on a buffer, and flag it so that the
973  *	device will write it in the order it was queued.  The buffer is
974  *	released when the output completes.  bwrite() ( or the VOP routine
975  *	anyway ) is responsible for handling B_INVAL buffers.
976  */
977 int
978 bowrite(struct buf *bp)
979 {
980 	bp->b_flags |= B_ORDERED | B_ASYNC;
981 	return (bwrite(bp));
982 }
983 
984 /*
985  * buf_dirty_count_severe:
986  *
987  *	Return true if we have too many dirty buffers.
988  */
989 int
990 buf_dirty_count_severe(void)
991 {
992 	return (runningbufspace + dirtybufspace >= hidirtybufspace ||
993 	        dirtybufcount >= nbuf / 2);
994 }
995 
996 /*
997  * brelse:
998  *
999  *	Release a busy buffer and, if requested, free its resources.  The
1000  *	buffer will be stashed in the appropriate bufqueue[] allowing it
1001  *	to be accessed later as a cache entity or reused for other purposes.
1002  */
1003 void
1004 brelse(struct buf *bp)
1005 {
1006 #ifdef INVARIANTS
1007 	int saved_flags = bp->b_flags;
1008 #endif
1009 
1010 	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1011 
1012 	crit_enter();
1013 
1014 	/*
1015 	 * If B_NOCACHE is set we are being asked to destroy the buffer and
1016 	 * its backing store.  Clear B_DELWRI.
1017 	 *
1018 	 * B_NOCACHE is set in two cases: (1) when the caller really wants
1019 	 * to destroy the buffer and backing store and (2) when the caller
1020 	 * wants to destroy the buffer and backing store after a write
1021 	 * completes.
1022 	 */
1023 	if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1024 		bundirty(bp);
1025 	}
1026 
1027 	if (bp->b_flags & B_LOCKED)
1028 		bp->b_flags &= ~B_ERROR;
1029 
1030 	/*
1031 	 * If a write error occurs and the caller does not want to throw
1032 	 * away the buffer, redirty the buffer.  This will also clear
1033 	 * B_NOCACHE.
1034 	 */
1035 	if (bp->b_cmd == BUF_CMD_WRITE &&
1036 	    (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
1037 		/*
1038 		 * Failed write, redirty.  Must clear B_ERROR to prevent
1039 		 * pages from being scrapped.  If B_INVAL is set then
1040 		 * this case is not run and the next case is run to
1041 		 * destroy the buffer.  B_INVAL can occur if the buffer
1042 		 * is outside the range supported by the underlying device.
1043 		 */
1044 		bp->b_flags &= ~B_ERROR;
1045 		bdirty(bp);
1046 	} else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1047 		   (bp->b_bufsize <= 0) || bp->b_cmd == BUF_CMD_FREEBLKS) {
1048 		/*
1049 		 * Either a failed I/O or we were asked to free or not
1050 		 * cache the buffer.
1051 		 *
1052 		 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1053 		 * buffer cannot be immediately freed.
1054 		 */
1055 		bp->b_flags |= B_INVAL;
1056 		if (LIST_FIRST(&bp->b_dep) != NULL)
1057 			buf_deallocate(bp);
1058 		if (bp->b_flags & B_DELWRI) {
1059 			--dirtybufcount;
1060 			dirtybufspace -= bp->b_bufsize;
1061 			if (bp->b_flags & B_HEAVY) {
1062 				--dirtybufcounthw;
1063 				dirtybufspacehw -= bp->b_bufsize;
1064 			}
1065 			bd_signal(bp->b_bufsize);
1066 		}
1067 		bp->b_flags &= ~(B_DELWRI | B_CACHE);
1068 	}
1069 
1070 	/*
1071 	 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set.
1072 	 * If vfs_vmio_release() is called with either bit set, the
1073 	 * underlying pages may wind up getting freed causing a previous
1074 	 * write (bdwrite()) to get 'lost' because pages associated with
1075 	 * a B_DELWRI bp are marked clean.  Pages associated with a
1076 	 * B_LOCKED buffer may be mapped by the filesystem.
1077 	 *
1078 	 * If we want to release the buffer ourselves (rather then the
1079 	 * originator asking us to release it), give the originator a
1080 	 * chance to countermand the release by setting B_LOCKED.
1081 	 *
1082 	 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1083 	 * if B_DELWRI is set.
1084 	 *
1085 	 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1086 	 * on pages to return pages to the VM page queues.
1087 	 */
1088 	if (bp->b_flags & (B_DELWRI | B_LOCKED)) {
1089 		bp->b_flags &= ~B_RELBUF;
1090 	} else if (vm_page_count_severe()) {
1091 		if (LIST_FIRST(&bp->b_dep) != NULL)
1092 			buf_deallocate(bp);
1093 		if (bp->b_flags & (B_DELWRI | B_LOCKED))
1094 			bp->b_flags &= ~B_RELBUF;
1095 		else
1096 			bp->b_flags |= B_RELBUF;
1097 	}
1098 
1099 	/*
1100 	 * At this point destroying the buffer is governed by the B_INVAL
1101 	 * or B_RELBUF flags.
1102 	 */
1103 	bp->b_cmd = BUF_CMD_DONE;
1104 
1105 	/*
1106 	 * VMIO buffer rundown.  Make sure the VM page array is restored
1107 	 * after an I/O may have replaces some of the pages with bogus pages
1108 	 * in order to not destroy dirty pages in a fill-in read.
1109 	 *
1110 	 * Note that due to the code above, if a buffer is marked B_DELWRI
1111 	 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1112 	 * B_INVAL may still be set, however.
1113 	 *
1114 	 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1115 	 * but not the backing store.   B_NOCACHE will destroy the backing
1116 	 * store.
1117 	 *
1118 	 * Note that dirty NFS buffers contain byte-granular write ranges
1119 	 * and should not be destroyed w/ B_INVAL even if the backing store
1120 	 * is left intact.
1121 	 */
1122 	if (bp->b_flags & B_VMIO) {
1123 		/*
1124 		 * Rundown for VMIO buffers which are not dirty NFS buffers.
1125 		 */
1126 		int i, j, resid;
1127 		vm_page_t m;
1128 		off_t foff;
1129 		vm_pindex_t poff;
1130 		vm_object_t obj;
1131 		struct vnode *vp;
1132 
1133 		vp = bp->b_vp;
1134 
1135 		/*
1136 		 * Get the base offset and length of the buffer.  Note that
1137 		 * in the VMIO case if the buffer block size is not
1138 		 * page-aligned then b_data pointer may not be page-aligned.
1139 		 * But our b_xio.xio_pages array *IS* page aligned.
1140 		 *
1141 		 * block sizes less then DEV_BSIZE (usually 512) are not
1142 		 * supported due to the page granularity bits (m->valid,
1143 		 * m->dirty, etc...).
1144 		 *
1145 		 * See man buf(9) for more information
1146 		 */
1147 
1148 		resid = bp->b_bufsize;
1149 		foff = bp->b_loffset;
1150 
1151 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
1152 			m = bp->b_xio.xio_pages[i];
1153 			vm_page_flag_clear(m, PG_ZERO);
1154 			/*
1155 			 * If we hit a bogus page, fixup *all* of them
1156 			 * now.  Note that we left these pages wired
1157 			 * when we removed them so they had better exist,
1158 			 * and they cannot be ripped out from under us so
1159 			 * no critical section protection is necessary.
1160 			 */
1161 			if (m == bogus_page) {
1162 				obj = vp->v_object;
1163 				poff = OFF_TO_IDX(bp->b_loffset);
1164 
1165 				for (j = i; j < bp->b_xio.xio_npages; j++) {
1166 					vm_page_t mtmp;
1167 
1168 					mtmp = bp->b_xio.xio_pages[j];
1169 					if (mtmp == bogus_page) {
1170 						mtmp = vm_page_lookup(obj, poff + j);
1171 						if (!mtmp) {
1172 							panic("brelse: page missing");
1173 						}
1174 						bp->b_xio.xio_pages[j] = mtmp;
1175 					}
1176 				}
1177 
1178 				if ((bp->b_flags & B_INVAL) == 0) {
1179 					pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1180 						bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1181 				}
1182 				m = bp->b_xio.xio_pages[i];
1183 			}
1184 
1185 			/*
1186 			 * Invalidate the backing store if B_NOCACHE is set
1187 			 * (e.g. used with vinvalbuf()).  If this is NFS
1188 			 * we impose a requirement that the block size be
1189 			 * a multiple of PAGE_SIZE and create a temporary
1190 			 * hack to basically invalidate the whole page.  The
1191 			 * problem is that NFS uses really odd buffer sizes
1192 			 * especially when tracking piecemeal writes and
1193 			 * it also vinvalbuf()'s a lot, which would result
1194 			 * in only partial page validation and invalidation
1195 			 * here.  If the file page is mmap()'d, however,
1196 			 * all the valid bits get set so after we invalidate
1197 			 * here we would end up with weird m->valid values
1198 			 * like 0xfc.  nfs_getpages() can't handle this so
1199 			 * we clear all the valid bits for the NFS case
1200 			 * instead of just some of them.
1201 			 *
1202 			 * The real bug is the VM system having to set m->valid
1203 			 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1204 			 * itself is an artifact of the whole 512-byte
1205 			 * granular mess that exists to support odd block
1206 			 * sizes and UFS meta-data block sizes (e.g. 6144).
1207 			 * A complete rewrite is required.
1208 			 */
1209 			if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1210 				int poffset = foff & PAGE_MASK;
1211 				int presid;
1212 
1213 				presid = PAGE_SIZE - poffset;
1214 				if (bp->b_vp->v_tag == VT_NFS &&
1215 				    bp->b_vp->v_type == VREG) {
1216 					; /* entire page */
1217 				} else if (presid > resid) {
1218 					presid = resid;
1219 				}
1220 				KASSERT(presid >= 0, ("brelse: extra page"));
1221 				vm_page_set_invalid(m, poffset, presid);
1222 			}
1223 			resid -= PAGE_SIZE - (foff & PAGE_MASK);
1224 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1225 		}
1226 		if (bp->b_flags & (B_INVAL | B_RELBUF))
1227 			vfs_vmio_release(bp);
1228 	} else {
1229 		/*
1230 		 * Rundown for non-VMIO buffers.
1231 		 */
1232 		if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1233 #if 0
1234 			if (bp->b_vp)
1235 				kprintf("brelse bp %p %08x/%08x: Warning, caught and fixed brelvp bug\n", bp, saved_flags, bp->b_flags);
1236 #endif
1237 			if (bp->b_bufsize)
1238 				allocbuf(bp, 0);
1239 			KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1240 			if (bp->b_vp)
1241 				brelvp(bp);
1242 		}
1243 	}
1244 
1245 	if (bp->b_qindex != BQUEUE_NONE)
1246 		panic("brelse: free buffer onto another queue???");
1247 	if (BUF_REFCNTNB(bp) > 1) {
1248 		/* Temporary panic to verify exclusive locking */
1249 		/* This panic goes away when we allow shared refs */
1250 		panic("brelse: multiple refs");
1251 		/* do not release to free list */
1252 		BUF_UNLOCK(bp);
1253 		crit_exit();
1254 		return;
1255 	}
1256 
1257 	/*
1258 	 * Figure out the correct queue to place the cleaned up buffer on.
1259 	 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1260 	 * disassociated from their vnode.
1261 	 */
1262 	if (bp->b_flags & B_LOCKED) {
1263 		/*
1264 		 * Buffers that are locked are placed in the locked queue
1265 		 * immediately, regardless of their state.
1266 		 */
1267 		bp->b_qindex = BQUEUE_LOCKED;
1268 		TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1269 	} else if (bp->b_bufsize == 0) {
1270 		/*
1271 		 * Buffers with no memory.  Due to conditionals near the top
1272 		 * of brelse() such buffers should probably already be
1273 		 * marked B_INVAL and disassociated from their vnode.
1274 		 */
1275 		bp->b_flags |= B_INVAL;
1276 		KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1277 		KKASSERT((bp->b_flags & B_HASHED) == 0);
1278 		if (bp->b_kvasize) {
1279 			bp->b_qindex = BQUEUE_EMPTYKVA;
1280 		} else {
1281 			bp->b_qindex = BQUEUE_EMPTY;
1282 		}
1283 		TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1284 	} else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1285 		/*
1286 		 * Buffers with junk contents.   Again these buffers had better
1287 		 * already be disassociated from their vnode.
1288 		 */
1289 		KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1290 		KKASSERT((bp->b_flags & B_HASHED) == 0);
1291 		bp->b_flags |= B_INVAL;
1292 		bp->b_qindex = BQUEUE_CLEAN;
1293 		TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1294 	} else {
1295 		/*
1296 		 * Remaining buffers.  These buffers are still associated with
1297 		 * their vnode.
1298 		 */
1299 		switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
1300 		case B_DELWRI:
1301 		    bp->b_qindex = BQUEUE_DIRTY;
1302 		    TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1303 		    break;
1304 		case B_DELWRI | B_HEAVY:
1305 		    bp->b_qindex = BQUEUE_DIRTY_HW;
1306 		    TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY_HW], bp,
1307 				      b_freelist);
1308 		    break;
1309 		default:
1310 		    /*
1311 		     * NOTE: Buffers are always placed at the end of the
1312 		     * queue.  If B_AGE is not set the buffer will cycle
1313 		     * through the queue twice.
1314 		     */
1315 		    bp->b_qindex = BQUEUE_CLEAN;
1316 		    TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1317 		    break;
1318 		}
1319 	}
1320 
1321 	/*
1322 	 * If B_INVAL, clear B_DELWRI.  We've already placed the buffer
1323 	 * on the correct queue.
1324 	 */
1325 	if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1326 		bundirty(bp);
1327 
1328 	/*
1329 	 * The bp is on an appropriate queue unless locked.  If it is not
1330 	 * locked or dirty we can wakeup threads waiting for buffer space.
1331 	 *
1332 	 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1333 	 * if B_INVAL is set ).
1334 	 */
1335 	if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1336 		bufcountwakeup();
1337 
1338 	/*
1339 	 * Something we can maybe free or reuse
1340 	 */
1341 	if (bp->b_bufsize || bp->b_kvasize)
1342 		bufspacewakeup();
1343 
1344 	/*
1345 	 * Clean up temporary flags and unlock the buffer.
1346 	 */
1347 	bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_RELBUF | B_DIRECT);
1348 	BUF_UNLOCK(bp);
1349 	crit_exit();
1350 }
1351 
1352 /*
1353  * bqrelse:
1354  *
1355  *	Release a buffer back to the appropriate queue but do not try to free
1356  *	it.  The buffer is expected to be used again soon.
1357  *
1358  *	bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1359  *	biodone() to requeue an async I/O on completion.  It is also used when
1360  *	known good buffers need to be requeued but we think we may need the data
1361  *	again soon.
1362  *
1363  *	XXX we should be able to leave the B_RELBUF hint set on completion.
1364  */
1365 void
1366 bqrelse(struct buf *bp)
1367 {
1368 	crit_enter();
1369 
1370 	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1371 
1372 	if (bp->b_qindex != BQUEUE_NONE)
1373 		panic("bqrelse: free buffer onto another queue???");
1374 	if (BUF_REFCNTNB(bp) > 1) {
1375 		/* do not release to free list */
1376 		panic("bqrelse: multiple refs");
1377 		BUF_UNLOCK(bp);
1378 		crit_exit();
1379 		return;
1380 	}
1381 	if (bp->b_flags & B_LOCKED) {
1382 		/*
1383 		 * Locked buffers are released to the locked queue.  However,
1384 		 * if the buffer is dirty it will first go into the dirty
1385 		 * queue and later on after the I/O completes successfully it
1386 		 * will be released to the locked queue.
1387 		 */
1388 		bp->b_flags &= ~B_ERROR;
1389 		bp->b_qindex = BQUEUE_LOCKED;
1390 		TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1391 	} else if (bp->b_flags & B_DELWRI) {
1392 		bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1393 			       BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1394 		TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1395 	} else if (vm_page_count_severe()) {
1396 		/*
1397 		 * We are too low on memory, we have to try to free the
1398 		 * buffer (most importantly: the wired pages making up its
1399 		 * backing store) *now*.
1400 		 */
1401 		crit_exit();
1402 		brelse(bp);
1403 		return;
1404 	} else {
1405 		bp->b_qindex = BQUEUE_CLEAN;
1406 		TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1407 	}
1408 
1409 	if ((bp->b_flags & B_LOCKED) == 0 &&
1410 	    ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1411 		bufcountwakeup();
1412 	}
1413 
1414 	/*
1415 	 * Something we can maybe free or reuse.
1416 	 */
1417 	if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1418 		bufspacewakeup();
1419 
1420 	/*
1421 	 * Final cleanup and unlock.  Clear bits that are only used while a
1422 	 * buffer is actively locked.
1423 	 */
1424 	bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_RELBUF);
1425 	BUF_UNLOCK(bp);
1426 	crit_exit();
1427 }
1428 
1429 /*
1430  * vfs_vmio_release:
1431  *
1432  *	Return backing pages held by the buffer 'bp' back to the VM system
1433  *	if possible.  The pages are freed if they are no longer valid or
1434  *	attempt to free if it was used for direct I/O otherwise they are
1435  *	sent to the page cache.
1436  *
1437  *	Pages that were marked busy are left alone and skipped.
1438  *
1439  *	The KVA mapping (b_data) for the underlying pages is removed by
1440  *	this function.
1441  */
1442 static void
1443 vfs_vmio_release(struct buf *bp)
1444 {
1445 	int i;
1446 	vm_page_t m;
1447 
1448 	crit_enter();
1449 	for (i = 0; i < bp->b_xio.xio_npages; i++) {
1450 		m = bp->b_xio.xio_pages[i];
1451 		bp->b_xio.xio_pages[i] = NULL;
1452 		/*
1453 		 * In order to keep page LRU ordering consistent, put
1454 		 * everything on the inactive queue.
1455 		 */
1456 		vm_page_unwire(m, 0);
1457 		/*
1458 		 * We don't mess with busy pages, it is
1459 		 * the responsibility of the process that
1460 		 * busied the pages to deal with them.
1461 		 */
1462 		if ((m->flags & PG_BUSY) || (m->busy != 0))
1463 			continue;
1464 
1465 		if (m->wire_count == 0) {
1466 			vm_page_flag_clear(m, PG_ZERO);
1467 			/*
1468 			 * Might as well free the page if we can and it has
1469 			 * no valid data.  We also free the page if the
1470 			 * buffer was used for direct I/O.
1471 			 */
1472 			if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1473 					m->hold_count == 0) {
1474 				vm_page_busy(m);
1475 				vm_page_protect(m, VM_PROT_NONE);
1476 				vm_page_free(m);
1477 			} else if (bp->b_flags & B_DIRECT) {
1478 				vm_page_try_to_free(m);
1479 			} else if (vm_page_count_severe()) {
1480 				vm_page_try_to_cache(m);
1481 			}
1482 		}
1483 	}
1484 	crit_exit();
1485 	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1486 	if (bp->b_bufsize) {
1487 		bufspacewakeup();
1488 		bp->b_bufsize = 0;
1489 	}
1490 	bp->b_xio.xio_npages = 0;
1491 	bp->b_flags &= ~B_VMIO;
1492 	KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1493 	if (bp->b_vp)
1494 		brelvp(bp);
1495 }
1496 
1497 /*
1498  * vfs_bio_awrite:
1499  *
1500  *	Implement clustered async writes for clearing out B_DELWRI buffers.
1501  *	This is much better then the old way of writing only one buffer at
1502  *	a time.  Note that we may not be presented with the buffers in the
1503  *	correct order, so we search for the cluster in both directions.
1504  *
1505  *	The buffer is locked on call.
1506  */
1507 int
1508 vfs_bio_awrite(struct buf *bp)
1509 {
1510 	int i;
1511 	int j;
1512 	off_t loffset = bp->b_loffset;
1513 	struct vnode *vp = bp->b_vp;
1514 	int nbytes;
1515 	struct buf *bpa;
1516 	int nwritten;
1517 	int size;
1518 
1519 	crit_enter();
1520 	/*
1521 	 * right now we support clustered writing only to regular files.  If
1522 	 * we find a clusterable block we could be in the middle of a cluster
1523 	 * rather then at the beginning.
1524 	 *
1525 	 * NOTE: b_bio1 contains the logical loffset and is aliased
1526 	 * to b_loffset.  b_bio2 contains the translated block number.
1527 	 */
1528 	if ((vp->v_type == VREG) &&
1529 	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1530 	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1531 
1532 		size = vp->v_mount->mnt_stat.f_iosize;
1533 
1534 		for (i = size; i < MAXPHYS; i += size) {
1535 			if ((bpa = findblk(vp, loffset + i)) &&
1536 			    BUF_REFCNT(bpa) == 0 &&
1537 			    ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1538 			    (B_DELWRI | B_CLUSTEROK)) &&
1539 			    (bpa->b_bufsize == size)) {
1540 				if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1541 				    (bpa->b_bio2.bio_offset !=
1542 				     bp->b_bio2.bio_offset + i))
1543 					break;
1544 			} else {
1545 				break;
1546 			}
1547 		}
1548 		for (j = size; i + j <= MAXPHYS && j <= loffset; j += size) {
1549 			if ((bpa = findblk(vp, loffset - j)) &&
1550 			    BUF_REFCNT(bpa) == 0 &&
1551 			    ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1552 			    (B_DELWRI | B_CLUSTEROK)) &&
1553 			    (bpa->b_bufsize == size)) {
1554 				if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1555 				    (bpa->b_bio2.bio_offset !=
1556 				     bp->b_bio2.bio_offset - j))
1557 					break;
1558 			} else {
1559 				break;
1560 			}
1561 		}
1562 		j -= size;
1563 		nbytes = (i + j);
1564 		/*
1565 		 * this is a possible cluster write
1566 		 */
1567 		if (nbytes != size) {
1568 			BUF_UNLOCK(bp);
1569 			nwritten = cluster_wbuild(vp, size,
1570 						  loffset - j, nbytes);
1571 			crit_exit();
1572 			return nwritten;
1573 		}
1574 	}
1575 
1576 	bremfree(bp);
1577 	bp->b_flags |= B_ASYNC;
1578 
1579 	crit_exit();
1580 	/*
1581 	 * default (old) behavior, writing out only one block
1582 	 *
1583 	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1584 	 */
1585 	nwritten = bp->b_bufsize;
1586 	bwrite(bp);
1587 
1588 	return nwritten;
1589 }
1590 
1591 /*
1592  * getnewbuf:
1593  *
1594  *	Find and initialize a new buffer header, freeing up existing buffers
1595  *	in the bufqueues as necessary.  The new buffer is returned locked.
1596  *
1597  *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1598  *	buffer away, the caller must set B_INVAL prior to calling brelse().
1599  *
1600  *	We block if:
1601  *		We have insufficient buffer headers
1602  *		We have insufficient buffer space
1603  *		buffer_map is too fragmented ( space reservation fails )
1604  *		If we have to flush dirty buffers ( but we try to avoid this )
1605  *
1606  *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1607  *	Instead we ask the buf daemon to do it for us.  We attempt to
1608  *	avoid piecemeal wakeups of the pageout daemon.
1609  */
1610 
1611 static struct buf *
1612 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1613 {
1614 	struct buf *bp;
1615 	struct buf *nbp;
1616 	int defrag = 0;
1617 	int nqindex;
1618 	int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1619 	static int flushingbufs;
1620 
1621 	/*
1622 	 * We can't afford to block since we might be holding a vnode lock,
1623 	 * which may prevent system daemons from running.  We deal with
1624 	 * low-memory situations by proactively returning memory and running
1625 	 * async I/O rather then sync I/O.
1626 	 */
1627 
1628 	++getnewbufcalls;
1629 	--getnewbufrestarts;
1630 restart:
1631 	++getnewbufrestarts;
1632 
1633 	/*
1634 	 * Setup for scan.  If we do not have enough free buffers,
1635 	 * we setup a degenerate case that immediately fails.  Note
1636 	 * that if we are specially marked process, we are allowed to
1637 	 * dip into our reserves.
1638 	 *
1639 	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1640 	 *
1641 	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1642 	 * However, there are a number of cases (defragging, reusing, ...)
1643 	 * where we cannot backup.
1644 	 */
1645 	nqindex = BQUEUE_EMPTYKVA;
1646 	nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1647 
1648 	if (nbp == NULL) {
1649 		/*
1650 		 * If no EMPTYKVA buffers and we are either
1651 		 * defragging or reusing, locate a CLEAN buffer
1652 		 * to free or reuse.  If bufspace useage is low
1653 		 * skip this step so we can allocate a new buffer.
1654 		 */
1655 		if (defrag || bufspace >= lobufspace) {
1656 			nqindex = BQUEUE_CLEAN;
1657 			nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1658 		}
1659 
1660 		/*
1661 		 * If we could not find or were not allowed to reuse a
1662 		 * CLEAN buffer, check to see if it is ok to use an EMPTY
1663 		 * buffer.  We can only use an EMPTY buffer if allocating
1664 		 * its KVA would not otherwise run us out of buffer space.
1665 		 */
1666 		if (nbp == NULL && defrag == 0 &&
1667 		    bufspace + maxsize < hibufspace) {
1668 			nqindex = BQUEUE_EMPTY;
1669 			nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1670 		}
1671 	}
1672 
1673 	/*
1674 	 * Run scan, possibly freeing data and/or kva mappings on the fly
1675 	 * depending.
1676 	 */
1677 
1678 	while ((bp = nbp) != NULL) {
1679 		int qindex = nqindex;
1680 
1681 		nbp = TAILQ_NEXT(bp, b_freelist);
1682 
1683 		/*
1684 		 * BQUEUE_CLEAN - B_AGE special case.  If not set the bp
1685 		 * cycles through the queue twice before being selected.
1686 		 */
1687 		if (qindex == BQUEUE_CLEAN &&
1688 		    (bp->b_flags & B_AGE) == 0 && nbp) {
1689 			bp->b_flags |= B_AGE;
1690 			TAILQ_REMOVE(&bufqueues[qindex], bp, b_freelist);
1691 			TAILQ_INSERT_TAIL(&bufqueues[qindex], bp, b_freelist);
1692 			continue;
1693 		}
1694 
1695 		/*
1696 		 * Calculate next bp ( we can only use it if we do not block
1697 		 * or do other fancy things ).
1698 		 */
1699 		if (nbp == NULL) {
1700 			switch(qindex) {
1701 			case BQUEUE_EMPTY:
1702 				nqindex = BQUEUE_EMPTYKVA;
1703 				if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1704 					break;
1705 				/* fall through */
1706 			case BQUEUE_EMPTYKVA:
1707 				nqindex = BQUEUE_CLEAN;
1708 				if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1709 					break;
1710 				/* fall through */
1711 			case BQUEUE_CLEAN:
1712 				/*
1713 				 * nbp is NULL.
1714 				 */
1715 				break;
1716 			}
1717 		}
1718 
1719 		/*
1720 		 * Sanity Checks
1721 		 */
1722 		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1723 
1724 		/*
1725 		 * Note: we no longer distinguish between VMIO and non-VMIO
1726 		 * buffers.
1727 		 */
1728 
1729 		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1730 
1731 		/*
1732 		 * If we are defragging then we need a buffer with
1733 		 * b_kvasize != 0.  XXX this situation should no longer
1734 		 * occur, if defrag is non-zero the buffer's b_kvasize
1735 		 * should also be non-zero at this point.  XXX
1736 		 */
1737 		if (defrag && bp->b_kvasize == 0) {
1738 			kprintf("Warning: defrag empty buffer %p\n", bp);
1739 			continue;
1740 		}
1741 
1742 		/*
1743 		 * Start freeing the bp.  This is somewhat involved.  nbp
1744 		 * remains valid only for BQUEUE_EMPTY[KVA] bp's.  Buffers
1745 		 * on the clean list must be disassociated from their
1746 		 * current vnode.  Buffers on the empty[kva] lists have
1747 		 * already been disassociated.
1748 		 */
1749 
1750 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1751 			kprintf("getnewbuf: warning, locked buf %p, race corrected\n", bp);
1752 			tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1753 			goto restart;
1754 		}
1755 		if (bp->b_qindex != qindex) {
1756 			kprintf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp, qindex, bp->b_qindex);
1757 			BUF_UNLOCK(bp);
1758 			goto restart;
1759 		}
1760 		bremfree(bp);
1761 
1762 		/*
1763 		 * Dependancies must be handled before we disassociate the
1764 		 * vnode.
1765 		 *
1766 		 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1767 		 * be immediately disassociated.  HAMMER then becomes
1768 		 * responsible for releasing the buffer.
1769 		 */
1770 		if (LIST_FIRST(&bp->b_dep) != NULL) {
1771 			buf_deallocate(bp);
1772 			if (bp->b_flags & B_LOCKED) {
1773 				bqrelse(bp);
1774 				goto restart;
1775 			}
1776 			KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
1777 		}
1778 
1779 		if (qindex == BQUEUE_CLEAN) {
1780 			if (bp->b_flags & B_VMIO) {
1781 				bp->b_flags &= ~B_ASYNC;
1782 				vfs_vmio_release(bp);
1783 			}
1784 			if (bp->b_vp)
1785 				brelvp(bp);
1786 		}
1787 
1788 		/*
1789 		 * NOTE:  nbp is now entirely invalid.  We can only restart
1790 		 * the scan from this point on.
1791 		 *
1792 		 * Get the rest of the buffer freed up.  b_kva* is still
1793 		 * valid after this operation.
1794 		 */
1795 
1796 		KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
1797 		KKASSERT((bp->b_flags & B_HASHED) == 0);
1798 
1799 		/*
1800 		 * critical section protection is not required when
1801 		 * scrapping a buffer's contents because it is already
1802 		 * wired.
1803 		 */
1804 		if (bp->b_bufsize)
1805 			allocbuf(bp, 0);
1806 
1807 		bp->b_flags = B_BNOCLIP;
1808 		bp->b_cmd = BUF_CMD_DONE;
1809 		bp->b_vp = NULL;
1810 		bp->b_error = 0;
1811 		bp->b_resid = 0;
1812 		bp->b_bcount = 0;
1813 		bp->b_xio.xio_npages = 0;
1814 		bp->b_dirtyoff = bp->b_dirtyend = 0;
1815 		reinitbufbio(bp);
1816 		KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
1817 		buf_dep_init(bp);
1818 		if (blkflags & GETBLK_BHEAVY)
1819 			bp->b_flags |= B_HEAVY;
1820 
1821 		/*
1822 		 * If we are defragging then free the buffer.
1823 		 */
1824 		if (defrag) {
1825 			bp->b_flags |= B_INVAL;
1826 			bfreekva(bp);
1827 			brelse(bp);
1828 			defrag = 0;
1829 			goto restart;
1830 		}
1831 
1832 		/*
1833 		 * If we are overcomitted then recover the buffer and its
1834 		 * KVM space.  This occurs in rare situations when multiple
1835 		 * processes are blocked in getnewbuf() or allocbuf().
1836 		 */
1837 		if (bufspace >= hibufspace)
1838 			flushingbufs = 1;
1839 		if (flushingbufs && bp->b_kvasize != 0) {
1840 			bp->b_flags |= B_INVAL;
1841 			bfreekva(bp);
1842 			brelse(bp);
1843 			goto restart;
1844 		}
1845 		if (bufspace < lobufspace)
1846 			flushingbufs = 0;
1847 		break;
1848 	}
1849 
1850 	/*
1851 	 * If we exhausted our list, sleep as appropriate.  We may have to
1852 	 * wakeup various daemons and write out some dirty buffers.
1853 	 *
1854 	 * Generally we are sleeping due to insufficient buffer space.
1855 	 */
1856 
1857 	if (bp == NULL) {
1858 		int flags;
1859 		char *waitmsg;
1860 
1861 		if (defrag) {
1862 			flags = VFS_BIO_NEED_BUFSPACE;
1863 			waitmsg = "nbufkv";
1864 		} else if (bufspace >= hibufspace) {
1865 			waitmsg = "nbufbs";
1866 			flags = VFS_BIO_NEED_BUFSPACE;
1867 		} else {
1868 			waitmsg = "newbuf";
1869 			flags = VFS_BIO_NEED_ANY;
1870 		}
1871 
1872 		needsbuffer |= flags;
1873 		bd_speedup();	/* heeeelp */
1874 		while (needsbuffer & flags) {
1875 			if (tsleep(&needsbuffer, slpflags, waitmsg, slptimeo))
1876 				return (NULL);
1877 		}
1878 	} else {
1879 		/*
1880 		 * We finally have a valid bp.  We aren't quite out of the
1881 		 * woods, we still have to reserve kva space.  In order
1882 		 * to keep fragmentation sane we only allocate kva in
1883 		 * BKVASIZE chunks.
1884 		 */
1885 		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1886 
1887 		if (maxsize != bp->b_kvasize) {
1888 			vm_offset_t addr = 0;
1889 			int count;
1890 
1891 			bfreekva(bp);
1892 
1893 			count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1894 			vm_map_lock(&buffer_map);
1895 
1896 			if (vm_map_findspace(&buffer_map,
1897 				    vm_map_min(&buffer_map), maxsize,
1898 				    maxsize, &addr)) {
1899 				/*
1900 				 * Uh oh.  Buffer map is too fragmented.  We
1901 				 * must defragment the map.
1902 				 */
1903 				vm_map_unlock(&buffer_map);
1904 				vm_map_entry_release(count);
1905 				++bufdefragcnt;
1906 				defrag = 1;
1907 				bp->b_flags |= B_INVAL;
1908 				brelse(bp);
1909 				goto restart;
1910 			}
1911 			if (addr) {
1912 				vm_map_insert(&buffer_map, &count,
1913 					NULL, 0,
1914 					addr, addr + maxsize,
1915 					VM_MAPTYPE_NORMAL,
1916 					VM_PROT_ALL, VM_PROT_ALL,
1917 					MAP_NOFAULT);
1918 
1919 				bp->b_kvabase = (caddr_t) addr;
1920 				bp->b_kvasize = maxsize;
1921 				bufspace += bp->b_kvasize;
1922 				++bufreusecnt;
1923 			}
1924 			vm_map_unlock(&buffer_map);
1925 			vm_map_entry_release(count);
1926 		}
1927 		bp->b_data = bp->b_kvabase;
1928 	}
1929 	return(bp);
1930 }
1931 
1932 /*
1933  * This routine is called in an emergency to recover VM pages from the
1934  * buffer cache by cashing in clean buffers.  The idea is to recover
1935  * enough pages to be able to satisfy a stuck bio_page_alloc().
1936  */
1937 static int
1938 recoverbufpages(void)
1939 {
1940 	struct buf *bp;
1941 	int bytes = 0;
1942 
1943 	++recoverbufcalls;
1944 
1945 	while (bytes < MAXBSIZE) {
1946 		bp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1947 		if (bp == NULL)
1948 			break;
1949 
1950 		/*
1951 		 * BQUEUE_CLEAN - B_AGE special case.  If not set the bp
1952 		 * cycles through the queue twice before being selected.
1953 		 */
1954 		if ((bp->b_flags & B_AGE) == 0 && TAILQ_NEXT(bp, b_freelist)) {
1955 			bp->b_flags |= B_AGE;
1956 			TAILQ_REMOVE(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1957 			TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN],
1958 					  bp, b_freelist);
1959 			continue;
1960 		}
1961 
1962 		/*
1963 		 * Sanity Checks
1964 		 */
1965 		KKASSERT(bp->b_qindex == BQUEUE_CLEAN);
1966 		KKASSERT((bp->b_flags & B_DELWRI) == 0);
1967 
1968 		/*
1969 		 * Start freeing the bp.  This is somewhat involved.
1970 		 *
1971 		 * Buffers on the clean list must be disassociated from
1972 		 * their current vnode
1973 		 */
1974 
1975 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1976 			kprintf("recoverbufpages: warning, locked buf %p, race corrected\n", bp);
1977 			tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1978 			continue;
1979 		}
1980 		if (bp->b_qindex != BQUEUE_CLEAN) {
1981 			kprintf("recoverbufpages: warning, BUF_LOCK blocked unexpectedly on buf %p index %d, race corrected\n", bp, bp->b_qindex);
1982 			BUF_UNLOCK(bp);
1983 			continue;
1984 		}
1985 		bremfree(bp);
1986 
1987 		/*
1988 		 * Dependancies must be handled before we disassociate the
1989 		 * vnode.
1990 		 *
1991 		 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1992 		 * be immediately disassociated.  HAMMER then becomes
1993 		 * responsible for releasing the buffer.
1994 		 */
1995 		if (LIST_FIRST(&bp->b_dep) != NULL) {
1996 			buf_deallocate(bp);
1997 			if (bp->b_flags & B_LOCKED) {
1998 				bqrelse(bp);
1999 				continue;
2000 			}
2001 			KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2002 		}
2003 
2004 		bytes += bp->b_bufsize;
2005 
2006 		if (bp->b_flags & B_VMIO) {
2007 			bp->b_flags &= ~B_ASYNC;
2008 			bp->b_flags |= B_DIRECT;    /* try to free pages */
2009 			vfs_vmio_release(bp);
2010 		}
2011 		if (bp->b_vp)
2012 			brelvp(bp);
2013 
2014 		KKASSERT(bp->b_vp == NULL);
2015 		KKASSERT((bp->b_flags & B_HASHED) == 0);
2016 
2017 		/*
2018 		 * critical section protection is not required when
2019 		 * scrapping a buffer's contents because it is already
2020 		 * wired.
2021 		 */
2022 		if (bp->b_bufsize)
2023 			allocbuf(bp, 0);
2024 
2025 		bp->b_flags = B_BNOCLIP;
2026 		bp->b_cmd = BUF_CMD_DONE;
2027 		bp->b_vp = NULL;
2028 		bp->b_error = 0;
2029 		bp->b_resid = 0;
2030 		bp->b_bcount = 0;
2031 		bp->b_xio.xio_npages = 0;
2032 		bp->b_dirtyoff = bp->b_dirtyend = 0;
2033 		reinitbufbio(bp);
2034 		KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2035 		buf_dep_init(bp);
2036 		bp->b_flags |= B_INVAL;
2037 		/* bfreekva(bp); */
2038 		brelse(bp);
2039 	}
2040 	return(bytes);
2041 }
2042 
2043 /*
2044  * buf_daemon:
2045  *
2046  *	Buffer flushing daemon.  Buffers are normally flushed by the
2047  *	update daemon but if it cannot keep up this process starts to
2048  *	take the load in an attempt to prevent getnewbuf() from blocking.
2049  *
2050  *	Once a flush is initiated it does not stop until the number
2051  *	of buffers falls below lodirtybuffers, but we will wake up anyone
2052  *	waiting at the mid-point.
2053  */
2054 
2055 static struct kproc_desc buf_kp = {
2056 	"bufdaemon",
2057 	buf_daemon,
2058 	&bufdaemon_td
2059 };
2060 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2061 	kproc_start, &buf_kp)
2062 
2063 static struct kproc_desc bufhw_kp = {
2064 	"bufdaemon_hw",
2065 	buf_daemon_hw,
2066 	&bufdaemonhw_td
2067 };
2068 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2069 	kproc_start, &bufhw_kp)
2070 
2071 static void
2072 buf_daemon(void)
2073 {
2074 	int limit;
2075 
2076 	/*
2077 	 * This process needs to be suspended prior to shutdown sync.
2078 	 */
2079 	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2080 			      bufdaemon_td, SHUTDOWN_PRI_LAST);
2081 	curthread->td_flags |= TDF_SYSTHREAD;
2082 
2083 	/*
2084 	 * This process is allowed to take the buffer cache to the limit
2085 	 */
2086 	crit_enter();
2087 
2088 	for (;;) {
2089 		kproc_suspend_loop();
2090 
2091 		/*
2092 		 * Do the flush.  Limit the amount of in-transit I/O we
2093 		 * allow to build up, otherwise we would completely saturate
2094 		 * the I/O system.  Wakeup any waiting processes before we
2095 		 * normally would so they can run in parallel with our drain.
2096 		 *
2097 		 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2098 		 * but because we split the operation into two threads we
2099 		 * have to cut it in half for each thread.
2100 		 */
2101 		limit = lodirtybufspace / 2;
2102 		waitrunningbufspace(limit);
2103 		while (runningbufspace + dirtybufspace > limit ||
2104 		       dirtybufcount - dirtybufcounthw >= nbuf / 2) {
2105 			if (flushbufqueues(BQUEUE_DIRTY) == 0)
2106 				break;
2107 			waitrunningbufspace(limit);
2108 		}
2109 
2110 		/*
2111 		 * We reached our low water mark, reset the
2112 		 * request and sleep until we are needed again.
2113 		 * The sleep is just so the suspend code works.
2114 		 */
2115 		spin_lock_wr(&needsbuffer_spin);
2116 		if (bd_request == 0) {
2117 			msleep(&bd_request, &needsbuffer_spin, 0,
2118 			       "psleep", hz);
2119 		}
2120 		bd_request = 0;
2121 		spin_unlock_wr(&needsbuffer_spin);
2122 	}
2123 }
2124 
2125 static void
2126 buf_daemon_hw(void)
2127 {
2128 	int limit;
2129 
2130 	/*
2131 	 * This process needs to be suspended prior to shutdown sync.
2132 	 */
2133 	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2134 			      bufdaemonhw_td, SHUTDOWN_PRI_LAST);
2135 	curthread->td_flags |= TDF_SYSTHREAD;
2136 
2137 	/*
2138 	 * This process is allowed to take the buffer cache to the limit
2139 	 */
2140 	crit_enter();
2141 
2142 	for (;;) {
2143 		kproc_suspend_loop();
2144 
2145 		/*
2146 		 * Do the flush.  Limit the amount of in-transit I/O we
2147 		 * allow to build up, otherwise we would completely saturate
2148 		 * the I/O system.  Wakeup any waiting processes before we
2149 		 * normally would so they can run in parallel with our drain.
2150 		 *
2151 		 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2152 		 * but because we split the operation into two threads we
2153 		 * have to cut it in half for each thread.
2154 		 */
2155 		limit = lodirtybufspace / 2;
2156 		waitrunningbufspace(limit);
2157 		while (runningbufspace + dirtybufspacehw > limit ||
2158 		       dirtybufcounthw >= nbuf / 2) {
2159 			if (flushbufqueues(BQUEUE_DIRTY_HW) == 0)
2160 				break;
2161 			waitrunningbufspace(limit);
2162 		}
2163 
2164 		/*
2165 		 * We reached our low water mark, reset the
2166 		 * request and sleep until we are needed again.
2167 		 * The sleep is just so the suspend code works.
2168 		 */
2169 		spin_lock_wr(&needsbuffer_spin);
2170 		if (bd_request_hw == 0) {
2171 			msleep(&bd_request_hw, &needsbuffer_spin, 0,
2172 			       "psleep", hz);
2173 		}
2174 		bd_request_hw = 0;
2175 		spin_unlock_wr(&needsbuffer_spin);
2176 	}
2177 }
2178 
2179 /*
2180  * flushbufqueues:
2181  *
2182  *	Try to flush a buffer in the dirty queue.  We must be careful to
2183  *	free up B_INVAL buffers instead of write them, which NFS is
2184  *	particularly sensitive to.
2185  *
2186  *	B_RELBUF may only be set by VFSs.  We do set B_AGE to indicate
2187  *	that we really want to try to get the buffer out and reuse it
2188  *	due to the write load on the machine.
2189  */
2190 
2191 static int
2192 flushbufqueues(bufq_type_t q)
2193 {
2194 	struct buf *bp;
2195 	int r = 0;
2196 
2197 	bp = TAILQ_FIRST(&bufqueues[q]);
2198 
2199 	while (bp) {
2200 		KASSERT((bp->b_flags & B_DELWRI),
2201 			("unexpected clean buffer %p", bp));
2202 
2203 		if (bp->b_flags & B_DELWRI) {
2204 			if (bp->b_flags & B_INVAL) {
2205 				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2206 					panic("flushbufqueues: locked buf");
2207 				bremfree(bp);
2208 				brelse(bp);
2209 				++r;
2210 				break;
2211 			}
2212 			if (LIST_FIRST(&bp->b_dep) != NULL &&
2213 			    (bp->b_flags & B_DEFERRED) == 0 &&
2214 			    buf_countdeps(bp, 0)) {
2215 				TAILQ_REMOVE(&bufqueues[q], bp, b_freelist);
2216 				TAILQ_INSERT_TAIL(&bufqueues[q], bp,
2217 						  b_freelist);
2218 				bp->b_flags |= B_DEFERRED;
2219 				bp = TAILQ_FIRST(&bufqueues[q]);
2220 				continue;
2221 			}
2222 
2223 			/*
2224 			 * Only write it out if we can successfully lock
2225 			 * it.  If the buffer has a dependancy,
2226 			 * buf_checkwrite must also return 0.
2227 			 */
2228 			if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
2229 				if (LIST_FIRST(&bp->b_dep) != NULL &&
2230 				    buf_checkwrite(bp)) {
2231 					bremfree(bp);
2232 					brelse(bp);
2233 				} else {
2234 					bp->b_flags |= B_AGE;
2235 					vfs_bio_awrite(bp);
2236 				}
2237 				++r;
2238 				break;
2239 			}
2240 		}
2241 		bp = TAILQ_NEXT(bp, b_freelist);
2242 	}
2243 	return (r);
2244 }
2245 
2246 /*
2247  * inmem:
2248  *
2249  *	Returns true if no I/O is needed to access the associated VM object.
2250  *	This is like findblk except it also hunts around in the VM system for
2251  *	the data.
2252  *
2253  *	Note that we ignore vm_page_free() races from interrupts against our
2254  *	lookup, since if the caller is not protected our return value will not
2255  *	be any more valid then otherwise once we exit the critical section.
2256  */
2257 int
2258 inmem(struct vnode *vp, off_t loffset)
2259 {
2260 	vm_object_t obj;
2261 	vm_offset_t toff, tinc, size;
2262 	vm_page_t m;
2263 
2264 	if (findblk(vp, loffset))
2265 		return 1;
2266 	if (vp->v_mount == NULL)
2267 		return 0;
2268 	if ((obj = vp->v_object) == NULL)
2269 		return 0;
2270 
2271 	size = PAGE_SIZE;
2272 	if (size > vp->v_mount->mnt_stat.f_iosize)
2273 		size = vp->v_mount->mnt_stat.f_iosize;
2274 
2275 	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2276 		m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2277 		if (m == NULL)
2278 			return 0;
2279 		tinc = size;
2280 		if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2281 			tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2282 		if (vm_page_is_valid(m,
2283 		    (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0)
2284 			return 0;
2285 	}
2286 	return 1;
2287 }
2288 
2289 /*
2290  * vfs_setdirty:
2291  *
2292  *	Sets the dirty range for a buffer based on the status of the dirty
2293  *	bits in the pages comprising the buffer.
2294  *
2295  *	The range is limited to the size of the buffer.
2296  *
2297  *	This routine is primarily used by NFS, but is generalized for the
2298  *	B_VMIO case.
2299  */
2300 static void
2301 vfs_setdirty(struct buf *bp)
2302 {
2303 	int i;
2304 	vm_object_t object;
2305 
2306 	/*
2307 	 * Degenerate case - empty buffer
2308 	 */
2309 
2310 	if (bp->b_bufsize == 0)
2311 		return;
2312 
2313 	/*
2314 	 * We qualify the scan for modified pages on whether the
2315 	 * object has been flushed yet.  The OBJ_WRITEABLE flag
2316 	 * is not cleared simply by protecting pages off.
2317 	 */
2318 
2319 	if ((bp->b_flags & B_VMIO) == 0)
2320 		return;
2321 
2322 	object = bp->b_xio.xio_pages[0]->object;
2323 
2324 	if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2325 		kprintf("Warning: object %p writeable but not mightbedirty\n", object);
2326 	if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2327 		kprintf("Warning: object %p mightbedirty but not writeable\n", object);
2328 
2329 	if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2330 		vm_offset_t boffset;
2331 		vm_offset_t eoffset;
2332 
2333 		/*
2334 		 * test the pages to see if they have been modified directly
2335 		 * by users through the VM system.
2336 		 */
2337 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
2338 			vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2339 			vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2340 		}
2341 
2342 		/*
2343 		 * Calculate the encompassing dirty range, boffset and eoffset,
2344 		 * (eoffset - boffset) bytes.
2345 		 */
2346 
2347 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
2348 			if (bp->b_xio.xio_pages[i]->dirty)
2349 				break;
2350 		}
2351 		boffset = (i << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2352 
2353 		for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2354 			if (bp->b_xio.xio_pages[i]->dirty) {
2355 				break;
2356 			}
2357 		}
2358 		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2359 
2360 		/*
2361 		 * Fit it to the buffer.
2362 		 */
2363 
2364 		if (eoffset > bp->b_bcount)
2365 			eoffset = bp->b_bcount;
2366 
2367 		/*
2368 		 * If we have a good dirty range, merge with the existing
2369 		 * dirty range.
2370 		 */
2371 
2372 		if (boffset < eoffset) {
2373 			if (bp->b_dirtyoff > boffset)
2374 				bp->b_dirtyoff = boffset;
2375 			if (bp->b_dirtyend < eoffset)
2376 				bp->b_dirtyend = eoffset;
2377 		}
2378 	}
2379 }
2380 
2381 /*
2382  * findblk:
2383  *
2384  *	Locate and return the specified buffer, or NULL if the buffer does
2385  *	not exist.  Do not attempt to lock the buffer or manipulate it in
2386  *	any way.  The caller must validate that the correct buffer has been
2387  *	obtain after locking it.
2388  */
2389 struct buf *
2390 findblk(struct vnode *vp, off_t loffset)
2391 {
2392 	struct buf *bp;
2393 
2394 	crit_enter();
2395 	bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2396 	crit_exit();
2397 	return(bp);
2398 }
2399 
2400 /*
2401  * getblk:
2402  *
2403  *	Get a block given a specified block and offset into a file/device.
2404  * 	B_INVAL may or may not be set on return.  The caller should clear
2405  *	B_INVAL prior to initiating a READ.
2406  *
2407  *	IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2408  *	IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2409  *	OR SET B_INVAL BEFORE RETIRING IT.  If you retire a getblk'd buffer
2410  *	without doing any of those things the system will likely believe
2411  *	the buffer to be valid (especially if it is not B_VMIO), and the
2412  *	next getblk() will return the buffer with B_CACHE set.
2413  *
2414  *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2415  *	an existing buffer.
2416  *
2417  *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2418  *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2419  *	and then cleared based on the backing VM.  If the previous buffer is
2420  *	non-0-sized but invalid, B_CACHE will be cleared.
2421  *
2422  *	If getblk() must create a new buffer, the new buffer is returned with
2423  *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2424  *	case it is returned with B_INVAL clear and B_CACHE set based on the
2425  *	backing VM.
2426  *
2427  *	getblk() also forces a bwrite() for any B_DELWRI buffer whos
2428  *	B_CACHE bit is clear.
2429  *
2430  *	What this means, basically, is that the caller should use B_CACHE to
2431  *	determine whether the buffer is fully valid or not and should clear
2432  *	B_INVAL prior to issuing a read.  If the caller intends to validate
2433  *	the buffer by loading its data area with something, the caller needs
2434  *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2435  *	the caller should set B_CACHE ( as an optimization ), else the caller
2436  *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2437  *	a write attempt or if it was a successfull read.  If the caller
2438  *	intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2439  *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2440  *
2441  *	getblk flags:
2442  *
2443  *	GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2444  *	GETBLK_BHEAVY - heavy-weight buffer cache buffer
2445  */
2446 struct buf *
2447 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2448 {
2449 	struct buf *bp;
2450 	int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2451 	int error;
2452 
2453 	if (size > MAXBSIZE)
2454 		panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2455 	if (vp->v_object == NULL)
2456 		panic("getblk: vnode %p has no object!", vp);
2457 
2458 	crit_enter();
2459 loop:
2460 	if ((bp = findblk(vp, loffset))) {
2461 		/*
2462 		 * The buffer was found in the cache, but we need to lock it.
2463 		 * Even with LK_NOWAIT the lockmgr may break our critical
2464 		 * section, so double-check the validity of the buffer
2465 		 * once the lock has been obtained.
2466 		 */
2467 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2468 			int lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2469 			if (blkflags & GETBLK_PCATCH)
2470 				lkflags |= LK_PCATCH;
2471 			error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2472 			if (error) {
2473 				if (error == ENOLCK)
2474 					goto loop;
2475 				crit_exit();
2476 				return (NULL);
2477 			}
2478 		}
2479 
2480 		/*
2481 		 * Once the buffer has been locked, make sure we didn't race
2482 		 * a buffer recyclement.  Buffers that are no longer hashed
2483 		 * will have b_vp == NULL, so this takes care of that check
2484 		 * as well.
2485 		 */
2486 		if (bp->b_vp != vp || bp->b_loffset != loffset) {
2487 			kprintf("Warning buffer %p (vp %p loffset %lld) was recycled\n", bp, vp, loffset);
2488 			BUF_UNLOCK(bp);
2489 			goto loop;
2490 		}
2491 
2492 		/*
2493 		 * All vnode-based buffers must be backed by a VM object.
2494 		 */
2495 		KKASSERT(bp->b_flags & B_VMIO);
2496 		KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2497 		bp->b_flags &= ~B_AGE;
2498 
2499 		/*
2500 		 * Make sure that B_INVAL buffers do not have a cached
2501 		 * block number translation.
2502 		 */
2503 		if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2504 			kprintf("Warning invalid buffer %p (vp %p loffset %lld) did not have cleared bio_offset cache\n", bp, vp, loffset);
2505 			clearbiocache(&bp->b_bio2);
2506 		}
2507 
2508 		/*
2509 		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2510 		 * invalid.
2511 		 */
2512 		if (bp->b_flags & B_INVAL)
2513 			bp->b_flags &= ~B_CACHE;
2514 		bremfree(bp);
2515 
2516 		/*
2517 		 * Any size inconsistancy with a dirty buffer or a buffer
2518 		 * with a softupdates dependancy must be resolved.  Resizing
2519 		 * the buffer in such circumstances can lead to problems.
2520 		 */
2521 		if (size != bp->b_bcount) {
2522 			if (bp->b_flags & B_DELWRI) {
2523 				bp->b_flags |= B_NOCACHE;
2524 				bwrite(bp);
2525 			} else if (LIST_FIRST(&bp->b_dep)) {
2526 				bp->b_flags |= B_NOCACHE;
2527 				bwrite(bp);
2528 			} else {
2529 				bp->b_flags |= B_RELBUF;
2530 				brelse(bp);
2531 			}
2532 			goto loop;
2533 		}
2534 		KKASSERT(size <= bp->b_kvasize);
2535 		KASSERT(bp->b_loffset != NOOFFSET,
2536 			("getblk: no buffer offset"));
2537 
2538 		/*
2539 		 * A buffer with B_DELWRI set and B_CACHE clear must
2540 		 * be committed before we can return the buffer in
2541 		 * order to prevent the caller from issuing a read
2542 		 * ( due to B_CACHE not being set ) and overwriting
2543 		 * it.
2544 		 *
2545 		 * Most callers, including NFS and FFS, need this to
2546 		 * operate properly either because they assume they
2547 		 * can issue a read if B_CACHE is not set, or because
2548 		 * ( for example ) an uncached B_DELWRI might loop due
2549 		 * to softupdates re-dirtying the buffer.  In the latter
2550 		 * case, B_CACHE is set after the first write completes,
2551 		 * preventing further loops.
2552 		 *
2553 		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2554 		 * above while extending the buffer, we cannot allow the
2555 		 * buffer to remain with B_CACHE set after the write
2556 		 * completes or it will represent a corrupt state.  To
2557 		 * deal with this we set B_NOCACHE to scrap the buffer
2558 		 * after the write.
2559 		 *
2560 		 * We might be able to do something fancy, like setting
2561 		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2562 		 * so the below call doesn't set B_CACHE, but that gets real
2563 		 * confusing.  This is much easier.
2564 		 */
2565 
2566 		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2567 			bp->b_flags |= B_NOCACHE;
2568 			bwrite(bp);
2569 			goto loop;
2570 		}
2571 		crit_exit();
2572 	} else {
2573 		/*
2574 		 * Buffer is not in-core, create new buffer.  The buffer
2575 		 * returned by getnewbuf() is locked.  Note that the returned
2576 		 * buffer is also considered valid (not marked B_INVAL).
2577 		 *
2578 		 * Calculating the offset for the I/O requires figuring out
2579 		 * the block size.  We use DEV_BSIZE for VBLK or VCHR and
2580 		 * the mount's f_iosize otherwise.  If the vnode does not
2581 		 * have an associated mount we assume that the passed size is
2582 		 * the block size.
2583 		 *
2584 		 * Note that vn_isdisk() cannot be used here since it may
2585 		 * return a failure for numerous reasons.   Note that the
2586 		 * buffer size may be larger then the block size (the caller
2587 		 * will use block numbers with the proper multiple).  Beware
2588 		 * of using any v_* fields which are part of unions.  In
2589 		 * particular, in DragonFly the mount point overloading
2590 		 * mechanism uses the namecache only and the underlying
2591 		 * directory vnode is not a special case.
2592 		 */
2593 		int bsize, maxsize;
2594 
2595 		if (vp->v_type == VBLK || vp->v_type == VCHR)
2596 			bsize = DEV_BSIZE;
2597 		else if (vp->v_mount)
2598 			bsize = vp->v_mount->mnt_stat.f_iosize;
2599 		else
2600 			bsize = size;
2601 
2602 		maxsize = size + (loffset & PAGE_MASK);
2603 		maxsize = imax(maxsize, bsize);
2604 
2605 		if ((bp = getnewbuf(blkflags, slptimeo, size, maxsize)) == NULL) {
2606 			if (slpflags || slptimeo) {
2607 				crit_exit();
2608 				return NULL;
2609 			}
2610 			goto loop;
2611 		}
2612 
2613 		/*
2614 		 * This code is used to make sure that a buffer is not
2615 		 * created while the getnewbuf routine is blocked.
2616 		 * This can be a problem whether the vnode is locked or not.
2617 		 * If the buffer is created out from under us, we have to
2618 		 * throw away the one we just created.  There is no window
2619 		 * race because we are safely running in a critical section
2620 		 * from the point of the duplicate buffer creation through
2621 		 * to here, and we've locked the buffer.
2622 		 */
2623 		if (findblk(vp, loffset)) {
2624 			bp->b_flags |= B_INVAL;
2625 			brelse(bp);
2626 			goto loop;
2627 		}
2628 
2629 		/*
2630 		 * Insert the buffer into the hash, so that it can
2631 		 * be found by findblk().
2632 		 *
2633 		 * Make sure the translation layer has been cleared.
2634 		 */
2635 		bp->b_loffset = loffset;
2636 		bp->b_bio2.bio_offset = NOOFFSET;
2637 		/* bp->b_bio2.bio_next = NULL; */
2638 
2639 		bgetvp(vp, bp);
2640 
2641 		/*
2642 		 * All vnode-based buffers must be backed by a VM object.
2643 		 */
2644 		KKASSERT(vp->v_object != NULL);
2645 		bp->b_flags |= B_VMIO;
2646 		KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2647 
2648 		allocbuf(bp, size);
2649 
2650 		crit_exit();
2651 	}
2652 	return (bp);
2653 }
2654 
2655 /*
2656  * regetblk(bp)
2657  *
2658  * Reacquire a buffer that was previously released to the locked queue,
2659  * or reacquire a buffer which is interlocked by having bioops->io_deallocate
2660  * set B_LOCKED (which handles the acquisition race).
2661  *
2662  * To this end, either B_LOCKED must be set or the dependancy list must be
2663  * non-empty.
2664  */
2665 void
2666 regetblk(struct buf *bp)
2667 {
2668 	KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
2669 	BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
2670 	crit_enter();
2671 	bremfree(bp);
2672 	crit_exit();
2673 }
2674 
2675 /*
2676  * geteblk:
2677  *
2678  *	Get an empty, disassociated buffer of given size.  The buffer is
2679  *	initially set to B_INVAL.
2680  *
2681  *	critical section protection is not required for the allocbuf()
2682  *	call because races are impossible here.
2683  */
2684 struct buf *
2685 geteblk(int size)
2686 {
2687 	struct buf *bp;
2688 	int maxsize;
2689 
2690 	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2691 
2692 	crit_enter();
2693 	while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2694 		;
2695 	crit_exit();
2696 	allocbuf(bp, size);
2697 	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2698 	return (bp);
2699 }
2700 
2701 
2702 /*
2703  * allocbuf:
2704  *
2705  *	This code constitutes the buffer memory from either anonymous system
2706  *	memory (in the case of non-VMIO operations) or from an associated
2707  *	VM object (in the case of VMIO operations).  This code is able to
2708  *	resize a buffer up or down.
2709  *
2710  *	Note that this code is tricky, and has many complications to resolve
2711  *	deadlock or inconsistant data situations.  Tread lightly!!!
2712  *	There are B_CACHE and B_DELWRI interactions that must be dealt with by
2713  *	the caller.  Calling this code willy nilly can result in the loss of data.
2714  *
2715  *	allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2716  *	B_CACHE for the non-VMIO case.
2717  *
2718  *	This routine does not need to be called from a critical section but you
2719  *	must own the buffer.
2720  */
2721 int
2722 allocbuf(struct buf *bp, int size)
2723 {
2724 	int newbsize, mbsize;
2725 	int i;
2726 
2727 	if (BUF_REFCNT(bp) == 0)
2728 		panic("allocbuf: buffer not busy");
2729 
2730 	if (bp->b_kvasize < size)
2731 		panic("allocbuf: buffer too small");
2732 
2733 	if ((bp->b_flags & B_VMIO) == 0) {
2734 		caddr_t origbuf;
2735 		int origbufsize;
2736 		/*
2737 		 * Just get anonymous memory from the kernel.  Don't
2738 		 * mess with B_CACHE.
2739 		 */
2740 		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2741 		if (bp->b_flags & B_MALLOC)
2742 			newbsize = mbsize;
2743 		else
2744 			newbsize = round_page(size);
2745 
2746 		if (newbsize < bp->b_bufsize) {
2747 			/*
2748 			 * Malloced buffers are not shrunk
2749 			 */
2750 			if (bp->b_flags & B_MALLOC) {
2751 				if (newbsize) {
2752 					bp->b_bcount = size;
2753 				} else {
2754 					kfree(bp->b_data, M_BIOBUF);
2755 					if (bp->b_bufsize) {
2756 						bufmallocspace -= bp->b_bufsize;
2757 						bufspacewakeup();
2758 						bp->b_bufsize = 0;
2759 					}
2760 					bp->b_data = bp->b_kvabase;
2761 					bp->b_bcount = 0;
2762 					bp->b_flags &= ~B_MALLOC;
2763 				}
2764 				return 1;
2765 			}
2766 			vm_hold_free_pages(
2767 			    bp,
2768 			    (vm_offset_t) bp->b_data + newbsize,
2769 			    (vm_offset_t) bp->b_data + bp->b_bufsize);
2770 		} else if (newbsize > bp->b_bufsize) {
2771 			/*
2772 			 * We only use malloced memory on the first allocation.
2773 			 * and revert to page-allocated memory when the buffer
2774 			 * grows.
2775 			 */
2776 			if ((bufmallocspace < maxbufmallocspace) &&
2777 				(bp->b_bufsize == 0) &&
2778 				(mbsize <= PAGE_SIZE/2)) {
2779 
2780 				bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
2781 				bp->b_bufsize = mbsize;
2782 				bp->b_bcount = size;
2783 				bp->b_flags |= B_MALLOC;
2784 				bufmallocspace += mbsize;
2785 				return 1;
2786 			}
2787 			origbuf = NULL;
2788 			origbufsize = 0;
2789 			/*
2790 			 * If the buffer is growing on its other-than-first
2791 			 * allocation, then we revert to the page-allocation
2792 			 * scheme.
2793 			 */
2794 			if (bp->b_flags & B_MALLOC) {
2795 				origbuf = bp->b_data;
2796 				origbufsize = bp->b_bufsize;
2797 				bp->b_data = bp->b_kvabase;
2798 				if (bp->b_bufsize) {
2799 					bufmallocspace -= bp->b_bufsize;
2800 					bufspacewakeup();
2801 					bp->b_bufsize = 0;
2802 				}
2803 				bp->b_flags &= ~B_MALLOC;
2804 				newbsize = round_page(newbsize);
2805 			}
2806 			vm_hold_load_pages(
2807 			    bp,
2808 			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2809 			    (vm_offset_t) bp->b_data + newbsize);
2810 			if (origbuf) {
2811 				bcopy(origbuf, bp->b_data, origbufsize);
2812 				kfree(origbuf, M_BIOBUF);
2813 			}
2814 		}
2815 	} else {
2816 		vm_page_t m;
2817 		int desiredpages;
2818 
2819 		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2820 		desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
2821 				newbsize + PAGE_MASK) >> PAGE_SHIFT;
2822 		KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
2823 
2824 		if (bp->b_flags & B_MALLOC)
2825 			panic("allocbuf: VMIO buffer can't be malloced");
2826 		/*
2827 		 * Set B_CACHE initially if buffer is 0 length or will become
2828 		 * 0-length.
2829 		 */
2830 		if (size == 0 || bp->b_bufsize == 0)
2831 			bp->b_flags |= B_CACHE;
2832 
2833 		if (newbsize < bp->b_bufsize) {
2834 			/*
2835 			 * DEV_BSIZE aligned new buffer size is less then the
2836 			 * DEV_BSIZE aligned existing buffer size.  Figure out
2837 			 * if we have to remove any pages.
2838 			 */
2839 			if (desiredpages < bp->b_xio.xio_npages) {
2840 				for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2841 					/*
2842 					 * the page is not freed here -- it
2843 					 * is the responsibility of
2844 					 * vnode_pager_setsize
2845 					 */
2846 					m = bp->b_xio.xio_pages[i];
2847 					KASSERT(m != bogus_page,
2848 					    ("allocbuf: bogus page found"));
2849 					while (vm_page_sleep_busy(m, TRUE, "biodep"))
2850 						;
2851 
2852 					bp->b_xio.xio_pages[i] = NULL;
2853 					vm_page_unwire(m, 0);
2854 				}
2855 				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2856 				    (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2857 				bp->b_xio.xio_npages = desiredpages;
2858 			}
2859 		} else if (size > bp->b_bcount) {
2860 			/*
2861 			 * We are growing the buffer, possibly in a
2862 			 * byte-granular fashion.
2863 			 */
2864 			struct vnode *vp;
2865 			vm_object_t obj;
2866 			vm_offset_t toff;
2867 			vm_offset_t tinc;
2868 
2869 			/*
2870 			 * Step 1, bring in the VM pages from the object,
2871 			 * allocating them if necessary.  We must clear
2872 			 * B_CACHE if these pages are not valid for the
2873 			 * range covered by the buffer.
2874 			 *
2875 			 * critical section protection is required to protect
2876 			 * against interrupts unbusying and freeing pages
2877 			 * between our vm_page_lookup() and our
2878 			 * busycheck/wiring call.
2879 			 */
2880 			vp = bp->b_vp;
2881 			obj = vp->v_object;
2882 
2883 			crit_enter();
2884 			while (bp->b_xio.xio_npages < desiredpages) {
2885 				vm_page_t m;
2886 				vm_pindex_t pi;
2887 
2888 				pi = OFF_TO_IDX(bp->b_loffset) + bp->b_xio.xio_npages;
2889 				if ((m = vm_page_lookup(obj, pi)) == NULL) {
2890 					/*
2891 					 * note: must allocate system pages
2892 					 * since blocking here could intefere
2893 					 * with paging I/O, no matter which
2894 					 * process we are.
2895 					 */
2896 					m = bio_page_alloc(obj, pi, desiredpages - bp->b_xio.xio_npages);
2897 					if (m) {
2898 						vm_page_wire(m);
2899 						vm_page_wakeup(m);
2900 						bp->b_flags &= ~B_CACHE;
2901 						bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2902 						++bp->b_xio.xio_npages;
2903 					}
2904 					continue;
2905 				}
2906 
2907 				/*
2908 				 * We found a page.  If we have to sleep on it,
2909 				 * retry because it might have gotten freed out
2910 				 * from under us.
2911 				 *
2912 				 * We can only test PG_BUSY here.  Blocking on
2913 				 * m->busy might lead to a deadlock:
2914 				 *
2915 				 *  vm_fault->getpages->cluster_read->allocbuf
2916 				 *
2917 				 */
2918 
2919 				if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2920 					continue;
2921 
2922 				/*
2923 				 * We have a good page.  Should we wakeup the
2924 				 * page daemon?
2925 				 */
2926 				if ((curthread != pagethread) &&
2927 				    ((m->queue - m->pc) == PQ_CACHE) &&
2928 				    ((vmstats.v_free_count + vmstats.v_cache_count) <
2929 					(vmstats.v_free_min + vmstats.v_cache_min))) {
2930 					pagedaemon_wakeup();
2931 				}
2932 				vm_page_flag_clear(m, PG_ZERO);
2933 				vm_page_wire(m);
2934 				bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2935 				++bp->b_xio.xio_npages;
2936 			}
2937 			crit_exit();
2938 
2939 			/*
2940 			 * Step 2.  We've loaded the pages into the buffer,
2941 			 * we have to figure out if we can still have B_CACHE
2942 			 * set.  Note that B_CACHE is set according to the
2943 			 * byte-granular range ( bcount and size ), not the
2944 			 * aligned range ( newbsize ).
2945 			 *
2946 			 * The VM test is against m->valid, which is DEV_BSIZE
2947 			 * aligned.  Needless to say, the validity of the data
2948 			 * needs to also be DEV_BSIZE aligned.  Note that this
2949 			 * fails with NFS if the server or some other client
2950 			 * extends the file's EOF.  If our buffer is resized,
2951 			 * B_CACHE may remain set! XXX
2952 			 */
2953 
2954 			toff = bp->b_bcount;
2955 			tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
2956 
2957 			while ((bp->b_flags & B_CACHE) && toff < size) {
2958 				vm_pindex_t pi;
2959 
2960 				if (tinc > (size - toff))
2961 					tinc = size - toff;
2962 
2963 				pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
2964 				    PAGE_SHIFT;
2965 
2966 				vfs_buf_test_cache(
2967 				    bp,
2968 				    bp->b_loffset,
2969 				    toff,
2970 				    tinc,
2971 				    bp->b_xio.xio_pages[pi]
2972 				);
2973 				toff += tinc;
2974 				tinc = PAGE_SIZE;
2975 			}
2976 
2977 			/*
2978 			 * Step 3, fixup the KVM pmap.  Remember that
2979 			 * bp->b_data is relative to bp->b_loffset, but
2980 			 * bp->b_loffset may be offset into the first page.
2981 			 */
2982 
2983 			bp->b_data = (caddr_t)
2984 			    trunc_page((vm_offset_t)bp->b_data);
2985 			pmap_qenter(
2986 			    (vm_offset_t)bp->b_data,
2987 			    bp->b_xio.xio_pages,
2988 			    bp->b_xio.xio_npages
2989 			);
2990 			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2991 			    (vm_offset_t)(bp->b_loffset & PAGE_MASK));
2992 		}
2993 	}
2994 
2995 	/* adjust space use on already-dirty buffer */
2996 	if (bp->b_flags & B_DELWRI) {
2997 		dirtybufspace += newbsize - bp->b_bufsize;
2998 		if (bp->b_flags & B_HEAVY)
2999 			dirtybufspacehw += newbsize - bp->b_bufsize;
3000 	}
3001 	if (newbsize < bp->b_bufsize)
3002 		bufspacewakeup();
3003 	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
3004 	bp->b_bcount = size;		/* requested buffer size	*/
3005 	return 1;
3006 }
3007 
3008 /*
3009  * biowait:
3010  *
3011  *	Wait for buffer I/O completion, returning error status.  The buffer
3012  *	is left locked on return.  B_EINTR is converted into an EINTR error
3013  *	and cleared.
3014  *
3015  *	NOTE!  The original b_cmd is lost on return, since b_cmd will be
3016  *	set to BUF_CMD_DONE.
3017  */
3018 int
3019 biowait(struct buf *bp)
3020 {
3021 	crit_enter();
3022 	while (bp->b_cmd != BUF_CMD_DONE) {
3023 		if (bp->b_cmd == BUF_CMD_READ)
3024 			tsleep(bp, 0, "biord", 0);
3025 		else
3026 			tsleep(bp, 0, "biowr", 0);
3027 	}
3028 	crit_exit();
3029 	if (bp->b_flags & B_EINTR) {
3030 		bp->b_flags &= ~B_EINTR;
3031 		return (EINTR);
3032 	}
3033 	if (bp->b_flags & B_ERROR) {
3034 		return (bp->b_error ? bp->b_error : EIO);
3035 	} else {
3036 		return (0);
3037 	}
3038 }
3039 
3040 /*
3041  * This associates a tracking count with an I/O.  vn_strategy() and
3042  * dev_dstrategy() do this automatically but there are a few cases
3043  * where a vnode or device layer is bypassed when a block translation
3044  * is cached.  In such cases bio_start_transaction() may be called on
3045  * the bypassed layers so the system gets an I/O in progress indication
3046  * for those higher layers.
3047  */
3048 void
3049 bio_start_transaction(struct bio *bio, struct bio_track *track)
3050 {
3051 	bio->bio_track = track;
3052 	atomic_add_int(&track->bk_active, 1);
3053 }
3054 
3055 /*
3056  * Initiate I/O on a vnode.
3057  */
3058 void
3059 vn_strategy(struct vnode *vp, struct bio *bio)
3060 {
3061 	struct bio_track *track;
3062 
3063 	KKASSERT(bio->bio_buf->b_cmd != BUF_CMD_DONE);
3064         if (bio->bio_buf->b_cmd == BUF_CMD_READ)
3065                 track = &vp->v_track_read;
3066         else
3067                 track = &vp->v_track_write;
3068 	bio->bio_track = track;
3069 	atomic_add_int(&track->bk_active, 1);
3070         vop_strategy(*vp->v_ops, vp, bio);
3071 }
3072 
3073 
3074 /*
3075  * biodone:
3076  *
3077  *	Finish I/O on a buffer, optionally calling a completion function.
3078  *	This is usually called from an interrupt so process blocking is
3079  *	not allowed.
3080  *
3081  *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3082  *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3083  *	assuming B_INVAL is clear.
3084  *
3085  *	For the VMIO case, we set B_CACHE if the op was a read and no
3086  *	read error occured, or if the op was a write.  B_CACHE is never
3087  *	set if the buffer is invalid or otherwise uncacheable.
3088  *
3089  *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3090  *	initiator to leave B_INVAL set to brelse the buffer out of existance
3091  *	in the biodone routine.
3092  */
3093 void
3094 biodone(struct bio *bio)
3095 {
3096 	struct buf *bp = bio->bio_buf;
3097 	buf_cmd_t cmd;
3098 
3099 	crit_enter();
3100 
3101 	KASSERT(BUF_REFCNTNB(bp) > 0,
3102 		("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3103 	KASSERT(bp->b_cmd != BUF_CMD_DONE,
3104 		("biodone: bp %p already done!", bp));
3105 
3106 	runningbufwakeup(bp);
3107 
3108 	/*
3109 	 * Run up the chain of BIO's.   Leave b_cmd intact for the duration.
3110 	 */
3111 	while (bio) {
3112 		biodone_t *done_func;
3113 		struct bio_track *track;
3114 
3115 		/*
3116 		 * BIO tracking.  Most but not all BIOs are tracked.
3117 		 */
3118 		if ((track = bio->bio_track) != NULL) {
3119 			atomic_subtract_int(&track->bk_active, 1);
3120 			if (track->bk_active < 0) {
3121 				panic("biodone: bad active count bio %p\n",
3122 				      bio);
3123 			}
3124 			if (track->bk_waitflag) {
3125 				track->bk_waitflag = 0;
3126 				wakeup(track);
3127 			}
3128 			bio->bio_track = NULL;
3129 		}
3130 
3131 		/*
3132 		 * A bio_done function terminates the loop.  The function
3133 		 * will be responsible for any further chaining and/or
3134 		 * buffer management.
3135 		 *
3136 		 * WARNING!  The done function can deallocate the buffer!
3137 		 */
3138 		if ((done_func = bio->bio_done) != NULL) {
3139 			bio->bio_done = NULL;
3140 			done_func(bio);
3141 			crit_exit();
3142 			return;
3143 		}
3144 		bio = bio->bio_prev;
3145 	}
3146 
3147 	cmd = bp->b_cmd;
3148 	bp->b_cmd = BUF_CMD_DONE;
3149 
3150 	/*
3151 	 * Only reads and writes are processed past this point.
3152 	 */
3153 	if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3154 		brelse(bp);
3155 		crit_exit();
3156 		return;
3157 	}
3158 
3159 	/*
3160 	 * Warning: softupdates may re-dirty the buffer.
3161 	 */
3162 	if (LIST_FIRST(&bp->b_dep) != NULL)
3163 		buf_complete(bp);
3164 
3165 	if (bp->b_flags & B_VMIO) {
3166 		int i;
3167 		vm_ooffset_t foff;
3168 		vm_page_t m;
3169 		vm_object_t obj;
3170 		int iosize;
3171 		struct vnode *vp = bp->b_vp;
3172 
3173 		obj = vp->v_object;
3174 
3175 #if defined(VFS_BIO_DEBUG)
3176 		if (vp->v_auxrefs == 0)
3177 			panic("biodone: zero vnode hold count");
3178 		if ((vp->v_flag & VOBJBUF) == 0)
3179 			panic("biodone: vnode is not setup for merged cache");
3180 #endif
3181 
3182 		foff = bp->b_loffset;
3183 		KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3184 		KASSERT(obj != NULL, ("biodone: missing VM object"));
3185 
3186 #if defined(VFS_BIO_DEBUG)
3187 		if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3188 			kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
3189 			    obj->paging_in_progress, bp->b_xio.xio_npages);
3190 		}
3191 #endif
3192 
3193 		/*
3194 		 * Set B_CACHE if the op was a normal read and no error
3195 		 * occured.  B_CACHE is set for writes in the b*write()
3196 		 * routines.
3197 		 */
3198 		iosize = bp->b_bcount - bp->b_resid;
3199 		if (cmd == BUF_CMD_READ && (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3200 			bp->b_flags |= B_CACHE;
3201 		}
3202 
3203 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
3204 			int bogusflag = 0;
3205 			int resid;
3206 
3207 			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3208 			if (resid > iosize)
3209 				resid = iosize;
3210 
3211 			/*
3212 			 * cleanup bogus pages, restoring the originals.  Since
3213 			 * the originals should still be wired, we don't have
3214 			 * to worry about interrupt/freeing races destroying
3215 			 * the VM object association.
3216 			 */
3217 			m = bp->b_xio.xio_pages[i];
3218 			if (m == bogus_page) {
3219 				bogusflag = 1;
3220 				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3221 				if (m == NULL)
3222 					panic("biodone: page disappeared");
3223 				bp->b_xio.xio_pages[i] = m;
3224 				pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3225 					bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3226 			}
3227 #if defined(VFS_BIO_DEBUG)
3228 			if (OFF_TO_IDX(foff) != m->pindex) {
3229 				kprintf(
3230 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
3231 				    (unsigned long)foff, m->pindex);
3232 			}
3233 #endif
3234 
3235 			/*
3236 			 * In the write case, the valid and clean bits are
3237 			 * already changed correctly ( see bdwrite() ), so we
3238 			 * only need to do this here in the read case.
3239 			 */
3240 			if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3241 				vfs_page_set_valid(bp, foff, i, m);
3242 			}
3243 			vm_page_flag_clear(m, PG_ZERO);
3244 
3245 			/*
3246 			 * when debugging new filesystems or buffer I/O methods, this
3247 			 * is the most common error that pops up.  if you see this, you
3248 			 * have not set the page busy flag correctly!!!
3249 			 */
3250 			if (m->busy == 0) {
3251 				kprintf("biodone: page busy < 0, "
3252 				    "pindex: %d, foff: 0x(%x,%x), "
3253 				    "resid: %d, index: %d\n",
3254 				    (int) m->pindex, (int)(foff >> 32),
3255 						(int) foff & 0xffffffff, resid, i);
3256 				if (!vn_isdisk(vp, NULL))
3257 					kprintf(" iosize: %ld, loffset: %lld, flags: 0x%08x, npages: %d\n",
3258 					    bp->b_vp->v_mount->mnt_stat.f_iosize,
3259 					    bp->b_loffset,
3260 					    bp->b_flags, bp->b_xio.xio_npages);
3261 				else
3262 					kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3263 					    bp->b_loffset,
3264 					    bp->b_flags, bp->b_xio.xio_npages);
3265 				kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3266 				    m->valid, m->dirty, m->wire_count);
3267 				panic("biodone: page busy < 0");
3268 			}
3269 			vm_page_io_finish(m);
3270 			vm_object_pip_subtract(obj, 1);
3271 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3272 			iosize -= resid;
3273 		}
3274 		if (obj)
3275 			vm_object_pip_wakeupn(obj, 0);
3276 	}
3277 
3278 	/*
3279 	 * For asynchronous completions, release the buffer now. The brelse
3280 	 * will do a wakeup there if necessary - so no need to do a wakeup
3281 	 * here in the async case. The sync case always needs to do a wakeup.
3282 	 */
3283 
3284 	if (bp->b_flags & B_ASYNC) {
3285 		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
3286 			brelse(bp);
3287 		else
3288 			bqrelse(bp);
3289 	} else {
3290 		wakeup(bp);
3291 	}
3292 	crit_exit();
3293 }
3294 
3295 /*
3296  * vfs_unbusy_pages:
3297  *
3298  *	This routine is called in lieu of iodone in the case of
3299  *	incomplete I/O.  This keeps the busy status for pages
3300  *	consistant.
3301  */
3302 void
3303 vfs_unbusy_pages(struct buf *bp)
3304 {
3305 	int i;
3306 
3307 	runningbufwakeup(bp);
3308 	if (bp->b_flags & B_VMIO) {
3309 		struct vnode *vp = bp->b_vp;
3310 		vm_object_t obj;
3311 
3312 		obj = vp->v_object;
3313 
3314 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
3315 			vm_page_t m = bp->b_xio.xio_pages[i];
3316 
3317 			/*
3318 			 * When restoring bogus changes the original pages
3319 			 * should still be wired, so we are in no danger of
3320 			 * losing the object association and do not need
3321 			 * critical section protection particularly.
3322 			 */
3323 			if (m == bogus_page) {
3324 				m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3325 				if (!m) {
3326 					panic("vfs_unbusy_pages: page missing");
3327 				}
3328 				bp->b_xio.xio_pages[i] = m;
3329 				pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3330 					bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3331 			}
3332 			vm_object_pip_subtract(obj, 1);
3333 			vm_page_flag_clear(m, PG_ZERO);
3334 			vm_page_io_finish(m);
3335 		}
3336 		vm_object_pip_wakeupn(obj, 0);
3337 	}
3338 }
3339 
3340 /*
3341  * vfs_page_set_valid:
3342  *
3343  *	Set the valid bits in a page based on the supplied offset.   The
3344  *	range is restricted to the buffer's size.
3345  *
3346  *	This routine is typically called after a read completes.
3347  */
3348 static void
3349 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3350 {
3351 	vm_ooffset_t soff, eoff;
3352 
3353 	/*
3354 	 * Start and end offsets in buffer.  eoff - soff may not cross a
3355 	 * page boundry or cross the end of the buffer.  The end of the
3356 	 * buffer, in this case, is our file EOF, not the allocation size
3357 	 * of the buffer.
3358 	 */
3359 	soff = off;
3360 	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3361 	if (eoff > bp->b_loffset + bp->b_bcount)
3362 		eoff = bp->b_loffset + bp->b_bcount;
3363 
3364 	/*
3365 	 * Set valid range.  This is typically the entire buffer and thus the
3366 	 * entire page.
3367 	 */
3368 	if (eoff > soff) {
3369 		vm_page_set_validclean(
3370 		    m,
3371 		   (vm_offset_t) (soff & PAGE_MASK),
3372 		   (vm_offset_t) (eoff - soff)
3373 		);
3374 	}
3375 }
3376 
3377 /*
3378  * vfs_busy_pages:
3379  *
3380  *	This routine is called before a device strategy routine.
3381  *	It is used to tell the VM system that paging I/O is in
3382  *	progress, and treat the pages associated with the buffer
3383  *	almost as being PG_BUSY.  Also the object 'paging_in_progress'
3384  *	flag is handled to make sure that the object doesn't become
3385  *	inconsistant.
3386  *
3387  *	Since I/O has not been initiated yet, certain buffer flags
3388  *	such as B_ERROR or B_INVAL may be in an inconsistant state
3389  *	and should be ignored.
3390  */
3391 void
3392 vfs_busy_pages(struct vnode *vp, struct buf *bp)
3393 {
3394 	int i, bogus;
3395 	struct lwp *lp = curthread->td_lwp;
3396 
3397 	/*
3398 	 * The buffer's I/O command must already be set.  If reading,
3399 	 * B_CACHE must be 0 (double check against callers only doing
3400 	 * I/O when B_CACHE is 0).
3401 	 */
3402 	KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3403 	KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
3404 
3405 	if (bp->b_flags & B_VMIO) {
3406 		vm_object_t obj;
3407 		vm_ooffset_t foff;
3408 
3409 		obj = vp->v_object;
3410 		foff = bp->b_loffset;
3411 		KASSERT(bp->b_loffset != NOOFFSET,
3412 			("vfs_busy_pages: no buffer offset"));
3413 		vfs_setdirty(bp);
3414 
3415 		/*
3416 		 * Loop until none of the pages are busy.
3417 		 */
3418 retry:
3419 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
3420 			vm_page_t m = bp->b_xio.xio_pages[i];
3421 
3422 			if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3423 				goto retry;
3424 		}
3425 
3426 		/*
3427 		 * Setup for I/O, soft-busy the page right now because
3428 		 * the next loop may block.
3429 		 */
3430 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
3431 			vm_page_t m = bp->b_xio.xio_pages[i];
3432 
3433 			vm_page_flag_clear(m, PG_ZERO);
3434 			if ((bp->b_flags & B_CLUSTER) == 0) {
3435 				vm_object_pip_add(obj, 1);
3436 				vm_page_io_start(m);
3437 			}
3438 		}
3439 
3440 		/*
3441 		 * Adjust protections for I/O and do bogus-page mapping.
3442 		 * Assume that vm_page_protect() can block (it can block
3443 		 * if VM_PROT_NONE, don't take any chances regardless).
3444 		 */
3445 		bogus = 0;
3446 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
3447 			vm_page_t m = bp->b_xio.xio_pages[i];
3448 
3449 			/*
3450 			 * When readying a vnode-backed buffer for a write
3451 			 * we must zero-fill any invalid portions of the
3452 			 * backing VM pages.
3453 			 *
3454 			 * When readying a vnode-backed buffer for a read
3455 			 * we must replace any dirty pages with a bogus
3456 			 * page so we do not destroy dirty data when
3457 			 * filling in gaps.  Dirty pages might not
3458 			 * necessarily be marked dirty yet, so use m->valid
3459 			 * as a reasonable test.
3460 			 *
3461 			 * Bogus page replacement is, uh, bogus.  We need
3462 			 * to find a better way.
3463 			 */
3464 			if (bp->b_cmd == BUF_CMD_WRITE) {
3465 				vm_page_protect(m, VM_PROT_READ);
3466 				vfs_page_set_valid(bp, foff, i, m);
3467 			} else if (m->valid == VM_PAGE_BITS_ALL) {
3468 				bp->b_xio.xio_pages[i] = bogus_page;
3469 				bogus++;
3470 			} else {
3471 				vm_page_protect(m, VM_PROT_NONE);
3472 			}
3473 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3474 		}
3475 		if (bogus)
3476 			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3477 				bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3478 	}
3479 
3480 	/*
3481 	 * This is the easiest place to put the process accounting for the I/O
3482 	 * for now.
3483 	 */
3484 	if (lp != NULL) {
3485 		if (bp->b_cmd == BUF_CMD_READ)
3486 			lp->lwp_ru.ru_inblock++;
3487 		else
3488 			lp->lwp_ru.ru_oublock++;
3489 	}
3490 }
3491 
3492 /*
3493  * vfs_clean_pages:
3494  *
3495  *	Tell the VM system that the pages associated with this buffer
3496  *	are clean.  This is used for delayed writes where the data is
3497  *	going to go to disk eventually without additional VM intevention.
3498  *
3499  *	Note that while we only really need to clean through to b_bcount, we
3500  *	just go ahead and clean through to b_bufsize.
3501  */
3502 static void
3503 vfs_clean_pages(struct buf *bp)
3504 {
3505 	int i;
3506 
3507 	if (bp->b_flags & B_VMIO) {
3508 		vm_ooffset_t foff;
3509 
3510 		foff = bp->b_loffset;
3511 		KASSERT(foff != NOOFFSET, ("vfs_clean_pages: no buffer offset"));
3512 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
3513 			vm_page_t m = bp->b_xio.xio_pages[i];
3514 			vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3515 			vm_ooffset_t eoff = noff;
3516 
3517 			if (eoff > bp->b_loffset + bp->b_bufsize)
3518 				eoff = bp->b_loffset + bp->b_bufsize;
3519 			vfs_page_set_valid(bp, foff, i, m);
3520 			/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3521 			foff = noff;
3522 		}
3523 	}
3524 }
3525 
3526 /*
3527  * vfs_bio_set_validclean:
3528  *
3529  *	Set the range within the buffer to valid and clean.  The range is
3530  *	relative to the beginning of the buffer, b_loffset.  Note that
3531  *	b_loffset itself may be offset from the beginning of the first page.
3532  */
3533 
3534 void
3535 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3536 {
3537 	if (bp->b_flags & B_VMIO) {
3538 		int i;
3539 		int n;
3540 
3541 		/*
3542 		 * Fixup base to be relative to beginning of first page.
3543 		 * Set initial n to be the maximum number of bytes in the
3544 		 * first page that can be validated.
3545 		 */
3546 
3547 		base += (bp->b_loffset & PAGE_MASK);
3548 		n = PAGE_SIZE - (base & PAGE_MASK);
3549 
3550 		for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3551 			vm_page_t m = bp->b_xio.xio_pages[i];
3552 
3553 			if (n > size)
3554 				n = size;
3555 
3556 			vm_page_set_validclean(m, base & PAGE_MASK, n);
3557 			base += n;
3558 			size -= n;
3559 			n = PAGE_SIZE;
3560 		}
3561 	}
3562 }
3563 
3564 /*
3565  * vfs_bio_clrbuf:
3566  *
3567  *	Clear a buffer.  This routine essentially fakes an I/O, so we need
3568  *	to clear B_ERROR and B_INVAL.
3569  *
3570  *	Note that while we only theoretically need to clear through b_bcount,
3571  *	we go ahead and clear through b_bufsize.
3572  */
3573 
3574 void
3575 vfs_bio_clrbuf(struct buf *bp)
3576 {
3577 	int i, mask = 0;
3578 	caddr_t sa, ea;
3579 	if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3580 		bp->b_flags &= ~(B_INVAL|B_ERROR);
3581 		if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3582 		    (bp->b_loffset & PAGE_MASK) == 0) {
3583 			mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3584 			if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3585 				bp->b_resid = 0;
3586 				return;
3587 			}
3588 			if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3589 			    ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3590 				bzero(bp->b_data, bp->b_bufsize);
3591 				bp->b_xio.xio_pages[0]->valid |= mask;
3592 				bp->b_resid = 0;
3593 				return;
3594 			}
3595 		}
3596 		ea = sa = bp->b_data;
3597 		for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3598 			int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3599 			ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3600 			ea = (caddr_t)(vm_offset_t)ulmin(
3601 			    (u_long)(vm_offset_t)ea,
3602 			    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3603 			mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3604 			if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3605 				continue;
3606 			if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3607 				if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3608 					bzero(sa, ea - sa);
3609 				}
3610 			} else {
3611 				for (; sa < ea; sa += DEV_BSIZE, j++) {
3612 					if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3613 						(bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3614 						bzero(sa, DEV_BSIZE);
3615 				}
3616 			}
3617 			bp->b_xio.xio_pages[i]->valid |= mask;
3618 			vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3619 		}
3620 		bp->b_resid = 0;
3621 	} else {
3622 		clrbuf(bp);
3623 	}
3624 }
3625 
3626 /*
3627  * vm_hold_load_pages:
3628  *
3629  *	Load pages into the buffer's address space.  The pages are
3630  *	allocated from the kernel object in order to reduce interference
3631  *	with the any VM paging I/O activity.  The range of loaded
3632  *	pages will be wired.
3633  *
3634  *	If a page cannot be allocated, the 'pagedaemon' is woken up to
3635  *	retrieve the full range (to - from) of pages.
3636  *
3637  */
3638 void
3639 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3640 {
3641 	vm_offset_t pg;
3642 	vm_page_t p;
3643 	int index;
3644 
3645 	to = round_page(to);
3646 	from = round_page(from);
3647 	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3648 
3649 	pg = from;
3650 	while (pg < to) {
3651 		/*
3652 		 * Note: must allocate system pages since blocking here
3653 		 * could intefere with paging I/O, no matter which
3654 		 * process we are.
3655 		 */
3656 		p = bio_page_alloc(&kernel_object, pg >> PAGE_SHIFT,
3657 				   (vm_pindex_t)((to - pg) >> PAGE_SHIFT));
3658 		if (p) {
3659 			vm_page_wire(p);
3660 			p->valid = VM_PAGE_BITS_ALL;
3661 			vm_page_flag_clear(p, PG_ZERO);
3662 			pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3663 			bp->b_xio.xio_pages[index] = p;
3664 			vm_page_wakeup(p);
3665 
3666 			pg += PAGE_SIZE;
3667 			++index;
3668 		}
3669 	}
3670 	bp->b_xio.xio_npages = index;
3671 }
3672 
3673 /*
3674  * Allocate pages for a buffer cache buffer.
3675  *
3676  * Under extremely severe memory conditions even allocating out of the
3677  * system reserve can fail.  If this occurs we must allocate out of the
3678  * interrupt reserve to avoid a deadlock with the pageout daemon.
3679  *
3680  * The pageout daemon can run (putpages -> VOP_WRITE -> getblk -> allocbuf).
3681  * If the buffer cache's vm_page_alloc() fails a vm_wait() can deadlock
3682  * against the pageout daemon if pages are not freed from other sources.
3683  */
3684 static
3685 vm_page_t
3686 bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit)
3687 {
3688 	vm_page_t p;
3689 
3690 	/*
3691 	 * Try a normal allocation, allow use of system reserve.
3692 	 */
3693 	p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3694 	if (p)
3695 		return(p);
3696 
3697 	/*
3698 	 * The normal allocation failed and we clearly have a page
3699 	 * deficit.  Try to reclaim some clean VM pages directly
3700 	 * from the buffer cache.
3701 	 */
3702 	vm_pageout_deficit += deficit;
3703 	recoverbufpages();
3704 
3705 	/*
3706 	 * We may have blocked, the caller will know what to do if the
3707 	 * page now exists.
3708 	 */
3709 	if (vm_page_lookup(obj, pg))
3710 		return(NULL);
3711 
3712 	/*
3713 	 * Allocate and allow use of the interrupt reserve.
3714 	 *
3715 	 * If after all that we still can't allocate a VM page we are
3716 	 * in real trouble, but we slog on anyway hoping that the system
3717 	 * won't deadlock.
3718 	 */
3719 	p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
3720 				   VM_ALLOC_INTERRUPT);
3721 	if (p) {
3722 		kprintf("bio_page_alloc: WARNING emergency page "
3723 			"allocation\n");
3724 		if (vm_page_count_severe())
3725 			vm_wait(hz / 20);
3726 	} else {
3727 		kprintf("bio_page_alloc: WARNING emergency page "
3728 			"allocation failed\n");
3729 		vm_wait(hz * 5);
3730 	}
3731 	return(p);
3732 }
3733 
3734 /*
3735  * vm_hold_free_pages:
3736  *
3737  *	Return pages associated with the buffer back to the VM system.
3738  *
3739  *	The range of pages underlying the buffer's address space will
3740  *	be unmapped and un-wired.
3741  */
3742 void
3743 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3744 {
3745 	vm_offset_t pg;
3746 	vm_page_t p;
3747 	int index, newnpages;
3748 
3749 	from = round_page(from);
3750 	to = round_page(to);
3751 	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3752 
3753 	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3754 		p = bp->b_xio.xio_pages[index];
3755 		if (p && (index < bp->b_xio.xio_npages)) {
3756 			if (p->busy) {
3757 				kprintf("vm_hold_free_pages: doffset: %lld, loffset: %lld\n",
3758 					bp->b_bio2.bio_offset, bp->b_loffset);
3759 			}
3760 			bp->b_xio.xio_pages[index] = NULL;
3761 			pmap_kremove(pg);
3762 			vm_page_busy(p);
3763 			vm_page_unwire(p, 0);
3764 			vm_page_free(p);
3765 		}
3766 	}
3767 	bp->b_xio.xio_npages = newnpages;
3768 }
3769 
3770 /*
3771  * vmapbuf:
3772  *
3773  *	Map a user buffer into KVM via a pbuf.  On return the buffer's
3774  *	b_data, b_bufsize, and b_bcount will be set, and its XIO page array
3775  *	initialized.
3776  */
3777 int
3778 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
3779 {
3780 	caddr_t addr;
3781 	vm_offset_t va;
3782 	vm_page_t m;
3783 	int vmprot;
3784 	int error;
3785 	int pidx;
3786 	int i;
3787 
3788 	/*
3789 	 * bp had better have a command and it better be a pbuf.
3790 	 */
3791 	KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3792 	KKASSERT(bp->b_flags & B_PAGING);
3793 
3794 	if (bytes < 0)
3795 		return (-1);
3796 
3797 	/*
3798 	 * Map the user data into KVM.  Mappings have to be page-aligned.
3799 	 */
3800 	addr = (caddr_t)trunc_page((vm_offset_t)udata);
3801 	pidx = 0;
3802 
3803 	vmprot = VM_PROT_READ;
3804 	if (bp->b_cmd == BUF_CMD_READ)
3805 		vmprot |= VM_PROT_WRITE;
3806 
3807 	while (addr < udata + bytes) {
3808 		/*
3809 		 * Do the vm_fault if needed; do the copy-on-write thing
3810 		 * when reading stuff off device into memory.
3811 		 *
3812 		 * vm_fault_page*() returns a held VM page.
3813 		 */
3814 		va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
3815 		va = trunc_page(va);
3816 
3817 		m = vm_fault_page_quick(va, vmprot, &error);
3818 		if (m == NULL) {
3819 			for (i = 0; i < pidx; ++i) {
3820 			    vm_page_unhold(bp->b_xio.xio_pages[i]);
3821 			    bp->b_xio.xio_pages[i] = NULL;
3822 			}
3823 			return(-1);
3824 		}
3825 		bp->b_xio.xio_pages[pidx] = m;
3826 		addr += PAGE_SIZE;
3827 		++pidx;
3828 	}
3829 
3830 	/*
3831 	 * Map the page array and set the buffer fields to point to
3832 	 * the mapped data buffer.
3833 	 */
3834 	if (pidx > btoc(MAXPHYS))
3835 		panic("vmapbuf: mapped more than MAXPHYS");
3836 	pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
3837 
3838 	bp->b_xio.xio_npages = pidx;
3839 	bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
3840 	bp->b_bcount = bytes;
3841 	bp->b_bufsize = bytes;
3842 	return(0);
3843 }
3844 
3845 /*
3846  * vunmapbuf:
3847  *
3848  *	Free the io map PTEs associated with this IO operation.
3849  *	We also invalidate the TLB entries and restore the original b_addr.
3850  */
3851 void
3852 vunmapbuf(struct buf *bp)
3853 {
3854 	int pidx;
3855 	int npages;
3856 
3857 	KKASSERT(bp->b_flags & B_PAGING);
3858 
3859 	npages = bp->b_xio.xio_npages;
3860 	pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3861 	for (pidx = 0; pidx < npages; ++pidx) {
3862 		vm_page_unhold(bp->b_xio.xio_pages[pidx]);
3863 		bp->b_xio.xio_pages[pidx] = NULL;
3864 	}
3865 	bp->b_xio.xio_npages = 0;
3866 	bp->b_data = bp->b_kvabase;
3867 }
3868 
3869 /*
3870  * Scan all buffers in the system and issue the callback.
3871  */
3872 int
3873 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
3874 {
3875 	int count = 0;
3876 	int error;
3877 	int n;
3878 
3879 	for (n = 0; n < nbuf; ++n) {
3880 		if ((error = callback(&buf[n], info)) < 0) {
3881 			count = error;
3882 			break;
3883 		}
3884 		count += error;
3885 	}
3886 	return (count);
3887 }
3888 
3889 /*
3890  * print out statistics from the current status of the buffer pool
3891  * this can be toggeled by the system control option debug.syncprt
3892  */
3893 #ifdef DEBUG
3894 void
3895 vfs_bufstats(void)
3896 {
3897         int i, j, count;
3898         struct buf *bp;
3899         struct bqueues *dp;
3900         int counts[(MAXBSIZE / PAGE_SIZE) + 1];
3901         static char *bname[3] = { "LOCKED", "LRU", "AGE" };
3902 
3903         for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
3904                 count = 0;
3905                 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3906                         counts[j] = 0;
3907 		crit_enter();
3908                 TAILQ_FOREACH(bp, dp, b_freelist) {
3909                         counts[bp->b_bufsize/PAGE_SIZE]++;
3910                         count++;
3911                 }
3912 		crit_exit();
3913                 kprintf("%s: total-%d", bname[i], count);
3914                 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3915                         if (counts[j] != 0)
3916                                 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
3917                 kprintf("\n");
3918         }
3919 }
3920 #endif
3921 
3922 #ifdef DDB
3923 
3924 DB_SHOW_COMMAND(buffer, db_show_buffer)
3925 {
3926 	/* get args */
3927 	struct buf *bp = (struct buf *)addr;
3928 
3929 	if (!have_addr) {
3930 		db_printf("usage: show buffer <addr>\n");
3931 		return;
3932 	}
3933 
3934 	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3935 	db_printf("b_cmd = %d\n", bp->b_cmd);
3936 	db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
3937 		  "b_resid = %d\n, b_data = %p, "
3938 		  "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
3939 		  bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3940 		  bp->b_data, bp->b_bio2.bio_offset, (bp->b_bio2.bio_next ? bp->b_bio2.bio_next->bio_offset : (off_t)-1));
3941 	if (bp->b_xio.xio_npages) {
3942 		int i;
3943 		db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3944 			bp->b_xio.xio_npages);
3945 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
3946 			vm_page_t m;
3947 			m = bp->b_xio.xio_pages[i];
3948 			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3949 			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3950 			if ((i + 1) < bp->b_xio.xio_npages)
3951 				db_printf(",");
3952 		}
3953 		db_printf("\n");
3954 	}
3955 }
3956 #endif /* DDB */
3957