xref: /freebsd/sys/kern/vfs_bio.c (revision b52b9d56d4e96089873a75f9e29062eec19fabba)
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$
15  */
16 
17 /*
18  * this file contains a new buffer I/O scheme implementing a coherent
19  * VM object and buffer cache scheme.  Pains have been taken to make
20  * sure that the performance degradation associated with schemes such
21  * as this is not realized.
22  *
23  * Author:  John S. Dyson
24  * Significant help during the development and debugging phases
25  * had been provided by David Greenman, also of the FreeBSD core team.
26  *
27  * see man buf(9) for more info.
28  */
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/stdint.h>
33 #include <sys/bio.h>
34 #include <sys/buf.h>
35 #include <sys/eventhandler.h>
36 #include <sys/lock.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/mutex.h>
40 #include <sys/kernel.h>
41 #include <sys/kthread.h>
42 #include <sys/ktr.h>
43 #include <sys/proc.h>
44 #include <sys/reboot.h>
45 #include <sys/resourcevar.h>
46 #include <sys/sysctl.h>
47 #include <sys/vmmeter.h>
48 #include <sys/vnode.h>
49 #include <vm/vm.h>
50 #include <vm/vm_param.h>
51 #include <vm/vm_kern.h>
52 #include <vm/vm_pageout.h>
53 #include <vm/vm_page.h>
54 #include <vm/vm_object.h>
55 #include <vm/vm_extern.h>
56 #include <vm/vm_map.h>
57 
58 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
59 
60 struct	bio_ops bioops;		/* I/O operation notification */
61 
62 struct	buf_ops buf_ops_bio = {
63 	"buf_ops_bio",
64 	bwrite
65 };
66 
67 /*
68  * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
69  * carnal knowledge of buffers.  This knowledge should be moved to vfs_bio.c.
70  */
71 struct buf *buf;		/* buffer header pool */
72 struct mtx buftimelock;		/* Interlock on setting prio and timo */
73 
74 static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
75 		vm_offset_t to);
76 static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
77 		vm_offset_t to);
78 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
79 			       int pageno, vm_page_t m);
80 static void vfs_clean_pages(struct buf * bp);
81 static void vfs_setdirty(struct buf *bp);
82 static void vfs_vmio_release(struct buf *bp);
83 static void vfs_backgroundwritedone(struct buf *bp);
84 static int flushbufqueues(void);
85 static void buf_daemon(void);
86 
87 int vmiodirenable = TRUE;
88 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
89     "Use the VM system for directory writes");
90 int runningbufspace;
91 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
92     "Amount of presently outstanding async buffer io");
93 static int bufspace;
94 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
95     "KVA memory used for bufs");
96 static int maxbufspace;
97 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
98     "Maximum allowed value of bufspace (including buf_daemon)");
99 static int bufmallocspace;
100 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
101     "Amount of malloced memory for buffers");
102 static int maxbufmallocspace;
103 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
104     "Maximum amount of malloced memory for buffers");
105 static int lobufspace;
106 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
107     "Minimum amount of buffers we want to have");
108 static int hibufspace;
109 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
110     "Maximum allowed value of bufspace (excluding buf_daemon)");
111 static int bufreusecnt;
112 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
113     "Number of times we have reused a buffer");
114 static int buffreekvacnt;
115 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
116     "Number of times we have freed the KVA space from some buffer");
117 static int bufdefragcnt;
118 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
119     "Number of times we have had to repeat buffer allocation to defragment");
120 static int lorunningspace;
121 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
122     "Minimum preferred space used for in-progress I/O");
123 static int hirunningspace;
124 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
125     "Maximum amount of space to use for in-progress I/O");
126 static int numdirtybuffers;
127 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
128     "Number of buffers that are dirty (has unwritten changes) at the moment");
129 static int lodirtybuffers;
130 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
131     "How many buffers we want to have free before bufdaemon can sleep");
132 static int hidirtybuffers;
133 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
134     "When the number of dirty buffers is considered severe");
135 static int numfreebuffers;
136 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
137     "Number of free buffers");
138 static int lofreebuffers;
139 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
140    "XXX Unused");
141 static int hifreebuffers;
142 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
143    "XXX Complicatedly unused");
144 static int getnewbufcalls;
145 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
146    "Number of calls to getnewbuf");
147 static int getnewbufrestarts;
148 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
149     "Number of times getnewbuf has had to restart a buffer aquisition");
150 static int dobkgrdwrite = 1;
151 SYSCTL_INT(_debug, OID_AUTO, dobkgrdwrite, CTLFLAG_RW, &dobkgrdwrite, 0,
152     "Do background writes (honoring the BX_BKGRDWRITE flag)?");
153 
154 /*
155  * Wakeup point for bufdaemon, as well as indicator of whether it is already
156  * active.  Set to 1 when the bufdaemon is already "on" the queue, 0 when it
157  * is idling.
158  */
159 static int bd_request;
160 
161 /*
162  * bogus page -- for I/O to/from partially complete buffers
163  * this is a temporary solution to the problem, but it is not
164  * really that bad.  it would be better to split the buffer
165  * for input in the case of buffers partially already in memory,
166  * but the code is intricate enough already.
167  */
168 vm_page_t bogus_page;
169 
170 /*
171  * Offset for bogus_page.
172  * XXX bogus_offset should be local to bufinit
173  */
174 static vm_offset_t bogus_offset;
175 
176 /*
177  * Synchronization (sleep/wakeup) variable for active buffer space requests.
178  * Set when wait starts, cleared prior to wakeup().
179  * Used in runningbufwakeup() and waitrunningbufspace().
180  */
181 static int runningbufreq;
182 
183 /*
184  * Synchronization (sleep/wakeup) variable for buffer requests.
185  * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
186  * by and/or.
187  * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
188  * getnewbuf(), and getblk().
189  */
190 static int needsbuffer;
191 
192 #ifdef USE_BUFHASH
193 /*
194  * Mask for index into the buffer hash table, which needs to be power of 2 in
195  * size.  Set in kern_vfs_bio_buffer_alloc.
196  */
197 static int bufhashmask;
198 
199 /*
200  * Hash table for all buffers, with a linked list hanging from each table
201  * entry.  Set in kern_vfs_bio_buffer_alloc, initialized in buf_init.
202  */
203 static LIST_HEAD(bufhashhdr, buf) *bufhashtbl;
204 
205 /*
206  * Somewhere to store buffers when they are not in another list, to always
207  * have them in a list (and thus being able to use the same set of operations
208  * on them.)
209  */
210 static struct bufhashhdr invalhash;
211 
212 #endif
213 
214 /*
215  * Definitions for the buffer free lists.
216  */
217 #define BUFFER_QUEUES	6	/* number of free buffer queues */
218 
219 #define QUEUE_NONE	0	/* on no queue */
220 #define QUEUE_LOCKED	1	/* locked buffers */
221 #define QUEUE_CLEAN	2	/* non-B_DELWRI buffers */
222 #define QUEUE_DIRTY	3	/* B_DELWRI buffers */
223 #define QUEUE_EMPTYKVA	4	/* empty buffer headers w/KVA assignment */
224 #define QUEUE_EMPTY	5	/* empty buffer headers */
225 
226 /* Queues for free buffers with various properties */
227 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
228 /*
229  * Single global constant for BUF_WMESG, to avoid getting multiple references.
230  * buf_wmesg is referred from macros.
231  */
232 const char *buf_wmesg = BUF_WMESG;
233 
234 #define VFS_BIO_NEED_ANY	0x01	/* any freeable buffer */
235 #define VFS_BIO_NEED_DIRTYFLUSH	0x02	/* waiting for dirty buffer flush */
236 #define VFS_BIO_NEED_FREE	0x04	/* wait for free bufs, hi hysteresis */
237 #define VFS_BIO_NEED_BUFSPACE	0x08	/* wait for buf space, lo hysteresis */
238 
239 #ifdef USE_BUFHASH
240 /*
241  * Buffer hash table code.  Note that the logical block scans linearly, which
242  * gives us some L1 cache locality.
243  */
244 
245 static __inline
246 struct bufhashhdr *
247 bufhash(struct vnode *vnp, daddr_t bn)
248 {
249 	return(&bufhashtbl[(((uintptr_t)(vnp) >> 7) + (int)bn) & bufhashmask]);
250 }
251 
252 #endif
253 
254 /*
255  *	numdirtywakeup:
256  *
257  *	If someone is blocked due to there being too many dirty buffers,
258  *	and numdirtybuffers is now reasonable, wake them up.
259  */
260 
261 static __inline void
262 numdirtywakeup(int level)
263 {
264 	if (numdirtybuffers <= level) {
265 		if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
266 			needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
267 			wakeup(&needsbuffer);
268 		}
269 	}
270 }
271 
272 /*
273  *	bufspacewakeup:
274  *
275  *	Called when buffer space is potentially available for recovery.
276  *	getnewbuf() will block on this flag when it is unable to free
277  *	sufficient buffer space.  Buffer space becomes recoverable when
278  *	bp's get placed back in the queues.
279  */
280 
281 static __inline void
282 bufspacewakeup(void)
283 {
284 	/*
285 	 * If someone is waiting for BUF space, wake them up.  Even
286 	 * though we haven't freed the kva space yet, the waiting
287 	 * process will be able to now.
288 	 */
289 	if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
290 		needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
291 		wakeup(&needsbuffer);
292 	}
293 }
294 
295 /*
296  * runningbufwakeup() - in-progress I/O accounting.
297  *
298  */
299 static __inline void
300 runningbufwakeup(struct buf *bp)
301 {
302 	if (bp->b_runningbufspace) {
303 		runningbufspace -= bp->b_runningbufspace;
304 		bp->b_runningbufspace = 0;
305 		if (runningbufreq && runningbufspace <= lorunningspace) {
306 			runningbufreq = 0;
307 			wakeup(&runningbufreq);
308 		}
309 	}
310 }
311 
312 /*
313  *	bufcountwakeup:
314  *
315  *	Called when a buffer has been added to one of the free queues to
316  *	account for the buffer and to wakeup anyone waiting for free buffers.
317  *	This typically occurs when large amounts of metadata are being handled
318  *	by the buffer cache ( else buffer space runs out first, usually ).
319  */
320 
321 static __inline void
322 bufcountwakeup(void)
323 {
324 	++numfreebuffers;
325 	if (needsbuffer) {
326 		needsbuffer &= ~VFS_BIO_NEED_ANY;
327 		if (numfreebuffers >= hifreebuffers)
328 			needsbuffer &= ~VFS_BIO_NEED_FREE;
329 		wakeup(&needsbuffer);
330 	}
331 }
332 
333 /*
334  *	waitrunningbufspace()
335  *
336  *	runningbufspace is a measure of the amount of I/O currently
337  *	running.  This routine is used in async-write situations to
338  *	prevent creating huge backups of pending writes to a device.
339  *	Only asynchronous writes are governed by this function.
340  *
341  *	Reads will adjust runningbufspace, but will not block based on it.
342  *	The read load has a side effect of reducing the allowed write load.
343  *
344  *	This does NOT turn an async write into a sync write.  It waits
345  *	for earlier writes to complete and generally returns before the
346  *	caller's write has reached the device.
347  */
348 static __inline void
349 waitrunningbufspace(void)
350 {
351 	/*
352 	 * XXX race against wakeup interrupt, currently
353 	 * protected by Giant.  FIXME!
354 	 */
355 	while (runningbufspace > hirunningspace) {
356 		++runningbufreq;
357 		tsleep(&runningbufreq, PVM, "wdrain", 0);
358 	}
359 }
360 
361 
362 /*
363  *	vfs_buf_test_cache:
364  *
365  *	Called when a buffer is extended.  This function clears the B_CACHE
366  *	bit if the newly extended portion of the buffer does not contain
367  *	valid data.
368  */
369 static __inline__
370 void
371 vfs_buf_test_cache(struct buf *bp,
372 		  vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
373 		  vm_page_t m)
374 {
375 	GIANT_REQUIRED;
376 
377 	if (bp->b_flags & B_CACHE) {
378 		int base = (foff + off) & PAGE_MASK;
379 		if (vm_page_is_valid(m, base, size) == 0)
380 			bp->b_flags &= ~B_CACHE;
381 	}
382 }
383 
384 /* Wake up the buffer deamon if necessary */
385 static __inline__
386 void
387 bd_wakeup(int dirtybuflevel)
388 {
389 	if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
390 		bd_request = 1;
391 		wakeup(&bd_request);
392 	}
393 }
394 
395 /*
396  * bd_speedup - speedup the buffer cache flushing code
397  */
398 
399 static __inline__
400 void
401 bd_speedup(void)
402 {
403 	bd_wakeup(1);
404 }
405 
406 /*
407  * Calculating buffer cache scaling values and reserve space for buffer
408  * headers.  This is called during low level kernel initialization and
409  * may be called more then once.  We CANNOT write to the memory area
410  * being reserved at this time.
411  */
412 caddr_t
413 kern_vfs_bio_buffer_alloc(caddr_t v, int physmem_est)
414 {
415 	/*
416 	 * physmem_est is in pages.  Convert it to kilobytes (assumes
417 	 * PAGE_SIZE is >= 1K)
418 	 */
419 	physmem_est = physmem_est * (PAGE_SIZE / 1024);
420 
421 	/*
422 	 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
423 	 * For the first 64MB of ram nominally allocate sufficient buffers to
424 	 * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
425 	 * buffers to cover 1/20 of our ram over 64MB.  When auto-sizing
426 	 * the buffer cache we limit the eventual kva reservation to
427 	 * maxbcache bytes.
428 	 *
429 	 * factor represents the 1/4 x ram conversion.
430 	 */
431 	if (nbuf == 0) {
432 		int factor = 4 * BKVASIZE / 1024;
433 
434 		nbuf = 50;
435 		if (physmem_est > 4096)
436 			nbuf += min((physmem_est - 4096) / factor,
437 			    65536 / factor);
438 		if (physmem_est > 65536)
439 			nbuf += (physmem_est - 65536) * 2 / (factor * 5);
440 
441 		if (maxbcache && nbuf > maxbcache / BKVASIZE)
442 			nbuf = maxbcache / BKVASIZE;
443 	}
444 
445 #if 0
446 	/*
447 	 * Do not allow the buffer_map to be more then 1/2 the size of the
448 	 * kernel_map.
449 	 */
450 	if (nbuf > (kernel_map->max_offset - kernel_map->min_offset) /
451 	    (BKVASIZE * 2)) {
452 		nbuf = (kernel_map->max_offset - kernel_map->min_offset) /
453 		    (BKVASIZE * 2);
454 		printf("Warning: nbufs capped at %d\n", nbuf);
455 	}
456 #endif
457 
458 	/*
459 	 * swbufs are used as temporary holders for I/O, such as paging I/O.
460 	 * We have no less then 16 and no more then 256.
461 	 */
462 	nswbuf = max(min(nbuf/4, 256), 16);
463 
464 	/*
465 	 * Reserve space for the buffer cache buffers
466 	 */
467 	swbuf = (void *)v;
468 	v = (caddr_t)(swbuf + nswbuf);
469 	buf = (void *)v;
470 	v = (caddr_t)(buf + nbuf);
471 
472 #ifdef USE_BUFHASH
473 	/*
474 	 * Calculate the hash table size and reserve space
475 	 */
476 	for (bufhashmask = 8; bufhashmask < nbuf / 4; bufhashmask <<= 1)
477 		;
478 	bufhashtbl = (void *)v;
479 	v = (caddr_t)(bufhashtbl + bufhashmask);
480 	--bufhashmask;
481 #endif
482 	return(v);
483 }
484 
485 /* Initialize the buffer subsystem.  Called before use of any buffers. */
486 void
487 bufinit(void)
488 {
489 	struct buf *bp;
490 	int i;
491 
492 	GIANT_REQUIRED;
493 
494 #ifdef USE_BUFHASH
495 	LIST_INIT(&invalhash);
496 #endif
497 	mtx_init(&buftimelock, "buftime lock", NULL, MTX_DEF);
498 
499 #ifdef USE_BUFHASH
500 	for (i = 0; i <= bufhashmask; i++)
501 		LIST_INIT(&bufhashtbl[i]);
502 #endif
503 
504 	/* next, make a null set of free lists */
505 	for (i = 0; i < BUFFER_QUEUES; i++)
506 		TAILQ_INIT(&bufqueues[i]);
507 
508 	/* finally, initialize each buffer header and stick on empty q */
509 	for (i = 0; i < nbuf; i++) {
510 		bp = &buf[i];
511 		bzero(bp, sizeof *bp);
512 		bp->b_flags = B_INVAL;	/* we're just an empty header */
513 		bp->b_dev = NODEV;
514 		bp->b_rcred = NOCRED;
515 		bp->b_wcred = NOCRED;
516 		bp->b_qindex = QUEUE_EMPTY;
517 		bp->b_xflags = 0;
518 		LIST_INIT(&bp->b_dep);
519 		BUF_LOCKINIT(bp);
520 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
521 #ifdef USE_BUFHASH
522 		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
523 #endif
524 	}
525 
526 	/*
527 	 * maxbufspace is the absolute maximum amount of buffer space we are
528 	 * allowed to reserve in KVM and in real terms.  The absolute maximum
529 	 * is nominally used by buf_daemon.  hibufspace is the nominal maximum
530 	 * used by most other processes.  The differential is required to
531 	 * ensure that buf_daemon is able to run when other processes might
532 	 * be blocked waiting for buffer space.
533 	 *
534 	 * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
535 	 * this may result in KVM fragmentation which is not handled optimally
536 	 * by the system.
537 	 */
538 	maxbufspace = nbuf * BKVASIZE;
539 	hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
540 	lobufspace = hibufspace - MAXBSIZE;
541 
542 	lorunningspace = 512 * 1024;
543 	hirunningspace = 1024 * 1024;
544 
545 /*
546  * Limit the amount of malloc memory since it is wired permanently into
547  * the kernel space.  Even though this is accounted for in the buffer
548  * allocation, we don't want the malloced region to grow uncontrolled.
549  * The malloc scheme improves memory utilization significantly on average
550  * (small) directories.
551  */
552 	maxbufmallocspace = hibufspace / 20;
553 
554 /*
555  * Reduce the chance of a deadlock occuring by limiting the number
556  * of delayed-write dirty buffers we allow to stack up.
557  */
558 	hidirtybuffers = nbuf / 4 + 20;
559 	numdirtybuffers = 0;
560 /*
561  * To support extreme low-memory systems, make sure hidirtybuffers cannot
562  * eat up all available buffer space.  This occurs when our minimum cannot
563  * be met.  We try to size hidirtybuffers to 3/4 our buffer space assuming
564  * BKVASIZE'd (8K) buffers.
565  */
566 	while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
567 		hidirtybuffers >>= 1;
568 	}
569 	lodirtybuffers = hidirtybuffers / 2;
570 
571 /*
572  * Try to keep the number of free buffers in the specified range,
573  * and give special processes (e.g. like buf_daemon) access to an
574  * emergency reserve.
575  */
576 	lofreebuffers = nbuf / 18 + 5;
577 	hifreebuffers = 2 * lofreebuffers;
578 	numfreebuffers = nbuf;
579 
580 /*
581  * Maximum number of async ops initiated per buf_daemon loop.  This is
582  * somewhat of a hack at the moment, we really need to limit ourselves
583  * based on the number of bytes of I/O in-transit that were initiated
584  * from buf_daemon.
585  */
586 
587 	bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
588 	bogus_page = vm_page_alloc(kernel_object,
589 			((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
590 			VM_ALLOC_NORMAL);
591 	cnt.v_wire_count++;
592 }
593 
594 /*
595  * bfreekva() - free the kva allocation for a buffer.
596  *
597  *	Must be called at splbio() or higher as this is the only locking for
598  *	buffer_map.
599  *
600  *	Since this call frees up buffer space, we call bufspacewakeup().
601  */
602 static void
603 bfreekva(struct buf * bp)
604 {
605 	GIANT_REQUIRED;
606 
607 	if (bp->b_kvasize) {
608 		++buffreekvacnt;
609 		bufspace -= bp->b_kvasize;
610 		vm_map_delete(buffer_map,
611 		    (vm_offset_t) bp->b_kvabase,
612 		    (vm_offset_t) bp->b_kvabase + bp->b_kvasize
613 		);
614 		bp->b_kvasize = 0;
615 		bufspacewakeup();
616 	}
617 }
618 
619 /*
620  *	bremfree:
621  *
622  *	Remove the buffer from the appropriate free list.
623  */
624 void
625 bremfree(struct buf * bp)
626 {
627 	int s = splbio();
628 	int old_qindex = bp->b_qindex;
629 
630 	GIANT_REQUIRED;
631 
632 	if (bp->b_qindex != QUEUE_NONE) {
633 		KASSERT(BUF_REFCNT(bp) == 1, ("bremfree: bp %p not locked",bp));
634 		TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
635 		bp->b_qindex = QUEUE_NONE;
636 	} else {
637 		if (BUF_REFCNT(bp) <= 1)
638 			panic("bremfree: removing a buffer not on a queue");
639 	}
640 
641 	/*
642 	 * Fixup numfreebuffers count.  If the buffer is invalid or not
643 	 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
644 	 * the buffer was free and we must decrement numfreebuffers.
645 	 */
646 	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
647 		switch(old_qindex) {
648 		case QUEUE_DIRTY:
649 		case QUEUE_CLEAN:
650 		case QUEUE_EMPTY:
651 		case QUEUE_EMPTYKVA:
652 			--numfreebuffers;
653 			break;
654 		default:
655 			break;
656 		}
657 	}
658 	splx(s);
659 }
660 
661 
662 /*
663  * Get a buffer with the specified data.  Look in the cache first.  We
664  * must clear BIO_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
665  * is set, the buffer is valid and we do not have to do anything ( see
666  * getblk() ).  This is really just a special case of breadn().
667  */
668 int
669 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
670     struct buf ** bpp)
671 {
672 
673 	return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp));
674 }
675 
676 /*
677  * Operates like bread, but also starts asynchronous I/O on
678  * read-ahead blocks.  We must clear BIO_ERROR and B_INVAL prior
679  * to initiating I/O . If B_CACHE is set, the buffer is valid
680  * and we do not have to do anything.
681  */
682 int
683 breadn(struct vnode * vp, daddr_t blkno, int size,
684     daddr_t * rablkno, int *rabsize,
685     int cnt, struct ucred * cred, struct buf ** bpp)
686 {
687 	struct buf *bp, *rabp;
688 	int i;
689 	int rv = 0, readwait = 0;
690 
691 	*bpp = bp = getblk(vp, blkno, size, 0, 0);
692 
693 	/* if not found in cache, do some I/O */
694 	if ((bp->b_flags & B_CACHE) == 0) {
695 		if (curthread != PCPU_GET(idlethread))
696 			curthread->td_proc->p_stats->p_ru.ru_inblock++;
697 		bp->b_iocmd = BIO_READ;
698 		bp->b_flags &= ~B_INVAL;
699 		bp->b_ioflags &= ~BIO_ERROR;
700 		if (bp->b_rcred == NOCRED && cred != NOCRED)
701 			bp->b_rcred = crhold(cred);
702 		vfs_busy_pages(bp, 0);
703 		VOP_STRATEGY(vp, bp);
704 		++readwait;
705 	}
706 
707 	for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
708 		if (inmem(vp, *rablkno))
709 			continue;
710 		rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
711 
712 		if ((rabp->b_flags & B_CACHE) == 0) {
713 			if (curthread != PCPU_GET(idlethread))
714 				curthread->td_proc->p_stats->p_ru.ru_inblock++;
715 			rabp->b_flags |= B_ASYNC;
716 			rabp->b_flags &= ~B_INVAL;
717 			rabp->b_ioflags &= ~BIO_ERROR;
718 			rabp->b_iocmd = BIO_READ;
719 			if (rabp->b_rcred == NOCRED && cred != NOCRED)
720 				rabp->b_rcred = crhold(cred);
721 			vfs_busy_pages(rabp, 0);
722 			BUF_KERNPROC(rabp);
723 			VOP_STRATEGY(vp, rabp);
724 		} else {
725 			brelse(rabp);
726 		}
727 	}
728 
729 	if (readwait) {
730 		rv = bufwait(bp);
731 	}
732 	return (rv);
733 }
734 
735 /*
736  * Write, release buffer on completion.  (Done by iodone
737  * if async).  Do not bother writing anything if the buffer
738  * is invalid.
739  *
740  * Note that we set B_CACHE here, indicating that buffer is
741  * fully valid and thus cacheable.  This is true even of NFS
742  * now so we set it generally.  This could be set either here
743  * or in biodone() since the I/O is synchronous.  We put it
744  * here.
745  */
746 
747 int
748 bwrite(struct buf * bp)
749 {
750 	int oldflags, s;
751 	struct buf *newbp;
752 
753 	if (bp->b_flags & B_INVAL) {
754 		brelse(bp);
755 		return (0);
756 	}
757 
758 	oldflags = bp->b_flags;
759 
760 	if (BUF_REFCNT(bp) == 0)
761 		panic("bwrite: buffer is not busy???");
762 	s = splbio();
763 	/*
764 	 * If a background write is already in progress, delay
765 	 * writing this block if it is asynchronous. Otherwise
766 	 * wait for the background write to complete.
767 	 */
768 	if (bp->b_xflags & BX_BKGRDINPROG) {
769 		if (bp->b_flags & B_ASYNC) {
770 			splx(s);
771 			bdwrite(bp);
772 			return (0);
773 		}
774 		bp->b_xflags |= BX_BKGRDWAIT;
775 		tsleep(&bp->b_xflags, PRIBIO, "bwrbg", 0);
776 		if (bp->b_xflags & BX_BKGRDINPROG)
777 			panic("bwrite: still writing");
778 	}
779 
780 	/* Mark the buffer clean */
781 	bundirty(bp);
782 
783 	/*
784 	 * If this buffer is marked for background writing and we
785 	 * do not have to wait for it, make a copy and write the
786 	 * copy so as to leave this buffer ready for further use.
787 	 *
788 	 * This optimization eats a lot of memory.  If we have a page
789 	 * or buffer shortfall we can't do it.
790 	 */
791 	if (dobkgrdwrite && (bp->b_xflags & BX_BKGRDWRITE) &&
792 	    (bp->b_flags & B_ASYNC) &&
793 	    !vm_page_count_severe() &&
794 	    !buf_dirty_count_severe()) {
795 		if (bp->b_iodone != NULL) {
796 			printf("bp->b_iodone = %p\n", bp->b_iodone);
797 			panic("bwrite: need chained iodone");
798 		}
799 
800 		/* get a new block */
801 		newbp = geteblk(bp->b_bufsize);
802 
803 		/*
804 		 * set it to be identical to the old block.  We have to
805 		 * set b_lblkno and BKGRDMARKER before calling bgetvp()
806 		 * to avoid confusing the splay tree and gbincore().
807 		 */
808 		memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
809 		newbp->b_lblkno = bp->b_lblkno;
810 		newbp->b_xflags |= BX_BKGRDMARKER;
811 		bgetvp(bp->b_vp, newbp);
812 		newbp->b_blkno = bp->b_blkno;
813 		newbp->b_offset = bp->b_offset;
814 		newbp->b_iodone = vfs_backgroundwritedone;
815 		newbp->b_flags |= B_ASYNC;
816 		newbp->b_flags &= ~B_INVAL;
817 
818 		/* move over the dependencies */
819 		if (LIST_FIRST(&bp->b_dep) != NULL)
820 			buf_movedeps(bp, newbp);
821 
822 		/*
823 		 * Initiate write on the copy, release the original to
824 		 * the B_LOCKED queue so that it cannot go away until
825 		 * the background write completes. If not locked it could go
826 		 * away and then be reconstituted while it was being written.
827 		 * If the reconstituted buffer were written, we could end up
828 		 * with two background copies being written at the same time.
829 		 */
830 		bp->b_xflags |= BX_BKGRDINPROG;
831 		bp->b_flags |= B_LOCKED;
832 		bqrelse(bp);
833 		bp = newbp;
834 	}
835 
836 	bp->b_flags &= ~B_DONE;
837 	bp->b_ioflags &= ~BIO_ERROR;
838 	bp->b_flags |= B_WRITEINPROG | B_CACHE;
839 	bp->b_iocmd = BIO_WRITE;
840 
841 	bp->b_vp->v_numoutput++;
842 	vfs_busy_pages(bp, 1);
843 
844 	/*
845 	 * Normal bwrites pipeline writes
846 	 */
847 	bp->b_runningbufspace = bp->b_bufsize;
848 	runningbufspace += bp->b_runningbufspace;
849 
850 	if (curthread != PCPU_GET(idlethread))
851 		curthread->td_proc->p_stats->p_ru.ru_oublock++;
852 	splx(s);
853 	if (oldflags & B_ASYNC)
854 		BUF_KERNPROC(bp);
855 	BUF_STRATEGY(bp);
856 
857 	if ((oldflags & B_ASYNC) == 0) {
858 		int rtval = bufwait(bp);
859 		brelse(bp);
860 		return (rtval);
861 	} else if ((oldflags & B_NOWDRAIN) == 0) {
862 		/*
863 		 * don't allow the async write to saturate the I/O
864 		 * system.  Deadlocks can occur only if a device strategy
865 		 * routine (like in MD) turns around and issues another
866 		 * high-level write, in which case B_NOWDRAIN is expected
867 		 * to be set.  Otherwise we will not deadlock here because
868 		 * we are blocking waiting for I/O that is already in-progress
869 		 * to complete.
870 		 */
871 		waitrunningbufspace();
872 	}
873 
874 	return (0);
875 }
876 
877 /*
878  * Complete a background write started from bwrite.
879  */
880 static void
881 vfs_backgroundwritedone(bp)
882 	struct buf *bp;
883 {
884 	struct buf *origbp;
885 
886 	/*
887 	 * Find the original buffer that we are writing.
888 	 */
889 	if ((origbp = gbincore(bp->b_vp, bp->b_lblkno)) == NULL)
890 		panic("backgroundwritedone: lost buffer");
891 	/*
892 	 * Process dependencies then return any unfinished ones.
893 	 */
894 	if (LIST_FIRST(&bp->b_dep) != NULL)
895 		buf_complete(bp);
896 	if (LIST_FIRST(&bp->b_dep) != NULL)
897 		buf_movedeps(bp, origbp);
898 	/*
899 	 * Clear the BX_BKGRDINPROG flag in the original buffer
900 	 * and awaken it if it is waiting for the write to complete.
901 	 * If BX_BKGRDINPROG is not set in the original buffer it must
902 	 * have been released and re-instantiated - which is not legal.
903 	 */
904 	KASSERT((origbp->b_xflags & BX_BKGRDINPROG),
905 	    ("backgroundwritedone: lost buffer2"));
906 	origbp->b_xflags &= ~BX_BKGRDINPROG;
907 	if (origbp->b_xflags & BX_BKGRDWAIT) {
908 		origbp->b_xflags &= ~BX_BKGRDWAIT;
909 		wakeup(&origbp->b_xflags);
910 	}
911 	/*
912 	 * Clear the B_LOCKED flag and remove it from the locked
913 	 * queue if it currently resides there.
914 	 */
915 	origbp->b_flags &= ~B_LOCKED;
916 	if (BUF_LOCK(origbp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
917 		bremfree(origbp);
918 		bqrelse(origbp);
919 	}
920 	/*
921 	 * This buffer is marked B_NOCACHE, so when it is released
922 	 * by biodone, it will be tossed. We mark it with BIO_READ
923 	 * to avoid biodone doing a second vwakeup.
924 	 */
925 	bp->b_flags |= B_NOCACHE;
926 	bp->b_iocmd = BIO_READ;
927 	bp->b_flags &= ~(B_CACHE | B_DONE);
928 	bp->b_iodone = 0;
929 	bufdone(bp);
930 }
931 
932 /*
933  * Delayed write. (Buffer is marked dirty).  Do not bother writing
934  * anything if the buffer is marked invalid.
935  *
936  * Note that since the buffer must be completely valid, we can safely
937  * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
938  * biodone() in order to prevent getblk from writing the buffer
939  * out synchronously.
940  */
941 void
942 bdwrite(struct buf * bp)
943 {
944 	GIANT_REQUIRED;
945 
946 	if (BUF_REFCNT(bp) == 0)
947 		panic("bdwrite: buffer is not busy");
948 
949 	if (bp->b_flags & B_INVAL) {
950 		brelse(bp);
951 		return;
952 	}
953 	bdirty(bp);
954 
955 	/*
956 	 * Set B_CACHE, indicating that the buffer is fully valid.  This is
957 	 * true even of NFS now.
958 	 */
959 	bp->b_flags |= B_CACHE;
960 
961 	/*
962 	 * This bmap keeps the system from needing to do the bmap later,
963 	 * perhaps when the system is attempting to do a sync.  Since it
964 	 * is likely that the indirect block -- or whatever other datastructure
965 	 * that the filesystem needs is still in memory now, it is a good
966 	 * thing to do this.  Note also, that if the pageout daemon is
967 	 * requesting a sync -- there might not be enough memory to do
968 	 * the bmap then...  So, this is important to do.
969 	 */
970 	if (bp->b_lblkno == bp->b_blkno) {
971 		VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
972 	}
973 
974 	/*
975 	 * Set the *dirty* buffer range based upon the VM system dirty pages.
976 	 */
977 	vfs_setdirty(bp);
978 
979 	/*
980 	 * We need to do this here to satisfy the vnode_pager and the
981 	 * pageout daemon, so that it thinks that the pages have been
982 	 * "cleaned".  Note that since the pages are in a delayed write
983 	 * buffer -- the VFS layer "will" see that the pages get written
984 	 * out on the next sync, or perhaps the cluster will be completed.
985 	 */
986 	vfs_clean_pages(bp);
987 	bqrelse(bp);
988 
989 	/*
990 	 * Wakeup the buffer flushing daemon if we have a lot of dirty
991 	 * buffers (midpoint between our recovery point and our stall
992 	 * point).
993 	 */
994 	bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
995 
996 	/*
997 	 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
998 	 * due to the softdep code.
999 	 */
1000 }
1001 
1002 /*
1003  *	bdirty:
1004  *
1005  *	Turn buffer into delayed write request.  We must clear BIO_READ and
1006  *	B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to
1007  *	itself to properly update it in the dirty/clean lists.  We mark it
1008  *	B_DONE to ensure that any asynchronization of the buffer properly
1009  *	clears B_DONE ( else a panic will occur later ).
1010  *
1011  *	bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1012  *	might have been set pre-getblk().  Unlike bwrite/bdwrite, bdirty()
1013  *	should only be called if the buffer is known-good.
1014  *
1015  *	Since the buffer is not on a queue, we do not update the numfreebuffers
1016  *	count.
1017  *
1018  *	Must be called at splbio().
1019  *	The buffer must be on QUEUE_NONE.
1020  */
1021 void
1022 bdirty(bp)
1023 	struct buf *bp;
1024 {
1025 	KASSERT(bp->b_qindex == QUEUE_NONE,
1026 	    ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1027 	bp->b_flags &= ~(B_RELBUF);
1028 	bp->b_iocmd = BIO_WRITE;
1029 
1030 	if ((bp->b_flags & B_DELWRI) == 0) {
1031 		bp->b_flags |= B_DONE | B_DELWRI;
1032 		reassignbuf(bp, bp->b_vp);
1033 		++numdirtybuffers;
1034 		bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1035 	}
1036 }
1037 
1038 /*
1039  *	bundirty:
1040  *
1041  *	Clear B_DELWRI for buffer.
1042  *
1043  *	Since the buffer is not on a queue, we do not update the numfreebuffers
1044  *	count.
1045  *
1046  *	Must be called at splbio().
1047  *	The buffer must be on QUEUE_NONE.
1048  */
1049 
1050 void
1051 bundirty(bp)
1052 	struct buf *bp;
1053 {
1054 	KASSERT(bp->b_qindex == QUEUE_NONE,
1055 	    ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1056 
1057 	if (bp->b_flags & B_DELWRI) {
1058 		bp->b_flags &= ~B_DELWRI;
1059 		reassignbuf(bp, bp->b_vp);
1060 		--numdirtybuffers;
1061 		numdirtywakeup(lodirtybuffers);
1062 	}
1063 	/*
1064 	 * Since it is now being written, we can clear its deferred write flag.
1065 	 */
1066 	bp->b_flags &= ~B_DEFERRED;
1067 }
1068 
1069 /*
1070  *	bawrite:
1071  *
1072  *	Asynchronous write.  Start output on a buffer, but do not wait for
1073  *	it to complete.  The buffer is released when the output completes.
1074  *
1075  *	bwrite() ( or the VOP routine anyway ) is responsible for handling
1076  *	B_INVAL buffers.  Not us.
1077  */
1078 void
1079 bawrite(struct buf * bp)
1080 {
1081 	bp->b_flags |= B_ASYNC;
1082 	(void) BUF_WRITE(bp);
1083 }
1084 
1085 /*
1086  *	bwillwrite:
1087  *
1088  *	Called prior to the locking of any vnodes when we are expecting to
1089  *	write.  We do not want to starve the buffer cache with too many
1090  *	dirty buffers so we block here.  By blocking prior to the locking
1091  *	of any vnodes we attempt to avoid the situation where a locked vnode
1092  *	prevents the various system daemons from flushing related buffers.
1093  */
1094 
1095 void
1096 bwillwrite(void)
1097 {
1098 	if (numdirtybuffers >= hidirtybuffers) {
1099 		int s;
1100 
1101 		mtx_lock(&Giant);
1102 		s = splbio();
1103 		while (numdirtybuffers >= hidirtybuffers) {
1104 			bd_wakeup(1);
1105 			needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1106 			tsleep(&needsbuffer, (PRIBIO + 4), "flswai", 0);
1107 		}
1108 		splx(s);
1109 		mtx_unlock(&Giant);
1110 	}
1111 }
1112 
1113 /*
1114  * Return true if we have too many dirty buffers.
1115  */
1116 int
1117 buf_dirty_count_severe(void)
1118 {
1119 	return(numdirtybuffers >= hidirtybuffers);
1120 }
1121 
1122 /*
1123  *	brelse:
1124  *
1125  *	Release a busy buffer and, if requested, free its resources.  The
1126  *	buffer will be stashed in the appropriate bufqueue[] allowing it
1127  *	to be accessed later as a cache entity or reused for other purposes.
1128  */
1129 void
1130 brelse(struct buf * bp)
1131 {
1132 	int s;
1133 
1134 	GIANT_REQUIRED;
1135 
1136 	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1137 	    ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1138 
1139 	s = splbio();
1140 
1141 	if (bp->b_flags & B_LOCKED)
1142 		bp->b_ioflags &= ~BIO_ERROR;
1143 
1144 	if (bp->b_iocmd == BIO_WRITE &&
1145 	    (bp->b_ioflags & BIO_ERROR) &&
1146 	    !(bp->b_flags & B_INVAL)) {
1147 		/*
1148 		 * Failed write, redirty.  Must clear BIO_ERROR to prevent
1149 		 * pages from being scrapped.  If B_INVAL is set then
1150 		 * this case is not run and the next case is run to
1151 		 * destroy the buffer.  B_INVAL can occur if the buffer
1152 		 * is outside the range supported by the underlying device.
1153 		 */
1154 		bp->b_ioflags &= ~BIO_ERROR;
1155 		bdirty(bp);
1156 	} else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1157 	    (bp->b_ioflags & BIO_ERROR) ||
1158 	    bp->b_iocmd == BIO_DELETE || (bp->b_bufsize <= 0)) {
1159 		/*
1160 		 * Either a failed I/O or we were asked to free or not
1161 		 * cache the buffer.
1162 		 */
1163 		bp->b_flags |= B_INVAL;
1164 		if (LIST_FIRST(&bp->b_dep) != NULL)
1165 			buf_deallocate(bp);
1166 		if (bp->b_flags & B_DELWRI) {
1167 			--numdirtybuffers;
1168 			numdirtywakeup(lodirtybuffers);
1169 		}
1170 		bp->b_flags &= ~(B_DELWRI | B_CACHE);
1171 		if ((bp->b_flags & B_VMIO) == 0) {
1172 			if (bp->b_bufsize)
1173 				allocbuf(bp, 0);
1174 			if (bp->b_vp)
1175 				brelvp(bp);
1176 		}
1177 	}
1178 
1179 	/*
1180 	 * We must clear B_RELBUF if B_DELWRI is set.  If vfs_vmio_release()
1181 	 * is called with B_DELWRI set, the underlying pages may wind up
1182 	 * getting freed causing a previous write (bdwrite()) to get 'lost'
1183 	 * because pages associated with a B_DELWRI bp are marked clean.
1184 	 *
1185 	 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1186 	 * if B_DELWRI is set.
1187 	 *
1188 	 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1189 	 * on pages to return pages to the VM page queues.
1190 	 */
1191 	if (bp->b_flags & B_DELWRI)
1192 		bp->b_flags &= ~B_RELBUF;
1193 	else if (vm_page_count_severe() && !(bp->b_xflags & BX_BKGRDINPROG))
1194 		bp->b_flags |= B_RELBUF;
1195 
1196 	/*
1197 	 * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
1198 	 * constituted, not even NFS buffers now.  Two flags effect this.  If
1199 	 * B_INVAL, the struct buf is invalidated but the VM object is kept
1200 	 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1201 	 *
1202 	 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1203 	 * invalidated.  BIO_ERROR cannot be set for a failed write unless the
1204 	 * buffer is also B_INVAL because it hits the re-dirtying code above.
1205 	 *
1206 	 * Normally we can do this whether a buffer is B_DELWRI or not.  If
1207 	 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1208 	 * the commit state and we cannot afford to lose the buffer. If the
1209 	 * buffer has a background write in progress, we need to keep it
1210 	 * around to prevent it from being reconstituted and starting a second
1211 	 * background write.
1212 	 */
1213 	if ((bp->b_flags & B_VMIO)
1214 	    && !(bp->b_vp->v_tag == VT_NFS &&
1215 		 !vn_isdisk(bp->b_vp, NULL) &&
1216 		 (bp->b_flags & B_DELWRI))
1217 	    ) {
1218 
1219 		int i, j, resid;
1220 		vm_page_t m;
1221 		off_t foff;
1222 		vm_pindex_t poff;
1223 		vm_object_t obj;
1224 		struct vnode *vp;
1225 
1226 		vp = bp->b_vp;
1227 		obj = bp->b_object;
1228 
1229 		/*
1230 		 * Get the base offset and length of the buffer.  Note that
1231 		 * in the VMIO case if the buffer block size is not
1232 		 * page-aligned then b_data pointer may not be page-aligned.
1233 		 * But our b_pages[] array *IS* page aligned.
1234 		 *
1235 		 * block sizes less then DEV_BSIZE (usually 512) are not
1236 		 * supported due to the page granularity bits (m->valid,
1237 		 * m->dirty, etc...).
1238 		 *
1239 		 * See man buf(9) for more information
1240 		 */
1241 		resid = bp->b_bufsize;
1242 		foff = bp->b_offset;
1243 
1244 		for (i = 0; i < bp->b_npages; i++) {
1245 			int had_bogus = 0;
1246 
1247 			m = bp->b_pages[i];
1248 			vm_page_flag_clear(m, PG_ZERO);
1249 
1250 			/*
1251 			 * If we hit a bogus page, fixup *all* the bogus pages
1252 			 * now.
1253 			 */
1254 			if (m == bogus_page) {
1255 				poff = OFF_TO_IDX(bp->b_offset);
1256 				had_bogus = 1;
1257 
1258 				for (j = i; j < bp->b_npages; j++) {
1259 					vm_page_t mtmp;
1260 					mtmp = bp->b_pages[j];
1261 					if (mtmp == bogus_page) {
1262 						mtmp = vm_page_lookup(obj, poff + j);
1263 						if (!mtmp) {
1264 							panic("brelse: page missing\n");
1265 						}
1266 						bp->b_pages[j] = mtmp;
1267 					}
1268 				}
1269 
1270 				if ((bp->b_flags & B_INVAL) == 0) {
1271 					pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
1272 				}
1273 				m = bp->b_pages[i];
1274 			}
1275 			if ((bp->b_flags & B_NOCACHE) || (bp->b_ioflags & BIO_ERROR)) {
1276 				int poffset = foff & PAGE_MASK;
1277 				int presid = resid > (PAGE_SIZE - poffset) ?
1278 					(PAGE_SIZE - poffset) : resid;
1279 
1280 				KASSERT(presid >= 0, ("brelse: extra page"));
1281 				vm_page_set_invalid(m, poffset, presid);
1282 				if (had_bogus)
1283 					printf("avoided corruption bug in bogus_page/brelse code\n");
1284 			}
1285 			resid -= PAGE_SIZE - (foff & PAGE_MASK);
1286 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1287 		}
1288 
1289 		if (bp->b_flags & (B_INVAL | B_RELBUF))
1290 			vfs_vmio_release(bp);
1291 
1292 	} else if (bp->b_flags & B_VMIO) {
1293 
1294 		if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1295 			vfs_vmio_release(bp);
1296 		}
1297 
1298 	}
1299 
1300 	if (bp->b_qindex != QUEUE_NONE)
1301 		panic("brelse: free buffer onto another queue???");
1302 	if (BUF_REFCNT(bp) > 1) {
1303 		/* do not release to free list */
1304 		BUF_UNLOCK(bp);
1305 		splx(s);
1306 		return;
1307 	}
1308 
1309 	/* enqueue */
1310 
1311 	/* buffers with no memory */
1312 	if (bp->b_bufsize == 0) {
1313 		bp->b_flags |= B_INVAL;
1314 		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1315 		if (bp->b_xflags & BX_BKGRDINPROG)
1316 			panic("losing buffer 1");
1317 		if (bp->b_kvasize) {
1318 			bp->b_qindex = QUEUE_EMPTYKVA;
1319 		} else {
1320 			bp->b_qindex = QUEUE_EMPTY;
1321 		}
1322 		TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1323 #ifdef USE_BUFHASH
1324 		LIST_REMOVE(bp, b_hash);
1325 		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1326 #endif
1327 		bp->b_dev = NODEV;
1328 	/* buffers with junk contents */
1329 	} else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1330 	    (bp->b_ioflags & BIO_ERROR)) {
1331 		bp->b_flags |= B_INVAL;
1332 		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1333 		if (bp->b_xflags & BX_BKGRDINPROG)
1334 			panic("losing buffer 2");
1335 		bp->b_qindex = QUEUE_CLEAN;
1336 		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1337 #ifdef USE_BUFHASH
1338 		LIST_REMOVE(bp, b_hash);
1339 		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1340 #endif
1341 		bp->b_dev = NODEV;
1342 
1343 	/* buffers that are locked */
1344 	} else if (bp->b_flags & B_LOCKED) {
1345 		bp->b_qindex = QUEUE_LOCKED;
1346 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1347 
1348 	/* remaining buffers */
1349 	} else {
1350 		if (bp->b_flags & B_DELWRI)
1351 			bp->b_qindex = QUEUE_DIRTY;
1352 		else
1353 			bp->b_qindex = QUEUE_CLEAN;
1354 		if (bp->b_flags & B_AGE)
1355 			TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1356 		else
1357 			TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1358 	}
1359 
1360 	/*
1361 	 * If B_INVAL and B_DELWRI is set, clear B_DELWRI.  We have already
1362 	 * placed the buffer on the correct queue.  We must also disassociate
1363 	 * the device and vnode for a B_INVAL buffer so gbincore() doesn't
1364 	 * find it.
1365 	 */
1366 	if (bp->b_flags & B_INVAL) {
1367 		if (bp->b_flags & B_DELWRI)
1368 			bundirty(bp);
1369 		if (bp->b_vp)
1370 			brelvp(bp);
1371 	}
1372 
1373 	/*
1374 	 * Fixup numfreebuffers count.  The bp is on an appropriate queue
1375 	 * unless locked.  We then bump numfreebuffers if it is not B_DELWRI.
1376 	 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1377 	 * if B_INVAL is set ).
1378 	 */
1379 
1380 	if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1381 		bufcountwakeup();
1382 
1383 	/*
1384 	 * Something we can maybe free or reuse
1385 	 */
1386 	if (bp->b_bufsize || bp->b_kvasize)
1387 		bufspacewakeup();
1388 
1389 	/* unlock */
1390 	BUF_UNLOCK(bp);
1391 	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1392 			B_DIRECT | B_NOWDRAIN);
1393 	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1394 		panic("brelse: not dirty");
1395 	splx(s);
1396 }
1397 
1398 /*
1399  * Release a buffer back to the appropriate queue but do not try to free
1400  * it.  The buffer is expected to be used again soon.
1401  *
1402  * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1403  * biodone() to requeue an async I/O on completion.  It is also used when
1404  * known good buffers need to be requeued but we think we may need the data
1405  * again soon.
1406  *
1407  * XXX we should be able to leave the B_RELBUF hint set on completion.
1408  */
1409 void
1410 bqrelse(struct buf * bp)
1411 {
1412 	int s;
1413 
1414 	s = splbio();
1415 
1416 	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1417 
1418 	if (bp->b_qindex != QUEUE_NONE)
1419 		panic("bqrelse: free buffer onto another queue???");
1420 	if (BUF_REFCNT(bp) > 1) {
1421 		/* do not release to free list */
1422 		BUF_UNLOCK(bp);
1423 		splx(s);
1424 		return;
1425 	}
1426 	if (bp->b_flags & B_LOCKED) {
1427 		bp->b_ioflags &= ~BIO_ERROR;
1428 		bp->b_qindex = QUEUE_LOCKED;
1429 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1430 		/* buffers with stale but valid contents */
1431 	} else if (bp->b_flags & B_DELWRI) {
1432 		bp->b_qindex = QUEUE_DIRTY;
1433 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1434 	} else if (vm_page_count_severe()) {
1435 		/*
1436 		 * We are too low on memory, we have to try to free the
1437 		 * buffer (most importantly: the wired pages making up its
1438 		 * backing store) *now*.
1439 		 */
1440 		splx(s);
1441 		brelse(bp);
1442 		return;
1443 	} else {
1444 		bp->b_qindex = QUEUE_CLEAN;
1445 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1446 	}
1447 
1448 	if ((bp->b_flags & B_LOCKED) == 0 &&
1449 	    ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1450 		bufcountwakeup();
1451 	}
1452 
1453 	/*
1454 	 * Something we can maybe free or reuse.
1455 	 */
1456 	if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1457 		bufspacewakeup();
1458 
1459 	/* unlock */
1460 	BUF_UNLOCK(bp);
1461 	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1462 	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1463 		panic("bqrelse: not dirty");
1464 	splx(s);
1465 }
1466 
1467 /* Give pages used by the bp back to the VM system (where possible) */
1468 static void
1469 vfs_vmio_release(bp)
1470 	struct buf *bp;
1471 {
1472 	int i;
1473 	vm_page_t m;
1474 
1475 	GIANT_REQUIRED;
1476 	vm_page_lock_queues();
1477 	for (i = 0; i < bp->b_npages; i++) {
1478 		m = bp->b_pages[i];
1479 		bp->b_pages[i] = NULL;
1480 		/*
1481 		 * In order to keep page LRU ordering consistent, put
1482 		 * everything on the inactive queue.
1483 		 */
1484 		vm_page_unwire(m, 0);
1485 		/*
1486 		 * We don't mess with busy pages, it is
1487 		 * the responsibility of the process that
1488 		 * busied the pages to deal with them.
1489 		 */
1490 		if ((m->flags & PG_BUSY) || (m->busy != 0))
1491 			continue;
1492 
1493 		if (m->wire_count == 0) {
1494 			vm_page_flag_clear(m, PG_ZERO);
1495 			/*
1496 			 * Might as well free the page if we can and it has
1497 			 * no valid data.  We also free the page if the
1498 			 * buffer was used for direct I/O
1499 			 */
1500 			if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1501 			    m->hold_count == 0) {
1502 				vm_page_busy(m);
1503 				vm_page_protect(m, VM_PROT_NONE);
1504 				vm_page_free(m);
1505 			} else if (bp->b_flags & B_DIRECT) {
1506 				vm_page_try_to_free(m);
1507 			} else if (vm_page_count_severe()) {
1508 				vm_page_try_to_cache(m);
1509 			}
1510 		}
1511 	}
1512 	vm_page_unlock_queues();
1513 	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1514 
1515 	if (bp->b_bufsize) {
1516 		bufspacewakeup();
1517 		bp->b_bufsize = 0;
1518 	}
1519 	bp->b_npages = 0;
1520 	bp->b_flags &= ~B_VMIO;
1521 	if (bp->b_vp)
1522 		brelvp(bp);
1523 }
1524 
1525 #ifdef USE_BUFHASH
1526 /*
1527  * XXX MOVED TO VFS_SUBR.C
1528  *
1529  * Check to see if a block is currently memory resident.
1530  */
1531 struct buf *
1532 gbincore(struct vnode * vp, daddr_t blkno)
1533 {
1534 	struct buf *bp;
1535 	struct bufhashhdr *bh;
1536 
1537 	bh = bufhash(vp, blkno);
1538 
1539 	/* Search hash chain */
1540 	LIST_FOREACH(bp, bh, b_hash) {
1541 		/* hit */
1542 		if (bp->b_vp == vp && bp->b_lblkno == blkno &&
1543 		    (bp->b_flags & B_INVAL) == 0) {
1544 			break;
1545 		}
1546 	}
1547 	return (bp);
1548 }
1549 #endif
1550 
1551 /*
1552  *	vfs_bio_awrite:
1553  *
1554  *	Implement clustered async writes for clearing out B_DELWRI buffers.
1555  *	This is much better then the old way of writing only one buffer at
1556  *	a time.  Note that we may not be presented with the buffers in the
1557  *	correct order, so we search for the cluster in both directions.
1558  */
1559 int
1560 vfs_bio_awrite(struct buf * bp)
1561 {
1562 	int i;
1563 	int j;
1564 	daddr_t lblkno = bp->b_lblkno;
1565 	struct vnode *vp = bp->b_vp;
1566 	int s;
1567 	int ncl;
1568 	struct buf *bpa;
1569 	int nwritten;
1570 	int size;
1571 	int maxcl;
1572 
1573 	s = splbio();
1574 	/*
1575 	 * right now we support clustered writing only to regular files.  If
1576 	 * we find a clusterable block we could be in the middle of a cluster
1577 	 * rather then at the beginning.
1578 	 */
1579 	if ((vp->v_type == VREG) &&
1580 	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1581 	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1582 
1583 		size = vp->v_mount->mnt_stat.f_iosize;
1584 		maxcl = MAXPHYS / size;
1585 
1586 		for (i = 1; i < maxcl; i++) {
1587 			if ((bpa = gbincore(vp, lblkno + i)) &&
1588 			    BUF_REFCNT(bpa) == 0 &&
1589 			    ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1590 			    (B_DELWRI | B_CLUSTEROK)) &&
1591 			    (bpa->b_bufsize == size)) {
1592 				if ((bpa->b_blkno == bpa->b_lblkno) ||
1593 				    (bpa->b_blkno !=
1594 				     bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
1595 					break;
1596 			} else {
1597 				break;
1598 			}
1599 		}
1600 		for (j = 1; i + j <= maxcl && j <= lblkno; j++) {
1601 			if ((bpa = gbincore(vp, lblkno - j)) &&
1602 			    BUF_REFCNT(bpa) == 0 &&
1603 			    ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1604 			    (B_DELWRI | B_CLUSTEROK)) &&
1605 			    (bpa->b_bufsize == size)) {
1606 				if ((bpa->b_blkno == bpa->b_lblkno) ||
1607 				    (bpa->b_blkno !=
1608 				     bp->b_blkno - ((j * size) >> DEV_BSHIFT)))
1609 					break;
1610 			} else {
1611 				break;
1612 			}
1613 		}
1614 		--j;
1615 		ncl = i + j;
1616 		/*
1617 		 * this is a possible cluster write
1618 		 */
1619 		if (ncl != 1) {
1620 			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1621 			splx(s);
1622 			return nwritten;
1623 		}
1624 	}
1625 
1626 	BUF_LOCK(bp, LK_EXCLUSIVE);
1627 	bremfree(bp);
1628 	bp->b_flags |= B_ASYNC;
1629 
1630 	splx(s);
1631 	/*
1632 	 * default (old) behavior, writing out only one block
1633 	 *
1634 	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1635 	 */
1636 	nwritten = bp->b_bufsize;
1637 	(void) BUF_WRITE(bp);
1638 
1639 	return nwritten;
1640 }
1641 
1642 /*
1643  *	getnewbuf:
1644  *
1645  *	Find and initialize a new buffer header, freeing up existing buffers
1646  *	in the bufqueues as necessary.  The new buffer is returned locked.
1647  *
1648  *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1649  *	buffer away, the caller must set B_INVAL prior to calling brelse().
1650  *
1651  *	We block if:
1652  *		We have insufficient buffer headers
1653  *		We have insufficient buffer space
1654  *		buffer_map is too fragmented ( space reservation fails )
1655  *		If we have to flush dirty buffers ( but we try to avoid this )
1656  *
1657  *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1658  *	Instead we ask the buf daemon to do it for us.  We attempt to
1659  *	avoid piecemeal wakeups of the pageout daemon.
1660  */
1661 
1662 static struct buf *
1663 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1664 {
1665 	struct buf *bp;
1666 	struct buf *nbp;
1667 	int defrag = 0;
1668 	int nqindex;
1669 	static int flushingbufs;
1670 
1671 	GIANT_REQUIRED;
1672 
1673 	/*
1674 	 * We can't afford to block since we might be holding a vnode lock,
1675 	 * which may prevent system daemons from running.  We deal with
1676 	 * low-memory situations by proactively returning memory and running
1677 	 * async I/O rather then sync I/O.
1678 	 */
1679 
1680 	++getnewbufcalls;
1681 	--getnewbufrestarts;
1682 restart:
1683 	++getnewbufrestarts;
1684 
1685 	/*
1686 	 * Setup for scan.  If we do not have enough free buffers,
1687 	 * we setup a degenerate case that immediately fails.  Note
1688 	 * that if we are specially marked process, we are allowed to
1689 	 * dip into our reserves.
1690 	 *
1691 	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1692 	 *
1693 	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1694 	 * However, there are a number of cases (defragging, reusing, ...)
1695 	 * where we cannot backup.
1696 	 */
1697 	nqindex = QUEUE_EMPTYKVA;
1698 	nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1699 
1700 	if (nbp == NULL) {
1701 		/*
1702 		 * If no EMPTYKVA buffers and we are either
1703 		 * defragging or reusing, locate a CLEAN buffer
1704 		 * to free or reuse.  If bufspace useage is low
1705 		 * skip this step so we can allocate a new buffer.
1706 		 */
1707 		if (defrag || bufspace >= lobufspace) {
1708 			nqindex = QUEUE_CLEAN;
1709 			nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1710 		}
1711 
1712 		/*
1713 		 * If we could not find or were not allowed to reuse a
1714 		 * CLEAN buffer, check to see if it is ok to use an EMPTY
1715 		 * buffer.  We can only use an EMPTY buffer if allocating
1716 		 * its KVA would not otherwise run us out of buffer space.
1717 		 */
1718 		if (nbp == NULL && defrag == 0 &&
1719 		    bufspace + maxsize < hibufspace) {
1720 			nqindex = QUEUE_EMPTY;
1721 			nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1722 		}
1723 	}
1724 
1725 	/*
1726 	 * Run scan, possibly freeing data and/or kva mappings on the fly
1727 	 * depending.
1728 	 */
1729 
1730 	while ((bp = nbp) != NULL) {
1731 		int qindex = nqindex;
1732 
1733 		/*
1734 		 * Calculate next bp ( we can only use it if we do not block
1735 		 * or do other fancy things ).
1736 		 */
1737 		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1738 			switch(qindex) {
1739 			case QUEUE_EMPTY:
1740 				nqindex = QUEUE_EMPTYKVA;
1741 				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1742 					break;
1743 				/* fall through */
1744 			case QUEUE_EMPTYKVA:
1745 				nqindex = QUEUE_CLEAN;
1746 				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1747 					break;
1748 				/* fall through */
1749 			case QUEUE_CLEAN:
1750 				/*
1751 				 * nbp is NULL.
1752 				 */
1753 				break;
1754 			}
1755 		}
1756 
1757 		/*
1758 		 * Sanity Checks
1759 		 */
1760 		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1761 
1762 		/*
1763 		 * Note: we no longer distinguish between VMIO and non-VMIO
1764 		 * buffers.
1765 		 */
1766 
1767 		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1768 
1769 		/*
1770 		 * If we are defragging then we need a buffer with
1771 		 * b_kvasize != 0.  XXX this situation should no longer
1772 		 * occur, if defrag is non-zero the buffer's b_kvasize
1773 		 * should also be non-zero at this point.  XXX
1774 		 */
1775 		if (defrag && bp->b_kvasize == 0) {
1776 			printf("Warning: defrag empty buffer %p\n", bp);
1777 			continue;
1778 		}
1779 
1780 		/*
1781 		 * Start freeing the bp.  This is somewhat involved.  nbp
1782 		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1783 		 */
1784 
1785 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1786 			panic("getnewbuf: locked buf");
1787 		bremfree(bp);
1788 
1789 		if (qindex == QUEUE_CLEAN) {
1790 			if (bp->b_flags & B_VMIO) {
1791 				bp->b_flags &= ~B_ASYNC;
1792 				vfs_vmio_release(bp);
1793 			}
1794 			if (bp->b_vp)
1795 				brelvp(bp);
1796 		}
1797 
1798 		/*
1799 		 * NOTE:  nbp is now entirely invalid.  We can only restart
1800 		 * the scan from this point on.
1801 		 *
1802 		 * Get the rest of the buffer freed up.  b_kva* is still
1803 		 * valid after this operation.
1804 		 */
1805 
1806 		if (bp->b_rcred != NOCRED) {
1807 			crfree(bp->b_rcred);
1808 			bp->b_rcred = NOCRED;
1809 		}
1810 		if (bp->b_wcred != NOCRED) {
1811 			crfree(bp->b_wcred);
1812 			bp->b_wcred = NOCRED;
1813 		}
1814 		if (LIST_FIRST(&bp->b_dep) != NULL)
1815 			buf_deallocate(bp);
1816 		if (bp->b_xflags & BX_BKGRDINPROG)
1817 			panic("losing buffer 3");
1818 #ifdef USE_BUFHASH
1819 		LIST_REMOVE(bp, b_hash);
1820 		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1821 #endif
1822 
1823 		if (bp->b_bufsize)
1824 			allocbuf(bp, 0);
1825 
1826 		bp->b_flags = 0;
1827 		bp->b_ioflags = 0;
1828 		bp->b_xflags = 0;
1829 		bp->b_dev = NODEV;
1830 		bp->b_vp = NULL;
1831 		bp->b_blkno = bp->b_lblkno = 0;
1832 		bp->b_offset = NOOFFSET;
1833 		bp->b_iodone = 0;
1834 		bp->b_error = 0;
1835 		bp->b_resid = 0;
1836 		bp->b_bcount = 0;
1837 		bp->b_npages = 0;
1838 		bp->b_dirtyoff = bp->b_dirtyend = 0;
1839 		bp->b_magic = B_MAGIC_BIO;
1840 		bp->b_op = &buf_ops_bio;
1841 		bp->b_object = NULL;
1842 
1843 		LIST_INIT(&bp->b_dep);
1844 
1845 		/*
1846 		 * If we are defragging then free the buffer.
1847 		 */
1848 		if (defrag) {
1849 			bp->b_flags |= B_INVAL;
1850 			bfreekva(bp);
1851 			brelse(bp);
1852 			defrag = 0;
1853 			goto restart;
1854 		}
1855 
1856 		/*
1857 		 * If we are overcomitted then recover the buffer and its
1858 		 * KVM space.  This occurs in rare situations when multiple
1859 		 * processes are blocked in getnewbuf() or allocbuf().
1860 		 */
1861 		if (bufspace >= hibufspace)
1862 			flushingbufs = 1;
1863 		if (flushingbufs && bp->b_kvasize != 0) {
1864 			bp->b_flags |= B_INVAL;
1865 			bfreekva(bp);
1866 			brelse(bp);
1867 			goto restart;
1868 		}
1869 		if (bufspace < lobufspace)
1870 			flushingbufs = 0;
1871 		break;
1872 	}
1873 
1874 	/*
1875 	 * If we exhausted our list, sleep as appropriate.  We may have to
1876 	 * wakeup various daemons and write out some dirty buffers.
1877 	 *
1878 	 * Generally we are sleeping due to insufficient buffer space.
1879 	 */
1880 
1881 	if (bp == NULL) {
1882 		int flags;
1883 		char *waitmsg;
1884 
1885 		if (defrag) {
1886 			flags = VFS_BIO_NEED_BUFSPACE;
1887 			waitmsg = "nbufkv";
1888 		} else if (bufspace >= hibufspace) {
1889 			waitmsg = "nbufbs";
1890 			flags = VFS_BIO_NEED_BUFSPACE;
1891 		} else {
1892 			waitmsg = "newbuf";
1893 			flags = VFS_BIO_NEED_ANY;
1894 		}
1895 
1896 		bd_speedup();	/* heeeelp */
1897 
1898 		needsbuffer |= flags;
1899 		while (needsbuffer & flags) {
1900 			if (tsleep(&needsbuffer, (PRIBIO + 4) | slpflag,
1901 			    waitmsg, slptimeo))
1902 				return (NULL);
1903 		}
1904 	} else {
1905 		/*
1906 		 * We finally have a valid bp.  We aren't quite out of the
1907 		 * woods, we still have to reserve kva space.  In order
1908 		 * to keep fragmentation sane we only allocate kva in
1909 		 * BKVASIZE chunks.
1910 		 */
1911 		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1912 
1913 		if (maxsize != bp->b_kvasize) {
1914 			vm_offset_t addr = 0;
1915 
1916 			bfreekva(bp);
1917 
1918 			if (vm_map_findspace(buffer_map,
1919 				vm_map_min(buffer_map), maxsize, &addr)) {
1920 				/*
1921 				 * Uh oh.  Buffer map is to fragmented.  We
1922 				 * must defragment the map.
1923 				 */
1924 				++bufdefragcnt;
1925 				defrag = 1;
1926 				bp->b_flags |= B_INVAL;
1927 				brelse(bp);
1928 				goto restart;
1929 			}
1930 			if (addr) {
1931 				vm_map_insert(buffer_map, NULL, 0,
1932 					addr, addr + maxsize,
1933 					VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1934 
1935 				bp->b_kvabase = (caddr_t) addr;
1936 				bp->b_kvasize = maxsize;
1937 				bufspace += bp->b_kvasize;
1938 				++bufreusecnt;
1939 			}
1940 		}
1941 		bp->b_data = bp->b_kvabase;
1942 	}
1943 	return(bp);
1944 }
1945 
1946 /*
1947  *	buf_daemon:
1948  *
1949  *	buffer flushing daemon.  Buffers are normally flushed by the
1950  *	update daemon but if it cannot keep up this process starts to
1951  *	take the load in an attempt to prevent getnewbuf() from blocking.
1952  */
1953 
1954 static struct proc *bufdaemonproc;
1955 
1956 static struct kproc_desc buf_kp = {
1957 	"bufdaemon",
1958 	buf_daemon,
1959 	&bufdaemonproc
1960 };
1961 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1962 
1963 static void
1964 buf_daemon()
1965 {
1966 	int s;
1967 
1968 	mtx_lock(&Giant);
1969 
1970 	/*
1971 	 * This process needs to be suspended prior to shutdown sync.
1972 	 */
1973 	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
1974 	    SHUTDOWN_PRI_LAST);
1975 
1976 	/*
1977 	 * This process is allowed to take the buffer cache to the limit
1978 	 */
1979 	s = splbio();
1980 
1981 	for (;;) {
1982 		kthread_suspend_check(bufdaemonproc);
1983 
1984 		bd_request = 0;
1985 
1986 		/*
1987 		 * Do the flush.  Limit the amount of in-transit I/O we
1988 		 * allow to build up, otherwise we would completely saturate
1989 		 * the I/O system.  Wakeup any waiting processes before we
1990 		 * normally would so they can run in parallel with our drain.
1991 		 */
1992 		while (numdirtybuffers > lodirtybuffers) {
1993 			if (flushbufqueues() == 0)
1994 				break;
1995 			waitrunningbufspace();
1996 			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
1997 		}
1998 
1999 		/*
2000 		 * Only clear bd_request if we have reached our low water
2001 		 * mark.  The buf_daemon normally waits 1 second and
2002 		 * then incrementally flushes any dirty buffers that have
2003 		 * built up, within reason.
2004 		 *
2005 		 * If we were unable to hit our low water mark and couldn't
2006 		 * find any flushable buffers, we sleep half a second.
2007 		 * Otherwise we loop immediately.
2008 		 */
2009 		if (numdirtybuffers <= lodirtybuffers) {
2010 			/*
2011 			 * We reached our low water mark, reset the
2012 			 * request and sleep until we are needed again.
2013 			 * The sleep is just so the suspend code works.
2014 			 */
2015 			bd_request = 0;
2016 			tsleep(&bd_request, PVM, "psleep", hz);
2017 		} else {
2018 			/*
2019 			 * We couldn't find any flushable dirty buffers but
2020 			 * still have too many dirty buffers, we
2021 			 * have to sleep and try again.  (rare)
2022 			 */
2023 			tsleep(&bd_request, PVM, "qsleep", hz / 2);
2024 		}
2025 	}
2026 }
2027 
2028 /*
2029  *	flushbufqueues:
2030  *
2031  *	Try to flush a buffer in the dirty queue.  We must be careful to
2032  *	free up B_INVAL buffers instead of write them, which NFS is
2033  *	particularly sensitive to.
2034  */
2035 
2036 static int
2037 flushbufqueues(void)
2038 {
2039 	struct buf *bp;
2040 	int r = 0;
2041 
2042 	bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
2043 
2044 	while (bp) {
2045 		KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
2046 		if ((bp->b_flags & B_DELWRI) != 0 &&
2047 		    (bp->b_xflags & BX_BKGRDINPROG) == 0) {
2048 			if (bp->b_flags & B_INVAL) {
2049 				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2050 					panic("flushbufqueues: locked buf");
2051 				bremfree(bp);
2052 				brelse(bp);
2053 				++r;
2054 				break;
2055 			}
2056 			if (LIST_FIRST(&bp->b_dep) != NULL &&
2057 			    (bp->b_flags & B_DEFERRED) == 0 &&
2058 			    buf_countdeps(bp, 0)) {
2059 				TAILQ_REMOVE(&bufqueues[QUEUE_DIRTY],
2060 				    bp, b_freelist);
2061 				TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY],
2062 				    bp, b_freelist);
2063 				bp->b_flags |= B_DEFERRED;
2064 				bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
2065 				continue;
2066 			}
2067 			vfs_bio_awrite(bp);
2068 			++r;
2069 			break;
2070 		}
2071 		bp = TAILQ_NEXT(bp, b_freelist);
2072 	}
2073 	return (r);
2074 }
2075 
2076 /*
2077  * Check to see if a block is currently memory resident.
2078  */
2079 struct buf *
2080 incore(struct vnode * vp, daddr_t blkno)
2081 {
2082 	struct buf *bp;
2083 
2084 	int s = splbio();
2085 	bp = gbincore(vp, blkno);
2086 	splx(s);
2087 	return (bp);
2088 }
2089 
2090 /*
2091  * Returns true if no I/O is needed to access the
2092  * associated VM object.  This is like incore except
2093  * it also hunts around in the VM system for the data.
2094  */
2095 
2096 int
2097 inmem(struct vnode * vp, daddr_t blkno)
2098 {
2099 	vm_object_t obj;
2100 	vm_offset_t toff, tinc, size;
2101 	vm_page_t m;
2102 	vm_ooffset_t off;
2103 
2104 	GIANT_REQUIRED;
2105 
2106 	if (incore(vp, blkno))
2107 		return 1;
2108 	if (vp->v_mount == NULL)
2109 		return 0;
2110 	if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_flag & VOBJBUF) == 0)
2111 		return 0;
2112 
2113 	size = PAGE_SIZE;
2114 	if (size > vp->v_mount->mnt_stat.f_iosize)
2115 		size = vp->v_mount->mnt_stat.f_iosize;
2116 	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2117 
2118 	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2119 		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2120 		if (!m)
2121 			goto notinmem;
2122 		tinc = size;
2123 		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2124 			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2125 		if (vm_page_is_valid(m,
2126 		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2127 			goto notinmem;
2128 	}
2129 	return 1;
2130 
2131 notinmem:
2132 	return (0);
2133 }
2134 
2135 /*
2136  *	vfs_setdirty:
2137  *
2138  *	Sets the dirty range for a buffer based on the status of the dirty
2139  *	bits in the pages comprising the buffer.
2140  *
2141  *	The range is limited to the size of the buffer.
2142  *
2143  *	This routine is primarily used by NFS, but is generalized for the
2144  *	B_VMIO case.
2145  */
2146 static void
2147 vfs_setdirty(struct buf *bp)
2148 {
2149 	int i;
2150 	vm_object_t object;
2151 
2152 	GIANT_REQUIRED;
2153 	/*
2154 	 * Degenerate case - empty buffer
2155 	 */
2156 
2157 	if (bp->b_bufsize == 0)
2158 		return;
2159 
2160 	/*
2161 	 * We qualify the scan for modified pages on whether the
2162 	 * object has been flushed yet.  The OBJ_WRITEABLE flag
2163 	 * is not cleared simply by protecting pages off.
2164 	 */
2165 
2166 	if ((bp->b_flags & B_VMIO) == 0)
2167 		return;
2168 
2169 	object = bp->b_pages[0]->object;
2170 
2171 	if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2172 		printf("Warning: object %p writeable but not mightbedirty\n", object);
2173 	if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2174 		printf("Warning: object %p mightbedirty but not writeable\n", object);
2175 
2176 	if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2177 		vm_offset_t boffset;
2178 		vm_offset_t eoffset;
2179 
2180 		/*
2181 		 * test the pages to see if they have been modified directly
2182 		 * by users through the VM system.
2183 		 */
2184 		for (i = 0; i < bp->b_npages; i++) {
2185 			vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
2186 			vm_page_test_dirty(bp->b_pages[i]);
2187 		}
2188 
2189 		/*
2190 		 * Calculate the encompassing dirty range, boffset and eoffset,
2191 		 * (eoffset - boffset) bytes.
2192 		 */
2193 
2194 		for (i = 0; i < bp->b_npages; i++) {
2195 			if (bp->b_pages[i]->dirty)
2196 				break;
2197 		}
2198 		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2199 
2200 		for (i = bp->b_npages - 1; i >= 0; --i) {
2201 			if (bp->b_pages[i]->dirty) {
2202 				break;
2203 			}
2204 		}
2205 		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2206 
2207 		/*
2208 		 * Fit it to the buffer.
2209 		 */
2210 
2211 		if (eoffset > bp->b_bcount)
2212 			eoffset = bp->b_bcount;
2213 
2214 		/*
2215 		 * If we have a good dirty range, merge with the existing
2216 		 * dirty range.
2217 		 */
2218 
2219 		if (boffset < eoffset) {
2220 			if (bp->b_dirtyoff > boffset)
2221 				bp->b_dirtyoff = boffset;
2222 			if (bp->b_dirtyend < eoffset)
2223 				bp->b_dirtyend = eoffset;
2224 		}
2225 	}
2226 }
2227 
2228 /*
2229  *	getblk:
2230  *
2231  *	Get a block given a specified block and offset into a file/device.
2232  *	The buffers B_DONE bit will be cleared on return, making it almost
2233  * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2234  *	return.  The caller should clear B_INVAL prior to initiating a
2235  *	READ.
2236  *
2237  *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2238  *	an existing buffer.
2239  *
2240  *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2241  *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2242  *	and then cleared based on the backing VM.  If the previous buffer is
2243  *	non-0-sized but invalid, B_CACHE will be cleared.
2244  *
2245  *	If getblk() must create a new buffer, the new buffer is returned with
2246  *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2247  *	case it is returned with B_INVAL clear and B_CACHE set based on the
2248  *	backing VM.
2249  *
2250  *	getblk() also forces a BUF_WRITE() for any B_DELWRI buffer whos
2251  *	B_CACHE bit is clear.
2252  *
2253  *	What this means, basically, is that the caller should use B_CACHE to
2254  *	determine whether the buffer is fully valid or not and should clear
2255  *	B_INVAL prior to issuing a read.  If the caller intends to validate
2256  *	the buffer by loading its data area with something, the caller needs
2257  *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2258  *	the caller should set B_CACHE ( as an optimization ), else the caller
2259  *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2260  *	a write attempt or if it was a successfull read.  If the caller
2261  *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2262  *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2263  */
2264 struct buf *
2265 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
2266 {
2267 	struct buf *bp;
2268 	int s;
2269 #ifdef USE_BUFHASH
2270 	struct bufhashhdr *bh;
2271 #endif
2272 
2273 	if (size > MAXBSIZE)
2274 		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2275 
2276 	s = splbio();
2277 loop:
2278 	/*
2279 	 * Block if we are low on buffers.   Certain processes are allowed
2280 	 * to completely exhaust the buffer cache.
2281          *
2282          * If this check ever becomes a bottleneck it may be better to
2283          * move it into the else, when gbincore() fails.  At the moment
2284          * it isn't a problem.
2285 	 *
2286 	 * XXX remove if 0 sections (clean this up after its proven)
2287          */
2288 	if (numfreebuffers == 0) {
2289 		if (curthread == PCPU_GET(idlethread))
2290 			return NULL;
2291 		needsbuffer |= VFS_BIO_NEED_ANY;
2292 	}
2293 
2294 	if ((bp = gbincore(vp, blkno))) {
2295 		/*
2296 		 * Buffer is in-core.  If the buffer is not busy, it must
2297 		 * be on a queue.
2298 		 */
2299 
2300 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2301 			if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2302 			    "getblk", slpflag, slptimeo) == ENOLCK)
2303 				goto loop;
2304 			splx(s);
2305 			return (struct buf *) NULL;
2306 		}
2307 
2308 		/*
2309 		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2310 		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
2311 		 * and for a VMIO buffer B_CACHE is adjusted according to the
2312 		 * backing VM cache.
2313 		 */
2314 		if (bp->b_flags & B_INVAL)
2315 			bp->b_flags &= ~B_CACHE;
2316 		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2317 			bp->b_flags |= B_CACHE;
2318 		bremfree(bp);
2319 
2320 		/*
2321 		 * check for size inconsistancies for non-VMIO case.
2322 		 */
2323 
2324 		if (bp->b_bcount != size) {
2325 			if ((bp->b_flags & B_VMIO) == 0 ||
2326 			    (size > bp->b_kvasize)) {
2327 				if (bp->b_flags & B_DELWRI) {
2328 					bp->b_flags |= B_NOCACHE;
2329 					BUF_WRITE(bp);
2330 				} else {
2331 					if ((bp->b_flags & B_VMIO) &&
2332 					   (LIST_FIRST(&bp->b_dep) == NULL)) {
2333 						bp->b_flags |= B_RELBUF;
2334 						brelse(bp);
2335 					} else {
2336 						bp->b_flags |= B_NOCACHE;
2337 						BUF_WRITE(bp);
2338 					}
2339 				}
2340 				goto loop;
2341 			}
2342 		}
2343 
2344 		/*
2345 		 * If the size is inconsistant in the VMIO case, we can resize
2346 		 * the buffer.  This might lead to B_CACHE getting set or
2347 		 * cleared.  If the size has not changed, B_CACHE remains
2348 		 * unchanged from its previous state.
2349 		 */
2350 
2351 		if (bp->b_bcount != size)
2352 			allocbuf(bp, size);
2353 
2354 		KASSERT(bp->b_offset != NOOFFSET,
2355 		    ("getblk: no buffer offset"));
2356 
2357 		/*
2358 		 * A buffer with B_DELWRI set and B_CACHE clear must
2359 		 * be committed before we can return the buffer in
2360 		 * order to prevent the caller from issuing a read
2361 		 * ( due to B_CACHE not being set ) and overwriting
2362 		 * it.
2363 		 *
2364 		 * Most callers, including NFS and FFS, need this to
2365 		 * operate properly either because they assume they
2366 		 * can issue a read if B_CACHE is not set, or because
2367 		 * ( for example ) an uncached B_DELWRI might loop due
2368 		 * to softupdates re-dirtying the buffer.  In the latter
2369 		 * case, B_CACHE is set after the first write completes,
2370 		 * preventing further loops.
2371 		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2372 		 * above while extending the buffer, we cannot allow the
2373 		 * buffer to remain with B_CACHE set after the write
2374 		 * completes or it will represent a corrupt state.  To
2375 		 * deal with this we set B_NOCACHE to scrap the buffer
2376 		 * after the write.
2377 		 *
2378 		 * We might be able to do something fancy, like setting
2379 		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2380 		 * so the below call doesn't set B_CACHE, but that gets real
2381 		 * confusing.  This is much easier.
2382 		 */
2383 
2384 		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2385 			bp->b_flags |= B_NOCACHE;
2386 			BUF_WRITE(bp);
2387 			goto loop;
2388 		}
2389 
2390 		splx(s);
2391 		bp->b_flags &= ~B_DONE;
2392 	} else {
2393 		/*
2394 		 * Buffer is not in-core, create new buffer.  The buffer
2395 		 * returned by getnewbuf() is locked.  Note that the returned
2396 		 * buffer is also considered valid (not marked B_INVAL).
2397 		 */
2398 		int bsize, maxsize, vmio;
2399 		off_t offset;
2400 
2401 		if (vn_isdisk(vp, NULL))
2402 			bsize = DEV_BSIZE;
2403 		else if (vp->v_mountedhere)
2404 			bsize = vp->v_mountedhere->mnt_stat.f_iosize;
2405 		else if (vp->v_mount)
2406 			bsize = vp->v_mount->mnt_stat.f_iosize;
2407 		else
2408 			bsize = size;
2409 
2410 		offset = blkno * bsize;
2411 		vmio = (VOP_GETVOBJECT(vp, NULL) == 0) && (vp->v_flag & VOBJBUF);
2412 		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2413 		maxsize = imax(maxsize, bsize);
2414 
2415 		if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2416 			if (slpflag || slptimeo) {
2417 				splx(s);
2418 				return NULL;
2419 			}
2420 			goto loop;
2421 		}
2422 
2423 		/*
2424 		 * This code is used to make sure that a buffer is not
2425 		 * created while the getnewbuf routine is blocked.
2426 		 * This can be a problem whether the vnode is locked or not.
2427 		 * If the buffer is created out from under us, we have to
2428 		 * throw away the one we just created.  There is now window
2429 		 * race because we are safely running at splbio() from the
2430 		 * point of the duplicate buffer creation through to here,
2431 		 * and we've locked the buffer.
2432 		 *
2433 		 * Note: this must occur before we associate the buffer
2434 		 * with the vp especially considering limitations in
2435 		 * the splay tree implementation when dealing with duplicate
2436 		 * lblkno's.
2437 		 */
2438 		if (gbincore(vp, blkno)) {
2439 			bp->b_flags |= B_INVAL;
2440 			brelse(bp);
2441 			goto loop;
2442 		}
2443 
2444 		/*
2445 		 * Insert the buffer into the hash, so that it can
2446 		 * be found by incore.
2447 		 */
2448 		bp->b_blkno = bp->b_lblkno = blkno;
2449 		bp->b_offset = offset;
2450 
2451 		bgetvp(vp, bp);
2452 #ifdef USE_BUFHASH
2453 		LIST_REMOVE(bp, b_hash);
2454 		bh = bufhash(vp, blkno);
2455 		LIST_INSERT_HEAD(bh, bp, b_hash);
2456 #endif
2457 
2458 		/*
2459 		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2460 		 * buffer size starts out as 0, B_CACHE will be set by
2461 		 * allocbuf() for the VMIO case prior to it testing the
2462 		 * backing store for validity.
2463 		 */
2464 
2465 		if (vmio) {
2466 			bp->b_flags |= B_VMIO;
2467 #if defined(VFS_BIO_DEBUG)
2468 			if (vp->v_type != VREG)
2469 				printf("getblk: vmioing file type %d???\n", vp->v_type);
2470 #endif
2471 			VOP_GETVOBJECT(vp, &bp->b_object);
2472 		} else {
2473 			bp->b_flags &= ~B_VMIO;
2474 			bp->b_object = NULL;
2475 		}
2476 
2477 		allocbuf(bp, size);
2478 
2479 		splx(s);
2480 		bp->b_flags &= ~B_DONE;
2481 	}
2482 	KASSERT(BUF_REFCNT(bp) == 1, ("getblk: bp %p not locked",bp));
2483 	return (bp);
2484 }
2485 
2486 /*
2487  * Get an empty, disassociated buffer of given size.  The buffer is initially
2488  * set to B_INVAL.
2489  */
2490 struct buf *
2491 geteblk(int size)
2492 {
2493 	struct buf *bp;
2494 	int s;
2495 	int maxsize;
2496 
2497 	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2498 
2499 	s = splbio();
2500 	while ((bp = getnewbuf(0, 0, size, maxsize)) == 0);
2501 	splx(s);
2502 	allocbuf(bp, size);
2503 	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2504 	KASSERT(BUF_REFCNT(bp) == 1, ("geteblk: bp %p not locked",bp));
2505 	return (bp);
2506 }
2507 
2508 
2509 /*
2510  * This code constitutes the buffer memory from either anonymous system
2511  * memory (in the case of non-VMIO operations) or from an associated
2512  * VM object (in the case of VMIO operations).  This code is able to
2513  * resize a buffer up or down.
2514  *
2515  * Note that this code is tricky, and has many complications to resolve
2516  * deadlock or inconsistant data situations.  Tread lightly!!!
2517  * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2518  * the caller.  Calling this code willy nilly can result in the loss of data.
2519  *
2520  * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2521  * B_CACHE for the non-VMIO case.
2522  */
2523 
2524 int
2525 allocbuf(struct buf *bp, int size)
2526 {
2527 	int newbsize, mbsize;
2528 	int i;
2529 
2530 	GIANT_REQUIRED;
2531 
2532 	if (BUF_REFCNT(bp) == 0)
2533 		panic("allocbuf: buffer not busy");
2534 
2535 	if (bp->b_kvasize < size)
2536 		panic("allocbuf: buffer too small");
2537 
2538 	if ((bp->b_flags & B_VMIO) == 0) {
2539 		caddr_t origbuf;
2540 		int origbufsize;
2541 		/*
2542 		 * Just get anonymous memory from the kernel.  Don't
2543 		 * mess with B_CACHE.
2544 		 */
2545 		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2546 		if (bp->b_flags & B_MALLOC)
2547 			newbsize = mbsize;
2548 		else
2549 			newbsize = round_page(size);
2550 
2551 		if (newbsize < bp->b_bufsize) {
2552 			/*
2553 			 * malloced buffers are not shrunk
2554 			 */
2555 			if (bp->b_flags & B_MALLOC) {
2556 				if (newbsize) {
2557 					bp->b_bcount = size;
2558 				} else {
2559 					free(bp->b_data, M_BIOBUF);
2560 					if (bp->b_bufsize) {
2561 						bufmallocspace -= bp->b_bufsize;
2562 						bufspacewakeup();
2563 						bp->b_bufsize = 0;
2564 					}
2565 					bp->b_data = bp->b_kvabase;
2566 					bp->b_bcount = 0;
2567 					bp->b_flags &= ~B_MALLOC;
2568 				}
2569 				return 1;
2570 			}
2571 			vm_hold_free_pages(
2572 			    bp,
2573 			    (vm_offset_t) bp->b_data + newbsize,
2574 			    (vm_offset_t) bp->b_data + bp->b_bufsize);
2575 		} else if (newbsize > bp->b_bufsize) {
2576 			/*
2577 			 * We only use malloced memory on the first allocation.
2578 			 * and revert to page-allocated memory when the buffer
2579 			 * grows.
2580 			 */
2581 			if ( (bufmallocspace < maxbufmallocspace) &&
2582 				(bp->b_bufsize == 0) &&
2583 				(mbsize <= PAGE_SIZE/2)) {
2584 
2585 				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2586 				bp->b_bufsize = mbsize;
2587 				bp->b_bcount = size;
2588 				bp->b_flags |= B_MALLOC;
2589 				bufmallocspace += mbsize;
2590 				return 1;
2591 			}
2592 			origbuf = NULL;
2593 			origbufsize = 0;
2594 			/*
2595 			 * If the buffer is growing on its other-than-first allocation,
2596 			 * then we revert to the page-allocation scheme.
2597 			 */
2598 			if (bp->b_flags & B_MALLOC) {
2599 				origbuf = bp->b_data;
2600 				origbufsize = bp->b_bufsize;
2601 				bp->b_data = bp->b_kvabase;
2602 				if (bp->b_bufsize) {
2603 					bufmallocspace -= bp->b_bufsize;
2604 					bufspacewakeup();
2605 					bp->b_bufsize = 0;
2606 				}
2607 				bp->b_flags &= ~B_MALLOC;
2608 				newbsize = round_page(newbsize);
2609 			}
2610 			vm_hold_load_pages(
2611 			    bp,
2612 			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2613 			    (vm_offset_t) bp->b_data + newbsize);
2614 			if (origbuf) {
2615 				bcopy(origbuf, bp->b_data, origbufsize);
2616 				free(origbuf, M_BIOBUF);
2617 			}
2618 		}
2619 	} else {
2620 		vm_page_t m;
2621 		int desiredpages;
2622 
2623 		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2624 		desiredpages = (size == 0) ? 0 :
2625 			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2626 
2627 		if (bp->b_flags & B_MALLOC)
2628 			panic("allocbuf: VMIO buffer can't be malloced");
2629 		/*
2630 		 * Set B_CACHE initially if buffer is 0 length or will become
2631 		 * 0-length.
2632 		 */
2633 		if (size == 0 || bp->b_bufsize == 0)
2634 			bp->b_flags |= B_CACHE;
2635 
2636 		if (newbsize < bp->b_bufsize) {
2637 			/*
2638 			 * DEV_BSIZE aligned new buffer size is less then the
2639 			 * DEV_BSIZE aligned existing buffer size.  Figure out
2640 			 * if we have to remove any pages.
2641 			 */
2642 			if (desiredpages < bp->b_npages) {
2643 				for (i = desiredpages; i < bp->b_npages; i++) {
2644 					/*
2645 					 * the page is not freed here -- it
2646 					 * is the responsibility of
2647 					 * vnode_pager_setsize
2648 					 */
2649 					m = bp->b_pages[i];
2650 					KASSERT(m != bogus_page,
2651 					    ("allocbuf: bogus page found"));
2652 					while (vm_page_sleep_busy(m, TRUE, "biodep"))
2653 						;
2654 
2655 					bp->b_pages[i] = NULL;
2656 					vm_page_lock_queues();
2657 					vm_page_unwire(m, 0);
2658 					vm_page_unlock_queues();
2659 				}
2660 				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2661 				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2662 				bp->b_npages = desiredpages;
2663 			}
2664 		} else if (size > bp->b_bcount) {
2665 			/*
2666 			 * We are growing the buffer, possibly in a
2667 			 * byte-granular fashion.
2668 			 */
2669 			struct vnode *vp;
2670 			vm_object_t obj;
2671 			vm_offset_t toff;
2672 			vm_offset_t tinc;
2673 
2674 			/*
2675 			 * Step 1, bring in the VM pages from the object,
2676 			 * allocating them if necessary.  We must clear
2677 			 * B_CACHE if these pages are not valid for the
2678 			 * range covered by the buffer.
2679 			 */
2680 
2681 			vp = bp->b_vp;
2682 			obj = bp->b_object;
2683 
2684 			while (bp->b_npages < desiredpages) {
2685 				vm_page_t m;
2686 				vm_pindex_t pi;
2687 
2688 				pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2689 				if ((m = vm_page_lookup(obj, pi)) == NULL) {
2690 					/*
2691 					 * note: must allocate system pages
2692 					 * since blocking here could intefere
2693 					 * with paging I/O, no matter which
2694 					 * process we are.
2695 					 */
2696 					m = vm_page_alloc(obj, pi,
2697 					    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
2698 					if (m == NULL) {
2699 						VM_WAIT;
2700 						vm_pageout_deficit += desiredpages - bp->b_npages;
2701 					} else {
2702 						vm_page_lock_queues();
2703 						vm_page_wakeup(m);
2704 						vm_page_unlock_queues();
2705 						bp->b_flags &= ~B_CACHE;
2706 						bp->b_pages[bp->b_npages] = m;
2707 						++bp->b_npages;
2708 					}
2709 					continue;
2710 				}
2711 
2712 				/*
2713 				 * We found a page.  If we have to sleep on it,
2714 				 * retry because it might have gotten freed out
2715 				 * from under us.
2716 				 *
2717 				 * We can only test PG_BUSY here.  Blocking on
2718 				 * m->busy might lead to a deadlock:
2719 				 *
2720 				 *  vm_fault->getpages->cluster_read->allocbuf
2721 				 *
2722 				 */
2723 
2724 				if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2725 					continue;
2726 
2727 				/*
2728 				 * We have a good page.  Should we wakeup the
2729 				 * page daemon?
2730 				 */
2731 				if ((curproc != pageproc) &&
2732 				    ((m->queue - m->pc) == PQ_CACHE) &&
2733 				    ((cnt.v_free_count + cnt.v_cache_count) <
2734 					(cnt.v_free_min + cnt.v_cache_min))) {
2735 					pagedaemon_wakeup();
2736 				}
2737 				vm_page_lock_queues();
2738 				vm_page_flag_clear(m, PG_ZERO);
2739 				vm_page_wire(m);
2740 				vm_page_unlock_queues();
2741 				bp->b_pages[bp->b_npages] = m;
2742 				++bp->b_npages;
2743 			}
2744 
2745 			/*
2746 			 * Step 2.  We've loaded the pages into the buffer,
2747 			 * we have to figure out if we can still have B_CACHE
2748 			 * set.  Note that B_CACHE is set according to the
2749 			 * byte-granular range ( bcount and size ), new the
2750 			 * aligned range ( newbsize ).
2751 			 *
2752 			 * The VM test is against m->valid, which is DEV_BSIZE
2753 			 * aligned.  Needless to say, the validity of the data
2754 			 * needs to also be DEV_BSIZE aligned.  Note that this
2755 			 * fails with NFS if the server or some other client
2756 			 * extends the file's EOF.  If our buffer is resized,
2757 			 * B_CACHE may remain set! XXX
2758 			 */
2759 
2760 			toff = bp->b_bcount;
2761 			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2762 
2763 			while ((bp->b_flags & B_CACHE) && toff < size) {
2764 				vm_pindex_t pi;
2765 
2766 				if (tinc > (size - toff))
2767 					tinc = size - toff;
2768 
2769 				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2770 				    PAGE_SHIFT;
2771 
2772 				vfs_buf_test_cache(
2773 				    bp,
2774 				    bp->b_offset,
2775 				    toff,
2776 				    tinc,
2777 				    bp->b_pages[pi]
2778 				);
2779 				toff += tinc;
2780 				tinc = PAGE_SIZE;
2781 			}
2782 
2783 			/*
2784 			 * Step 3, fixup the KVM pmap.  Remember that
2785 			 * bp->b_data is relative to bp->b_offset, but
2786 			 * bp->b_offset may be offset into the first page.
2787 			 */
2788 
2789 			bp->b_data = (caddr_t)
2790 			    trunc_page((vm_offset_t)bp->b_data);
2791 			pmap_qenter(
2792 			    (vm_offset_t)bp->b_data,
2793 			    bp->b_pages,
2794 			    bp->b_npages
2795 			);
2796 
2797 			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2798 			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
2799 		}
2800 	}
2801 	if (newbsize < bp->b_bufsize)
2802 		bufspacewakeup();
2803 	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
2804 	bp->b_bcount = size;		/* requested buffer size	*/
2805 	return 1;
2806 }
2807 
2808 /*
2809  *	bufwait:
2810  *
2811  *	Wait for buffer I/O completion, returning error status.  The buffer
2812  *	is left locked and B_DONE on return.  B_EINTR is converted into a EINTR
2813  *	error and cleared.
2814  */
2815 int
2816 bufwait(register struct buf * bp)
2817 {
2818 	int s;
2819 
2820 	s = splbio();
2821 	while ((bp->b_flags & B_DONE) == 0) {
2822 		if (bp->b_iocmd == BIO_READ)
2823 			tsleep(bp, PRIBIO, "biord", 0);
2824 		else
2825 			tsleep(bp, PRIBIO, "biowr", 0);
2826 	}
2827 	splx(s);
2828 	if (bp->b_flags & B_EINTR) {
2829 		bp->b_flags &= ~B_EINTR;
2830 		return (EINTR);
2831 	}
2832 	if (bp->b_ioflags & BIO_ERROR) {
2833 		return (bp->b_error ? bp->b_error : EIO);
2834 	} else {
2835 		return (0);
2836 	}
2837 }
2838 
2839  /*
2840   * Call back function from struct bio back up to struct buf.
2841   * The corresponding initialization lives in sys/conf.h:DEV_STRATEGY().
2842   */
2843 void
2844 bufdonebio(struct bio *bp)
2845 {
2846 	bufdone(bp->bio_caller2);
2847 }
2848 
2849 /*
2850  *	bufdone:
2851  *
2852  *	Finish I/O on a buffer, optionally calling a completion function.
2853  *	This is usually called from an interrupt so process blocking is
2854  *	not allowed.
2855  *
2856  *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2857  *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
2858  *	assuming B_INVAL is clear.
2859  *
2860  *	For the VMIO case, we set B_CACHE if the op was a read and no
2861  *	read error occured, or if the op was a write.  B_CACHE is never
2862  *	set if the buffer is invalid or otherwise uncacheable.
2863  *
2864  *	biodone does not mess with B_INVAL, allowing the I/O routine or the
2865  *	initiator to leave B_INVAL set to brelse the buffer out of existance
2866  *	in the biodone routine.
2867  */
2868 void
2869 bufdone(struct buf *bp)
2870 {
2871 	int s;
2872 	void    (*biodone)(struct buf *);
2873 
2874 	GIANT_REQUIRED;
2875 
2876 	s = splbio();
2877 
2878 	KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
2879 	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2880 
2881 	bp->b_flags |= B_DONE;
2882 	runningbufwakeup(bp);
2883 
2884 	if (bp->b_iocmd == BIO_DELETE) {
2885 		brelse(bp);
2886 		splx(s);
2887 		return;
2888 	}
2889 
2890 	if (bp->b_iocmd == BIO_WRITE) {
2891 		vwakeup(bp);
2892 	}
2893 
2894 	/* call optional completion function if requested */
2895 	if (bp->b_iodone != NULL) {
2896 		biodone = bp->b_iodone;
2897 		bp->b_iodone = NULL;
2898 		(*biodone) (bp);
2899 		splx(s);
2900 		return;
2901 	}
2902 	if (LIST_FIRST(&bp->b_dep) != NULL)
2903 		buf_complete(bp);
2904 
2905 	if (bp->b_flags & B_VMIO) {
2906 		int i;
2907 		vm_ooffset_t foff;
2908 		vm_page_t m;
2909 		vm_object_t obj;
2910 		int iosize;
2911 		struct vnode *vp = bp->b_vp;
2912 
2913 		obj = bp->b_object;
2914 
2915 #if defined(VFS_BIO_DEBUG)
2916 		if (vp->v_usecount == 0) {
2917 			panic("biodone: zero vnode ref count");
2918 		}
2919 
2920 		if ((vp->v_flag & VOBJBUF) == 0) {
2921 			panic("biodone: vnode is not setup for merged cache");
2922 		}
2923 #endif
2924 
2925 		foff = bp->b_offset;
2926 		KASSERT(bp->b_offset != NOOFFSET,
2927 		    ("biodone: no buffer offset"));
2928 
2929 #if defined(VFS_BIO_DEBUG)
2930 		if (obj->paging_in_progress < bp->b_npages) {
2931 			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
2932 			    obj->paging_in_progress, bp->b_npages);
2933 		}
2934 #endif
2935 
2936 		/*
2937 		 * Set B_CACHE if the op was a normal read and no error
2938 		 * occured.  B_CACHE is set for writes in the b*write()
2939 		 * routines.
2940 		 */
2941 		iosize = bp->b_bcount - bp->b_resid;
2942 		if (bp->b_iocmd == BIO_READ &&
2943 		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
2944 		    !(bp->b_ioflags & BIO_ERROR)) {
2945 			bp->b_flags |= B_CACHE;
2946 		}
2947 
2948 		for (i = 0; i < bp->b_npages; i++) {
2949 			int bogusflag = 0;
2950 			int resid;
2951 
2952 			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2953 			if (resid > iosize)
2954 				resid = iosize;
2955 
2956 			/*
2957 			 * cleanup bogus pages, restoring the originals
2958 			 */
2959 			m = bp->b_pages[i];
2960 			if (m == bogus_page) {
2961 				bogusflag = 1;
2962 				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2963 				if (m == NULL)
2964 					panic("biodone: page disappeared!");
2965 				bp->b_pages[i] = m;
2966 				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2967 			}
2968 #if defined(VFS_BIO_DEBUG)
2969 			if (OFF_TO_IDX(foff) != m->pindex) {
2970 				printf(
2971 "biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
2972 				    (intmax_t)foff, (uintmax_t)m->pindex);
2973 			}
2974 #endif
2975 
2976 			/*
2977 			 * In the write case, the valid and clean bits are
2978 			 * already changed correctly ( see bdwrite() ), so we
2979 			 * only need to do this here in the read case.
2980 			 */
2981 			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
2982 				vfs_page_set_valid(bp, foff, i, m);
2983 			}
2984 			vm_page_flag_clear(m, PG_ZERO);
2985 
2986 			/*
2987 			 * when debugging new filesystems or buffer I/O methods, this
2988 			 * is the most common error that pops up.  if you see this, you
2989 			 * have not set the page busy flag correctly!!!
2990 			 */
2991 			if (m->busy == 0) {
2992 				printf("biodone: page busy < 0, "
2993 				    "pindex: %d, foff: 0x(%x,%x), "
2994 				    "resid: %d, index: %d\n",
2995 				    (int) m->pindex, (int)(foff >> 32),
2996 						(int) foff & 0xffffffff, resid, i);
2997 				if (!vn_isdisk(vp, NULL))
2998 					printf(" iosize: %ld, lblkno: %jd, flags: 0x%lx, npages: %d\n",
2999 					    bp->b_vp->v_mount->mnt_stat.f_iosize,
3000 					    (intmax_t) bp->b_lblkno,
3001 					    bp->b_flags, bp->b_npages);
3002 				else
3003 					printf(" VDEV, lblkno: %jd, flags: 0x%lx, npages: %d\n",
3004 					    (intmax_t) bp->b_lblkno,
3005 					    bp->b_flags, bp->b_npages);
3006 				printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3007 				    m->valid, m->dirty, m->wire_count);
3008 				panic("biodone: page busy < 0\n");
3009 			}
3010 			vm_page_io_finish(m);
3011 			vm_object_pip_subtract(obj, 1);
3012 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3013 			iosize -= resid;
3014 		}
3015 		if (obj)
3016 			vm_object_pip_wakeupn(obj, 0);
3017 	}
3018 
3019 	/*
3020 	 * For asynchronous completions, release the buffer now. The brelse
3021 	 * will do a wakeup there if necessary - so no need to do a wakeup
3022 	 * here in the async case. The sync case always needs to do a wakeup.
3023 	 */
3024 
3025 	if (bp->b_flags & B_ASYNC) {
3026 		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3027 			brelse(bp);
3028 		else
3029 			bqrelse(bp);
3030 	} else {
3031 		wakeup(bp);
3032 	}
3033 	splx(s);
3034 }
3035 
3036 /*
3037  * This routine is called in lieu of iodone in the case of
3038  * incomplete I/O.  This keeps the busy status for pages
3039  * consistant.
3040  */
3041 void
3042 vfs_unbusy_pages(struct buf * bp)
3043 {
3044 	int i;
3045 
3046 	GIANT_REQUIRED;
3047 
3048 	runningbufwakeup(bp);
3049 	if (bp->b_flags & B_VMIO) {
3050 		vm_object_t obj;
3051 
3052 		obj = bp->b_object;
3053 
3054 		for (i = 0; i < bp->b_npages; i++) {
3055 			vm_page_t m = bp->b_pages[i];
3056 
3057 			if (m == bogus_page) {
3058 				m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3059 				if (!m) {
3060 					panic("vfs_unbusy_pages: page missing\n");
3061 				}
3062 				bp->b_pages[i] = m;
3063 				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3064 			}
3065 			vm_object_pip_subtract(obj, 1);
3066 			vm_page_flag_clear(m, PG_ZERO);
3067 			vm_page_io_finish(m);
3068 		}
3069 		vm_object_pip_wakeupn(obj, 0);
3070 	}
3071 }
3072 
3073 /*
3074  * vfs_page_set_valid:
3075  *
3076  *	Set the valid bits in a page based on the supplied offset.   The
3077  *	range is restricted to the buffer's size.
3078  *
3079  *	This routine is typically called after a read completes.
3080  */
3081 static void
3082 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3083 {
3084 	vm_ooffset_t soff, eoff;
3085 
3086 	GIANT_REQUIRED;
3087 	/*
3088 	 * Start and end offsets in buffer.  eoff - soff may not cross a
3089 	 * page boundry or cross the end of the buffer.  The end of the
3090 	 * buffer, in this case, is our file EOF, not the allocation size
3091 	 * of the buffer.
3092 	 */
3093 	soff = off;
3094 	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3095 	if (eoff > bp->b_offset + bp->b_bcount)
3096 		eoff = bp->b_offset + bp->b_bcount;
3097 
3098 	/*
3099 	 * Set valid range.  This is typically the entire buffer and thus the
3100 	 * entire page.
3101 	 */
3102 	if (eoff > soff) {
3103 		vm_page_set_validclean(
3104 		    m,
3105 		   (vm_offset_t) (soff & PAGE_MASK),
3106 		   (vm_offset_t) (eoff - soff)
3107 		);
3108 	}
3109 }
3110 
3111 /*
3112  * This routine is called before a device strategy routine.
3113  * It is used to tell the VM system that paging I/O is in
3114  * progress, and treat the pages associated with the buffer
3115  * almost as being PG_BUSY.  Also the object paging_in_progress
3116  * flag is handled to make sure that the object doesn't become
3117  * inconsistant.
3118  *
3119  * Since I/O has not been initiated yet, certain buffer flags
3120  * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3121  * and should be ignored.
3122  */
3123 void
3124 vfs_busy_pages(struct buf * bp, int clear_modify)
3125 {
3126 	int i, bogus;
3127 
3128 	GIANT_REQUIRED;
3129 
3130 	if (bp->b_flags & B_VMIO) {
3131 		vm_object_t obj;
3132 		vm_ooffset_t foff;
3133 
3134 		obj = bp->b_object;
3135 		foff = bp->b_offset;
3136 		KASSERT(bp->b_offset != NOOFFSET,
3137 		    ("vfs_busy_pages: no buffer offset"));
3138 		vfs_setdirty(bp);
3139 
3140 retry:
3141 		for (i = 0; i < bp->b_npages; i++) {
3142 			vm_page_t m = bp->b_pages[i];
3143 			if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3144 				goto retry;
3145 		}
3146 
3147 		bogus = 0;
3148 		for (i = 0; i < bp->b_npages; i++) {
3149 			vm_page_t m = bp->b_pages[i];
3150 
3151 			vm_page_flag_clear(m, PG_ZERO);
3152 			if ((bp->b_flags & B_CLUSTER) == 0) {
3153 				vm_object_pip_add(obj, 1);
3154 				vm_page_io_start(m);
3155 			}
3156 
3157 			/*
3158 			 * When readying a buffer for a read ( i.e
3159 			 * clear_modify == 0 ), it is important to do
3160 			 * bogus_page replacement for valid pages in
3161 			 * partially instantiated buffers.  Partially
3162 			 * instantiated buffers can, in turn, occur when
3163 			 * reconstituting a buffer from its VM backing store
3164 			 * base.  We only have to do this if B_CACHE is
3165 			 * clear ( which causes the I/O to occur in the
3166 			 * first place ).  The replacement prevents the read
3167 			 * I/O from overwriting potentially dirty VM-backed
3168 			 * pages.  XXX bogus page replacement is, uh, bogus.
3169 			 * It may not work properly with small-block devices.
3170 			 * We need to find a better way.
3171 			 */
3172 
3173 			vm_page_protect(m, VM_PROT_NONE);
3174 			if (clear_modify)
3175 				vfs_page_set_valid(bp, foff, i, m);
3176 			else if (m->valid == VM_PAGE_BITS_ALL &&
3177 				(bp->b_flags & B_CACHE) == 0) {
3178 				bp->b_pages[i] = bogus_page;
3179 				bogus++;
3180 			}
3181 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3182 		}
3183 		if (bogus)
3184 			pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3185 	}
3186 }
3187 
3188 /*
3189  * Tell the VM system that the pages associated with this buffer
3190  * are clean.  This is used for delayed writes where the data is
3191  * going to go to disk eventually without additional VM intevention.
3192  *
3193  * Note that while we only really need to clean through to b_bcount, we
3194  * just go ahead and clean through to b_bufsize.
3195  */
3196 static void
3197 vfs_clean_pages(struct buf * bp)
3198 {
3199 	int i;
3200 
3201 	GIANT_REQUIRED;
3202 
3203 	if (bp->b_flags & B_VMIO) {
3204 		vm_ooffset_t foff;
3205 
3206 		foff = bp->b_offset;
3207 		KASSERT(bp->b_offset != NOOFFSET,
3208 		    ("vfs_clean_pages: no buffer offset"));
3209 		for (i = 0; i < bp->b_npages; i++) {
3210 			vm_page_t m = bp->b_pages[i];
3211 			vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3212 			vm_ooffset_t eoff = noff;
3213 
3214 			if (eoff > bp->b_offset + bp->b_bufsize)
3215 				eoff = bp->b_offset + bp->b_bufsize;
3216 			vfs_page_set_valid(bp, foff, i, m);
3217 			/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3218 			foff = noff;
3219 		}
3220 	}
3221 }
3222 
3223 /*
3224  *	vfs_bio_set_validclean:
3225  *
3226  *	Set the range within the buffer to valid and clean.  The range is
3227  *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3228  *	itself may be offset from the beginning of the first page.
3229  *
3230  */
3231 
3232 void
3233 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3234 {
3235 	if (bp->b_flags & B_VMIO) {
3236 		int i;
3237 		int n;
3238 
3239 		/*
3240 		 * Fixup base to be relative to beginning of first page.
3241 		 * Set initial n to be the maximum number of bytes in the
3242 		 * first page that can be validated.
3243 		 */
3244 
3245 		base += (bp->b_offset & PAGE_MASK);
3246 		n = PAGE_SIZE - (base & PAGE_MASK);
3247 
3248 		for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3249 			vm_page_t m = bp->b_pages[i];
3250 
3251 			if (n > size)
3252 				n = size;
3253 
3254 			vm_page_set_validclean(m, base & PAGE_MASK, n);
3255 			base += n;
3256 			size -= n;
3257 			n = PAGE_SIZE;
3258 		}
3259 	}
3260 }
3261 
3262 /*
3263  *	vfs_bio_clrbuf:
3264  *
3265  *	clear a buffer.  This routine essentially fakes an I/O, so we need
3266  *	to clear BIO_ERROR and B_INVAL.
3267  *
3268  *	Note that while we only theoretically need to clear through b_bcount,
3269  *	we go ahead and clear through b_bufsize.
3270  */
3271 
3272 void
3273 vfs_bio_clrbuf(struct buf *bp)
3274 {
3275 	int i, mask = 0;
3276 	caddr_t sa, ea;
3277 
3278 	GIANT_REQUIRED;
3279 
3280 	if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3281 		bp->b_flags &= ~B_INVAL;
3282 		bp->b_ioflags &= ~BIO_ERROR;
3283 		if( (bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3284 		    (bp->b_offset & PAGE_MASK) == 0) {
3285 			mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3286 			if ((bp->b_pages[0]->valid & mask) == mask) {
3287 				bp->b_resid = 0;
3288 				return;
3289 			}
3290 			if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3291 			    ((bp->b_pages[0]->valid & mask) == 0)) {
3292 				bzero(bp->b_data, bp->b_bufsize);
3293 				bp->b_pages[0]->valid |= mask;
3294 				bp->b_resid = 0;
3295 				return;
3296 			}
3297 		}
3298 		ea = sa = bp->b_data;
3299 		for(i=0;i<bp->b_npages;i++,sa=ea) {
3300 			int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3301 			ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3302 			ea = (caddr_t)(vm_offset_t)ulmin(
3303 			    (u_long)(vm_offset_t)ea,
3304 			    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3305 			mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3306 			if ((bp->b_pages[i]->valid & mask) == mask)
3307 				continue;
3308 			if ((bp->b_pages[i]->valid & mask) == 0) {
3309 				if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
3310 					bzero(sa, ea - sa);
3311 				}
3312 			} else {
3313 				for (; sa < ea; sa += DEV_BSIZE, j++) {
3314 					if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3315 						(bp->b_pages[i]->valid & (1<<j)) == 0)
3316 						bzero(sa, DEV_BSIZE);
3317 				}
3318 			}
3319 			bp->b_pages[i]->valid |= mask;
3320 			vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3321 		}
3322 		bp->b_resid = 0;
3323 	} else {
3324 		clrbuf(bp);
3325 	}
3326 }
3327 
3328 /*
3329  * vm_hold_load_pages and vm_hold_free_pages get pages into
3330  * a buffers address space.  The pages are anonymous and are
3331  * not associated with a file object.
3332  */
3333 static void
3334 vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3335 {
3336 	vm_offset_t pg;
3337 	vm_page_t p;
3338 	int index;
3339 
3340 	GIANT_REQUIRED;
3341 
3342 	to = round_page(to);
3343 	from = round_page(from);
3344 	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3345 
3346 	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3347 tryagain:
3348 		/*
3349 		 * note: must allocate system pages since blocking here
3350 		 * could intefere with paging I/O, no matter which
3351 		 * process we are.
3352 		 */
3353 		p = vm_page_alloc(kernel_object,
3354 			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3355 		    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3356 		if (!p) {
3357 			vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3358 			VM_WAIT;
3359 			goto tryagain;
3360 		}
3361 		vm_page_lock_queues();
3362 		p->valid = VM_PAGE_BITS_ALL;
3363 		vm_page_flag_clear(p, PG_ZERO);
3364 		vm_page_unlock_queues();
3365 		pmap_qenter(pg, &p, 1);
3366 		bp->b_pages[index] = p;
3367 		vm_page_wakeup(p);
3368 	}
3369 	bp->b_npages = index;
3370 }
3371 
3372 /* Return pages associated with this buf to the vm system */
3373 void
3374 vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3375 {
3376 	vm_offset_t pg;
3377 	vm_page_t p;
3378 	int index, newnpages;
3379 
3380 	GIANT_REQUIRED;
3381 
3382 	from = round_page(from);
3383 	to = round_page(to);
3384 	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3385 
3386 	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3387 		p = bp->b_pages[index];
3388 		if (p && (index < bp->b_npages)) {
3389 			if (p->busy) {
3390 				printf(
3391 			    "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3392 				    (intmax_t)bp->b_blkno,
3393 				    (intmax_t)bp->b_lblkno);
3394 			}
3395 			bp->b_pages[index] = NULL;
3396 			pmap_qremove(pg, 1);
3397 			vm_page_lock_queues();
3398 			vm_page_busy(p);
3399 			vm_page_unwire(p, 0);
3400 			vm_page_free(p);
3401 			vm_page_unlock_queues();
3402 		}
3403 	}
3404 	bp->b_npages = newnpages;
3405 }
3406 
3407 
3408 #include "opt_ddb.h"
3409 #ifdef DDB
3410 #include <ddb/ddb.h>
3411 
3412 /* DDB command to show buffer data */
3413 DB_SHOW_COMMAND(buffer, db_show_buffer)
3414 {
3415 	/* get args */
3416 	struct buf *bp = (struct buf *)addr;
3417 
3418 	if (!have_addr) {
3419 		db_printf("usage: show buffer <addr>\n");
3420 		return;
3421 	}
3422 
3423 	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3424 	db_printf(
3425 	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
3426 	    "b_dev = (%d,%d), b_data = %p, b_blkno = %jd, b_pblkno = %jd\n",
3427 	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3428 	    major(bp->b_dev), minor(bp->b_dev), bp->b_data,
3429 	    (intmax_t)bp->b_blkno, (intmax_t)bp->b_pblkno);
3430 	if (bp->b_npages) {
3431 		int i;
3432 		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3433 		for (i = 0; i < bp->b_npages; i++) {
3434 			vm_page_t m;
3435 			m = bp->b_pages[i];
3436 			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3437 			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3438 			if ((i + 1) < bp->b_npages)
3439 				db_printf(",");
3440 		}
3441 		db_printf("\n");
3442 	}
3443 }
3444 #endif /* DDB */
3445