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