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