vfs_bio.c revision 103314
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 103314 2002-09-14 09:02:28Z njl $
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, long 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_mount != NULL &&
1215		 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1216		 !vn_isdisk(bp->b_vp, NULL) &&
1217		 (bp->b_flags & B_DELWRI))
1218	    ) {
1219
1220		int i, j, resid;
1221		vm_page_t m;
1222		off_t foff;
1223		vm_pindex_t poff;
1224		vm_object_t obj;
1225		struct vnode *vp;
1226
1227		vp = bp->b_vp;
1228		obj = bp->b_object;
1229
1230		/*
1231		 * Get the base offset and length of the buffer.  Note that
1232		 * in the VMIO case if the buffer block size is not
1233		 * page-aligned then b_data pointer may not be page-aligned.
1234		 * But our b_pages[] array *IS* page aligned.
1235		 *
1236		 * block sizes less then DEV_BSIZE (usually 512) are not
1237		 * supported due to the page granularity bits (m->valid,
1238		 * m->dirty, etc...).
1239		 *
1240		 * See man buf(9) for more information
1241		 */
1242		resid = bp->b_bufsize;
1243		foff = bp->b_offset;
1244
1245		for (i = 0; i < bp->b_npages; i++) {
1246			int had_bogus = 0;
1247
1248			m = bp->b_pages[i];
1249			vm_page_flag_clear(m, PG_ZERO);
1250
1251			/*
1252			 * If we hit a bogus page, fixup *all* the bogus pages
1253			 * now.
1254			 */
1255			if (m == bogus_page) {
1256				poff = OFF_TO_IDX(bp->b_offset);
1257				had_bogus = 1;
1258
1259				for (j = i; j < bp->b_npages; j++) {
1260					vm_page_t mtmp;
1261					mtmp = bp->b_pages[j];
1262					if (mtmp == bogus_page) {
1263						mtmp = vm_page_lookup(obj, poff + j);
1264						if (!mtmp) {
1265							panic("brelse: page missing\n");
1266						}
1267						bp->b_pages[j] = mtmp;
1268					}
1269				}
1270
1271				if ((bp->b_flags & B_INVAL) == 0) {
1272					pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
1273				}
1274				m = bp->b_pages[i];
1275			}
1276			if ((bp->b_flags & B_NOCACHE) || (bp->b_ioflags & BIO_ERROR)) {
1277				int poffset = foff & PAGE_MASK;
1278				int presid = resid > (PAGE_SIZE - poffset) ?
1279					(PAGE_SIZE - poffset) : resid;
1280
1281				KASSERT(presid >= 0, ("brelse: extra page"));
1282				vm_page_set_invalid(m, poffset, presid);
1283				if (had_bogus)
1284					printf("avoided corruption bug in bogus_page/brelse code\n");
1285			}
1286			resid -= PAGE_SIZE - (foff & PAGE_MASK);
1287			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1288		}
1289
1290		if (bp->b_flags & (B_INVAL | B_RELBUF))
1291			vfs_vmio_release(bp);
1292
1293	} else if (bp->b_flags & B_VMIO) {
1294
1295		if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1296			vfs_vmio_release(bp);
1297		}
1298
1299	}
1300
1301	if (bp->b_qindex != QUEUE_NONE)
1302		panic("brelse: free buffer onto another queue???");
1303	if (BUF_REFCNT(bp) > 1) {
1304		/* do not release to free list */
1305		BUF_UNLOCK(bp);
1306		splx(s);
1307		return;
1308	}
1309
1310	/* enqueue */
1311
1312	/* buffers with no memory */
1313	if (bp->b_bufsize == 0) {
1314		bp->b_flags |= B_INVAL;
1315		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1316		if (bp->b_xflags & BX_BKGRDINPROG)
1317			panic("losing buffer 1");
1318		if (bp->b_kvasize) {
1319			bp->b_qindex = QUEUE_EMPTYKVA;
1320		} else {
1321			bp->b_qindex = QUEUE_EMPTY;
1322		}
1323		TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1324#ifdef USE_BUFHASH
1325		LIST_REMOVE(bp, b_hash);
1326		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1327#endif
1328		bp->b_dev = NODEV;
1329	/* buffers with junk contents */
1330	} else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1331	    (bp->b_ioflags & BIO_ERROR)) {
1332		bp->b_flags |= B_INVAL;
1333		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1334		if (bp->b_xflags & BX_BKGRDINPROG)
1335			panic("losing buffer 2");
1336		bp->b_qindex = QUEUE_CLEAN;
1337		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1338#ifdef USE_BUFHASH
1339		LIST_REMOVE(bp, b_hash);
1340		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1341#endif
1342		bp->b_dev = NODEV;
1343
1344	/* buffers that are locked */
1345	} else if (bp->b_flags & B_LOCKED) {
1346		bp->b_qindex = QUEUE_LOCKED;
1347		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1348
1349	/* remaining buffers */
1350	} else {
1351		if (bp->b_flags & B_DELWRI)
1352			bp->b_qindex = QUEUE_DIRTY;
1353		else
1354			bp->b_qindex = QUEUE_CLEAN;
1355		if (bp->b_flags & B_AGE)
1356			TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1357		else
1358			TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1359	}
1360
1361	/*
1362	 * If B_INVAL and B_DELWRI is set, clear B_DELWRI.  We have already
1363	 * placed the buffer on the correct queue.  We must also disassociate
1364	 * the device and vnode for a B_INVAL buffer so gbincore() doesn't
1365	 * find it.
1366	 */
1367	if (bp->b_flags & B_INVAL) {
1368		if (bp->b_flags & B_DELWRI)
1369			bundirty(bp);
1370		if (bp->b_vp)
1371			brelvp(bp);
1372	}
1373
1374	/*
1375	 * Fixup numfreebuffers count.  The bp is on an appropriate queue
1376	 * unless locked.  We then bump numfreebuffers if it is not B_DELWRI.
1377	 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1378	 * if B_INVAL is set ).
1379	 */
1380
1381	if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1382		bufcountwakeup();
1383
1384	/*
1385	 * Something we can maybe free or reuse
1386	 */
1387	if (bp->b_bufsize || bp->b_kvasize)
1388		bufspacewakeup();
1389
1390	/* unlock */
1391	BUF_UNLOCK(bp);
1392	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1393			B_DIRECT | B_NOWDRAIN);
1394	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1395		panic("brelse: not dirty");
1396	splx(s);
1397}
1398
1399/*
1400 * Release a buffer back to the appropriate queue but do not try to free
1401 * it.  The buffer is expected to be used again soon.
1402 *
1403 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1404 * biodone() to requeue an async I/O on completion.  It is also used when
1405 * known good buffers need to be requeued but we think we may need the data
1406 * again soon.
1407 *
1408 * XXX we should be able to leave the B_RELBUF hint set on completion.
1409 */
1410void
1411bqrelse(struct buf * bp)
1412{
1413	int s;
1414
1415	s = splbio();
1416
1417	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1418
1419	if (bp->b_qindex != QUEUE_NONE)
1420		panic("bqrelse: free buffer onto another queue???");
1421	if (BUF_REFCNT(bp) > 1) {
1422		/* do not release to free list */
1423		BUF_UNLOCK(bp);
1424		splx(s);
1425		return;
1426	}
1427	if (bp->b_flags & B_LOCKED) {
1428		bp->b_ioflags &= ~BIO_ERROR;
1429		bp->b_qindex = QUEUE_LOCKED;
1430		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1431		/* buffers with stale but valid contents */
1432	} else if (bp->b_flags & B_DELWRI) {
1433		bp->b_qindex = QUEUE_DIRTY;
1434		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1435	} else if (vm_page_count_severe()) {
1436		/*
1437		 * We are too low on memory, we have to try to free the
1438		 * buffer (most importantly: the wired pages making up its
1439		 * backing store) *now*.
1440		 */
1441		splx(s);
1442		brelse(bp);
1443		return;
1444	} else {
1445		bp->b_qindex = QUEUE_CLEAN;
1446		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1447	}
1448
1449	if ((bp->b_flags & B_LOCKED) == 0 &&
1450	    ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1451		bufcountwakeup();
1452	}
1453
1454	/*
1455	 * Something we can maybe free or reuse.
1456	 */
1457	if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1458		bufspacewakeup();
1459
1460	/* unlock */
1461	BUF_UNLOCK(bp);
1462	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1463	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1464		panic("bqrelse: not dirty");
1465	splx(s);
1466}
1467
1468/* Give pages used by the bp back to the VM system (where possible) */
1469static void
1470vfs_vmio_release(bp)
1471	struct buf *bp;
1472{
1473	int i;
1474	vm_page_t m;
1475
1476	GIANT_REQUIRED;
1477	vm_page_lock_queues();
1478	for (i = 0; i < bp->b_npages; i++) {
1479		m = bp->b_pages[i];
1480		bp->b_pages[i] = NULL;
1481		/*
1482		 * In order to keep page LRU ordering consistent, put
1483		 * everything on the inactive queue.
1484		 */
1485		vm_page_unwire(m, 0);
1486		/*
1487		 * We don't mess with busy pages, it is
1488		 * the responsibility of the process that
1489		 * busied the pages to deal with them.
1490		 */
1491		if ((m->flags & PG_BUSY) || (m->busy != 0))
1492			continue;
1493
1494		if (m->wire_count == 0) {
1495			vm_page_flag_clear(m, PG_ZERO);
1496			/*
1497			 * Might as well free the page if we can and it has
1498			 * no valid data.  We also free the page if the
1499			 * buffer was used for direct I/O
1500			 */
1501			if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1502			    m->hold_count == 0) {
1503				vm_page_busy(m);
1504				vm_page_protect(m, VM_PROT_NONE);
1505				vm_page_free(m);
1506			} else if (bp->b_flags & B_DIRECT) {
1507				vm_page_try_to_free(m);
1508			} else if (vm_page_count_severe()) {
1509				vm_page_try_to_cache(m);
1510			}
1511		}
1512	}
1513	vm_page_unlock_queues();
1514	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1515
1516	if (bp->b_bufsize) {
1517		bufspacewakeup();
1518		bp->b_bufsize = 0;
1519	}
1520	bp->b_npages = 0;
1521	bp->b_flags &= ~B_VMIO;
1522	if (bp->b_vp)
1523		brelvp(bp);
1524}
1525
1526#ifdef USE_BUFHASH
1527/*
1528 * XXX MOVED TO VFS_SUBR.C
1529 *
1530 * Check to see if a block is currently memory resident.
1531 */
1532struct buf *
1533gbincore(struct vnode * vp, daddr_t blkno)
1534{
1535	struct buf *bp;
1536	struct bufhashhdr *bh;
1537
1538	bh = bufhash(vp, blkno);
1539
1540	/* Search hash chain */
1541	LIST_FOREACH(bp, bh, b_hash) {
1542		/* hit */
1543		if (bp->b_vp == vp && bp->b_lblkno == blkno &&
1544		    (bp->b_flags & B_INVAL) == 0) {
1545			break;
1546		}
1547	}
1548	return (bp);
1549}
1550#endif
1551
1552/*
1553 *	vfs_bio_awrite:
1554 *
1555 *	Implement clustered async writes for clearing out B_DELWRI buffers.
1556 *	This is much better then the old way of writing only one buffer at
1557 *	a time.  Note that we may not be presented with the buffers in the
1558 *	correct order, so we search for the cluster in both directions.
1559 */
1560int
1561vfs_bio_awrite(struct buf * bp)
1562{
1563	int i;
1564	int j;
1565	daddr_t lblkno = bp->b_lblkno;
1566	struct vnode *vp = bp->b_vp;
1567	int s;
1568	int ncl;
1569	struct buf *bpa;
1570	int nwritten;
1571	int size;
1572	int maxcl;
1573
1574	s = splbio();
1575	/*
1576	 * right now we support clustered writing only to regular files.  If
1577	 * we find a clusterable block we could be in the middle of a cluster
1578	 * rather then at the beginning.
1579	 */
1580	if ((vp->v_type == VREG) &&
1581	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1582	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1583
1584		size = vp->v_mount->mnt_stat.f_iosize;
1585		maxcl = MAXPHYS / size;
1586
1587		for (i = 1; i < maxcl; i++) {
1588			if ((bpa = gbincore(vp, lblkno + i)) &&
1589			    BUF_REFCNT(bpa) == 0 &&
1590			    ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1591			    (B_DELWRI | B_CLUSTEROK)) &&
1592			    (bpa->b_bufsize == size)) {
1593				if ((bpa->b_blkno == bpa->b_lblkno) ||
1594				    (bpa->b_blkno !=
1595				     bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
1596					break;
1597			} else {
1598				break;
1599			}
1600		}
1601		for (j = 1; i + j <= maxcl && j <= lblkno; j++) {
1602			if ((bpa = gbincore(vp, lblkno - j)) &&
1603			    BUF_REFCNT(bpa) == 0 &&
1604			    ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1605			    (B_DELWRI | B_CLUSTEROK)) &&
1606			    (bpa->b_bufsize == size)) {
1607				if ((bpa->b_blkno == bpa->b_lblkno) ||
1608				    (bpa->b_blkno !=
1609				     bp->b_blkno - ((j * size) >> DEV_BSHIFT)))
1610					break;
1611			} else {
1612				break;
1613			}
1614		}
1615		--j;
1616		ncl = i + j;
1617		/*
1618		 * this is a possible cluster write
1619		 */
1620		if (ncl != 1) {
1621			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1622			splx(s);
1623			return nwritten;
1624		}
1625	}
1626
1627	BUF_LOCK(bp, LK_EXCLUSIVE);
1628	bremfree(bp);
1629	bp->b_flags |= B_ASYNC;
1630
1631	splx(s);
1632	/*
1633	 * default (old) behavior, writing out only one block
1634	 *
1635	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1636	 */
1637	nwritten = bp->b_bufsize;
1638	(void) BUF_WRITE(bp);
1639
1640	return nwritten;
1641}
1642
1643/*
1644 *	getnewbuf:
1645 *
1646 *	Find and initialize a new buffer header, freeing up existing buffers
1647 *	in the bufqueues as necessary.  The new buffer is returned locked.
1648 *
1649 *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1650 *	buffer away, the caller must set B_INVAL prior to calling brelse().
1651 *
1652 *	We block if:
1653 *		We have insufficient buffer headers
1654 *		We have insufficient buffer space
1655 *		buffer_map is too fragmented ( space reservation fails )
1656 *		If we have to flush dirty buffers ( but we try to avoid this )
1657 *
1658 *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1659 *	Instead we ask the buf daemon to do it for us.  We attempt to
1660 *	avoid piecemeal wakeups of the pageout daemon.
1661 */
1662
1663static struct buf *
1664getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1665{
1666	struct buf *bp;
1667	struct buf *nbp;
1668	int defrag = 0;
1669	int nqindex;
1670	static int flushingbufs;
1671
1672	GIANT_REQUIRED;
1673
1674	/*
1675	 * We can't afford to block since we might be holding a vnode lock,
1676	 * which may prevent system daemons from running.  We deal with
1677	 * low-memory situations by proactively returning memory and running
1678	 * async I/O rather then sync I/O.
1679	 */
1680
1681	++getnewbufcalls;
1682	--getnewbufrestarts;
1683restart:
1684	++getnewbufrestarts;
1685
1686	/*
1687	 * Setup for scan.  If we do not have enough free buffers,
1688	 * we setup a degenerate case that immediately fails.  Note
1689	 * that if we are specially marked process, we are allowed to
1690	 * dip into our reserves.
1691	 *
1692	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1693	 *
1694	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1695	 * However, there are a number of cases (defragging, reusing, ...)
1696	 * where we cannot backup.
1697	 */
1698	nqindex = QUEUE_EMPTYKVA;
1699	nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1700
1701	if (nbp == NULL) {
1702		/*
1703		 * If no EMPTYKVA buffers and we are either
1704		 * defragging or reusing, locate a CLEAN buffer
1705		 * to free or reuse.  If bufspace useage is low
1706		 * skip this step so we can allocate a new buffer.
1707		 */
1708		if (defrag || bufspace >= lobufspace) {
1709			nqindex = QUEUE_CLEAN;
1710			nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1711		}
1712
1713		/*
1714		 * If we could not find or were not allowed to reuse a
1715		 * CLEAN buffer, check to see if it is ok to use an EMPTY
1716		 * buffer.  We can only use an EMPTY buffer if allocating
1717		 * its KVA would not otherwise run us out of buffer space.
1718		 */
1719		if (nbp == NULL && defrag == 0 &&
1720		    bufspace + maxsize < hibufspace) {
1721			nqindex = QUEUE_EMPTY;
1722			nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1723		}
1724	}
1725
1726	/*
1727	 * Run scan, possibly freeing data and/or kva mappings on the fly
1728	 * depending.
1729	 */
1730
1731	while ((bp = nbp) != NULL) {
1732		int qindex = nqindex;
1733
1734		/*
1735		 * Calculate next bp ( we can only use it if we do not block
1736		 * or do other fancy things ).
1737		 */
1738		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1739			switch(qindex) {
1740			case QUEUE_EMPTY:
1741				nqindex = QUEUE_EMPTYKVA;
1742				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1743					break;
1744				/* FALLTHROUGH */
1745			case QUEUE_EMPTYKVA:
1746				nqindex = QUEUE_CLEAN;
1747				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1748					break;
1749				/* FALLTHROUGH */
1750			case QUEUE_CLEAN:
1751				/*
1752				 * nbp is NULL.
1753				 */
1754				break;
1755			}
1756		}
1757
1758		/*
1759		 * Sanity Checks
1760		 */
1761		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1762
1763		/*
1764		 * Note: we no longer distinguish between VMIO and non-VMIO
1765		 * buffers.
1766		 */
1767
1768		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1769
1770		/*
1771		 * If we are defragging then we need a buffer with
1772		 * b_kvasize != 0.  XXX this situation should no longer
1773		 * occur, if defrag is non-zero the buffer's b_kvasize
1774		 * should also be non-zero at this point.  XXX
1775		 */
1776		if (defrag && bp->b_kvasize == 0) {
1777			printf("Warning: defrag empty buffer %p\n", bp);
1778			continue;
1779		}
1780
1781		/*
1782		 * Start freeing the bp.  This is somewhat involved.  nbp
1783		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1784		 */
1785
1786		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1787			panic("getnewbuf: locked buf");
1788		bremfree(bp);
1789
1790		if (qindex == QUEUE_CLEAN) {
1791			if (bp->b_flags & B_VMIO) {
1792				bp->b_flags &= ~B_ASYNC;
1793				vfs_vmio_release(bp);
1794			}
1795			if (bp->b_vp)
1796				brelvp(bp);
1797		}
1798
1799		/*
1800		 * NOTE:  nbp is now entirely invalid.  We can only restart
1801		 * the scan from this point on.
1802		 *
1803		 * Get the rest of the buffer freed up.  b_kva* is still
1804		 * valid after this operation.
1805		 */
1806
1807		if (bp->b_rcred != NOCRED) {
1808			crfree(bp->b_rcred);
1809			bp->b_rcred = NOCRED;
1810		}
1811		if (bp->b_wcred != NOCRED) {
1812			crfree(bp->b_wcred);
1813			bp->b_wcred = NOCRED;
1814		}
1815		if (LIST_FIRST(&bp->b_dep) != NULL)
1816			buf_deallocate(bp);
1817		if (bp->b_xflags & BX_BKGRDINPROG)
1818			panic("losing buffer 3");
1819#ifdef USE_BUFHASH
1820		LIST_REMOVE(bp, b_hash);
1821		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1822#endif
1823
1824		if (bp->b_bufsize)
1825			allocbuf(bp, 0);
1826
1827		bp->b_flags = 0;
1828		bp->b_ioflags = 0;
1829		bp->b_xflags = 0;
1830		bp->b_dev = NODEV;
1831		bp->b_vp = NULL;
1832		bp->b_blkno = bp->b_lblkno = 0;
1833		bp->b_offset = NOOFFSET;
1834		bp->b_iodone = 0;
1835		bp->b_error = 0;
1836		bp->b_resid = 0;
1837		bp->b_bcount = 0;
1838		bp->b_npages = 0;
1839		bp->b_dirtyoff = bp->b_dirtyend = 0;
1840		bp->b_magic = B_MAGIC_BIO;
1841		bp->b_op = &buf_ops_bio;
1842		bp->b_object = NULL;
1843
1844		LIST_INIT(&bp->b_dep);
1845
1846		/*
1847		 * If we are defragging then free the buffer.
1848		 */
1849		if (defrag) {
1850			bp->b_flags |= B_INVAL;
1851			bfreekva(bp);
1852			brelse(bp);
1853			defrag = 0;
1854			goto restart;
1855		}
1856
1857		/*
1858		 * If we are overcomitted then recover the buffer and its
1859		 * KVM space.  This occurs in rare situations when multiple
1860		 * processes are blocked in getnewbuf() or allocbuf().
1861		 */
1862		if (bufspace >= hibufspace)
1863			flushingbufs = 1;
1864		if (flushingbufs && bp->b_kvasize != 0) {
1865			bp->b_flags |= B_INVAL;
1866			bfreekva(bp);
1867			brelse(bp);
1868			goto restart;
1869		}
1870		if (bufspace < lobufspace)
1871			flushingbufs = 0;
1872		break;
1873	}
1874
1875	/*
1876	 * If we exhausted our list, sleep as appropriate.  We may have to
1877	 * wakeup various daemons and write out some dirty buffers.
1878	 *
1879	 * Generally we are sleeping due to insufficient buffer space.
1880	 */
1881
1882	if (bp == NULL) {
1883		int flags;
1884		char *waitmsg;
1885
1886		if (defrag) {
1887			flags = VFS_BIO_NEED_BUFSPACE;
1888			waitmsg = "nbufkv";
1889		} else if (bufspace >= hibufspace) {
1890			waitmsg = "nbufbs";
1891			flags = VFS_BIO_NEED_BUFSPACE;
1892		} else {
1893			waitmsg = "newbuf";
1894			flags = VFS_BIO_NEED_ANY;
1895		}
1896
1897		bd_speedup();	/* heeeelp */
1898
1899		needsbuffer |= flags;
1900		while (needsbuffer & flags) {
1901			if (tsleep(&needsbuffer, (PRIBIO + 4) | slpflag,
1902			    waitmsg, slptimeo))
1903				return (NULL);
1904		}
1905	} else {
1906		/*
1907		 * We finally have a valid bp.  We aren't quite out of the
1908		 * woods, we still have to reserve kva space.  In order
1909		 * to keep fragmentation sane we only allocate kva in
1910		 * BKVASIZE chunks.
1911		 */
1912		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1913
1914		if (maxsize != bp->b_kvasize) {
1915			vm_offset_t addr = 0;
1916
1917			bfreekva(bp);
1918
1919			if (vm_map_findspace(buffer_map,
1920				vm_map_min(buffer_map), maxsize, &addr)) {
1921				/*
1922				 * Uh oh.  Buffer map is to fragmented.  We
1923				 * must defragment the map.
1924				 */
1925				++bufdefragcnt;
1926				defrag = 1;
1927				bp->b_flags |= B_INVAL;
1928				brelse(bp);
1929				goto restart;
1930			}
1931			if (addr) {
1932				vm_map_insert(buffer_map, NULL, 0,
1933					addr, addr + maxsize,
1934					VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1935
1936				bp->b_kvabase = (caddr_t) addr;
1937				bp->b_kvasize = maxsize;
1938				bufspace += bp->b_kvasize;
1939				++bufreusecnt;
1940			}
1941		}
1942		bp->b_data = bp->b_kvabase;
1943	}
1944	return(bp);
1945}
1946
1947/*
1948 *	buf_daemon:
1949 *
1950 *	buffer flushing daemon.  Buffers are normally flushed by the
1951 *	update daemon but if it cannot keep up this process starts to
1952 *	take the load in an attempt to prevent getnewbuf() from blocking.
1953 */
1954
1955static struct proc *bufdaemonproc;
1956
1957static struct kproc_desc buf_kp = {
1958	"bufdaemon",
1959	buf_daemon,
1960	&bufdaemonproc
1961};
1962SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1963
1964static void
1965buf_daemon()
1966{
1967	int s;
1968
1969	mtx_lock(&Giant);
1970
1971	/*
1972	 * This process needs to be suspended prior to shutdown sync.
1973	 */
1974	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
1975	    SHUTDOWN_PRI_LAST);
1976
1977	/*
1978	 * This process is allowed to take the buffer cache to the limit
1979	 */
1980	s = splbio();
1981
1982	for (;;) {
1983		kthread_suspend_check(bufdaemonproc);
1984
1985		bd_request = 0;
1986
1987		/*
1988		 * Do the flush.  Limit the amount of in-transit I/O we
1989		 * allow to build up, otherwise we would completely saturate
1990		 * the I/O system.  Wakeup any waiting processes before we
1991		 * normally would so they can run in parallel with our drain.
1992		 */
1993		while (numdirtybuffers > lodirtybuffers) {
1994			if (flushbufqueues() == 0)
1995				break;
1996			waitrunningbufspace();
1997			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
1998		}
1999
2000		/*
2001		 * Only clear bd_request if we have reached our low water
2002		 * mark.  The buf_daemon normally waits 1 second and
2003		 * then incrementally flushes any dirty buffers that have
2004		 * built up, within reason.
2005		 *
2006		 * If we were unable to hit our low water mark and couldn't
2007		 * find any flushable buffers, we sleep half a second.
2008		 * Otherwise we loop immediately.
2009		 */
2010		if (numdirtybuffers <= lodirtybuffers) {
2011			/*
2012			 * We reached our low water mark, reset the
2013			 * request and sleep until we are needed again.
2014			 * The sleep is just so the suspend code works.
2015			 */
2016			bd_request = 0;
2017			tsleep(&bd_request, PVM, "psleep", hz);
2018		} else {
2019			/*
2020			 * We couldn't find any flushable dirty buffers but
2021			 * still have too many dirty buffers, we
2022			 * have to sleep and try again.  (rare)
2023			 */
2024			tsleep(&bd_request, PVM, "qsleep", hz / 2);
2025		}
2026	}
2027}
2028
2029/*
2030 *	flushbufqueues:
2031 *
2032 *	Try to flush a buffer in the dirty queue.  We must be careful to
2033 *	free up B_INVAL buffers instead of write them, which NFS is
2034 *	particularly sensitive to.
2035 */
2036
2037static int
2038flushbufqueues(void)
2039{
2040	struct buf *bp;
2041	int r = 0;
2042
2043	bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
2044
2045	while (bp) {
2046		KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
2047		if ((bp->b_flags & B_DELWRI) != 0 &&
2048		    (bp->b_xflags & BX_BKGRDINPROG) == 0) {
2049			if (bp->b_flags & B_INVAL) {
2050				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2051					panic("flushbufqueues: locked buf");
2052				bremfree(bp);
2053				brelse(bp);
2054				++r;
2055				break;
2056			}
2057			if (LIST_FIRST(&bp->b_dep) != NULL &&
2058			    (bp->b_flags & B_DEFERRED) == 0 &&
2059			    buf_countdeps(bp, 0)) {
2060				TAILQ_REMOVE(&bufqueues[QUEUE_DIRTY],
2061				    bp, b_freelist);
2062				TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY],
2063				    bp, b_freelist);
2064				bp->b_flags |= B_DEFERRED;
2065				bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
2066				continue;
2067			}
2068			vfs_bio_awrite(bp);
2069			++r;
2070			break;
2071		}
2072		bp = TAILQ_NEXT(bp, b_freelist);
2073	}
2074	return (r);
2075}
2076
2077/*
2078 * Check to see if a block is currently memory resident.
2079 */
2080struct buf *
2081incore(struct vnode * vp, daddr_t blkno)
2082{
2083	struct buf *bp;
2084
2085	int s = splbio();
2086	bp = gbincore(vp, blkno);
2087	splx(s);
2088	return (bp);
2089}
2090
2091/*
2092 * Returns true if no I/O is needed to access the
2093 * associated VM object.  This is like incore except
2094 * it also hunts around in the VM system for the data.
2095 */
2096
2097int
2098inmem(struct vnode * vp, daddr_t blkno)
2099{
2100	vm_object_t obj;
2101	vm_offset_t toff, tinc, size;
2102	vm_page_t m;
2103	vm_ooffset_t off;
2104
2105	GIANT_REQUIRED;
2106
2107	if (incore(vp, blkno))
2108		return 1;
2109	if (vp->v_mount == NULL)
2110		return 0;
2111	if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_vflag & VV_OBJBUF) == 0)
2112		return 0;
2113
2114	size = PAGE_SIZE;
2115	if (size > vp->v_mount->mnt_stat.f_iosize)
2116		size = vp->v_mount->mnt_stat.f_iosize;
2117	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2118
2119	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2120		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2121		if (!m)
2122			goto notinmem;
2123		tinc = size;
2124		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2125			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2126		if (vm_page_is_valid(m,
2127		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2128			goto notinmem;
2129	}
2130	return 1;
2131
2132notinmem:
2133	return (0);
2134}
2135
2136/*
2137 *	vfs_setdirty:
2138 *
2139 *	Sets the dirty range for a buffer based on the status of the dirty
2140 *	bits in the pages comprising the buffer.
2141 *
2142 *	The range is limited to the size of the buffer.
2143 *
2144 *	This routine is primarily used by NFS, but is generalized for the
2145 *	B_VMIO case.
2146 */
2147static void
2148vfs_setdirty(struct buf *bp)
2149{
2150	int i;
2151	vm_object_t object;
2152
2153	GIANT_REQUIRED;
2154	/*
2155	 * Degenerate case - empty buffer
2156	 */
2157
2158	if (bp->b_bufsize == 0)
2159		return;
2160
2161	/*
2162	 * We qualify the scan for modified pages on whether the
2163	 * object has been flushed yet.  The OBJ_WRITEABLE flag
2164	 * is not cleared simply by protecting pages off.
2165	 */
2166
2167	if ((bp->b_flags & B_VMIO) == 0)
2168		return;
2169
2170	object = bp->b_pages[0]->object;
2171
2172	if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2173		printf("Warning: object %p writeable but not mightbedirty\n", object);
2174	if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2175		printf("Warning: object %p mightbedirty but not writeable\n", object);
2176
2177	if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2178		vm_offset_t boffset;
2179		vm_offset_t eoffset;
2180
2181		/*
2182		 * test the pages to see if they have been modified directly
2183		 * by users through the VM system.
2184		 */
2185		for (i = 0; i < bp->b_npages; i++) {
2186			vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
2187			vm_page_test_dirty(bp->b_pages[i]);
2188		}
2189
2190		/*
2191		 * Calculate the encompassing dirty range, boffset and eoffset,
2192		 * (eoffset - boffset) bytes.
2193		 */
2194
2195		for (i = 0; i < bp->b_npages; i++) {
2196			if (bp->b_pages[i]->dirty)
2197				break;
2198		}
2199		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2200
2201		for (i = bp->b_npages - 1; i >= 0; --i) {
2202			if (bp->b_pages[i]->dirty) {
2203				break;
2204			}
2205		}
2206		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2207
2208		/*
2209		 * Fit it to the buffer.
2210		 */
2211
2212		if (eoffset > bp->b_bcount)
2213			eoffset = bp->b_bcount;
2214
2215		/*
2216		 * If we have a good dirty range, merge with the existing
2217		 * dirty range.
2218		 */
2219
2220		if (boffset < eoffset) {
2221			if (bp->b_dirtyoff > boffset)
2222				bp->b_dirtyoff = boffset;
2223			if (bp->b_dirtyend < eoffset)
2224				bp->b_dirtyend = eoffset;
2225		}
2226	}
2227}
2228
2229/*
2230 *	getblk:
2231 *
2232 *	Get a block given a specified block and offset into a file/device.
2233 *	The buffers B_DONE bit will be cleared on return, making it almost
2234 * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2235 *	return.  The caller should clear B_INVAL prior to initiating a
2236 *	READ.
2237 *
2238 *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2239 *	an existing buffer.
2240 *
2241 *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2242 *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2243 *	and then cleared based on the backing VM.  If the previous buffer is
2244 *	non-0-sized but invalid, B_CACHE will be cleared.
2245 *
2246 *	If getblk() must create a new buffer, the new buffer is returned with
2247 *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2248 *	case it is returned with B_INVAL clear and B_CACHE set based on the
2249 *	backing VM.
2250 *
2251 *	getblk() also forces a BUF_WRITE() for any B_DELWRI buffer whos
2252 *	B_CACHE bit is clear.
2253 *
2254 *	What this means, basically, is that the caller should use B_CACHE to
2255 *	determine whether the buffer is fully valid or not and should clear
2256 *	B_INVAL prior to issuing a read.  If the caller intends to validate
2257 *	the buffer by loading its data area with something, the caller needs
2258 *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2259 *	the caller should set B_CACHE ( as an optimization ), else the caller
2260 *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2261 *	a write attempt or if it was a successfull read.  If the caller
2262 *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2263 *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2264 */
2265struct buf *
2266getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
2267{
2268	struct buf *bp;
2269	int s;
2270#ifdef USE_BUFHASH
2271	struct bufhashhdr *bh;
2272#endif
2273
2274	if (size > MAXBSIZE)
2275		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2276
2277	s = splbio();
2278loop:
2279	/*
2280	 * Block if we are low on buffers.   Certain processes are allowed
2281	 * to completely exhaust the buffer cache.
2282         *
2283         * If this check ever becomes a bottleneck it may be better to
2284         * move it into the else, when gbincore() fails.  At the moment
2285         * it isn't a problem.
2286	 *
2287	 * XXX remove if 0 sections (clean this up after its proven)
2288         */
2289	if (numfreebuffers == 0) {
2290		if (curthread == PCPU_GET(idlethread))
2291			return NULL;
2292		needsbuffer |= VFS_BIO_NEED_ANY;
2293	}
2294
2295	if ((bp = gbincore(vp, blkno))) {
2296		/*
2297		 * Buffer is in-core.  If the buffer is not busy, it must
2298		 * be on a queue.
2299		 */
2300
2301		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2302			if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2303			    "getblk", slpflag, slptimeo) == ENOLCK)
2304				goto loop;
2305			splx(s);
2306			return (struct buf *) NULL;
2307		}
2308
2309		/*
2310		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2311		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
2312		 * and for a VMIO buffer B_CACHE is adjusted according to the
2313		 * backing VM cache.
2314		 */
2315		if (bp->b_flags & B_INVAL)
2316			bp->b_flags &= ~B_CACHE;
2317		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2318			bp->b_flags |= B_CACHE;
2319		bremfree(bp);
2320
2321		/*
2322		 * check for size inconsistancies for non-VMIO case.
2323		 */
2324
2325		if (bp->b_bcount != size) {
2326			if ((bp->b_flags & B_VMIO) == 0 ||
2327			    (size > bp->b_kvasize)) {
2328				if (bp->b_flags & B_DELWRI) {
2329					bp->b_flags |= B_NOCACHE;
2330					BUF_WRITE(bp);
2331				} else {
2332					if ((bp->b_flags & B_VMIO) &&
2333					   (LIST_FIRST(&bp->b_dep) == NULL)) {
2334						bp->b_flags |= B_RELBUF;
2335						brelse(bp);
2336					} else {
2337						bp->b_flags |= B_NOCACHE;
2338						BUF_WRITE(bp);
2339					}
2340				}
2341				goto loop;
2342			}
2343		}
2344
2345		/*
2346		 * If the size is inconsistant in the VMIO case, we can resize
2347		 * the buffer.  This might lead to B_CACHE getting set or
2348		 * cleared.  If the size has not changed, B_CACHE remains
2349		 * unchanged from its previous state.
2350		 */
2351
2352		if (bp->b_bcount != size)
2353			allocbuf(bp, size);
2354
2355		KASSERT(bp->b_offset != NOOFFSET,
2356		    ("getblk: no buffer offset"));
2357
2358		/*
2359		 * A buffer with B_DELWRI set and B_CACHE clear must
2360		 * be committed before we can return the buffer in
2361		 * order to prevent the caller from issuing a read
2362		 * ( due to B_CACHE not being set ) and overwriting
2363		 * it.
2364		 *
2365		 * Most callers, including NFS and FFS, need this to
2366		 * operate properly either because they assume they
2367		 * can issue a read if B_CACHE is not set, or because
2368		 * ( for example ) an uncached B_DELWRI might loop due
2369		 * to softupdates re-dirtying the buffer.  In the latter
2370		 * case, B_CACHE is set after the first write completes,
2371		 * preventing further loops.
2372		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2373		 * above while extending the buffer, we cannot allow the
2374		 * buffer to remain with B_CACHE set after the write
2375		 * completes or it will represent a corrupt state.  To
2376		 * deal with this we set B_NOCACHE to scrap the buffer
2377		 * after the write.
2378		 *
2379		 * We might be able to do something fancy, like setting
2380		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2381		 * so the below call doesn't set B_CACHE, but that gets real
2382		 * confusing.  This is much easier.
2383		 */
2384
2385		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2386			bp->b_flags |= B_NOCACHE;
2387			BUF_WRITE(bp);
2388			goto loop;
2389		}
2390
2391		splx(s);
2392		bp->b_flags &= ~B_DONE;
2393	} else {
2394		/*
2395		 * Buffer is not in-core, create new buffer.  The buffer
2396		 * returned by getnewbuf() is locked.  Note that the returned
2397		 * buffer is also considered valid (not marked B_INVAL).
2398		 */
2399		int bsize, maxsize, vmio;
2400		off_t offset;
2401
2402		if (vn_isdisk(vp, NULL))
2403			bsize = DEV_BSIZE;
2404		else if (vp->v_mountedhere)
2405			bsize = vp->v_mountedhere->mnt_stat.f_iosize;
2406		else if (vp->v_mount)
2407			bsize = vp->v_mount->mnt_stat.f_iosize;
2408		else
2409			bsize = size;
2410
2411		offset = blkno * bsize;
2412		vmio = (VOP_GETVOBJECT(vp, NULL) == 0) &&
2413		    (vp->v_vflag & VV_OBJBUF);
2414		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2415		maxsize = imax(maxsize, bsize);
2416
2417		if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2418			if (slpflag || slptimeo) {
2419				splx(s);
2420				return NULL;
2421			}
2422			goto loop;
2423		}
2424
2425		/*
2426		 * This code is used to make sure that a buffer is not
2427		 * created while the getnewbuf routine is blocked.
2428		 * This can be a problem whether the vnode is locked or not.
2429		 * If the buffer is created out from under us, we have to
2430		 * throw away the one we just created.  There is now window
2431		 * race because we are safely running at splbio() from the
2432		 * point of the duplicate buffer creation through to here,
2433		 * and we've locked the buffer.
2434		 *
2435		 * Note: this must occur before we associate the buffer
2436		 * with the vp especially considering limitations in
2437		 * the splay tree implementation when dealing with duplicate
2438		 * lblkno's.
2439		 */
2440		if (gbincore(vp, blkno)) {
2441			bp->b_flags |= B_INVAL;
2442			brelse(bp);
2443			goto loop;
2444		}
2445
2446		/*
2447		 * Insert the buffer into the hash, so that it can
2448		 * be found by incore.
2449		 */
2450		bp->b_blkno = bp->b_lblkno = blkno;
2451		bp->b_offset = offset;
2452
2453		bgetvp(vp, bp);
2454#ifdef USE_BUFHASH
2455		LIST_REMOVE(bp, b_hash);
2456		bh = bufhash(vp, blkno);
2457		LIST_INSERT_HEAD(bh, bp, b_hash);
2458#endif
2459
2460		/*
2461		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2462		 * buffer size starts out as 0, B_CACHE will be set by
2463		 * allocbuf() for the VMIO case prior to it testing the
2464		 * backing store for validity.
2465		 */
2466
2467		if (vmio) {
2468			bp->b_flags |= B_VMIO;
2469#if defined(VFS_BIO_DEBUG)
2470			if (vp->v_type != VREG)
2471				printf("getblk: vmioing file type %d???\n", vp->v_type);
2472#endif
2473			VOP_GETVOBJECT(vp, &bp->b_object);
2474		} else {
2475			bp->b_flags &= ~B_VMIO;
2476			bp->b_object = NULL;
2477		}
2478
2479		allocbuf(bp, size);
2480
2481		splx(s);
2482		bp->b_flags &= ~B_DONE;
2483	}
2484	KASSERT(BUF_REFCNT(bp) == 1, ("getblk: bp %p not locked",bp));
2485	return (bp);
2486}
2487
2488/*
2489 * Get an empty, disassociated buffer of given size.  The buffer is initially
2490 * set to B_INVAL.
2491 */
2492struct buf *
2493geteblk(int size)
2494{
2495	struct buf *bp;
2496	int s;
2497	int maxsize;
2498
2499	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2500
2501	s = splbio();
2502	while ((bp = getnewbuf(0, 0, size, maxsize)) == 0);
2503	splx(s);
2504	allocbuf(bp, size);
2505	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2506	KASSERT(BUF_REFCNT(bp) == 1, ("geteblk: bp %p not locked",bp));
2507	return (bp);
2508}
2509
2510
2511/*
2512 * This code constitutes the buffer memory from either anonymous system
2513 * memory (in the case of non-VMIO operations) or from an associated
2514 * VM object (in the case of VMIO operations).  This code is able to
2515 * resize a buffer up or down.
2516 *
2517 * Note that this code is tricky, and has many complications to resolve
2518 * deadlock or inconsistant data situations.  Tread lightly!!!
2519 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2520 * the caller.  Calling this code willy nilly can result in the loss of data.
2521 *
2522 * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2523 * B_CACHE for the non-VMIO case.
2524 */
2525
2526int
2527allocbuf(struct buf *bp, int size)
2528{
2529	int newbsize, mbsize;
2530	int i;
2531
2532	GIANT_REQUIRED;
2533
2534	if (BUF_REFCNT(bp) == 0)
2535		panic("allocbuf: buffer not busy");
2536
2537	if (bp->b_kvasize < size)
2538		panic("allocbuf: buffer too small");
2539
2540	if ((bp->b_flags & B_VMIO) == 0) {
2541		caddr_t origbuf;
2542		int origbufsize;
2543		/*
2544		 * Just get anonymous memory from the kernel.  Don't
2545		 * mess with B_CACHE.
2546		 */
2547		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2548		if (bp->b_flags & B_MALLOC)
2549			newbsize = mbsize;
2550		else
2551			newbsize = round_page(size);
2552
2553		if (newbsize < bp->b_bufsize) {
2554			/*
2555			 * malloced buffers are not shrunk
2556			 */
2557			if (bp->b_flags & B_MALLOC) {
2558				if (newbsize) {
2559					bp->b_bcount = size;
2560				} else {
2561					free(bp->b_data, M_BIOBUF);
2562					if (bp->b_bufsize) {
2563						bufmallocspace -= bp->b_bufsize;
2564						bufspacewakeup();
2565						bp->b_bufsize = 0;
2566					}
2567					bp->b_data = bp->b_kvabase;
2568					bp->b_bcount = 0;
2569					bp->b_flags &= ~B_MALLOC;
2570				}
2571				return 1;
2572			}
2573			vm_hold_free_pages(
2574			    bp,
2575			    (vm_offset_t) bp->b_data + newbsize,
2576			    (vm_offset_t) bp->b_data + bp->b_bufsize);
2577		} else if (newbsize > bp->b_bufsize) {
2578			/*
2579			 * We only use malloced memory on the first allocation.
2580			 * and revert to page-allocated memory when the buffer
2581			 * grows.
2582			 */
2583			if ( (bufmallocspace < maxbufmallocspace) &&
2584				(bp->b_bufsize == 0) &&
2585				(mbsize <= PAGE_SIZE/2)) {
2586
2587				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2588				bp->b_bufsize = mbsize;
2589				bp->b_bcount = size;
2590				bp->b_flags |= B_MALLOC;
2591				bufmallocspace += mbsize;
2592				return 1;
2593			}
2594			origbuf = NULL;
2595			origbufsize = 0;
2596			/*
2597			 * If the buffer is growing on its other-than-first allocation,
2598			 * then we revert to the page-allocation scheme.
2599			 */
2600			if (bp->b_flags & B_MALLOC) {
2601				origbuf = bp->b_data;
2602				origbufsize = bp->b_bufsize;
2603				bp->b_data = bp->b_kvabase;
2604				if (bp->b_bufsize) {
2605					bufmallocspace -= bp->b_bufsize;
2606					bufspacewakeup();
2607					bp->b_bufsize = 0;
2608				}
2609				bp->b_flags &= ~B_MALLOC;
2610				newbsize = round_page(newbsize);
2611			}
2612			vm_hold_load_pages(
2613			    bp,
2614			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2615			    (vm_offset_t) bp->b_data + newbsize);
2616			if (origbuf) {
2617				bcopy(origbuf, bp->b_data, origbufsize);
2618				free(origbuf, M_BIOBUF);
2619			}
2620		}
2621	} else {
2622		vm_page_t m;
2623		int desiredpages;
2624
2625		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2626		desiredpages = (size == 0) ? 0 :
2627			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2628
2629		if (bp->b_flags & B_MALLOC)
2630			panic("allocbuf: VMIO buffer can't be malloced");
2631		/*
2632		 * Set B_CACHE initially if buffer is 0 length or will become
2633		 * 0-length.
2634		 */
2635		if (size == 0 || bp->b_bufsize == 0)
2636			bp->b_flags |= B_CACHE;
2637
2638		if (newbsize < bp->b_bufsize) {
2639			/*
2640			 * DEV_BSIZE aligned new buffer size is less then the
2641			 * DEV_BSIZE aligned existing buffer size.  Figure out
2642			 * if we have to remove any pages.
2643			 */
2644			if (desiredpages < bp->b_npages) {
2645				vm_page_lock_queues();
2646				for (i = desiredpages; i < bp->b_npages; i++) {
2647					/*
2648					 * the page is not freed here -- it
2649					 * is the responsibility of
2650					 * vnode_pager_setsize
2651					 */
2652					m = bp->b_pages[i];
2653					KASSERT(m != bogus_page,
2654					    ("allocbuf: bogus page found"));
2655					while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
2656						vm_page_lock_queues();
2657
2658					bp->b_pages[i] = NULL;
2659					vm_page_unwire(m, 0);
2660				}
2661				vm_page_unlock_queues();
2662				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2663				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2664				bp->b_npages = desiredpages;
2665			}
2666		} else if (size > bp->b_bcount) {
2667			/*
2668			 * We are growing the buffer, possibly in a
2669			 * byte-granular fashion.
2670			 */
2671			struct vnode *vp;
2672			vm_object_t obj;
2673			vm_offset_t toff;
2674			vm_offset_t tinc;
2675
2676			/*
2677			 * Step 1, bring in the VM pages from the object,
2678			 * allocating them if necessary.  We must clear
2679			 * B_CACHE if these pages are not valid for the
2680			 * range covered by the buffer.
2681			 */
2682
2683			vp = bp->b_vp;
2684			obj = bp->b_object;
2685
2686			while (bp->b_npages < desiredpages) {
2687				vm_page_t m;
2688				vm_pindex_t pi;
2689
2690				pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2691				if ((m = vm_page_lookup(obj, pi)) == NULL) {
2692					/*
2693					 * note: must allocate system pages
2694					 * since blocking here could intefere
2695					 * with paging I/O, no matter which
2696					 * process we are.
2697					 */
2698					m = vm_page_alloc(obj, pi,
2699					    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
2700					if (m == NULL) {
2701						VM_WAIT;
2702						vm_pageout_deficit += desiredpages - bp->b_npages;
2703					} else {
2704						vm_page_lock_queues();
2705						vm_page_wakeup(m);
2706						vm_page_unlock_queues();
2707						bp->b_flags &= ~B_CACHE;
2708						bp->b_pages[bp->b_npages] = m;
2709						++bp->b_npages;
2710					}
2711					continue;
2712				}
2713
2714				/*
2715				 * We found a page.  If we have to sleep on it,
2716				 * retry because it might have gotten freed out
2717				 * from under us.
2718				 *
2719				 * We can only test PG_BUSY here.  Blocking on
2720				 * m->busy might lead to a deadlock:
2721				 *
2722				 *  vm_fault->getpages->cluster_read->allocbuf
2723				 *
2724				 */
2725				vm_page_lock_queues();
2726				if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
2727					continue;
2728
2729				/*
2730				 * We have a good page.  Should we wakeup the
2731				 * page daemon?
2732				 */
2733				if ((curproc != pageproc) &&
2734				    ((m->queue - m->pc) == PQ_CACHE) &&
2735				    ((cnt.v_free_count + cnt.v_cache_count) <
2736					(cnt.v_free_min + cnt.v_cache_min))) {
2737					pagedaemon_wakeup();
2738				}
2739				vm_page_flag_clear(m, PG_ZERO);
2740				vm_page_wire(m);
2741				vm_page_unlock_queues();
2742				bp->b_pages[bp->b_npages] = m;
2743				++bp->b_npages;
2744			}
2745
2746			/*
2747			 * Step 2.  We've loaded the pages into the buffer,
2748			 * we have to figure out if we can still have B_CACHE
2749			 * set.  Note that B_CACHE is set according to the
2750			 * byte-granular range ( bcount and size ), new the
2751			 * aligned range ( newbsize ).
2752			 *
2753			 * The VM test is against m->valid, which is DEV_BSIZE
2754			 * aligned.  Needless to say, the validity of the data
2755			 * needs to also be DEV_BSIZE aligned.  Note that this
2756			 * fails with NFS if the server or some other client
2757			 * extends the file's EOF.  If our buffer is resized,
2758			 * B_CACHE may remain set! XXX
2759			 */
2760
2761			toff = bp->b_bcount;
2762			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2763
2764			while ((bp->b_flags & B_CACHE) && toff < size) {
2765				vm_pindex_t pi;
2766
2767				if (tinc > (size - toff))
2768					tinc = size - toff;
2769
2770				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2771				    PAGE_SHIFT;
2772
2773				vfs_buf_test_cache(
2774				    bp,
2775				    bp->b_offset,
2776				    toff,
2777				    tinc,
2778				    bp->b_pages[pi]
2779				);
2780				toff += tinc;
2781				tinc = PAGE_SIZE;
2782			}
2783
2784			/*
2785			 * Step 3, fixup the KVM pmap.  Remember that
2786			 * bp->b_data is relative to bp->b_offset, but
2787			 * bp->b_offset may be offset into the first page.
2788			 */
2789
2790			bp->b_data = (caddr_t)
2791			    trunc_page((vm_offset_t)bp->b_data);
2792			pmap_qenter(
2793			    (vm_offset_t)bp->b_data,
2794			    bp->b_pages,
2795			    bp->b_npages
2796			);
2797
2798			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2799			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
2800		}
2801	}
2802	if (newbsize < bp->b_bufsize)
2803		bufspacewakeup();
2804	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
2805	bp->b_bcount = size;		/* requested buffer size	*/
2806	return 1;
2807}
2808
2809void
2810biodone(struct bio *bp)
2811{
2812	bp->bio_flags |= BIO_DONE;
2813	if (bp->bio_done != NULL)
2814		bp->bio_done(bp);
2815	else
2816		wakeup(bp);
2817}
2818
2819/*
2820 * Wait for a BIO to finish.
2821 * XXX: For now resort to a timeout, the optimal locking (if any) for this
2822 * case is not at this point obvious.
2823 */
2824int
2825biowait(struct bio *bp, const char *wchan)
2826{
2827
2828	while ((bp->bio_flags & BIO_DONE) == 0)
2829		msleep(bp, NULL, 0, wchan, hz);
2830	if (!(bp->bio_flags & BIO_ERROR))
2831		return (0);
2832	if (bp->bio_error)
2833		return (bp->bio_error);
2834	return (EIO);
2835}
2836
2837/*
2838 *	bufwait:
2839 *
2840 *	Wait for buffer I/O completion, returning error status.  The buffer
2841 *	is left locked and B_DONE on return.  B_EINTR is converted into a EINTR
2842 *	error and cleared.
2843 */
2844int
2845bufwait(register struct buf * bp)
2846{
2847	int s;
2848
2849	s = splbio();
2850	while ((bp->b_flags & B_DONE) == 0) {
2851		if (bp->b_iocmd == BIO_READ)
2852			tsleep(bp, PRIBIO, "biord", 0);
2853		else
2854			tsleep(bp, PRIBIO, "biowr", 0);
2855	}
2856	splx(s);
2857	if (bp->b_flags & B_EINTR) {
2858		bp->b_flags &= ~B_EINTR;
2859		return (EINTR);
2860	}
2861	if (bp->b_ioflags & BIO_ERROR) {
2862		return (bp->b_error ? bp->b_error : EIO);
2863	} else {
2864		return (0);
2865	}
2866}
2867
2868 /*
2869  * Call back function from struct bio back up to struct buf.
2870  * The corresponding initialization lives in sys/conf.h:DEV_STRATEGY().
2871  */
2872void
2873bufdonebio(struct bio *bp)
2874{
2875	bufdone(bp->bio_caller2);
2876}
2877
2878/*
2879 *	bufdone:
2880 *
2881 *	Finish I/O on a buffer, optionally calling a completion function.
2882 *	This is usually called from an interrupt so process blocking is
2883 *	not allowed.
2884 *
2885 *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2886 *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
2887 *	assuming B_INVAL is clear.
2888 *
2889 *	For the VMIO case, we set B_CACHE if the op was a read and no
2890 *	read error occured, or if the op was a write.  B_CACHE is never
2891 *	set if the buffer is invalid or otherwise uncacheable.
2892 *
2893 *	biodone does not mess with B_INVAL, allowing the I/O routine or the
2894 *	initiator to leave B_INVAL set to brelse the buffer out of existance
2895 *	in the biodone routine.
2896 */
2897void
2898bufdone(struct buf *bp)
2899{
2900	int s;
2901	void    (*biodone)(struct buf *);
2902
2903	GIANT_REQUIRED;
2904
2905	s = splbio();
2906
2907	KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
2908	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2909
2910	bp->b_flags |= B_DONE;
2911	runningbufwakeup(bp);
2912
2913	if (bp->b_iocmd == BIO_DELETE) {
2914		brelse(bp);
2915		splx(s);
2916		return;
2917	}
2918
2919	if (bp->b_iocmd == BIO_WRITE) {
2920		vwakeup(bp);
2921	}
2922
2923	/* call optional completion function if requested */
2924	if (bp->b_iodone != NULL) {
2925		biodone = bp->b_iodone;
2926		bp->b_iodone = NULL;
2927		(*biodone) (bp);
2928		splx(s);
2929		return;
2930	}
2931	if (LIST_FIRST(&bp->b_dep) != NULL)
2932		buf_complete(bp);
2933
2934	if (bp->b_flags & B_VMIO) {
2935		int i;
2936		vm_ooffset_t foff;
2937		vm_page_t m;
2938		vm_object_t obj;
2939		int iosize;
2940		struct vnode *vp = bp->b_vp;
2941
2942		obj = bp->b_object;
2943
2944#if defined(VFS_BIO_DEBUG)
2945		mp_fixme("usecount and vflag accessed without locks.");
2946		if (vp->v_usecount == 0) {
2947			panic("biodone: zero vnode ref count");
2948		}
2949
2950		if ((vp->v_vflag & VV_OBJBUF) == 0) {
2951			panic("biodone: vnode is not setup for merged cache");
2952		}
2953#endif
2954
2955		foff = bp->b_offset;
2956		KASSERT(bp->b_offset != NOOFFSET,
2957		    ("biodone: no buffer offset"));
2958
2959#if defined(VFS_BIO_DEBUG)
2960		if (obj->paging_in_progress < bp->b_npages) {
2961			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
2962			    obj->paging_in_progress, bp->b_npages);
2963		}
2964#endif
2965
2966		/*
2967		 * Set B_CACHE if the op was a normal read and no error
2968		 * occured.  B_CACHE is set for writes in the b*write()
2969		 * routines.
2970		 */
2971		iosize = bp->b_bcount - bp->b_resid;
2972		if (bp->b_iocmd == BIO_READ &&
2973		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
2974		    !(bp->b_ioflags & BIO_ERROR)) {
2975			bp->b_flags |= B_CACHE;
2976		}
2977		vm_page_lock_queues();
2978		for (i = 0; i < bp->b_npages; i++) {
2979			int bogusflag = 0;
2980			int resid;
2981
2982			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2983			if (resid > iosize)
2984				resid = iosize;
2985
2986			/*
2987			 * cleanup bogus pages, restoring the originals
2988			 */
2989			m = bp->b_pages[i];
2990			if (m == bogus_page) {
2991				bogusflag = 1;
2992				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2993				if (m == NULL)
2994					panic("biodone: page disappeared!");
2995				bp->b_pages[i] = m;
2996				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2997			}
2998#if defined(VFS_BIO_DEBUG)
2999			if (OFF_TO_IDX(foff) != m->pindex) {
3000				printf(
3001"biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3002				    (intmax_t)foff, (uintmax_t)m->pindex);
3003			}
3004#endif
3005
3006			/*
3007			 * In the write case, the valid and clean bits are
3008			 * already changed correctly ( see bdwrite() ), so we
3009			 * only need to do this here in the read case.
3010			 */
3011			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3012				vfs_page_set_valid(bp, foff, i, m);
3013			}
3014			vm_page_flag_clear(m, PG_ZERO);
3015
3016			/*
3017			 * when debugging new filesystems or buffer I/O methods, this
3018			 * is the most common error that pops up.  if you see this, you
3019			 * have not set the page busy flag correctly!!!
3020			 */
3021			if (m->busy == 0) {
3022				printf("biodone: page busy < 0, "
3023				    "pindex: %d, foff: 0x(%x,%x), "
3024				    "resid: %d, index: %d\n",
3025				    (int) m->pindex, (int)(foff >> 32),
3026						(int) foff & 0xffffffff, resid, i);
3027				if (!vn_isdisk(vp, NULL))
3028					printf(" iosize: %ld, lblkno: %jd, flags: 0x%lx, npages: %d\n",
3029					    bp->b_vp->v_mount->mnt_stat.f_iosize,
3030					    (intmax_t) bp->b_lblkno,
3031					    bp->b_flags, bp->b_npages);
3032				else
3033					printf(" VDEV, lblkno: %jd, flags: 0x%lx, npages: %d\n",
3034					    (intmax_t) bp->b_lblkno,
3035					    bp->b_flags, bp->b_npages);
3036				printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3037				    m->valid, m->dirty, m->wire_count);
3038				panic("biodone: page busy < 0\n");
3039			}
3040			vm_page_io_finish(m);
3041			vm_object_pip_subtract(obj, 1);
3042			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3043			iosize -= resid;
3044		}
3045		vm_page_unlock_queues();
3046		if (obj)
3047			vm_object_pip_wakeupn(obj, 0);
3048	}
3049
3050	/*
3051	 * For asynchronous completions, release the buffer now. The brelse
3052	 * will do a wakeup there if necessary - so no need to do a wakeup
3053	 * here in the async case. The sync case always needs to do a wakeup.
3054	 */
3055
3056	if (bp->b_flags & B_ASYNC) {
3057		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3058			brelse(bp);
3059		else
3060			bqrelse(bp);
3061	} else {
3062		wakeup(bp);
3063	}
3064	splx(s);
3065}
3066
3067/*
3068 * This routine is called in lieu of iodone in the case of
3069 * incomplete I/O.  This keeps the busy status for pages
3070 * consistant.
3071 */
3072void
3073vfs_unbusy_pages(struct buf * bp)
3074{
3075	int i;
3076
3077	GIANT_REQUIRED;
3078
3079	runningbufwakeup(bp);
3080	if (bp->b_flags & B_VMIO) {
3081		vm_object_t obj;
3082
3083		obj = bp->b_object;
3084		vm_page_lock_queues();
3085		for (i = 0; i < bp->b_npages; i++) {
3086			vm_page_t m = bp->b_pages[i];
3087
3088			if (m == bogus_page) {
3089				m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3090				if (!m) {
3091					panic("vfs_unbusy_pages: page missing\n");
3092				}
3093				bp->b_pages[i] = m;
3094				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3095			}
3096			vm_object_pip_subtract(obj, 1);
3097			vm_page_flag_clear(m, PG_ZERO);
3098			vm_page_io_finish(m);
3099		}
3100		vm_page_unlock_queues();
3101		vm_object_pip_wakeupn(obj, 0);
3102	}
3103}
3104
3105/*
3106 * vfs_page_set_valid:
3107 *
3108 *	Set the valid bits in a page based on the supplied offset.   The
3109 *	range is restricted to the buffer's size.
3110 *
3111 *	This routine is typically called after a read completes.
3112 */
3113static void
3114vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3115{
3116	vm_ooffset_t soff, eoff;
3117
3118	GIANT_REQUIRED;
3119	/*
3120	 * Start and end offsets in buffer.  eoff - soff may not cross a
3121	 * page boundry or cross the end of the buffer.  The end of the
3122	 * buffer, in this case, is our file EOF, not the allocation size
3123	 * of the buffer.
3124	 */
3125	soff = off;
3126	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3127	if (eoff > bp->b_offset + bp->b_bcount)
3128		eoff = bp->b_offset + bp->b_bcount;
3129
3130	/*
3131	 * Set valid range.  This is typically the entire buffer and thus the
3132	 * entire page.
3133	 */
3134	if (eoff > soff) {
3135		vm_page_set_validclean(
3136		    m,
3137		   (vm_offset_t) (soff & PAGE_MASK),
3138		   (vm_offset_t) (eoff - soff)
3139		);
3140	}
3141}
3142
3143/*
3144 * This routine is called before a device strategy routine.
3145 * It is used to tell the VM system that paging I/O is in
3146 * progress, and treat the pages associated with the buffer
3147 * almost as being PG_BUSY.  Also the object paging_in_progress
3148 * flag is handled to make sure that the object doesn't become
3149 * inconsistant.
3150 *
3151 * Since I/O has not been initiated yet, certain buffer flags
3152 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3153 * and should be ignored.
3154 */
3155void
3156vfs_busy_pages(struct buf * bp, int clear_modify)
3157{
3158	int i, bogus;
3159
3160	if (bp->b_flags & B_VMIO) {
3161		vm_object_t obj;
3162		vm_ooffset_t foff;
3163
3164		obj = bp->b_object;
3165		foff = bp->b_offset;
3166		KASSERT(bp->b_offset != NOOFFSET,
3167		    ("vfs_busy_pages: no buffer offset"));
3168		vfs_setdirty(bp);
3169retry:
3170		vm_page_lock_queues();
3171		for (i = 0; i < bp->b_npages; i++) {
3172			vm_page_t m = bp->b_pages[i];
3173
3174			if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3175				goto retry;
3176		}
3177		bogus = 0;
3178		for (i = 0; i < bp->b_npages; i++) {
3179			vm_page_t m = bp->b_pages[i];
3180
3181			vm_page_flag_clear(m, PG_ZERO);
3182			if ((bp->b_flags & B_CLUSTER) == 0) {
3183				vm_object_pip_add(obj, 1);
3184				vm_page_io_start(m);
3185			}
3186			/*
3187			 * When readying a buffer for a read ( i.e
3188			 * clear_modify == 0 ), it is important to do
3189			 * bogus_page replacement for valid pages in
3190			 * partially instantiated buffers.  Partially
3191			 * instantiated buffers can, in turn, occur when
3192			 * reconstituting a buffer from its VM backing store
3193			 * base.  We only have to do this if B_CACHE is
3194			 * clear ( which causes the I/O to occur in the
3195			 * first place ).  The replacement prevents the read
3196			 * I/O from overwriting potentially dirty VM-backed
3197			 * pages.  XXX bogus page replacement is, uh, bogus.
3198			 * It may not work properly with small-block devices.
3199			 * We need to find a better way.
3200			 */
3201			vm_page_protect(m, VM_PROT_NONE);
3202			if (clear_modify)
3203				vfs_page_set_valid(bp, foff, i, m);
3204			else if (m->valid == VM_PAGE_BITS_ALL &&
3205				(bp->b_flags & B_CACHE) == 0) {
3206				bp->b_pages[i] = bogus_page;
3207				bogus++;
3208			}
3209			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3210		}
3211		vm_page_unlock_queues();
3212		if (bogus)
3213			pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3214	}
3215}
3216
3217/*
3218 * Tell the VM system that the pages associated with this buffer
3219 * are clean.  This is used for delayed writes where the data is
3220 * going to go to disk eventually without additional VM intevention.
3221 *
3222 * Note that while we only really need to clean through to b_bcount, we
3223 * just go ahead and clean through to b_bufsize.
3224 */
3225static void
3226vfs_clean_pages(struct buf * bp)
3227{
3228	int i;
3229
3230	GIANT_REQUIRED;
3231
3232	if (bp->b_flags & B_VMIO) {
3233		vm_ooffset_t foff;
3234
3235		foff = bp->b_offset;
3236		KASSERT(bp->b_offset != NOOFFSET,
3237		    ("vfs_clean_pages: no buffer offset"));
3238		for (i = 0; i < bp->b_npages; i++) {
3239			vm_page_t m = bp->b_pages[i];
3240			vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3241			vm_ooffset_t eoff = noff;
3242
3243			if (eoff > bp->b_offset + bp->b_bufsize)
3244				eoff = bp->b_offset + bp->b_bufsize;
3245			vfs_page_set_valid(bp, foff, i, m);
3246			/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3247			foff = noff;
3248		}
3249	}
3250}
3251
3252/*
3253 *	vfs_bio_set_validclean:
3254 *
3255 *	Set the range within the buffer to valid and clean.  The range is
3256 *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3257 *	itself may be offset from the beginning of the first page.
3258 *
3259 */
3260
3261void
3262vfs_bio_set_validclean(struct buf *bp, int base, int size)
3263{
3264	if (bp->b_flags & B_VMIO) {
3265		int i;
3266		int n;
3267
3268		/*
3269		 * Fixup base to be relative to beginning of first page.
3270		 * Set initial n to be the maximum number of bytes in the
3271		 * first page that can be validated.
3272		 */
3273
3274		base += (bp->b_offset & PAGE_MASK);
3275		n = PAGE_SIZE - (base & PAGE_MASK);
3276
3277		for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3278			vm_page_t m = bp->b_pages[i];
3279
3280			if (n > size)
3281				n = size;
3282
3283			vm_page_set_validclean(m, base & PAGE_MASK, n);
3284			base += n;
3285			size -= n;
3286			n = PAGE_SIZE;
3287		}
3288	}
3289}
3290
3291/*
3292 *	vfs_bio_clrbuf:
3293 *
3294 *	clear a buffer.  This routine essentially fakes an I/O, so we need
3295 *	to clear BIO_ERROR and B_INVAL.
3296 *
3297 *	Note that while we only theoretically need to clear through b_bcount,
3298 *	we go ahead and clear through b_bufsize.
3299 */
3300
3301void
3302vfs_bio_clrbuf(struct buf *bp)
3303{
3304	int i, mask = 0;
3305	caddr_t sa, ea;
3306
3307	GIANT_REQUIRED;
3308
3309	if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3310		bp->b_flags &= ~B_INVAL;
3311		bp->b_ioflags &= ~BIO_ERROR;
3312		if( (bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3313		    (bp->b_offset & PAGE_MASK) == 0) {
3314			mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3315			if ((bp->b_pages[0]->valid & mask) == mask) {
3316				bp->b_resid = 0;
3317				return;
3318			}
3319			if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3320			    ((bp->b_pages[0]->valid & mask) == 0)) {
3321				bzero(bp->b_data, bp->b_bufsize);
3322				bp->b_pages[0]->valid |= mask;
3323				bp->b_resid = 0;
3324				return;
3325			}
3326		}
3327		ea = sa = bp->b_data;
3328		for(i=0;i<bp->b_npages;i++,sa=ea) {
3329			int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3330			ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3331			ea = (caddr_t)(vm_offset_t)ulmin(
3332			    (u_long)(vm_offset_t)ea,
3333			    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3334			mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3335			if ((bp->b_pages[i]->valid & mask) == mask)
3336				continue;
3337			if ((bp->b_pages[i]->valid & mask) == 0) {
3338				if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
3339					bzero(sa, ea - sa);
3340				}
3341			} else {
3342				for (; sa < ea; sa += DEV_BSIZE, j++) {
3343					if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3344						(bp->b_pages[i]->valid & (1<<j)) == 0)
3345						bzero(sa, DEV_BSIZE);
3346				}
3347			}
3348			bp->b_pages[i]->valid |= mask;
3349			vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3350		}
3351		bp->b_resid = 0;
3352	} else {
3353		clrbuf(bp);
3354	}
3355}
3356
3357/*
3358 * vm_hold_load_pages and vm_hold_free_pages get pages into
3359 * a buffers address space.  The pages are anonymous and are
3360 * not associated with a file object.
3361 */
3362static void
3363vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3364{
3365	vm_offset_t pg;
3366	vm_page_t p;
3367	int index;
3368
3369	GIANT_REQUIRED;
3370
3371	to = round_page(to);
3372	from = round_page(from);
3373	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3374
3375	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3376tryagain:
3377		/*
3378		 * note: must allocate system pages since blocking here
3379		 * could intefere with paging I/O, no matter which
3380		 * process we are.
3381		 */
3382		p = vm_page_alloc(kernel_object,
3383			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3384		    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3385		if (!p) {
3386			vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3387			VM_WAIT;
3388			goto tryagain;
3389		}
3390		vm_page_lock_queues();
3391		p->valid = VM_PAGE_BITS_ALL;
3392		vm_page_flag_clear(p, PG_ZERO);
3393		vm_page_unlock_queues();
3394		pmap_qenter(pg, &p, 1);
3395		bp->b_pages[index] = p;
3396		vm_page_wakeup(p);
3397	}
3398	bp->b_npages = index;
3399}
3400
3401/* Return pages associated with this buf to the vm system */
3402void
3403vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3404{
3405	vm_offset_t pg;
3406	vm_page_t p;
3407	int index, newnpages;
3408
3409	GIANT_REQUIRED;
3410
3411	from = round_page(from);
3412	to = round_page(to);
3413	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3414
3415	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3416		p = bp->b_pages[index];
3417		if (p && (index < bp->b_npages)) {
3418			if (p->busy) {
3419				printf(
3420			    "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3421				    (intmax_t)bp->b_blkno,
3422				    (intmax_t)bp->b_lblkno);
3423			}
3424			bp->b_pages[index] = NULL;
3425			pmap_qremove(pg, 1);
3426			vm_page_lock_queues();
3427			vm_page_busy(p);
3428			vm_page_unwire(p, 0);
3429			vm_page_free(p);
3430			vm_page_unlock_queues();
3431		}
3432	}
3433	bp->b_npages = newnpages;
3434}
3435
3436
3437#include "opt_ddb.h"
3438#ifdef DDB
3439#include <ddb/ddb.h>
3440
3441/* DDB command to show buffer data */
3442DB_SHOW_COMMAND(buffer, db_show_buffer)
3443{
3444	/* get args */
3445	struct buf *bp = (struct buf *)addr;
3446
3447	if (!have_addr) {
3448		db_printf("usage: show buffer <addr>\n");
3449		return;
3450	}
3451
3452	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3453	db_printf(
3454	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
3455	    "b_dev = (%d,%d), b_data = %p, b_blkno = %jd, b_pblkno = %jd\n",
3456	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3457	    major(bp->b_dev), minor(bp->b_dev), bp->b_data,
3458	    (intmax_t)bp->b_blkno, (intmax_t)bp->b_pblkno);
3459	if (bp->b_npages) {
3460		int i;
3461		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3462		for (i = 0; i < bp->b_npages; i++) {
3463			vm_page_t m;
3464			m = bp->b_pages[i];
3465			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3466			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3467			if ((i + 1) < bp->b_npages)
3468				db_printf(",");
3469		}
3470		db_printf("\n");
3471	}
3472}
3473#endif /* DDB */
3474