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