vfs_bio.c revision 101174
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: head/sys/kern/vfs_bio.c 101174 2002-08-01 17:57:42Z alc $
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
58static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
59
60struct	bio_ops bioops;		/* I/O operation notification */
61
62struct	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 */
71struct buf *buf;		/* buffer header pool */
72struct mtx buftimelock;		/* Interlock on setting prio and timo */
73
74static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
75		vm_offset_t to);
76static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
77		vm_offset_t to);
78static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
79			       int pageno, vm_page_t m);
80static void vfs_clean_pages(struct buf * bp);
81static void vfs_setdirty(struct buf *bp);
82static void vfs_vmio_release(struct buf *bp);
83static void vfs_backgroundwritedone(struct buf *bp);
84static int flushbufqueues(void);
85static void buf_daemon(void);
86
87int vmiodirenable = TRUE;
88SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
89    "Use the VM system for directory writes");
90int runningbufspace;
91SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
92    "Amount of presently outstanding async buffer io");
93static int bufspace;
94SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
95    "KVA memory used for bufs");
96static int maxbufspace;
97SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
98    "Maximum allowed value of bufspace (including buf_daemon)");
99static int bufmallocspace;
100SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
101    "Amount of malloced memory for buffers");
102static int maxbufmallocspace;
103SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
104    "Maximum amount of malloced memory for buffers");
105static int lobufspace;
106SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
107    "Minimum amount of buffers we want to have");
108static int hibufspace;
109SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
110    "Maximum allowed value of bufspace (excluding buf_daemon)");
111static int bufreusecnt;
112SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
113    "Number of times we have reused a buffer");
114static int buffreekvacnt;
115SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
116    "Number of times we have freed the KVA space from some buffer");
117static int bufdefragcnt;
118SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
119    "Number of times we have had to repeat buffer allocation to defragment");
120static int lorunningspace;
121SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
122    "Minimum preferred space used for in-progress I/O");
123static int hirunningspace;
124SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
125    "Maximum amount of space to use for in-progress I/O");
126static int numdirtybuffers;
127SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
128    "Number of buffers that are dirty (has unwritten changes) at the moment");
129static int lodirtybuffers;
130SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
131    "How many buffers we want to have free before bufdaemon can sleep");
132static int hidirtybuffers;
133SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
134    "When the number of dirty buffers is considered severe");
135static int numfreebuffers;
136SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
137    "Number of free buffers");
138static int lofreebuffers;
139SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
140   "XXX Unused");
141static int hifreebuffers;
142SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
143   "XXX Complicatedly unused");
144static int getnewbufcalls;
145SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
146   "Number of calls to getnewbuf");
147static int getnewbufrestarts;
148SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
149    "Number of times getnewbuf has had to restart a buffer aquisition");
150static int dobkgrdwrite = 1;
151SYSCTL_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 */
159static 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 */
168vm_page_t bogus_page;
169
170/*
171 * Offset for bogus_page.
172 * XXX bogus_offset should be local to bufinit
173 */
174static 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 */
181static 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 */
190static 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 */
197static 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 */
203static 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 */
210static 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 */
227static 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 */
232const 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
245static __inline
246struct bufhashhdr *
247bufhash(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
261static __inline void
262numdirtywakeup(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
281static __inline void
282bufspacewakeup(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 */
299static __inline void
300runningbufwakeup(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
321static __inline void
322bufcountwakeup(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 */
348static __inline void
349waitrunningbufspace(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 */
369static __inline__
370void
371vfs_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 */
385static __inline__
386void
387bd_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
399static __inline__
400void
401bd_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 */
412caddr_t
413kern_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. */
486void
487bufinit(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 */
602static void
603bfreekva(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 */
624void
625bremfree(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 */
668int
669bread(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 */
682int
683breadn(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
747int
748bwrite(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 */
880static void
881vfs_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 */
941void
942bdwrite(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 */
1021void
1022bdirty(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
1050void
1051bundirty(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 */
1078void
1079bawrite(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
1095void
1096bwillwrite(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 */
1116int
1117buf_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 */
1129void
1130brelse(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 */
1409void
1410bqrelse(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) */
1468static void
1469vfs_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 */
1531struct buf *
1532gbincore(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 */
1559int
1560vfs_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
1662static struct buf *
1663getnewbuf(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;
1682restart:
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
1954static struct proc *bufdaemonproc;
1955
1956static struct kproc_desc buf_kp = {
1957	"bufdaemon",
1958	buf_daemon,
1959	&bufdaemonproc
1960};
1961SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1962
1963static void
1964buf_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
2036static int
2037flushbufqueues(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 */
2079struct buf *
2080incore(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
2096int
2097inmem(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
2131notinmem:
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 */
2146static void
2147vfs_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 */
2264struct buf *
2265getblk(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();
2277loop:
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 */
2490struct buf *
2491geteblk(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
2524int
2525allocbuf(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 */
2815int
2816bufwait(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  */
2843void
2844bufdonebio(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 */
2868void
2869bufdone(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		vm_page_lock_queues();
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		vm_page_unlock_queues();
3016		if (obj)
3017			vm_object_pip_wakeupn(obj, 0);
3018	}
3019
3020	/*
3021	 * For asynchronous completions, release the buffer now. The brelse
3022	 * will do a wakeup there if necessary - so no need to do a wakeup
3023	 * here in the async case. The sync case always needs to do a wakeup.
3024	 */
3025
3026	if (bp->b_flags & B_ASYNC) {
3027		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3028			brelse(bp);
3029		else
3030			bqrelse(bp);
3031	} else {
3032		wakeup(bp);
3033	}
3034	splx(s);
3035}
3036
3037/*
3038 * This routine is called in lieu of iodone in the case of
3039 * incomplete I/O.  This keeps the busy status for pages
3040 * consistant.
3041 */
3042void
3043vfs_unbusy_pages(struct buf * bp)
3044{
3045	int i;
3046
3047	GIANT_REQUIRED;
3048
3049	runningbufwakeup(bp);
3050	if (bp->b_flags & B_VMIO) {
3051		vm_object_t obj;
3052
3053		obj = bp->b_object;
3054		vm_page_lock_queues();
3055		for (i = 0; i < bp->b_npages; i++) {
3056			vm_page_t m = bp->b_pages[i];
3057
3058			if (m == bogus_page) {
3059				m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3060				if (!m) {
3061					panic("vfs_unbusy_pages: page missing\n");
3062				}
3063				bp->b_pages[i] = m;
3064				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3065			}
3066			vm_object_pip_subtract(obj, 1);
3067			vm_page_flag_clear(m, PG_ZERO);
3068			vm_page_io_finish(m);
3069		}
3070		vm_page_unlock_queues();
3071		vm_object_pip_wakeupn(obj, 0);
3072	}
3073}
3074
3075/*
3076 * vfs_page_set_valid:
3077 *
3078 *	Set the valid bits in a page based on the supplied offset.   The
3079 *	range is restricted to the buffer's size.
3080 *
3081 *	This routine is typically called after a read completes.
3082 */
3083static void
3084vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3085{
3086	vm_ooffset_t soff, eoff;
3087
3088	GIANT_REQUIRED;
3089	/*
3090	 * Start and end offsets in buffer.  eoff - soff may not cross a
3091	 * page boundry or cross the end of the buffer.  The end of the
3092	 * buffer, in this case, is our file EOF, not the allocation size
3093	 * of the buffer.
3094	 */
3095	soff = off;
3096	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3097	if (eoff > bp->b_offset + bp->b_bcount)
3098		eoff = bp->b_offset + bp->b_bcount;
3099
3100	/*
3101	 * Set valid range.  This is typically the entire buffer and thus the
3102	 * entire page.
3103	 */
3104	if (eoff > soff) {
3105		vm_page_set_validclean(
3106		    m,
3107		   (vm_offset_t) (soff & PAGE_MASK),
3108		   (vm_offset_t) (eoff - soff)
3109		);
3110	}
3111}
3112
3113/*
3114 * This routine is called before a device strategy routine.
3115 * It is used to tell the VM system that paging I/O is in
3116 * progress, and treat the pages associated with the buffer
3117 * almost as being PG_BUSY.  Also the object paging_in_progress
3118 * flag is handled to make sure that the object doesn't become
3119 * inconsistant.
3120 *
3121 * Since I/O has not been initiated yet, certain buffer flags
3122 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3123 * and should be ignored.
3124 */
3125void
3126vfs_busy_pages(struct buf * bp, int clear_modify)
3127{
3128	int i, bogus;
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);
3139retry:
3140		vm_page_lock_queues();
3141		for (i = 0; i < bp->b_npages; i++) {
3142			vm_page_t m = bp->b_pages[i];
3143
3144			if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3145				goto retry;
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			 * When readying a buffer for a read ( i.e
3158			 * clear_modify == 0 ), it is important to do
3159			 * bogus_page replacement for valid pages in
3160			 * partially instantiated buffers.  Partially
3161			 * instantiated buffers can, in turn, occur when
3162			 * reconstituting a buffer from its VM backing store
3163			 * base.  We only have to do this if B_CACHE is
3164			 * clear ( which causes the I/O to occur in the
3165			 * first place ).  The replacement prevents the read
3166			 * I/O from overwriting potentially dirty VM-backed
3167			 * pages.  XXX bogus page replacement is, uh, bogus.
3168			 * It may not work properly with small-block devices.
3169			 * We need to find a better way.
3170			 */
3171			vm_page_protect(m, VM_PROT_NONE);
3172			if (clear_modify)
3173				vfs_page_set_valid(bp, foff, i, m);
3174			else if (m->valid == VM_PAGE_BITS_ALL &&
3175				(bp->b_flags & B_CACHE) == 0) {
3176				bp->b_pages[i] = bogus_page;
3177				bogus++;
3178			}
3179			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3180		}
3181		vm_page_unlock_queues();
3182		if (bogus)
3183			pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3184	}
3185}
3186
3187/*
3188 * Tell the VM system that the pages associated with this buffer
3189 * are clean.  This is used for delayed writes where the data is
3190 * going to go to disk eventually without additional VM intevention.
3191 *
3192 * Note that while we only really need to clean through to b_bcount, we
3193 * just go ahead and clean through to b_bufsize.
3194 */
3195static void
3196vfs_clean_pages(struct buf * bp)
3197{
3198	int i;
3199
3200	GIANT_REQUIRED;
3201
3202	if (bp->b_flags & B_VMIO) {
3203		vm_ooffset_t foff;
3204
3205		foff = bp->b_offset;
3206		KASSERT(bp->b_offset != NOOFFSET,
3207		    ("vfs_clean_pages: no buffer offset"));
3208		for (i = 0; i < bp->b_npages; i++) {
3209			vm_page_t m = bp->b_pages[i];
3210			vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3211			vm_ooffset_t eoff = noff;
3212
3213			if (eoff > bp->b_offset + bp->b_bufsize)
3214				eoff = bp->b_offset + bp->b_bufsize;
3215			vfs_page_set_valid(bp, foff, i, m);
3216			/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3217			foff = noff;
3218		}
3219	}
3220}
3221
3222/*
3223 *	vfs_bio_set_validclean:
3224 *
3225 *	Set the range within the buffer to valid and clean.  The range is
3226 *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3227 *	itself may be offset from the beginning of the first page.
3228 *
3229 */
3230
3231void
3232vfs_bio_set_validclean(struct buf *bp, int base, int size)
3233{
3234	if (bp->b_flags & B_VMIO) {
3235		int i;
3236		int n;
3237
3238		/*
3239		 * Fixup base to be relative to beginning of first page.
3240		 * Set initial n to be the maximum number of bytes in the
3241		 * first page that can be validated.
3242		 */
3243
3244		base += (bp->b_offset & PAGE_MASK);
3245		n = PAGE_SIZE - (base & PAGE_MASK);
3246
3247		for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3248			vm_page_t m = bp->b_pages[i];
3249
3250			if (n > size)
3251				n = size;
3252
3253			vm_page_set_validclean(m, base & PAGE_MASK, n);
3254			base += n;
3255			size -= n;
3256			n = PAGE_SIZE;
3257		}
3258	}
3259}
3260
3261/*
3262 *	vfs_bio_clrbuf:
3263 *
3264 *	clear a buffer.  This routine essentially fakes an I/O, so we need
3265 *	to clear BIO_ERROR and B_INVAL.
3266 *
3267 *	Note that while we only theoretically need to clear through b_bcount,
3268 *	we go ahead and clear through b_bufsize.
3269 */
3270
3271void
3272vfs_bio_clrbuf(struct buf *bp)
3273{
3274	int i, mask = 0;
3275	caddr_t sa, ea;
3276
3277	GIANT_REQUIRED;
3278
3279	if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3280		bp->b_flags &= ~B_INVAL;
3281		bp->b_ioflags &= ~BIO_ERROR;
3282		if( (bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3283		    (bp->b_offset & PAGE_MASK) == 0) {
3284			mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3285			if ((bp->b_pages[0]->valid & mask) == mask) {
3286				bp->b_resid = 0;
3287				return;
3288			}
3289			if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3290			    ((bp->b_pages[0]->valid & mask) == 0)) {
3291				bzero(bp->b_data, bp->b_bufsize);
3292				bp->b_pages[0]->valid |= mask;
3293				bp->b_resid = 0;
3294				return;
3295			}
3296		}
3297		ea = sa = bp->b_data;
3298		for(i=0;i<bp->b_npages;i++,sa=ea) {
3299			int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3300			ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3301			ea = (caddr_t)(vm_offset_t)ulmin(
3302			    (u_long)(vm_offset_t)ea,
3303			    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3304			mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3305			if ((bp->b_pages[i]->valid & mask) == mask)
3306				continue;
3307			if ((bp->b_pages[i]->valid & mask) == 0) {
3308				if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
3309					bzero(sa, ea - sa);
3310				}
3311			} else {
3312				for (; sa < ea; sa += DEV_BSIZE, j++) {
3313					if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3314						(bp->b_pages[i]->valid & (1<<j)) == 0)
3315						bzero(sa, DEV_BSIZE);
3316				}
3317			}
3318			bp->b_pages[i]->valid |= mask;
3319			vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3320		}
3321		bp->b_resid = 0;
3322	} else {
3323		clrbuf(bp);
3324	}
3325}
3326
3327/*
3328 * vm_hold_load_pages and vm_hold_free_pages get pages into
3329 * a buffers address space.  The pages are anonymous and are
3330 * not associated with a file object.
3331 */
3332static void
3333vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3334{
3335	vm_offset_t pg;
3336	vm_page_t p;
3337	int index;
3338
3339	GIANT_REQUIRED;
3340
3341	to = round_page(to);
3342	from = round_page(from);
3343	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3344
3345	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3346tryagain:
3347		/*
3348		 * note: must allocate system pages since blocking here
3349		 * could intefere with paging I/O, no matter which
3350		 * process we are.
3351		 */
3352		p = vm_page_alloc(kernel_object,
3353			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3354		    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3355		if (!p) {
3356			vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3357			VM_WAIT;
3358			goto tryagain;
3359		}
3360		vm_page_lock_queues();
3361		p->valid = VM_PAGE_BITS_ALL;
3362		vm_page_flag_clear(p, PG_ZERO);
3363		vm_page_unlock_queues();
3364		pmap_qenter(pg, &p, 1);
3365		bp->b_pages[index] = p;
3366		vm_page_wakeup(p);
3367	}
3368	bp->b_npages = index;
3369}
3370
3371/* Return pages associated with this buf to the vm system */
3372void
3373vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3374{
3375	vm_offset_t pg;
3376	vm_page_t p;
3377	int index, newnpages;
3378
3379	GIANT_REQUIRED;
3380
3381	from = round_page(from);
3382	to = round_page(to);
3383	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3384
3385	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3386		p = bp->b_pages[index];
3387		if (p && (index < bp->b_npages)) {
3388			if (p->busy) {
3389				printf(
3390			    "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3391				    (intmax_t)bp->b_blkno,
3392				    (intmax_t)bp->b_lblkno);
3393			}
3394			bp->b_pages[index] = NULL;
3395			pmap_qremove(pg, 1);
3396			vm_page_lock_queues();
3397			vm_page_busy(p);
3398			vm_page_unwire(p, 0);
3399			vm_page_free(p);
3400			vm_page_unlock_queues();
3401		}
3402	}
3403	bp->b_npages = newnpages;
3404}
3405
3406
3407#include "opt_ddb.h"
3408#ifdef DDB
3409#include <ddb/ddb.h>
3410
3411/* DDB command to show buffer data */
3412DB_SHOW_COMMAND(buffer, db_show_buffer)
3413{
3414	/* get args */
3415	struct buf *bp = (struct buf *)addr;
3416
3417	if (!have_addr) {
3418		db_printf("usage: show buffer <addr>\n");
3419		return;
3420	}
3421
3422	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3423	db_printf(
3424	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
3425	    "b_dev = (%d,%d), b_data = %p, b_blkno = %jd, b_pblkno = %jd\n",
3426	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3427	    major(bp->b_dev), minor(bp->b_dev), bp->b_data,
3428	    (intmax_t)bp->b_blkno, (intmax_t)bp->b_pblkno);
3429	if (bp->b_npages) {
3430		int i;
3431		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3432		for (i = 0; i < bp->b_npages; i++) {
3433			vm_page_t m;
3434			m = bp->b_pages[i];
3435			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3436			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3437			if ((i + 1) < bp->b_npages)
3438				db_printf(",");
3439		}
3440		db_printf("\n");
3441	}
3442}
3443#endif /* DDB */
3444