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