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