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