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