xref: /openbsd-src/sys/uvm/uvm_vnode.c (revision 25c4e8bd056e974b28f4a0ffd39d76c190a56013)
1 /*	$OpenBSD: uvm_vnode.c,v 1.125 2022/07/07 13:52:20 mpi Exp $	*/
2 /*	$NetBSD: uvm_vnode.c,v 1.36 2000/11/24 20:34:01 chs Exp $	*/
3 
4 /*
5  * Copyright (c) 1997 Charles D. Cranor and Washington University.
6  * Copyright (c) 1991, 1993
7  *      The Regents of the University of California.
8  * Copyright (c) 1990 University of Utah.
9  *
10  * All rights reserved.
11  *
12  * This code is derived from software contributed to Berkeley by
13  * the Systems Programming Group of the University of Utah Computer
14  * Science Department.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 3. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  *
40  *      @(#)vnode_pager.c       8.8 (Berkeley) 2/13/94
41  * from: Id: uvm_vnode.c,v 1.1.2.26 1998/02/02 20:38:07 chuck Exp
42  */
43 
44 /*
45  * uvm_vnode.c: the vnode pager.
46  */
47 
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/proc.h>
51 #include <sys/malloc.h>
52 #include <sys/vnode.h>
53 #include <sys/lock.h>
54 #include <sys/disklabel.h>
55 #include <sys/fcntl.h>
56 #include <sys/conf.h>
57 #include <sys/rwlock.h>
58 #include <sys/dkio.h>
59 #include <sys/specdev.h>
60 
61 #include <uvm/uvm.h>
62 #include <uvm/uvm_vnode.h>
63 
64 /*
65  * private global data structure
66  *
67  * we keep a list of writeable active vnode-backed VM objects for sync op.
68  * we keep a simpleq of vnodes that are currently being sync'd.
69  */
70 
71 LIST_HEAD(uvn_list_struct, uvm_vnode);
72 struct uvn_list_struct uvn_wlist;	/* writeable uvns */
73 
74 SIMPLEQ_HEAD(uvn_sq_struct, uvm_vnode);
75 struct uvn_sq_struct uvn_sync_q;		/* sync'ing uvns */
76 struct rwlock uvn_sync_lock;			/* locks sync operation */
77 
78 extern int rebooting;
79 
80 /*
81  * functions
82  */
83 void		 uvn_cluster(struct uvm_object *, voff_t, voff_t *, voff_t *);
84 void		 uvn_detach(struct uvm_object *);
85 boolean_t	 uvn_flush(struct uvm_object *, voff_t, voff_t, int);
86 int		 uvn_get(struct uvm_object *, voff_t, vm_page_t *, int *, int,
87 		     vm_prot_t, int, int);
88 void		 uvn_init(void);
89 int		 uvn_io(struct uvm_vnode *, vm_page_t *, int, int, int);
90 int		 uvn_put(struct uvm_object *, vm_page_t *, int, boolean_t);
91 void		 uvn_reference(struct uvm_object *);
92 
93 /*
94  * master pager structure
95  */
96 const struct uvm_pagerops uvm_vnodeops = {
97 	.pgo_init = uvn_init,
98 	.pgo_reference = uvn_reference,
99 	.pgo_detach = uvn_detach,
100 	.pgo_flush = uvn_flush,
101 	.pgo_get = uvn_get,
102 	.pgo_put = uvn_put,
103 	.pgo_cluster = uvn_cluster,
104 	/* use generic version of this: see uvm_pager.c */
105 	.pgo_mk_pcluster = uvm_mk_pcluster,
106 };
107 
108 /*
109  * the ops!
110  */
111 /*
112  * uvn_init
113  *
114  * init pager private data structures.
115  */
116 void
117 uvn_init(void)
118 {
119 
120 	LIST_INIT(&uvn_wlist);
121 	/* note: uvn_sync_q init'd in uvm_vnp_sync() */
122 	rw_init_flags(&uvn_sync_lock, "uvnsync", RWL_IS_VNODE);
123 }
124 
125 /*
126  * uvn_attach
127  *
128  * attach a vnode structure to a VM object.  if the vnode is already
129  * attached, then just bump the reference count by one and return the
130  * VM object.   if not already attached, attach and return the new VM obj.
131  * the "accessprot" tells the max access the attaching thread wants to
132  * our pages.
133  *
134  * => in fact, nothing should be locked so that we can sleep here.
135  * => note that uvm_object is first thing in vnode structure, so their
136  *    pointers are equiv.
137  */
138 struct uvm_object *
139 uvn_attach(struct vnode *vp, vm_prot_t accessprot)
140 {
141 	struct uvm_vnode *uvn = vp->v_uvm;
142 	struct vattr vattr;
143 	int oldflags, result;
144 	struct partinfo pi;
145 	u_quad_t used_vnode_size = 0;
146 
147 	/* first get a lock on the uvn. */
148 	while (uvn->u_flags & UVM_VNODE_BLOCKED) {
149 		uvn->u_flags |= UVM_VNODE_WANTED;
150 		tsleep_nsec(uvn, PVM, "uvn_attach", INFSLP);
151 	}
152 
153 	/* if we're mapping a BLK device, make sure it is a disk. */
154 	if (vp->v_type == VBLK && bdevsw[major(vp->v_rdev)].d_type != D_DISK) {
155 		return NULL;
156 	}
157 
158 	/*
159 	 * now uvn must not be in a blocked state.
160 	 * first check to see if it is already active, in which case
161 	 * we can bump the reference count, check to see if we need to
162 	 * add it to the writeable list, and then return.
163 	 */
164 	if (uvn->u_flags & UVM_VNODE_VALID) {	/* already active? */
165 
166 		rw_enter(uvn->u_obj.vmobjlock, RW_WRITE);
167 		/* regain vref if we were persisting */
168 		if (uvn->u_obj.uo_refs == 0) {
169 			vref(vp);
170 		}
171 		uvn->u_obj.uo_refs++;		/* bump uvn ref! */
172 		rw_exit(uvn->u_obj.vmobjlock);
173 
174 		/* check for new writeable uvn */
175 		if ((accessprot & PROT_WRITE) != 0 &&
176 		    (uvn->u_flags & UVM_VNODE_WRITEABLE) == 0) {
177 			LIST_INSERT_HEAD(&uvn_wlist, uvn, u_wlist);
178 			/* we are now on wlist! */
179 			uvn->u_flags |= UVM_VNODE_WRITEABLE;
180 		}
181 
182 		return (&uvn->u_obj);
183 	}
184 
185 	/*
186 	 * need to call VOP_GETATTR() to get the attributes, but that could
187 	 * block (due to I/O), so we want to unlock the object before calling.
188 	 * however, we want to keep anyone else from playing with the object
189 	 * while it is unlocked.   to do this we set UVM_VNODE_ALOCK which
190 	 * prevents anyone from attaching to the vnode until we are done with
191 	 * it.
192 	 */
193 	uvn->u_flags = UVM_VNODE_ALOCK;
194 
195 	if (vp->v_type == VBLK) {
196 		/*
197 		 * We could implement this as a specfs getattr call, but:
198 		 *
199 		 *	(1) VOP_GETATTR() would get the file system
200 		 *	    vnode operation, not the specfs operation.
201 		 *
202 		 *	(2) All we want is the size, anyhow.
203 		 */
204 		result = (*bdevsw[major(vp->v_rdev)].d_ioctl)(vp->v_rdev,
205 		    DIOCGPART, (caddr_t)&pi, FREAD, curproc);
206 		if (result == 0) {
207 			/* XXX should remember blocksize */
208 			used_vnode_size = (u_quad_t)pi.disklab->d_secsize *
209 			    (u_quad_t)DL_GETPSIZE(pi.part);
210 		}
211 	} else {
212 		result = VOP_GETATTR(vp, &vattr, curproc->p_ucred, curproc);
213 		if (result == 0)
214 			used_vnode_size = vattr.va_size;
215 	}
216 
217 	if (result != 0) {
218 		if (uvn->u_flags & UVM_VNODE_WANTED)
219 			wakeup(uvn);
220 		uvn->u_flags = 0;
221 		return NULL;
222 	}
223 
224 	/*
225 	 * make sure that the newsize fits within a vaddr_t
226 	 * XXX: need to revise addressing data types
227 	 */
228 #ifdef DEBUG
229 	if (vp->v_type == VBLK)
230 		printf("used_vnode_size = %llu\n", (long long)used_vnode_size);
231 #endif
232 
233 	/* now set up the uvn. */
234 	KASSERT(uvn->u_obj.uo_refs == 0);
235 	uvn->u_obj.uo_refs++;
236 	oldflags = uvn->u_flags;
237 	uvn->u_flags = UVM_VNODE_VALID|UVM_VNODE_CANPERSIST;
238 	uvn->u_nio = 0;
239 	uvn->u_size = used_vnode_size;
240 
241 	/* if write access, we need to add it to the wlist */
242 	if (accessprot & PROT_WRITE) {
243 		LIST_INSERT_HEAD(&uvn_wlist, uvn, u_wlist);
244 		uvn->u_flags |= UVM_VNODE_WRITEABLE;	/* we are on wlist! */
245 	}
246 
247 	/*
248 	 * add a reference to the vnode.   this reference will stay as long
249 	 * as there is a valid mapping of the vnode.   dropped when the
250 	 * reference count goes to zero [and we either free or persist].
251 	 */
252 	vref(vp);
253 	if (oldflags & UVM_VNODE_WANTED)
254 		wakeup(uvn);
255 
256 	return &uvn->u_obj;
257 }
258 
259 
260 /*
261  * uvn_reference
262  *
263  * duplicate a reference to a VM object.  Note that the reference
264  * count must already be at least one (the passed in reference) so
265  * there is no chance of the uvn being killed out here.
266  *
267  * => caller must be using the same accessprot as was used at attach time
268  */
269 
270 
271 void
272 uvn_reference(struct uvm_object *uobj)
273 {
274 #ifdef DEBUG
275 	struct uvm_vnode *uvn = (struct uvm_vnode *) uobj;
276 #endif
277 
278 #ifdef DEBUG
279 	if ((uvn->u_flags & UVM_VNODE_VALID) == 0) {
280 		printf("uvn_reference: ref=%d, flags=0x%x\n",
281 		    uobj->uo_refs, uvn->u_flags);
282 		panic("uvn_reference: invalid state");
283 	}
284 #endif
285 	rw_enter(uobj->vmobjlock, RW_WRITE);
286 	uobj->uo_refs++;
287 	rw_exit(uobj->vmobjlock);
288 }
289 
290 /*
291  * uvn_detach
292  *
293  * remove a reference to a VM object.
294  *
295  * => caller must call with map locked.
296  * => this starts the detach process, but doesn't have to finish it
297  *    (async i/o could still be pending).
298  */
299 void
300 uvn_detach(struct uvm_object *uobj)
301 {
302 	struct uvm_vnode *uvn;
303 	struct vnode *vp;
304 	int oldflags;
305 
306 	rw_enter(uobj->vmobjlock, RW_WRITE);
307 	uobj->uo_refs--;			/* drop ref! */
308 	if (uobj->uo_refs) {			/* still more refs */
309 		rw_exit(uobj->vmobjlock);
310 		return;
311 	}
312 
313 	/* get other pointers ... */
314 	uvn = (struct uvm_vnode *) uobj;
315 	vp = uvn->u_vnode;
316 
317 	/*
318 	 * clear VTEXT flag now that there are no mappings left (VTEXT is used
319 	 * to keep an active text file from being overwritten).
320 	 */
321 	vp->v_flag &= ~VTEXT;
322 
323 	/*
324 	 * we just dropped the last reference to the uvn.   see if we can
325 	 * let it "stick around".
326 	 */
327 	if (uvn->u_flags & UVM_VNODE_CANPERSIST) {
328 		/* won't block */
329 		uvn_flush(uobj, 0, 0, PGO_DEACTIVATE|PGO_ALLPAGES);
330 		goto out;
331 	}
332 
333 	/* its a goner! */
334 	uvn->u_flags |= UVM_VNODE_DYING;
335 
336 	/*
337 	 * even though we may unlock in flush, no one can gain a reference
338 	 * to us until we clear the "dying" flag [because it blocks
339 	 * attaches].  we will not do that until after we've disposed of all
340 	 * the pages with uvn_flush().  note that before the flush the only
341 	 * pages that could be marked PG_BUSY are ones that are in async
342 	 * pageout by the daemon.  (there can't be any pending "get"'s
343 	 * because there are no references to the object).
344 	 */
345 	(void) uvn_flush(uobj, 0, 0, PGO_CLEANIT|PGO_FREE|PGO_ALLPAGES);
346 
347 	/*
348 	 * given the structure of this pager, the above flush request will
349 	 * create the following state: all the pages that were in the object
350 	 * have either been free'd or they are marked PG_BUSY and in the
351 	 * middle of an async io. If we still have pages we set the "relkill"
352 	 * state, so that in the case the vnode gets terminated we know
353 	 * to leave it alone. Otherwise we'll kill the vnode when it's empty.
354 	 */
355 	uvn->u_flags |= UVM_VNODE_RELKILL;
356 	/* wait on any outstanding io */
357 	while (uobj->uo_npages && uvn->u_flags & UVM_VNODE_RELKILL) {
358 		uvn->u_flags |= UVM_VNODE_IOSYNC;
359 		rwsleep_nsec(&uvn->u_nio, uobj->vmobjlock, PVM, "uvn_term",
360 		    INFSLP);
361 	}
362 
363 	if ((uvn->u_flags & UVM_VNODE_RELKILL) == 0) {
364 		rw_exit(uobj->vmobjlock);
365 		return;
366 	}
367 
368 	/*
369 	 * kill object now.   note that we can't be on the sync q because
370 	 * all references are gone.
371 	 */
372 	if (uvn->u_flags & UVM_VNODE_WRITEABLE) {
373 		LIST_REMOVE(uvn, u_wlist);
374 	}
375 	KASSERT(RBT_EMPTY(uvm_objtree, &uobj->memt));
376 	oldflags = uvn->u_flags;
377 	uvn->u_flags = 0;
378 
379 	/* wake up any sleepers */
380 	if (oldflags & UVM_VNODE_WANTED)
381 		wakeup(uvn);
382 out:
383 	rw_exit(uobj->vmobjlock);
384 
385 	/* drop our reference to the vnode. */
386 	vrele(vp);
387 
388 	return;
389 }
390 
391 /*
392  * uvm_vnp_terminate: external hook to clear out a vnode's VM
393  *
394  * called in two cases:
395  *  [1] when a persisting vnode vm object (i.e. one with a zero reference
396  *      count) needs to be freed so that a vnode can be reused.  this
397  *      happens under "getnewvnode" in vfs_subr.c.   if the vnode from
398  *      the free list is still attached (i.e. not VBAD) then vgone is
399  *	called.   as part of the vgone trace this should get called to
400  *	free the vm object.   this is the common case.
401  *  [2] when a filesystem is being unmounted by force (MNT_FORCE,
402  *	"umount -f") the vgone() function is called on active vnodes
403  *	on the mounted file systems to kill their data (the vnodes become
404  *	"dead" ones [see src/sys/miscfs/deadfs/...]).  that results in a
405  *	call here (even if the uvn is still in use -- i.e. has a non-zero
406  *	reference count).  this case happens at "umount -f" and during a
407  *	"reboot/halt" operation.
408  *
409  * => the caller must XLOCK and VOP_LOCK the vnode before calling us
410  *	[protects us from getting a vnode that is already in the DYING
411  *	 state...]
412  * => in case [2] the uvn is still alive after this call, but all I/O
413  *	ops will fail (due to the backing vnode now being "dead").  this
414  *	will prob. kill any process using the uvn due to pgo_get failing.
415  */
416 void
417 uvm_vnp_terminate(struct vnode *vp)
418 {
419 	struct uvm_vnode *uvn = vp->v_uvm;
420 	struct uvm_object *uobj = &uvn->u_obj;
421 	int oldflags;
422 
423 	/* check if it is valid */
424 	rw_enter(uobj->vmobjlock, RW_WRITE);
425 	if ((uvn->u_flags & UVM_VNODE_VALID) == 0) {
426 		rw_exit(uobj->vmobjlock);
427 		return;
428 	}
429 
430 	/*
431 	 * must be a valid uvn that is not already dying (because XLOCK
432 	 * protects us from that).   the uvn can't in the ALOCK state
433 	 * because it is valid, and uvn's that are in the ALOCK state haven't
434 	 * been marked valid yet.
435 	 */
436 #ifdef DEBUG
437 	/*
438 	 * debug check: are we yanking the vnode out from under our uvn?
439 	 */
440 	if (uvn->u_obj.uo_refs) {
441 		printf("uvm_vnp_terminate(%p): terminating active vnode "
442 		    "(refs=%d)\n", uvn, uvn->u_obj.uo_refs);
443 	}
444 #endif
445 
446 	/*
447 	 * it is possible that the uvn was detached and is in the relkill
448 	 * state [i.e. waiting for async i/o to finish].
449 	 * we take over the vnode now and cancel the relkill.
450 	 * we want to know when the i/o is done so we can recycle right
451 	 * away.   note that a uvn can only be in the RELKILL state if it
452 	 * has a zero reference count.
453 	 */
454 	if (uvn->u_flags & UVM_VNODE_RELKILL)
455 		uvn->u_flags &= ~UVM_VNODE_RELKILL;	/* cancel RELKILL */
456 
457 	/*
458 	 * block the uvn by setting the dying flag, and then flush the
459 	 * pages.
460 	 *
461 	 * also, note that we tell I/O that we are already VOP_LOCK'd so
462 	 * that uvn_io doesn't attempt to VOP_LOCK again.
463 	 *
464 	 * XXXCDC: setting VNISLOCKED on an active uvn which is being terminated
465 	 *	due to a forceful unmount might not be a good idea.  maybe we
466 	 *	need a way to pass in this info to uvn_flush through a
467 	 *	pager-defined PGO_ constant [currently there are none].
468 	 */
469 	uvn->u_flags |= UVM_VNODE_DYING|UVM_VNODE_VNISLOCKED;
470 
471 	(void) uvn_flush(&uvn->u_obj, 0, 0, PGO_CLEANIT|PGO_FREE|PGO_ALLPAGES);
472 
473 	/*
474 	 * as we just did a flush we expect all the pages to be gone or in
475 	 * the process of going.  sleep to wait for the rest to go [via iosync].
476 	 */
477 	while (uvn->u_obj.uo_npages) {
478 #ifdef DEBUG
479 		struct vm_page *pp;
480 		RBT_FOREACH(pp, uvm_objtree, &uvn->u_obj.memt) {
481 			if ((pp->pg_flags & PG_BUSY) == 0)
482 				panic("uvm_vnp_terminate: detected unbusy pg");
483 		}
484 		if (uvn->u_nio == 0)
485 			panic("uvm_vnp_terminate: no I/O to wait for?");
486 		printf("uvm_vnp_terminate: waiting for I/O to fin.\n");
487 		/*
488 		 * XXXCDC: this is unlikely to happen without async i/o so we
489 		 * put a printf in just to keep an eye on it.
490 		 */
491 #endif
492 		uvn->u_flags |= UVM_VNODE_IOSYNC;
493 		rwsleep_nsec(&uvn->u_nio, uobj->vmobjlock, PVM, "uvn_term",
494 		    INFSLP);
495 	}
496 
497 	/*
498 	 * done.   now we free the uvn if its reference count is zero
499 	 * (true if we are zapping a persisting uvn).   however, if we are
500 	 * terminating a uvn with active mappings we let it live ... future
501 	 * calls down to the vnode layer will fail.
502 	 */
503 	oldflags = uvn->u_flags;
504 	if (uvn->u_obj.uo_refs) {
505 		/*
506 		 * uvn must live on it is dead-vnode state until all references
507 		 * are gone.   restore flags.    clear CANPERSIST state.
508 		 */
509 		uvn->u_flags &= ~(UVM_VNODE_DYING|UVM_VNODE_VNISLOCKED|
510 		      UVM_VNODE_WANTED|UVM_VNODE_CANPERSIST);
511 	} else {
512 		/*
513 		 * free the uvn now.   note that the vref reference is already
514 		 * gone [it is dropped when we enter the persist state].
515 		 */
516 		if (uvn->u_flags & UVM_VNODE_IOSYNCWANTED)
517 			panic("uvm_vnp_terminate: io sync wanted bit set");
518 
519 		if (uvn->u_flags & UVM_VNODE_WRITEABLE) {
520 			LIST_REMOVE(uvn, u_wlist);
521 		}
522 		uvn->u_flags = 0;	/* uvn is history, clear all bits */
523 	}
524 
525 	if (oldflags & UVM_VNODE_WANTED)
526 		wakeup(uvn);
527 
528 	rw_exit(uobj->vmobjlock);
529 }
530 
531 /*
532  * NOTE: currently we have to use VOP_READ/VOP_WRITE because they go
533  * through the buffer cache and allow I/O in any size.  These VOPs use
534  * synchronous i/o.  [vs. VOP_STRATEGY which can be async, but doesn't
535  * go through the buffer cache or allow I/O sizes larger than a
536  * block].  we will eventually want to change this.
537  *
538  * issues to consider:
539  *   uvm provides the uvm_aiodesc structure for async i/o management.
540  * there are two tailq's in the uvm. structure... one for pending async
541  * i/o and one for "done" async i/o.   to do an async i/o one puts
542  * an aiodesc on the "pending" list (protected by splbio()), starts the
543  * i/o and returns VM_PAGER_PEND.    when the i/o is done, we expect
544  * some sort of "i/o done" function to be called (at splbio(), interrupt
545  * time).   this function should remove the aiodesc from the pending list
546  * and place it on the "done" list and wakeup the daemon.   the daemon
547  * will run at normal spl() and will remove all items from the "done"
548  * list and call the "aiodone" hook for each done request (see uvm_pager.c).
549  * [in the old vm code, this was done by calling the "put" routine with
550  * null arguments which made the code harder to read and understand because
551  * you had one function ("put") doing two things.]
552  *
553  * so the current pager needs:
554  *   int uvn_aiodone(struct uvm_aiodesc *)
555  *
556  * => return 0 (aio finished, free it). otherwise requeue for later collection.
557  * => called with pageq's locked by the daemon.
558  *
559  * general outline:
560  * - drop "u_nio" (this req is done!)
561  * - if (object->iosync && u_naio == 0) { wakeup &uvn->u_naio }
562  * - get "page" structures (atop?).
563  * - handle "wanted" pages
564  * dont forget to look at "object" wanted flag in all cases.
565  */
566 
567 /*
568  * uvn_flush: flush pages out of a uvm object.
569  *
570  * => if PGO_CLEANIT is set, we may block (due to I/O).   thus, a caller
571  *	might want to unlock higher level resources (e.g. vm_map)
572  *	before calling flush.
573  * => if PGO_CLEANIT is not set, then we will not block
574  * => if PGO_ALLPAGE is set, then all pages in the object are valid targets
575  *	for flushing.
576  * => NOTE: we are allowed to lock the page queues, so the caller
577  *	must not be holding the lock on them [e.g. pagedaemon had
578  *	better not call us with the queues locked]
579  * => we return TRUE unless we encountered some sort of I/O error
580  *
581  * comment on "cleaning" object and PG_BUSY pages:
582  *	this routine is holding the lock on the object.   the only time
583  *	that it can run into a PG_BUSY page that it does not own is if
584  *	some other process has started I/O on the page (e.g. either
585  *	a pagein, or a pageout).    if the PG_BUSY page is being paged
586  *	in, then it can not be dirty (!PG_CLEAN) because no one has
587  *	had a chance to modify it yet.    if the PG_BUSY page is being
588  *	paged out then it means that someone else has already started
589  *	cleaning the page for us (how nice!).    in this case, if we
590  *	have syncio specified, then after we make our pass through the
591  *	object we need to wait for the other PG_BUSY pages to clear
592  *	off (i.e. we need to do an iosync).   also note that once a
593  *	page is PG_BUSY it must stay in its object until it is un-busyed.
594  */
595 boolean_t
596 uvn_flush(struct uvm_object *uobj, voff_t start, voff_t stop, int flags)
597 {
598 	struct uvm_vnode *uvn = (struct uvm_vnode *) uobj;
599 	struct vm_page *pp, *ptmp;
600 	struct vm_page *pps[MAXBSIZE >> PAGE_SHIFT], **ppsp;
601 	struct pglist dead;
602 	int npages, result, lcv;
603 	boolean_t retval, need_iosync, needs_clean;
604 	voff_t curoff;
605 
606 	KASSERT(rw_write_held(uobj->vmobjlock));
607 	TAILQ_INIT(&dead);
608 
609 	/* get init vals and determine how we are going to traverse object */
610 	need_iosync = FALSE;
611 	retval = TRUE;		/* return value */
612 	if (flags & PGO_ALLPAGES) {
613 		start = 0;
614 		stop = round_page(uvn->u_size);
615 	} else {
616 		start = trunc_page(start);
617 		stop = MIN(round_page(stop), round_page(uvn->u_size));
618 	}
619 
620 	/*
621 	 * PG_CLEANCHK: this bit is used by the pgo_mk_pcluster function as
622 	 * a _hint_ as to how up to date the PG_CLEAN bit is.   if the hint
623 	 * is wrong it will only prevent us from clustering... it won't break
624 	 * anything.   we clear all PG_CLEANCHK bits here, and pgo_mk_pcluster
625 	 * will set them as it syncs PG_CLEAN.   This is only an issue if we
626 	 * are looking at non-inactive pages (because inactive page's PG_CLEAN
627 	 * bit is always up to date since there are no mappings).
628 	 * [borrowed PG_CLEANCHK idea from FreeBSD VM]
629 	 */
630 	if ((flags & PGO_CLEANIT) != 0) {
631 		KASSERT(uobj->pgops->pgo_mk_pcluster != 0);
632 		for (curoff = start ; curoff < stop; curoff += PAGE_SIZE) {
633 			if ((pp = uvm_pagelookup(uobj, curoff)) != NULL)
634 				atomic_clearbits_int(&pp->pg_flags,
635 				    PG_CLEANCHK);
636 		}
637 	}
638 
639 	ppsp = NULL;		/* XXX: shut up gcc */
640 	uvm_lock_pageq();
641 	/* locked: both page queues */
642 	for (curoff = start; curoff < stop; curoff += PAGE_SIZE) {
643 		if ((pp = uvm_pagelookup(uobj, curoff)) == NULL)
644 			continue;
645 		/*
646 		 * handle case where we do not need to clean page (either
647 		 * because we are not clean or because page is not dirty or
648 		 * is busy):
649 		 *
650 		 * NOTE: we are allowed to deactivate a non-wired active
651 		 * PG_BUSY page, but once a PG_BUSY page is on the inactive
652 		 * queue it must stay put until it is !PG_BUSY (so as not to
653 		 * confuse pagedaemon).
654 		 */
655 		if ((flags & PGO_CLEANIT) == 0 || (pp->pg_flags & PG_BUSY) != 0) {
656 			needs_clean = FALSE;
657 			if ((pp->pg_flags & PG_BUSY) != 0 &&
658 			    (flags & (PGO_CLEANIT|PGO_SYNCIO)) ==
659 			             (PGO_CLEANIT|PGO_SYNCIO))
660 				need_iosync = TRUE;
661 		} else {
662 			/*
663 			 * freeing: nuke all mappings so we can sync
664 			 * PG_CLEAN bit with no race
665 			 */
666 			if ((pp->pg_flags & PG_CLEAN) != 0 &&
667 			    (flags & PGO_FREE) != 0 &&
668 			    (pp->pg_flags & PQ_ACTIVE) != 0)
669 				pmap_page_protect(pp, PROT_NONE);
670 			if ((pp->pg_flags & PG_CLEAN) != 0 &&
671 			    pmap_is_modified(pp))
672 				atomic_clearbits_int(&pp->pg_flags, PG_CLEAN);
673 			atomic_setbits_int(&pp->pg_flags, PG_CLEANCHK);
674 
675 			needs_clean = ((pp->pg_flags & PG_CLEAN) == 0);
676 		}
677 
678 		/* if we don't need a clean, deactivate/free pages then cont. */
679 		if (!needs_clean) {
680 			if (flags & PGO_DEACTIVATE) {
681 				if (pp->wire_count == 0) {
682 					pmap_page_protect(pp, PROT_NONE);
683 					uvm_pagedeactivate(pp);
684 				}
685 			} else if (flags & PGO_FREE) {
686 				if (pp->pg_flags & PG_BUSY) {
687 					atomic_setbits_int(&pp->pg_flags,
688 					    PG_WANTED);
689 					uvm_unlock_pageq();
690 					rwsleep_nsec(pp, uobj->vmobjlock, PVM,
691 					    "uvn_flsh", INFSLP);
692 					uvm_lock_pageq();
693 					curoff -= PAGE_SIZE;
694 					continue;
695 				} else {
696 					pmap_page_protect(pp, PROT_NONE);
697 					/* removed page from object */
698 					uvm_pageclean(pp);
699 					TAILQ_INSERT_HEAD(&dead, pp, pageq);
700 				}
701 			}
702 			continue;
703 		}
704 
705 		/*
706 		 * pp points to a page in the object that we are
707 		 * working on.  if it is !PG_CLEAN,!PG_BUSY and we asked
708 		 * for cleaning (PGO_CLEANIT).  we clean it now.
709 		 *
710 		 * let uvm_pager_put attempted a clustered page out.
711 		 * note: locked: page queues.
712 		 */
713 		atomic_setbits_int(&pp->pg_flags, PG_BUSY);
714 		UVM_PAGE_OWN(pp, "uvn_flush");
715 		pmap_page_protect(pp, PROT_READ);
716 		/* if we're async, free the page in aiodoned */
717 		if ((flags & (PGO_FREE|PGO_SYNCIO)) == PGO_FREE)
718 			atomic_setbits_int(&pp->pg_flags, PG_RELEASED);
719 ReTry:
720 		ppsp = pps;
721 		npages = sizeof(pps) / sizeof(struct vm_page *);
722 
723 		result = uvm_pager_put(uobj, pp, &ppsp, &npages,
724 			   flags | PGO_DOACTCLUST, start, stop);
725 
726 		/*
727 		 * if we did an async I/O it is remotely possible for the
728 		 * async i/o to complete and the page "pp" be freed or what
729 		 * not before we get a chance to relock the object. Therefore,
730 		 * we only touch it when it won't be freed, RELEASED took care
731 		 * of the rest.
732 		 */
733 		uvm_lock_pageq();
734 
735 		/*
736 		 * VM_PAGER_AGAIN: given the structure of this pager, this
737 		 * can only happen when we are doing async I/O and can't
738 		 * map the pages into kernel memory (pager_map) due to lack
739 		 * of vm space.   if this happens we drop back to sync I/O.
740 		 */
741 		if (result == VM_PAGER_AGAIN) {
742 			/*
743 			 * it is unlikely, but page could have been released
744 			 * we ignore this now and retry the I/O.
745 			 * we will detect and
746 			 * handle the released page after the syncio I/O
747 			 * completes.
748 			 */
749 #ifdef DIAGNOSTIC
750 			if (flags & PGO_SYNCIO)
751 	panic("%s: PGO_SYNCIO return 'try again' error (impossible)", __func__);
752 #endif
753 			flags |= PGO_SYNCIO;
754 			if (flags & PGO_FREE)
755 				atomic_clearbits_int(&pp->pg_flags,
756 				    PG_RELEASED);
757 
758 			goto ReTry;
759 		}
760 
761 		/*
762 		 * the cleaning operation is now done.   finish up.  note that
763 		 * on error (!OK, !PEND) uvm_pager_put drops the cluster for us.
764 		 * if success (OK, PEND) then uvm_pager_put returns the cluster
765 		 * to us in ppsp/npages.
766 		 */
767 		/*
768 		 * for pending async i/o if we are not deactivating
769 		 * we can move on to the next page. aiodoned deals with
770 		 * the freeing case for us.
771 		 */
772 		if (result == VM_PAGER_PEND && (flags & PGO_DEACTIVATE) == 0)
773 			continue;
774 
775 		/*
776 		 * need to look at each page of the I/O operation, and do what
777 		 * we gotta do.
778 		 */
779 		for (lcv = 0 ; lcv < npages; lcv++) {
780 			ptmp = ppsp[lcv];
781 			/*
782 			 * verify the page didn't get moved
783 			 */
784 			if (result == VM_PAGER_PEND && ptmp->uobject != uobj)
785 				continue;
786 
787 			/*
788 			 * unbusy the page if I/O is done.   note that for
789 			 * pending I/O it is possible that the I/O op
790 			 * finished
791 			 * (in which case the page is no longer busy).
792 			 */
793 			if (result != VM_PAGER_PEND) {
794 				if (ptmp->pg_flags & PG_WANTED)
795 					wakeup(ptmp);
796 
797 				atomic_clearbits_int(&ptmp->pg_flags,
798 				    PG_WANTED|PG_BUSY);
799 				UVM_PAGE_OWN(ptmp, NULL);
800 				atomic_setbits_int(&ptmp->pg_flags,
801 				    PG_CLEAN|PG_CLEANCHK);
802 				if ((flags & PGO_FREE) == 0)
803 					pmap_clear_modify(ptmp);
804 			}
805 
806 			/* dispose of page */
807 			if (flags & PGO_DEACTIVATE) {
808 				if (ptmp->wire_count == 0) {
809 					pmap_page_protect(ptmp, PROT_NONE);
810 					uvm_pagedeactivate(ptmp);
811 				}
812 			} else if (flags & PGO_FREE &&
813 			    result != VM_PAGER_PEND) {
814 				if (result != VM_PAGER_OK) {
815 					static struct timeval lasttime;
816 					static const struct timeval interval =
817 					    { 5, 0 };
818 
819 					if (ratecheck(&lasttime, &interval)) {
820 						printf("%s: obj=%p, "
821 						   "offset=0x%llx.  error "
822 						   "during pageout.\n",
823 						    __func__, pp->uobject,
824 						    (long long)pp->offset);
825 						printf("%s: WARNING: "
826 						    "changes to page may be "
827 						    "lost!\n", __func__);
828 					}
829 					retval = FALSE;
830 				}
831 				pmap_page_protect(ptmp, PROT_NONE);
832 				uvm_pageclean(ptmp);
833 				TAILQ_INSERT_TAIL(&dead, ptmp, pageq);
834 			}
835 
836 		}		/* end of "lcv" for loop */
837 
838 	}		/* end of "pp" for loop */
839 
840 	/* done with pagequeues: unlock */
841 	uvm_unlock_pageq();
842 
843 	/* now wait for all I/O if required. */
844 	if (need_iosync) {
845 		while (uvn->u_nio != 0) {
846 			uvn->u_flags |= UVM_VNODE_IOSYNC;
847 			rwsleep_nsec(&uvn->u_nio, uobj->vmobjlock, PVM,
848 			    "uvn_flush", INFSLP);
849 		}
850 		if (uvn->u_flags & UVM_VNODE_IOSYNCWANTED)
851 			wakeup(&uvn->u_flags);
852 		uvn->u_flags &= ~(UVM_VNODE_IOSYNC|UVM_VNODE_IOSYNCWANTED);
853 	}
854 
855 	uvm_pglistfree(&dead);
856 
857 	return retval;
858 }
859 
860 /*
861  * uvn_cluster
862  *
863  * we are about to do I/O in an object at offset.   this function is called
864  * to establish a range of offsets around "offset" in which we can cluster
865  * I/O.
866  */
867 
868 void
869 uvn_cluster(struct uvm_object *uobj, voff_t offset, voff_t *loffset,
870     voff_t *hoffset)
871 {
872 	struct uvm_vnode *uvn = (struct uvm_vnode *) uobj;
873 	*loffset = offset;
874 
875 	if (*loffset >= uvn->u_size)
876 		panic("uvn_cluster: offset out of range");
877 
878 	/*
879 	 * XXX: old pager claims we could use VOP_BMAP to get maxcontig value.
880 	 */
881 	*hoffset = *loffset + MAXBSIZE;
882 	if (*hoffset > round_page(uvn->u_size))	/* past end? */
883 		*hoffset = round_page(uvn->u_size);
884 
885 	return;
886 }
887 
888 /*
889  * uvn_put: flush page data to backing store.
890  *
891  * => prefer map unlocked (not required)
892  * => flags: PGO_SYNCIO -- use sync. I/O
893  * => note: caller must set PG_CLEAN and pmap_clear_modify (if needed)
894  * => XXX: currently we use VOP_READ/VOP_WRITE which are only sync.
895  *	[thus we never do async i/o!  see iodone comment]
896  */
897 int
898 uvn_put(struct uvm_object *uobj, struct vm_page **pps, int npages, int flags)
899 {
900 	int retval;
901 
902 	KASSERT(rw_write_held(uobj->vmobjlock));
903 
904 	retval = uvn_io((struct uvm_vnode*)uobj, pps, npages, flags, UIO_WRITE);
905 
906 	return retval;
907 }
908 
909 /*
910  * uvn_get: get pages (synchronously) from backing store
911  *
912  * => prefer map unlocked (not required)
913  * => flags: PGO_ALLPAGES: get all of the pages
914  *           PGO_LOCKED: fault data structures are locked
915  * => NOTE: offset is the offset of pps[0], _NOT_ pps[centeridx]
916  * => NOTE: caller must check for released pages!!
917  */
918 int
919 uvn_get(struct uvm_object *uobj, voff_t offset, struct vm_page **pps,
920     int *npagesp, int centeridx, vm_prot_t access_type, int advice, int flags)
921 {
922 	voff_t current_offset;
923 	struct vm_page *ptmp;
924 	int lcv, result, gotpages;
925 	boolean_t done;
926 
927 	KASSERT(((flags & PGO_LOCKED) != 0 && rw_lock_held(uobj->vmobjlock)) ||
928 	    (flags & PGO_LOCKED) == 0);
929 
930 	/* step 1: handled the case where fault data structures are locked. */
931 	if (flags & PGO_LOCKED) {
932 		/*
933 		 * gotpages is the current number of pages we've gotten (which
934 		 * we pass back up to caller via *npagesp.
935 		 */
936 		gotpages = 0;
937 
938 		/*
939 		 * step 1a: get pages that are already resident.   only do this
940 		 * if the data structures are locked (i.e. the first time
941 		 * through).
942 		 */
943 		done = TRUE;	/* be optimistic */
944 
945 		for (lcv = 0, current_offset = offset ; lcv < *npagesp ;
946 		    lcv++, current_offset += PAGE_SIZE) {
947 
948 			/* do we care about this page?  if not, skip it */
949 			if (pps[lcv] == PGO_DONTCARE)
950 				continue;
951 
952 			/* lookup page */
953 			ptmp = uvm_pagelookup(uobj, current_offset);
954 
955 			/* to be useful must get a non-busy, non-released pg */
956 			if (ptmp == NULL ||
957 			    (ptmp->pg_flags & PG_BUSY) != 0) {
958 				if (lcv == centeridx || (flags & PGO_ALLPAGES)
959 				    != 0)
960 					done = FALSE;	/* need to do a wait or I/O! */
961 				continue;
962 			}
963 
964 			/*
965 			 * useful page: busy it and plug it in our
966 			 * result array
967 			 */
968 			atomic_setbits_int(&ptmp->pg_flags, PG_BUSY);
969 			UVM_PAGE_OWN(ptmp, "uvn_get1");
970 			pps[lcv] = ptmp;
971 			gotpages++;
972 
973 		}
974 
975 		/*
976 		 * XXX: given the "advice", should we consider async read-ahead?
977 		 * XXX: fault current does deactivate of pages behind us.  is
978 		 * this good (other callers might now).
979 		 */
980 		/*
981 		 * XXX: read-ahead currently handled by buffer cache (bread)
982 		 * level.
983 		 * XXX: no async i/o available.
984 		 * XXX: so we don't do anything now.
985 		 */
986 
987 		/*
988 		 * step 1c: now we've either done everything needed or we to
989 		 * unlock and do some waiting or I/O.
990 		 */
991 
992 		*npagesp = gotpages;		/* let caller know */
993 		if (done)
994 			return VM_PAGER_OK;		/* bingo! */
995 		else
996 			return VM_PAGER_UNLOCK;
997 	}
998 
999 	/*
1000 	 * step 2: get non-resident or busy pages.
1001 	 * data structures are unlocked.
1002 	 *
1003 	 * XXX: because we can't do async I/O at this level we get things
1004 	 * page at a time (otherwise we'd chunk).   the VOP_READ() will do
1005 	 * async-read-ahead for us at a lower level.
1006 	 */
1007 	for (lcv = 0, current_offset = offset;
1008 			 lcv < *npagesp ; lcv++, current_offset += PAGE_SIZE) {
1009 
1010 		/* skip over pages we've already gotten or don't want */
1011 		/* skip over pages we don't _have_ to get */
1012 		if (pps[lcv] != NULL || (lcv != centeridx &&
1013 		    (flags & PGO_ALLPAGES) == 0))
1014 			continue;
1015 
1016 		/*
1017 		 * we have yet to locate the current page (pps[lcv]).   we first
1018 		 * look for a page that is already at the current offset.   if
1019 		 * we fine a page, we check to see if it is busy or released.
1020 		 * if that is the case, then we sleep on the page until it is
1021 		 * no longer busy or released and repeat the lookup.    if the
1022 		 * page we found is neither busy nor released, then we busy it
1023 		 * (so we own it) and plug it into pps[lcv].   this breaks the
1024 		 * following while loop and indicates we are ready to move on
1025 		 * to the next page in the "lcv" loop above.
1026 		 *
1027 		 * if we exit the while loop with pps[lcv] still set to NULL,
1028 		 * then it means that we allocated a new busy/fake/clean page
1029 		 * ptmp in the object and we need to do I/O to fill in the data.
1030 		 */
1031 		while (pps[lcv] == NULL) {	/* top of "pps" while loop */
1032 			/* look for a current page */
1033 			ptmp = uvm_pagelookup(uobj, current_offset);
1034 
1035 			/* nope?   allocate one now (if we can) */
1036 			if (ptmp == NULL) {
1037 				ptmp = uvm_pagealloc(uobj, current_offset,
1038 				    NULL, 0);
1039 
1040 				/* out of RAM? */
1041 				if (ptmp == NULL) {
1042 					uvm_wait("uvn_getpage");
1043 
1044 					/* goto top of pps while loop */
1045 					continue;
1046 				}
1047 
1048 				/*
1049 				 * got new page ready for I/O.  break pps
1050 				 * while loop.  pps[lcv] is still NULL.
1051 				 */
1052 				break;
1053 			}
1054 
1055 			/* page is there, see if we need to wait on it */
1056 			if ((ptmp->pg_flags & PG_BUSY) != 0) {
1057 				atomic_setbits_int(&ptmp->pg_flags, PG_WANTED);
1058 				rwsleep_nsec(ptmp, uobj->vmobjlock, PVM,
1059 				    "uvn_get", INFSLP);
1060 				continue;	/* goto top of pps while loop */
1061 			}
1062 
1063 			/*
1064 			 * if we get here then the page has become resident
1065 			 * and unbusy between steps 1 and 2.  we busy it
1066 			 * now (so we own it) and set pps[lcv] (so that we
1067 			 * exit the while loop).
1068 			 */
1069 			atomic_setbits_int(&ptmp->pg_flags, PG_BUSY);
1070 			UVM_PAGE_OWN(ptmp, "uvn_get2");
1071 			pps[lcv] = ptmp;
1072 		}
1073 
1074 		/*
1075 		 * if we own the a valid page at the correct offset, pps[lcv]
1076 		 * will point to it.   nothing more to do except go to the
1077 		 * next page.
1078 		 */
1079 		if (pps[lcv])
1080 			continue;			/* next lcv */
1081 
1082 		/*
1083 		 * we have a "fake/busy/clean" page that we just allocated.  do
1084 		 * I/O to fill it with valid data.
1085 		 */
1086 		result = uvn_io((struct uvm_vnode *) uobj, &ptmp, 1,
1087 		    PGO_SYNCIO|PGO_NOWAIT, UIO_READ);
1088 
1089 		/*
1090 		 * I/O done.  because we used syncio the result can not be
1091 		 * PEND or AGAIN.
1092 		 */
1093 		if (result != VM_PAGER_OK) {
1094 			if (ptmp->pg_flags & PG_WANTED)
1095 				wakeup(ptmp);
1096 
1097 			atomic_clearbits_int(&ptmp->pg_flags,
1098 			    PG_WANTED|PG_BUSY);
1099 			UVM_PAGE_OWN(ptmp, NULL);
1100 			uvm_lock_pageq();
1101 			uvm_pagefree(ptmp);
1102 			uvm_unlock_pageq();
1103 			rw_exit(uobj->vmobjlock);
1104 			return result;
1105 		}
1106 
1107 		/*
1108 		 * we got the page!   clear the fake flag (indicates valid
1109 		 * data now in page) and plug into our result array.   note
1110 		 * that page is still busy.
1111 		 *
1112 		 * it is the callers job to:
1113 		 * => check if the page is released
1114 		 * => unbusy the page
1115 		 * => activate the page
1116 		 */
1117 
1118 		/* data is valid ... */
1119 		atomic_clearbits_int(&ptmp->pg_flags, PG_FAKE);
1120 		pmap_clear_modify(ptmp);		/* ... and clean */
1121 		pps[lcv] = ptmp;
1122 
1123 	}
1124 
1125 
1126 	rw_exit(uobj->vmobjlock);
1127 	return (VM_PAGER_OK);
1128 }
1129 
1130 /*
1131  * uvn_io: do I/O to a vnode
1132  *
1133  * => prefer map unlocked (not required)
1134  * => flags: PGO_SYNCIO -- use sync. I/O
1135  * => XXX: currently we use VOP_READ/VOP_WRITE which are only sync.
1136  *	[thus we never do async i/o!  see iodone comment]
1137  */
1138 
1139 int
1140 uvn_io(struct uvm_vnode *uvn, vm_page_t *pps, int npages, int flags, int rw)
1141 {
1142 	struct uvm_object *uobj = &uvn->u_obj;
1143 	struct vnode *vn;
1144 	struct uio uio;
1145 	struct iovec iov;
1146 	vaddr_t kva;
1147 	off_t file_offset;
1148 	int waitf, result, mapinflags;
1149 	size_t got, wanted;
1150 	int netunlocked = 0;
1151 	int lkflags = (flags & PGO_NOWAIT) ? LK_NOWAIT : 0;
1152 
1153 	KASSERT(rw_write_held(uobj->vmobjlock));
1154 
1155 	/* init values */
1156 	waitf = (flags & PGO_SYNCIO) ? M_WAITOK : M_NOWAIT;
1157 	vn = uvn->u_vnode;
1158 	file_offset = pps[0]->offset;
1159 
1160 	/* check for sync'ing I/O. */
1161 	while (uvn->u_flags & UVM_VNODE_IOSYNC) {
1162 		if (waitf == M_NOWAIT) {
1163 			return VM_PAGER_AGAIN;
1164 		}
1165 		uvn->u_flags |= UVM_VNODE_IOSYNCWANTED;
1166 		rwsleep_nsec(&uvn->u_flags, uobj->vmobjlock, PVM, "uvn_iosync",
1167 		    INFSLP);
1168 	}
1169 
1170 	/* check size */
1171 	if (file_offset >= uvn->u_size) {
1172 		return VM_PAGER_BAD;
1173 	}
1174 
1175 	/* first try and map the pages in (without waiting) */
1176 	mapinflags = (rw == UIO_READ) ?
1177 	    UVMPAGER_MAPIN_READ : UVMPAGER_MAPIN_WRITE;
1178 
1179 	kva = uvm_pagermapin(pps, npages, mapinflags);
1180 	if (kva == 0 && waitf == M_NOWAIT) {
1181 		return VM_PAGER_AGAIN;
1182 	}
1183 
1184 	/*
1185 	 * ok, now bump u_nio up.   at this point we are done with uvn
1186 	 * and can unlock it.   if we still don't have a kva, try again
1187 	 * (this time with sleep ok).
1188 	 */
1189 	uvn->u_nio++;			/* we have an I/O in progress! */
1190 	rw_exit(uobj->vmobjlock);
1191 	if (kva == 0)
1192 		kva = uvm_pagermapin(pps, npages,
1193 		    mapinflags | UVMPAGER_MAPIN_WAITOK);
1194 
1195 	/*
1196 	 * ok, mapped in.  our pages are PG_BUSY so they are not going to
1197 	 * get touched (so we can look at "offset" without having to lock
1198 	 * the object).  set up for I/O.
1199 	 */
1200 	/* fill out uio/iov */
1201 	iov.iov_base = (caddr_t) kva;
1202 	wanted = (size_t)npages << PAGE_SHIFT;
1203 	if (file_offset + wanted > uvn->u_size)
1204 		wanted = uvn->u_size - file_offset;	/* XXX: needed? */
1205 	iov.iov_len = wanted;
1206 	uio.uio_iov = &iov;
1207 	uio.uio_iovcnt = 1;
1208 	uio.uio_offset = file_offset;
1209 	uio.uio_segflg = UIO_SYSSPACE;
1210 	uio.uio_rw = rw;
1211 	uio.uio_resid = wanted;
1212 	uio.uio_procp = curproc;
1213 
1214 	/*
1215 	 * This process may already have the NET_LOCK(), if we
1216 	 * faulted in copyin() or copyout() in the network stack.
1217 	 */
1218 	if (rw_status(&netlock) == RW_WRITE) {
1219 		NET_UNLOCK();
1220 		netunlocked = 1;
1221 	}
1222 
1223 	/* do the I/O!  (XXX: curproc?) */
1224 	/*
1225 	 * This process may already have this vnode locked, if we faulted in
1226 	 * copyin() or copyout() on a region backed by this vnode
1227 	 * while doing I/O to the vnode.  If this is the case, don't
1228 	 * panic.. instead, return the error to the user.
1229 	 *
1230 	 * XXX this is a stopgap to prevent a panic.
1231 	 * Ideally, this kind of operation *should* work.
1232 	 */
1233 	result = 0;
1234 	KERNEL_LOCK();
1235 	if ((uvn->u_flags & UVM_VNODE_VNISLOCKED) == 0)
1236 		result = vn_lock(vn, LK_EXCLUSIVE | LK_RECURSEFAIL | lkflags);
1237 	if (result == 0) {
1238 		/* NOTE: vnode now locked! */
1239 		if (rw == UIO_READ)
1240 			result = VOP_READ(vn, &uio, 0, curproc->p_ucred);
1241 		else
1242 			result = VOP_WRITE(vn, &uio,
1243 			    (flags & PGO_PDFREECLUST) ? IO_NOCACHE : 0,
1244 			    curproc->p_ucred);
1245 
1246 		if ((uvn->u_flags & UVM_VNODE_VNISLOCKED) == 0)
1247 			VOP_UNLOCK(vn);
1248 
1249 	}
1250 	KERNEL_UNLOCK();
1251 
1252 	if (netunlocked)
1253 		NET_LOCK();
1254 
1255 
1256 	/* NOTE: vnode now unlocked (unless vnislocked) */
1257 	/*
1258 	 * result == unix style errno (0 == OK!)
1259 	 *
1260 	 * zero out rest of buffer (if needed)
1261 	 */
1262 	if (result == 0) {
1263 		got = wanted - uio.uio_resid;
1264 
1265 		if (wanted && got == 0) {
1266 			result = EIO;		/* XXX: error? */
1267 		} else if (got < PAGE_SIZE * npages && rw == UIO_READ) {
1268 			memset((void *) (kva + got), 0,
1269 			       ((size_t)npages << PAGE_SHIFT) - got);
1270 		}
1271 	}
1272 
1273 	/* now remove pager mapping */
1274 	uvm_pagermapout(kva, npages);
1275 
1276 	/* now clean up the object (i.e. drop I/O count) */
1277 	rw_enter(uobj->vmobjlock, RW_WRITE);
1278 	uvn->u_nio--;			/* I/O DONE! */
1279 	if ((uvn->u_flags & UVM_VNODE_IOSYNC) != 0 && uvn->u_nio == 0) {
1280 		wakeup(&uvn->u_nio);
1281 	}
1282 
1283 	if (result == 0) {
1284 		return VM_PAGER_OK;
1285 	} else if (result == EBUSY) {
1286 		KASSERT(flags & PGO_NOWAIT);
1287 		return VM_PAGER_AGAIN;
1288 	} else {
1289 		if (rebooting) {
1290 			KERNEL_LOCK();
1291 			while (rebooting)
1292 				tsleep_nsec(&rebooting, PVM, "uvndead", INFSLP);
1293 			KERNEL_UNLOCK();
1294 		}
1295 		return VM_PAGER_ERROR;
1296 	}
1297 }
1298 
1299 /*
1300  * uvm_vnp_uncache: disable "persisting" in a vnode... when last reference
1301  * is gone we will kill the object (flushing dirty pages back to the vnode
1302  * if needed).
1303  *
1304  * => returns TRUE if there was no uvm_object attached or if there was
1305  *	one and we killed it [i.e. if there is no active uvn]
1306  * => called with the vnode VOP_LOCK'd [we will unlock it for I/O, if
1307  *	needed]
1308  *
1309  * => XXX: given that we now kill uvn's when a vnode is recycled (without
1310  *	having to hold a reference on the vnode) and given a working
1311  *	uvm_vnp_sync(), how does that effect the need for this function?
1312  *      [XXXCDC: seems like it can die?]
1313  *
1314  * => XXX: this function should DIE once we merge the VM and buffer
1315  *	cache.
1316  *
1317  * research shows that this is called in the following places:
1318  * ext2fs_truncate, ffs_truncate, detrunc[msdosfs]: called when vnode
1319  *	changes sizes
1320  * ext2fs_write, WRITE [ufs_readwrite], msdosfs_write: called when we
1321  *	are written to
1322  * ex2fs_chmod, ufs_chmod: called if VTEXT vnode and the sticky bit
1323  *	is off
1324  * ffs_realloccg: when we can't extend the current block and have
1325  *	to allocate a new one we call this [XXX: why?]
1326  * nfsrv_rename, rename_files: called when the target filename is there
1327  *	and we want to remove it
1328  * nfsrv_remove, sys_unlink: called on file we are removing
1329  * nfsrv_access: if VTEXT and we want WRITE access and we don't uncache
1330  *	then return "text busy"
1331  * nfs_open: seems to uncache any file opened with nfs
1332  * vn_writechk: if VTEXT vnode and can't uncache return "text busy"
1333  * fusefs_open: uncaches any file that is opened
1334  * fusefs_write: uncaches on every write
1335  */
1336 
1337 int
1338 uvm_vnp_uncache(struct vnode *vp)
1339 {
1340 	struct uvm_vnode *uvn = vp->v_uvm;
1341 	struct uvm_object *uobj = &uvn->u_obj;
1342 
1343 	/* lock uvn part of the vnode and check if we need to do anything */
1344 
1345 	rw_enter(uobj->vmobjlock, RW_WRITE);
1346 	if ((uvn->u_flags & UVM_VNODE_VALID) == 0 ||
1347 			(uvn->u_flags & UVM_VNODE_BLOCKED) != 0) {
1348 		rw_exit(uobj->vmobjlock);
1349 		return TRUE;
1350 	}
1351 
1352 	/*
1353 	 * we have a valid, non-blocked uvn.   clear persist flag.
1354 	 * if uvn is currently active we can return now.
1355 	 */
1356 	uvn->u_flags &= ~UVM_VNODE_CANPERSIST;
1357 	if (uvn->u_obj.uo_refs) {
1358 		rw_exit(uobj->vmobjlock);
1359 		return FALSE;
1360 	}
1361 
1362 	/*
1363 	 * uvn is currently persisting!   we have to gain a reference to
1364 	 * it so that we can call uvn_detach to kill the uvn.
1365 	 */
1366 	vref(vp);			/* seems ok, even with VOP_LOCK */
1367 	uvn->u_obj.uo_refs++;		/* value is now 1 */
1368 	rw_exit(uobj->vmobjlock);
1369 
1370 #ifdef VFSLCKDEBUG
1371 	/*
1372 	 * carry over sanity check from old vnode pager: the vnode should
1373 	 * be VOP_LOCK'd, and we confirm it here.
1374 	 */
1375 	if ((vp->v_flag & VLOCKSWORK) && !VOP_ISLOCKED(vp))
1376 		panic("uvm_vnp_uncache: vnode not locked!");
1377 #endif
1378 
1379 	/*
1380 	 * now drop our reference to the vnode.   if we have the sole
1381 	 * reference to the vnode then this will cause it to die [as we
1382 	 * just cleared the persist flag].   we have to unlock the vnode
1383 	 * while we are doing this as it may trigger I/O.
1384 	 *
1385 	 * XXX: it might be possible for uvn to get reclaimed while we are
1386 	 * unlocked causing us to return TRUE when we should not.   we ignore
1387 	 * this as a false-positive return value doesn't hurt us.
1388 	 */
1389 	VOP_UNLOCK(vp);
1390 	uvn_detach(&uvn->u_obj);
1391 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1392 
1393 	return TRUE;
1394 }
1395 
1396 /*
1397  * uvm_vnp_setsize: grow or shrink a vnode uvn
1398  *
1399  * grow   => just update size value
1400  * shrink => toss un-needed pages
1401  *
1402  * => we assume that the caller has a reference of some sort to the
1403  *	vnode in question so that it will not be yanked out from under
1404  *	us.
1405  *
1406  * called from:
1407  *  => truncate fns (ext2fs_truncate, ffs_truncate, detrunc[msdos],
1408  *     fusefs_setattr)
1409  *  => "write" fns (ext2fs_write, WRITE [ufs/ufs], msdosfs_write, nfs_write
1410  *     fusefs_write)
1411  *  => ffs_balloc [XXX: why? doesn't WRITE handle?]
1412  *  => NFS: nfs_loadattrcache, nfs_getattrcache, nfs_setattr
1413  *  => union fs: union_newsize
1414  */
1415 
1416 void
1417 uvm_vnp_setsize(struct vnode *vp, off_t newsize)
1418 {
1419 	struct uvm_vnode *uvn = vp->v_uvm;
1420 	struct uvm_object *uobj = &uvn->u_obj;
1421 
1422 	KERNEL_ASSERT_LOCKED();
1423 
1424 	rw_enter(uobj->vmobjlock, RW_WRITE);
1425 
1426 	/* lock uvn and check for valid object, and if valid: do it! */
1427 	if (uvn->u_flags & UVM_VNODE_VALID) {
1428 
1429 		/*
1430 		 * now check if the size has changed: if we shrink we had better
1431 		 * toss some pages...
1432 		 */
1433 
1434 		if (uvn->u_size > newsize) {
1435 			(void)uvn_flush(&uvn->u_obj, newsize,
1436 			    uvn->u_size, PGO_FREE);
1437 		}
1438 		uvn->u_size = newsize;
1439 	}
1440 	rw_exit(uobj->vmobjlock);
1441 }
1442 
1443 /*
1444  * uvm_vnp_sync: flush all dirty VM pages back to their backing vnodes.
1445  *
1446  * => called from sys_sync with no VM structures locked
1447  * => only one process can do a sync at a time (because the uvn
1448  *    structure only has one queue for sync'ing).  we ensure this
1449  *    by holding the uvn_sync_lock while the sync is in progress.
1450  *    other processes attempting a sync will sleep on this lock
1451  *    until we are done.
1452  */
1453 void
1454 uvm_vnp_sync(struct mount *mp)
1455 {
1456 	struct uvm_vnode *uvn;
1457 	struct vnode *vp;
1458 
1459 	/*
1460 	 * step 1: ensure we are only ones using the uvn_sync_q by locking
1461 	 * our lock...
1462 	 */
1463 	rw_enter_write(&uvn_sync_lock);
1464 
1465 	/*
1466 	 * step 2: build up a simpleq of uvns of interest based on the
1467 	 * write list.   we gain a reference to uvns of interest.
1468 	 */
1469 	SIMPLEQ_INIT(&uvn_sync_q);
1470 	LIST_FOREACH(uvn, &uvn_wlist, u_wlist) {
1471 		vp = uvn->u_vnode;
1472 		if (mp && vp->v_mount != mp)
1473 			continue;
1474 
1475 		/*
1476 		 * If the vnode is "blocked" it means it must be dying, which
1477 		 * in turn means its in the process of being flushed out so
1478 		 * we can safely skip it.
1479 		 *
1480 		 * note that uvn must already be valid because we found it on
1481 		 * the wlist (this also means it can't be ALOCK'd).
1482 		 */
1483 		if ((uvn->u_flags & UVM_VNODE_BLOCKED) != 0)
1484 			continue;
1485 
1486 		/*
1487 		 * gain reference.   watch out for persisting uvns (need to
1488 		 * regain vnode REF).
1489 		 */
1490 		if (uvn->u_obj.uo_refs == 0)
1491 			vref(vp);
1492 		uvn->u_obj.uo_refs++;
1493 
1494 		SIMPLEQ_INSERT_HEAD(&uvn_sync_q, uvn, u_syncq);
1495 	}
1496 
1497 	/* step 3: we now have a list of uvn's that may need cleaning. */
1498 	SIMPLEQ_FOREACH(uvn, &uvn_sync_q, u_syncq) {
1499 		rw_enter(uvn->u_obj.vmobjlock, RW_WRITE);
1500 #ifdef DEBUG
1501 		if (uvn->u_flags & UVM_VNODE_DYING) {
1502 			printf("uvm_vnp_sync: dying vnode on sync list\n");
1503 		}
1504 #endif
1505 		uvn_flush(&uvn->u_obj, 0, 0, PGO_CLEANIT|PGO_ALLPAGES|PGO_DOACTCLUST);
1506 
1507 		/*
1508 		 * if we have the only reference and we just cleaned the uvn,
1509 		 * then we can pull it out of the UVM_VNODE_WRITEABLE state
1510 		 * thus allowing us to avoid thinking about flushing it again
1511 		 * on later sync ops.
1512 		 */
1513 		if (uvn->u_obj.uo_refs == 1 &&
1514 		    (uvn->u_flags & UVM_VNODE_WRITEABLE)) {
1515 			LIST_REMOVE(uvn, u_wlist);
1516 			uvn->u_flags &= ~UVM_VNODE_WRITEABLE;
1517 		}
1518 		rw_exit(uvn->u_obj.vmobjlock);
1519 
1520 		/* now drop our reference to the uvn */
1521 		uvn_detach(&uvn->u_obj);
1522 	}
1523 
1524 	rw_exit_write(&uvn_sync_lock);
1525 }
1526