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