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