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