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