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