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