xref: /netbsd-src/sys/miscfs/genfs/genfs_io.c (revision f3cfa6f6ce31685c6c4a758bc430e69eb99f50a4)
1 /*	$NetBSD: genfs_io.c,v 1.74 2018/12/10 21:10:52 jdolecek Exp $	*/
2 
3 /*
4  * Copyright (c) 1982, 1986, 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  */
32 
33 #include <sys/cdefs.h>
34 __KERNEL_RCSID(0, "$NetBSD: genfs_io.c,v 1.74 2018/12/10 21:10:52 jdolecek Exp $");
35 
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/proc.h>
39 #include <sys/kernel.h>
40 #include <sys/mount.h>
41 #include <sys/vnode.h>
42 #include <sys/kmem.h>
43 #include <sys/kauth.h>
44 #include <sys/fstrans.h>
45 #include <sys/buf.h>
46 
47 #include <miscfs/genfs/genfs.h>
48 #include <miscfs/genfs/genfs_node.h>
49 #include <miscfs/specfs/specdev.h>
50 
51 #include <uvm/uvm.h>
52 #include <uvm/uvm_pager.h>
53 
54 static int genfs_do_directio(struct vmspace *, vaddr_t, size_t, struct vnode *,
55     off_t, enum uio_rw);
56 static void genfs_dio_iodone(struct buf *);
57 
58 static int genfs_getpages_read(struct vnode *, struct vm_page **, int, off_t,
59     off_t, bool, bool, bool, bool);
60 static int genfs_do_io(struct vnode *, off_t, vaddr_t, size_t, int, enum uio_rw,
61     void (*)(struct buf *));
62 static void genfs_rel_pages(struct vm_page **, unsigned int);
63 static void genfs_markdirty(struct vnode *);
64 
65 int genfs_maxdio = MAXPHYS;
66 
67 static void
68 genfs_rel_pages(struct vm_page **pgs, unsigned int npages)
69 {
70 	unsigned int i;
71 
72 	for (i = 0; i < npages; i++) {
73 		struct vm_page *pg = pgs[i];
74 
75 		if (pg == NULL || pg == PGO_DONTCARE)
76 			continue;
77 		KASSERT(uvm_page_locked_p(pg));
78 		if (pg->flags & PG_FAKE) {
79 			pg->flags |= PG_RELEASED;
80 		}
81 	}
82 	mutex_enter(&uvm_pageqlock);
83 	uvm_page_unbusy(pgs, npages);
84 	mutex_exit(&uvm_pageqlock);
85 }
86 
87 static void
88 genfs_markdirty(struct vnode *vp)
89 {
90 	struct genfs_node * const gp = VTOG(vp);
91 
92 	KASSERT(mutex_owned(vp->v_interlock));
93 	gp->g_dirtygen++;
94 	if ((vp->v_iflag & VI_ONWORKLST) == 0) {
95 		vn_syncer_add_to_worklist(vp, filedelay);
96 	}
97 	if ((vp->v_iflag & (VI_WRMAP|VI_WRMAPDIRTY)) == VI_WRMAP) {
98 		vp->v_iflag |= VI_WRMAPDIRTY;
99 	}
100 }
101 
102 /*
103  * generic VM getpages routine.
104  * Return PG_BUSY pages for the given range,
105  * reading from backing store if necessary.
106  */
107 
108 int
109 genfs_getpages(void *v)
110 {
111 	struct vop_getpages_args /* {
112 		struct vnode *a_vp;
113 		voff_t a_offset;
114 		struct vm_page **a_m;
115 		int *a_count;
116 		int a_centeridx;
117 		vm_prot_t a_access_type;
118 		int a_advice;
119 		int a_flags;
120 	} */ * const ap = v;
121 
122 	off_t diskeof, memeof;
123 	int i, error, npages;
124 	const int flags = ap->a_flags;
125 	struct vnode * const vp = ap->a_vp;
126 	struct uvm_object * const uobj = &vp->v_uobj;
127 	const bool async = (flags & PGO_SYNCIO) == 0;
128 	const bool memwrite = (ap->a_access_type & VM_PROT_WRITE) != 0;
129 	const bool overwrite = (flags & PGO_OVERWRITE) != 0;
130 	const bool blockalloc = memwrite && (flags & PGO_NOBLOCKALLOC) == 0;
131 	const bool need_wapbl = (vp->v_mount->mnt_wapbl &&
132 			(flags & PGO_JOURNALLOCKED) == 0);
133 	const bool glocked = (flags & PGO_GLOCKHELD) != 0;
134 	bool holds_wapbl = false;
135 	struct mount *trans_mount = NULL;
136 	UVMHIST_FUNC("genfs_getpages"); UVMHIST_CALLED(ubchist);
137 
138 	UVMHIST_LOG(ubchist, "vp %#jx off 0x%jx/%jx count %jd",
139 	    (uintptr_t)vp, ap->a_offset >> 32, ap->a_offset, *ap->a_count);
140 
141 	KASSERT(vp->v_type == VREG || vp->v_type == VDIR ||
142 	    vp->v_type == VLNK || vp->v_type == VBLK);
143 
144 #ifdef DIAGNOSTIC
145 	if ((flags & PGO_JOURNALLOCKED) && vp->v_mount->mnt_wapbl)
146                 WAPBL_JLOCK_ASSERT(vp->v_mount);
147 #endif
148 
149 	error = vdead_check(vp, VDEAD_NOWAIT);
150 	if (error) {
151 		if ((flags & PGO_LOCKED) == 0)
152 			mutex_exit(uobj->vmobjlock);
153 		return error;
154 	}
155 
156 startover:
157 	error = 0;
158 	const voff_t origvsize = vp->v_size;
159 	const off_t origoffset = ap->a_offset;
160 	const int orignpages = *ap->a_count;
161 
162 	GOP_SIZE(vp, origvsize, &diskeof, 0);
163 	if (flags & PGO_PASTEOF) {
164 		off_t newsize;
165 #if defined(DIAGNOSTIC)
166 		off_t writeeof;
167 #endif /* defined(DIAGNOSTIC) */
168 
169 		newsize = MAX(origvsize,
170 		    origoffset + (orignpages << PAGE_SHIFT));
171 		GOP_SIZE(vp, newsize, &memeof, GOP_SIZE_MEM);
172 #if defined(DIAGNOSTIC)
173 		GOP_SIZE(vp, vp->v_writesize, &writeeof, GOP_SIZE_MEM);
174 		if (newsize > round_page(writeeof)) {
175 			panic("%s: past eof: %" PRId64 " vs. %" PRId64,
176 			    __func__, newsize, round_page(writeeof));
177 		}
178 #endif /* defined(DIAGNOSTIC) */
179 	} else {
180 		GOP_SIZE(vp, origvsize, &memeof, GOP_SIZE_MEM);
181 	}
182 	KASSERT(ap->a_centeridx >= 0 || ap->a_centeridx <= orignpages);
183 	KASSERT((origoffset & (PAGE_SIZE - 1)) == 0 && origoffset >= 0);
184 	KASSERT(orignpages > 0);
185 
186 	/*
187 	 * Bounds-check the request.
188 	 */
189 
190 	if (origoffset + (ap->a_centeridx << PAGE_SHIFT) >= memeof) {
191 		if ((flags & PGO_LOCKED) == 0) {
192 			mutex_exit(uobj->vmobjlock);
193 		}
194 		UVMHIST_LOG(ubchist, "off 0x%jx count %jd goes past EOF 0x%jx",
195 		    origoffset, *ap->a_count, memeof,0);
196 		error = EINVAL;
197 		goto out_err;
198 	}
199 
200 	/* uobj is locked */
201 
202 	if ((flags & PGO_NOTIMESTAMP) == 0 &&
203 	    (vp->v_type != VBLK ||
204 	    (vp->v_mount->mnt_flag & MNT_NODEVMTIME) == 0)) {
205 		int updflags = 0;
206 
207 		if ((vp->v_mount->mnt_flag & MNT_NOATIME) == 0) {
208 			updflags = GOP_UPDATE_ACCESSED;
209 		}
210 		if (memwrite) {
211 			updflags |= GOP_UPDATE_MODIFIED;
212 		}
213 		if (updflags != 0) {
214 			GOP_MARKUPDATE(vp, updflags);
215 		}
216 	}
217 
218 	/*
219 	 * For PGO_LOCKED requests, just return whatever's in memory.
220 	 */
221 
222 	if (flags & PGO_LOCKED) {
223 		int nfound;
224 		struct vm_page *pg;
225 
226 		KASSERT(!glocked);
227 		npages = *ap->a_count;
228 #if defined(DEBUG)
229 		for (i = 0; i < npages; i++) {
230 			pg = ap->a_m[i];
231 			KASSERT(pg == NULL || pg == PGO_DONTCARE);
232 		}
233 #endif /* defined(DEBUG) */
234 		nfound = uvn_findpages(uobj, origoffset, &npages,
235 		    ap->a_m, UFP_NOWAIT|UFP_NOALLOC|(memwrite ? UFP_NORDONLY : 0));
236 		KASSERT(npages == *ap->a_count);
237 		if (nfound == 0) {
238 			error = EBUSY;
239 			goto out_err;
240 		}
241 		if (!genfs_node_rdtrylock(vp)) {
242 			genfs_rel_pages(ap->a_m, npages);
243 
244 			/*
245 			 * restore the array.
246 			 */
247 
248 			for (i = 0; i < npages; i++) {
249 				pg = ap->a_m[i];
250 
251 				if (pg != NULL && pg != PGO_DONTCARE) {
252 					ap->a_m[i] = NULL;
253 				}
254 				KASSERT(ap->a_m[i] == NULL ||
255 				    ap->a_m[i] == PGO_DONTCARE);
256 			}
257 		} else {
258 			genfs_node_unlock(vp);
259 		}
260 		error = (ap->a_m[ap->a_centeridx] == NULL ? EBUSY : 0);
261 		if (error == 0 && memwrite) {
262 			genfs_markdirty(vp);
263 		}
264 		goto out_err;
265 	}
266 	mutex_exit(uobj->vmobjlock);
267 
268 	/*
269 	 * find the requested pages and make some simple checks.
270 	 * leave space in the page array for a whole block.
271 	 */
272 
273 	const int fs_bshift = (vp->v_type != VBLK) ?
274 	    vp->v_mount->mnt_fs_bshift : DEV_BSHIFT;
275 	const int fs_bsize = 1 << fs_bshift;
276 #define	blk_mask	(fs_bsize - 1)
277 #define	trunc_blk(x)	((x) & ~blk_mask)
278 #define	round_blk(x)	(((x) + blk_mask) & ~blk_mask)
279 
280 	const int orignmempages = MIN(orignpages,
281 	    round_page(memeof - origoffset) >> PAGE_SHIFT);
282 	npages = orignmempages;
283 	const off_t startoffset = trunc_blk(origoffset);
284 	const off_t endoffset = MIN(
285 	    round_page(round_blk(origoffset + (npages << PAGE_SHIFT))),
286 	    round_page(memeof));
287 	const int ridx = (origoffset - startoffset) >> PAGE_SHIFT;
288 
289 	const int pgs_size = sizeof(struct vm_page *) *
290 	    ((endoffset - startoffset) >> PAGE_SHIFT);
291 	struct vm_page **pgs, *pgs_onstack[UBC_MAX_PAGES];
292 
293 	if (pgs_size > sizeof(pgs_onstack)) {
294 		pgs = kmem_zalloc(pgs_size, async ? KM_NOSLEEP : KM_SLEEP);
295 		if (pgs == NULL) {
296 			pgs = pgs_onstack;
297 			error = ENOMEM;
298 			goto out_err;
299 		}
300 	} else {
301 		pgs = pgs_onstack;
302 		(void)memset(pgs, 0, pgs_size);
303 	}
304 
305 	UVMHIST_LOG(ubchist, "ridx %jd npages %jd startoff %jd endoff %jd",
306 	    ridx, npages, startoffset, endoffset);
307 
308 	if (trans_mount == NULL) {
309 		trans_mount = vp->v_mount;
310 		fstrans_start(trans_mount);
311 		/*
312 		 * check if this vnode is still valid.
313 		 */
314 		mutex_enter(vp->v_interlock);
315 		error = vdead_check(vp, 0);
316 		mutex_exit(vp->v_interlock);
317 		if (error)
318 			goto out_err_free;
319 		/*
320 		 * XXX: This assumes that we come here only via
321 		 * the mmio path
322 		 */
323 		if (blockalloc && need_wapbl) {
324 			error = WAPBL_BEGIN(trans_mount);
325 			if (error)
326 				goto out_err_free;
327 			holds_wapbl = true;
328 		}
329 	}
330 
331 	/*
332 	 * hold g_glock to prevent a race with truncate.
333 	 *
334 	 * check if our idea of v_size is still valid.
335 	 */
336 
337 	KASSERT(!glocked || genfs_node_wrlocked(vp));
338 	if (!glocked) {
339 		if (blockalloc) {
340 			genfs_node_wrlock(vp);
341 		} else {
342 			genfs_node_rdlock(vp);
343 		}
344 	}
345 	mutex_enter(uobj->vmobjlock);
346 	if (vp->v_size < origvsize) {
347 		if (!glocked) {
348 			genfs_node_unlock(vp);
349 		}
350 		if (pgs != pgs_onstack)
351 			kmem_free(pgs, pgs_size);
352 		goto startover;
353 	}
354 
355 	if (uvn_findpages(uobj, origoffset, &npages, &pgs[ridx],
356 	    async ? UFP_NOWAIT : UFP_ALL) != orignmempages) {
357 		if (!glocked) {
358 			genfs_node_unlock(vp);
359 		}
360 		KASSERT(async != 0);
361 		genfs_rel_pages(&pgs[ridx], orignmempages);
362 		mutex_exit(uobj->vmobjlock);
363 		error = EBUSY;
364 		goto out_err_free;
365 	}
366 
367 	/*
368 	 * if the pages are already resident, just return them.
369 	 */
370 
371 	for (i = 0; i < npages; i++) {
372 		struct vm_page *pg = pgs[ridx + i];
373 
374 		if ((pg->flags & PG_FAKE) ||
375 		    (blockalloc && (pg->flags & PG_RDONLY))) {
376 			break;
377 		}
378 	}
379 	if (i == npages) {
380 		if (!glocked) {
381 			genfs_node_unlock(vp);
382 		}
383 		UVMHIST_LOG(ubchist, "returning cached pages", 0,0,0,0);
384 		npages += ridx;
385 		goto out;
386 	}
387 
388 	/*
389 	 * if PGO_OVERWRITE is set, don't bother reading the pages.
390 	 */
391 
392 	if (overwrite) {
393 		if (!glocked) {
394 			genfs_node_unlock(vp);
395 		}
396 		UVMHIST_LOG(ubchist, "PGO_OVERWRITE",0,0,0,0);
397 
398 		for (i = 0; i < npages; i++) {
399 			struct vm_page *pg = pgs[ridx + i];
400 
401 			pg->flags &= ~(PG_RDONLY|PG_CLEAN);
402 		}
403 		npages += ridx;
404 		goto out;
405 	}
406 
407 	/*
408 	 * the page wasn't resident and we're not overwriting,
409 	 * so we're going to have to do some i/o.
410 	 * find any additional pages needed to cover the expanded range.
411 	 */
412 
413 	npages = (endoffset - startoffset) >> PAGE_SHIFT;
414 	if (startoffset != origoffset || npages != orignmempages) {
415 		int npgs;
416 
417 		/*
418 		 * we need to avoid deadlocks caused by locking
419 		 * additional pages at lower offsets than pages we
420 		 * already have locked.  unlock them all and start over.
421 		 */
422 
423 		genfs_rel_pages(&pgs[ridx], orignmempages);
424 		memset(pgs, 0, pgs_size);
425 
426 		UVMHIST_LOG(ubchist, "reset npages start 0x%jx end 0x%jx",
427 		    startoffset, endoffset, 0,0);
428 		npgs = npages;
429 		if (uvn_findpages(uobj, startoffset, &npgs, pgs,
430 		    async ? UFP_NOWAIT : UFP_ALL) != npages) {
431 			if (!glocked) {
432 				genfs_node_unlock(vp);
433 			}
434 			KASSERT(async != 0);
435 			genfs_rel_pages(pgs, npages);
436 			mutex_exit(uobj->vmobjlock);
437 			error = EBUSY;
438 			goto out_err_free;
439 		}
440 	}
441 
442 	mutex_exit(uobj->vmobjlock);
443 	error = genfs_getpages_read(vp, pgs, npages, startoffset, diskeof,
444 	    async, memwrite, blockalloc, glocked);
445 	if (!glocked) {
446 		genfs_node_unlock(vp);
447 	}
448 	if (error == 0 && async)
449 		goto out_err_free;
450 	mutex_enter(uobj->vmobjlock);
451 
452 	/*
453 	 * we're almost done!  release the pages...
454 	 * for errors, we free the pages.
455 	 * otherwise we activate them and mark them as valid and clean.
456 	 * also, unbusy pages that were not actually requested.
457 	 */
458 
459 	if (error) {
460 		genfs_rel_pages(pgs, npages);
461 		mutex_exit(uobj->vmobjlock);
462 		UVMHIST_LOG(ubchist, "returning error %jd", error,0,0,0);
463 		goto out_err_free;
464 	}
465 
466 out:
467 	UVMHIST_LOG(ubchist, "succeeding, npages %jd", npages,0,0,0);
468 	error = 0;
469 	mutex_enter(&uvm_pageqlock);
470 	for (i = 0; i < npages; i++) {
471 		struct vm_page *pg = pgs[i];
472 		if (pg == NULL) {
473 			continue;
474 		}
475 		UVMHIST_LOG(ubchist, "examining pg %#jx flags 0x%jx",
476 		    (uintptr_t)pg, pg->flags, 0,0);
477 		if (pg->flags & PG_FAKE && !overwrite) {
478 			pg->flags &= ~(PG_FAKE);
479 			pmap_clear_modify(pgs[i]);
480 		}
481 		KASSERT(!memwrite || !blockalloc || (pg->flags & PG_RDONLY) == 0);
482 		if (i < ridx || i >= ridx + orignmempages || async) {
483 			UVMHIST_LOG(ubchist, "unbusy pg %#jx offset 0x%jx",
484 			    (uintptr_t)pg, pg->offset,0,0);
485 			if (pg->flags & PG_WANTED) {
486 				wakeup(pg);
487 			}
488 			if (pg->flags & PG_FAKE) {
489 				KASSERT(overwrite);
490 				uvm_pagezero(pg);
491 			}
492 			if (pg->flags & PG_RELEASED) {
493 				uvm_pagefree(pg);
494 				continue;
495 			}
496 			uvm_pageenqueue(pg);
497 			pg->flags &= ~(PG_WANTED|PG_BUSY|PG_FAKE);
498 			UVM_PAGE_OWN(pg, NULL);
499 		}
500 	}
501 	mutex_exit(&uvm_pageqlock);
502 	if (memwrite) {
503 		genfs_markdirty(vp);
504 	}
505 	mutex_exit(uobj->vmobjlock);
506 	if (ap->a_m != NULL) {
507 		memcpy(ap->a_m, &pgs[ridx],
508 		    orignmempages * sizeof(struct vm_page *));
509 	}
510 
511 out_err_free:
512 	if (pgs != NULL && pgs != pgs_onstack)
513 		kmem_free(pgs, pgs_size);
514 out_err:
515 	if (trans_mount != NULL) {
516 		if (holds_wapbl)
517 			WAPBL_END(trans_mount);
518 		fstrans_done(trans_mount);
519 	}
520 	return error;
521 }
522 
523 /*
524  * genfs_getpages_read: Read the pages in with VOP_BMAP/VOP_STRATEGY.
525  *
526  * "glocked" (which is currently not actually used) tells us not whether
527  * the genfs_node is locked on entry (it always is) but whether it was
528  * locked on entry to genfs_getpages.
529  */
530 static int
531 genfs_getpages_read(struct vnode *vp, struct vm_page **pgs, int npages,
532     off_t startoffset, off_t diskeof,
533     bool async, bool memwrite, bool blockalloc, bool glocked)
534 {
535 	struct uvm_object * const uobj = &vp->v_uobj;
536 	const int fs_bshift = (vp->v_type != VBLK) ?
537 	    vp->v_mount->mnt_fs_bshift : DEV_BSHIFT;
538 	const int dev_bshift = (vp->v_type != VBLK) ?
539 	    vp->v_mount->mnt_dev_bshift : DEV_BSHIFT;
540 	kauth_cred_t const cred = curlwp->l_cred;		/* XXXUBC curlwp */
541 	size_t bytes, iobytes, tailstart, tailbytes, totalbytes, skipbytes;
542 	vaddr_t kva;
543 	struct buf *bp, *mbp;
544 	bool sawhole = false;
545 	int i;
546 	int error = 0;
547 
548 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(ubchist);
549 
550 	/*
551 	 * read the desired page(s).
552 	 */
553 
554 	totalbytes = npages << PAGE_SHIFT;
555 	bytes = MIN(totalbytes, MAX(diskeof - startoffset, 0));
556 	tailbytes = totalbytes - bytes;
557 	skipbytes = 0;
558 
559 	kva = uvm_pagermapin(pgs, npages,
560 	    UVMPAGER_MAPIN_READ | (async ? 0 : UVMPAGER_MAPIN_WAITOK));
561 	if (kva == 0)
562 		return EBUSY;
563 
564 	mbp = getiobuf(vp, true);
565 	mbp->b_bufsize = totalbytes;
566 	mbp->b_data = (void *)kva;
567 	mbp->b_resid = mbp->b_bcount = bytes;
568 	mbp->b_cflags = BC_BUSY;
569 	if (async) {
570 		mbp->b_flags = B_READ | B_ASYNC;
571 		mbp->b_iodone = uvm_aio_biodone;
572 	} else {
573 		mbp->b_flags = B_READ;
574 		mbp->b_iodone = NULL;
575 	}
576 	if (async)
577 		BIO_SETPRIO(mbp, BPRIO_TIMELIMITED);
578 	else
579 		BIO_SETPRIO(mbp, BPRIO_TIMECRITICAL);
580 
581 	/*
582 	 * if EOF is in the middle of the range, zero the part past EOF.
583 	 * skip over pages which are not PG_FAKE since in that case they have
584 	 * valid data that we need to preserve.
585 	 */
586 
587 	tailstart = bytes;
588 	while (tailbytes > 0) {
589 		const int len = PAGE_SIZE - (tailstart & PAGE_MASK);
590 
591 		KASSERT(len <= tailbytes);
592 		if ((pgs[tailstart >> PAGE_SHIFT]->flags & PG_FAKE) != 0) {
593 			memset((void *)(kva + tailstart), 0, len);
594 			UVMHIST_LOG(ubchist, "tailbytes %#jx 0x%jx 0x%jx",
595 			    (uintptr_t)kva, tailstart, len, 0);
596 		}
597 		tailstart += len;
598 		tailbytes -= len;
599 	}
600 
601 	/*
602 	 * now loop over the pages, reading as needed.
603 	 */
604 
605 	bp = NULL;
606 	off_t offset;
607 	for (offset = startoffset;
608 	    bytes > 0;
609 	    offset += iobytes, bytes -= iobytes) {
610 		int run;
611 		daddr_t lbn, blkno;
612 		int pidx;
613 		struct vnode *devvp;
614 
615 		/*
616 		 * skip pages which don't need to be read.
617 		 */
618 
619 		pidx = (offset - startoffset) >> PAGE_SHIFT;
620 		while ((pgs[pidx]->flags & PG_FAKE) == 0) {
621 			size_t b;
622 
623 			KASSERT((offset & (PAGE_SIZE - 1)) == 0);
624 			if ((pgs[pidx]->flags & PG_RDONLY)) {
625 				sawhole = true;
626 			}
627 			b = MIN(PAGE_SIZE, bytes);
628 			offset += b;
629 			bytes -= b;
630 			skipbytes += b;
631 			pidx++;
632 			UVMHIST_LOG(ubchist, "skipping, new offset 0x%jx",
633 			    offset, 0,0,0);
634 			if (bytes == 0) {
635 				goto loopdone;
636 			}
637 		}
638 
639 		/*
640 		 * bmap the file to find out the blkno to read from and
641 		 * how much we can read in one i/o.  if bmap returns an error,
642 		 * skip the rest of the top-level i/o.
643 		 */
644 
645 		lbn = offset >> fs_bshift;
646 		error = VOP_BMAP(vp, lbn, &devvp, &blkno, &run);
647 		if (error) {
648 			UVMHIST_LOG(ubchist, "VOP_BMAP lbn 0x%jx -> %jd\n",
649 			    lbn,error,0,0);
650 			skipbytes += bytes;
651 			bytes = 0;
652 			goto loopdone;
653 		}
654 
655 		/*
656 		 * see how many pages can be read with this i/o.
657 		 * reduce the i/o size if necessary to avoid
658 		 * overwriting pages with valid data.
659 		 */
660 
661 		iobytes = MIN((((off_t)lbn + 1 + run) << fs_bshift) - offset,
662 		    bytes);
663 		if (offset + iobytes > round_page(offset)) {
664 			int pcount;
665 
666 			pcount = 1;
667 			while (pidx + pcount < npages &&
668 			    pgs[pidx + pcount]->flags & PG_FAKE) {
669 				pcount++;
670 			}
671 			iobytes = MIN(iobytes, (pcount << PAGE_SHIFT) -
672 			    (offset - trunc_page(offset)));
673 		}
674 
675 		/*
676 		 * if this block isn't allocated, zero it instead of
677 		 * reading it.  unless we are going to allocate blocks,
678 		 * mark the pages we zeroed PG_RDONLY.
679 		 */
680 
681 		if (blkno == (daddr_t)-1) {
682 			int holepages = (round_page(offset + iobytes) -
683 			    trunc_page(offset)) >> PAGE_SHIFT;
684 			UVMHIST_LOG(ubchist, "lbn 0x%jx -> HOLE", lbn,0,0,0);
685 
686 			sawhole = true;
687 			memset((char *)kva + (offset - startoffset), 0,
688 			    iobytes);
689 			skipbytes += iobytes;
690 
691 			mutex_enter(uobj->vmobjlock);
692 			for (i = 0; i < holepages; i++) {
693 				if (memwrite) {
694 					pgs[pidx + i]->flags &= ~PG_CLEAN;
695 				}
696 				if (!blockalloc) {
697 					pgs[pidx + i]->flags |= PG_RDONLY;
698 				}
699 			}
700 			mutex_exit(uobj->vmobjlock);
701 			continue;
702 		}
703 
704 		/*
705 		 * allocate a sub-buf for this piece of the i/o
706 		 * (or just use mbp if there's only 1 piece),
707 		 * and start it going.
708 		 */
709 
710 		if (offset == startoffset && iobytes == bytes) {
711 			bp = mbp;
712 		} else {
713 			UVMHIST_LOG(ubchist, "vp %#jx bp %#jx num now %jd",
714 			    (uintptr_t)vp, (uintptr_t)bp, vp->v_numoutput, 0);
715 			bp = getiobuf(vp, true);
716 			nestiobuf_setup(mbp, bp, offset - startoffset, iobytes);
717 		}
718 		bp->b_lblkno = 0;
719 
720 		/* adjust physical blkno for partial blocks */
721 		bp->b_blkno = blkno + ((offset - ((off_t)lbn << fs_bshift)) >>
722 		    dev_bshift);
723 
724 		UVMHIST_LOG(ubchist,
725 		    "bp %#jx offset 0x%x bcount 0x%x blkno 0x%x",
726 		    (uintptr_t)bp, offset, bp->b_bcount, bp->b_blkno);
727 
728 		VOP_STRATEGY(devvp, bp);
729 	}
730 
731 loopdone:
732 	nestiobuf_done(mbp, skipbytes, error);
733 	if (async) {
734 		UVMHIST_LOG(ubchist, "returning 0 (async)",0,0,0,0);
735 		return 0;
736 	}
737 	if (bp != NULL) {
738 		error = biowait(mbp);
739 	}
740 
741 	/* Remove the mapping (make KVA available as soon as possible) */
742 	uvm_pagermapout(kva, npages);
743 
744 	/*
745 	 * if this we encountered a hole then we have to do a little more work.
746 	 * for read faults, we marked the page PG_RDONLY so that future
747 	 * write accesses to the page will fault again.
748 	 * for write faults, we must make sure that the backing store for
749 	 * the page is completely allocated while the pages are locked.
750 	 */
751 
752 	if (!error && sawhole && blockalloc) {
753 		error = GOP_ALLOC(vp, startoffset,
754 		    npages << PAGE_SHIFT, 0, cred);
755 		UVMHIST_LOG(ubchist, "gop_alloc off 0x%jx/0x%jx -> %jd",
756 		    startoffset, npages << PAGE_SHIFT, error,0);
757 		if (!error) {
758 			mutex_enter(uobj->vmobjlock);
759 			for (i = 0; i < npages; i++) {
760 				struct vm_page *pg = pgs[i];
761 
762 				if (pg == NULL) {
763 					continue;
764 				}
765 				pg->flags &= ~(PG_CLEAN|PG_RDONLY);
766 				UVMHIST_LOG(ubchist, "mark dirty pg %#jx",
767 				    (uintptr_t)pg, 0, 0, 0);
768 			}
769 			mutex_exit(uobj->vmobjlock);
770 		}
771 	}
772 
773 	putiobuf(mbp);
774 	return error;
775 }
776 
777 /*
778  * generic VM putpages routine.
779  * Write the given range of pages to backing store.
780  *
781  * => "offhi == 0" means flush all pages at or after "offlo".
782  * => object should be locked by caller.  we return with the
783  *      object unlocked.
784  * => if PGO_CLEANIT or PGO_SYNCIO is set, we may block (due to I/O).
785  *	thus, a caller might want to unlock higher level resources
786  *	(e.g. vm_map) before calling flush.
787  * => if neither PGO_CLEANIT nor PGO_SYNCIO is set, we will not block
788  * => if PGO_ALLPAGES is set, then all pages in the object will be processed.
789  * => NOTE: we rely on the fact that the object's memq is a TAILQ and
790  *	that new pages are inserted on the tail end of the list.   thus,
791  *	we can make a complete pass through the object in one go by starting
792  *	at the head and working towards the tail (new pages are put in
793  *	front of us).
794  * => NOTE: we are allowed to lock the page queues, so the caller
795  *	must not be holding the page queue lock.
796  *
797  * note on "cleaning" object and PG_BUSY pages:
798  *	this routine is holding the lock on the object.   the only time
799  *	that it can run into a PG_BUSY page that it does not own is if
800  *	some other process has started I/O on the page (e.g. either
801  *	a pagein, or a pageout).    if the PG_BUSY page is being paged
802  *	in, then it can not be dirty (!PG_CLEAN) because no one has
803  *	had a chance to modify it yet.    if the PG_BUSY page is being
804  *	paged out then it means that someone else has already started
805  *	cleaning the page for us (how nice!).    in this case, if we
806  *	have syncio specified, then after we make our pass through the
807  *	object we need to wait for the other PG_BUSY pages to clear
808  *	off (i.e. we need to do an iosync).   also note that once a
809  *	page is PG_BUSY it must stay in its object until it is un-busyed.
810  *
811  * note on page traversal:
812  *	we can traverse the pages in an object either by going down the
813  *	linked list in "uobj->memq", or we can go over the address range
814  *	by page doing hash table lookups for each address.    depending
815  *	on how many pages are in the object it may be cheaper to do one
816  *	or the other.   we set "by_list" to true if we are using memq.
817  *	if the cost of a hash lookup was equal to the cost of the list
818  *	traversal we could compare the number of pages in the start->stop
819  *	range to the total number of pages in the object.   however, it
820  *	seems that a hash table lookup is more expensive than the linked
821  *	list traversal, so we multiply the number of pages in the
822  *	range by an estimate of the relatively higher cost of the hash lookup.
823  */
824 
825 int
826 genfs_putpages(void *v)
827 {
828 	struct vop_putpages_args /* {
829 		struct vnode *a_vp;
830 		voff_t a_offlo;
831 		voff_t a_offhi;
832 		int a_flags;
833 	} */ * const ap = v;
834 
835 	return genfs_do_putpages(ap->a_vp, ap->a_offlo, ap->a_offhi,
836 	    ap->a_flags, NULL);
837 }
838 
839 int
840 genfs_do_putpages(struct vnode *vp, off_t startoff, off_t endoff,
841     int origflags, struct vm_page **busypg)
842 {
843 	struct uvm_object * const uobj = &vp->v_uobj;
844 	kmutex_t * const slock = uobj->vmobjlock;
845 	off_t off;
846 	int i, error, npages, nback;
847 	int freeflag;
848 	/*
849 	 * This array is larger than it should so that it's size is constant.
850 	 * The right size is MAXPAGES.
851 	 */
852 	struct vm_page *pgs[MAXPHYS / MIN_PAGE_SIZE];
853 #define MAXPAGES (MAXPHYS / PAGE_SIZE)
854 	struct vm_page *pg, *nextpg, *tpg, curmp, endmp;
855 	bool wasclean, by_list, needs_clean, yld;
856 	bool async = (origflags & PGO_SYNCIO) == 0;
857 	bool pagedaemon = curlwp == uvm.pagedaemon_lwp;
858 	struct lwp * const l = curlwp ? curlwp : &lwp0;
859 	struct genfs_node * const gp = VTOG(vp);
860 	struct mount *trans_mp;
861 	int flags;
862 	int dirtygen;
863 	bool modified;
864 	bool holds_wapbl;
865 	bool cleanall;
866 	bool onworklst;
867 
868 	UVMHIST_FUNC("genfs_putpages"); UVMHIST_CALLED(ubchist);
869 
870 	KASSERT(origflags & (PGO_CLEANIT|PGO_FREE|PGO_DEACTIVATE));
871 	KASSERT((startoff & PAGE_MASK) == 0 && (endoff & PAGE_MASK) == 0);
872 	KASSERT(startoff < endoff || endoff == 0);
873 
874 	UVMHIST_LOG(ubchist, "vp %#jx pages %jd off 0x%jx len 0x%jx",
875 	    (uintptr_t)vp, uobj->uo_npages, startoff, endoff - startoff);
876 
877 #ifdef DIAGNOSTIC
878 	if ((origflags & PGO_JOURNALLOCKED) && vp->v_mount->mnt_wapbl)
879                 WAPBL_JLOCK_ASSERT(vp->v_mount);
880 #endif
881 
882 	trans_mp = NULL;
883 	holds_wapbl = false;
884 
885 retry:
886 	modified = false;
887 	flags = origflags;
888 	KASSERT((vp->v_iflag & VI_ONWORKLST) != 0 ||
889 	    (vp->v_iflag & VI_WRMAPDIRTY) == 0);
890 	if (uobj->uo_npages == 0) {
891 		if (vp->v_iflag & VI_ONWORKLST) {
892 			vp->v_iflag &= ~VI_WRMAPDIRTY;
893 			if (LIST_FIRST(&vp->v_dirtyblkhd) == NULL)
894 				vn_syncer_remove_from_worklist(vp);
895 		}
896 		if (trans_mp) {
897 			if (holds_wapbl)
898 				WAPBL_END(trans_mp);
899 			fstrans_done(trans_mp);
900 		}
901 		mutex_exit(slock);
902 		return (0);
903 	}
904 
905 	/*
906 	 * the vnode has pages, set up to process the request.
907 	 */
908 
909 	if (trans_mp == NULL && (flags & PGO_CLEANIT) != 0) {
910 		if (pagedaemon) {
911 			/* Pagedaemon must not sleep here. */
912 			trans_mp = vp->v_mount;
913 			error = fstrans_start_nowait(trans_mp);
914 			if (error) {
915 				mutex_exit(slock);
916 				return error;
917 			}
918 		} else {
919 			/*
920 			 * Cannot use vdeadcheck() here as this operation
921 			 * usually gets used from VOP_RECLAIM().  Test for
922 			 * change of v_mount instead and retry on change.
923 			 */
924 			mutex_exit(slock);
925 			trans_mp = vp->v_mount;
926 			fstrans_start(trans_mp);
927 			if (vp->v_mount != trans_mp) {
928 				fstrans_done(trans_mp);
929 				trans_mp = NULL;
930 			} else {
931 				holds_wapbl = (trans_mp->mnt_wapbl &&
932 				    (origflags & PGO_JOURNALLOCKED) == 0);
933 				if (holds_wapbl) {
934 					error = WAPBL_BEGIN(trans_mp);
935 					if (error) {
936 						fstrans_done(trans_mp);
937 						return error;
938 					}
939 				}
940 			}
941 			mutex_enter(slock);
942 			goto retry;
943 		}
944 	}
945 
946 	error = 0;
947 	wasclean = (vp->v_numoutput == 0);
948 	off = startoff;
949 	if (endoff == 0 || flags & PGO_ALLPAGES) {
950 		endoff = trunc_page(LLONG_MAX);
951 	}
952 	by_list = (uobj->uo_npages <=
953 	    ((endoff - startoff) >> PAGE_SHIFT) * UVM_PAGE_TREE_PENALTY);
954 
955 	/*
956 	 * if this vnode is known not to have dirty pages,
957 	 * don't bother to clean it out.
958 	 */
959 
960 	if ((vp->v_iflag & VI_ONWORKLST) == 0) {
961 #if !defined(DEBUG)
962 		if ((flags & (PGO_FREE|PGO_DEACTIVATE)) == 0) {
963 			goto skip_scan;
964 		}
965 #endif /* !defined(DEBUG) */
966 		flags &= ~PGO_CLEANIT;
967 	}
968 
969 	/*
970 	 * start the loop.  when scanning by list, hold the last page
971 	 * in the list before we start.  pages allocated after we start
972 	 * will be added to the end of the list, so we can stop at the
973 	 * current last page.
974 	 */
975 
976 	cleanall = (flags & PGO_CLEANIT) != 0 && wasclean &&
977 	    startoff == 0 && endoff == trunc_page(LLONG_MAX) &&
978 	    (vp->v_iflag & VI_ONWORKLST) != 0;
979 	dirtygen = gp->g_dirtygen;
980 	freeflag = pagedaemon ? PG_PAGEOUT : PG_RELEASED;
981 	if (by_list) {
982 		curmp.flags = PG_MARKER;
983 		endmp.flags = PG_MARKER;
984 		pg = TAILQ_FIRST(&uobj->memq);
985 		TAILQ_INSERT_TAIL(&uobj->memq, &endmp, listq.queue);
986 	} else {
987 		pg = uvm_pagelookup(uobj, off);
988 	}
989 	nextpg = NULL;
990 	while (by_list || off < endoff) {
991 
992 		/*
993 		 * if the current page is not interesting, move on to the next.
994 		 */
995 
996 		KASSERT(pg == NULL || pg->uobject == uobj ||
997 		    (pg->flags & PG_MARKER) != 0);
998 		KASSERT(pg == NULL ||
999 		    (pg->flags & (PG_RELEASED|PG_PAGEOUT)) == 0 ||
1000 		    (pg->flags & (PG_BUSY|PG_MARKER)) != 0);
1001 		if (by_list) {
1002 			if (pg == &endmp) {
1003 				break;
1004 			}
1005 			if (pg->flags & PG_MARKER) {
1006 				pg = TAILQ_NEXT(pg, listq.queue);
1007 				continue;
1008 			}
1009 			if (pg->offset < startoff || pg->offset >= endoff ||
1010 			    pg->flags & (PG_RELEASED|PG_PAGEOUT)) {
1011 				if (pg->flags & (PG_RELEASED|PG_PAGEOUT)) {
1012 					wasclean = false;
1013 				}
1014 				pg = TAILQ_NEXT(pg, listq.queue);
1015 				continue;
1016 			}
1017 			off = pg->offset;
1018 		} else if (pg == NULL || pg->flags & (PG_RELEASED|PG_PAGEOUT)) {
1019 			if (pg != NULL) {
1020 				wasclean = false;
1021 			}
1022 			off += PAGE_SIZE;
1023 			if (off < endoff) {
1024 				pg = uvm_pagelookup(uobj, off);
1025 			}
1026 			continue;
1027 		}
1028 
1029 		/*
1030 		 * if the current page needs to be cleaned and it's busy,
1031 		 * wait for it to become unbusy.
1032 		 */
1033 
1034 		yld = (l->l_cpu->ci_schedstate.spc_flags &
1035 		    SPCF_SHOULDYIELD) && !pagedaemon;
1036 		if (pg->flags & PG_BUSY || yld) {
1037 			UVMHIST_LOG(ubchist, "busy %#jx", (uintptr_t)pg,
1038 			   0, 0, 0);
1039 			if (flags & PGO_BUSYFAIL && pg->flags & PG_BUSY) {
1040 				UVMHIST_LOG(ubchist, "busyfail %#jx",
1041 				    (uintptr_t)pg, 0, 0, 0);
1042 				error = EDEADLK;
1043 				if (busypg != NULL)
1044 					*busypg = pg;
1045 				break;
1046 			}
1047 			if (pagedaemon) {
1048 				/*
1049 				 * someone has taken the page while we
1050 				 * dropped the lock for fstrans_start.
1051 				 */
1052 				break;
1053 			}
1054 			if (by_list) {
1055 				TAILQ_INSERT_BEFORE(pg, &curmp, listq.queue);
1056 				UVMHIST_LOG(ubchist, "curmp next %#jx",
1057 				    (uintptr_t)TAILQ_NEXT(&curmp, listq.queue),
1058 				    0, 0, 0);
1059 			}
1060 			if (yld) {
1061 				mutex_exit(slock);
1062 				preempt();
1063 				mutex_enter(slock);
1064 			} else {
1065 				pg->flags |= PG_WANTED;
1066 				UVM_UNLOCK_AND_WAIT(pg, slock, 0, "genput", 0);
1067 				mutex_enter(slock);
1068 			}
1069 			if (by_list) {
1070 				UVMHIST_LOG(ubchist, "after next %#jx",
1071 				    (uintptr_t)TAILQ_NEXT(&curmp, listq.queue),
1072 				    0, 0, 0);
1073 				pg = TAILQ_NEXT(&curmp, listq.queue);
1074 				TAILQ_REMOVE(&uobj->memq, &curmp, listq.queue);
1075 			} else {
1076 				pg = uvm_pagelookup(uobj, off);
1077 			}
1078 			continue;
1079 		}
1080 
1081 		/*
1082 		 * if we're freeing, remove all mappings of the page now.
1083 		 * if we're cleaning, check if the page is needs to be cleaned.
1084 		 */
1085 
1086 		if (flags & PGO_FREE) {
1087 			pmap_page_protect(pg, VM_PROT_NONE);
1088 		} else if (flags & PGO_CLEANIT) {
1089 
1090 			/*
1091 			 * if we still have some hope to pull this vnode off
1092 			 * from the syncer queue, write-protect the page.
1093 			 */
1094 
1095 			if (cleanall && wasclean &&
1096 			    gp->g_dirtygen == dirtygen) {
1097 
1098 				/*
1099 				 * uobj pages get wired only by uvm_fault
1100 				 * where uobj is locked.
1101 				 */
1102 
1103 				if (pg->wire_count == 0) {
1104 					pmap_page_protect(pg,
1105 					    VM_PROT_READ|VM_PROT_EXECUTE);
1106 				} else {
1107 					cleanall = false;
1108 				}
1109 			}
1110 		}
1111 
1112 		if (flags & PGO_CLEANIT) {
1113 			needs_clean = pmap_clear_modify(pg) ||
1114 			    (pg->flags & PG_CLEAN) == 0;
1115 			pg->flags |= PG_CLEAN;
1116 		} else {
1117 			needs_clean = false;
1118 		}
1119 
1120 		/*
1121 		 * if we're cleaning, build a cluster.
1122 		 * the cluster will consist of pages which are currently dirty,
1123 		 * but they will be returned to us marked clean.
1124 		 * if not cleaning, just operate on the one page.
1125 		 */
1126 
1127 		if (needs_clean) {
1128 			KDASSERT((vp->v_iflag & VI_ONWORKLST));
1129 			wasclean = false;
1130 			memset(pgs, 0, sizeof(pgs));
1131 			pg->flags |= PG_BUSY;
1132 			UVM_PAGE_OWN(pg, "genfs_putpages");
1133 
1134 			/*
1135 			 * let the fs constrain the offset range of the cluster.
1136 			 * we additionally constrain the range here such that
1137 			 * it fits in the "pgs" pages array.
1138 			 */
1139 
1140 			off_t fslo, fshi, genlo, lo;
1141 			GOP_PUTRANGE(vp, off, &fslo, &fshi);
1142 			KASSERT(fslo == trunc_page(fslo));
1143 			KASSERT(fslo <= off);
1144 			KASSERT(fshi == trunc_page(fshi));
1145 			KASSERT(fshi == 0 || off < fshi);
1146 
1147 			if (off > MAXPHYS / 2)
1148 				genlo = trunc_page(off - (MAXPHYS / 2));
1149 			else
1150 				genlo = 0;
1151 			lo = MAX(fslo, genlo);
1152 
1153 			/*
1154 			 * first look backward.
1155 			 */
1156 
1157 			npages = (off - lo) >> PAGE_SHIFT;
1158 			nback = npages;
1159 			uvn_findpages(uobj, off - PAGE_SIZE, &nback, &pgs[0],
1160 			    UFP_NOWAIT|UFP_NOALLOC|UFP_DIRTYONLY|UFP_BACKWARD);
1161 			if (nback) {
1162 				memmove(&pgs[0], &pgs[npages - nback],
1163 				    nback * sizeof(pgs[0]));
1164 				if (npages - nback < nback)
1165 					memset(&pgs[nback], 0,
1166 					    (npages - nback) * sizeof(pgs[0]));
1167 				else
1168 					memset(&pgs[npages - nback], 0,
1169 					    nback * sizeof(pgs[0]));
1170 			}
1171 
1172 			/*
1173 			 * then plug in our page of interest.
1174 			 */
1175 
1176 			pgs[nback] = pg;
1177 
1178 			/*
1179 			 * then look forward to fill in the remaining space in
1180 			 * the array of pages.
1181 			 */
1182 
1183 			npages = MAXPAGES - nback - 1;
1184 			if (fshi)
1185 				npages = MIN(npages,
1186 					     (fshi - off - 1) >> PAGE_SHIFT);
1187 			uvn_findpages(uobj, off + PAGE_SIZE, &npages,
1188 			    &pgs[nback + 1],
1189 			    UFP_NOWAIT|UFP_NOALLOC|UFP_DIRTYONLY);
1190 			npages += nback + 1;
1191 		} else {
1192 			pgs[0] = pg;
1193 			npages = 1;
1194 			nback = 0;
1195 		}
1196 
1197 		/*
1198 		 * apply FREE or DEACTIVATE options if requested.
1199 		 */
1200 
1201 		if (flags & (PGO_DEACTIVATE|PGO_FREE)) {
1202 			mutex_enter(&uvm_pageqlock);
1203 		}
1204 		for (i = 0; i < npages; i++) {
1205 			tpg = pgs[i];
1206 			KASSERT(tpg->uobject == uobj);
1207 			if (by_list && tpg == TAILQ_NEXT(pg, listq.queue))
1208 				pg = tpg;
1209 			if (tpg->offset < startoff || tpg->offset >= endoff)
1210 				continue;
1211 			if (flags & PGO_DEACTIVATE && tpg->wire_count == 0) {
1212 				uvm_pagedeactivate(tpg);
1213 			} else if (flags & PGO_FREE) {
1214 				pmap_page_protect(tpg, VM_PROT_NONE);
1215 				if (tpg->flags & PG_BUSY) {
1216 					tpg->flags |= freeflag;
1217 					if (pagedaemon) {
1218 						uvm_pageout_start(1);
1219 						uvm_pagedequeue(tpg);
1220 					}
1221 				} else {
1222 
1223 					/*
1224 					 * ``page is not busy''
1225 					 * implies that npages is 1
1226 					 * and needs_clean is false.
1227 					 */
1228 
1229 					nextpg = TAILQ_NEXT(tpg, listq.queue);
1230 					uvm_pagefree(tpg);
1231 					if (pagedaemon)
1232 						uvmexp.pdfreed++;
1233 				}
1234 			}
1235 		}
1236 		if (flags & (PGO_DEACTIVATE|PGO_FREE)) {
1237 			mutex_exit(&uvm_pageqlock);
1238 		}
1239 		if (needs_clean) {
1240 			modified = true;
1241 
1242 			/*
1243 			 * start the i/o.  if we're traversing by list,
1244 			 * keep our place in the list with a marker page.
1245 			 */
1246 
1247 			if (by_list) {
1248 				TAILQ_INSERT_AFTER(&uobj->memq, pg, &curmp,
1249 				    listq.queue);
1250 			}
1251 			mutex_exit(slock);
1252 			error = GOP_WRITE(vp, pgs, npages, flags);
1253 			mutex_enter(slock);
1254 			if (by_list) {
1255 				pg = TAILQ_NEXT(&curmp, listq.queue);
1256 				TAILQ_REMOVE(&uobj->memq, &curmp, listq.queue);
1257 			}
1258 			if (error) {
1259 				break;
1260 			}
1261 			if (by_list) {
1262 				continue;
1263 			}
1264 		}
1265 
1266 		/*
1267 		 * find the next page and continue if there was no error.
1268 		 */
1269 
1270 		if (by_list) {
1271 			if (nextpg) {
1272 				pg = nextpg;
1273 				nextpg = NULL;
1274 			} else {
1275 				pg = TAILQ_NEXT(pg, listq.queue);
1276 			}
1277 		} else {
1278 			off += (npages - nback) << PAGE_SHIFT;
1279 			if (off < endoff) {
1280 				pg = uvm_pagelookup(uobj, off);
1281 			}
1282 		}
1283 	}
1284 	if (by_list) {
1285 		TAILQ_REMOVE(&uobj->memq, &endmp, listq.queue);
1286 	}
1287 
1288 	if (modified && (vp->v_iflag & VI_WRMAPDIRTY) != 0 &&
1289 	    (vp->v_type != VBLK ||
1290 	    (vp->v_mount->mnt_flag & MNT_NODEVMTIME) == 0)) {
1291 		GOP_MARKUPDATE(vp, GOP_UPDATE_MODIFIED);
1292 	}
1293 
1294 	/*
1295 	 * if we're cleaning and there was nothing to clean,
1296 	 * take us off the syncer list.  if we started any i/o
1297 	 * and we're doing sync i/o, wait for all writes to finish.
1298 	 */
1299 
1300 	if (cleanall && wasclean && gp->g_dirtygen == dirtygen &&
1301 	    (vp->v_iflag & VI_ONWORKLST) != 0) {
1302 #if defined(DEBUG)
1303 		TAILQ_FOREACH(pg, &uobj->memq, listq.queue) {
1304 			if ((pg->flags & (PG_FAKE | PG_MARKER)) != 0) {
1305 				continue;
1306 			}
1307 			if ((pg->flags & PG_CLEAN) == 0) {
1308 				printf("%s: %p: !CLEAN\n", __func__, pg);
1309 			}
1310 			if (pmap_is_modified(pg)) {
1311 				printf("%s: %p: modified\n", __func__, pg);
1312 			}
1313 		}
1314 #endif /* defined(DEBUG) */
1315 		vp->v_iflag &= ~VI_WRMAPDIRTY;
1316 		if (LIST_FIRST(&vp->v_dirtyblkhd) == NULL)
1317 			vn_syncer_remove_from_worklist(vp);
1318 	}
1319 
1320 #if !defined(DEBUG)
1321 skip_scan:
1322 #endif /* !defined(DEBUG) */
1323 
1324 	/* Wait for output to complete. */
1325 	if (!wasclean && !async && vp->v_numoutput != 0) {
1326 		while (vp->v_numoutput != 0)
1327 			cv_wait(&vp->v_cv, slock);
1328 	}
1329 	onworklst = (vp->v_iflag & VI_ONWORKLST) != 0;
1330 	mutex_exit(slock);
1331 
1332 	if ((flags & PGO_RECLAIM) != 0 && onworklst) {
1333 		/*
1334 		 * in the case of PGO_RECLAIM, ensure to make the vnode clean.
1335 		 * retrying is not a big deal because, in many cases,
1336 		 * uobj->uo_npages is already 0 here.
1337 		 */
1338 		mutex_enter(slock);
1339 		goto retry;
1340 	}
1341 
1342 	if (trans_mp) {
1343 		if (holds_wapbl)
1344 			WAPBL_END(trans_mp);
1345 		fstrans_done(trans_mp);
1346 	}
1347 
1348 	return (error);
1349 }
1350 
1351 /*
1352  * Default putrange method for file systems that do not care
1353  * how many pages are given to one GOP_WRITE() call.
1354  */
1355 void
1356 genfs_gop_putrange(struct vnode *vp, off_t off, off_t *lop, off_t *hip)
1357 {
1358 
1359 	*lop = 0;
1360 	*hip = 0;
1361 }
1362 
1363 int
1364 genfs_gop_write(struct vnode *vp, struct vm_page **pgs, int npages, int flags)
1365 {
1366 	off_t off;
1367 	vaddr_t kva;
1368 	size_t len;
1369 	int error;
1370 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(ubchist);
1371 
1372 	UVMHIST_LOG(ubchist, "vp %#jx pgs %#jx npages %jd flags 0x%jx",
1373 	    (uintptr_t)vp, (uintptr_t)pgs, npages, flags);
1374 
1375 	off = pgs[0]->offset;
1376 	kva = uvm_pagermapin(pgs, npages,
1377 	    UVMPAGER_MAPIN_WRITE | UVMPAGER_MAPIN_WAITOK);
1378 	len = npages << PAGE_SHIFT;
1379 
1380 	error = genfs_do_io(vp, off, kva, len, flags, UIO_WRITE,
1381 			    uvm_aio_biodone);
1382 
1383 	return error;
1384 }
1385 
1386 int
1387 genfs_gop_write_rwmap(struct vnode *vp, struct vm_page **pgs, int npages, int flags)
1388 {
1389 	off_t off;
1390 	vaddr_t kva;
1391 	size_t len;
1392 	int error;
1393 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(ubchist);
1394 
1395 	UVMHIST_LOG(ubchist, "vp %#jx pgs %#jx npages %jd flags 0x%jx",
1396 	    (uintptr_t)vp, (uintptr_t)pgs, npages, flags);
1397 
1398 	off = pgs[0]->offset;
1399 	kva = uvm_pagermapin(pgs, npages,
1400 	    UVMPAGER_MAPIN_READ | UVMPAGER_MAPIN_WAITOK);
1401 	len = npages << PAGE_SHIFT;
1402 
1403 	error = genfs_do_io(vp, off, kva, len, flags, UIO_WRITE,
1404 			    uvm_aio_biodone);
1405 
1406 	return error;
1407 }
1408 
1409 /*
1410  * Backend routine for doing I/O to vnode pages.  Pages are already locked
1411  * and mapped into kernel memory.  Here we just look up the underlying
1412  * device block addresses and call the strategy routine.
1413  */
1414 
1415 static int
1416 genfs_do_io(struct vnode *vp, off_t off, vaddr_t kva, size_t len, int flags,
1417     enum uio_rw rw, void (*iodone)(struct buf *))
1418 {
1419 	int s, error;
1420 	int fs_bshift, dev_bshift;
1421 	off_t eof, offset, startoffset;
1422 	size_t bytes, iobytes, skipbytes;
1423 	struct buf *mbp, *bp;
1424 	const bool async = (flags & PGO_SYNCIO) == 0;
1425 	const bool lazy = (flags & PGO_LAZY) == 0;
1426 	const bool iowrite = rw == UIO_WRITE;
1427 	const int brw = iowrite ? B_WRITE : B_READ;
1428 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(ubchist);
1429 
1430 	UVMHIST_LOG(ubchist, "vp %#jx kva %#jx len 0x%jx flags 0x%jx",
1431 	    (uintptr_t)vp, (uintptr_t)kva, len, flags);
1432 
1433 	KASSERT(vp->v_size <= vp->v_writesize);
1434 	GOP_SIZE(vp, vp->v_writesize, &eof, 0);
1435 	if (vp->v_type != VBLK) {
1436 		fs_bshift = vp->v_mount->mnt_fs_bshift;
1437 		dev_bshift = vp->v_mount->mnt_dev_bshift;
1438 	} else {
1439 		fs_bshift = DEV_BSHIFT;
1440 		dev_bshift = DEV_BSHIFT;
1441 	}
1442 	error = 0;
1443 	startoffset = off;
1444 	bytes = MIN(len, eof - startoffset);
1445 	skipbytes = 0;
1446 	KASSERT(bytes != 0);
1447 
1448 	if (iowrite) {
1449 		mutex_enter(vp->v_interlock);
1450 		vp->v_numoutput += 2;
1451 		mutex_exit(vp->v_interlock);
1452 	}
1453 	mbp = getiobuf(vp, true);
1454 	UVMHIST_LOG(ubchist, "vp %#jx mbp %#jx num now %jd bytes 0x%jx",
1455 	    (uintptr_t)vp, (uintptr_t)mbp, vp->v_numoutput, bytes);
1456 	mbp->b_bufsize = len;
1457 	mbp->b_data = (void *)kva;
1458 	mbp->b_resid = mbp->b_bcount = bytes;
1459 	mbp->b_cflags = BC_BUSY | BC_AGE;
1460 	if (async) {
1461 		mbp->b_flags = brw | B_ASYNC;
1462 		mbp->b_iodone = iodone;
1463 	} else {
1464 		mbp->b_flags = brw;
1465 		mbp->b_iodone = NULL;
1466 	}
1467 	if (curlwp == uvm.pagedaemon_lwp)
1468 		BIO_SETPRIO(mbp, BPRIO_TIMELIMITED);
1469 	else if (async || lazy)
1470 		BIO_SETPRIO(mbp, BPRIO_TIMENONCRITICAL);
1471 	else
1472 		BIO_SETPRIO(mbp, BPRIO_TIMECRITICAL);
1473 
1474 	bp = NULL;
1475 	for (offset = startoffset;
1476 	    bytes > 0;
1477 	    offset += iobytes, bytes -= iobytes) {
1478 		int run;
1479 		daddr_t lbn, blkno;
1480 		struct vnode *devvp;
1481 
1482 		/*
1483 		 * bmap the file to find out the blkno to read from and
1484 		 * how much we can read in one i/o.  if bmap returns an error,
1485 		 * skip the rest of the top-level i/o.
1486 		 */
1487 
1488 		lbn = offset >> fs_bshift;
1489 		error = VOP_BMAP(vp, lbn, &devvp, &blkno, &run);
1490 		if (error) {
1491 			UVMHIST_LOG(ubchist, "VOP_BMAP lbn 0x%jx -> %jd\n",
1492 			    lbn, error, 0, 0);
1493 			skipbytes += bytes;
1494 			bytes = 0;
1495 			goto loopdone;
1496 		}
1497 
1498 		/*
1499 		 * see how many pages can be read with this i/o.
1500 		 * reduce the i/o size if necessary to avoid
1501 		 * overwriting pages with valid data.
1502 		 */
1503 
1504 		iobytes = MIN((((off_t)lbn + 1 + run) << fs_bshift) - offset,
1505 		    bytes);
1506 
1507 		/*
1508 		 * if this block isn't allocated, zero it instead of
1509 		 * reading it.  unless we are going to allocate blocks,
1510 		 * mark the pages we zeroed PG_RDONLY.
1511 		 */
1512 
1513 		if (blkno == (daddr_t)-1) {
1514 			if (!iowrite) {
1515 				memset((char *)kva + (offset - startoffset), 0,
1516 				    iobytes);
1517 			}
1518 			skipbytes += iobytes;
1519 			continue;
1520 		}
1521 
1522 		/*
1523 		 * allocate a sub-buf for this piece of the i/o
1524 		 * (or just use mbp if there's only 1 piece),
1525 		 * and start it going.
1526 		 */
1527 
1528 		if (offset == startoffset && iobytes == bytes) {
1529 			bp = mbp;
1530 		} else {
1531 			UVMHIST_LOG(ubchist, "vp %#jx bp %#jx num now %jd",
1532 			    (uintptr_t)vp, (uintptr_t)bp, vp->v_numoutput, 0);
1533 			bp = getiobuf(vp, true);
1534 			nestiobuf_setup(mbp, bp, offset - startoffset, iobytes);
1535 		}
1536 		bp->b_lblkno = 0;
1537 
1538 		/* adjust physical blkno for partial blocks */
1539 		bp->b_blkno = blkno + ((offset - ((off_t)lbn << fs_bshift)) >>
1540 		    dev_bshift);
1541 
1542 		UVMHIST_LOG(ubchist,
1543 		    "bp %#jx offset 0x%jx bcount 0x%jx blkno 0x%jx",
1544 		    (uintptr_t)bp, offset, bp->b_bcount, bp->b_blkno);
1545 
1546 		VOP_STRATEGY(devvp, bp);
1547 	}
1548 
1549 loopdone:
1550 	if (skipbytes) {
1551 		UVMHIST_LOG(ubchist, "skipbytes %jd", skipbytes, 0,0,0);
1552 	}
1553 	nestiobuf_done(mbp, skipbytes, error);
1554 	if (async) {
1555 		UVMHIST_LOG(ubchist, "returning 0 (async)", 0,0,0,0);
1556 		return (0);
1557 	}
1558 	UVMHIST_LOG(ubchist, "waiting for mbp %#jx", (uintptr_t)mbp, 0, 0, 0);
1559 	error = biowait(mbp);
1560 	s = splbio();
1561 	(*iodone)(mbp);
1562 	splx(s);
1563 	UVMHIST_LOG(ubchist, "returning, error %jd", error, 0, 0, 0);
1564 	return (error);
1565 }
1566 
1567 int
1568 genfs_compat_getpages(void *v)
1569 {
1570 	struct vop_getpages_args /* {
1571 		struct vnode *a_vp;
1572 		voff_t a_offset;
1573 		struct vm_page **a_m;
1574 		int *a_count;
1575 		int a_centeridx;
1576 		vm_prot_t a_access_type;
1577 		int a_advice;
1578 		int a_flags;
1579 	} */ *ap = v;
1580 
1581 	off_t origoffset;
1582 	struct vnode *vp = ap->a_vp;
1583 	struct uvm_object *uobj = &vp->v_uobj;
1584 	struct vm_page *pg, **pgs;
1585 	vaddr_t kva;
1586 	int i, error, orignpages, npages;
1587 	struct iovec iov;
1588 	struct uio uio;
1589 	kauth_cred_t cred = curlwp->l_cred;
1590 	const bool memwrite = (ap->a_access_type & VM_PROT_WRITE) != 0;
1591 
1592 	error = 0;
1593 	origoffset = ap->a_offset;
1594 	orignpages = *ap->a_count;
1595 	pgs = ap->a_m;
1596 
1597 	if (ap->a_flags & PGO_LOCKED) {
1598 		uvn_findpages(uobj, origoffset, ap->a_count, ap->a_m,
1599 		    UFP_NOWAIT|UFP_NOALLOC| (memwrite ? UFP_NORDONLY : 0));
1600 
1601 		error = ap->a_m[ap->a_centeridx] == NULL ? EBUSY : 0;
1602 		if (error == 0 && memwrite) {
1603 			genfs_markdirty(vp);
1604 		}
1605 		return error;
1606 	}
1607 	if (origoffset + (ap->a_centeridx << PAGE_SHIFT) >= vp->v_size) {
1608 		mutex_exit(uobj->vmobjlock);
1609 		return EINVAL;
1610 	}
1611 	if ((ap->a_flags & PGO_SYNCIO) == 0) {
1612 		mutex_exit(uobj->vmobjlock);
1613 		return 0;
1614 	}
1615 	npages = orignpages;
1616 	uvn_findpages(uobj, origoffset, &npages, pgs, UFP_ALL);
1617 	mutex_exit(uobj->vmobjlock);
1618 	kva = uvm_pagermapin(pgs, npages,
1619 	    UVMPAGER_MAPIN_READ | UVMPAGER_MAPIN_WAITOK);
1620 	for (i = 0; i < npages; i++) {
1621 		pg = pgs[i];
1622 		if ((pg->flags & PG_FAKE) == 0) {
1623 			continue;
1624 		}
1625 		iov.iov_base = (char *)kva + (i << PAGE_SHIFT);
1626 		iov.iov_len = PAGE_SIZE;
1627 		uio.uio_iov = &iov;
1628 		uio.uio_iovcnt = 1;
1629 		uio.uio_offset = origoffset + (i << PAGE_SHIFT);
1630 		uio.uio_rw = UIO_READ;
1631 		uio.uio_resid = PAGE_SIZE;
1632 		UIO_SETUP_SYSSPACE(&uio);
1633 		/* XXX vn_lock */
1634 		error = VOP_READ(vp, &uio, 0, cred);
1635 		if (error) {
1636 			break;
1637 		}
1638 		if (uio.uio_resid) {
1639 			memset(iov.iov_base, 0, uio.uio_resid);
1640 		}
1641 	}
1642 	uvm_pagermapout(kva, npages);
1643 	mutex_enter(uobj->vmobjlock);
1644 	mutex_enter(&uvm_pageqlock);
1645 	for (i = 0; i < npages; i++) {
1646 		pg = pgs[i];
1647 		if (error && (pg->flags & PG_FAKE) != 0) {
1648 			pg->flags |= PG_RELEASED;
1649 		} else {
1650 			pmap_clear_modify(pg);
1651 			uvm_pageactivate(pg);
1652 		}
1653 	}
1654 	if (error) {
1655 		uvm_page_unbusy(pgs, npages);
1656 	}
1657 	mutex_exit(&uvm_pageqlock);
1658 	if (error == 0 && memwrite) {
1659 		genfs_markdirty(vp);
1660 	}
1661 	mutex_exit(uobj->vmobjlock);
1662 	return error;
1663 }
1664 
1665 int
1666 genfs_compat_gop_write(struct vnode *vp, struct vm_page **pgs, int npages,
1667     int flags)
1668 {
1669 	off_t offset;
1670 	struct iovec iov;
1671 	struct uio uio;
1672 	kauth_cred_t cred = curlwp->l_cred;
1673 	struct buf *bp;
1674 	vaddr_t kva;
1675 	int error;
1676 
1677 	offset = pgs[0]->offset;
1678 	kva = uvm_pagermapin(pgs, npages,
1679 	    UVMPAGER_MAPIN_WRITE | UVMPAGER_MAPIN_WAITOK);
1680 
1681 	iov.iov_base = (void *)kva;
1682 	iov.iov_len = npages << PAGE_SHIFT;
1683 	uio.uio_iov = &iov;
1684 	uio.uio_iovcnt = 1;
1685 	uio.uio_offset = offset;
1686 	uio.uio_rw = UIO_WRITE;
1687 	uio.uio_resid = npages << PAGE_SHIFT;
1688 	UIO_SETUP_SYSSPACE(&uio);
1689 	/* XXX vn_lock */
1690 	error = VOP_WRITE(vp, &uio, 0, cred);
1691 
1692 	mutex_enter(vp->v_interlock);
1693 	vp->v_numoutput++;
1694 	mutex_exit(vp->v_interlock);
1695 
1696 	bp = getiobuf(vp, true);
1697 	bp->b_cflags = BC_BUSY | BC_AGE;
1698 	bp->b_lblkno = offset >> vp->v_mount->mnt_fs_bshift;
1699 	bp->b_data = (char *)kva;
1700 	bp->b_bcount = npages << PAGE_SHIFT;
1701 	bp->b_bufsize = npages << PAGE_SHIFT;
1702 	bp->b_resid = 0;
1703 	bp->b_error = error;
1704 	uvm_aio_aiodone(bp);
1705 	return (error);
1706 }
1707 
1708 /*
1709  * Process a uio using direct I/O.  If we reach a part of the request
1710  * which cannot be processed in this fashion for some reason, just return.
1711  * The caller must handle some additional part of the request using
1712  * buffered I/O before trying direct I/O again.
1713  */
1714 
1715 void
1716 genfs_directio(struct vnode *vp, struct uio *uio, int ioflag)
1717 {
1718 	struct vmspace *vs;
1719 	struct iovec *iov;
1720 	vaddr_t va;
1721 	size_t len;
1722 	const int mask = DEV_BSIZE - 1;
1723 	int error;
1724 	bool need_wapbl = (vp->v_mount && vp->v_mount->mnt_wapbl &&
1725 	    (ioflag & IO_JOURNALLOCKED) == 0);
1726 
1727 #ifdef DIAGNOSTIC
1728 	if ((ioflag & IO_JOURNALLOCKED) && vp->v_mount->mnt_wapbl)
1729                 WAPBL_JLOCK_ASSERT(vp->v_mount);
1730 #endif
1731 
1732 	/*
1733 	 * We only support direct I/O to user space for now.
1734 	 */
1735 
1736 	if (VMSPACE_IS_KERNEL_P(uio->uio_vmspace)) {
1737 		return;
1738 	}
1739 
1740 	/*
1741 	 * If the vnode is mapped, we would need to get the getpages lock
1742 	 * to stabilize the bmap, but then we would get into trouble while
1743 	 * locking the pages if the pages belong to this same vnode (or a
1744 	 * multi-vnode cascade to the same effect).  Just fall back to
1745 	 * buffered I/O if the vnode is mapped to avoid this mess.
1746 	 */
1747 
1748 	if (vp->v_vflag & VV_MAPPED) {
1749 		return;
1750 	}
1751 
1752 	if (need_wapbl) {
1753 		error = WAPBL_BEGIN(vp->v_mount);
1754 		if (error)
1755 			return;
1756 	}
1757 
1758 	/*
1759 	 * Do as much of the uio as possible with direct I/O.
1760 	 */
1761 
1762 	vs = uio->uio_vmspace;
1763 	while (uio->uio_resid) {
1764 		iov = uio->uio_iov;
1765 		if (iov->iov_len == 0) {
1766 			uio->uio_iov++;
1767 			uio->uio_iovcnt--;
1768 			continue;
1769 		}
1770 		va = (vaddr_t)iov->iov_base;
1771 		len = MIN(iov->iov_len, genfs_maxdio);
1772 		len &= ~mask;
1773 
1774 		/*
1775 		 * If the next chunk is smaller than DEV_BSIZE or extends past
1776 		 * the current EOF, then fall back to buffered I/O.
1777 		 */
1778 
1779 		if (len == 0 || uio->uio_offset + len > vp->v_size) {
1780 			break;
1781 		}
1782 
1783 		/*
1784 		 * Check alignment.  The file offset must be at least
1785 		 * sector-aligned.  The exact constraint on memory alignment
1786 		 * is very hardware-dependent, but requiring sector-aligned
1787 		 * addresses there too is safe.
1788 		 */
1789 
1790 		if (uio->uio_offset & mask || va & mask) {
1791 			break;
1792 		}
1793 		error = genfs_do_directio(vs, va, len, vp, uio->uio_offset,
1794 					  uio->uio_rw);
1795 		if (error) {
1796 			break;
1797 		}
1798 		iov->iov_base = (char *)iov->iov_base + len;
1799 		iov->iov_len -= len;
1800 		uio->uio_offset += len;
1801 		uio->uio_resid -= len;
1802 	}
1803 
1804 	if (need_wapbl)
1805 		WAPBL_END(vp->v_mount);
1806 }
1807 
1808 /*
1809  * Iodone routine for direct I/O.  We don't do much here since the request is
1810  * always synchronous, so the caller will do most of the work after biowait().
1811  */
1812 
1813 static void
1814 genfs_dio_iodone(struct buf *bp)
1815 {
1816 
1817 	KASSERT((bp->b_flags & B_ASYNC) == 0);
1818 	if ((bp->b_flags & B_READ) == 0 && (bp->b_cflags & BC_AGE) != 0) {
1819 		mutex_enter(bp->b_objlock);
1820 		vwakeup(bp);
1821 		mutex_exit(bp->b_objlock);
1822 	}
1823 	putiobuf(bp);
1824 }
1825 
1826 /*
1827  * Process one chunk of a direct I/O request.
1828  */
1829 
1830 static int
1831 genfs_do_directio(struct vmspace *vs, vaddr_t uva, size_t len, struct vnode *vp,
1832     off_t off, enum uio_rw rw)
1833 {
1834 	struct vm_map *map;
1835 	struct pmap *upm, *kpm __unused;
1836 	size_t klen = round_page(uva + len) - trunc_page(uva);
1837 	off_t spoff, epoff;
1838 	vaddr_t kva, puva;
1839 	paddr_t pa;
1840 	vm_prot_t prot;
1841 	int error, rv __diagused, poff, koff;
1842 	const int pgoflags = PGO_CLEANIT | PGO_SYNCIO | PGO_JOURNALLOCKED |
1843 		(rw == UIO_WRITE ? PGO_FREE : 0);
1844 
1845 	/*
1846 	 * For writes, verify that this range of the file already has fully
1847 	 * allocated backing store.  If there are any holes, just punt and
1848 	 * make the caller take the buffered write path.
1849 	 */
1850 
1851 	if (rw == UIO_WRITE) {
1852 		daddr_t lbn, elbn, blkno;
1853 		int bsize, bshift, run;
1854 
1855 		bshift = vp->v_mount->mnt_fs_bshift;
1856 		bsize = 1 << bshift;
1857 		lbn = off >> bshift;
1858 		elbn = (off + len + bsize - 1) >> bshift;
1859 		while (lbn < elbn) {
1860 			error = VOP_BMAP(vp, lbn, NULL, &blkno, &run);
1861 			if (error) {
1862 				return error;
1863 			}
1864 			if (blkno == (daddr_t)-1) {
1865 				return ENOSPC;
1866 			}
1867 			lbn += 1 + run;
1868 		}
1869 	}
1870 
1871 	/*
1872 	 * Flush any cached pages for parts of the file that we're about to
1873 	 * access.  If we're writing, invalidate pages as well.
1874 	 */
1875 
1876 	spoff = trunc_page(off);
1877 	epoff = round_page(off + len);
1878 	mutex_enter(vp->v_interlock);
1879 	error = VOP_PUTPAGES(vp, spoff, epoff, pgoflags);
1880 	if (error) {
1881 		return error;
1882 	}
1883 
1884 	/*
1885 	 * Wire the user pages and remap them into kernel memory.
1886 	 */
1887 
1888 	prot = rw == UIO_READ ? VM_PROT_READ | VM_PROT_WRITE : VM_PROT_READ;
1889 	error = uvm_vslock(vs, (void *)uva, len, prot);
1890 	if (error) {
1891 		return error;
1892 	}
1893 
1894 	map = &vs->vm_map;
1895 	upm = vm_map_pmap(map);
1896 	kpm = vm_map_pmap(kernel_map);
1897 	puva = trunc_page(uva);
1898 	kva = uvm_km_alloc(kernel_map, klen, atop(puva) & uvmexp.colormask,
1899 	    UVM_KMF_VAONLY | UVM_KMF_WAITVA | UVM_KMF_COLORMATCH);
1900 	for (poff = 0; poff < klen; poff += PAGE_SIZE) {
1901 		rv = pmap_extract(upm, puva + poff, &pa);
1902 		KASSERT(rv);
1903 		pmap_kenter_pa(kva + poff, pa, prot, PMAP_WIRED);
1904 	}
1905 	pmap_update(kpm);
1906 
1907 	/*
1908 	 * Do the I/O.
1909 	 */
1910 
1911 	koff = uva - trunc_page(uva);
1912 	error = genfs_do_io(vp, off, kva + koff, len, PGO_SYNCIO, rw,
1913 			    genfs_dio_iodone);
1914 
1915 	/*
1916 	 * Tear down the kernel mapping.
1917 	 */
1918 
1919 	pmap_kremove(kva, klen);
1920 	pmap_update(kpm);
1921 	uvm_km_free(kernel_map, kva, klen, UVM_KMF_VAONLY);
1922 
1923 	/*
1924 	 * Unwire the user pages.
1925 	 */
1926 
1927 	uvm_vsunlock(vs, (void *)uva, len);
1928 	return error;
1929 }
1930