xref: /dragonfly/sys/kern/vfs_subr.c (revision 235099c3)
1 /*
2  * Copyright (c) 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)vfs_subr.c	8.31 (Berkeley) 5/26/95
39  * $FreeBSD: src/sys/kern/vfs_subr.c,v 1.249.2.30 2003/04/04 20:35:57 tegge Exp $
40  * $DragonFly: src/sys/kern/vfs_subr.c,v 1.118 2008/09/17 21:44:18 dillon Exp $
41  */
42 
43 /*
44  * External virtual filesystem routines
45  */
46 #include "opt_ddb.h"
47 
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/buf.h>
51 #include <sys/conf.h>
52 #include <sys/dirent.h>
53 #include <sys/domain.h>
54 #include <sys/eventhandler.h>
55 #include <sys/fcntl.h>
56 #include <sys/file.h>
57 #include <sys/kernel.h>
58 #include <sys/kthread.h>
59 #include <sys/malloc.h>
60 #include <sys/mbuf.h>
61 #include <sys/mount.h>
62 #include <sys/proc.h>
63 #include <sys/reboot.h>
64 #include <sys/socket.h>
65 #include <sys/stat.h>
66 #include <sys/sysctl.h>
67 #include <sys/syslog.h>
68 #include <sys/unistd.h>
69 #include <sys/vmmeter.h>
70 #include <sys/vnode.h>
71 
72 #include <machine/limits.h>
73 
74 #include <vm/vm.h>
75 #include <vm/vm_object.h>
76 #include <vm/vm_extern.h>
77 #include <vm/vm_kern.h>
78 #include <vm/pmap.h>
79 #include <vm/vm_map.h>
80 #include <vm/vm_page.h>
81 #include <vm/vm_pager.h>
82 #include <vm/vnode_pager.h>
83 #include <vm/vm_zone.h>
84 
85 #include <sys/buf2.h>
86 #include <sys/thread2.h>
87 #include <sys/sysref2.h>
88 
89 static MALLOC_DEFINE(M_NETADDR, "Export Host", "Export host address structure");
90 
91 int numvnodes;
92 SYSCTL_INT(_debug, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0, "");
93 int vfs_fastdev = 1;
94 SYSCTL_INT(_vfs, OID_AUTO, fastdev, CTLFLAG_RW, &vfs_fastdev, 0, "");
95 
96 enum vtype iftovt_tab[16] = {
97 	VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
98 	VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
99 };
100 int vttoif_tab[9] = {
101 	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
102 	S_IFSOCK, S_IFIFO, S_IFMT,
103 };
104 
105 static int reassignbufcalls;
106 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW,
107 		&reassignbufcalls, 0, "");
108 static int reassignbufloops;
109 SYSCTL_INT(_vfs, OID_AUTO, reassignbufloops, CTLFLAG_RW,
110 		&reassignbufloops, 0, "");
111 static int reassignbufsortgood;
112 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortgood, CTLFLAG_RW,
113 		&reassignbufsortgood, 0, "");
114 static int reassignbufsortbad;
115 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortbad, CTLFLAG_RW,
116 		&reassignbufsortbad, 0, "");
117 static int reassignbufmethod = 1;
118 SYSCTL_INT(_vfs, OID_AUTO, reassignbufmethod, CTLFLAG_RW,
119 		&reassignbufmethod, 0, "");
120 
121 int	nfs_mount_type = -1;
122 static struct lwkt_token spechash_token;
123 struct nfs_public nfs_pub;	/* publicly exported FS */
124 
125 int desiredvnodes;
126 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
127 		&desiredvnodes, 0, "Maximum number of vnodes");
128 
129 static void	vfs_free_addrlist (struct netexport *nep);
130 static int	vfs_free_netcred (struct radix_node *rn, void *w);
131 static int	vfs_hang_addrlist (struct mount *mp, struct netexport *nep,
132 				       const struct export_args *argp);
133 
134 /*
135  * Red black tree functions
136  */
137 static int rb_buf_compare(struct buf *b1, struct buf *b2);
138 RB_GENERATE2(buf_rb_tree, buf, b_rbnode, rb_buf_compare, off_t, b_loffset);
139 RB_GENERATE2(buf_rb_hash, buf, b_rbhash, rb_buf_compare, off_t, b_loffset);
140 
141 static int
142 rb_buf_compare(struct buf *b1, struct buf *b2)
143 {
144 	if (b1->b_loffset < b2->b_loffset)
145 		return(-1);
146 	if (b1->b_loffset > b2->b_loffset)
147 		return(1);
148 	return(0);
149 }
150 
151 /*
152  * Returns non-zero if the vnode is a candidate for lazy msyncing.
153  */
154 static __inline int
155 vshouldmsync(struct vnode *vp)
156 {
157 	if (vp->v_auxrefs != 0 || vp->v_sysref.refcnt > 0)
158 		return (0);		/* other holders */
159 	if (vp->v_object &&
160 	    (vp->v_object->ref_count || vp->v_object->resident_page_count)) {
161 		return (0);
162 	}
163 	return (1);
164 }
165 
166 /*
167  * Initialize the vnode management data structures.
168  *
169  * Called from vfsinit()
170  */
171 void
172 vfs_subr_init(void)
173 {
174 	/*
175 	 * Desiredvnodes is kern.maxvnodes.  We want to scale it
176 	 * according to available system memory but we may also have
177 	 * to limit it based on available KVM, which is capped on 32 bit
178 	 * systems.
179 	 */
180 	desiredvnodes = min(maxproc + vmstats.v_page_count / 4,
181 			    KvaSize / (20 *
182 			    (sizeof(struct vm_object) + sizeof(struct vnode))));
183 
184 	lwkt_token_init(&spechash_token);
185 }
186 
187 /*
188  * Knob to control the precision of file timestamps:
189  *
190  *   0 = seconds only; nanoseconds zeroed.
191  *   1 = seconds and nanoseconds, accurate within 1/HZ.
192  *   2 = seconds and nanoseconds, truncated to microseconds.
193  * >=3 = seconds and nanoseconds, maximum precision.
194  */
195 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
196 
197 static int timestamp_precision = TSP_SEC;
198 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
199 		&timestamp_precision, 0, "");
200 
201 /*
202  * Get a current timestamp.
203  *
204  * MPSAFE
205  */
206 void
207 vfs_timestamp(struct timespec *tsp)
208 {
209 	struct timeval tv;
210 
211 	switch (timestamp_precision) {
212 	case TSP_SEC:
213 		tsp->tv_sec = time_second;
214 		tsp->tv_nsec = 0;
215 		break;
216 	case TSP_HZ:
217 		getnanotime(tsp);
218 		break;
219 	case TSP_USEC:
220 		microtime(&tv);
221 		TIMEVAL_TO_TIMESPEC(&tv, tsp);
222 		break;
223 	case TSP_NSEC:
224 	default:
225 		nanotime(tsp);
226 		break;
227 	}
228 }
229 
230 /*
231  * Set vnode attributes to VNOVAL
232  */
233 void
234 vattr_null(struct vattr *vap)
235 {
236 	vap->va_type = VNON;
237 	vap->va_size = VNOVAL;
238 	vap->va_bytes = VNOVAL;
239 	vap->va_mode = VNOVAL;
240 	vap->va_nlink = VNOVAL;
241 	vap->va_uid = VNOVAL;
242 	vap->va_gid = VNOVAL;
243 	vap->va_fsid = VNOVAL;
244 	vap->va_fileid = VNOVAL;
245 	vap->va_blocksize = VNOVAL;
246 	vap->va_rmajor = VNOVAL;
247 	vap->va_rminor = VNOVAL;
248 	vap->va_atime.tv_sec = VNOVAL;
249 	vap->va_atime.tv_nsec = VNOVAL;
250 	vap->va_mtime.tv_sec = VNOVAL;
251 	vap->va_mtime.tv_nsec = VNOVAL;
252 	vap->va_ctime.tv_sec = VNOVAL;
253 	vap->va_ctime.tv_nsec = VNOVAL;
254 	vap->va_flags = VNOVAL;
255 	vap->va_gen = VNOVAL;
256 	vap->va_vaflags = 0;
257 	vap->va_fsmid = VNOVAL;
258 	/* va_*_uuid fields are only valid if related flags are set */
259 }
260 
261 /*
262  * Flush out and invalidate all buffers associated with a vnode.
263  *
264  * vp must be locked.
265  */
266 static int vinvalbuf_bp(struct buf *bp, void *data);
267 
268 struct vinvalbuf_bp_info {
269 	struct vnode *vp;
270 	int slptimeo;
271 	int lkflags;
272 	int flags;
273 };
274 
275 void
276 vupdatefsmid(struct vnode *vp)
277 {
278 	atomic_set_int(&vp->v_flag, VFSMID);
279 }
280 
281 int
282 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
283 {
284 	struct vinvalbuf_bp_info info;
285 	vm_object_t object;
286 	lwkt_tokref vlock;
287 	int error;
288 
289 	lwkt_gettoken(&vlock, &vp->v_token);
290 
291 	/*
292 	 * If we are being asked to save, call fsync to ensure that the inode
293 	 * is updated.
294 	 */
295 	if (flags & V_SAVE) {
296 		error = bio_track_wait(&vp->v_track_write, slpflag, slptimeo);
297 		if (error)
298 			goto done;
299 		if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
300 			if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)) != 0)
301 				goto done;
302 
303 			/*
304 			 * Dirty bufs may be left or generated via races
305 			 * in circumstances where vinvalbuf() is called on
306 			 * a vnode not undergoing reclamation.   Only
307 			 * panic if we are trying to reclaim the vnode.
308 			 */
309 			if ((vp->v_flag & VRECLAIMED) &&
310 			    (bio_track_active(&vp->v_track_write) ||
311 			    !RB_EMPTY(&vp->v_rbdirty_tree))) {
312 				panic("vinvalbuf: dirty bufs");
313 			}
314 		}
315   	}
316 	info.slptimeo = slptimeo;
317 	info.lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
318 	if (slpflag & PCATCH)
319 		info.lkflags |= LK_PCATCH;
320 	info.flags = flags;
321 	info.vp = vp;
322 
323 	/*
324 	 * Flush the buffer cache until nothing is left.
325 	 */
326 	while (!RB_EMPTY(&vp->v_rbclean_tree) ||
327 	       !RB_EMPTY(&vp->v_rbdirty_tree)) {
328 		error = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree, NULL,
329 				vinvalbuf_bp, &info);
330 		if (error == 0) {
331 			error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
332 					vinvalbuf_bp, &info);
333 		}
334 	}
335 
336 	/*
337 	 * Wait for I/O completion.  We may block in the pip code so we have
338 	 * to re-check.
339 	 */
340 	do {
341 		bio_track_wait(&vp->v_track_write, 0, 0);
342 		if ((object = vp->v_object) != NULL) {
343 			while (object->paging_in_progress)
344 				vm_object_pip_sleep(object, "vnvlbx");
345 		}
346 	} while (bio_track_active(&vp->v_track_write));
347 
348 	/*
349 	 * Destroy the copy in the VM cache, too.
350 	 */
351 	if ((object = vp->v_object) != NULL) {
352 		vm_object_page_remove(object, 0, 0,
353 			(flags & V_SAVE) ? TRUE : FALSE);
354 	}
355 
356 	if (!RB_EMPTY(&vp->v_rbdirty_tree) || !RB_EMPTY(&vp->v_rbclean_tree))
357 		panic("vinvalbuf: flush failed");
358 	if (!RB_EMPTY(&vp->v_rbhash_tree))
359 		panic("vinvalbuf: flush failed, buffers still present");
360 	error = 0;
361 done:
362 	lwkt_reltoken(&vlock);
363 	return (error);
364 }
365 
366 static int
367 vinvalbuf_bp(struct buf *bp, void *data)
368 {
369 	struct vinvalbuf_bp_info *info = data;
370 	int error;
371 
372 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
373 		error = BUF_TIMELOCK(bp, info->lkflags,
374 				     "vinvalbuf", info->slptimeo);
375 		if (error == 0) {
376 			BUF_UNLOCK(bp);
377 			error = ENOLCK;
378 		}
379 		if (error == ENOLCK)
380 			return(0);
381 		return (-error);
382 	}
383 
384 	KKASSERT(bp->b_vp == info->vp);
385 
386 	/*
387 	 * XXX Since there are no node locks for NFS, I
388 	 * believe there is a slight chance that a delayed
389 	 * write will occur while sleeping just above, so
390 	 * check for it.  Note that vfs_bio_awrite expects
391 	 * buffers to reside on a queue, while bwrite() and
392 	 * brelse() do not.
393 	 *
394 	 * NOTE:  NO B_LOCKED CHECK.  Also no buf_checkwrite()
395 	 * check.  This code will write out the buffer, period.
396 	 */
397 	if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
398 	    (info->flags & V_SAVE)) {
399 		if (bp->b_vp == info->vp) {
400 			if (bp->b_flags & B_CLUSTEROK) {
401 				vfs_bio_awrite(bp);
402 			} else {
403 				bremfree(bp);
404 				bawrite(bp);
405 			}
406 		} else {
407 			bremfree(bp);
408 			bwrite(bp);
409 		}
410 	} else if (info->flags & V_SAVE) {
411 		/*
412 		 * Cannot set B_NOCACHE on a clean buffer as this will
413 		 * destroy the VM backing store which might actually
414 		 * be dirty (and unsynchronized).
415 		 */
416 		bremfree(bp);
417 		bp->b_flags |= (B_INVAL | B_RELBUF);
418 		brelse(bp);
419 	} else {
420 		bremfree(bp);
421 		bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
422 		brelse(bp);
423 	}
424 	return(0);
425 }
426 
427 /*
428  * Truncate a file's buffer and pages to a specified length.  This
429  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
430  * sync activity.
431  *
432  * The vnode must be locked.
433  */
434 static int vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data);
435 static int vtruncbuf_bp_trunc(struct buf *bp, void *data);
436 static int vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data);
437 static int vtruncbuf_bp_metasync(struct buf *bp, void *data);
438 
439 int
440 vtruncbuf(struct vnode *vp, off_t length, int blksize)
441 {
442 	off_t truncloffset;
443 	const char *filename;
444 	lwkt_tokref vlock;
445 	int count;
446 
447 	/*
448 	 * Round up to the *next* block, then destroy the buffers in question.
449 	 * Since we are only removing some of the buffers we must rely on the
450 	 * scan count to determine whether a loop is necessary.
451 	 */
452 	if ((count = (int)(length % blksize)) != 0)
453 		truncloffset = length + (blksize - count);
454 	else
455 		truncloffset = length;
456 
457 	lwkt_gettoken(&vlock, &vp->v_token);
458 	do {
459 		count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
460 				vtruncbuf_bp_trunc_cmp,
461 				vtruncbuf_bp_trunc, &truncloffset);
462 		count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
463 				vtruncbuf_bp_trunc_cmp,
464 				vtruncbuf_bp_trunc, &truncloffset);
465 	} while(count);
466 
467 	/*
468 	 * For safety, fsync any remaining metadata if the file is not being
469 	 * truncated to 0.  Since the metadata does not represent the entire
470 	 * dirty list we have to rely on the hit count to ensure that we get
471 	 * all of it.
472 	 */
473 	if (length > 0) {
474 		do {
475 			count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
476 					vtruncbuf_bp_metasync_cmp,
477 					vtruncbuf_bp_metasync, vp);
478 		} while (count);
479 	}
480 
481 	/*
482 	 * Clean out any left over VM backing store.
483 	 *
484 	 * It is possible to have in-progress I/O from buffers that were
485 	 * not part of the truncation.  This should not happen if we
486 	 * are truncating to 0-length.
487 	 */
488 	vnode_pager_setsize(vp, length);
489 	bio_track_wait(&vp->v_track_write, 0, 0);
490 
491 	filename = TAILQ_FIRST(&vp->v_namecache) ?
492 		   TAILQ_FIRST(&vp->v_namecache)->nc_name : "?";
493 
494 	/*
495 	 * Make sure no buffers were instantiated while we were trying
496 	 * to clean out the remaining VM pages.  This could occur due
497 	 * to busy dirty VM pages being flushed out to disk.
498 	 */
499 	do {
500 		count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
501 				vtruncbuf_bp_trunc_cmp,
502 				vtruncbuf_bp_trunc, &truncloffset);
503 		count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
504 				vtruncbuf_bp_trunc_cmp,
505 				vtruncbuf_bp_trunc, &truncloffset);
506 		if (count) {
507 			kprintf("Warning: vtruncbuf():  Had to re-clean %d "
508 			       "left over buffers in %s\n", count, filename);
509 		}
510 	} while(count);
511 
512 	lwkt_reltoken(&vlock);
513 
514 	return (0);
515 }
516 
517 /*
518  * The callback buffer is beyond the new file EOF and must be destroyed.
519  * Note that the compare function must conform to the RB_SCAN's requirements.
520  */
521 static
522 int
523 vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data)
524 {
525 	if (bp->b_loffset >= *(off_t *)data)
526 		return(0);
527 	return(-1);
528 }
529 
530 static
531 int
532 vtruncbuf_bp_trunc(struct buf *bp, void *data)
533 {
534 	/*
535 	 * Do not try to use a buffer we cannot immediately lock, but sleep
536 	 * anyway to prevent a livelock.  The code will loop until all buffers
537 	 * can be acted upon.
538 	 */
539 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
540 		if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
541 			BUF_UNLOCK(bp);
542 	} else {
543 		bremfree(bp);
544 		bp->b_flags |= (B_INVAL | B_RELBUF | B_NOCACHE);
545 		brelse(bp);
546 	}
547 	return(1);
548 }
549 
550 /*
551  * Fsync all meta-data after truncating a file to be non-zero.  Only metadata
552  * blocks (with a negative loffset) are scanned.
553  * Note that the compare function must conform to the RB_SCAN's requirements.
554  */
555 static int
556 vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data)
557 {
558 	if (bp->b_loffset < 0)
559 		return(0);
560 	return(1);
561 }
562 
563 static int
564 vtruncbuf_bp_metasync(struct buf *bp, void *data)
565 {
566 	struct vnode *vp = data;
567 
568 	if (bp->b_flags & B_DELWRI) {
569 		/*
570 		 * Do not try to use a buffer we cannot immediately lock,
571 		 * but sleep anyway to prevent a livelock.  The code will
572 		 * loop until all buffers can be acted upon.
573 		 */
574 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
575 			if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
576 				BUF_UNLOCK(bp);
577 		} else {
578 			bremfree(bp);
579 			if (bp->b_vp == vp)
580 				bawrite(bp);
581 			else
582 				bwrite(bp);
583 		}
584 		return(1);
585 	} else {
586 		return(0);
587 	}
588 }
589 
590 /*
591  * vfsync - implements a multipass fsync on a file which understands
592  * dependancies and meta-data.  The passed vnode must be locked.  The
593  * waitfor argument may be MNT_WAIT or MNT_NOWAIT, or MNT_LAZY.
594  *
595  * When fsyncing data asynchronously just do one consolidated pass starting
596  * with the most negative block number.  This may not get all the data due
597  * to dependancies.
598  *
599  * When fsyncing data synchronously do a data pass, then a metadata pass,
600  * then do additional data+metadata passes to try to get all the data out.
601  */
602 static int vfsync_wait_output(struct vnode *vp,
603 			    int (*waitoutput)(struct vnode *, struct thread *));
604 static int vfsync_data_only_cmp(struct buf *bp, void *data);
605 static int vfsync_meta_only_cmp(struct buf *bp, void *data);
606 static int vfsync_lazy_range_cmp(struct buf *bp, void *data);
607 static int vfsync_bp(struct buf *bp, void *data);
608 
609 struct vfsync_info {
610 	struct vnode *vp;
611 	int synchronous;
612 	int syncdeps;
613 	int lazycount;
614 	int lazylimit;
615 	int skippedbufs;
616 	int (*checkdef)(struct buf *);
617 };
618 
619 int
620 vfsync(struct vnode *vp, int waitfor, int passes,
621 	int (*checkdef)(struct buf *),
622 	int (*waitoutput)(struct vnode *, struct thread *))
623 {
624 	struct vfsync_info info;
625 	lwkt_tokref vlock;
626 	int error;
627 
628 	bzero(&info, sizeof(info));
629 	info.vp = vp;
630 	if ((info.checkdef = checkdef) == NULL)
631 		info.syncdeps = 1;
632 
633 	lwkt_gettoken(&vlock, &vp->v_token);
634 
635 	switch(waitfor) {
636 	case MNT_LAZY:
637 		/*
638 		 * Lazy (filesystem syncer typ) Asynchronous plus limit the
639 		 * number of data (not meta) pages we try to flush to 1MB.
640 		 * A non-zero return means that lazy limit was reached.
641 		 */
642 		info.lazylimit = 1024 * 1024;
643 		info.syncdeps = 1;
644 		error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
645 				vfsync_lazy_range_cmp, vfsync_bp, &info);
646 		RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
647 				vfsync_meta_only_cmp, vfsync_bp, &info);
648 		if (error == 0)
649 			vp->v_lazyw = 0;
650 		else if (!RB_EMPTY(&vp->v_rbdirty_tree))
651 			vn_syncer_add_to_worklist(vp, 1);
652 		error = 0;
653 		break;
654 	case MNT_NOWAIT:
655 		/*
656 		 * Asynchronous.  Do a data-only pass and a meta-only pass.
657 		 */
658 		info.syncdeps = 1;
659 		RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
660 			vfsync_bp, &info);
661 		RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_meta_only_cmp,
662 			vfsync_bp, &info);
663 		error = 0;
664 		break;
665 	default:
666 		/*
667 		 * Synchronous.  Do a data-only pass, then a meta-data+data
668 		 * pass, then additional integrated passes to try to get
669 		 * all the dependancies flushed.
670 		 */
671 		RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
672 			vfsync_bp, &info);
673 		error = vfsync_wait_output(vp, waitoutput);
674 		if (error == 0) {
675 			info.skippedbufs = 0;
676 			RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
677 				vfsync_bp, &info);
678 			error = vfsync_wait_output(vp, waitoutput);
679 			if (info.skippedbufs)
680 				kprintf("Warning: vfsync skipped %d dirty bufs in pass2!\n", info.skippedbufs);
681 		}
682 		while (error == 0 && passes > 0 &&
683 		       !RB_EMPTY(&vp->v_rbdirty_tree)
684 		) {
685 			if (--passes == 0) {
686 				info.synchronous = 1;
687 				info.syncdeps = 1;
688 			}
689 			error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
690 				vfsync_bp, &info);
691 			if (error < 0)
692 				error = -error;
693 			info.syncdeps = 1;
694 			if (error == 0)
695 				error = vfsync_wait_output(vp, waitoutput);
696 		}
697 		break;
698 	}
699 	lwkt_reltoken(&vlock);
700 	return(error);
701 }
702 
703 static int
704 vfsync_wait_output(struct vnode *vp,
705 		   int (*waitoutput)(struct vnode *, struct thread *))
706 {
707 	int error;
708 
709 	error = bio_track_wait(&vp->v_track_write, 0, 0);
710 	if (waitoutput)
711 		error = waitoutput(vp, curthread);
712 	return(error);
713 }
714 
715 static int
716 vfsync_data_only_cmp(struct buf *bp, void *data)
717 {
718 	if (bp->b_loffset < 0)
719 		return(-1);
720 	return(0);
721 }
722 
723 static int
724 vfsync_meta_only_cmp(struct buf *bp, void *data)
725 {
726 	if (bp->b_loffset < 0)
727 		return(0);
728 	return(1);
729 }
730 
731 static int
732 vfsync_lazy_range_cmp(struct buf *bp, void *data)
733 {
734 	struct vfsync_info *info = data;
735 	if (bp->b_loffset < info->vp->v_lazyw)
736 		return(-1);
737 	return(0);
738 }
739 
740 static int
741 vfsync_bp(struct buf *bp, void *data)
742 {
743 	struct vfsync_info *info = data;
744 	struct vnode *vp = info->vp;
745 	int error;
746 
747 	/*
748 	 * if syncdeps is not set we do not try to write buffers which have
749 	 * dependancies.
750 	 */
751 	if (!info->synchronous && info->syncdeps == 0 && info->checkdef(bp))
752 		return(0);
753 
754 	/*
755 	 * Ignore buffers that we cannot immediately lock.  XXX
756 	 */
757 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
758 		kprintf("Warning: vfsync_bp skipping dirty buffer %p\n", bp);
759 		++info->skippedbufs;
760 		return(0);
761 	}
762 	if ((bp->b_flags & B_DELWRI) == 0)
763 		panic("vfsync_bp: buffer not dirty");
764 	if (vp != bp->b_vp)
765 		panic("vfsync_bp: buffer vp mismatch");
766 
767 	/*
768 	 * B_NEEDCOMMIT (primarily used by NFS) is a state where the buffer
769 	 * has been written but an additional handshake with the device
770 	 * is required before we can dispose of the buffer.  We have no idea
771 	 * how to do this so we have to skip these buffers.
772 	 */
773 	if (bp->b_flags & B_NEEDCOMMIT) {
774 		BUF_UNLOCK(bp);
775 		return(0);
776 	}
777 
778 	/*
779 	 * Ask bioops if it is ok to sync
780 	 */
781 	if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
782 		bremfree(bp);
783 		brelse(bp);
784 		return(0);
785 	}
786 
787 	if (info->synchronous) {
788 		/*
789 		 * Synchronous flushing.  An error may be returned.
790 		 */
791 		bremfree(bp);
792 		error = bwrite(bp);
793 	} else {
794 		/*
795 		 * Asynchronous flushing.  A negative return value simply
796 		 * stops the scan and is not considered an error.  We use
797 		 * this to support limited MNT_LAZY flushes.
798 		 */
799 		vp->v_lazyw = bp->b_loffset;
800 		if ((vp->v_flag & VOBJBUF) && (bp->b_flags & B_CLUSTEROK)) {
801 			info->lazycount += vfs_bio_awrite(bp);
802 		} else {
803 			info->lazycount += bp->b_bufsize;
804 			bremfree(bp);
805 			bawrite(bp);
806 		}
807 		if (info->lazylimit && info->lazycount >= info->lazylimit)
808 			error = 1;
809 		else
810 			error = 0;
811 	}
812 	return(-error);
813 }
814 
815 /*
816  * Associate a buffer with a vnode.
817  *
818  * MPSAFE
819  */
820 int
821 bgetvp(struct vnode *vp, struct buf *bp)
822 {
823 	lwkt_tokref vlock;
824 
825 	KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
826 	KKASSERT((bp->b_flags & (B_HASHED|B_DELWRI|B_VNCLEAN|B_VNDIRTY)) == 0);
827 
828 	/*
829 	 * Insert onto list for new vnode.
830 	 */
831 	lwkt_gettoken(&vlock, &vp->v_token);
832 	if (buf_rb_hash_RB_INSERT(&vp->v_rbhash_tree, bp)) {
833 		lwkt_reltoken(&vlock);
834 		return (EEXIST);
835 	}
836 	bp->b_vp = vp;
837 	bp->b_flags |= B_HASHED;
838 	bp->b_flags |= B_VNCLEAN;
839 	if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp))
840 		panic("reassignbuf: dup lblk/clean vp %p bp %p", vp, bp);
841 	vhold(vp);
842 	lwkt_reltoken(&vlock);
843 	return(0);
844 }
845 
846 /*
847  * Disassociate a buffer from a vnode.
848  */
849 void
850 brelvp(struct buf *bp)
851 {
852 	struct vnode *vp;
853 	lwkt_tokref vlock;
854 
855 	KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
856 
857 	/*
858 	 * Delete from old vnode list, if on one.
859 	 */
860 	vp = bp->b_vp;
861 	lwkt_gettoken(&vlock, &vp->v_token);
862 	if (bp->b_flags & (B_VNDIRTY | B_VNCLEAN)) {
863 		if (bp->b_flags & B_VNDIRTY)
864 			buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
865 		else
866 			buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
867 		bp->b_flags &= ~(B_VNDIRTY | B_VNCLEAN);
868 	}
869 	if (bp->b_flags & B_HASHED) {
870 		buf_rb_hash_RB_REMOVE(&vp->v_rbhash_tree, bp);
871 		bp->b_flags &= ~B_HASHED;
872 	}
873 	if ((vp->v_flag & VONWORKLST) && RB_EMPTY(&vp->v_rbdirty_tree)) {
874 		vp->v_flag &= ~VONWORKLST;
875 		LIST_REMOVE(vp, v_synclist);
876 	}
877 	bp->b_vp = NULL;
878 	lwkt_reltoken(&vlock);
879 
880 	vdrop(vp);
881 }
882 
883 /*
884  * Reassign the buffer to the proper clean/dirty list based on B_DELWRI.
885  * This routine is called when the state of the B_DELWRI bit is changed.
886  *
887  * MPSAFE
888  */
889 void
890 reassignbuf(struct buf *bp)
891 {
892 	struct vnode *vp = bp->b_vp;
893 	lwkt_tokref vlock;
894 	int delay;
895 
896 	KKASSERT(vp != NULL);
897 	++reassignbufcalls;
898 
899 	/*
900 	 * B_PAGING flagged buffers cannot be reassigned because their vp
901 	 * is not fully linked in.
902 	 */
903 	if (bp->b_flags & B_PAGING)
904 		panic("cannot reassign paging buffer");
905 
906 	lwkt_gettoken(&vlock, &vp->v_token);
907 	if (bp->b_flags & B_DELWRI) {
908 		/*
909 		 * Move to the dirty list, add the vnode to the worklist
910 		 */
911 		if (bp->b_flags & B_VNCLEAN) {
912 			buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
913 			bp->b_flags &= ~B_VNCLEAN;
914 		}
915 		if ((bp->b_flags & B_VNDIRTY) == 0) {
916 			if (buf_rb_tree_RB_INSERT(&vp->v_rbdirty_tree, bp)) {
917 				panic("reassignbuf: dup lblk vp %p bp %p",
918 				      vp, bp);
919 			}
920 			bp->b_flags |= B_VNDIRTY;
921 		}
922 		if ((vp->v_flag & VONWORKLST) == 0) {
923 			switch (vp->v_type) {
924 			case VDIR:
925 				delay = dirdelay;
926 				break;
927 			case VCHR:
928 			case VBLK:
929 				if (vp->v_rdev &&
930 				    vp->v_rdev->si_mountpoint != NULL) {
931 					delay = metadelay;
932 					break;
933 				}
934 				/* fall through */
935 			default:
936 				delay = filedelay;
937 			}
938 			vn_syncer_add_to_worklist(vp, delay);
939 		}
940 	} else {
941 		/*
942 		 * Move to the clean list, remove the vnode from the worklist
943 		 * if no dirty blocks remain.
944 		 */
945 		if (bp->b_flags & B_VNDIRTY) {
946 			buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
947 			bp->b_flags &= ~B_VNDIRTY;
948 		}
949 		if ((bp->b_flags & B_VNCLEAN) == 0) {
950 			if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp)) {
951 				panic("reassignbuf: dup lblk vp %p bp %p",
952 				      vp, bp);
953 			}
954 			bp->b_flags |= B_VNCLEAN;
955 		}
956 		if ((vp->v_flag & VONWORKLST) &&
957 		    RB_EMPTY(&vp->v_rbdirty_tree)) {
958 			vp->v_flag &= ~VONWORKLST;
959 			LIST_REMOVE(vp, v_synclist);
960 		}
961 	}
962 	lwkt_reltoken(&vlock);
963 }
964 
965 /*
966  * Create a vnode for a block device.
967  * Used for mounting the root file system.
968  */
969 extern struct vop_ops *devfs_vnode_dev_vops_p;
970 int
971 bdevvp(cdev_t dev, struct vnode **vpp)
972 {
973 	struct vnode *vp;
974 	struct vnode *nvp;
975 	int error;
976 
977 	if (dev == NULL) {
978 		*vpp = NULLVP;
979 		return (ENXIO);
980 	}
981 	error = getspecialvnode(VT_NON, NULL, &devfs_vnode_dev_vops_p,
982 				&nvp, 0, 0);
983 	if (error) {
984 		*vpp = NULLVP;
985 		return (error);
986 	}
987 	vp = nvp;
988 	vp->v_type = VCHR;
989 #if 0
990 	vp->v_rdev = dev;
991 #endif
992 	v_associate_rdev(vp, dev);
993 	vp->v_umajor = dev->si_umajor;
994 	vp->v_uminor = dev->si_uminor;
995 	vx_unlock(vp);
996 	*vpp = vp;
997 	return (0);
998 }
999 
1000 int
1001 v_associate_rdev(struct vnode *vp, cdev_t dev)
1002 {
1003 	lwkt_tokref ilock;
1004 
1005 	if (dev == NULL)
1006 		return(ENXIO);
1007 	if (dev_is_good(dev) == 0)
1008 		return(ENXIO);
1009 	KKASSERT(vp->v_rdev == NULL);
1010 	vp->v_rdev = reference_dev(dev);
1011 	lwkt_gettoken(&ilock, &spechash_token);
1012 	SLIST_INSERT_HEAD(&dev->si_hlist, vp, v_cdevnext);
1013 	lwkt_reltoken(&ilock);
1014 	return(0);
1015 }
1016 
1017 void
1018 v_release_rdev(struct vnode *vp)
1019 {
1020 	lwkt_tokref ilock;
1021 	cdev_t dev;
1022 
1023 	if ((dev = vp->v_rdev) != NULL) {
1024 		lwkt_gettoken(&ilock, &spechash_token);
1025 		SLIST_REMOVE(&dev->si_hlist, vp, vnode, v_cdevnext);
1026 		vp->v_rdev = NULL;
1027 		release_dev(dev);
1028 		lwkt_reltoken(&ilock);
1029 	}
1030 }
1031 
1032 /*
1033  * Add a vnode to the alias list hung off the cdev_t.  We only associate
1034  * the device number with the vnode.  The actual device is not associated
1035  * until the vnode is opened (usually in spec_open()), and will be
1036  * disassociated on last close.
1037  */
1038 void
1039 addaliasu(struct vnode *nvp, int x, int y)
1040 {
1041 	if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1042 		panic("addaliasu on non-special vnode");
1043 	nvp->v_umajor = x;
1044 	nvp->v_uminor = y;
1045 }
1046 
1047 /*
1048  * Simple call that a filesystem can make to try to get rid of a
1049  * vnode.  It will fail if anyone is referencing the vnode (including
1050  * the caller).
1051  *
1052  * The filesystem can check whether its in-memory inode structure still
1053  * references the vp on return.
1054  */
1055 void
1056 vclean_unlocked(struct vnode *vp)
1057 {
1058 	vx_get(vp);
1059 	if (sysref_isactive(&vp->v_sysref) == 0)
1060 		vgone_vxlocked(vp);
1061 	vx_put(vp);
1062 }
1063 
1064 /*
1065  * Disassociate a vnode from its underlying filesystem.
1066  *
1067  * The vnode must be VX locked and referenced.  In all normal situations
1068  * there are no active references.  If vclean_vxlocked() is called while
1069  * there are active references, the vnode is being ripped out and we have
1070  * to call VOP_CLOSE() as appropriate before we can reclaim it.
1071  */
1072 void
1073 vclean_vxlocked(struct vnode *vp, int flags)
1074 {
1075 	int active;
1076 	int n;
1077 	vm_object_t object;
1078 
1079 	/*
1080 	 * If the vnode has already been reclaimed we have nothing to do.
1081 	 */
1082 	if (vp->v_flag & VRECLAIMED)
1083 		return;
1084 	vp->v_flag |= VRECLAIMED;
1085 
1086 	/*
1087 	 * Scrap the vfs cache
1088 	 */
1089 	while (cache_inval_vp(vp, 0) != 0) {
1090 		kprintf("Warning: vnode %p clean/cache_resolution race detected\n", vp);
1091 		tsleep(vp, 0, "vclninv", 2);
1092 	}
1093 
1094 	/*
1095 	 * Check to see if the vnode is in use. If so we have to reference it
1096 	 * before we clean it out so that its count cannot fall to zero and
1097 	 * generate a race against ourselves to recycle it.
1098 	 */
1099 	active = sysref_isactive(&vp->v_sysref);
1100 
1101 	/*
1102 	 * Clean out any buffers associated with the vnode and destroy its
1103 	 * object, if it has one.
1104 	 */
1105 	vinvalbuf(vp, V_SAVE, 0, 0);
1106 
1107 	/*
1108 	 * If purging an active vnode (typically during a forced unmount
1109 	 * or reboot), it must be closed and deactivated before being
1110 	 * reclaimed.  This isn't really all that safe, but what can
1111 	 * we do? XXX.
1112 	 *
1113 	 * Note that neither of these routines unlocks the vnode.
1114 	 */
1115 	if (active && (flags & DOCLOSE)) {
1116 		while ((n = vp->v_opencount) != 0) {
1117 			if (vp->v_writecount)
1118 				VOP_CLOSE(vp, FWRITE|FNONBLOCK);
1119 			else
1120 				VOP_CLOSE(vp, FNONBLOCK);
1121 			if (vp->v_opencount == n) {
1122 				kprintf("Warning: unable to force-close"
1123 				       " vnode %p\n", vp);
1124 				break;
1125 			}
1126 		}
1127 	}
1128 
1129 	/*
1130 	 * If the vnode has not been deactivated, deactivated it.  Deactivation
1131 	 * can create new buffers and VM pages so we have to call vinvalbuf()
1132 	 * again to make sure they all get flushed.
1133 	 *
1134 	 * This can occur if a file with a link count of 0 needs to be
1135 	 * truncated.
1136 	 */
1137 	if ((vp->v_flag & VINACTIVE) == 0) {
1138 		vp->v_flag |= VINACTIVE;
1139 		VOP_INACTIVE(vp);
1140 		vinvalbuf(vp, V_SAVE, 0, 0);
1141 	}
1142 
1143 	/*
1144 	 * If the vnode has an object, destroy it.
1145 	 */
1146 	if ((object = vp->v_object) != NULL) {
1147 		if (object->ref_count == 0) {
1148 			if ((object->flags & OBJ_DEAD) == 0)
1149 				vm_object_terminate(object);
1150 		} else {
1151 			vm_pager_deallocate(object);
1152 		}
1153 		vp->v_flag &= ~VOBJBUF;
1154 	}
1155 	KKASSERT((vp->v_flag & VOBJBUF) == 0);
1156 
1157 	/*
1158 	 * Reclaim the vnode.
1159 	 */
1160 	if (VOP_RECLAIM(vp))
1161 		panic("vclean: cannot reclaim");
1162 
1163 	/*
1164 	 * Done with purge, notify sleepers of the grim news.
1165 	 */
1166 	vp->v_ops = &dead_vnode_vops_p;
1167 	vn_pollgone(vp);
1168 	vp->v_tag = VT_NON;
1169 
1170 	/*
1171 	 * If we are destroying an active vnode, reactivate it now that
1172 	 * we have reassociated it with deadfs.  This prevents the system
1173 	 * from crashing on the vnode due to it being unexpectedly marked
1174 	 * as inactive or reclaimed.
1175 	 */
1176 	if (active && (flags & DOCLOSE)) {
1177 		vp->v_flag &= ~(VINACTIVE|VRECLAIMED);
1178 	}
1179 }
1180 
1181 /*
1182  * Eliminate all activity associated with the requested vnode
1183  * and with all vnodes aliased to the requested vnode.
1184  *
1185  * The vnode must be referenced but should not be locked.
1186  */
1187 int
1188 vrevoke(struct vnode *vp, struct ucred *cred)
1189 {
1190 	struct vnode *vq;
1191 	struct vnode *vqn;
1192 	lwkt_tokref ilock;
1193 	cdev_t dev;
1194 	int error;
1195 
1196 	/*
1197 	 * If the vnode has a device association, scrap all vnodes associated
1198 	 * with the device.  Don't let the device disappear on us while we
1199 	 * are scrapping the vnodes.
1200 	 *
1201 	 * The passed vp will probably show up in the list, do not VX lock
1202 	 * it twice!
1203 	 *
1204 	 * Releasing the vnode's rdev here can mess up specfs's call to
1205 	 * device close, so don't do it.  The vnode has been disassociated
1206 	 * and the device will be closed after the last ref on the related
1207 	 * fp goes away (if not still open by e.g. the kernel).
1208 	 */
1209 	if (vp->v_type != VCHR) {
1210 		error = fdrevoke(vp, DTYPE_VNODE, cred);
1211 		return (error);
1212 	}
1213 	if ((dev = vp->v_rdev) == NULL) {
1214 		return(0);
1215 	}
1216 	reference_dev(dev);
1217 	lwkt_gettoken(&ilock, &spechash_token);
1218 
1219 	vqn = SLIST_FIRST(&dev->si_hlist);
1220 	if (vqn)
1221 		vref(vqn);
1222 	while ((vq = vqn) != NULL) {
1223 		vqn = SLIST_NEXT(vqn, v_cdevnext);
1224 		if (vqn)
1225 			vref(vqn);
1226 		fdrevoke(vq, DTYPE_VNODE, cred);
1227 		/*v_release_rdev(vq);*/
1228 		vrele(vq);
1229 	}
1230 	lwkt_reltoken(&ilock);
1231 	dev_drevoke(dev);
1232 	release_dev(dev);
1233 	return (0);
1234 }
1235 
1236 /*
1237  * This is called when the object underlying a vnode is being destroyed,
1238  * such as in a remove().  Try to recycle the vnode immediately if the
1239  * only active reference is our reference.
1240  *
1241  * Directory vnodes in the namecache with children cannot be immediately
1242  * recycled because numerous VOP_N*() ops require them to be stable.
1243  */
1244 int
1245 vrecycle(struct vnode *vp)
1246 {
1247 	if (vp->v_sysref.refcnt <= 1) {
1248 		if (cache_inval_vp_nonblock(vp))
1249 			return(0);
1250 		vgone_vxlocked(vp);
1251 		return (1);
1252 	}
1253 	return (0);
1254 }
1255 
1256 /*
1257  * Return the maximum I/O size allowed for strategy calls on VP.
1258  *
1259  * If vp is VCHR or VBLK we dive the device, otherwise we use
1260  * the vp's mount info.
1261  */
1262 int
1263 vmaxiosize(struct vnode *vp)
1264 {
1265 	if (vp->v_type == VBLK || vp->v_type == VCHR) {
1266 		return(vp->v_rdev->si_iosize_max);
1267 	} else {
1268 		return(vp->v_mount->mnt_iosize_max);
1269 	}
1270 }
1271 
1272 /*
1273  * Eliminate all activity associated with a vnode in preparation for reuse.
1274  *
1275  * The vnode must be VX locked and refd and will remain VX locked and refd
1276  * on return.  This routine may be called with the vnode in any state, as
1277  * long as it is VX locked.  The vnode will be cleaned out and marked
1278  * VRECLAIMED but will not actually be reused until all existing refs and
1279  * holds go away.
1280  *
1281  * NOTE: This routine may be called on a vnode which has not yet been
1282  * already been deactivated (VOP_INACTIVE), or on a vnode which has
1283  * already been reclaimed.
1284  *
1285  * This routine is not responsible for placing us back on the freelist.
1286  * Instead, it happens automatically when the caller releases the VX lock
1287  * (assuming there aren't any other references).
1288  */
1289 
1290 void
1291 vgone_vxlocked(struct vnode *vp)
1292 {
1293 	/*
1294 	 * assert that the VX lock is held.  This is an absolute requirement
1295 	 * now for vgone_vxlocked() to be called.
1296 	 */
1297 	KKASSERT(vp->v_lock.lk_exclusivecount == 1);
1298 
1299 	/*
1300 	 * Clean out the filesystem specific data and set the VRECLAIMED
1301 	 * bit.  Also deactivate the vnode if necessary.
1302 	 */
1303 	vclean_vxlocked(vp, DOCLOSE);
1304 
1305 	/*
1306 	 * Delete from old mount point vnode list, if on one.
1307 	 */
1308 	if (vp->v_mount != NULL)
1309 		insmntque(vp, NULL);
1310 
1311 	/*
1312 	 * If special device, remove it from special device alias list
1313 	 * if it is on one.  This should normally only occur if a vnode is
1314 	 * being revoked as the device should otherwise have been released
1315 	 * naturally.
1316 	 */
1317 	if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
1318 		v_release_rdev(vp);
1319 	}
1320 
1321 	/*
1322 	 * Set us to VBAD
1323 	 */
1324 	vp->v_type = VBAD;
1325 }
1326 
1327 /*
1328  * Lookup a vnode by device number.
1329  *
1330  * Returns non-zero and *vpp set to a vref'd vnode on success.
1331  * Returns zero on failure.
1332  */
1333 int
1334 vfinddev(cdev_t dev, enum vtype type, struct vnode **vpp)
1335 {
1336 	lwkt_tokref ilock;
1337 	struct vnode *vp;
1338 
1339 	lwkt_gettoken(&ilock, &spechash_token);
1340 	SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1341 		if (type == vp->v_type) {
1342 			*vpp = vp;
1343 			vref(vp);
1344 			lwkt_reltoken(&ilock);
1345 			return (1);
1346 		}
1347 	}
1348 	lwkt_reltoken(&ilock);
1349 	return (0);
1350 }
1351 
1352 /*
1353  * Calculate the total number of references to a special device.  This
1354  * routine may only be called for VBLK and VCHR vnodes since v_rdev is
1355  * an overloaded field.  Since udev2dev can now return NULL, we have
1356  * to check for a NULL v_rdev.
1357  */
1358 int
1359 count_dev(cdev_t dev)
1360 {
1361 	lwkt_tokref ilock;
1362 	struct vnode *vp;
1363 	int count = 0;
1364 
1365 	if (SLIST_FIRST(&dev->si_hlist)) {
1366 		lwkt_gettoken(&ilock, &spechash_token);
1367 		SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1368 			count += vp->v_opencount;
1369 		}
1370 		lwkt_reltoken(&ilock);
1371 	}
1372 	return(count);
1373 }
1374 
1375 int
1376 vcount(struct vnode *vp)
1377 {
1378 	if (vp->v_rdev == NULL)
1379 		return(0);
1380 	return(count_dev(vp->v_rdev));
1381 }
1382 
1383 /*
1384  * Initialize VMIO for a vnode.  This routine MUST be called before a
1385  * VFS can issue buffer cache ops on a vnode.  It is typically called
1386  * when a vnode is initialized from its inode.
1387  */
1388 int
1389 vinitvmio(struct vnode *vp, off_t filesize)
1390 {
1391 	vm_object_t object;
1392 	int error = 0;
1393 
1394 retry:
1395 	if ((object = vp->v_object) == NULL) {
1396 		object = vnode_pager_alloc(vp, filesize, 0, 0);
1397 		/*
1398 		 * Dereference the reference we just created.  This assumes
1399 		 * that the object is associated with the vp.
1400 		 */
1401 		object->ref_count--;
1402 		vrele(vp);
1403 	} else {
1404 		if (object->flags & OBJ_DEAD) {
1405 			vn_unlock(vp);
1406 			vm_object_dead_sleep(object, "vodead");
1407 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1408 			goto retry;
1409 		}
1410 	}
1411 	KASSERT(vp->v_object != NULL, ("vinitvmio: NULL object"));
1412 	vp->v_flag |= VOBJBUF;
1413 	return (error);
1414 }
1415 
1416 
1417 /*
1418  * Print out a description of a vnode.
1419  */
1420 static char *typename[] =
1421 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
1422 
1423 void
1424 vprint(char *label, struct vnode *vp)
1425 {
1426 	char buf[96];
1427 
1428 	if (label != NULL)
1429 		kprintf("%s: %p: ", label, (void *)vp);
1430 	else
1431 		kprintf("%p: ", (void *)vp);
1432 	kprintf("type %s, sysrefs %d, writecount %d, holdcnt %d,",
1433 		typename[vp->v_type],
1434 		vp->v_sysref.refcnt, vp->v_writecount, vp->v_auxrefs);
1435 	buf[0] = '\0';
1436 	if (vp->v_flag & VROOT)
1437 		strcat(buf, "|VROOT");
1438 	if (vp->v_flag & VPFSROOT)
1439 		strcat(buf, "|VPFSROOT");
1440 	if (vp->v_flag & VTEXT)
1441 		strcat(buf, "|VTEXT");
1442 	if (vp->v_flag & VSYSTEM)
1443 		strcat(buf, "|VSYSTEM");
1444 	if (vp->v_flag & VFREE)
1445 		strcat(buf, "|VFREE");
1446 	if (vp->v_flag & VOBJBUF)
1447 		strcat(buf, "|VOBJBUF");
1448 	if (buf[0] != '\0')
1449 		kprintf(" flags (%s)", &buf[1]);
1450 	if (vp->v_data == NULL) {
1451 		kprintf("\n");
1452 	} else {
1453 		kprintf("\n\t");
1454 		VOP_PRINT(vp);
1455 	}
1456 }
1457 
1458 #ifdef DDB
1459 #include <ddb/ddb.h>
1460 
1461 static int db_show_locked_vnodes(struct mount *mp, void *data);
1462 
1463 /*
1464  * List all of the locked vnodes in the system.
1465  * Called when debugging the kernel.
1466  */
1467 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
1468 {
1469 	kprintf("Locked vnodes\n");
1470 	mountlist_scan(db_show_locked_vnodes, NULL,
1471 			MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1472 }
1473 
1474 static int
1475 db_show_locked_vnodes(struct mount *mp, void *data __unused)
1476 {
1477 	struct vnode *vp;
1478 
1479 	TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
1480 		if (vn_islocked(vp))
1481 			vprint(NULL, vp);
1482 	}
1483 	return(0);
1484 }
1485 #endif
1486 
1487 /*
1488  * Top level filesystem related information gathering.
1489  */
1490 static int	sysctl_ovfs_conf (SYSCTL_HANDLER_ARGS);
1491 
1492 static int
1493 vfs_sysctl(SYSCTL_HANDLER_ARGS)
1494 {
1495 	int *name = (int *)arg1 - 1;	/* XXX */
1496 	u_int namelen = arg2 + 1;	/* XXX */
1497 	struct vfsconf *vfsp;
1498 	int maxtypenum;
1499 
1500 #if 1 || defined(COMPAT_PRELITE2)
1501 	/* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
1502 	if (namelen == 1)
1503 		return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
1504 #endif
1505 
1506 #ifdef notyet
1507 	/* all sysctl names at this level are at least name and field */
1508 	if (namelen < 2)
1509 		return (ENOTDIR);		/* overloaded */
1510 	if (name[0] != VFS_GENERIC) {
1511 		vfsp = vfsconf_find_by_typenum(name[0]);
1512 		if (vfsp == NULL)
1513 			return (EOPNOTSUPP);
1514 		return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
1515 		    oldp, oldlenp, newp, newlen, p));
1516 	}
1517 #endif
1518 	switch (name[1]) {
1519 	case VFS_MAXTYPENUM:
1520 		if (namelen != 2)
1521 			return (ENOTDIR);
1522 		maxtypenum = vfsconf_get_maxtypenum();
1523 		return (SYSCTL_OUT(req, &maxtypenum, sizeof(maxtypenum)));
1524 	case VFS_CONF:
1525 		if (namelen != 3)
1526 			return (ENOTDIR);	/* overloaded */
1527 		vfsp = vfsconf_find_by_typenum(name[2]);
1528 		if (vfsp == NULL)
1529 			return (EOPNOTSUPP);
1530 		return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
1531 	}
1532 	return (EOPNOTSUPP);
1533 }
1534 
1535 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
1536 	"Generic filesystem");
1537 
1538 #if 1 || defined(COMPAT_PRELITE2)
1539 
1540 static int
1541 sysctl_ovfs_conf_iter(struct vfsconf *vfsp, void *data)
1542 {
1543 	int error;
1544 	struct ovfsconf ovfs;
1545 	struct sysctl_req *req = (struct sysctl_req*) data;
1546 
1547 	bzero(&ovfs, sizeof(ovfs));
1548 	ovfs.vfc_vfsops = vfsp->vfc_vfsops;	/* XXX used as flag */
1549 	strcpy(ovfs.vfc_name, vfsp->vfc_name);
1550 	ovfs.vfc_index = vfsp->vfc_typenum;
1551 	ovfs.vfc_refcount = vfsp->vfc_refcount;
1552 	ovfs.vfc_flags = vfsp->vfc_flags;
1553 	error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
1554 	if (error)
1555 		return error; /* abort iteration with error code */
1556 	else
1557 		return 0; /* continue iterating with next element */
1558 }
1559 
1560 static int
1561 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
1562 {
1563 	return vfsconf_each(sysctl_ovfs_conf_iter, (void*)req);
1564 }
1565 
1566 #endif /* 1 || COMPAT_PRELITE2 */
1567 
1568 /*
1569  * Check to see if a filesystem is mounted on a block device.
1570  */
1571 int
1572 vfs_mountedon(struct vnode *vp)
1573 {
1574 	cdev_t dev;
1575 
1576 	if ((dev = vp->v_rdev) == NULL) {
1577 /*		if (vp->v_type != VBLK)
1578 			dev = get_dev(vp->v_uminor, vp->v_umajor); */
1579 	}
1580 	if (dev != NULL && dev->si_mountpoint)
1581 		return (EBUSY);
1582 	return (0);
1583 }
1584 
1585 /*
1586  * Unmount all filesystems. The list is traversed in reverse order
1587  * of mounting to avoid dependencies.
1588  */
1589 
1590 static int vfs_umountall_callback(struct mount *mp, void *data);
1591 
1592 void
1593 vfs_unmountall(void)
1594 {
1595 	int count;
1596 
1597 	do {
1598 		count = mountlist_scan(vfs_umountall_callback,
1599 					NULL, MNTSCAN_REVERSE|MNTSCAN_NOBUSY);
1600 	} while (count);
1601 }
1602 
1603 static
1604 int
1605 vfs_umountall_callback(struct mount *mp, void *data)
1606 {
1607 	int error;
1608 
1609 	error = dounmount(mp, MNT_FORCE);
1610 	if (error) {
1611 		mountlist_remove(mp);
1612 		kprintf("unmount of filesystem mounted from %s failed (",
1613 			mp->mnt_stat.f_mntfromname);
1614 		if (error == EBUSY)
1615 			kprintf("BUSY)\n");
1616 		else
1617 			kprintf("%d)\n", error);
1618 	}
1619 	return(1);
1620 }
1621 
1622 /*
1623  * Checks the mount flags for parameter mp and put the names comma-separated
1624  * into a string buffer buf with a size limit specified by len.
1625  *
1626  * It returns the number of bytes written into buf, and (*errorp) will be
1627  * set to 0, EINVAL (if passed length is 0), or ENOSPC (supplied buffer was
1628  * not large enough).  The buffer will be 0-terminated if len was not 0.
1629  */
1630 size_t
1631 vfs_flagstostr(int flags, const struct mountctl_opt *optp,
1632 	       char *buf, size_t len, int *errorp)
1633 {
1634 	static const struct mountctl_opt optnames[] = {
1635 		{ MNT_ASYNC,            "asynchronous" },
1636 		{ MNT_EXPORTED,         "NFS exported" },
1637 		{ MNT_LOCAL,            "local" },
1638 		{ MNT_NOATIME,          "noatime" },
1639 		{ MNT_NODEV,            "nodev" },
1640 		{ MNT_NOEXEC,           "noexec" },
1641 		{ MNT_NOSUID,           "nosuid" },
1642 		{ MNT_NOSYMFOLLOW,      "nosymfollow" },
1643 		{ MNT_QUOTA,            "with-quotas" },
1644 		{ MNT_RDONLY,           "read-only" },
1645 		{ MNT_SYNCHRONOUS,      "synchronous" },
1646 		{ MNT_UNION,            "union" },
1647 		{ MNT_NOCLUSTERR,       "noclusterr" },
1648 		{ MNT_NOCLUSTERW,       "noclusterw" },
1649 		{ MNT_SUIDDIR,          "suiddir" },
1650 		{ MNT_SOFTDEP,          "soft-updates" },
1651 		{ MNT_IGNORE,           "ignore" },
1652 		{ 0,			NULL}
1653 	};
1654 	int bwritten;
1655 	int bleft;
1656 	int optlen;
1657 	int actsize;
1658 
1659 	*errorp = 0;
1660 	bwritten = 0;
1661 	bleft = len - 1;	/* leave room for trailing \0 */
1662 
1663 	/*
1664 	 * Checks the size of the string. If it contains
1665 	 * any data, then we will append the new flags to
1666 	 * it.
1667 	 */
1668 	actsize = strlen(buf);
1669 	if (actsize > 0)
1670 		buf += actsize;
1671 
1672 	/* Default flags if no flags passed */
1673 	if (optp == NULL)
1674 		optp = optnames;
1675 
1676 	if (bleft < 0) {	/* degenerate case, 0-length buffer */
1677 		*errorp = EINVAL;
1678 		return(0);
1679 	}
1680 
1681 	for (; flags && optp->o_opt; ++optp) {
1682 		if ((flags & optp->o_opt) == 0)
1683 			continue;
1684 		optlen = strlen(optp->o_name);
1685 		if (bwritten || actsize > 0) {
1686 			if (bleft < 2) {
1687 				*errorp = ENOSPC;
1688 				break;
1689 			}
1690 			buf[bwritten++] = ',';
1691 			buf[bwritten++] = ' ';
1692 			bleft -= 2;
1693 		}
1694 		if (bleft < optlen) {
1695 			*errorp = ENOSPC;
1696 			break;
1697 		}
1698 		bcopy(optp->o_name, buf + bwritten, optlen);
1699 		bwritten += optlen;
1700 		bleft -= optlen;
1701 		flags &= ~optp->o_opt;
1702 	}
1703 
1704 	/*
1705 	 * Space already reserved for trailing \0
1706 	 */
1707 	buf[bwritten] = 0;
1708 	return (bwritten);
1709 }
1710 
1711 /*
1712  * Build hash lists of net addresses and hang them off the mount point.
1713  * Called by ufs_mount() to set up the lists of export addresses.
1714  */
1715 static int
1716 vfs_hang_addrlist(struct mount *mp, struct netexport *nep,
1717 		const struct export_args *argp)
1718 {
1719 	struct netcred *np;
1720 	struct radix_node_head *rnh;
1721 	int i;
1722 	struct radix_node *rn;
1723 	struct sockaddr *saddr, *smask = 0;
1724 	struct domain *dom;
1725 	int error;
1726 
1727 	if (argp->ex_addrlen == 0) {
1728 		if (mp->mnt_flag & MNT_DEFEXPORTED)
1729 			return (EPERM);
1730 		np = &nep->ne_defexported;
1731 		np->netc_exflags = argp->ex_flags;
1732 		np->netc_anon = argp->ex_anon;
1733 		np->netc_anon.cr_ref = 1;
1734 		mp->mnt_flag |= MNT_DEFEXPORTED;
1735 		return (0);
1736 	}
1737 
1738 	if (argp->ex_addrlen < 0 || argp->ex_addrlen > MLEN)
1739 		return (EINVAL);
1740 	if (argp->ex_masklen < 0 || argp->ex_masklen > MLEN)
1741 		return (EINVAL);
1742 
1743 	i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
1744 	np = (struct netcred *) kmalloc(i, M_NETADDR, M_WAITOK | M_ZERO);
1745 	saddr = (struct sockaddr *) (np + 1);
1746 	if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
1747 		goto out;
1748 	if (saddr->sa_len > argp->ex_addrlen)
1749 		saddr->sa_len = argp->ex_addrlen;
1750 	if (argp->ex_masklen) {
1751 		smask = (struct sockaddr *)((caddr_t)saddr + argp->ex_addrlen);
1752 		error = copyin(argp->ex_mask, (caddr_t)smask, argp->ex_masklen);
1753 		if (error)
1754 			goto out;
1755 		if (smask->sa_len > argp->ex_masklen)
1756 			smask->sa_len = argp->ex_masklen;
1757 	}
1758 	i = saddr->sa_family;
1759 	if ((rnh = nep->ne_rtable[i]) == 0) {
1760 		/*
1761 		 * Seems silly to initialize every AF when most are not used,
1762 		 * do so on demand here
1763 		 */
1764 		SLIST_FOREACH(dom, &domains, dom_next)
1765 			if (dom->dom_family == i && dom->dom_rtattach) {
1766 				dom->dom_rtattach((void **) &nep->ne_rtable[i],
1767 				    dom->dom_rtoffset);
1768 				break;
1769 			}
1770 		if ((rnh = nep->ne_rtable[i]) == 0) {
1771 			error = ENOBUFS;
1772 			goto out;
1773 		}
1774 	}
1775 	rn = (*rnh->rnh_addaddr) ((char *) saddr, (char *) smask, rnh,
1776 	    np->netc_rnodes);
1777 	if (rn == 0 || np != (struct netcred *) rn) {	/* already exists */
1778 		error = EPERM;
1779 		goto out;
1780 	}
1781 	np->netc_exflags = argp->ex_flags;
1782 	np->netc_anon = argp->ex_anon;
1783 	np->netc_anon.cr_ref = 1;
1784 	return (0);
1785 out:
1786 	kfree(np, M_NETADDR);
1787 	return (error);
1788 }
1789 
1790 /* ARGSUSED */
1791 static int
1792 vfs_free_netcred(struct radix_node *rn, void *w)
1793 {
1794 	struct radix_node_head *rnh = (struct radix_node_head *) w;
1795 
1796 	(*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
1797 	kfree((caddr_t) rn, M_NETADDR);
1798 	return (0);
1799 }
1800 
1801 /*
1802  * Free the net address hash lists that are hanging off the mount points.
1803  */
1804 static void
1805 vfs_free_addrlist(struct netexport *nep)
1806 {
1807 	int i;
1808 	struct radix_node_head *rnh;
1809 
1810 	for (i = 0; i <= AF_MAX; i++)
1811 		if ((rnh = nep->ne_rtable[i])) {
1812 			(*rnh->rnh_walktree) (rnh, vfs_free_netcred,
1813 			    (caddr_t) rnh);
1814 			kfree((caddr_t) rnh, M_RTABLE);
1815 			nep->ne_rtable[i] = 0;
1816 		}
1817 }
1818 
1819 int
1820 vfs_export(struct mount *mp, struct netexport *nep,
1821 	   const struct export_args *argp)
1822 {
1823 	int error;
1824 
1825 	if (argp->ex_flags & MNT_DELEXPORT) {
1826 		if (mp->mnt_flag & MNT_EXPUBLIC) {
1827 			vfs_setpublicfs(NULL, NULL, NULL);
1828 			mp->mnt_flag &= ~MNT_EXPUBLIC;
1829 		}
1830 		vfs_free_addrlist(nep);
1831 		mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
1832 	}
1833 	if (argp->ex_flags & MNT_EXPORTED) {
1834 		if (argp->ex_flags & MNT_EXPUBLIC) {
1835 			if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
1836 				return (error);
1837 			mp->mnt_flag |= MNT_EXPUBLIC;
1838 		}
1839 		if ((error = vfs_hang_addrlist(mp, nep, argp)))
1840 			return (error);
1841 		mp->mnt_flag |= MNT_EXPORTED;
1842 	}
1843 	return (0);
1844 }
1845 
1846 
1847 /*
1848  * Set the publicly exported filesystem (WebNFS). Currently, only
1849  * one public filesystem is possible in the spec (RFC 2054 and 2055)
1850  */
1851 int
1852 vfs_setpublicfs(struct mount *mp, struct netexport *nep,
1853 		const struct export_args *argp)
1854 {
1855 	int error;
1856 	struct vnode *rvp;
1857 	char *cp;
1858 
1859 	/*
1860 	 * mp == NULL -> invalidate the current info, the FS is
1861 	 * no longer exported. May be called from either vfs_export
1862 	 * or unmount, so check if it hasn't already been done.
1863 	 */
1864 	if (mp == NULL) {
1865 		if (nfs_pub.np_valid) {
1866 			nfs_pub.np_valid = 0;
1867 			if (nfs_pub.np_index != NULL) {
1868 				FREE(nfs_pub.np_index, M_TEMP);
1869 				nfs_pub.np_index = NULL;
1870 			}
1871 		}
1872 		return (0);
1873 	}
1874 
1875 	/*
1876 	 * Only one allowed at a time.
1877 	 */
1878 	if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
1879 		return (EBUSY);
1880 
1881 	/*
1882 	 * Get real filehandle for root of exported FS.
1883 	 */
1884 	bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
1885 	nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
1886 
1887 	if ((error = VFS_ROOT(mp, &rvp)))
1888 		return (error);
1889 
1890 	if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
1891 		return (error);
1892 
1893 	vput(rvp);
1894 
1895 	/*
1896 	 * If an indexfile was specified, pull it in.
1897 	 */
1898 	if (argp->ex_indexfile != NULL) {
1899 		int namelen;
1900 
1901 		error = vn_get_namelen(rvp, &namelen);
1902 		if (error)
1903 			return (error);
1904 		MALLOC(nfs_pub.np_index, char *, namelen, M_TEMP,
1905 		    M_WAITOK);
1906 		error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
1907 		    namelen, NULL);
1908 		if (!error) {
1909 			/*
1910 			 * Check for illegal filenames.
1911 			 */
1912 			for (cp = nfs_pub.np_index; *cp; cp++) {
1913 				if (*cp == '/') {
1914 					error = EINVAL;
1915 					break;
1916 				}
1917 			}
1918 		}
1919 		if (error) {
1920 			FREE(nfs_pub.np_index, M_TEMP);
1921 			return (error);
1922 		}
1923 	}
1924 
1925 	nfs_pub.np_mount = mp;
1926 	nfs_pub.np_valid = 1;
1927 	return (0);
1928 }
1929 
1930 struct netcred *
1931 vfs_export_lookup(struct mount *mp, struct netexport *nep,
1932 		struct sockaddr *nam)
1933 {
1934 	struct netcred *np;
1935 	struct radix_node_head *rnh;
1936 	struct sockaddr *saddr;
1937 
1938 	np = NULL;
1939 	if (mp->mnt_flag & MNT_EXPORTED) {
1940 		/*
1941 		 * Lookup in the export list first.
1942 		 */
1943 		if (nam != NULL) {
1944 			saddr = nam;
1945 			rnh = nep->ne_rtable[saddr->sa_family];
1946 			if (rnh != NULL) {
1947 				np = (struct netcred *)
1948 					(*rnh->rnh_matchaddr)((char *)saddr,
1949 							      rnh);
1950 				if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
1951 					np = NULL;
1952 			}
1953 		}
1954 		/*
1955 		 * If no address match, use the default if it exists.
1956 		 */
1957 		if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
1958 			np = &nep->ne_defexported;
1959 	}
1960 	return (np);
1961 }
1962 
1963 /*
1964  * perform msync on all vnodes under a mount point.  The mount point must
1965  * be locked.  This code is also responsible for lazy-freeing unreferenced
1966  * vnodes whos VM objects no longer contain pages.
1967  *
1968  * NOTE: MNT_WAIT still skips vnodes in the VXLOCK state.
1969  *
1970  * NOTE: XXX VOP_PUTPAGES and friends requires that the vnode be locked,
1971  * but vnode_pager_putpages() doesn't lock the vnode.  We have to do it
1972  * way up in this high level function.
1973  */
1974 static int vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data);
1975 static int vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data);
1976 
1977 void
1978 vfs_msync(struct mount *mp, int flags)
1979 {
1980 	int vmsc_flags;
1981 
1982 	vmsc_flags = VMSC_GETVP;
1983 	if (flags != MNT_WAIT)
1984 		vmsc_flags |= VMSC_NOWAIT;
1985 	vmntvnodescan(mp, vmsc_flags, vfs_msync_scan1, vfs_msync_scan2,
1986 			(void *)(intptr_t)flags);
1987 }
1988 
1989 /*
1990  * scan1 is a fast pre-check.  There could be hundreds of thousands of
1991  * vnodes, we cannot afford to do anything heavy weight until we have a
1992  * fairly good indication that there is work to do.
1993  */
1994 static
1995 int
1996 vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data)
1997 {
1998 	int flags = (int)(intptr_t)data;
1999 
2000 	if ((vp->v_flag & VRECLAIMED) == 0) {
2001 		if (vshouldmsync(vp))
2002 			return(0);	/* call scan2 */
2003 		if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
2004 		    (vp->v_flag & VOBJDIRTY) &&
2005 		    (flags == MNT_WAIT || vn_islocked(vp) == 0)) {
2006 			return(0);	/* call scan2 */
2007 		}
2008 	}
2009 
2010 	/*
2011 	 * do not call scan2, continue the loop
2012 	 */
2013 	return(-1);
2014 }
2015 
2016 /*
2017  * This callback is handed a locked vnode.
2018  */
2019 static
2020 int
2021 vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data)
2022 {
2023 	vm_object_t obj;
2024 	int flags = (int)(intptr_t)data;
2025 
2026 	if (vp->v_flag & VRECLAIMED)
2027 		return(0);
2028 
2029 	if ((mp->mnt_flag & MNT_RDONLY) == 0 && (vp->v_flag & VOBJDIRTY)) {
2030 		if ((obj = vp->v_object) != NULL) {
2031 			vm_object_page_clean(obj, 0, 0,
2032 			 flags == MNT_WAIT ? OBJPC_SYNC : OBJPC_NOSYNC);
2033 		}
2034 	}
2035 	return(0);
2036 }
2037 
2038 /*
2039  * Record a process's interest in events which might happen to
2040  * a vnode.  Because poll uses the historic select-style interface
2041  * internally, this routine serves as both the ``check for any
2042  * pending events'' and the ``record my interest in future events''
2043  * functions.  (These are done together, while the lock is held,
2044  * to avoid race conditions.)
2045  */
2046 int
2047 vn_pollrecord(struct vnode *vp, int events)
2048 {
2049 	lwkt_tokref vlock;
2050 
2051 	KKASSERT(curthread->td_proc != NULL);
2052 
2053 	lwkt_gettoken(&vlock, &vp->v_token);
2054 	if (vp->v_pollinfo.vpi_revents & events) {
2055 		/*
2056 		 * This leaves events we are not interested
2057 		 * in available for the other process which
2058 		 * which presumably had requested them
2059 		 * (otherwise they would never have been
2060 		 * recorded).
2061 		 */
2062 		events &= vp->v_pollinfo.vpi_revents;
2063 		vp->v_pollinfo.vpi_revents &= ~events;
2064 
2065 		lwkt_reltoken(&vlock);
2066 		return events;
2067 	}
2068 	vp->v_pollinfo.vpi_events |= events;
2069 	selrecord(curthread, &vp->v_pollinfo.vpi_selinfo);
2070 	lwkt_reltoken(&vlock);
2071 	return 0;
2072 }
2073 
2074 /*
2075  * Note the occurrence of an event.  If the VN_POLLEVENT macro is used,
2076  * it is possible for us to miss an event due to race conditions, but
2077  * that condition is expected to be rare, so for the moment it is the
2078  * preferred interface.
2079  */
2080 void
2081 vn_pollevent(struct vnode *vp, int events)
2082 {
2083 	lwkt_tokref vlock;
2084 
2085 	lwkt_gettoken(&vlock, &vp->v_token);
2086 	if (vp->v_pollinfo.vpi_events & events) {
2087 		/*
2088 		 * We clear vpi_events so that we don't
2089 		 * call selwakeup() twice if two events are
2090 		 * posted before the polling process(es) is
2091 		 * awakened.  This also ensures that we take at
2092 		 * most one selwakeup() if the polling process
2093 		 * is no longer interested.  However, it does
2094 		 * mean that only one event can be noticed at
2095 		 * a time.  (Perhaps we should only clear those
2096 		 * event bits which we note?) XXX
2097 		 */
2098 		vp->v_pollinfo.vpi_events = 0;	/* &= ~events ??? */
2099 		vp->v_pollinfo.vpi_revents |= events;
2100 		selwakeup(&vp->v_pollinfo.vpi_selinfo);
2101 	}
2102 	lwkt_reltoken(&vlock);
2103 }
2104 
2105 /*
2106  * Wake up anyone polling on vp because it is being revoked.
2107  * This depends on dead_poll() returning POLLHUP for correct
2108  * behavior.
2109  */
2110 void
2111 vn_pollgone(struct vnode *vp)
2112 {
2113 	lwkt_tokref vlock;
2114 
2115 	lwkt_gettoken(&vlock, &vp->v_token);
2116 	if (vp->v_pollinfo.vpi_events) {
2117 		vp->v_pollinfo.vpi_events = 0;
2118 		selwakeup(&vp->v_pollinfo.vpi_selinfo);
2119 	}
2120 	lwkt_reltoken(&vlock);
2121 }
2122 
2123 /*
2124  * extract the cdev_t from a VBLK or VCHR.  The vnode must have been opened
2125  * (or v_rdev might be NULL).
2126  */
2127 cdev_t
2128 vn_todev(struct vnode *vp)
2129 {
2130 	if (vp->v_type != VBLK && vp->v_type != VCHR)
2131 		return (NULL);
2132 	KKASSERT(vp->v_rdev != NULL);
2133 	return (vp->v_rdev);
2134 }
2135 
2136 /*
2137  * Check if vnode represents a disk device.  The vnode does not need to be
2138  * opened.
2139  *
2140  * MPALMOSTSAFE
2141  */
2142 int
2143 vn_isdisk(struct vnode *vp, int *errp)
2144 {
2145 	cdev_t dev;
2146 
2147 	if (vp->v_type != VCHR) {
2148 		if (errp != NULL)
2149 			*errp = ENOTBLK;
2150 		return (0);
2151 	}
2152 
2153 	dev = vp->v_rdev;
2154 
2155 	if (dev == NULL) {
2156 		if (errp != NULL)
2157 			*errp = ENXIO;
2158 		return (0);
2159 	}
2160 	if (dev_is_good(dev) == 0) {
2161 		if (errp != NULL)
2162 			*errp = ENXIO;
2163 		return (0);
2164 	}
2165 	if ((dev_dflags(dev) & D_DISK) == 0) {
2166 		if (errp != NULL)
2167 			*errp = ENOTBLK;
2168 		return (0);
2169 	}
2170 	if (errp != NULL)
2171 		*errp = 0;
2172 	return (1);
2173 }
2174 
2175 int
2176 vn_get_namelen(struct vnode *vp, int *namelen)
2177 {
2178 	int error;
2179 	register_t retval[2];
2180 
2181 	error = VOP_PATHCONF(vp, _PC_NAME_MAX, retval);
2182 	if (error)
2183 		return (error);
2184 	*namelen = (int)retval[0];
2185 	return (0);
2186 }
2187 
2188 int
2189 vop_write_dirent(int *error, struct uio *uio, ino_t d_ino, uint8_t d_type,
2190 		uint16_t d_namlen, const char *d_name)
2191 {
2192 	struct dirent *dp;
2193 	size_t len;
2194 
2195 	len = _DIRENT_RECLEN(d_namlen);
2196 	if (len > uio->uio_resid)
2197 		return(1);
2198 
2199 	dp = kmalloc(len, M_TEMP, M_WAITOK | M_ZERO);
2200 
2201 	dp->d_ino = d_ino;
2202 	dp->d_namlen = d_namlen;
2203 	dp->d_type = d_type;
2204 	bcopy(d_name, dp->d_name, d_namlen);
2205 
2206 	*error = uiomove((caddr_t)dp, len, uio);
2207 
2208 	kfree(dp, M_TEMP);
2209 
2210 	return(0);
2211 }
2212 
2213 void
2214 vn_mark_atime(struct vnode *vp, struct thread *td)
2215 {
2216 	struct proc *p = td->td_proc;
2217 	struct ucred *cred = p ? p->p_ucred : proc0.p_ucred;
2218 
2219 	if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
2220 		VOP_MARKATIME(vp, cred);
2221 	}
2222 }
2223