xref: /freebsd/sys/vm/vnode_pager.c (revision 19fae0f66023a97a9b464b3beeeabb2081f575b3)
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1990 University of Utah.
5  * Copyright (c) 1991 The Regents of the University of California.
6  * All rights reserved.
7  * Copyright (c) 1993, 1994 John S. Dyson
8  * Copyright (c) 1995, David Greenman
9  *
10  * This code is derived from software contributed to Berkeley by
11  * the Systems Programming Group of the University of Utah Computer
12  * Science Department.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. All advertising materials mentioning features or use of this software
23  *    must display the following acknowledgement:
24  *	This product includes software developed by the University of
25  *	California, Berkeley and its contributors.
26  * 4. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  *
42  *	from: @(#)vnode_pager.c	7.5 (Berkeley) 4/20/91
43  */
44 
45 /*
46  * Page to/from files (vnodes).
47  */
48 
49 /*
50  * TODO:
51  *	Implement VOP_GETPAGES/PUTPAGES interface for filesystems. Will
52  *	greatly re-simplify the vnode_pager.
53  */
54 
55 #include <sys/cdefs.h>
56 __FBSDID("$FreeBSD$");
57 
58 #include "opt_vm.h"
59 
60 #include <sys/param.h>
61 #include <sys/kernel.h>
62 #include <sys/systm.h>
63 #include <sys/sysctl.h>
64 #include <sys/proc.h>
65 #include <sys/vnode.h>
66 #include <sys/mount.h>
67 #include <sys/bio.h>
68 #include <sys/buf.h>
69 #include <sys/vmmeter.h>
70 #include <sys/ktr.h>
71 #include <sys/limits.h>
72 #include <sys/conf.h>
73 #include <sys/refcount.h>
74 #include <sys/rwlock.h>
75 #include <sys/sf_buf.h>
76 #include <sys/domainset.h>
77 #include <sys/user.h>
78 
79 #include <machine/atomic.h>
80 
81 #include <vm/vm.h>
82 #include <vm/vm_param.h>
83 #include <vm/vm_object.h>
84 #include <vm/vm_page.h>
85 #include <vm/vm_pager.h>
86 #include <vm/vm_map.h>
87 #include <vm/vnode_pager.h>
88 #include <vm/vm_extern.h>
89 #include <vm/uma.h>
90 
91 static int vnode_pager_addr(struct vnode *vp, vm_ooffset_t address,
92     daddr_t *rtaddress, int *run);
93 static int vnode_pager_input_smlfs(vm_object_t object, vm_page_t m);
94 static int vnode_pager_input_old(vm_object_t object, vm_page_t m);
95 static void vnode_pager_dealloc(vm_object_t);
96 static int vnode_pager_getpages(vm_object_t, vm_page_t *, int, int *, int *);
97 static int vnode_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
98     int *, vop_getpages_iodone_t, void *);
99 static void vnode_pager_putpages(vm_object_t, vm_page_t *, int, int, int *);
100 static boolean_t vnode_pager_haspage(vm_object_t, vm_pindex_t, int *, int *);
101 static vm_object_t vnode_pager_alloc(void *, vm_ooffset_t, vm_prot_t,
102     vm_ooffset_t, struct ucred *cred);
103 static int vnode_pager_generic_getpages_done(struct buf *);
104 static void vnode_pager_generic_getpages_done_async(struct buf *);
105 static void vnode_pager_update_writecount(vm_object_t, vm_offset_t,
106     vm_offset_t);
107 static void vnode_pager_release_writecount(vm_object_t, vm_offset_t,
108     vm_offset_t);
109 static void vnode_pager_getvp(vm_object_t, struct vnode **, bool *);
110 
111 const struct pagerops vnodepagerops = {
112 	.pgo_kvme_type = KVME_TYPE_VNODE,
113 	.pgo_alloc =	vnode_pager_alloc,
114 	.pgo_dealloc =	vnode_pager_dealloc,
115 	.pgo_getpages =	vnode_pager_getpages,
116 	.pgo_getpages_async = vnode_pager_getpages_async,
117 	.pgo_putpages =	vnode_pager_putpages,
118 	.pgo_haspage =	vnode_pager_haspage,
119 	.pgo_update_writecount = vnode_pager_update_writecount,
120 	.pgo_release_writecount = vnode_pager_release_writecount,
121 	.pgo_set_writeable_dirty = vm_object_set_writeable_dirty_,
122 	.pgo_mightbedirty = vm_object_mightbedirty_,
123 	.pgo_getvp = vnode_pager_getvp,
124 };
125 
126 static struct domainset *vnode_domainset = NULL;
127 
128 SYSCTL_PROC(_debug, OID_AUTO, vnode_domainset,
129     CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_RW, &vnode_domainset, 0,
130     sysctl_handle_domainset, "A", "Default vnode NUMA policy");
131 
132 static int nvnpbufs;
133 SYSCTL_INT(_vm, OID_AUTO, vnode_pbufs, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
134     &nvnpbufs, 0, "number of physical buffers allocated for vnode pager");
135 
136 static uma_zone_t vnode_pbuf_zone;
137 
138 static void
139 vnode_pager_init(void *dummy)
140 {
141 
142 #ifdef __LP64__
143 	nvnpbufs = nswbuf * 2;
144 #else
145 	nvnpbufs = nswbuf / 2;
146 #endif
147 	TUNABLE_INT_FETCH("vm.vnode_pbufs", &nvnpbufs);
148 	vnode_pbuf_zone = pbuf_zsecond_create("vnpbuf", nvnpbufs);
149 }
150 SYSINIT(vnode_pager, SI_SUB_CPU, SI_ORDER_ANY, vnode_pager_init, NULL);
151 
152 /* Create the VM system backing object for this vnode */
153 int
154 vnode_create_vobject(struct vnode *vp, off_t isize, struct thread *td)
155 {
156 	vm_object_t object;
157 	vm_ooffset_t size = isize;
158 	bool last;
159 
160 	if (!vn_isdisk(vp) && vn_canvmio(vp) == FALSE)
161 		return (0);
162 
163 	object = vp->v_object;
164 	if (object != NULL)
165 		return (0);
166 
167 	if (size == 0) {
168 		if (vn_isdisk(vp)) {
169 			size = IDX_TO_OFF(INT_MAX);
170 		} else {
171 			if (vn_getsize_locked(vp, &size, td->td_ucred) != 0)
172 				return (0);
173 		}
174 	}
175 
176 	object = vnode_pager_alloc(vp, size, 0, 0, td->td_ucred);
177 	/*
178 	 * Dereference the reference we just created.  This assumes
179 	 * that the object is associated with the vp.  We still have
180 	 * to serialize with vnode_pager_dealloc() for the last
181 	 * potential reference.
182 	 */
183 	VM_OBJECT_RLOCK(object);
184 	last = refcount_release(&object->ref_count);
185 	VM_OBJECT_RUNLOCK(object);
186 	if (last)
187 		vrele(vp);
188 
189 	KASSERT(vp->v_object != NULL, ("vnode_create_vobject: NULL object"));
190 
191 	return (0);
192 }
193 
194 void
195 vnode_destroy_vobject(struct vnode *vp)
196 {
197 	struct vm_object *obj;
198 
199 	obj = vp->v_object;
200 	if (obj == NULL || obj->handle != vp)
201 		return;
202 	ASSERT_VOP_ELOCKED(vp, "vnode_destroy_vobject");
203 	VM_OBJECT_WLOCK(obj);
204 	MPASS(obj->type == OBJT_VNODE);
205 	umtx_shm_object_terminated(obj);
206 	if (obj->ref_count == 0) {
207 		KASSERT((obj->flags & OBJ_DEAD) == 0,
208 		   ("vnode_destroy_vobject: Terminating dead object"));
209 		vm_object_set_flag(obj, OBJ_DEAD);
210 
211 		/*
212 		 * Clean pages and flush buffers.
213 		 */
214 		vm_object_page_clean(obj, 0, 0, OBJPC_SYNC);
215 		VM_OBJECT_WUNLOCK(obj);
216 
217 		vinvalbuf(vp, V_SAVE, 0, 0);
218 
219 		BO_LOCK(&vp->v_bufobj);
220 		vp->v_bufobj.bo_flag |= BO_DEAD;
221 		BO_UNLOCK(&vp->v_bufobj);
222 
223 		VM_OBJECT_WLOCK(obj);
224 		vm_object_terminate(obj);
225 	} else {
226 		/*
227 		 * Woe to the process that tries to page now :-).
228 		 */
229 		vm_pager_deallocate(obj);
230 		VM_OBJECT_WUNLOCK(obj);
231 	}
232 	KASSERT(vp->v_object == NULL, ("vp %p obj %p", vp, vp->v_object));
233 }
234 
235 /*
236  * Allocate (or lookup) pager for a vnode.
237  * Handle is a vnode pointer.
238  */
239 vm_object_t
240 vnode_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
241     vm_ooffset_t offset, struct ucred *cred)
242 {
243 	vm_object_t object;
244 	struct vnode *vp;
245 
246 	/*
247 	 * Pageout to vnode, no can do yet.
248 	 */
249 	if (handle == NULL)
250 		return (NULL);
251 
252 	vp = (struct vnode *)handle;
253 	ASSERT_VOP_LOCKED(vp, "vnode_pager_alloc");
254 	VNPASS(vp->v_usecount > 0, vp);
255 retry:
256 	object = vp->v_object;
257 
258 	if (object == NULL) {
259 		/*
260 		 * Add an object of the appropriate size
261 		 */
262 		object = vm_object_allocate(OBJT_VNODE,
263 		    OFF_TO_IDX(round_page(size)));
264 
265 		object->un_pager.vnp.vnp_size = size;
266 		object->un_pager.vnp.writemappings = 0;
267 		object->domain.dr_policy = vnode_domainset;
268 		object->handle = handle;
269 		if ((vp->v_vflag & VV_VMSIZEVNLOCK) != 0) {
270 			VM_OBJECT_WLOCK(object);
271 			vm_object_set_flag(object, OBJ_SIZEVNLOCK);
272 			VM_OBJECT_WUNLOCK(object);
273 		}
274 		VI_LOCK(vp);
275 		if (vp->v_object != NULL) {
276 			/*
277 			 * Object has been created while we were allocating.
278 			 */
279 			VI_UNLOCK(vp);
280 			VM_OBJECT_WLOCK(object);
281 			KASSERT(object->ref_count == 1,
282 			    ("leaked ref %p %d", object, object->ref_count));
283 			object->type = OBJT_DEAD;
284 			refcount_init(&object->ref_count, 0);
285 			VM_OBJECT_WUNLOCK(object);
286 			vm_object_destroy(object);
287 			goto retry;
288 		}
289 		vp->v_object = object;
290 		VI_UNLOCK(vp);
291 		vrefact(vp);
292 	} else {
293 		vm_object_reference(object);
294 #if VM_NRESERVLEVEL > 0
295 		if ((object->flags & OBJ_COLORED) == 0) {
296 			VM_OBJECT_WLOCK(object);
297 			vm_object_color(object, 0);
298 			VM_OBJECT_WUNLOCK(object);
299 		}
300 #endif
301 	}
302 	return (object);
303 }
304 
305 /*
306  *	The object must be locked.
307  */
308 static void
309 vnode_pager_dealloc(vm_object_t object)
310 {
311 	struct vnode *vp;
312 	int refs;
313 
314 	vp = object->handle;
315 	if (vp == NULL)
316 		panic("vnode_pager_dealloc: pager already dealloced");
317 
318 	VM_OBJECT_ASSERT_WLOCKED(object);
319 	vm_object_pip_wait(object, "vnpdea");
320 	refs = object->ref_count;
321 
322 	object->handle = NULL;
323 	object->type = OBJT_DEAD;
324 	ASSERT_VOP_ELOCKED(vp, "vnode_pager_dealloc");
325 	if (object->un_pager.vnp.writemappings > 0) {
326 		object->un_pager.vnp.writemappings = 0;
327 		VOP_ADD_WRITECOUNT_CHECKED(vp, -1);
328 		CTR3(KTR_VFS, "%s: vp %p v_writecount decreased to %d",
329 		    __func__, vp, vp->v_writecount);
330 	}
331 	vp->v_object = NULL;
332 	VI_LOCK(vp);
333 
334 	/*
335 	 * vm_map_entry_set_vnode_text() cannot reach this vnode by
336 	 * following object->handle.  Clear all text references now.
337 	 * This also clears the transient references from
338 	 * kern_execve(), which is fine because dead_vnodeops uses nop
339 	 * for VOP_UNSET_TEXT().
340 	 */
341 	if (vp->v_writecount < 0)
342 		vp->v_writecount = 0;
343 	VI_UNLOCK(vp);
344 	VM_OBJECT_WUNLOCK(object);
345 	if (refs > 0)
346 		vunref(vp);
347 	VM_OBJECT_WLOCK(object);
348 }
349 
350 static boolean_t
351 vnode_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
352     int *after)
353 {
354 	struct vnode *vp = object->handle;
355 	daddr_t bn;
356 	uintptr_t lockstate;
357 	int err;
358 	daddr_t reqblock;
359 	int poff;
360 	int bsize;
361 	int pagesperblock, blocksperpage;
362 
363 	VM_OBJECT_ASSERT_LOCKED(object);
364 	/*
365 	 * If no vp or vp is doomed or marked transparent to VM, we do not
366 	 * have the page.
367 	 */
368 	if (vp == NULL || VN_IS_DOOMED(vp))
369 		return FALSE;
370 	/*
371 	 * If the offset is beyond end of file we do
372 	 * not have the page.
373 	 */
374 	if (IDX_TO_OFF(pindex) >= object->un_pager.vnp.vnp_size)
375 		return FALSE;
376 
377 	bsize = vp->v_mount->mnt_stat.f_iosize;
378 	pagesperblock = bsize / PAGE_SIZE;
379 	blocksperpage = 0;
380 	if (pagesperblock > 0) {
381 		reqblock = pindex / pagesperblock;
382 	} else {
383 		blocksperpage = (PAGE_SIZE / bsize);
384 		reqblock = pindex * blocksperpage;
385 	}
386 	lockstate = VM_OBJECT_DROP(object);
387 	err = VOP_BMAP(vp, reqblock, NULL, &bn, after, before);
388 	VM_OBJECT_PICKUP(object, lockstate);
389 	if (err)
390 		return TRUE;
391 	if (bn == -1)
392 		return FALSE;
393 	if (pagesperblock > 0) {
394 		poff = pindex - (reqblock * pagesperblock);
395 		if (before) {
396 			*before *= pagesperblock;
397 			*before += poff;
398 		}
399 		if (after) {
400 			/*
401 			 * The BMAP vop can report a partial block in the
402 			 * 'after', but must not report blocks after EOF.
403 			 * Assert the latter, and truncate 'after' in case
404 			 * of the former.
405 			 */
406 			KASSERT((reqblock + *after) * pagesperblock <
407 			    roundup2(object->size, pagesperblock),
408 			    ("%s: reqblock %jd after %d size %ju", __func__,
409 			    (intmax_t )reqblock, *after,
410 			    (uintmax_t )object->size));
411 			*after *= pagesperblock;
412 			*after += pagesperblock - (poff + 1);
413 			if (pindex + *after >= object->size)
414 				*after = object->size - 1 - pindex;
415 		}
416 	} else {
417 		if (before) {
418 			*before /= blocksperpage;
419 		}
420 
421 		if (after) {
422 			*after /= blocksperpage;
423 		}
424 	}
425 	return TRUE;
426 }
427 
428 /*
429  * Internal routine clearing partial-page content
430  */
431 static void
432 vnode_pager_subpage_purge(struct vm_page *m, int base, int end)
433 {
434 	int size;
435 
436 	KASSERT(end > base && end <= PAGE_SIZE,
437 	    ("%s: start %d end %d", __func__, base, end));
438 	size = end - base;
439 
440 	/*
441 	 * Clear out partial-page garbage in case
442 	 * the page has been mapped.
443 	 */
444 	pmap_zero_page_area(m, base, size);
445 
446 	/*
447 	 * Update the valid bits to reflect the blocks
448 	 * that have been zeroed.  Some of these valid
449 	 * bits may have already been set.
450 	 */
451 	vm_page_set_valid_range(m, base, size);
452 
453 	/*
454 	 * Round up "base" to the next block boundary so
455 	 * that the dirty bit for a partially zeroed
456 	 * block is not cleared.
457 	 */
458 	base = roundup2(base, DEV_BSIZE);
459 	end = rounddown2(end, DEV_BSIZE);
460 
461 	if (end > base) {
462 		/*
463 		 * Clear out partial-page dirty bits.
464 		 *
465 		 * note that we do not clear out the
466 		 * valid bits.  This would prevent
467 		 * bogus_page replacement from working
468 		 * properly.
469 		 */
470 		vm_page_clear_dirty(m, base, end - base);
471 	}
472 
473 }
474 
475 /*
476  * Lets the VM system know about a change in size for a file.
477  * We adjust our own internal size and flush any cached pages in
478  * the associated object that are affected by the size change.
479  *
480  * Note: this routine may be invoked as a result of a pager put
481  * operation (possibly at object termination time), so we must be careful.
482  */
483 void
484 vnode_pager_setsize(struct vnode *vp, vm_ooffset_t nsize)
485 {
486 	vm_object_t object;
487 	vm_page_t m;
488 	vm_pindex_t nobjsize;
489 
490 	if ((object = vp->v_object) == NULL)
491 		return;
492 #ifdef DEBUG_VFS_LOCKS
493 	{
494 		struct mount *mp;
495 
496 		mp = vp->v_mount;
497 		if (mp != NULL && (mp->mnt_kern_flag & MNTK_VMSETSIZE_BUG) == 0)
498 			assert_vop_elocked(vp,
499 			    "vnode_pager_setsize and not locked vnode");
500 	}
501 #endif
502 	VM_OBJECT_WLOCK(object);
503 	if (object->type == OBJT_DEAD) {
504 		VM_OBJECT_WUNLOCK(object);
505 		return;
506 	}
507 	KASSERT(object->type == OBJT_VNODE,
508 	    ("not vnode-backed object %p", object));
509 	if (nsize == object->un_pager.vnp.vnp_size) {
510 		/*
511 		 * Hasn't changed size
512 		 */
513 		VM_OBJECT_WUNLOCK(object);
514 		return;
515 	}
516 	nobjsize = OFF_TO_IDX(nsize + PAGE_MASK);
517 	if (nsize < object->un_pager.vnp.vnp_size) {
518 		/*
519 		 * File has shrunk. Toss any cached pages beyond the new EOF.
520 		 */
521 		if (nobjsize < object->size)
522 			vm_object_page_remove(object, nobjsize, object->size,
523 			    0);
524 		/*
525 		 * this gets rid of garbage at the end of a page that is now
526 		 * only partially backed by the vnode.
527 		 *
528 		 * XXX for some reason (I don't know yet), if we take a
529 		 * completely invalid page and mark it partially valid
530 		 * it can screw up NFS reads, so we don't allow the case.
531 		 */
532 		if (!(nsize & PAGE_MASK))
533 			goto out;
534 		m = vm_page_grab(object, OFF_TO_IDX(nsize), VM_ALLOC_NOCREAT);
535 		if (m == NULL)
536 			goto out;
537 		if (!vm_page_none_valid(m))
538 			vnode_pager_subpage_purge(m, (int)nsize & PAGE_MASK,
539 			    PAGE_SIZE);
540 		vm_page_xunbusy(m);
541 	}
542 out:
543 #if defined(__powerpc__) && !defined(__powerpc64__)
544 	object->un_pager.vnp.vnp_size = nsize;
545 #else
546 	atomic_store_64(&object->un_pager.vnp.vnp_size, nsize);
547 #endif
548 	object->size = nobjsize;
549 	VM_OBJECT_WUNLOCK(object);
550 }
551 
552 /*
553  * Lets the VM system know about the purged range for a file. We toss away any
554  * cached pages in the associated object that are affected by the purge
555  * operation. Partial-page area not aligned to page boundaries will be zeroed
556  * and the dirty blocks in DEV_BSIZE unit within a page will not be flushed.
557  */
558 void
559 vnode_pager_purge_range(struct vnode *vp, vm_ooffset_t start, vm_ooffset_t end)
560 {
561 	struct vm_page *m;
562 	struct vm_object *object;
563 	vm_pindex_t pi, pistart, piend;
564 	bool same_page;
565 	int base, pend;
566 
567 	ASSERT_VOP_LOCKED(vp, "vnode_pager_purge_range");
568 
569 	object = vp->v_object;
570 	pi = start + PAGE_MASK < start ? OBJ_MAX_SIZE :
571 	    OFF_TO_IDX(start + PAGE_MASK);
572 	pistart = OFF_TO_IDX(start);
573 	piend = end == 0 ? OBJ_MAX_SIZE : OFF_TO_IDX(end);
574 	same_page = pistart == piend;
575 	if ((end != 0 && end <= start) || object == NULL)
576 		return;
577 
578 	VM_OBJECT_WLOCK(object);
579 
580 	if (pi < piend)
581 		vm_object_page_remove(object, pi, piend, 0);
582 
583 	if ((start & PAGE_MASK) != 0) {
584 		base = (int)start & PAGE_MASK;
585 		pend = same_page ? (int)end & PAGE_MASK : PAGE_SIZE;
586 		m = vm_page_grab(object, pistart, VM_ALLOC_NOCREAT);
587 		if (m != NULL) {
588 			if (!vm_page_none_valid(m))
589 				vnode_pager_subpage_purge(m, base, pend);
590 			vm_page_xunbusy(m);
591 		}
592 		if (same_page)
593 			goto out;
594 	}
595 	if ((end & PAGE_MASK) != 0) {
596 		base = same_page ? (int)start & PAGE_MASK : 0 ;
597 		pend = (int)end & PAGE_MASK;
598 		m = vm_page_grab(object, piend, VM_ALLOC_NOCREAT);
599 		if (m != NULL) {
600 			if (!vm_page_none_valid(m))
601 				vnode_pager_subpage_purge(m, base, pend);
602 			vm_page_xunbusy(m);
603 		}
604 	}
605 out:
606 	VM_OBJECT_WUNLOCK(object);
607 }
608 
609 /*
610  * calculate the linear (byte) disk address of specified virtual
611  * file address
612  */
613 static int
614 vnode_pager_addr(struct vnode *vp, vm_ooffset_t address, daddr_t *rtaddress,
615     int *run)
616 {
617 	int bsize;
618 	int err;
619 	daddr_t vblock;
620 	daddr_t voffset;
621 
622 	if (VN_IS_DOOMED(vp))
623 		return -1;
624 
625 	bsize = vp->v_mount->mnt_stat.f_iosize;
626 	vblock = address / bsize;
627 	voffset = address % bsize;
628 
629 	err = VOP_BMAP(vp, vblock, NULL, rtaddress, run, NULL);
630 	if (err == 0) {
631 		if (*rtaddress != -1)
632 			*rtaddress += voffset / DEV_BSIZE;
633 		if (run) {
634 			*run += 1;
635 			*run *= bsize / PAGE_SIZE;
636 			*run -= voffset / PAGE_SIZE;
637 		}
638 	}
639 
640 	return (err);
641 }
642 
643 static void
644 vnode_pager_input_bdone(struct buf *bp)
645 {
646 	runningbufwakeup(bp);
647 	bdone(bp);
648 }
649 
650 /*
651  * small block filesystem vnode pager input
652  */
653 static int
654 vnode_pager_input_smlfs(vm_object_t object, vm_page_t m)
655 {
656 	struct vnode *vp;
657 	struct bufobj *bo;
658 	struct buf *bp;
659 	struct sf_buf *sf;
660 	daddr_t fileaddr;
661 	vm_offset_t bsize;
662 	vm_page_bits_t bits;
663 	int error, i;
664 
665 	error = 0;
666 	vp = object->handle;
667 	if (VN_IS_DOOMED(vp))
668 		return VM_PAGER_BAD;
669 
670 	bsize = vp->v_mount->mnt_stat.f_iosize;
671 
672 	VOP_BMAP(vp, 0, &bo, 0, NULL, NULL);
673 
674 	sf = sf_buf_alloc(m, 0);
675 
676 	for (i = 0; i < PAGE_SIZE / bsize; i++) {
677 		vm_ooffset_t address;
678 
679 		bits = vm_page_bits(i * bsize, bsize);
680 		if (m->valid & bits)
681 			continue;
682 
683 		address = IDX_TO_OFF(m->pindex) + i * bsize;
684 		if (address >= object->un_pager.vnp.vnp_size) {
685 			fileaddr = -1;
686 		} else {
687 			error = vnode_pager_addr(vp, address, &fileaddr, NULL);
688 			if (error)
689 				break;
690 		}
691 		if (fileaddr != -1) {
692 			bp = uma_zalloc(vnode_pbuf_zone, M_WAITOK);
693 
694 			/* build a minimal buffer header */
695 			bp->b_iocmd = BIO_READ;
696 			bp->b_iodone = vnode_pager_input_bdone;
697 			KASSERT(bp->b_rcred == NOCRED, ("leaking read ucred"));
698 			KASSERT(bp->b_wcred == NOCRED, ("leaking write ucred"));
699 			bp->b_rcred = crhold(curthread->td_ucred);
700 			bp->b_wcred = crhold(curthread->td_ucred);
701 			bp->b_data = (caddr_t)sf_buf_kva(sf) + i * bsize;
702 			bp->b_blkno = fileaddr;
703 			pbgetbo(bo, bp);
704 			bp->b_vp = vp;
705 			bp->b_bcount = bsize;
706 			bp->b_bufsize = bsize;
707 			bp->b_runningbufspace = bp->b_bufsize;
708 			atomic_add_long(&runningbufspace, bp->b_runningbufspace);
709 
710 			/* do the input */
711 			bp->b_iooffset = dbtob(bp->b_blkno);
712 			bstrategy(bp);
713 
714 			bwait(bp, PVM, "vnsrd");
715 
716 			if ((bp->b_ioflags & BIO_ERROR) != 0) {
717 				KASSERT(bp->b_error != 0,
718 				    ("%s: buf error but b_error == 0\n", __func__));
719 				error = bp->b_error;
720 			}
721 
722 			/*
723 			 * free the buffer header back to the swap buffer pool
724 			 */
725 			bp->b_vp = NULL;
726 			pbrelbo(bp);
727 			uma_zfree(vnode_pbuf_zone, bp);
728 			if (error)
729 				break;
730 		} else
731 			bzero((caddr_t)sf_buf_kva(sf) + i * bsize, bsize);
732 		KASSERT((m->dirty & bits) == 0,
733 		    ("vnode_pager_input_smlfs: page %p is dirty", m));
734 		vm_page_bits_set(m, &m->valid, bits);
735 	}
736 	sf_buf_free(sf);
737 	if (error) {
738 		return VM_PAGER_ERROR;
739 	}
740 	return VM_PAGER_OK;
741 }
742 
743 /*
744  * old style vnode pager input routine
745  */
746 static int
747 vnode_pager_input_old(vm_object_t object, vm_page_t m)
748 {
749 	struct uio auio;
750 	struct iovec aiov;
751 	int error;
752 	int size;
753 	struct sf_buf *sf;
754 	struct vnode *vp;
755 
756 	VM_OBJECT_ASSERT_WLOCKED(object);
757 	error = 0;
758 
759 	/*
760 	 * Return failure if beyond current EOF
761 	 */
762 	if (IDX_TO_OFF(m->pindex) >= object->un_pager.vnp.vnp_size) {
763 		return VM_PAGER_BAD;
764 	} else {
765 		size = PAGE_SIZE;
766 		if (IDX_TO_OFF(m->pindex) + size > object->un_pager.vnp.vnp_size)
767 			size = object->un_pager.vnp.vnp_size - IDX_TO_OFF(m->pindex);
768 		vp = object->handle;
769 		VM_OBJECT_WUNLOCK(object);
770 
771 		/*
772 		 * Allocate a kernel virtual address and initialize so that
773 		 * we can use VOP_READ/WRITE routines.
774 		 */
775 		sf = sf_buf_alloc(m, 0);
776 
777 		aiov.iov_base = (caddr_t)sf_buf_kva(sf);
778 		aiov.iov_len = size;
779 		auio.uio_iov = &aiov;
780 		auio.uio_iovcnt = 1;
781 		auio.uio_offset = IDX_TO_OFF(m->pindex);
782 		auio.uio_segflg = UIO_SYSSPACE;
783 		auio.uio_rw = UIO_READ;
784 		auio.uio_resid = size;
785 		auio.uio_td = curthread;
786 
787 		error = VOP_READ(vp, &auio, 0, curthread->td_ucred);
788 		if (!error) {
789 			int count = size - auio.uio_resid;
790 
791 			if (count == 0)
792 				error = EINVAL;
793 			else if (count != PAGE_SIZE)
794 				bzero((caddr_t)sf_buf_kva(sf) + count,
795 				    PAGE_SIZE - count);
796 		}
797 		sf_buf_free(sf);
798 
799 		VM_OBJECT_WLOCK(object);
800 	}
801 	KASSERT(m->dirty == 0, ("vnode_pager_input_old: page %p is dirty", m));
802 	if (!error)
803 		vm_page_valid(m);
804 	return error ? VM_PAGER_ERROR : VM_PAGER_OK;
805 }
806 
807 /*
808  * generic vnode pager input routine
809  */
810 
811 /*
812  * Local media VFS's that do not implement their own VOP_GETPAGES
813  * should have their VOP_GETPAGES call to vnode_pager_generic_getpages()
814  * to implement the previous behaviour.
815  *
816  * All other FS's should use the bypass to get to the local media
817  * backing vp's VOP_GETPAGES.
818  */
819 static int
820 vnode_pager_getpages(vm_object_t object, vm_page_t *m, int count, int *rbehind,
821     int *rahead)
822 {
823 	struct vnode *vp;
824 	int rtval;
825 
826 	/* Handle is stable with paging in progress. */
827 	vp = object->handle;
828 	rtval = VOP_GETPAGES(vp, m, count, rbehind, rahead);
829 	KASSERT(rtval != EOPNOTSUPP,
830 	    ("vnode_pager: FS getpages not implemented\n"));
831 	return rtval;
832 }
833 
834 static int
835 vnode_pager_getpages_async(vm_object_t object, vm_page_t *m, int count,
836     int *rbehind, int *rahead, vop_getpages_iodone_t iodone, void *arg)
837 {
838 	struct vnode *vp;
839 	int rtval;
840 
841 	vp = object->handle;
842 	rtval = VOP_GETPAGES_ASYNC(vp, m, count, rbehind, rahead, iodone, arg);
843 	KASSERT(rtval != EOPNOTSUPP,
844 	    ("vnode_pager: FS getpages_async not implemented\n"));
845 	return (rtval);
846 }
847 
848 /*
849  * The implementation of VOP_GETPAGES() and VOP_GETPAGES_ASYNC() for
850  * local filesystems, where partially valid pages can only occur at
851  * the end of file.
852  */
853 int
854 vnode_pager_local_getpages(struct vop_getpages_args *ap)
855 {
856 
857 	return (vnode_pager_generic_getpages(ap->a_vp, ap->a_m, ap->a_count,
858 	    ap->a_rbehind, ap->a_rahead, NULL, NULL));
859 }
860 
861 int
862 vnode_pager_local_getpages_async(struct vop_getpages_async_args *ap)
863 {
864 	int error;
865 
866 	error = vnode_pager_generic_getpages(ap->a_vp, ap->a_m, ap->a_count,
867 	    ap->a_rbehind, ap->a_rahead, ap->a_iodone, ap->a_arg);
868 	if (error != 0 && ap->a_iodone != NULL)
869 		ap->a_iodone(ap->a_arg, ap->a_m, ap->a_count, error);
870 	return (error);
871 }
872 
873 /*
874  * This is now called from local media FS's to operate against their
875  * own vnodes if they fail to implement VOP_GETPAGES.
876  */
877 int
878 vnode_pager_generic_getpages(struct vnode *vp, vm_page_t *m, int count,
879     int *a_rbehind, int *a_rahead, vop_getpages_iodone_t iodone, void *arg)
880 {
881 	vm_object_t object;
882 	struct bufobj *bo;
883 	struct buf *bp;
884 	off_t foff;
885 #ifdef INVARIANTS
886 	off_t blkno0;
887 #endif
888 	int bsize, pagesperblock;
889 	int error, before, after, rbehind, rahead, poff, i;
890 	int bytecount, secmask;
891 
892 	KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
893 	    ("%s does not support devices", __func__));
894 
895 	if (VN_IS_DOOMED(vp))
896 		return (VM_PAGER_BAD);
897 
898 	object = vp->v_object;
899 	foff = IDX_TO_OFF(m[0]->pindex);
900 	bsize = vp->v_mount->mnt_stat.f_iosize;
901 	pagesperblock = bsize / PAGE_SIZE;
902 
903 	KASSERT(foff < object->un_pager.vnp.vnp_size,
904 	    ("%s: page %p offset beyond vp %p size", __func__, m[0], vp));
905 	KASSERT(count <= atop(maxphys),
906 	    ("%s: requested %d pages", __func__, count));
907 
908 	/*
909 	 * The last page has valid blocks.  Invalid part can only
910 	 * exist at the end of file, and the page is made fully valid
911 	 * by zeroing in vm_pager_get_pages().
912 	 */
913 	if (!vm_page_none_valid(m[count - 1]) && --count == 0) {
914 		if (iodone != NULL)
915 			iodone(arg, m, 1, 0);
916 		return (VM_PAGER_OK);
917 	}
918 
919 	bp = uma_zalloc(vnode_pbuf_zone, M_WAITOK);
920 	MPASS((bp->b_flags & B_MAXPHYS) != 0);
921 
922 	/*
923 	 * Get the underlying device blocks for the file with VOP_BMAP().
924 	 * If the file system doesn't support VOP_BMAP, use old way of
925 	 * getting pages via VOP_READ.
926 	 */
927 	error = VOP_BMAP(vp, foff / bsize, &bo, &bp->b_blkno, &after, &before);
928 	if (error == EOPNOTSUPP) {
929 		uma_zfree(vnode_pbuf_zone, bp);
930 		VM_OBJECT_WLOCK(object);
931 		for (i = 0; i < count; i++) {
932 			VM_CNT_INC(v_vnodein);
933 			VM_CNT_INC(v_vnodepgsin);
934 			error = vnode_pager_input_old(object, m[i]);
935 			if (error)
936 				break;
937 		}
938 		VM_OBJECT_WUNLOCK(object);
939 		return (error);
940 	} else if (error != 0) {
941 		uma_zfree(vnode_pbuf_zone, bp);
942 		return (VM_PAGER_ERROR);
943 	}
944 
945 	/*
946 	 * If the file system supports BMAP, but blocksize is smaller
947 	 * than a page size, then use special small filesystem code.
948 	 */
949 	if (pagesperblock == 0) {
950 		uma_zfree(vnode_pbuf_zone, bp);
951 		for (i = 0; i < count; i++) {
952 			VM_CNT_INC(v_vnodein);
953 			VM_CNT_INC(v_vnodepgsin);
954 			error = vnode_pager_input_smlfs(object, m[i]);
955 			if (error)
956 				break;
957 		}
958 		return (error);
959 	}
960 
961 	/*
962 	 * A sparse file can be encountered only for a single page request,
963 	 * which may not be preceded by call to vm_pager_haspage().
964 	 */
965 	if (bp->b_blkno == -1) {
966 		KASSERT(count == 1,
967 		    ("%s: array[%d] request to a sparse file %p", __func__,
968 		    count, vp));
969 		uma_zfree(vnode_pbuf_zone, bp);
970 		pmap_zero_page(m[0]);
971 		KASSERT(m[0]->dirty == 0, ("%s: page %p is dirty",
972 		    __func__, m[0]));
973 		vm_page_valid(m[0]);
974 		return (VM_PAGER_OK);
975 	}
976 
977 #ifdef INVARIANTS
978 	blkno0 = bp->b_blkno;
979 #endif
980 	bp->b_blkno += (foff % bsize) / DEV_BSIZE;
981 
982 	/* Recalculate blocks available after/before to pages. */
983 	poff = (foff % bsize) / PAGE_SIZE;
984 	before *= pagesperblock;
985 	before += poff;
986 	after *= pagesperblock;
987 	after += pagesperblock - (poff + 1);
988 	if (m[0]->pindex + after >= object->size)
989 		after = object->size - 1 - m[0]->pindex;
990 	KASSERT(count <= after + 1, ("%s: %d pages asked, can do only %d",
991 	    __func__, count, after + 1));
992 	after -= count - 1;
993 
994 	/* Trim requested rbehind/rahead to possible values. */
995 	rbehind = a_rbehind ? *a_rbehind : 0;
996 	rahead = a_rahead ? *a_rahead : 0;
997 	rbehind = min(rbehind, before);
998 	rbehind = min(rbehind, m[0]->pindex);
999 	rahead = min(rahead, after);
1000 	rahead = min(rahead, object->size - m[count - 1]->pindex);
1001 	/*
1002 	 * Check that total amount of pages fit into buf.  Trim rbehind and
1003 	 * rahead evenly if not.
1004 	 */
1005 	if (rbehind + rahead + count > atop(maxphys)) {
1006 		int trim, sum;
1007 
1008 		trim = rbehind + rahead + count - atop(maxphys) + 1;
1009 		sum = rbehind + rahead;
1010 		if (rbehind == before) {
1011 			/* Roundup rbehind trim to block size. */
1012 			rbehind -= roundup(trim * rbehind / sum, pagesperblock);
1013 			if (rbehind < 0)
1014 				rbehind = 0;
1015 		} else
1016 			rbehind -= trim * rbehind / sum;
1017 		rahead -= trim * rahead / sum;
1018 	}
1019 	KASSERT(rbehind + rahead + count <= atop(maxphys),
1020 	    ("%s: behind %d ahead %d count %d maxphys %lu", __func__,
1021 	    rbehind, rahead, count, maxphys));
1022 
1023 	/*
1024 	 * Fill in the bp->b_pages[] array with requested and optional
1025 	 * read behind or read ahead pages.  Read behind pages are looked
1026 	 * up in a backward direction, down to a first cached page.  Same
1027 	 * for read ahead pages, but there is no need to shift the array
1028 	 * in case of encountering a cached page.
1029 	 */
1030 	i = bp->b_npages = 0;
1031 	if (rbehind) {
1032 		vm_pindex_t startpindex, tpindex;
1033 		vm_page_t p;
1034 
1035 		VM_OBJECT_WLOCK(object);
1036 		startpindex = m[0]->pindex - rbehind;
1037 		if ((p = TAILQ_PREV(m[0], pglist, listq)) != NULL &&
1038 		    p->pindex >= startpindex)
1039 			startpindex = p->pindex + 1;
1040 
1041 		/* tpindex is unsigned; beware of numeric underflow. */
1042 		for (tpindex = m[0]->pindex - 1;
1043 		    tpindex >= startpindex && tpindex < m[0]->pindex;
1044 		    tpindex--, i++) {
1045 			p = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
1046 			if (p == NULL) {
1047 				/* Shift the array. */
1048 				for (int j = 0; j < i; j++)
1049 					bp->b_pages[j] = bp->b_pages[j +
1050 					    tpindex + 1 - startpindex];
1051 				break;
1052 			}
1053 			bp->b_pages[tpindex - startpindex] = p;
1054 		}
1055 
1056 		bp->b_pgbefore = i;
1057 		bp->b_npages += i;
1058 		bp->b_blkno -= IDX_TO_OFF(i) / DEV_BSIZE;
1059 	} else
1060 		bp->b_pgbefore = 0;
1061 
1062 	/* Requested pages. */
1063 	for (int j = 0; j < count; j++, i++)
1064 		bp->b_pages[i] = m[j];
1065 	bp->b_npages += count;
1066 
1067 	if (rahead) {
1068 		vm_pindex_t endpindex, tpindex;
1069 		vm_page_t p;
1070 
1071 		if (!VM_OBJECT_WOWNED(object))
1072 			VM_OBJECT_WLOCK(object);
1073 		endpindex = m[count - 1]->pindex + rahead + 1;
1074 		if ((p = TAILQ_NEXT(m[count - 1], listq)) != NULL &&
1075 		    p->pindex < endpindex)
1076 			endpindex = p->pindex;
1077 		if (endpindex > object->size)
1078 			endpindex = object->size;
1079 
1080 		for (tpindex = m[count - 1]->pindex + 1;
1081 		    tpindex < endpindex; i++, tpindex++) {
1082 			p = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
1083 			if (p == NULL)
1084 				break;
1085 			bp->b_pages[i] = p;
1086 		}
1087 
1088 		bp->b_pgafter = i - bp->b_npages;
1089 		bp->b_npages = i;
1090 	} else
1091 		bp->b_pgafter = 0;
1092 
1093 	if (VM_OBJECT_WOWNED(object))
1094 		VM_OBJECT_WUNLOCK(object);
1095 
1096 	/* Report back actual behind/ahead read. */
1097 	if (a_rbehind)
1098 		*a_rbehind = bp->b_pgbefore;
1099 	if (a_rahead)
1100 		*a_rahead = bp->b_pgafter;
1101 
1102 #ifdef INVARIANTS
1103 	KASSERT(bp->b_npages <= atop(maxphys),
1104 	    ("%s: buf %p overflowed", __func__, bp));
1105 	for (int j = 1, prev = 0; j < bp->b_npages; j++) {
1106 		if (bp->b_pages[j] == bogus_page)
1107 			continue;
1108 		KASSERT(bp->b_pages[j]->pindex - bp->b_pages[prev]->pindex ==
1109 		    j - prev, ("%s: pages array not consecutive, bp %p",
1110 		     __func__, bp));
1111 		prev = j;
1112 	}
1113 #endif
1114 
1115 	/*
1116 	 * Recalculate first offset and bytecount with regards to read behind.
1117 	 * Truncate bytecount to vnode real size and round up physical size
1118 	 * for real devices.
1119 	 */
1120 	foff = IDX_TO_OFF(bp->b_pages[0]->pindex);
1121 	bytecount = bp->b_npages << PAGE_SHIFT;
1122 	if ((foff + bytecount) > object->un_pager.vnp.vnp_size)
1123 		bytecount = object->un_pager.vnp.vnp_size - foff;
1124 	secmask = bo->bo_bsize - 1;
1125 	KASSERT(secmask < PAGE_SIZE && secmask > 0,
1126 	    ("%s: sector size %d too large", __func__, secmask + 1));
1127 	bytecount = (bytecount + secmask) & ~secmask;
1128 
1129 	/*
1130 	 * And map the pages to be read into the kva, if the filesystem
1131 	 * requires mapped buffers.
1132 	 */
1133 	if ((vp->v_mount->mnt_kern_flag & MNTK_UNMAPPED_BUFS) != 0 &&
1134 	    unmapped_buf_allowed) {
1135 		bp->b_data = unmapped_buf;
1136 		bp->b_offset = 0;
1137 	} else {
1138 		bp->b_data = bp->b_kvabase;
1139 		pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
1140 	}
1141 
1142 	/* Build a minimal buffer header. */
1143 	bp->b_iocmd = BIO_READ;
1144 	KASSERT(bp->b_rcred == NOCRED, ("leaking read ucred"));
1145 	KASSERT(bp->b_wcred == NOCRED, ("leaking write ucred"));
1146 	bp->b_rcred = crhold(curthread->td_ucred);
1147 	bp->b_wcred = crhold(curthread->td_ucred);
1148 	pbgetbo(bo, bp);
1149 	bp->b_vp = vp;
1150 	bp->b_bcount = bp->b_bufsize = bp->b_runningbufspace = bytecount;
1151 	bp->b_iooffset = dbtob(bp->b_blkno);
1152 	KASSERT(IDX_TO_OFF(m[0]->pindex - bp->b_pages[0]->pindex) ==
1153 	    (blkno0 - bp->b_blkno) * DEV_BSIZE +
1154 	    IDX_TO_OFF(m[0]->pindex) % bsize,
1155 	    ("wrong offsets bsize %d m[0] %ju b_pages[0] %ju "
1156 	    "blkno0 %ju b_blkno %ju", bsize,
1157 	    (uintmax_t)m[0]->pindex, (uintmax_t)bp->b_pages[0]->pindex,
1158 	    (uintmax_t)blkno0, (uintmax_t)bp->b_blkno));
1159 
1160 	atomic_add_long(&runningbufspace, bp->b_runningbufspace);
1161 	VM_CNT_INC(v_vnodein);
1162 	VM_CNT_ADD(v_vnodepgsin, bp->b_npages);
1163 
1164 	if (iodone != NULL) { /* async */
1165 		bp->b_pgiodone = iodone;
1166 		bp->b_caller1 = arg;
1167 		bp->b_iodone = vnode_pager_generic_getpages_done_async;
1168 		bp->b_flags |= B_ASYNC;
1169 		BUF_KERNPROC(bp);
1170 		bstrategy(bp);
1171 		return (VM_PAGER_OK);
1172 	} else {
1173 		bp->b_iodone = bdone;
1174 		bstrategy(bp);
1175 		bwait(bp, PVM, "vnread");
1176 		error = vnode_pager_generic_getpages_done(bp);
1177 		for (i = 0; i < bp->b_npages; i++)
1178 			bp->b_pages[i] = NULL;
1179 		bp->b_vp = NULL;
1180 		pbrelbo(bp);
1181 		uma_zfree(vnode_pbuf_zone, bp);
1182 		return (error != 0 ? VM_PAGER_ERROR : VM_PAGER_OK);
1183 	}
1184 }
1185 
1186 static void
1187 vnode_pager_generic_getpages_done_async(struct buf *bp)
1188 {
1189 	int error;
1190 
1191 	error = vnode_pager_generic_getpages_done(bp);
1192 	/* Run the iodone upon the requested range. */
1193 	bp->b_pgiodone(bp->b_caller1, bp->b_pages + bp->b_pgbefore,
1194 	    bp->b_npages - bp->b_pgbefore - bp->b_pgafter, error);
1195 	for (int i = 0; i < bp->b_npages; i++)
1196 		bp->b_pages[i] = NULL;
1197 	bp->b_vp = NULL;
1198 	pbrelbo(bp);
1199 	uma_zfree(vnode_pbuf_zone, bp);
1200 }
1201 
1202 static int
1203 vnode_pager_generic_getpages_done(struct buf *bp)
1204 {
1205 	vm_object_t object;
1206 	off_t tfoff, nextoff;
1207 	int i, error;
1208 
1209 	KASSERT((bp->b_ioflags & BIO_ERROR) == 0 || bp->b_error != 0,
1210 	    ("%s: buf error but b_error == 0\n", __func__));
1211 	error = (bp->b_ioflags & BIO_ERROR) != 0 ? bp->b_error : 0;
1212 	object = bp->b_vp->v_object;
1213 
1214 	runningbufwakeup(bp);
1215 
1216 	if (error == 0 && bp->b_bcount != bp->b_npages * PAGE_SIZE) {
1217 		if (!buf_mapped(bp)) {
1218 			bp->b_data = bp->b_kvabase;
1219 			pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages,
1220 			    bp->b_npages);
1221 		}
1222 		bzero(bp->b_data + bp->b_bcount,
1223 		    PAGE_SIZE * bp->b_npages - bp->b_bcount);
1224 	}
1225 	if (buf_mapped(bp)) {
1226 		pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1227 		bp->b_data = unmapped_buf;
1228 	}
1229 
1230 	/*
1231 	 * If the read failed, we must free any read ahead/behind pages here.
1232 	 * The requested pages are freed by the caller (for sync requests)
1233 	 * or by the bp->b_pgiodone callback (for async requests).
1234 	 */
1235 	if (error != 0) {
1236 		VM_OBJECT_WLOCK(object);
1237 		for (i = 0; i < bp->b_pgbefore; i++)
1238 			vm_page_free_invalid(bp->b_pages[i]);
1239 		for (i = bp->b_npages - bp->b_pgafter; i < bp->b_npages; i++)
1240 			vm_page_free_invalid(bp->b_pages[i]);
1241 		VM_OBJECT_WUNLOCK(object);
1242 		return (error);
1243 	}
1244 
1245 	/* Read lock to protect size. */
1246 	VM_OBJECT_RLOCK(object);
1247 	for (i = 0, tfoff = IDX_TO_OFF(bp->b_pages[0]->pindex);
1248 	    i < bp->b_npages; i++, tfoff = nextoff) {
1249 		vm_page_t mt;
1250 
1251 		nextoff = tfoff + PAGE_SIZE;
1252 		mt = bp->b_pages[i];
1253 		if (mt == bogus_page)
1254 			continue;
1255 
1256 		if (nextoff <= object->un_pager.vnp.vnp_size) {
1257 			/*
1258 			 * Read filled up entire page.
1259 			 */
1260 			vm_page_valid(mt);
1261 			KASSERT(mt->dirty == 0,
1262 			    ("%s: page %p is dirty", __func__, mt));
1263 			KASSERT(!pmap_page_is_mapped(mt),
1264 			    ("%s: page %p is mapped", __func__, mt));
1265 		} else {
1266 			/*
1267 			 * Read did not fill up entire page.
1268 			 *
1269 			 * Currently we do not set the entire page valid,
1270 			 * we just try to clear the piece that we couldn't
1271 			 * read.
1272 			 */
1273 			vm_page_set_valid_range(mt, 0,
1274 			    object->un_pager.vnp.vnp_size - tfoff);
1275 			KASSERT((mt->dirty & vm_page_bits(0,
1276 			    object->un_pager.vnp.vnp_size - tfoff)) == 0,
1277 			    ("%s: page %p is dirty", __func__, mt));
1278 		}
1279 
1280 		if (i < bp->b_pgbefore || i >= bp->b_npages - bp->b_pgafter)
1281 			vm_page_readahead_finish(mt);
1282 	}
1283 	VM_OBJECT_RUNLOCK(object);
1284 
1285 	return (error);
1286 }
1287 
1288 /*
1289  * EOPNOTSUPP is no longer legal.  For local media VFS's that do not
1290  * implement their own VOP_PUTPAGES, their VOP_PUTPAGES should call to
1291  * vnode_pager_generic_putpages() to implement the previous behaviour.
1292  *
1293  * All other FS's should use the bypass to get to the local media
1294  * backing vp's VOP_PUTPAGES.
1295  */
1296 static void
1297 vnode_pager_putpages(vm_object_t object, vm_page_t *m, int count,
1298     int flags, int *rtvals)
1299 {
1300 	int rtval __diagused;
1301 	struct vnode *vp;
1302 	int bytes = count * PAGE_SIZE;
1303 
1304 	/*
1305 	 * Force synchronous operation if we are extremely low on memory
1306 	 * to prevent a low-memory deadlock.  VOP operations often need to
1307 	 * allocate more memory to initiate the I/O ( i.e. do a BMAP
1308 	 * operation ).  The swapper handles the case by limiting the amount
1309 	 * of asynchronous I/O, but that sort of solution doesn't scale well
1310 	 * for the vnode pager without a lot of work.
1311 	 *
1312 	 * Also, the backing vnode's iodone routine may not wake the pageout
1313 	 * daemon up.  This should be probably be addressed XXX.
1314 	 */
1315 
1316 	if (vm_page_count_min())
1317 		flags |= VM_PAGER_PUT_SYNC;
1318 
1319 	/*
1320 	 * Call device-specific putpages function
1321 	 */
1322 	vp = object->handle;
1323 	VM_OBJECT_WUNLOCK(object);
1324 	rtval = VOP_PUTPAGES(vp, m, bytes, flags, rtvals);
1325 	KASSERT(rtval != EOPNOTSUPP,
1326 	    ("vnode_pager: stale FS putpages\n"));
1327 	VM_OBJECT_WLOCK(object);
1328 }
1329 
1330 static int
1331 vn_off2bidx(vm_ooffset_t offset)
1332 {
1333 
1334 	return ((offset & PAGE_MASK) / DEV_BSIZE);
1335 }
1336 
1337 static bool
1338 vn_dirty_blk(vm_page_t m, vm_ooffset_t offset)
1339 {
1340 
1341 	KASSERT(IDX_TO_OFF(m->pindex) <= offset &&
1342 	    offset < IDX_TO_OFF(m->pindex + 1),
1343 	    ("page %p pidx %ju offset %ju", m, (uintmax_t)m->pindex,
1344 	    (uintmax_t)offset));
1345 	return ((m->dirty & ((vm_page_bits_t)1 << vn_off2bidx(offset))) != 0);
1346 }
1347 
1348 /*
1349  * This is now called from local media FS's to operate against their
1350  * own vnodes if they fail to implement VOP_PUTPAGES.
1351  *
1352  * This is typically called indirectly via the pageout daemon and
1353  * clustering has already typically occurred, so in general we ask the
1354  * underlying filesystem to write the data out asynchronously rather
1355  * then delayed.
1356  */
1357 int
1358 vnode_pager_generic_putpages(struct vnode *vp, vm_page_t *ma, int bytecount,
1359     int flags, int *rtvals)
1360 {
1361 	vm_object_t object;
1362 	vm_page_t m;
1363 	vm_ooffset_t maxblksz, next_offset, poffset, prev_offset;
1364 	struct uio auio;
1365 	struct iovec aiov;
1366 	off_t prev_resid, wrsz;
1367 	int count, error, i, maxsize, ncount, pgoff, ppscheck;
1368 	bool in_hole;
1369 	static struct timeval lastfail;
1370 	static int curfail;
1371 
1372 	object = vp->v_object;
1373 	count = bytecount / PAGE_SIZE;
1374 
1375 	for (i = 0; i < count; i++)
1376 		rtvals[i] = VM_PAGER_ERROR;
1377 
1378 	if ((int64_t)ma[0]->pindex < 0) {
1379 		printf("vnode_pager_generic_putpages: "
1380 		    "attempt to write meta-data 0x%jx(%lx)\n",
1381 		    (uintmax_t)ma[0]->pindex, (u_long)ma[0]->dirty);
1382 		rtvals[0] = VM_PAGER_BAD;
1383 		return (VM_PAGER_BAD);
1384 	}
1385 
1386 	maxsize = count * PAGE_SIZE;
1387 	ncount = count;
1388 
1389 	poffset = IDX_TO_OFF(ma[0]->pindex);
1390 
1391 	/*
1392 	 * If the page-aligned write is larger then the actual file we
1393 	 * have to invalidate pages occurring beyond the file EOF.  However,
1394 	 * there is an edge case where a file may not be page-aligned where
1395 	 * the last page is partially invalid.  In this case the filesystem
1396 	 * may not properly clear the dirty bits for the entire page (which
1397 	 * could be VM_PAGE_BITS_ALL due to the page having been mmap()d).
1398 	 * With the page busied we are free to fix up the dirty bits here.
1399 	 *
1400 	 * We do not under any circumstances truncate the valid bits, as
1401 	 * this will screw up bogus page replacement.
1402 	 */
1403 	VM_OBJECT_RLOCK(object);
1404 	if (maxsize + poffset > object->un_pager.vnp.vnp_size) {
1405 		if (object->un_pager.vnp.vnp_size > poffset) {
1406 			maxsize = object->un_pager.vnp.vnp_size - poffset;
1407 			ncount = btoc(maxsize);
1408 			if ((pgoff = (int)maxsize & PAGE_MASK) != 0) {
1409 				pgoff = roundup2(pgoff, DEV_BSIZE);
1410 
1411 				/*
1412 				 * If the page is busy and the following
1413 				 * conditions hold, then the page's dirty
1414 				 * field cannot be concurrently changed by a
1415 				 * pmap operation.
1416 				 */
1417 				m = ma[ncount - 1];
1418 				vm_page_assert_sbusied(m);
1419 				KASSERT(!pmap_page_is_write_mapped(m),
1420 		("vnode_pager_generic_putpages: page %p is not read-only", m));
1421 				MPASS(m->dirty != 0);
1422 				vm_page_clear_dirty(m, pgoff, PAGE_SIZE -
1423 				    pgoff);
1424 			}
1425 		} else {
1426 			maxsize = 0;
1427 			ncount = 0;
1428 		}
1429 		for (i = ncount; i < count; i++)
1430 			rtvals[i] = VM_PAGER_BAD;
1431 	}
1432 	VM_OBJECT_RUNLOCK(object);
1433 
1434 	auio.uio_iov = &aiov;
1435 	auio.uio_segflg = UIO_NOCOPY;
1436 	auio.uio_rw = UIO_WRITE;
1437 	auio.uio_td = NULL;
1438 	maxblksz = roundup2(poffset + maxsize, DEV_BSIZE);
1439 
1440 	for (prev_offset = poffset; prev_offset < maxblksz;) {
1441 		/* Skip clean blocks. */
1442 		for (in_hole = true; in_hole && prev_offset < maxblksz;) {
1443 			m = ma[OFF_TO_IDX(prev_offset - poffset)];
1444 			for (i = vn_off2bidx(prev_offset);
1445 			    i < sizeof(vm_page_bits_t) * NBBY &&
1446 			    prev_offset < maxblksz; i++) {
1447 				if (vn_dirty_blk(m, prev_offset)) {
1448 					in_hole = false;
1449 					break;
1450 				}
1451 				prev_offset += DEV_BSIZE;
1452 			}
1453 		}
1454 		if (in_hole)
1455 			goto write_done;
1456 
1457 		/* Find longest run of dirty blocks. */
1458 		for (next_offset = prev_offset; next_offset < maxblksz;) {
1459 			m = ma[OFF_TO_IDX(next_offset - poffset)];
1460 			for (i = vn_off2bidx(next_offset);
1461 			    i < sizeof(vm_page_bits_t) * NBBY &&
1462 			    next_offset < maxblksz; i++) {
1463 				if (!vn_dirty_blk(m, next_offset))
1464 					goto start_write;
1465 				next_offset += DEV_BSIZE;
1466 			}
1467 		}
1468 start_write:
1469 		if (next_offset > poffset + maxsize)
1470 			next_offset = poffset + maxsize;
1471 
1472 		/*
1473 		 * Getting here requires finding a dirty block in the
1474 		 * 'skip clean blocks' loop.
1475 		 */
1476 		MPASS(prev_offset < next_offset);
1477 
1478 		aiov.iov_base = NULL;
1479 		auio.uio_iovcnt = 1;
1480 		auio.uio_offset = prev_offset;
1481 		prev_resid = auio.uio_resid = aiov.iov_len = next_offset -
1482 		    prev_offset;
1483 		error = VOP_WRITE(vp, &auio,
1484 		    vnode_pager_putpages_ioflags(flags), curthread->td_ucred);
1485 
1486 		wrsz = prev_resid - auio.uio_resid;
1487 		if (wrsz == 0) {
1488 			if (ppsratecheck(&lastfail, &curfail, 1) != 0) {
1489 				vn_printf(vp, "vnode_pager_putpages: "
1490 				    "zero-length write at %ju resid %zd\n",
1491 				    auio.uio_offset, auio.uio_resid);
1492 			}
1493 			break;
1494 		}
1495 
1496 		/* Adjust the starting offset for next iteration. */
1497 		prev_offset += wrsz;
1498 		MPASS(auio.uio_offset == prev_offset);
1499 
1500 		ppscheck = 0;
1501 		if (error != 0 && (ppscheck = ppsratecheck(&lastfail,
1502 		    &curfail, 1)) != 0)
1503 			vn_printf(vp, "vnode_pager_putpages: I/O error %d\n",
1504 			    error);
1505 		if (auio.uio_resid != 0 && (ppscheck != 0 ||
1506 		    ppsratecheck(&lastfail, &curfail, 1) != 0))
1507 			vn_printf(vp, "vnode_pager_putpages: residual I/O %zd "
1508 			    "at %ju\n", auio.uio_resid,
1509 			    (uintmax_t)ma[0]->pindex);
1510 		if (error != 0 || auio.uio_resid != 0)
1511 			break;
1512 	}
1513 write_done:
1514 	/* Mark completely processed pages. */
1515 	for (i = 0; i < OFF_TO_IDX(prev_offset - poffset); i++)
1516 		rtvals[i] = VM_PAGER_OK;
1517 	/* Mark partial EOF page. */
1518 	if (prev_offset == poffset + maxsize && (prev_offset & PAGE_MASK) != 0)
1519 		rtvals[i++] = VM_PAGER_OK;
1520 	/* Unwritten pages in range, free bonus if the page is clean. */
1521 	for (; i < ncount; i++)
1522 		rtvals[i] = ma[i]->dirty == 0 ? VM_PAGER_OK : VM_PAGER_ERROR;
1523 	VM_CNT_ADD(v_vnodepgsout, i);
1524 	VM_CNT_INC(v_vnodeout);
1525 	return (rtvals[0]);
1526 }
1527 
1528 int
1529 vnode_pager_putpages_ioflags(int pager_flags)
1530 {
1531 	int ioflags;
1532 
1533 	/*
1534 	 * Pageouts are already clustered, use IO_ASYNC to force a
1535 	 * bawrite() rather then a bdwrite() to prevent paging I/O
1536 	 * from saturating the buffer cache.  Dummy-up the sequential
1537 	 * heuristic to cause large ranges to cluster.  If neither
1538 	 * IO_SYNC or IO_ASYNC is set, the system decides how to
1539 	 * cluster.
1540 	 */
1541 	ioflags = IO_VMIO;
1542 	if ((pager_flags & (VM_PAGER_PUT_SYNC | VM_PAGER_PUT_INVAL)) != 0)
1543 		ioflags |= IO_SYNC;
1544 	else if ((pager_flags & VM_PAGER_CLUSTER_OK) == 0)
1545 		ioflags |= IO_ASYNC;
1546 	ioflags |= (pager_flags & VM_PAGER_PUT_INVAL) != 0 ? IO_INVAL: 0;
1547 	ioflags |= (pager_flags & VM_PAGER_PUT_NOREUSE) != 0 ? IO_NOREUSE : 0;
1548 	ioflags |= IO_SEQMAX << IO_SEQSHIFT;
1549 	return (ioflags);
1550 }
1551 
1552 /*
1553  * vnode_pager_undirty_pages().
1554  *
1555  * A helper to mark pages as clean after pageout that was possibly
1556  * done with a short write.  The lpos argument specifies the page run
1557  * length in bytes, and the written argument specifies how many bytes
1558  * were actually written.  eof is the offset past the last valid byte
1559  * in the vnode using the absolute file position of the first byte in
1560  * the run as the base from which it is computed.
1561  */
1562 void
1563 vnode_pager_undirty_pages(vm_page_t *ma, int *rtvals, int written, off_t eof,
1564     int lpos)
1565 {
1566 	int i, pos, pos_devb;
1567 
1568 	if (written == 0 && eof >= lpos)
1569 		return;
1570 	for (i = 0, pos = 0; pos < written; i++, pos += PAGE_SIZE) {
1571 		if (pos < trunc_page(written)) {
1572 			rtvals[i] = VM_PAGER_OK;
1573 			vm_page_undirty(ma[i]);
1574 		} else {
1575 			/* Partially written page. */
1576 			rtvals[i] = VM_PAGER_AGAIN;
1577 			vm_page_clear_dirty(ma[i], 0, written & PAGE_MASK);
1578 		}
1579 	}
1580 	if (eof >= lpos) /* avoid truncation */
1581 		return;
1582 	for (pos = eof, i = OFF_TO_IDX(trunc_page(pos)); pos < lpos; i++) {
1583 		if (pos != trunc_page(pos)) {
1584 			/*
1585 			 * The page contains the last valid byte in
1586 			 * the vnode, mark the rest of the page as
1587 			 * clean, potentially making the whole page
1588 			 * clean.
1589 			 */
1590 			pos_devb = roundup2(pos & PAGE_MASK, DEV_BSIZE);
1591 			vm_page_clear_dirty(ma[i], pos_devb, PAGE_SIZE -
1592 			    pos_devb);
1593 
1594 			/*
1595 			 * If the page was cleaned, report the pageout
1596 			 * on it as successful.  msync() no longer
1597 			 * needs to write out the page, endlessly
1598 			 * creating write requests and dirty buffers.
1599 			 */
1600 			if (ma[i]->dirty == 0)
1601 				rtvals[i] = VM_PAGER_OK;
1602 
1603 			pos = round_page(pos);
1604 		} else {
1605 			/* vm_pageout_flush() clears dirty */
1606 			rtvals[i] = VM_PAGER_BAD;
1607 			pos += PAGE_SIZE;
1608 		}
1609 	}
1610 }
1611 
1612 static void
1613 vnode_pager_update_writecount(vm_object_t object, vm_offset_t start,
1614     vm_offset_t end)
1615 {
1616 	struct vnode *vp;
1617 	vm_ooffset_t old_wm;
1618 
1619 	VM_OBJECT_WLOCK(object);
1620 	if (object->type != OBJT_VNODE) {
1621 		VM_OBJECT_WUNLOCK(object);
1622 		return;
1623 	}
1624 	old_wm = object->un_pager.vnp.writemappings;
1625 	object->un_pager.vnp.writemappings += (vm_ooffset_t)end - start;
1626 	vp = object->handle;
1627 	if (old_wm == 0 && object->un_pager.vnp.writemappings != 0) {
1628 		ASSERT_VOP_LOCKED(vp, "v_writecount inc");
1629 		VOP_ADD_WRITECOUNT_CHECKED(vp, 1);
1630 		CTR3(KTR_VFS, "%s: vp %p v_writecount increased to %d",
1631 		    __func__, vp, vp->v_writecount);
1632 	} else if (old_wm != 0 && object->un_pager.vnp.writemappings == 0) {
1633 		ASSERT_VOP_LOCKED(vp, "v_writecount dec");
1634 		VOP_ADD_WRITECOUNT_CHECKED(vp, -1);
1635 		CTR3(KTR_VFS, "%s: vp %p v_writecount decreased to %d",
1636 		    __func__, vp, vp->v_writecount);
1637 	}
1638 	VM_OBJECT_WUNLOCK(object);
1639 }
1640 
1641 static void
1642 vnode_pager_release_writecount(vm_object_t object, vm_offset_t start,
1643     vm_offset_t end)
1644 {
1645 	struct vnode *vp;
1646 	struct mount *mp;
1647 	vm_offset_t inc;
1648 
1649 	VM_OBJECT_WLOCK(object);
1650 
1651 	/*
1652 	 * First, recheck the object type to account for the race when
1653 	 * the vnode is reclaimed.
1654 	 */
1655 	if (object->type != OBJT_VNODE) {
1656 		VM_OBJECT_WUNLOCK(object);
1657 		return;
1658 	}
1659 
1660 	/*
1661 	 * Optimize for the case when writemappings is not going to
1662 	 * zero.
1663 	 */
1664 	inc = end - start;
1665 	if (object->un_pager.vnp.writemappings != inc) {
1666 		object->un_pager.vnp.writemappings -= inc;
1667 		VM_OBJECT_WUNLOCK(object);
1668 		return;
1669 	}
1670 
1671 	vp = object->handle;
1672 	vhold(vp);
1673 	VM_OBJECT_WUNLOCK(object);
1674 	mp = NULL;
1675 	vn_start_write(vp, &mp, V_WAIT);
1676 	vn_lock(vp, LK_SHARED | LK_RETRY);
1677 
1678 	/*
1679 	 * Decrement the object's writemappings, by swapping the start
1680 	 * and end arguments for vnode_pager_update_writecount().  If
1681 	 * there was not a race with vnode reclaimation, then the
1682 	 * vnode's v_writecount is decremented.
1683 	 */
1684 	vnode_pager_update_writecount(object, end, start);
1685 	VOP_UNLOCK(vp);
1686 	vdrop(vp);
1687 	if (mp != NULL)
1688 		vn_finished_write(mp);
1689 }
1690 
1691 static void
1692 vnode_pager_getvp(vm_object_t object, struct vnode **vpp, bool *vp_heldp)
1693 {
1694 	*vpp = object->handle;
1695 }
1696