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