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