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