vfs_bio.c revision 112846
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 112846 2003-03-30 08:51:23Z 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 if ((oldflags & B_NOWDRAIN) == 0) {
886		/*
887		 * don't allow the async write to saturate the I/O
888		 * system.  Deadlocks can occur only if a device strategy
889		 * routine (like in MD) turns around and issues another
890		 * high-level write, in which case B_NOWDRAIN is expected
891		 * to be set.  Otherwise we will not deadlock here because
892		 * we are blocking waiting for I/O that is already in-progress
893		 * to complete.
894		 */
895		waitrunningbufspace();
896	}
897
898	return (0);
899}
900
901/*
902 * Complete a background write started from bwrite.
903 */
904static void
905vfs_backgroundwritedone(bp)
906	struct buf *bp;
907{
908	struct buf *origbp;
909
910	/*
911	 * Find the original buffer that we are writing.
912	 */
913	VI_LOCK(bp->b_vp);
914	if ((origbp = gbincore(bp->b_vp, bp->b_lblkno)) == NULL)
915		panic("backgroundwritedone: lost buffer");
916	VI_UNLOCK(bp->b_vp);
917	/*
918	 * Process dependencies then return any unfinished ones.
919	 */
920	if (LIST_FIRST(&bp->b_dep) != NULL)
921		buf_complete(bp);
922	if (LIST_FIRST(&bp->b_dep) != NULL)
923		buf_movedeps(bp, origbp);
924
925	/* XXX Find out if origbp can disappear or get inconsistent */
926	/*
927	 * Clear the BX_BKGRDINPROG flag in the original buffer
928	 * and awaken it if it is waiting for the write to complete.
929	 * If BX_BKGRDINPROG is not set in the original buffer it must
930	 * have been released and re-instantiated - which is not legal.
931	 */
932	KASSERT((origbp->b_xflags & BX_BKGRDINPROG),
933	    ("backgroundwritedone: lost buffer2"));
934	origbp->b_xflags &= ~BX_BKGRDINPROG;
935	if (origbp->b_xflags & BX_BKGRDWAIT) {
936		origbp->b_xflags &= ~BX_BKGRDWAIT;
937		wakeup(&origbp->b_xflags);
938	}
939	/*
940	 * Clear the B_LOCKED flag and remove it from the locked
941	 * queue if it currently resides there.
942	 */
943	origbp->b_flags &= ~B_LOCKED;
944	if (BUF_LOCK(origbp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0) {
945		bremfree(origbp);
946		bqrelse(origbp);
947	}
948	/*
949	 * This buffer is marked B_NOCACHE, so when it is released
950	 * by biodone, it will be tossed. We mark it with BIO_READ
951	 * to avoid biodone doing a second vwakeup.
952	 */
953	bp->b_flags |= B_NOCACHE;
954	bp->b_iocmd = BIO_READ;
955	bp->b_flags &= ~(B_CACHE | B_DONE);
956	bp->b_iodone = 0;
957	bufdone(bp);
958}
959
960/*
961 * Delayed write. (Buffer is marked dirty).  Do not bother writing
962 * anything if the buffer is marked invalid.
963 *
964 * Note that since the buffer must be completely valid, we can safely
965 * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
966 * biodone() in order to prevent getblk from writing the buffer
967 * out synchronously.
968 */
969void
970bdwrite(struct buf * bp)
971{
972	struct thread *td = curthread;
973	struct vnode *vp;
974	struct buf *nbp;
975
976	GIANT_REQUIRED;
977
978	if (BUF_REFCNT(bp) == 0)
979		panic("bdwrite: buffer is not busy");
980
981	if (bp->b_flags & B_INVAL) {
982		brelse(bp);
983		return;
984	}
985
986	/*
987	 * If we have too many dirty buffers, don't create any more.
988	 * If we are wildly over our limit, then force a complete
989	 * cleanup. Otherwise, just keep the situation from getting
990	 * out of control. Note that we have to avoid a recursive
991	 * disaster and not try to clean up after our own cleanup!
992	 */
993	vp = bp->b_vp;
994	VI_LOCK(vp);
995	if (td->td_proc->p_flag & P_COWINPROGRESS) {
996		recursiveflushes++;
997	} else if (vp != NULL && vp->v_dirtybufcnt > dirtybufthresh + 10) {
998		VI_UNLOCK(vp);
999		(void) VOP_FSYNC(vp, td->td_ucred, MNT_NOWAIT, td);
1000		VI_LOCK(vp);
1001		altbufferflushes++;
1002	} else if (vp != NULL && vp->v_dirtybufcnt > dirtybufthresh) {
1003		/*
1004		 * Try to find a buffer to flush.
1005		 */
1006		TAILQ_FOREACH(nbp, &vp->v_dirtyblkhd, b_vnbufs) {
1007			if ((nbp->b_xflags & BX_BKGRDINPROG) ||
1008			    buf_countdeps(nbp, 0) ||
1009			    BUF_LOCK(nbp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
1010				continue;
1011			if (bp == nbp)
1012				panic("bdwrite: found ourselves");
1013			VI_UNLOCK(vp);
1014			if (nbp->b_flags & B_CLUSTEROK) {
1015				vfs_bio_awrite(nbp);
1016			} else {
1017				bremfree(nbp);
1018				bawrite(nbp);
1019			}
1020			VI_LOCK(vp);
1021			dirtybufferflushes++;
1022			break;
1023		}
1024	}
1025	VI_UNLOCK(vp);
1026
1027	bdirty(bp);
1028	/*
1029	 * Set B_CACHE, indicating that the buffer is fully valid.  This is
1030	 * true even of NFS now.
1031	 */
1032	bp->b_flags |= B_CACHE;
1033
1034	/*
1035	 * This bmap keeps the system from needing to do the bmap later,
1036	 * perhaps when the system is attempting to do a sync.  Since it
1037	 * is likely that the indirect block -- or whatever other datastructure
1038	 * that the filesystem needs is still in memory now, it is a good
1039	 * thing to do this.  Note also, that if the pageout daemon is
1040	 * requesting a sync -- there might not be enough memory to do
1041	 * the bmap then...  So, this is important to do.
1042	 */
1043	if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1044		VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1045	}
1046
1047	/*
1048	 * Set the *dirty* buffer range based upon the VM system dirty pages.
1049	 */
1050	vfs_setdirty(bp);
1051
1052	/*
1053	 * We need to do this here to satisfy the vnode_pager and the
1054	 * pageout daemon, so that it thinks that the pages have been
1055	 * "cleaned".  Note that since the pages are in a delayed write
1056	 * buffer -- the VFS layer "will" see that the pages get written
1057	 * out on the next sync, or perhaps the cluster will be completed.
1058	 */
1059	vfs_clean_pages(bp);
1060	bqrelse(bp);
1061
1062	/*
1063	 * Wakeup the buffer flushing daemon if we have a lot of dirty
1064	 * buffers (midpoint between our recovery point and our stall
1065	 * point).
1066	 */
1067	bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1068
1069	/*
1070	 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1071	 * due to the softdep code.
1072	 */
1073}
1074
1075/*
1076 *	bdirty:
1077 *
1078 *	Turn buffer into delayed write request.  We must clear BIO_READ and
1079 *	B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to
1080 *	itself to properly update it in the dirty/clean lists.  We mark it
1081 *	B_DONE to ensure that any asynchronization of the buffer properly
1082 *	clears B_DONE ( else a panic will occur later ).
1083 *
1084 *	bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1085 *	might have been set pre-getblk().  Unlike bwrite/bdwrite, bdirty()
1086 *	should only be called if the buffer is known-good.
1087 *
1088 *	Since the buffer is not on a queue, we do not update the numfreebuffers
1089 *	count.
1090 *
1091 *	Must be called at splbio().
1092 *	The buffer must be on QUEUE_NONE.
1093 */
1094void
1095bdirty(bp)
1096	struct buf *bp;
1097{
1098	KASSERT(bp->b_qindex == QUEUE_NONE,
1099	    ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1100	bp->b_flags &= ~(B_RELBUF);
1101	bp->b_iocmd = BIO_WRITE;
1102
1103	if ((bp->b_flags & B_DELWRI) == 0) {
1104		bp->b_flags |= B_DONE | B_DELWRI;
1105		reassignbuf(bp, bp->b_vp);
1106		atomic_add_int(&numdirtybuffers, 1);
1107		bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1108	}
1109}
1110
1111/*
1112 *	bundirty:
1113 *
1114 *	Clear B_DELWRI for buffer.
1115 *
1116 *	Since the buffer is not on a queue, we do not update the numfreebuffers
1117 *	count.
1118 *
1119 *	Must be called at splbio().
1120 *	The buffer must be on QUEUE_NONE.
1121 */
1122
1123void
1124bundirty(bp)
1125	struct buf *bp;
1126{
1127	KASSERT(bp->b_qindex == QUEUE_NONE,
1128	    ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1129
1130	if (bp->b_flags & B_DELWRI) {
1131		bp->b_flags &= ~B_DELWRI;
1132		reassignbuf(bp, bp->b_vp);
1133		atomic_subtract_int(&numdirtybuffers, 1);
1134		numdirtywakeup(lodirtybuffers);
1135	}
1136	/*
1137	 * Since it is now being written, we can clear its deferred write flag.
1138	 */
1139	bp->b_flags &= ~B_DEFERRED;
1140}
1141
1142/*
1143 *	bawrite:
1144 *
1145 *	Asynchronous write.  Start output on a buffer, but do not wait for
1146 *	it to complete.  The buffer is released when the output completes.
1147 *
1148 *	bwrite() ( or the VOP routine anyway ) is responsible for handling
1149 *	B_INVAL buffers.  Not us.
1150 */
1151void
1152bawrite(struct buf * bp)
1153{
1154	bp->b_flags |= B_ASYNC;
1155	(void) BUF_WRITE(bp);
1156}
1157
1158/*
1159 *	bwillwrite:
1160 *
1161 *	Called prior to the locking of any vnodes when we are expecting to
1162 *	write.  We do not want to starve the buffer cache with too many
1163 *	dirty buffers so we block here.  By blocking prior to the locking
1164 *	of any vnodes we attempt to avoid the situation where a locked vnode
1165 *	prevents the various system daemons from flushing related buffers.
1166 */
1167
1168void
1169bwillwrite(void)
1170{
1171	if (numdirtybuffers >= hidirtybuffers) {
1172		int s;
1173
1174		mtx_lock(&Giant);
1175		s = splbio();
1176		mtx_lock(&nblock);
1177		while (numdirtybuffers >= hidirtybuffers) {
1178			bd_wakeup(1);
1179			needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1180			msleep(&needsbuffer, &nblock,
1181			    (PRIBIO + 4), "flswai", 0);
1182		}
1183		splx(s);
1184		mtx_unlock(&nblock);
1185		mtx_unlock(&Giant);
1186	}
1187}
1188
1189/*
1190 * Return true if we have too many dirty buffers.
1191 */
1192int
1193buf_dirty_count_severe(void)
1194{
1195	return(numdirtybuffers >= hidirtybuffers);
1196}
1197
1198/*
1199 *	brelse:
1200 *
1201 *	Release a busy buffer and, if requested, free its resources.  The
1202 *	buffer will be stashed in the appropriate bufqueue[] allowing it
1203 *	to be accessed later as a cache entity or reused for other purposes.
1204 */
1205void
1206brelse(struct buf * bp)
1207{
1208	int s;
1209
1210	GIANT_REQUIRED;
1211
1212	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1213	    ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1214
1215	s = splbio();
1216
1217	if (bp->b_flags & B_LOCKED)
1218		bp->b_ioflags &= ~BIO_ERROR;
1219
1220	if (bp->b_iocmd == BIO_WRITE &&
1221	    (bp->b_ioflags & BIO_ERROR) &&
1222	    !(bp->b_flags & B_INVAL)) {
1223		/*
1224		 * Failed write, redirty.  Must clear BIO_ERROR to prevent
1225		 * pages from being scrapped.  If B_INVAL is set then
1226		 * this case is not run and the next case is run to
1227		 * destroy the buffer.  B_INVAL can occur if the buffer
1228		 * is outside the range supported by the underlying device.
1229		 */
1230		bp->b_ioflags &= ~BIO_ERROR;
1231		bdirty(bp);
1232	} else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1233	    (bp->b_ioflags & BIO_ERROR) ||
1234	    bp->b_iocmd == BIO_DELETE || (bp->b_bufsize <= 0)) {
1235		/*
1236		 * Either a failed I/O or we were asked to free or not
1237		 * cache the buffer.
1238		 */
1239		bp->b_flags |= B_INVAL;
1240		if (LIST_FIRST(&bp->b_dep) != NULL)
1241			buf_deallocate(bp);
1242		if (bp->b_flags & B_DELWRI) {
1243			atomic_subtract_int(&numdirtybuffers, 1);
1244			numdirtywakeup(lodirtybuffers);
1245		}
1246		bp->b_flags &= ~(B_DELWRI | B_CACHE);
1247		if ((bp->b_flags & B_VMIO) == 0) {
1248			if (bp->b_bufsize)
1249				allocbuf(bp, 0);
1250			if (bp->b_vp)
1251				brelvp(bp);
1252		}
1253	}
1254
1255	/*
1256	 * We must clear B_RELBUF if B_DELWRI is set.  If vfs_vmio_release()
1257	 * is called with B_DELWRI set, the underlying pages may wind up
1258	 * getting freed causing a previous write (bdwrite()) to get 'lost'
1259	 * because pages associated with a B_DELWRI bp are marked clean.
1260	 *
1261	 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1262	 * if B_DELWRI is set.
1263	 *
1264	 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1265	 * on pages to return pages to the VM page queues.
1266	 */
1267	if (bp->b_flags & B_DELWRI)
1268		bp->b_flags &= ~B_RELBUF;
1269	else if (vm_page_count_severe() && !(bp->b_xflags & BX_BKGRDINPROG))
1270		bp->b_flags |= B_RELBUF;
1271
1272	/*
1273	 * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
1274	 * constituted, not even NFS buffers now.  Two flags effect this.  If
1275	 * B_INVAL, the struct buf is invalidated but the VM object is kept
1276	 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1277	 *
1278	 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1279	 * invalidated.  BIO_ERROR cannot be set for a failed write unless the
1280	 * buffer is also B_INVAL because it hits the re-dirtying code above.
1281	 *
1282	 * Normally we can do this whether a buffer is B_DELWRI or not.  If
1283	 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1284	 * the commit state and we cannot afford to lose the buffer. If the
1285	 * buffer has a background write in progress, we need to keep it
1286	 * around to prevent it from being reconstituted and starting a second
1287	 * background write.
1288	 */
1289	if ((bp->b_flags & B_VMIO)
1290	    && !(bp->b_vp->v_mount != NULL &&
1291		 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1292		 !vn_isdisk(bp->b_vp, NULL) &&
1293		 (bp->b_flags & B_DELWRI))
1294	    ) {
1295
1296		int i, j, resid;
1297		vm_page_t m;
1298		off_t foff;
1299		vm_pindex_t poff;
1300		vm_object_t obj;
1301		struct vnode *vp;
1302
1303		vp = bp->b_vp;
1304		obj = bp->b_object;
1305
1306		/*
1307		 * Get the base offset and length of the buffer.  Note that
1308		 * in the VMIO case if the buffer block size is not
1309		 * page-aligned then b_data pointer may not be page-aligned.
1310		 * But our b_pages[] array *IS* page aligned.
1311		 *
1312		 * block sizes less then DEV_BSIZE (usually 512) are not
1313		 * supported due to the page granularity bits (m->valid,
1314		 * m->dirty, etc...).
1315		 *
1316		 * See man buf(9) for more information
1317		 */
1318		resid = bp->b_bufsize;
1319		foff = bp->b_offset;
1320
1321		for (i = 0; i < bp->b_npages; i++) {
1322			int had_bogus = 0;
1323
1324			m = bp->b_pages[i];
1325			vm_page_lock_queues();
1326			vm_page_flag_clear(m, PG_ZERO);
1327			vm_page_unlock_queues();
1328
1329			/*
1330			 * If we hit a bogus page, fixup *all* the bogus pages
1331			 * now.
1332			 */
1333			if (m == bogus_page) {
1334				poff = OFF_TO_IDX(bp->b_offset);
1335				had_bogus = 1;
1336
1337				for (j = i; j < bp->b_npages; j++) {
1338					vm_page_t mtmp;
1339					mtmp = bp->b_pages[j];
1340					if (mtmp == bogus_page) {
1341						mtmp = vm_page_lookup(obj, poff + j);
1342						if (!mtmp) {
1343							panic("brelse: page missing\n");
1344						}
1345						bp->b_pages[j] = mtmp;
1346					}
1347				}
1348
1349				if ((bp->b_flags & B_INVAL) == 0) {
1350					pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
1351				}
1352				m = bp->b_pages[i];
1353			}
1354			if ((bp->b_flags & B_NOCACHE) || (bp->b_ioflags & BIO_ERROR)) {
1355				int poffset = foff & PAGE_MASK;
1356				int presid = resid > (PAGE_SIZE - poffset) ?
1357					(PAGE_SIZE - poffset) : resid;
1358
1359				KASSERT(presid >= 0, ("brelse: extra page"));
1360				vm_page_set_invalid(m, poffset, presid);
1361				if (had_bogus)
1362					printf("avoided corruption bug in bogus_page/brelse code\n");
1363			}
1364			resid -= PAGE_SIZE - (foff & PAGE_MASK);
1365			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1366		}
1367
1368		if (bp->b_flags & (B_INVAL | B_RELBUF))
1369			vfs_vmio_release(bp);
1370
1371	} else if (bp->b_flags & B_VMIO) {
1372
1373		if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1374			vfs_vmio_release(bp);
1375		}
1376
1377	}
1378
1379	if (bp->b_qindex != QUEUE_NONE)
1380		panic("brelse: free buffer onto another queue???");
1381	if (BUF_REFCNT(bp) > 1) {
1382		/* do not release to free list */
1383		BUF_UNLOCK(bp);
1384		splx(s);
1385		return;
1386	}
1387
1388	/* enqueue */
1389	mtx_lock(&bqlock);
1390
1391	/* buffers with no memory */
1392	if (bp->b_bufsize == 0) {
1393		bp->b_flags |= B_INVAL;
1394		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1395		if (bp->b_xflags & BX_BKGRDINPROG)
1396			panic("losing buffer 1");
1397		if (bp->b_kvasize) {
1398			bp->b_qindex = QUEUE_EMPTYKVA;
1399		} else {
1400			bp->b_qindex = QUEUE_EMPTY;
1401		}
1402		TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1403		bp->b_dev = NODEV;
1404	/* buffers with junk contents */
1405	} else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1406	    (bp->b_ioflags & BIO_ERROR)) {
1407		bp->b_flags |= B_INVAL;
1408		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1409		if (bp->b_xflags & BX_BKGRDINPROG)
1410			panic("losing buffer 2");
1411		bp->b_qindex = QUEUE_CLEAN;
1412		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1413		bp->b_dev = NODEV;
1414
1415	/* buffers that are locked */
1416	} else if (bp->b_flags & B_LOCKED) {
1417		bp->b_qindex = QUEUE_LOCKED;
1418		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1419
1420	/* remaining buffers */
1421	} else {
1422		if (bp->b_flags & B_DELWRI)
1423			bp->b_qindex = QUEUE_DIRTY;
1424		else
1425			bp->b_qindex = QUEUE_CLEAN;
1426		if (bp->b_flags & B_AGE)
1427			TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1428		else
1429			TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1430	}
1431	mtx_unlock(&bqlock);
1432
1433	/*
1434	 * If B_INVAL and B_DELWRI is set, clear B_DELWRI.  We have already
1435	 * placed the buffer on the correct queue.  We must also disassociate
1436	 * the device and vnode for a B_INVAL buffer so gbincore() doesn't
1437	 * find it.
1438	 */
1439	if (bp->b_flags & B_INVAL) {
1440		if (bp->b_flags & B_DELWRI)
1441			bundirty(bp);
1442		if (bp->b_vp)
1443			brelvp(bp);
1444	}
1445
1446	/*
1447	 * Fixup numfreebuffers count.  The bp is on an appropriate queue
1448	 * unless locked.  We then bump numfreebuffers if it is not B_DELWRI.
1449	 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1450	 * if B_INVAL is set ).
1451	 */
1452
1453	if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1454		bufcountwakeup();
1455
1456	/*
1457	 * Something we can maybe free or reuse
1458	 */
1459	if (bp->b_bufsize || bp->b_kvasize)
1460		bufspacewakeup();
1461
1462	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1463			B_DIRECT | B_NOWDRAIN);
1464	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1465		panic("brelse: not dirty");
1466	/* unlock */
1467	BUF_UNLOCK(bp);
1468	splx(s);
1469}
1470
1471/*
1472 * Release a buffer back to the appropriate queue but do not try to free
1473 * it.  The buffer is expected to be used again soon.
1474 *
1475 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1476 * biodone() to requeue an async I/O on completion.  It is also used when
1477 * known good buffers need to be requeued but we think we may need the data
1478 * again soon.
1479 *
1480 * XXX we should be able to leave the B_RELBUF hint set on completion.
1481 */
1482void
1483bqrelse(struct buf * bp)
1484{
1485	int s;
1486
1487	s = splbio();
1488
1489	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1490
1491	if (bp->b_qindex != QUEUE_NONE)
1492		panic("bqrelse: free buffer onto another queue???");
1493	if (BUF_REFCNT(bp) > 1) {
1494		/* do not release to free list */
1495		BUF_UNLOCK(bp);
1496		splx(s);
1497		return;
1498	}
1499	mtx_lock(&bqlock);
1500	if (bp->b_flags & B_LOCKED) {
1501		bp->b_ioflags &= ~BIO_ERROR;
1502		bp->b_qindex = QUEUE_LOCKED;
1503		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1504		/* buffers with stale but valid contents */
1505	} else if (bp->b_flags & B_DELWRI) {
1506		bp->b_qindex = QUEUE_DIRTY;
1507		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1508	} else if (vm_page_count_severe()) {
1509		/*
1510		 * We are too low on memory, we have to try to free the
1511		 * buffer (most importantly: the wired pages making up its
1512		 * backing store) *now*.
1513		 */
1514		mtx_unlock(&bqlock);
1515		splx(s);
1516		brelse(bp);
1517		return;
1518	} else {
1519		bp->b_qindex = QUEUE_CLEAN;
1520		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1521	}
1522	mtx_unlock(&bqlock);
1523
1524	if ((bp->b_flags & B_LOCKED) == 0 &&
1525	    ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1526		bufcountwakeup();
1527	}
1528
1529	/*
1530	 * Something we can maybe free or reuse.
1531	 */
1532	if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1533		bufspacewakeup();
1534
1535	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1536	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1537		panic("bqrelse: not dirty");
1538	/* unlock */
1539	BUF_UNLOCK(bp);
1540	splx(s);
1541}
1542
1543/* Give pages used by the bp back to the VM system (where possible) */
1544static void
1545vfs_vmio_release(bp)
1546	struct buf *bp;
1547{
1548	int i;
1549	vm_page_t m;
1550
1551	GIANT_REQUIRED;
1552	vm_page_lock_queues();
1553	for (i = 0; i < bp->b_npages; i++) {
1554		m = bp->b_pages[i];
1555		bp->b_pages[i] = NULL;
1556		/*
1557		 * In order to keep page LRU ordering consistent, put
1558		 * everything on the inactive queue.
1559		 */
1560		vm_page_unwire(m, 0);
1561		/*
1562		 * We don't mess with busy pages, it is
1563		 * the responsibility of the process that
1564		 * busied the pages to deal with them.
1565		 */
1566		if ((m->flags & PG_BUSY) || (m->busy != 0))
1567			continue;
1568
1569		if (m->wire_count == 0) {
1570			vm_page_flag_clear(m, PG_ZERO);
1571			/*
1572			 * Might as well free the page if we can and it has
1573			 * no valid data.  We also free the page if the
1574			 * buffer was used for direct I/O
1575			 */
1576			if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1577			    m->hold_count == 0) {
1578				vm_page_busy(m);
1579				pmap_remove_all(m);
1580				vm_page_free(m);
1581			} else if (bp->b_flags & B_DIRECT) {
1582				vm_page_try_to_free(m);
1583			} else if (vm_page_count_severe()) {
1584				vm_page_try_to_cache(m);
1585			}
1586		}
1587	}
1588	vm_page_unlock_queues();
1589	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1590
1591	if (bp->b_bufsize) {
1592		bufspacewakeup();
1593		bp->b_bufsize = 0;
1594	}
1595	bp->b_npages = 0;
1596	bp->b_flags &= ~B_VMIO;
1597	if (bp->b_vp)
1598		brelvp(bp);
1599}
1600
1601/*
1602 * Check to see if a block at a particular lbn is available for a clustered
1603 * write.
1604 */
1605static int
1606vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1607{
1608	struct buf *bpa;
1609	int match;
1610
1611	match = 0;
1612
1613	/* If the buf isn't in core skip it */
1614	if ((bpa = gbincore(vp, lblkno)) == NULL)
1615		return (0);
1616
1617	/* If the buf is busy we don't want to wait for it */
1618	if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1619		return (0);
1620
1621	/* Only cluster with valid clusterable delayed write buffers */
1622	if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1623	    (B_DELWRI | B_CLUSTEROK))
1624		goto done;
1625
1626	if (bpa->b_bufsize != size)
1627		goto done;
1628
1629	/*
1630	 * Check to see if it is in the expected place on disk and that the
1631	 * block has been mapped.
1632	 */
1633	if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1634		match = 1;
1635done:
1636	BUF_UNLOCK(bpa);
1637	return (match);
1638}
1639
1640/*
1641 *	vfs_bio_awrite:
1642 *
1643 *	Implement clustered async writes for clearing out B_DELWRI buffers.
1644 *	This is much better then the old way of writing only one buffer at
1645 *	a time.  Note that we may not be presented with the buffers in the
1646 *	correct order, so we search for the cluster in both directions.
1647 */
1648int
1649vfs_bio_awrite(struct buf * bp)
1650{
1651	int i;
1652	int j;
1653	daddr_t lblkno = bp->b_lblkno;
1654	struct vnode *vp = bp->b_vp;
1655	int s;
1656	int ncl;
1657	int nwritten;
1658	int size;
1659	int maxcl;
1660
1661	s = splbio();
1662	/*
1663	 * right now we support clustered writing only to regular files.  If
1664	 * we find a clusterable block we could be in the middle of a cluster
1665	 * rather then at the beginning.
1666	 */
1667	if ((vp->v_type == VREG) &&
1668	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1669	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1670
1671		size = vp->v_mount->mnt_stat.f_iosize;
1672		maxcl = MAXPHYS / size;
1673
1674		VI_LOCK(vp);
1675		for (i = 1; i < maxcl; i++)
1676			if (vfs_bio_clcheck(vp, size, lblkno + i,
1677			    bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1678				break;
1679
1680		for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1681			if (vfs_bio_clcheck(vp, size, lblkno - j,
1682			    bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1683				break;
1684
1685		VI_UNLOCK(vp);
1686		--j;
1687		ncl = i + j;
1688		/*
1689		 * this is a possible cluster write
1690		 */
1691		if (ncl != 1) {
1692			BUF_UNLOCK(bp);
1693			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1694			splx(s);
1695			return nwritten;
1696		}
1697	}
1698
1699	bremfree(bp);
1700	bp->b_flags |= B_ASYNC;
1701
1702	splx(s);
1703	/*
1704	 * default (old) behavior, writing out only one block
1705	 *
1706	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1707	 */
1708	nwritten = bp->b_bufsize;
1709	(void) BUF_WRITE(bp);
1710
1711	return nwritten;
1712}
1713
1714/*
1715 *	getnewbuf:
1716 *
1717 *	Find and initialize a new buffer header, freeing up existing buffers
1718 *	in the bufqueues as necessary.  The new buffer is returned locked.
1719 *
1720 *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1721 *	buffer away, the caller must set B_INVAL prior to calling brelse().
1722 *
1723 *	We block if:
1724 *		We have insufficient buffer headers
1725 *		We have insufficient buffer space
1726 *		buffer_map is too fragmented ( space reservation fails )
1727 *		If we have to flush dirty buffers ( but we try to avoid this )
1728 *
1729 *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1730 *	Instead we ask the buf daemon to do it for us.  We attempt to
1731 *	avoid piecemeal wakeups of the pageout daemon.
1732 */
1733
1734static struct buf *
1735getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1736{
1737	struct buf *bp;
1738	struct buf *nbp;
1739	int defrag = 0;
1740	int nqindex;
1741	static int flushingbufs;
1742
1743	GIANT_REQUIRED;
1744
1745	/*
1746	 * We can't afford to block since we might be holding a vnode lock,
1747	 * which may prevent system daemons from running.  We deal with
1748	 * low-memory situations by proactively returning memory and running
1749	 * async I/O rather then sync I/O.
1750	 */
1751
1752	atomic_add_int(&getnewbufcalls, 1);
1753	atomic_subtract_int(&getnewbufrestarts, 1);
1754restart:
1755	atomic_add_int(&getnewbufrestarts, 1);
1756
1757	/*
1758	 * Setup for scan.  If we do not have enough free buffers,
1759	 * we setup a degenerate case that immediately fails.  Note
1760	 * that if we are specially marked process, we are allowed to
1761	 * dip into our reserves.
1762	 *
1763	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1764	 *
1765	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1766	 * However, there are a number of cases (defragging, reusing, ...)
1767	 * where we cannot backup.
1768	 */
1769	mtx_lock(&bqlock);
1770	nqindex = QUEUE_EMPTYKVA;
1771	nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1772
1773	if (nbp == NULL) {
1774		/*
1775		 * If no EMPTYKVA buffers and we are either
1776		 * defragging or reusing, locate a CLEAN buffer
1777		 * to free or reuse.  If bufspace useage is low
1778		 * skip this step so we can allocate a new buffer.
1779		 */
1780		if (defrag || bufspace >= lobufspace) {
1781			nqindex = QUEUE_CLEAN;
1782			nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1783		}
1784
1785		/*
1786		 * If we could not find or were not allowed to reuse a
1787		 * CLEAN buffer, check to see if it is ok to use an EMPTY
1788		 * buffer.  We can only use an EMPTY buffer if allocating
1789		 * its KVA would not otherwise run us out of buffer space.
1790		 */
1791		if (nbp == NULL && defrag == 0 &&
1792		    bufspace + maxsize < hibufspace) {
1793			nqindex = QUEUE_EMPTY;
1794			nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1795		}
1796	}
1797
1798	/*
1799	 * Run scan, possibly freeing data and/or kva mappings on the fly
1800	 * depending.
1801	 */
1802
1803	while ((bp = nbp) != NULL) {
1804		int qindex = nqindex;
1805
1806		/*
1807		 * Calculate next bp ( we can only use it if we do not block
1808		 * or do other fancy things ).
1809		 */
1810		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1811			switch(qindex) {
1812			case QUEUE_EMPTY:
1813				nqindex = QUEUE_EMPTYKVA;
1814				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1815					break;
1816				/* FALLTHROUGH */
1817			case QUEUE_EMPTYKVA:
1818				nqindex = QUEUE_CLEAN;
1819				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1820					break;
1821				/* FALLTHROUGH */
1822			case QUEUE_CLEAN:
1823				/*
1824				 * nbp is NULL.
1825				 */
1826				break;
1827			}
1828		}
1829
1830		/*
1831		 * Sanity Checks
1832		 */
1833		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1834
1835		/*
1836		 * Note: we no longer distinguish between VMIO and non-VMIO
1837		 * buffers.
1838		 */
1839
1840		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1841
1842		/*
1843		 * If we are defragging then we need a buffer with
1844		 * b_kvasize != 0.  XXX this situation should no longer
1845		 * occur, if defrag is non-zero the buffer's b_kvasize
1846		 * should also be non-zero at this point.  XXX
1847		 */
1848		if (defrag && bp->b_kvasize == 0) {
1849			printf("Warning: defrag empty buffer %p\n", bp);
1850			continue;
1851		}
1852
1853		/*
1854		 * Start freeing the bp.  This is somewhat involved.  nbp
1855		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1856		 */
1857
1858		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1859			panic("getnewbuf: locked buf");
1860		bremfreel(bp);
1861		mtx_unlock(&bqlock);
1862
1863		if (qindex == QUEUE_CLEAN) {
1864			if (bp->b_flags & B_VMIO) {
1865				bp->b_flags &= ~B_ASYNC;
1866				vfs_vmio_release(bp);
1867			}
1868			if (bp->b_vp)
1869				brelvp(bp);
1870		}
1871
1872		/*
1873		 * NOTE:  nbp is now entirely invalid.  We can only restart
1874		 * the scan from this point on.
1875		 *
1876		 * Get the rest of the buffer freed up.  b_kva* is still
1877		 * valid after this operation.
1878		 */
1879
1880		if (bp->b_rcred != NOCRED) {
1881			crfree(bp->b_rcred);
1882			bp->b_rcred = NOCRED;
1883		}
1884		if (bp->b_wcred != NOCRED) {
1885			crfree(bp->b_wcred);
1886			bp->b_wcred = NOCRED;
1887		}
1888		if (LIST_FIRST(&bp->b_dep) != NULL)
1889			buf_deallocate(bp);
1890		if (bp->b_xflags & BX_BKGRDINPROG)
1891			panic("losing buffer 3");
1892
1893		if (bp->b_bufsize)
1894			allocbuf(bp, 0);
1895
1896		bp->b_flags = 0;
1897		bp->b_ioflags = 0;
1898		bp->b_xflags = 0;
1899		bp->b_vflags = 0;
1900		bp->b_dev = NODEV;
1901		bp->b_vp = NULL;
1902		bp->b_blkno = bp->b_lblkno = 0;
1903		bp->b_offset = NOOFFSET;
1904		bp->b_iodone = 0;
1905		bp->b_error = 0;
1906		bp->b_resid = 0;
1907		bp->b_bcount = 0;
1908		bp->b_npages = 0;
1909		bp->b_dirtyoff = bp->b_dirtyend = 0;
1910		bp->b_magic = B_MAGIC_BIO;
1911		bp->b_op = &buf_ops_bio;
1912		bp->b_object = NULL;
1913
1914		LIST_INIT(&bp->b_dep);
1915
1916		/*
1917		 * If we are defragging then free the buffer.
1918		 */
1919		if (defrag) {
1920			bp->b_flags |= B_INVAL;
1921			bfreekva(bp);
1922			brelse(bp);
1923			defrag = 0;
1924			goto restart;
1925		}
1926
1927		/*
1928		 * If we are overcomitted then recover the buffer and its
1929		 * KVM space.  This occurs in rare situations when multiple
1930		 * processes are blocked in getnewbuf() or allocbuf().
1931		 */
1932		if (bufspace >= hibufspace)
1933			flushingbufs = 1;
1934		if (flushingbufs && bp->b_kvasize != 0) {
1935			bp->b_flags |= B_INVAL;
1936			bfreekva(bp);
1937			brelse(bp);
1938			goto restart;
1939		}
1940		if (bufspace < lobufspace)
1941			flushingbufs = 0;
1942		break;
1943	}
1944
1945	/*
1946	 * If we exhausted our list, sleep as appropriate.  We may have to
1947	 * wakeup various daemons and write out some dirty buffers.
1948	 *
1949	 * Generally we are sleeping due to insufficient buffer space.
1950	 */
1951
1952	if (bp == NULL) {
1953		int flags;
1954		char *waitmsg;
1955
1956		mtx_unlock(&bqlock);
1957		if (defrag) {
1958			flags = VFS_BIO_NEED_BUFSPACE;
1959			waitmsg = "nbufkv";
1960		} else if (bufspace >= hibufspace) {
1961			waitmsg = "nbufbs";
1962			flags = VFS_BIO_NEED_BUFSPACE;
1963		} else {
1964			waitmsg = "newbuf";
1965			flags = VFS_BIO_NEED_ANY;
1966		}
1967
1968		bd_speedup();	/* heeeelp */
1969
1970		mtx_lock(&nblock);
1971		needsbuffer |= flags;
1972		while (needsbuffer & flags) {
1973			if (msleep(&needsbuffer, &nblock,
1974			    (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
1975				mtx_unlock(&nblock);
1976				return (NULL);
1977			}
1978		}
1979		mtx_unlock(&nblock);
1980	} else {
1981		/*
1982		 * We finally have a valid bp.  We aren't quite out of the
1983		 * woods, we still have to reserve kva space.  In order
1984		 * to keep fragmentation sane we only allocate kva in
1985		 * BKVASIZE chunks.
1986		 */
1987		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1988
1989		if (maxsize != bp->b_kvasize) {
1990			vm_offset_t addr = 0;
1991
1992			bfreekva(bp);
1993
1994			if (vm_map_findspace(buffer_map,
1995				vm_map_min(buffer_map), maxsize, &addr)) {
1996				/*
1997				 * Uh oh.  Buffer map is to fragmented.  We
1998				 * must defragment the map.
1999				 */
2000				atomic_add_int(&bufdefragcnt, 1);
2001				defrag = 1;
2002				bp->b_flags |= B_INVAL;
2003				brelse(bp);
2004				goto restart;
2005			}
2006			if (addr) {
2007				vm_map_insert(buffer_map, NULL, 0,
2008					addr, addr + maxsize,
2009					VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
2010
2011				bp->b_kvabase = (caddr_t) addr;
2012				bp->b_kvasize = maxsize;
2013				atomic_add_int(&bufspace, bp->b_kvasize);
2014				atomic_add_int(&bufreusecnt, 1);
2015			}
2016		}
2017		bp->b_data = bp->b_kvabase;
2018	}
2019	return(bp);
2020}
2021
2022/*
2023 *	buf_daemon:
2024 *
2025 *	buffer flushing daemon.  Buffers are normally flushed by the
2026 *	update daemon but if it cannot keep up this process starts to
2027 *	take the load in an attempt to prevent getnewbuf() from blocking.
2028 */
2029
2030static struct proc *bufdaemonproc;
2031
2032static struct kproc_desc buf_kp = {
2033	"bufdaemon",
2034	buf_daemon,
2035	&bufdaemonproc
2036};
2037SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
2038
2039static void
2040buf_daemon()
2041{
2042	int s;
2043
2044	mtx_lock(&Giant);
2045
2046	/*
2047	 * This process needs to be suspended prior to shutdown sync.
2048	 */
2049	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2050	    SHUTDOWN_PRI_LAST);
2051
2052	/*
2053	 * This process is allowed to take the buffer cache to the limit
2054	 */
2055	s = splbio();
2056	mtx_lock(&bdlock);
2057
2058	for (;;) {
2059		bd_request = 0;
2060		mtx_unlock(&bdlock);
2061
2062		kthread_suspend_check(bufdaemonproc);
2063
2064		/*
2065		 * Do the flush.  Limit the amount of in-transit I/O we
2066		 * allow to build up, otherwise we would completely saturate
2067		 * the I/O system.  Wakeup any waiting processes before we
2068		 * normally would so they can run in parallel with our drain.
2069		 */
2070		while (numdirtybuffers > lodirtybuffers) {
2071			if (flushbufqueues(0) == 0) {
2072				/*
2073				 * Could not find any buffers without rollback
2074				 * dependencies, so just write the first one
2075				 * in the hopes of eventually making progress.
2076				 */
2077				flushbufqueues(1);
2078				break;
2079			}
2080			waitrunningbufspace();
2081			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2082		}
2083
2084		/*
2085		 * Only clear bd_request if we have reached our low water
2086		 * mark.  The buf_daemon normally waits 1 second and
2087		 * then incrementally flushes any dirty buffers that have
2088		 * built up, within reason.
2089		 *
2090		 * If we were unable to hit our low water mark and couldn't
2091		 * find any flushable buffers, we sleep half a second.
2092		 * Otherwise we loop immediately.
2093		 */
2094		mtx_lock(&bdlock);
2095		if (numdirtybuffers <= lodirtybuffers) {
2096			/*
2097			 * We reached our low water mark, reset the
2098			 * request and sleep until we are needed again.
2099			 * The sleep is just so the suspend code works.
2100			 */
2101			bd_request = 0;
2102			msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2103		} else {
2104			/*
2105			 * We couldn't find any flushable dirty buffers but
2106			 * still have too many dirty buffers, we
2107			 * have to sleep and try again.  (rare)
2108			 */
2109			msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2110		}
2111	}
2112}
2113
2114/*
2115 *	flushbufqueues:
2116 *
2117 *	Try to flush a buffer in the dirty queue.  We must be careful to
2118 *	free up B_INVAL buffers instead of write them, which NFS is
2119 *	particularly sensitive to.
2120 */
2121int flushwithdeps = 0;
2122SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2123    0, "Number of buffers flushed with dependecies that require rollbacks");
2124static int
2125flushbufqueues(int flushdeps)
2126{
2127	struct thread *td = curthread;
2128	struct vnode *vp;
2129	struct buf *bp;
2130	int hasdeps;
2131
2132	mtx_lock(&bqlock);
2133	TAILQ_FOREACH(bp, &bufqueues[QUEUE_DIRTY], b_freelist) {
2134		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2135			continue;
2136		KASSERT((bp->b_flags & B_DELWRI),
2137		    ("unexpected clean buffer %p", bp));
2138		if ((bp->b_xflags & BX_BKGRDINPROG) != 0) {
2139			BUF_UNLOCK(bp);
2140			continue;
2141		}
2142		if (bp->b_flags & B_INVAL) {
2143			bremfreel(bp);
2144			mtx_unlock(&bqlock);
2145			brelse(bp);
2146			return (1);
2147		}
2148
2149		if (LIST_FIRST(&bp->b_dep) != NULL && buf_countdeps(bp, 0)) {
2150			if (flushdeps == 0) {
2151				BUF_UNLOCK(bp);
2152				continue;
2153			}
2154			hasdeps = 1;
2155		} else
2156			hasdeps = 0;
2157		/*
2158		 * We must hold the lock on a vnode before writing
2159		 * one of its buffers. Otherwise we may confuse, or
2160		 * in the case of a snapshot vnode, deadlock the
2161		 * system.
2162		 *
2163		 * The lock order here is the reverse of the normal
2164		 * of vnode followed by buf lock.  This is ok because
2165		 * the NOWAIT will prevent deadlock.
2166		 */
2167		if ((vp = bp->b_vp) == NULL ||
2168		    vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT, td) == 0) {
2169			mtx_unlock(&bqlock);
2170			vfs_bio_awrite(bp);
2171			if (vp != NULL)
2172				VOP_UNLOCK(vp, 0, td);
2173			flushwithdeps += hasdeps;
2174			return (1);
2175		}
2176		BUF_UNLOCK(bp);
2177	}
2178	mtx_unlock(&bqlock);
2179	return (0);
2180}
2181
2182/*
2183 * Check to see if a block is currently memory resident.
2184 */
2185struct buf *
2186incore(struct vnode * vp, daddr_t blkno)
2187{
2188	struct buf *bp;
2189
2190	int s = splbio();
2191	VI_LOCK(vp);
2192	bp = gbincore(vp, blkno);
2193	VI_UNLOCK(vp);
2194	splx(s);
2195	return (bp);
2196}
2197
2198/*
2199 * Returns true if no I/O is needed to access the
2200 * associated VM object.  This is like incore except
2201 * it also hunts around in the VM system for the data.
2202 */
2203
2204int
2205inmem(struct vnode * vp, daddr_t blkno)
2206{
2207	vm_object_t obj;
2208	vm_offset_t toff, tinc, size;
2209	vm_page_t m;
2210	vm_ooffset_t off;
2211
2212	GIANT_REQUIRED;
2213	ASSERT_VOP_LOCKED(vp, "inmem");
2214
2215	if (incore(vp, blkno))
2216		return 1;
2217	if (vp->v_mount == NULL)
2218		return 0;
2219	if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_vflag & VV_OBJBUF) == 0)
2220		return 0;
2221
2222	size = PAGE_SIZE;
2223	if (size > vp->v_mount->mnt_stat.f_iosize)
2224		size = vp->v_mount->mnt_stat.f_iosize;
2225	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2226
2227	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2228		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
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
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}
2338
2339/*
2340 *	getblk:
2341 *
2342 *	Get a block given a specified block and offset into a file/device.
2343 *	The buffers B_DONE bit will be cleared on return, making it almost
2344 * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2345 *	return.  The caller should clear B_INVAL prior to initiating a
2346 *	READ.
2347 *
2348 *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2349 *	an existing buffer.
2350 *
2351 *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2352 *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2353 *	and then cleared based on the backing VM.  If the previous buffer is
2354 *	non-0-sized but invalid, B_CACHE will be cleared.
2355 *
2356 *	If getblk() must create a new buffer, the new buffer is returned with
2357 *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2358 *	case it is returned with B_INVAL clear and B_CACHE set based on the
2359 *	backing VM.
2360 *
2361 *	getblk() also forces a BUF_WRITE() for any B_DELWRI buffer whos
2362 *	B_CACHE bit is clear.
2363 *
2364 *	What this means, basically, is that the caller should use B_CACHE to
2365 *	determine whether the buffer is fully valid or not and should clear
2366 *	B_INVAL prior to issuing a read.  If the caller intends to validate
2367 *	the buffer by loading its data area with something, the caller needs
2368 *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2369 *	the caller should set B_CACHE ( as an optimization ), else the caller
2370 *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2371 *	a write attempt or if it was a successfull read.  If the caller
2372 *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2373 *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2374 */
2375struct buf *
2376getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2377    int flags)
2378{
2379	struct buf *bp;
2380	int s;
2381	int error;
2382	ASSERT_VOP_LOCKED(vp, "getblk");
2383
2384	if (size > MAXBSIZE)
2385		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2386
2387	s = splbio();
2388loop:
2389	/*
2390	 * Block if we are low on buffers.   Certain processes are allowed
2391	 * to completely exhaust the buffer cache.
2392         *
2393         * If this check ever becomes a bottleneck it may be better to
2394         * move it into the else, when gbincore() fails.  At the moment
2395         * it isn't a problem.
2396	 *
2397	 * XXX remove if 0 sections (clean this up after its proven)
2398         */
2399	if (numfreebuffers == 0) {
2400		if (curthread == PCPU_GET(idlethread))
2401			return NULL;
2402		mtx_lock(&nblock);
2403		needsbuffer |= VFS_BIO_NEED_ANY;
2404		mtx_unlock(&nblock);
2405	}
2406
2407	VI_LOCK(vp);
2408	if ((bp = gbincore(vp, blkno))) {
2409		int lockflags;
2410		/*
2411		 * Buffer is in-core.  If the buffer is not busy, it must
2412		 * be on a queue.
2413		 */
2414		lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2415
2416		if (flags & GB_LOCK_NOWAIT)
2417			lockflags |= LK_NOWAIT;
2418
2419		error = BUF_TIMELOCK(bp, lockflags,
2420		    VI_MTX(vp), "getblk", slpflag, slptimeo);
2421
2422		/*
2423		 * If we slept and got the lock we have to restart in case
2424		 * the buffer changed identities.
2425		 */
2426		if (error == ENOLCK)
2427			goto loop;
2428		/* We timed out or were interrupted. */
2429		else if (error)
2430			return (NULL);
2431
2432		/*
2433		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2434		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
2435		 * and for a VMIO buffer B_CACHE is adjusted according to the
2436		 * backing VM cache.
2437		 */
2438		if (bp->b_flags & B_INVAL)
2439			bp->b_flags &= ~B_CACHE;
2440		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2441			bp->b_flags |= B_CACHE;
2442		bremfree(bp);
2443
2444		/*
2445		 * check for size inconsistancies for non-VMIO case.
2446		 */
2447
2448		if (bp->b_bcount != size) {
2449			if ((bp->b_flags & B_VMIO) == 0 ||
2450			    (size > bp->b_kvasize)) {
2451				if (bp->b_flags & B_DELWRI) {
2452					bp->b_flags |= B_NOCACHE;
2453					BUF_WRITE(bp);
2454				} else {
2455					if ((bp->b_flags & B_VMIO) &&
2456					   (LIST_FIRST(&bp->b_dep) == NULL)) {
2457						bp->b_flags |= B_RELBUF;
2458						brelse(bp);
2459					} else {
2460						bp->b_flags |= B_NOCACHE;
2461						BUF_WRITE(bp);
2462					}
2463				}
2464				goto loop;
2465			}
2466		}
2467
2468		/*
2469		 * If the size is inconsistant in the VMIO case, we can resize
2470		 * the buffer.  This might lead to B_CACHE getting set or
2471		 * cleared.  If the size has not changed, B_CACHE remains
2472		 * unchanged from its previous state.
2473		 */
2474
2475		if (bp->b_bcount != size)
2476			allocbuf(bp, size);
2477
2478		KASSERT(bp->b_offset != NOOFFSET,
2479		    ("getblk: no buffer offset"));
2480
2481		/*
2482		 * A buffer with B_DELWRI set and B_CACHE clear must
2483		 * be committed before we can return the buffer in
2484		 * order to prevent the caller from issuing a read
2485		 * ( due to B_CACHE not being set ) and overwriting
2486		 * it.
2487		 *
2488		 * Most callers, including NFS and FFS, need this to
2489		 * operate properly either because they assume they
2490		 * can issue a read if B_CACHE is not set, or because
2491		 * ( for example ) an uncached B_DELWRI might loop due
2492		 * to softupdates re-dirtying the buffer.  In the latter
2493		 * case, B_CACHE is set after the first write completes,
2494		 * preventing further loops.
2495		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2496		 * above while extending the buffer, we cannot allow the
2497		 * buffer to remain with B_CACHE set after the write
2498		 * completes or it will represent a corrupt state.  To
2499		 * deal with this we set B_NOCACHE to scrap the buffer
2500		 * after the write.
2501		 *
2502		 * We might be able to do something fancy, like setting
2503		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2504		 * so the below call doesn't set B_CACHE, but that gets real
2505		 * confusing.  This is much easier.
2506		 */
2507
2508		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2509			bp->b_flags |= B_NOCACHE;
2510			BUF_WRITE(bp);
2511			goto loop;
2512		}
2513
2514		splx(s);
2515		bp->b_flags &= ~B_DONE;
2516	} else {
2517		int bsize, maxsize, vmio;
2518		off_t offset;
2519
2520		/*
2521		 * Buffer is not in-core, create new buffer.  The buffer
2522		 * returned by getnewbuf() is locked.  Note that the returned
2523		 * buffer is also considered valid (not marked B_INVAL).
2524		 */
2525		VI_UNLOCK(vp);
2526		if (vn_isdisk(vp, NULL))
2527			bsize = DEV_BSIZE;
2528		else if (vp->v_mountedhere)
2529			bsize = vp->v_mountedhere->mnt_stat.f_iosize;
2530		else if (vp->v_mount)
2531			bsize = vp->v_mount->mnt_stat.f_iosize;
2532		else
2533			bsize = size;
2534
2535		offset = blkno * bsize;
2536		vmio = (VOP_GETVOBJECT(vp, NULL) == 0) &&
2537		    (vp->v_vflag & VV_OBJBUF);
2538		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2539		maxsize = imax(maxsize, bsize);
2540
2541		if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2542			if (slpflag || slptimeo) {
2543				splx(s);
2544				return NULL;
2545			}
2546			goto loop;
2547		}
2548
2549		/*
2550		 * This code is used to make sure that a buffer is not
2551		 * created while the getnewbuf routine is blocked.
2552		 * This can be a problem whether the vnode is locked or not.
2553		 * If the buffer is created out from under us, we have to
2554		 * throw away the one we just created.  There is now window
2555		 * race because we are safely running at splbio() from the
2556		 * point of the duplicate buffer creation through to here,
2557		 * and we've locked the buffer.
2558		 *
2559		 * Note: this must occur before we associate the buffer
2560		 * with the vp especially considering limitations in
2561		 * the splay tree implementation when dealing with duplicate
2562		 * lblkno's.
2563		 */
2564		VI_LOCK(vp);
2565		if (gbincore(vp, blkno)) {
2566			VI_UNLOCK(vp);
2567			bp->b_flags |= B_INVAL;
2568			brelse(bp);
2569			goto loop;
2570		}
2571
2572		/*
2573		 * Insert the buffer into the hash, so that it can
2574		 * be found by incore.
2575		 */
2576		bp->b_blkno = bp->b_lblkno = blkno;
2577		bp->b_offset = offset;
2578
2579		bgetvp(vp, bp);
2580		VI_UNLOCK(vp);
2581
2582		/*
2583		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2584		 * buffer size starts out as 0, B_CACHE will be set by
2585		 * allocbuf() for the VMIO case prior to it testing the
2586		 * backing store for validity.
2587		 */
2588
2589		if (vmio) {
2590			bp->b_flags |= B_VMIO;
2591#if defined(VFS_BIO_DEBUG)
2592			if (vp->v_type != VREG)
2593				printf("getblk: vmioing file type %d???\n", vp->v_type);
2594#endif
2595			VOP_GETVOBJECT(vp, &bp->b_object);
2596		} else {
2597			bp->b_flags &= ~B_VMIO;
2598			bp->b_object = NULL;
2599		}
2600
2601		allocbuf(bp, size);
2602
2603		splx(s);
2604		bp->b_flags &= ~B_DONE;
2605	}
2606	KASSERT(BUF_REFCNT(bp) == 1, ("getblk: bp %p not locked",bp));
2607	return (bp);
2608}
2609
2610/*
2611 * Get an empty, disassociated buffer of given size.  The buffer is initially
2612 * set to B_INVAL.
2613 */
2614struct buf *
2615geteblk(int size)
2616{
2617	struct buf *bp;
2618	int s;
2619	int maxsize;
2620
2621	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2622
2623	s = splbio();
2624	while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2625		continue;
2626	splx(s);
2627	allocbuf(bp, size);
2628	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2629	KASSERT(BUF_REFCNT(bp) == 1, ("geteblk: bp %p not locked",bp));
2630	return (bp);
2631}
2632
2633
2634/*
2635 * This code constitutes the buffer memory from either anonymous system
2636 * memory (in the case of non-VMIO operations) or from an associated
2637 * VM object (in the case of VMIO operations).  This code is able to
2638 * resize a buffer up or down.
2639 *
2640 * Note that this code is tricky, and has many complications to resolve
2641 * deadlock or inconsistant data situations.  Tread lightly!!!
2642 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2643 * the caller.  Calling this code willy nilly can result in the loss of data.
2644 *
2645 * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2646 * B_CACHE for the non-VMIO case.
2647 */
2648
2649int
2650allocbuf(struct buf *bp, int size)
2651{
2652	int newbsize, mbsize;
2653	int i;
2654
2655	GIANT_REQUIRED;
2656
2657	if (BUF_REFCNT(bp) == 0)
2658		panic("allocbuf: buffer not busy");
2659
2660	if (bp->b_kvasize < size)
2661		panic("allocbuf: buffer too small");
2662
2663	if ((bp->b_flags & B_VMIO) == 0) {
2664		caddr_t origbuf;
2665		int origbufsize;
2666		/*
2667		 * Just get anonymous memory from the kernel.  Don't
2668		 * mess with B_CACHE.
2669		 */
2670		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2671		if (bp->b_flags & B_MALLOC)
2672			newbsize = mbsize;
2673		else
2674			newbsize = round_page(size);
2675
2676		if (newbsize < bp->b_bufsize) {
2677			/*
2678			 * malloced buffers are not shrunk
2679			 */
2680			if (bp->b_flags & B_MALLOC) {
2681				if (newbsize) {
2682					bp->b_bcount = size;
2683				} else {
2684					free(bp->b_data, M_BIOBUF);
2685					if (bp->b_bufsize) {
2686						atomic_subtract_int(
2687						    &bufmallocspace,
2688						    bp->b_bufsize);
2689						bufspacewakeup();
2690						bp->b_bufsize = 0;
2691					}
2692					bp->b_data = bp->b_kvabase;
2693					bp->b_bcount = 0;
2694					bp->b_flags &= ~B_MALLOC;
2695				}
2696				return 1;
2697			}
2698			vm_hold_free_pages(
2699			    bp,
2700			    (vm_offset_t) bp->b_data + newbsize,
2701			    (vm_offset_t) bp->b_data + bp->b_bufsize);
2702		} else if (newbsize > bp->b_bufsize) {
2703			/*
2704			 * We only use malloced memory on the first allocation.
2705			 * and revert to page-allocated memory when the buffer
2706			 * grows.
2707			 */
2708			/*
2709			 * There is a potential smp race here that could lead
2710			 * to bufmallocspace slightly passing the max.  It
2711			 * is probably extremely rare and not worth worrying
2712			 * over.
2713			 */
2714			if ( (bufmallocspace < maxbufmallocspace) &&
2715				(bp->b_bufsize == 0) &&
2716				(mbsize <= PAGE_SIZE/2)) {
2717
2718				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2719				bp->b_bufsize = mbsize;
2720				bp->b_bcount = size;
2721				bp->b_flags |= B_MALLOC;
2722				atomic_add_int(&bufmallocspace, mbsize);
2723				return 1;
2724			}
2725			origbuf = NULL;
2726			origbufsize = 0;
2727			/*
2728			 * If the buffer is growing on its other-than-first allocation,
2729			 * then we revert to the page-allocation scheme.
2730			 */
2731			if (bp->b_flags & B_MALLOC) {
2732				origbuf = bp->b_data;
2733				origbufsize = bp->b_bufsize;
2734				bp->b_data = bp->b_kvabase;
2735				if (bp->b_bufsize) {
2736					atomic_subtract_int(&bufmallocspace,
2737					    bp->b_bufsize);
2738					bufspacewakeup();
2739					bp->b_bufsize = 0;
2740				}
2741				bp->b_flags &= ~B_MALLOC;
2742				newbsize = round_page(newbsize);
2743			}
2744			vm_hold_load_pages(
2745			    bp,
2746			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2747			    (vm_offset_t) bp->b_data + newbsize);
2748			if (origbuf) {
2749				bcopy(origbuf, bp->b_data, origbufsize);
2750				free(origbuf, M_BIOBUF);
2751			}
2752		}
2753	} else {
2754		int desiredpages;
2755
2756		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2757		desiredpages = (size == 0) ? 0 :
2758			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2759
2760		if (bp->b_flags & B_MALLOC)
2761			panic("allocbuf: VMIO buffer can't be malloced");
2762		/*
2763		 * Set B_CACHE initially if buffer is 0 length or will become
2764		 * 0-length.
2765		 */
2766		if (size == 0 || bp->b_bufsize == 0)
2767			bp->b_flags |= B_CACHE;
2768
2769		if (newbsize < bp->b_bufsize) {
2770			/*
2771			 * DEV_BSIZE aligned new buffer size is less then the
2772			 * DEV_BSIZE aligned existing buffer size.  Figure out
2773			 * if we have to remove any pages.
2774			 */
2775			if (desiredpages < bp->b_npages) {
2776				vm_page_t m;
2777
2778				vm_page_lock_queues();
2779				for (i = desiredpages; i < bp->b_npages; i++) {
2780					/*
2781					 * the page is not freed here -- it
2782					 * is the responsibility of
2783					 * vnode_pager_setsize
2784					 */
2785					m = bp->b_pages[i];
2786					KASSERT(m != bogus_page,
2787					    ("allocbuf: bogus page found"));
2788					while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
2789						vm_page_lock_queues();
2790
2791					bp->b_pages[i] = NULL;
2792					vm_page_unwire(m, 0);
2793				}
2794				vm_page_unlock_queues();
2795				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2796				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2797				bp->b_npages = desiredpages;
2798			}
2799		} else if (size > bp->b_bcount) {
2800			/*
2801			 * We are growing the buffer, possibly in a
2802			 * byte-granular fashion.
2803			 */
2804			struct vnode *vp;
2805			vm_object_t obj;
2806			vm_offset_t toff;
2807			vm_offset_t tinc;
2808
2809			/*
2810			 * Step 1, bring in the VM pages from the object,
2811			 * allocating them if necessary.  We must clear
2812			 * B_CACHE if these pages are not valid for the
2813			 * range covered by the buffer.
2814			 */
2815
2816			vp = bp->b_vp;
2817			obj = bp->b_object;
2818
2819			while (bp->b_npages < desiredpages) {
2820				vm_page_t m;
2821				vm_pindex_t pi;
2822
2823				pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2824				if ((m = vm_page_lookup(obj, pi)) == NULL) {
2825					/*
2826					 * note: must allocate system pages
2827					 * since blocking here could intefere
2828					 * with paging I/O, no matter which
2829					 * process we are.
2830					 */
2831					m = vm_page_alloc(obj, pi,
2832					    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
2833					if (m == NULL) {
2834						atomic_add_int(&vm_pageout_deficit,
2835						    desiredpages - bp->b_npages);
2836						VM_WAIT;
2837					} else {
2838						vm_page_lock_queues();
2839						vm_page_wakeup(m);
2840						vm_page_unlock_queues();
2841						bp->b_flags &= ~B_CACHE;
2842						bp->b_pages[bp->b_npages] = m;
2843						++bp->b_npages;
2844					}
2845					continue;
2846				}
2847
2848				/*
2849				 * We found a page.  If we have to sleep on it,
2850				 * retry because it might have gotten freed out
2851				 * from under us.
2852				 *
2853				 * We can only test PG_BUSY here.  Blocking on
2854				 * m->busy might lead to a deadlock:
2855				 *
2856				 *  vm_fault->getpages->cluster_read->allocbuf
2857				 *
2858				 */
2859				vm_page_lock_queues();
2860				if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
2861					continue;
2862
2863				/*
2864				 * We have a good page.  Should we wakeup the
2865				 * page daemon?
2866				 */
2867				if ((curproc != pageproc) &&
2868				    ((m->queue - m->pc) == PQ_CACHE) &&
2869				    ((cnt.v_free_count + cnt.v_cache_count) <
2870					(cnt.v_free_min + cnt.v_cache_min))) {
2871					pagedaemon_wakeup();
2872				}
2873				vm_page_flag_clear(m, PG_ZERO);
2874				vm_page_wire(m);
2875				vm_page_unlock_queues();
2876				bp->b_pages[bp->b_npages] = m;
2877				++bp->b_npages;
2878			}
2879
2880			/*
2881			 * Step 2.  We've loaded the pages into the buffer,
2882			 * we have to figure out if we can still have B_CACHE
2883			 * set.  Note that B_CACHE is set according to the
2884			 * byte-granular range ( bcount and size ), new the
2885			 * aligned range ( newbsize ).
2886			 *
2887			 * The VM test is against m->valid, which is DEV_BSIZE
2888			 * aligned.  Needless to say, the validity of the data
2889			 * needs to also be DEV_BSIZE aligned.  Note that this
2890			 * fails with NFS if the server or some other client
2891			 * extends the file's EOF.  If our buffer is resized,
2892			 * B_CACHE may remain set! XXX
2893			 */
2894
2895			toff = bp->b_bcount;
2896			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2897
2898			while ((bp->b_flags & B_CACHE) && toff < size) {
2899				vm_pindex_t pi;
2900
2901				if (tinc > (size - toff))
2902					tinc = size - toff;
2903
2904				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2905				    PAGE_SHIFT;
2906
2907				vfs_buf_test_cache(
2908				    bp,
2909				    bp->b_offset,
2910				    toff,
2911				    tinc,
2912				    bp->b_pages[pi]
2913				);
2914				toff += tinc;
2915				tinc = PAGE_SIZE;
2916			}
2917
2918			/*
2919			 * Step 3, fixup the KVM pmap.  Remember that
2920			 * bp->b_data is relative to bp->b_offset, but
2921			 * bp->b_offset may be offset into the first page.
2922			 */
2923
2924			bp->b_data = (caddr_t)
2925			    trunc_page((vm_offset_t)bp->b_data);
2926			pmap_qenter(
2927			    (vm_offset_t)bp->b_data,
2928			    bp->b_pages,
2929			    bp->b_npages
2930			);
2931
2932			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2933			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
2934		}
2935	}
2936	if (newbsize < bp->b_bufsize)
2937		bufspacewakeup();
2938	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
2939	bp->b_bcount = size;		/* requested buffer size	*/
2940	return 1;
2941}
2942
2943void
2944biodone(struct bio *bp)
2945{
2946	mtx_lock(&bdonelock);
2947	bp->bio_flags |= BIO_DONE;
2948	if (bp->bio_done == NULL)
2949		wakeup(bp);
2950	mtx_unlock(&bdonelock);
2951	if (bp->bio_done != NULL)
2952		bp->bio_done(bp);
2953}
2954
2955/*
2956 * Wait for a BIO to finish.
2957 *
2958 * XXX: resort to a timeout for now.  The optimal locking (if any) for this
2959 * case is not yet clear.
2960 */
2961int
2962biowait(struct bio *bp, const char *wchan)
2963{
2964
2965	mtx_lock(&bdonelock);
2966	while ((bp->bio_flags & BIO_DONE) == 0)
2967		msleep(bp, &bdonelock, PRIBIO, wchan, hz / 10);
2968	mtx_unlock(&bdonelock);
2969	if (bp->bio_error != 0)
2970		return (bp->bio_error);
2971	if (!(bp->bio_flags & BIO_ERROR))
2972		return (0);
2973	return (EIO);
2974}
2975
2976void
2977biofinish(struct bio *bp, struct devstat *stat, int error)
2978{
2979
2980	if (error) {
2981		bp->bio_error = error;
2982		bp->bio_flags |= BIO_ERROR;
2983	}
2984	if (stat != NULL)
2985		devstat_end_transaction_bio(stat, bp);
2986	biodone(bp);
2987}
2988
2989/*
2990 *	bufwait:
2991 *
2992 *	Wait for buffer I/O completion, returning error status.  The buffer
2993 *	is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
2994 *	error and cleared.
2995 */
2996int
2997bufwait(register struct buf * bp)
2998{
2999	int s;
3000
3001	s = splbio();
3002	if (bp->b_iocmd == BIO_READ)
3003		bwait(bp, PRIBIO, "biord");
3004	else
3005		bwait(bp, PRIBIO, "biowr");
3006	splx(s);
3007	if (bp->b_flags & B_EINTR) {
3008		bp->b_flags &= ~B_EINTR;
3009		return (EINTR);
3010	}
3011	if (bp->b_ioflags & BIO_ERROR) {
3012		return (bp->b_error ? bp->b_error : EIO);
3013	} else {
3014		return (0);
3015	}
3016}
3017
3018 /*
3019  * Call back function from struct bio back up to struct buf.
3020  * The corresponding initialization lives in sys/conf.h:DEV_STRATEGY().
3021  */
3022void
3023bufdonebio(struct bio *bp)
3024{
3025	bufdone(bp->bio_caller2);
3026}
3027
3028/*
3029 *	bufdone:
3030 *
3031 *	Finish I/O on a buffer, optionally calling a completion function.
3032 *	This is usually called from an interrupt so process blocking is
3033 *	not allowed.
3034 *
3035 *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3036 *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3037 *	assuming B_INVAL is clear.
3038 *
3039 *	For the VMIO case, we set B_CACHE if the op was a read and no
3040 *	read error occured, or if the op was a write.  B_CACHE is never
3041 *	set if the buffer is invalid or otherwise uncacheable.
3042 *
3043 *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3044 *	initiator to leave B_INVAL set to brelse the buffer out of existance
3045 *	in the biodone routine.
3046 */
3047void
3048bufdone(struct buf *bp)
3049{
3050	int s;
3051	void    (*biodone)(struct buf *);
3052
3053	GIANT_REQUIRED;
3054
3055	s = splbio();
3056
3057	KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
3058	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3059
3060	bp->b_flags |= B_DONE;
3061	runningbufwakeup(bp);
3062
3063	if (bp->b_iocmd == BIO_DELETE) {
3064		brelse(bp);
3065		splx(s);
3066		return;
3067	}
3068
3069	if (bp->b_iocmd == BIO_WRITE) {
3070		vwakeup(bp);
3071	}
3072
3073	/* call optional completion function if requested */
3074	if (bp->b_iodone != NULL) {
3075		biodone = bp->b_iodone;
3076		bp->b_iodone = NULL;
3077		(*biodone) (bp);
3078		splx(s);
3079		return;
3080	}
3081	if (LIST_FIRST(&bp->b_dep) != NULL)
3082		buf_complete(bp);
3083
3084	if (bp->b_flags & B_VMIO) {
3085		int i;
3086		vm_ooffset_t foff;
3087		vm_page_t m;
3088		vm_object_t obj;
3089		int iosize;
3090		struct vnode *vp = bp->b_vp;
3091
3092		obj = bp->b_object;
3093
3094#if defined(VFS_BIO_DEBUG)
3095		mp_fixme("usecount and vflag accessed without locks.");
3096		if (vp->v_usecount == 0) {
3097			panic("biodone: zero vnode ref count");
3098		}
3099
3100		if ((vp->v_vflag & VV_OBJBUF) == 0) {
3101			panic("biodone: vnode is not setup for merged cache");
3102		}
3103#endif
3104
3105		foff = bp->b_offset;
3106		KASSERT(bp->b_offset != NOOFFSET,
3107		    ("biodone: no buffer offset"));
3108
3109#if defined(VFS_BIO_DEBUG)
3110		if (obj->paging_in_progress < bp->b_npages) {
3111			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3112			    obj->paging_in_progress, bp->b_npages);
3113		}
3114#endif
3115
3116		/*
3117		 * Set B_CACHE if the op was a normal read and no error
3118		 * occured.  B_CACHE is set for writes in the b*write()
3119		 * routines.
3120		 */
3121		iosize = bp->b_bcount - bp->b_resid;
3122		if (bp->b_iocmd == BIO_READ &&
3123		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3124		    !(bp->b_ioflags & BIO_ERROR)) {
3125			bp->b_flags |= B_CACHE;
3126		}
3127		vm_page_lock_queues();
3128		for (i = 0; i < bp->b_npages; i++) {
3129			int bogusflag = 0;
3130			int resid;
3131
3132			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3133			if (resid > iosize)
3134				resid = iosize;
3135
3136			/*
3137			 * cleanup bogus pages, restoring the originals
3138			 */
3139			m = bp->b_pages[i];
3140			if (m == bogus_page) {
3141				bogusflag = 1;
3142				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3143				if (m == NULL)
3144					panic("biodone: page disappeared!");
3145				bp->b_pages[i] = m;
3146				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3147			}
3148#if defined(VFS_BIO_DEBUG)
3149			if (OFF_TO_IDX(foff) != m->pindex) {
3150				printf(
3151"biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3152				    (intmax_t)foff, (uintmax_t)m->pindex);
3153			}
3154#endif
3155
3156			/*
3157			 * In the write case, the valid and clean bits are
3158			 * already changed correctly ( see bdwrite() ), so we
3159			 * only need to do this here in the read case.
3160			 */
3161			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3162				vfs_page_set_valid(bp, foff, i, m);
3163			}
3164			vm_page_flag_clear(m, PG_ZERO);
3165
3166			/*
3167			 * when debugging new filesystems or buffer I/O methods, this
3168			 * is the most common error that pops up.  if you see this, you
3169			 * have not set the page busy flag correctly!!!
3170			 */
3171			if (m->busy == 0) {
3172				printf("biodone: page busy < 0, "
3173				    "pindex: %d, foff: 0x(%x,%x), "
3174				    "resid: %d, index: %d\n",
3175				    (int) m->pindex, (int)(foff >> 32),
3176						(int) foff & 0xffffffff, resid, i);
3177				if (!vn_isdisk(vp, NULL))
3178					printf(" iosize: %ld, lblkno: %jd, flags: 0x%x, npages: %d\n",
3179					    bp->b_vp->v_mount->mnt_stat.f_iosize,
3180					    (intmax_t) bp->b_lblkno,
3181					    bp->b_flags, bp->b_npages);
3182				else
3183					printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3184					    (intmax_t) bp->b_lblkno,
3185					    bp->b_flags, bp->b_npages);
3186				printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3187				    m->valid, m->dirty, m->wire_count);
3188				panic("biodone: page busy < 0\n");
3189			}
3190			vm_page_io_finish(m);
3191			vm_object_pip_subtract(obj, 1);
3192			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3193			iosize -= resid;
3194		}
3195		vm_page_unlock_queues();
3196		if (obj)
3197			vm_object_pip_wakeupn(obj, 0);
3198	}
3199
3200	/*
3201	 * For asynchronous completions, release the buffer now. The brelse
3202	 * will do a wakeup there if necessary - so no need to do a wakeup
3203	 * here in the async case. The sync case always needs to do a wakeup.
3204	 */
3205
3206	if (bp->b_flags & B_ASYNC) {
3207		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3208			brelse(bp);
3209		else
3210			bqrelse(bp);
3211	} else {
3212		bdone(bp);
3213	}
3214	splx(s);
3215}
3216
3217/*
3218 * This routine is called in lieu of iodone in the case of
3219 * incomplete I/O.  This keeps the busy status for pages
3220 * consistant.
3221 */
3222void
3223vfs_unbusy_pages(struct buf * bp)
3224{
3225	int i;
3226
3227	GIANT_REQUIRED;
3228
3229	runningbufwakeup(bp);
3230	if (bp->b_flags & B_VMIO) {
3231		vm_object_t obj;
3232
3233		obj = bp->b_object;
3234		vm_page_lock_queues();
3235		for (i = 0; i < bp->b_npages; i++) {
3236			vm_page_t m = bp->b_pages[i];
3237
3238			if (m == bogus_page) {
3239				m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3240				if (!m) {
3241					panic("vfs_unbusy_pages: page missing\n");
3242				}
3243				bp->b_pages[i] = m;
3244				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3245			}
3246			vm_object_pip_subtract(obj, 1);
3247			vm_page_flag_clear(m, PG_ZERO);
3248			vm_page_io_finish(m);
3249		}
3250		vm_page_unlock_queues();
3251		vm_object_pip_wakeupn(obj, 0);
3252	}
3253}
3254
3255/*
3256 * vfs_page_set_valid:
3257 *
3258 *	Set the valid bits in a page based on the supplied offset.   The
3259 *	range is restricted to the buffer's size.
3260 *
3261 *	This routine is typically called after a read completes.
3262 */
3263static void
3264vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3265{
3266	vm_ooffset_t soff, eoff;
3267
3268	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3269	/*
3270	 * Start and end offsets in buffer.  eoff - soff may not cross a
3271	 * page boundry or cross the end of the buffer.  The end of the
3272	 * buffer, in this case, is our file EOF, not the allocation size
3273	 * of the buffer.
3274	 */
3275	soff = off;
3276	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3277	if (eoff > bp->b_offset + bp->b_bcount)
3278		eoff = bp->b_offset + bp->b_bcount;
3279
3280	/*
3281	 * Set valid range.  This is typically the entire buffer and thus the
3282	 * entire page.
3283	 */
3284	if (eoff > soff) {
3285		vm_page_set_validclean(
3286		    m,
3287		   (vm_offset_t) (soff & PAGE_MASK),
3288		   (vm_offset_t) (eoff - soff)
3289		);
3290	}
3291}
3292
3293/*
3294 * This routine is called before a device strategy routine.
3295 * It is used to tell the VM system that paging I/O is in
3296 * progress, and treat the pages associated with the buffer
3297 * almost as being PG_BUSY.  Also the object paging_in_progress
3298 * flag is handled to make sure that the object doesn't become
3299 * inconsistant.
3300 *
3301 * Since I/O has not been initiated yet, certain buffer flags
3302 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3303 * and should be ignored.
3304 */
3305void
3306vfs_busy_pages(struct buf * bp, int clear_modify)
3307{
3308	int i, bogus;
3309
3310	if (bp->b_flags & B_VMIO) {
3311		vm_object_t obj;
3312		vm_ooffset_t foff;
3313
3314		obj = bp->b_object;
3315		foff = bp->b_offset;
3316		KASSERT(bp->b_offset != NOOFFSET,
3317		    ("vfs_busy_pages: no buffer offset"));
3318		vfs_setdirty(bp);
3319retry:
3320		vm_page_lock_queues();
3321		for (i = 0; i < bp->b_npages; i++) {
3322			vm_page_t m = bp->b_pages[i];
3323
3324			if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3325				goto retry;
3326		}
3327		bogus = 0;
3328		for (i = 0; i < bp->b_npages; i++) {
3329			vm_page_t m = bp->b_pages[i];
3330
3331			vm_page_flag_clear(m, PG_ZERO);
3332			if ((bp->b_flags & B_CLUSTER) == 0) {
3333				vm_object_pip_add(obj, 1);
3334				vm_page_io_start(m);
3335			}
3336			/*
3337			 * When readying a buffer for a read ( i.e
3338			 * clear_modify == 0 ), it is important to do
3339			 * bogus_page replacement for valid pages in
3340			 * partially instantiated buffers.  Partially
3341			 * instantiated buffers can, in turn, occur when
3342			 * reconstituting a buffer from its VM backing store
3343			 * base.  We only have to do this if B_CACHE is
3344			 * clear ( which causes the I/O to occur in the
3345			 * first place ).  The replacement prevents the read
3346			 * I/O from overwriting potentially dirty VM-backed
3347			 * pages.  XXX bogus page replacement is, uh, bogus.
3348			 * It may not work properly with small-block devices.
3349			 * We need to find a better way.
3350			 */
3351			pmap_remove_all(m);
3352			if (clear_modify)
3353				vfs_page_set_valid(bp, foff, i, m);
3354			else if (m->valid == VM_PAGE_BITS_ALL &&
3355				(bp->b_flags & B_CACHE) == 0) {
3356				bp->b_pages[i] = bogus_page;
3357				bogus++;
3358			}
3359			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3360		}
3361		vm_page_unlock_queues();
3362		if (bogus)
3363			pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3364	}
3365}
3366
3367/*
3368 * Tell the VM system that the pages associated with this buffer
3369 * are clean.  This is used for delayed writes where the data is
3370 * going to go to disk eventually without additional VM intevention.
3371 *
3372 * Note that while we only really need to clean through to b_bcount, we
3373 * just go ahead and clean through to b_bufsize.
3374 */
3375static void
3376vfs_clean_pages(struct buf * bp)
3377{
3378	int i;
3379
3380	GIANT_REQUIRED;
3381
3382	if (bp->b_flags & B_VMIO) {
3383		vm_ooffset_t foff;
3384
3385		foff = bp->b_offset;
3386		KASSERT(bp->b_offset != NOOFFSET,
3387		    ("vfs_clean_pages: no buffer offset"));
3388		vm_page_lock_queues();
3389		for (i = 0; i < bp->b_npages; i++) {
3390			vm_page_t m = bp->b_pages[i];
3391			vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3392			vm_ooffset_t eoff = noff;
3393
3394			if (eoff > bp->b_offset + bp->b_bufsize)
3395				eoff = bp->b_offset + bp->b_bufsize;
3396			vfs_page_set_valid(bp, foff, i, m);
3397			/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3398			foff = noff;
3399		}
3400		vm_page_unlock_queues();
3401	}
3402}
3403
3404/*
3405 *	vfs_bio_set_validclean:
3406 *
3407 *	Set the range within the buffer to valid and clean.  The range is
3408 *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3409 *	itself may be offset from the beginning of the first page.
3410 *
3411 */
3412
3413void
3414vfs_bio_set_validclean(struct buf *bp, int base, int size)
3415{
3416	if (bp->b_flags & B_VMIO) {
3417		int i;
3418		int n;
3419
3420		/*
3421		 * Fixup base to be relative to beginning of first page.
3422		 * Set initial n to be the maximum number of bytes in the
3423		 * first page that can be validated.
3424		 */
3425
3426		base += (bp->b_offset & PAGE_MASK);
3427		n = PAGE_SIZE - (base & PAGE_MASK);
3428
3429		vm_page_lock_queues();
3430		for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3431			vm_page_t m = bp->b_pages[i];
3432
3433			if (n > size)
3434				n = size;
3435
3436			vm_page_set_validclean(m, base & PAGE_MASK, n);
3437			base += n;
3438			size -= n;
3439			n = PAGE_SIZE;
3440		}
3441		vm_page_unlock_queues();
3442	}
3443}
3444
3445/*
3446 *	vfs_bio_clrbuf:
3447 *
3448 *	clear a buffer.  This routine essentially fakes an I/O, so we need
3449 *	to clear BIO_ERROR and B_INVAL.
3450 *
3451 *	Note that while we only theoretically need to clear through b_bcount,
3452 *	we go ahead and clear through b_bufsize.
3453 */
3454
3455void
3456vfs_bio_clrbuf(struct buf *bp)
3457{
3458	int i, mask = 0;
3459	caddr_t sa, ea;
3460
3461	GIANT_REQUIRED;
3462
3463	if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3464		bp->b_flags &= ~B_INVAL;
3465		bp->b_ioflags &= ~BIO_ERROR;
3466		if( (bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3467		    (bp->b_offset & PAGE_MASK) == 0) {
3468			mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3469			if ((bp->b_pages[0]->valid & mask) == mask) {
3470				bp->b_resid = 0;
3471				return;
3472			}
3473			if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3474			    ((bp->b_pages[0]->valid & mask) == 0)) {
3475				bzero(bp->b_data, bp->b_bufsize);
3476				bp->b_pages[0]->valid |= mask;
3477				bp->b_resid = 0;
3478				return;
3479			}
3480		}
3481		ea = sa = bp->b_data;
3482		for(i=0;i<bp->b_npages;i++,sa=ea) {
3483			int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3484			ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3485			ea = (caddr_t)(vm_offset_t)ulmin(
3486			    (u_long)(vm_offset_t)ea,
3487			    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3488			mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3489			if ((bp->b_pages[i]->valid & mask) == mask)
3490				continue;
3491			if ((bp->b_pages[i]->valid & mask) == 0) {
3492				if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
3493					bzero(sa, ea - sa);
3494				}
3495			} else {
3496				for (; sa < ea; sa += DEV_BSIZE, j++) {
3497					if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3498						(bp->b_pages[i]->valid & (1<<j)) == 0)
3499						bzero(sa, DEV_BSIZE);
3500				}
3501			}
3502			bp->b_pages[i]->valid |= mask;
3503			vm_page_lock_queues();
3504			vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3505			vm_page_unlock_queues();
3506		}
3507		bp->b_resid = 0;
3508	} else {
3509		clrbuf(bp);
3510	}
3511}
3512
3513/*
3514 * vm_hold_load_pages and vm_hold_free_pages get pages into
3515 * a buffers address space.  The pages are anonymous and are
3516 * not associated with a file object.
3517 */
3518static void
3519vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3520{
3521	vm_offset_t pg;
3522	vm_page_t p;
3523	int index;
3524
3525	GIANT_REQUIRED;
3526
3527	to = round_page(to);
3528	from = round_page(from);
3529	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3530
3531	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3532tryagain:
3533		/*
3534		 * note: must allocate system pages since blocking here
3535		 * could intefere with paging I/O, no matter which
3536		 * process we are.
3537		 */
3538		vm_object_lock(kernel_object);
3539		p = vm_page_alloc(kernel_object,
3540			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3541		    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3542		vm_object_unlock(kernel_object);
3543		if (!p) {
3544			atomic_add_int(&vm_pageout_deficit,
3545			    (to - pg) >> PAGE_SHIFT);
3546			VM_WAIT;
3547			goto tryagain;
3548		}
3549		vm_page_lock_queues();
3550		p->valid = VM_PAGE_BITS_ALL;
3551		vm_page_unlock_queues();
3552		pmap_qenter(pg, &p, 1);
3553		bp->b_pages[index] = p;
3554		vm_page_lock_queues();
3555		vm_page_wakeup(p);
3556		vm_page_unlock_queues();
3557	}
3558	bp->b_npages = index;
3559}
3560
3561/* Return pages associated with this buf to the vm system */
3562static void
3563vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3564{
3565	vm_offset_t pg;
3566	vm_page_t p;
3567	int index, newnpages;
3568
3569	GIANT_REQUIRED;
3570
3571	from = round_page(from);
3572	to = round_page(to);
3573	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3574
3575	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3576		p = bp->b_pages[index];
3577		if (p && (index < bp->b_npages)) {
3578			if (p->busy) {
3579				printf(
3580			    "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3581				    (intmax_t)bp->b_blkno,
3582				    (intmax_t)bp->b_lblkno);
3583			}
3584			bp->b_pages[index] = NULL;
3585			pmap_qremove(pg, 1);
3586			vm_page_lock_queues();
3587			vm_page_busy(p);
3588			vm_page_unwire(p, 0);
3589			vm_page_free(p);
3590			vm_page_unlock_queues();
3591		}
3592	}
3593	bp->b_npages = newnpages;
3594}
3595
3596/*
3597 * Map an IO request into kernel virtual address space.
3598 *
3599 * All requests are (re)mapped into kernel VA space.
3600 * Notice that we use b_bufsize for the size of the buffer
3601 * to be mapped.  b_bcount might be modified by the driver.
3602 *
3603 * Note that even if the caller determines that the address space should
3604 * be valid, a race or a smaller-file mapped into a larger space may
3605 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3606 * check the return value.
3607 */
3608int
3609vmapbuf(struct buf *bp)
3610{
3611	caddr_t addr, kva;
3612	vm_paddr_t pa;
3613	int pidx, i;
3614	struct vm_page *m;
3615	struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3616
3617	GIANT_REQUIRED;
3618
3619	if ((bp->b_flags & B_PHYS) == 0)
3620		panic("vmapbuf");
3621
3622	for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3623	     addr < bp->b_data + bp->b_bufsize;
3624	     addr += PAGE_SIZE, pidx++) {
3625		/*
3626		 * Do the vm_fault if needed; do the copy-on-write thing
3627		 * when reading stuff off device into memory.
3628		 *
3629		 * NOTE! Must use pmap_extract() because addr may be in
3630		 * the userland address space, and kextract is only guarenteed
3631		 * to work for the kernland address space (see: sparc64 port).
3632		 */
3633retry:
3634		i = vm_fault_quick((addr >= bp->b_data) ? addr : bp->b_data,
3635			(bp->b_iocmd == BIO_READ) ?
3636			(VM_PROT_READ|VM_PROT_WRITE) : VM_PROT_READ);
3637		if (i < 0) {
3638			printf("vmapbuf: warning, bad user address during I/O\n");
3639			vm_page_lock_queues();
3640			for (i = 0; i < pidx; ++i) {
3641				vm_page_unhold(bp->b_pages[i]);
3642				bp->b_pages[i] = NULL;
3643			}
3644			vm_page_unlock_queues();
3645			return(-1);
3646		}
3647		pa = trunc_page(pmap_extract(pmap, (vm_offset_t) addr));
3648		if (pa == 0) {
3649			printf("vmapbuf: warning, race against user address during I/O");
3650			goto retry;
3651		}
3652		m = PHYS_TO_VM_PAGE(pa);
3653		vm_page_lock_queues();
3654		vm_page_hold(m);
3655		vm_page_unlock_queues();
3656		bp->b_pages[pidx] = m;
3657	}
3658	if (pidx > btoc(MAXPHYS))
3659		panic("vmapbuf: mapped more than MAXPHYS");
3660	pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3661
3662	kva = bp->b_saveaddr;
3663	bp->b_npages = pidx;
3664	bp->b_saveaddr = bp->b_data;
3665	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3666	return(0);
3667}
3668
3669/*
3670 * Free the io map PTEs associated with this IO operation.
3671 * We also invalidate the TLB entries and restore the original b_addr.
3672 */
3673void
3674vunmapbuf(struct buf *bp)
3675{
3676	int pidx;
3677	int npages;
3678
3679	GIANT_REQUIRED;
3680
3681	if ((bp->b_flags & B_PHYS) == 0)
3682		panic("vunmapbuf");
3683
3684	npages = bp->b_npages;
3685	pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3686		     npages);
3687	vm_page_lock_queues();
3688	for (pidx = 0; pidx < npages; pidx++)
3689		vm_page_unhold(bp->b_pages[pidx]);
3690	vm_page_unlock_queues();
3691
3692	bp->b_data = bp->b_saveaddr;
3693}
3694
3695void
3696bdone(struct buf *bp)
3697{
3698	mtx_lock(&bdonelock);
3699	bp->b_flags |= B_DONE;
3700	wakeup(bp);
3701	mtx_unlock(&bdonelock);
3702}
3703
3704void
3705bwait(struct buf *bp, u_char pri, const char *wchan)
3706{
3707	mtx_lock(&bdonelock);
3708	while ((bp->b_flags & B_DONE) == 0)
3709		msleep(bp, &bdonelock, pri, wchan, 0);
3710	mtx_unlock(&bdonelock);
3711}
3712
3713#include "opt_ddb.h"
3714#ifdef DDB
3715#include <ddb/ddb.h>
3716
3717/* DDB command to show buffer data */
3718DB_SHOW_COMMAND(buffer, db_show_buffer)
3719{
3720	/* get args */
3721	struct buf *bp = (struct buf *)addr;
3722
3723	if (!have_addr) {
3724		db_printf("usage: show buffer <addr>\n");
3725		return;
3726	}
3727
3728	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3729	db_printf(
3730	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
3731	    "b_dev = (%d,%d), b_data = %p, b_blkno = %jd, b_pblkno = %jd\n",
3732	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3733	    major(bp->b_dev), minor(bp->b_dev), bp->b_data,
3734	    (intmax_t)bp->b_blkno, (intmax_t)bp->b_pblkno);
3735	if (bp->b_npages) {
3736		int i;
3737		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3738		for (i = 0; i < bp->b_npages; i++) {
3739			vm_page_t m;
3740			m = bp->b_pages[i];
3741			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3742			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3743			if ((i + 1) < bp->b_npages)
3744				db_printf(",");
3745		}
3746		db_printf("\n");
3747	}
3748}
3749#endif /* DDB */
3750