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