xref: /dflybsd-src/sys/kern/vfs_subr.c (revision 6693db176654a0f25095ec64d0a74d58dcf0e47e)
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/priv.h>
63 #include <sys/proc.h>
64 #include <sys/reboot.h>
65 #include <sys/socket.h>
66 #include <sys/stat.h>
67 #include <sys/sysctl.h>
68 #include <sys/syslog.h>
69 #include <sys/unistd.h>
70 #include <sys/vmmeter.h>
71 #include <sys/vnode.h>
72 
73 #include <machine/limits.h>
74 
75 #include <vm/vm.h>
76 #include <vm/vm_object.h>
77 #include <vm/vm_extern.h>
78 #include <vm/vm_kern.h>
79 #include <vm/pmap.h>
80 #include <vm/vm_map.h>
81 #include <vm/vm_page.h>
82 #include <vm/vm_pager.h>
83 #include <vm/vnode_pager.h>
84 #include <vm/vm_zone.h>
85 
86 #include <sys/buf2.h>
87 #include <sys/thread2.h>
88 #include <sys/sysref2.h>
89 #include <sys/mplock2.h>
90 
91 static MALLOC_DEFINE(M_NETADDR, "Export Host", "Export host address structure");
92 
93 int numvnodes;
94 SYSCTL_INT(_debug, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0, "");
95 int vfs_fastdev = 1;
96 SYSCTL_INT(_vfs, OID_AUTO, fastdev, CTLFLAG_RW, &vfs_fastdev, 0, "");
97 
98 enum vtype iftovt_tab[16] = {
99 	VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
100 	VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
101 };
102 int vttoif_tab[9] = {
103 	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
104 	S_IFSOCK, S_IFIFO, S_IFMT,
105 };
106 
107 static int reassignbufcalls;
108 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW,
109 		&reassignbufcalls, 0, "");
110 static int reassignbufloops;
111 SYSCTL_INT(_vfs, OID_AUTO, reassignbufloops, CTLFLAG_RW,
112 		&reassignbufloops, 0, "");
113 static int reassignbufsortgood;
114 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortgood, CTLFLAG_RW,
115 		&reassignbufsortgood, 0, "");
116 static int reassignbufsortbad;
117 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortbad, CTLFLAG_RW,
118 		&reassignbufsortbad, 0, "");
119 static int reassignbufmethod = 1;
120 SYSCTL_INT(_vfs, OID_AUTO, reassignbufmethod, CTLFLAG_RW,
121 		&reassignbufmethod, 0, "");
122 
123 int	nfs_mount_type = -1;
124 static struct lwkt_token spechash_token;
125 struct nfs_public nfs_pub;	/* publicly exported FS */
126 
127 int desiredvnodes;
128 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
129 		&desiredvnodes, 0, "Maximum number of vnodes");
130 
131 static void	vfs_free_addrlist (struct netexport *nep);
132 static int	vfs_free_netcred (struct radix_node *rn, void *w);
133 static int	vfs_hang_addrlist (struct mount *mp, struct netexport *nep,
134 				       const struct export_args *argp);
135 
136 /*
137  * Red black tree functions
138  */
139 static int rb_buf_compare(struct buf *b1, struct buf *b2);
140 RB_GENERATE2(buf_rb_tree, buf, b_rbnode, rb_buf_compare, off_t, b_loffset);
141 RB_GENERATE2(buf_rb_hash, buf, b_rbhash, rb_buf_compare, off_t, b_loffset);
142 
143 static int
144 rb_buf_compare(struct buf *b1, struct buf *b2)
145 {
146 	if (b1->b_loffset < b2->b_loffset)
147 		return(-1);
148 	if (b1->b_loffset > b2->b_loffset)
149 		return(1);
150 	return(0);
151 }
152 
153 /*
154  * Returns non-zero if the vnode is a candidate for lazy msyncing.
155  */
156 static __inline int
157 vshouldmsync(struct vnode *vp)
158 {
159 	if (vp->v_auxrefs != 0 || vp->v_sysref.refcnt > 0)
160 		return (0);		/* other holders */
161 	if (vp->v_object &&
162 	    (vp->v_object->ref_count || vp->v_object->resident_page_count)) {
163 		return (0);
164 	}
165 	return (1);
166 }
167 
168 /*
169  * Initialize the vnode management data structures.
170  *
171  * Called from vfsinit()
172  */
173 void
174 vfs_subr_init(void)
175 {
176 	/*
177 	 * Desiredvnodes is kern.maxvnodes.  We want to scale it
178 	 * according to available system memory but we may also have
179 	 * to limit it based on available KVM, which is capped on 32 bit
180 	 * systems.
181 	 */
182 	desiredvnodes = min(maxproc + vmstats.v_page_count / 4,
183 			    KvaSize / (20 *
184 			    (sizeof(struct vm_object) + sizeof(struct vnode))));
185 
186 	lwkt_token_init(&spechash_token);
187 }
188 
189 /*
190  * Knob to control the precision of file timestamps:
191  *
192  *   0 = seconds only; nanoseconds zeroed.
193  *   1 = seconds and nanoseconds, accurate within 1/HZ.
194  *   2 = seconds and nanoseconds, truncated to microseconds.
195  * >=3 = seconds and nanoseconds, maximum precision.
196  */
197 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
198 
199 static int timestamp_precision = TSP_SEC;
200 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
201 		&timestamp_precision, 0, "");
202 
203 /*
204  * Get a current timestamp.
205  *
206  * MPSAFE
207  */
208 void
209 vfs_timestamp(struct timespec *tsp)
210 {
211 	struct timeval tv;
212 
213 	switch (timestamp_precision) {
214 	case TSP_SEC:
215 		tsp->tv_sec = time_second;
216 		tsp->tv_nsec = 0;
217 		break;
218 	case TSP_HZ:
219 		getnanotime(tsp);
220 		break;
221 	case TSP_USEC:
222 		microtime(&tv);
223 		TIMEVAL_TO_TIMESPEC(&tv, tsp);
224 		break;
225 	case TSP_NSEC:
226 	default:
227 		nanotime(tsp);
228 		break;
229 	}
230 }
231 
232 /*
233  * Set vnode attributes to VNOVAL
234  */
235 void
236 vattr_null(struct vattr *vap)
237 {
238 	vap->va_type = VNON;
239 	vap->va_size = VNOVAL;
240 	vap->va_bytes = VNOVAL;
241 	vap->va_mode = VNOVAL;
242 	vap->va_nlink = VNOVAL;
243 	vap->va_uid = VNOVAL;
244 	vap->va_gid = VNOVAL;
245 	vap->va_fsid = VNOVAL;
246 	vap->va_fileid = VNOVAL;
247 	vap->va_blocksize = VNOVAL;
248 	vap->va_rmajor = VNOVAL;
249 	vap->va_rminor = VNOVAL;
250 	vap->va_atime.tv_sec = VNOVAL;
251 	vap->va_atime.tv_nsec = VNOVAL;
252 	vap->va_mtime.tv_sec = VNOVAL;
253 	vap->va_mtime.tv_nsec = VNOVAL;
254 	vap->va_ctime.tv_sec = VNOVAL;
255 	vap->va_ctime.tv_nsec = VNOVAL;
256 	vap->va_flags = VNOVAL;
257 	vap->va_gen = VNOVAL;
258 	vap->va_vaflags = 0;
259 	/* va_*_uuid fields are only valid if related flags are set */
260 }
261 
262 /*
263  * Flush out and invalidate all buffers associated with a vnode.
264  *
265  * vp must be locked.
266  */
267 static int vinvalbuf_bp(struct buf *bp, void *data);
268 
269 struct vinvalbuf_bp_info {
270 	struct vnode *vp;
271 	int slptimeo;
272 	int lkflags;
273 	int flags;
274 };
275 
276 int
277 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
278 {
279 	struct vinvalbuf_bp_info info;
280 	vm_object_t object;
281 	lwkt_tokref vlock;
282 	int error;
283 
284 	lwkt_gettoken(&vlock, &vp->v_token);
285 
286 	/*
287 	 * If we are being asked to save, call fsync to ensure that the inode
288 	 * is updated.
289 	 */
290 	if (flags & V_SAVE) {
291 		error = bio_track_wait(&vp->v_track_write, slpflag, slptimeo);
292 		if (error)
293 			goto done;
294 		if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
295 			if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)) != 0)
296 				goto done;
297 
298 			/*
299 			 * Dirty bufs may be left or generated via races
300 			 * in circumstances where vinvalbuf() is called on
301 			 * a vnode not undergoing reclamation.   Only
302 			 * panic if we are trying to reclaim the vnode.
303 			 */
304 			if ((vp->v_flag & VRECLAIMED) &&
305 			    (bio_track_active(&vp->v_track_write) ||
306 			    !RB_EMPTY(&vp->v_rbdirty_tree))) {
307 				panic("vinvalbuf: dirty bufs");
308 			}
309 		}
310   	}
311 	info.slptimeo = slptimeo;
312 	info.lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
313 	if (slpflag & PCATCH)
314 		info.lkflags |= LK_PCATCH;
315 	info.flags = flags;
316 	info.vp = vp;
317 
318 	/*
319 	 * Flush the buffer cache until nothing is left.
320 	 */
321 	while (!RB_EMPTY(&vp->v_rbclean_tree) ||
322 	       !RB_EMPTY(&vp->v_rbdirty_tree)) {
323 		error = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree, NULL,
324 				vinvalbuf_bp, &info);
325 		if (error == 0) {
326 			error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
327 					vinvalbuf_bp, &info);
328 		}
329 	}
330 
331 	/*
332 	 * Wait for I/O completion.  We may block in the pip code so we have
333 	 * to re-check.
334 	 */
335 	do {
336 		bio_track_wait(&vp->v_track_write, 0, 0);
337 		if ((object = vp->v_object) != NULL) {
338 			while (object->paging_in_progress)
339 				vm_object_pip_sleep(object, "vnvlbx");
340 		}
341 	} while (bio_track_active(&vp->v_track_write));
342 
343 	/*
344 	 * Destroy the copy in the VM cache, too.
345 	 */
346 	if ((object = vp->v_object) != NULL) {
347 		vm_object_page_remove(object, 0, 0,
348 			(flags & V_SAVE) ? TRUE : FALSE);
349 	}
350 
351 	if (!RB_EMPTY(&vp->v_rbdirty_tree) || !RB_EMPTY(&vp->v_rbclean_tree))
352 		panic("vinvalbuf: flush failed");
353 	if (!RB_EMPTY(&vp->v_rbhash_tree))
354 		panic("vinvalbuf: flush failed, buffers still present");
355 	error = 0;
356 done:
357 	lwkt_reltoken(&vlock);
358 	return (error);
359 }
360 
361 static int
362 vinvalbuf_bp(struct buf *bp, void *data)
363 {
364 	struct vinvalbuf_bp_info *info = data;
365 	int error;
366 
367 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
368 		error = BUF_TIMELOCK(bp, info->lkflags,
369 				     "vinvalbuf", info->slptimeo);
370 		if (error == 0) {
371 			BUF_UNLOCK(bp);
372 			error = ENOLCK;
373 		}
374 		if (error == ENOLCK)
375 			return(0);
376 		return (-error);
377 	}
378 
379 	KKASSERT(bp->b_vp == info->vp);
380 
381 	/*
382 	 * XXX Since there are no node locks for NFS, I
383 	 * believe there is a slight chance that a delayed
384 	 * write will occur while sleeping just above, so
385 	 * check for it.  Note that vfs_bio_awrite expects
386 	 * buffers to reside on a queue, while bwrite() and
387 	 * brelse() do not.
388 	 *
389 	 * NOTE:  NO B_LOCKED CHECK.  Also no buf_checkwrite()
390 	 * check.  This code will write out the buffer, period.
391 	 */
392 	if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
393 	    (info->flags & V_SAVE)) {
394 		if (bp->b_vp == info->vp) {
395 			if (bp->b_flags & B_CLUSTEROK) {
396 				vfs_bio_awrite(bp);
397 			} else {
398 				bremfree(bp);
399 				bawrite(bp);
400 			}
401 		} else {
402 			bremfree(bp);
403 			bwrite(bp);
404 		}
405 	} else if (info->flags & V_SAVE) {
406 		/*
407 		 * Cannot set B_NOCACHE on a clean buffer as this will
408 		 * destroy the VM backing store which might actually
409 		 * be dirty (and unsynchronized).
410 		 */
411 		bremfree(bp);
412 		bp->b_flags |= (B_INVAL | B_RELBUF);
413 		brelse(bp);
414 	} else {
415 		bremfree(bp);
416 		bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
417 		brelse(bp);
418 	}
419 	return(0);
420 }
421 
422 /*
423  * Truncate a file's buffer and pages to a specified length.  This
424  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
425  * sync activity.
426  *
427  * The vnode must be locked.
428  */
429 static int vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data);
430 static int vtruncbuf_bp_trunc(struct buf *bp, void *data);
431 static int vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data);
432 static int vtruncbuf_bp_metasync(struct buf *bp, void *data);
433 
434 int
435 vtruncbuf(struct vnode *vp, off_t length, int blksize)
436 {
437 	off_t truncloffset;
438 	const char *filename;
439 	lwkt_tokref vlock;
440 	int count;
441 
442 	/*
443 	 * Round up to the *next* block, then destroy the buffers in question.
444 	 * Since we are only removing some of the buffers we must rely on the
445 	 * scan count to determine whether a loop is necessary.
446 	 */
447 	if ((count = (int)(length % blksize)) != 0)
448 		truncloffset = length + (blksize - count);
449 	else
450 		truncloffset = length;
451 
452 	lwkt_gettoken(&vlock, &vp->v_token);
453 	do {
454 		count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
455 				vtruncbuf_bp_trunc_cmp,
456 				vtruncbuf_bp_trunc, &truncloffset);
457 		count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
458 				vtruncbuf_bp_trunc_cmp,
459 				vtruncbuf_bp_trunc, &truncloffset);
460 	} while(count);
461 
462 	/*
463 	 * For safety, fsync any remaining metadata if the file is not being
464 	 * truncated to 0.  Since the metadata does not represent the entire
465 	 * dirty list we have to rely on the hit count to ensure that we get
466 	 * all of it.
467 	 */
468 	if (length > 0) {
469 		do {
470 			count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
471 					vtruncbuf_bp_metasync_cmp,
472 					vtruncbuf_bp_metasync, vp);
473 		} while (count);
474 	}
475 
476 	/*
477 	 * Clean out any left over VM backing store.
478 	 *
479 	 * It is possible to have in-progress I/O from buffers that were
480 	 * not part of the truncation.  This should not happen if we
481 	 * are truncating to 0-length.
482 	 */
483 	vnode_pager_setsize(vp, length);
484 	bio_track_wait(&vp->v_track_write, 0, 0);
485 
486 	/*
487 	 * Debugging only
488 	 */
489 	spin_lock_wr(&vp->v_spinlock);
490 	filename = TAILQ_FIRST(&vp->v_namecache) ?
491 		   TAILQ_FIRST(&vp->v_namecache)->nc_name : "?";
492 	spin_unlock_wr(&vp->v_spinlock);
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 		vclrflags(vp, 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 			vclrflags(vp, 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 	vsetflags(vp, 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 the vnode is already dead don't try to deactivate it.
1138 	 */
1139 	if ((vp->v_flag & VINACTIVE) == 0) {
1140 		vsetflags(vp, VINACTIVE);
1141 		if (vp->v_mount)
1142 			VOP_INACTIVE(vp);
1143 		vinvalbuf(vp, V_SAVE, 0, 0);
1144 	}
1145 
1146 	/*
1147 	 * If the vnode has an object, destroy it.
1148 	 */
1149 	if ((object = vp->v_object) != NULL) {
1150 		if (object->ref_count == 0) {
1151 			if ((object->flags & OBJ_DEAD) == 0)
1152 				vm_object_terminate(object);
1153 		} else {
1154 			vm_pager_deallocate(object);
1155 		}
1156 		vclrflags(vp, VOBJBUF);
1157 	}
1158 	KKASSERT((vp->v_flag & VOBJBUF) == 0);
1159 
1160 	/*
1161 	 * Reclaim the vnode if not already dead.
1162 	 */
1163 	if (vp->v_mount && VOP_RECLAIM(vp))
1164 		panic("vclean: cannot reclaim");
1165 
1166 	/*
1167 	 * Done with purge, notify sleepers of the grim news.
1168 	 */
1169 	vp->v_ops = &dead_vnode_vops_p;
1170 	vn_pollgone(vp);
1171 	vp->v_tag = VT_NON;
1172 
1173 	/*
1174 	 * If we are destroying an active vnode, reactivate it now that
1175 	 * we have reassociated it with deadfs.  This prevents the system
1176 	 * from crashing on the vnode due to it being unexpectedly marked
1177 	 * as inactive or reclaimed.
1178 	 */
1179 	if (active && (flags & DOCLOSE)) {
1180 		vclrflags(vp, VINACTIVE | VRECLAIMED);
1181 	}
1182 }
1183 
1184 /*
1185  * Eliminate all activity associated with the requested vnode
1186  * and with all vnodes aliased to the requested vnode.
1187  *
1188  * The vnode must be referenced but should not be locked.
1189  */
1190 int
1191 vrevoke(struct vnode *vp, struct ucred *cred)
1192 {
1193 	struct vnode *vq;
1194 	struct vnode *vqn;
1195 	lwkt_tokref ilock;
1196 	cdev_t dev;
1197 	int error;
1198 
1199 	/*
1200 	 * If the vnode has a device association, scrap all vnodes associated
1201 	 * with the device.  Don't let the device disappear on us while we
1202 	 * are scrapping the vnodes.
1203 	 *
1204 	 * The passed vp will probably show up in the list, do not VX lock
1205 	 * it twice!
1206 	 *
1207 	 * Releasing the vnode's rdev here can mess up specfs's call to
1208 	 * device close, so don't do it.  The vnode has been disassociated
1209 	 * and the device will be closed after the last ref on the related
1210 	 * fp goes away (if not still open by e.g. the kernel).
1211 	 */
1212 	if (vp->v_type != VCHR) {
1213 		error = fdrevoke(vp, DTYPE_VNODE, cred);
1214 		return (error);
1215 	}
1216 	if ((dev = vp->v_rdev) == NULL) {
1217 		return(0);
1218 	}
1219 	reference_dev(dev);
1220 	lwkt_gettoken(&ilock, &spechash_token);
1221 
1222 	vqn = SLIST_FIRST(&dev->si_hlist);
1223 	if (vqn)
1224 		vref(vqn);
1225 	while ((vq = vqn) != NULL) {
1226 		vqn = SLIST_NEXT(vqn, v_cdevnext);
1227 		if (vqn)
1228 			vref(vqn);
1229 		fdrevoke(vq, DTYPE_VNODE, cred);
1230 		/*v_release_rdev(vq);*/
1231 		vrele(vq);
1232 	}
1233 	lwkt_reltoken(&ilock);
1234 	dev_drevoke(dev);
1235 	release_dev(dev);
1236 	return (0);
1237 }
1238 
1239 /*
1240  * This is called when the object underlying a vnode is being destroyed,
1241  * such as in a remove().  Try to recycle the vnode immediately if the
1242  * only active reference is our reference.
1243  *
1244  * Directory vnodes in the namecache with children cannot be immediately
1245  * recycled because numerous VOP_N*() ops require them to be stable.
1246  */
1247 int
1248 vrecycle(struct vnode *vp)
1249 {
1250 	if (vp->v_sysref.refcnt <= 1) {
1251 		if (cache_inval_vp_nonblock(vp))
1252 			return(0);
1253 		vgone_vxlocked(vp);
1254 		return (1);
1255 	}
1256 	return (0);
1257 }
1258 
1259 /*
1260  * Return the maximum I/O size allowed for strategy calls on VP.
1261  *
1262  * If vp is VCHR or VBLK we dive the device, otherwise we use
1263  * the vp's mount info.
1264  */
1265 int
1266 vmaxiosize(struct vnode *vp)
1267 {
1268 	if (vp->v_type == VBLK || vp->v_type == VCHR) {
1269 		return(vp->v_rdev->si_iosize_max);
1270 	} else {
1271 		return(vp->v_mount->mnt_iosize_max);
1272 	}
1273 }
1274 
1275 /*
1276  * Eliminate all activity associated with a vnode in preparation for reuse.
1277  *
1278  * The vnode must be VX locked and refd and will remain VX locked and refd
1279  * on return.  This routine may be called with the vnode in any state, as
1280  * long as it is VX locked.  The vnode will be cleaned out and marked
1281  * VRECLAIMED but will not actually be reused until all existing refs and
1282  * holds go away.
1283  *
1284  * NOTE: This routine may be called on a vnode which has not yet been
1285  * already been deactivated (VOP_INACTIVE), or on a vnode which has
1286  * already been reclaimed.
1287  *
1288  * This routine is not responsible for placing us back on the freelist.
1289  * Instead, it happens automatically when the caller releases the VX lock
1290  * (assuming there aren't any other references).
1291  */
1292 void
1293 vgone_vxlocked(struct vnode *vp)
1294 {
1295 	/*
1296 	 * assert that the VX lock is held.  This is an absolute requirement
1297 	 * now for vgone_vxlocked() to be called.
1298 	 */
1299 	KKASSERT(vp->v_lock.lk_exclusivecount == 1);
1300 
1301 	get_mplock();
1302 
1303 	/*
1304 	 * Clean out the filesystem specific data and set the VRECLAIMED
1305 	 * bit.  Also deactivate the vnode if necessary.
1306 	 */
1307 	vclean_vxlocked(vp, DOCLOSE);
1308 
1309 	/*
1310 	 * Delete from old mount point vnode list, if on one.
1311 	 */
1312 	if (vp->v_mount != NULL)
1313 		insmntque(vp, NULL);
1314 
1315 	/*
1316 	 * If special device, remove it from special device alias list
1317 	 * if it is on one.  This should normally only occur if a vnode is
1318 	 * being revoked as the device should otherwise have been released
1319 	 * naturally.
1320 	 */
1321 	if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
1322 		v_release_rdev(vp);
1323 	}
1324 
1325 	/*
1326 	 * Set us to VBAD
1327 	 */
1328 	vp->v_type = VBAD;
1329 	rel_mplock();
1330 }
1331 
1332 /*
1333  * Lookup a vnode by device number.
1334  *
1335  * Returns non-zero and *vpp set to a vref'd vnode on success.
1336  * Returns zero on failure.
1337  */
1338 int
1339 vfinddev(cdev_t dev, enum vtype type, struct vnode **vpp)
1340 {
1341 	lwkt_tokref ilock;
1342 	struct vnode *vp;
1343 
1344 	lwkt_gettoken(&ilock, &spechash_token);
1345 	SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1346 		if (type == vp->v_type) {
1347 			*vpp = vp;
1348 			vref(vp);
1349 			lwkt_reltoken(&ilock);
1350 			return (1);
1351 		}
1352 	}
1353 	lwkt_reltoken(&ilock);
1354 	return (0);
1355 }
1356 
1357 /*
1358  * Calculate the total number of references to a special device.  This
1359  * routine may only be called for VBLK and VCHR vnodes since v_rdev is
1360  * an overloaded field.  Since udev2dev can now return NULL, we have
1361  * to check for a NULL v_rdev.
1362  */
1363 int
1364 count_dev(cdev_t dev)
1365 {
1366 	lwkt_tokref ilock;
1367 	struct vnode *vp;
1368 	int count = 0;
1369 
1370 	if (SLIST_FIRST(&dev->si_hlist)) {
1371 		lwkt_gettoken(&ilock, &spechash_token);
1372 		SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1373 			count += vp->v_opencount;
1374 		}
1375 		lwkt_reltoken(&ilock);
1376 	}
1377 	return(count);
1378 }
1379 
1380 int
1381 vcount(struct vnode *vp)
1382 {
1383 	if (vp->v_rdev == NULL)
1384 		return(0);
1385 	return(count_dev(vp->v_rdev));
1386 }
1387 
1388 /*
1389  * Initialize VMIO for a vnode.  This routine MUST be called before a
1390  * VFS can issue buffer cache ops on a vnode.  It is typically called
1391  * when a vnode is initialized from its inode.
1392  */
1393 int
1394 vinitvmio(struct vnode *vp, off_t filesize)
1395 {
1396 	vm_object_t object;
1397 	int error = 0;
1398 
1399 retry:
1400 	if ((object = vp->v_object) == NULL) {
1401 		object = vnode_pager_alloc(vp, filesize, 0, 0);
1402 		/*
1403 		 * Dereference the reference we just created.  This assumes
1404 		 * that the object is associated with the vp.
1405 		 */
1406 		object->ref_count--;
1407 		vrele(vp);
1408 	} else {
1409 		if (object->flags & OBJ_DEAD) {
1410 			vn_unlock(vp);
1411 			vm_object_dead_sleep(object, "vodead");
1412 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1413 			goto retry;
1414 		}
1415 	}
1416 	KASSERT(vp->v_object != NULL, ("vinitvmio: NULL object"));
1417 	vsetflags(vp, VOBJBUF);
1418 	return (error);
1419 }
1420 
1421 
1422 /*
1423  * Print out a description of a vnode.
1424  */
1425 static char *typename[] =
1426 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
1427 
1428 void
1429 vprint(char *label, struct vnode *vp)
1430 {
1431 	char buf[96];
1432 
1433 	if (label != NULL)
1434 		kprintf("%s: %p: ", label, (void *)vp);
1435 	else
1436 		kprintf("%p: ", (void *)vp);
1437 	kprintf("type %s, sysrefs %d, writecount %d, holdcnt %d,",
1438 		typename[vp->v_type],
1439 		vp->v_sysref.refcnt, vp->v_writecount, vp->v_auxrefs);
1440 	buf[0] = '\0';
1441 	if (vp->v_flag & VROOT)
1442 		strcat(buf, "|VROOT");
1443 	if (vp->v_flag & VPFSROOT)
1444 		strcat(buf, "|VPFSROOT");
1445 	if (vp->v_flag & VTEXT)
1446 		strcat(buf, "|VTEXT");
1447 	if (vp->v_flag & VSYSTEM)
1448 		strcat(buf, "|VSYSTEM");
1449 	if (vp->v_flag & VFREE)
1450 		strcat(buf, "|VFREE");
1451 	if (vp->v_flag & VOBJBUF)
1452 		strcat(buf, "|VOBJBUF");
1453 	if (buf[0] != '\0')
1454 		kprintf(" flags (%s)", &buf[1]);
1455 	if (vp->v_data == NULL) {
1456 		kprintf("\n");
1457 	} else {
1458 		kprintf("\n\t");
1459 		VOP_PRINT(vp);
1460 	}
1461 }
1462 
1463 /*
1464  * Do the usual access checking.
1465  * file_mode, uid and gid are from the vnode in question,
1466  * while acc_mode and cred are from the VOP_ACCESS parameter list
1467  */
1468 int
1469 vaccess(enum vtype type, mode_t file_mode, uid_t uid, gid_t gid,
1470     mode_t acc_mode, struct ucred *cred)
1471 {
1472 	mode_t mask;
1473 	int ismember;
1474 
1475 	/*
1476 	 * Super-user always gets read/write access, but execute access depends
1477 	 * on at least one execute bit being set.
1478 	 */
1479 	if (priv_check_cred(cred, PRIV_ROOT, 0) == 0) {
1480 		if ((acc_mode & VEXEC) && type != VDIR &&
1481 		    (file_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0)
1482 			return (EACCES);
1483 		return (0);
1484 	}
1485 
1486 	mask = 0;
1487 
1488 	/* Otherwise, check the owner. */
1489 	if (cred->cr_uid == uid) {
1490 		if (acc_mode & VEXEC)
1491 			mask |= S_IXUSR;
1492 		if (acc_mode & VREAD)
1493 			mask |= S_IRUSR;
1494 		if (acc_mode & VWRITE)
1495 			mask |= S_IWUSR;
1496 		return ((file_mode & mask) == mask ? 0 : EACCES);
1497 	}
1498 
1499 	/* Otherwise, check the groups. */
1500 	ismember = groupmember(gid, cred);
1501 	if (cred->cr_svgid == gid || ismember) {
1502 		if (acc_mode & VEXEC)
1503 			mask |= S_IXGRP;
1504 		if (acc_mode & VREAD)
1505 			mask |= S_IRGRP;
1506 		if (acc_mode & VWRITE)
1507 			mask |= S_IWGRP;
1508 		return ((file_mode & mask) == mask ? 0 : EACCES);
1509 	}
1510 
1511 	/* Otherwise, check everyone else. */
1512 	if (acc_mode & VEXEC)
1513 		mask |= S_IXOTH;
1514 	if (acc_mode & VREAD)
1515 		mask |= S_IROTH;
1516 	if (acc_mode & VWRITE)
1517 		mask |= S_IWOTH;
1518 	return ((file_mode & mask) == mask ? 0 : EACCES);
1519 }
1520 
1521 #ifdef DDB
1522 #include <ddb/ddb.h>
1523 
1524 static int db_show_locked_vnodes(struct mount *mp, void *data);
1525 
1526 /*
1527  * List all of the locked vnodes in the system.
1528  * Called when debugging the kernel.
1529  */
1530 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
1531 {
1532 	kprintf("Locked vnodes\n");
1533 	mountlist_scan(db_show_locked_vnodes, NULL,
1534 			MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1535 }
1536 
1537 static int
1538 db_show_locked_vnodes(struct mount *mp, void *data __unused)
1539 {
1540 	struct vnode *vp;
1541 
1542 	TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
1543 		if (vn_islocked(vp))
1544 			vprint(NULL, vp);
1545 	}
1546 	return(0);
1547 }
1548 #endif
1549 
1550 /*
1551  * Top level filesystem related information gathering.
1552  */
1553 static int	sysctl_ovfs_conf (SYSCTL_HANDLER_ARGS);
1554 
1555 static int
1556 vfs_sysctl(SYSCTL_HANDLER_ARGS)
1557 {
1558 	int *name = (int *)arg1 - 1;	/* XXX */
1559 	u_int namelen = arg2 + 1;	/* XXX */
1560 	struct vfsconf *vfsp;
1561 	int maxtypenum;
1562 
1563 #if 1 || defined(COMPAT_PRELITE2)
1564 	/* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
1565 	if (namelen == 1)
1566 		return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
1567 #endif
1568 
1569 #ifdef notyet
1570 	/* all sysctl names at this level are at least name and field */
1571 	if (namelen < 2)
1572 		return (ENOTDIR);		/* overloaded */
1573 	if (name[0] != VFS_GENERIC) {
1574 		vfsp = vfsconf_find_by_typenum(name[0]);
1575 		if (vfsp == NULL)
1576 			return (EOPNOTSUPP);
1577 		return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
1578 		    oldp, oldlenp, newp, newlen, p));
1579 	}
1580 #endif
1581 	switch (name[1]) {
1582 	case VFS_MAXTYPENUM:
1583 		if (namelen != 2)
1584 			return (ENOTDIR);
1585 		maxtypenum = vfsconf_get_maxtypenum();
1586 		return (SYSCTL_OUT(req, &maxtypenum, sizeof(maxtypenum)));
1587 	case VFS_CONF:
1588 		if (namelen != 3)
1589 			return (ENOTDIR);	/* overloaded */
1590 		vfsp = vfsconf_find_by_typenum(name[2]);
1591 		if (vfsp == NULL)
1592 			return (EOPNOTSUPP);
1593 		return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
1594 	}
1595 	return (EOPNOTSUPP);
1596 }
1597 
1598 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
1599 	"Generic filesystem");
1600 
1601 #if 1 || defined(COMPAT_PRELITE2)
1602 
1603 static int
1604 sysctl_ovfs_conf_iter(struct vfsconf *vfsp, void *data)
1605 {
1606 	int error;
1607 	struct ovfsconf ovfs;
1608 	struct sysctl_req *req = (struct sysctl_req*) data;
1609 
1610 	bzero(&ovfs, sizeof(ovfs));
1611 	ovfs.vfc_vfsops = vfsp->vfc_vfsops;	/* XXX used as flag */
1612 	strcpy(ovfs.vfc_name, vfsp->vfc_name);
1613 	ovfs.vfc_index = vfsp->vfc_typenum;
1614 	ovfs.vfc_refcount = vfsp->vfc_refcount;
1615 	ovfs.vfc_flags = vfsp->vfc_flags;
1616 	error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
1617 	if (error)
1618 		return error; /* abort iteration with error code */
1619 	else
1620 		return 0; /* continue iterating with next element */
1621 }
1622 
1623 static int
1624 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
1625 {
1626 	return vfsconf_each(sysctl_ovfs_conf_iter, (void*)req);
1627 }
1628 
1629 #endif /* 1 || COMPAT_PRELITE2 */
1630 
1631 /*
1632  * Check to see if a filesystem is mounted on a block device.
1633  */
1634 int
1635 vfs_mountedon(struct vnode *vp)
1636 {
1637 	cdev_t dev;
1638 
1639 	if ((dev = vp->v_rdev) == NULL) {
1640 /*		if (vp->v_type != VBLK)
1641 			dev = get_dev(vp->v_uminor, vp->v_umajor); */
1642 	}
1643 	if (dev != NULL && dev->si_mountpoint)
1644 		return (EBUSY);
1645 	return (0);
1646 }
1647 
1648 /*
1649  * Unmount all filesystems. The list is traversed in reverse order
1650  * of mounting to avoid dependencies.
1651  */
1652 
1653 static int vfs_umountall_callback(struct mount *mp, void *data);
1654 
1655 void
1656 vfs_unmountall(void)
1657 {
1658 	int count;
1659 
1660 	do {
1661 		count = mountlist_scan(vfs_umountall_callback,
1662 					NULL, MNTSCAN_REVERSE|MNTSCAN_NOBUSY);
1663 	} while (count);
1664 }
1665 
1666 static
1667 int
1668 vfs_umountall_callback(struct mount *mp, void *data)
1669 {
1670 	int error;
1671 
1672 	error = dounmount(mp, MNT_FORCE);
1673 	if (error) {
1674 		mountlist_remove(mp);
1675 		kprintf("unmount of filesystem mounted from %s failed (",
1676 			mp->mnt_stat.f_mntfromname);
1677 		if (error == EBUSY)
1678 			kprintf("BUSY)\n");
1679 		else
1680 			kprintf("%d)\n", error);
1681 	}
1682 	return(1);
1683 }
1684 
1685 /*
1686  * Checks the mount flags for parameter mp and put the names comma-separated
1687  * into a string buffer buf with a size limit specified by len.
1688  *
1689  * It returns the number of bytes written into buf, and (*errorp) will be
1690  * set to 0, EINVAL (if passed length is 0), or ENOSPC (supplied buffer was
1691  * not large enough).  The buffer will be 0-terminated if len was not 0.
1692  */
1693 size_t
1694 vfs_flagstostr(int flags, const struct mountctl_opt *optp,
1695 	       char *buf, size_t len, int *errorp)
1696 {
1697 	static const struct mountctl_opt optnames[] = {
1698 		{ MNT_ASYNC,            "asynchronous" },
1699 		{ MNT_EXPORTED,         "NFS exported" },
1700 		{ MNT_LOCAL,            "local" },
1701 		{ MNT_NOATIME,          "noatime" },
1702 		{ MNT_NODEV,            "nodev" },
1703 		{ MNT_NOEXEC,           "noexec" },
1704 		{ MNT_NOSUID,           "nosuid" },
1705 		{ MNT_NOSYMFOLLOW,      "nosymfollow" },
1706 		{ MNT_QUOTA,            "with-quotas" },
1707 		{ MNT_RDONLY,           "read-only" },
1708 		{ MNT_SYNCHRONOUS,      "synchronous" },
1709 		{ MNT_UNION,            "union" },
1710 		{ MNT_NOCLUSTERR,       "noclusterr" },
1711 		{ MNT_NOCLUSTERW,       "noclusterw" },
1712 		{ MNT_SUIDDIR,          "suiddir" },
1713 		{ MNT_SOFTDEP,          "soft-updates" },
1714 		{ MNT_IGNORE,           "ignore" },
1715 		{ 0,			NULL}
1716 	};
1717 	int bwritten;
1718 	int bleft;
1719 	int optlen;
1720 	int actsize;
1721 
1722 	*errorp = 0;
1723 	bwritten = 0;
1724 	bleft = len - 1;	/* leave room for trailing \0 */
1725 
1726 	/*
1727 	 * Checks the size of the string. If it contains
1728 	 * any data, then we will append the new flags to
1729 	 * it.
1730 	 */
1731 	actsize = strlen(buf);
1732 	if (actsize > 0)
1733 		buf += actsize;
1734 
1735 	/* Default flags if no flags passed */
1736 	if (optp == NULL)
1737 		optp = optnames;
1738 
1739 	if (bleft < 0) {	/* degenerate case, 0-length buffer */
1740 		*errorp = EINVAL;
1741 		return(0);
1742 	}
1743 
1744 	for (; flags && optp->o_opt; ++optp) {
1745 		if ((flags & optp->o_opt) == 0)
1746 			continue;
1747 		optlen = strlen(optp->o_name);
1748 		if (bwritten || actsize > 0) {
1749 			if (bleft < 2) {
1750 				*errorp = ENOSPC;
1751 				break;
1752 			}
1753 			buf[bwritten++] = ',';
1754 			buf[bwritten++] = ' ';
1755 			bleft -= 2;
1756 		}
1757 		if (bleft < optlen) {
1758 			*errorp = ENOSPC;
1759 			break;
1760 		}
1761 		bcopy(optp->o_name, buf + bwritten, optlen);
1762 		bwritten += optlen;
1763 		bleft -= optlen;
1764 		flags &= ~optp->o_opt;
1765 	}
1766 
1767 	/*
1768 	 * Space already reserved for trailing \0
1769 	 */
1770 	buf[bwritten] = 0;
1771 	return (bwritten);
1772 }
1773 
1774 /*
1775  * Build hash lists of net addresses and hang them off the mount point.
1776  * Called by ufs_mount() to set up the lists of export addresses.
1777  */
1778 static int
1779 vfs_hang_addrlist(struct mount *mp, struct netexport *nep,
1780 		const struct export_args *argp)
1781 {
1782 	struct netcred *np;
1783 	struct radix_node_head *rnh;
1784 	int i;
1785 	struct radix_node *rn;
1786 	struct sockaddr *saddr, *smask = 0;
1787 	struct domain *dom;
1788 	int error;
1789 
1790 	if (argp->ex_addrlen == 0) {
1791 		if (mp->mnt_flag & MNT_DEFEXPORTED)
1792 			return (EPERM);
1793 		np = &nep->ne_defexported;
1794 		np->netc_exflags = argp->ex_flags;
1795 		np->netc_anon = argp->ex_anon;
1796 		np->netc_anon.cr_ref = 1;
1797 		mp->mnt_flag |= MNT_DEFEXPORTED;
1798 		return (0);
1799 	}
1800 
1801 	if (argp->ex_addrlen < 0 || argp->ex_addrlen > MLEN)
1802 		return (EINVAL);
1803 	if (argp->ex_masklen < 0 || argp->ex_masklen > MLEN)
1804 		return (EINVAL);
1805 
1806 	i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
1807 	np = (struct netcred *) kmalloc(i, M_NETADDR, M_WAITOK | M_ZERO);
1808 	saddr = (struct sockaddr *) (np + 1);
1809 	if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
1810 		goto out;
1811 	if (saddr->sa_len > argp->ex_addrlen)
1812 		saddr->sa_len = argp->ex_addrlen;
1813 	if (argp->ex_masklen) {
1814 		smask = (struct sockaddr *)((caddr_t)saddr + argp->ex_addrlen);
1815 		error = copyin(argp->ex_mask, (caddr_t)smask, argp->ex_masklen);
1816 		if (error)
1817 			goto out;
1818 		if (smask->sa_len > argp->ex_masklen)
1819 			smask->sa_len = argp->ex_masklen;
1820 	}
1821 	i = saddr->sa_family;
1822 	if ((rnh = nep->ne_rtable[i]) == 0) {
1823 		/*
1824 		 * Seems silly to initialize every AF when most are not used,
1825 		 * do so on demand here
1826 		 */
1827 		SLIST_FOREACH(dom, &domains, dom_next)
1828 			if (dom->dom_family == i && dom->dom_rtattach) {
1829 				dom->dom_rtattach((void **) &nep->ne_rtable[i],
1830 				    dom->dom_rtoffset);
1831 				break;
1832 			}
1833 		if ((rnh = nep->ne_rtable[i]) == 0) {
1834 			error = ENOBUFS;
1835 			goto out;
1836 		}
1837 	}
1838 	rn = (*rnh->rnh_addaddr) ((char *) saddr, (char *) smask, rnh,
1839 	    np->netc_rnodes);
1840 	if (rn == 0 || np != (struct netcred *) rn) {	/* already exists */
1841 		error = EPERM;
1842 		goto out;
1843 	}
1844 	np->netc_exflags = argp->ex_flags;
1845 	np->netc_anon = argp->ex_anon;
1846 	np->netc_anon.cr_ref = 1;
1847 	return (0);
1848 out:
1849 	kfree(np, M_NETADDR);
1850 	return (error);
1851 }
1852 
1853 /* ARGSUSED */
1854 static int
1855 vfs_free_netcred(struct radix_node *rn, void *w)
1856 {
1857 	struct radix_node_head *rnh = (struct radix_node_head *) w;
1858 
1859 	(*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
1860 	kfree((caddr_t) rn, M_NETADDR);
1861 	return (0);
1862 }
1863 
1864 /*
1865  * Free the net address hash lists that are hanging off the mount points.
1866  */
1867 static void
1868 vfs_free_addrlist(struct netexport *nep)
1869 {
1870 	int i;
1871 	struct radix_node_head *rnh;
1872 
1873 	for (i = 0; i <= AF_MAX; i++)
1874 		if ((rnh = nep->ne_rtable[i])) {
1875 			(*rnh->rnh_walktree) (rnh, vfs_free_netcred,
1876 			    (caddr_t) rnh);
1877 			kfree((caddr_t) rnh, M_RTABLE);
1878 			nep->ne_rtable[i] = 0;
1879 		}
1880 }
1881 
1882 int
1883 vfs_export(struct mount *mp, struct netexport *nep,
1884 	   const struct export_args *argp)
1885 {
1886 	int error;
1887 
1888 	if (argp->ex_flags & MNT_DELEXPORT) {
1889 		if (mp->mnt_flag & MNT_EXPUBLIC) {
1890 			vfs_setpublicfs(NULL, NULL, NULL);
1891 			mp->mnt_flag &= ~MNT_EXPUBLIC;
1892 		}
1893 		vfs_free_addrlist(nep);
1894 		mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
1895 	}
1896 	if (argp->ex_flags & MNT_EXPORTED) {
1897 		if (argp->ex_flags & MNT_EXPUBLIC) {
1898 			if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
1899 				return (error);
1900 			mp->mnt_flag |= MNT_EXPUBLIC;
1901 		}
1902 		if ((error = vfs_hang_addrlist(mp, nep, argp)))
1903 			return (error);
1904 		mp->mnt_flag |= MNT_EXPORTED;
1905 	}
1906 	return (0);
1907 }
1908 
1909 
1910 /*
1911  * Set the publicly exported filesystem (WebNFS). Currently, only
1912  * one public filesystem is possible in the spec (RFC 2054 and 2055)
1913  */
1914 int
1915 vfs_setpublicfs(struct mount *mp, struct netexport *nep,
1916 		const struct export_args *argp)
1917 {
1918 	int error;
1919 	struct vnode *rvp;
1920 	char *cp;
1921 
1922 	/*
1923 	 * mp == NULL -> invalidate the current info, the FS is
1924 	 * no longer exported. May be called from either vfs_export
1925 	 * or unmount, so check if it hasn't already been done.
1926 	 */
1927 	if (mp == NULL) {
1928 		if (nfs_pub.np_valid) {
1929 			nfs_pub.np_valid = 0;
1930 			if (nfs_pub.np_index != NULL) {
1931 				FREE(nfs_pub.np_index, M_TEMP);
1932 				nfs_pub.np_index = NULL;
1933 			}
1934 		}
1935 		return (0);
1936 	}
1937 
1938 	/*
1939 	 * Only one allowed at a time.
1940 	 */
1941 	if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
1942 		return (EBUSY);
1943 
1944 	/*
1945 	 * Get real filehandle for root of exported FS.
1946 	 */
1947 	bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
1948 	nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
1949 
1950 	if ((error = VFS_ROOT(mp, &rvp)))
1951 		return (error);
1952 
1953 	if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
1954 		return (error);
1955 
1956 	vput(rvp);
1957 
1958 	/*
1959 	 * If an indexfile was specified, pull it in.
1960 	 */
1961 	if (argp->ex_indexfile != NULL) {
1962 		int namelen;
1963 
1964 		error = vn_get_namelen(rvp, &namelen);
1965 		if (error)
1966 			return (error);
1967 		MALLOC(nfs_pub.np_index, char *, namelen, M_TEMP,
1968 		    M_WAITOK);
1969 		error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
1970 		    namelen, NULL);
1971 		if (!error) {
1972 			/*
1973 			 * Check for illegal filenames.
1974 			 */
1975 			for (cp = nfs_pub.np_index; *cp; cp++) {
1976 				if (*cp == '/') {
1977 					error = EINVAL;
1978 					break;
1979 				}
1980 			}
1981 		}
1982 		if (error) {
1983 			FREE(nfs_pub.np_index, M_TEMP);
1984 			return (error);
1985 		}
1986 	}
1987 
1988 	nfs_pub.np_mount = mp;
1989 	nfs_pub.np_valid = 1;
1990 	return (0);
1991 }
1992 
1993 struct netcred *
1994 vfs_export_lookup(struct mount *mp, struct netexport *nep,
1995 		struct sockaddr *nam)
1996 {
1997 	struct netcred *np;
1998 	struct radix_node_head *rnh;
1999 	struct sockaddr *saddr;
2000 
2001 	np = NULL;
2002 	if (mp->mnt_flag & MNT_EXPORTED) {
2003 		/*
2004 		 * Lookup in the export list first.
2005 		 */
2006 		if (nam != NULL) {
2007 			saddr = nam;
2008 			rnh = nep->ne_rtable[saddr->sa_family];
2009 			if (rnh != NULL) {
2010 				np = (struct netcred *)
2011 					(*rnh->rnh_matchaddr)((char *)saddr,
2012 							      rnh);
2013 				if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
2014 					np = NULL;
2015 			}
2016 		}
2017 		/*
2018 		 * If no address match, use the default if it exists.
2019 		 */
2020 		if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
2021 			np = &nep->ne_defexported;
2022 	}
2023 	return (np);
2024 }
2025 
2026 /*
2027  * perform msync on all vnodes under a mount point.  The mount point must
2028  * be locked.  This code is also responsible for lazy-freeing unreferenced
2029  * vnodes whos VM objects no longer contain pages.
2030  *
2031  * NOTE: MNT_WAIT still skips vnodes in the VXLOCK state.
2032  *
2033  * NOTE: XXX VOP_PUTPAGES and friends requires that the vnode be locked,
2034  * but vnode_pager_putpages() doesn't lock the vnode.  We have to do it
2035  * way up in this high level function.
2036  */
2037 static int vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data);
2038 static int vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data);
2039 
2040 void
2041 vfs_msync(struct mount *mp, int flags)
2042 {
2043 	int vmsc_flags;
2044 
2045 	vmsc_flags = VMSC_GETVP;
2046 	if (flags != MNT_WAIT)
2047 		vmsc_flags |= VMSC_NOWAIT;
2048 	vmntvnodescan(mp, vmsc_flags, vfs_msync_scan1, vfs_msync_scan2,
2049 			(void *)(intptr_t)flags);
2050 }
2051 
2052 /*
2053  * scan1 is a fast pre-check.  There could be hundreds of thousands of
2054  * vnodes, we cannot afford to do anything heavy weight until we have a
2055  * fairly good indication that there is work to do.
2056  */
2057 static
2058 int
2059 vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data)
2060 {
2061 	int flags = (int)(intptr_t)data;
2062 
2063 	if ((vp->v_flag & VRECLAIMED) == 0) {
2064 		if (vshouldmsync(vp))
2065 			return(0);	/* call scan2 */
2066 		if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
2067 		    (vp->v_flag & VOBJDIRTY) &&
2068 		    (flags == MNT_WAIT || vn_islocked(vp) == 0)) {
2069 			return(0);	/* call scan2 */
2070 		}
2071 	}
2072 
2073 	/*
2074 	 * do not call scan2, continue the loop
2075 	 */
2076 	return(-1);
2077 }
2078 
2079 /*
2080  * This callback is handed a locked vnode.
2081  */
2082 static
2083 int
2084 vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data)
2085 {
2086 	vm_object_t obj;
2087 	int flags = (int)(intptr_t)data;
2088 
2089 	if (vp->v_flag & VRECLAIMED)
2090 		return(0);
2091 
2092 	if ((mp->mnt_flag & MNT_RDONLY) == 0 && (vp->v_flag & VOBJDIRTY)) {
2093 		if ((obj = vp->v_object) != NULL) {
2094 			vm_object_page_clean(obj, 0, 0,
2095 			 flags == MNT_WAIT ? OBJPC_SYNC : OBJPC_NOSYNC);
2096 		}
2097 	}
2098 	return(0);
2099 }
2100 
2101 /*
2102  * Record a process's interest in events which might happen to
2103  * a vnode.  Because poll uses the historic select-style interface
2104  * internally, this routine serves as both the ``check for any
2105  * pending events'' and the ``record my interest in future events''
2106  * functions.  (These are done together, while the lock is held,
2107  * to avoid race conditions.)
2108  */
2109 int
2110 vn_pollrecord(struct vnode *vp, int events)
2111 {
2112 	lwkt_tokref vlock;
2113 
2114 	KKASSERT(curthread->td_proc != NULL);
2115 
2116 	lwkt_gettoken(&vlock, &vp->v_token);
2117 	if (vp->v_pollinfo.vpi_revents & events) {
2118 		/*
2119 		 * This leaves events we are not interested
2120 		 * in available for the other process which
2121 		 * which presumably had requested them
2122 		 * (otherwise they would never have been
2123 		 * recorded).
2124 		 */
2125 		events &= vp->v_pollinfo.vpi_revents;
2126 		vp->v_pollinfo.vpi_revents &= ~events;
2127 
2128 		lwkt_reltoken(&vlock);
2129 		return events;
2130 	}
2131 	vp->v_pollinfo.vpi_events |= events;
2132 	selrecord(curthread, &vp->v_pollinfo.vpi_selinfo);
2133 	lwkt_reltoken(&vlock);
2134 	return 0;
2135 }
2136 
2137 /*
2138  * Note the occurrence of an event.  If the VN_POLLEVENT macro is used,
2139  * it is possible for us to miss an event due to race conditions, but
2140  * that condition is expected to be rare, so for the moment it is the
2141  * preferred interface.
2142  */
2143 void
2144 vn_pollevent(struct vnode *vp, int events)
2145 {
2146 	lwkt_tokref vlock;
2147 
2148 	lwkt_gettoken(&vlock, &vp->v_token);
2149 	if (vp->v_pollinfo.vpi_events & events) {
2150 		/*
2151 		 * We clear vpi_events so that we don't
2152 		 * call selwakeup() twice if two events are
2153 		 * posted before the polling process(es) is
2154 		 * awakened.  This also ensures that we take at
2155 		 * most one selwakeup() if the polling process
2156 		 * is no longer interested.  However, it does
2157 		 * mean that only one event can be noticed at
2158 		 * a time.  (Perhaps we should only clear those
2159 		 * event bits which we note?) XXX
2160 		 */
2161 		vp->v_pollinfo.vpi_events = 0;	/* &= ~events ??? */
2162 		vp->v_pollinfo.vpi_revents |= events;
2163 		selwakeup(&vp->v_pollinfo.vpi_selinfo);
2164 	}
2165 	lwkt_reltoken(&vlock);
2166 }
2167 
2168 /*
2169  * Wake up anyone polling on vp because it is being revoked.
2170  * This depends on dead_poll() returning POLLHUP for correct
2171  * behavior.
2172  */
2173 void
2174 vn_pollgone(struct vnode *vp)
2175 {
2176 	lwkt_tokref vlock;
2177 
2178 	lwkt_gettoken(&vlock, &vp->v_token);
2179 	if (vp->v_pollinfo.vpi_events) {
2180 		vp->v_pollinfo.vpi_events = 0;
2181 		selwakeup(&vp->v_pollinfo.vpi_selinfo);
2182 	}
2183 	lwkt_reltoken(&vlock);
2184 }
2185 
2186 /*
2187  * extract the cdev_t from a VBLK or VCHR.  The vnode must have been opened
2188  * (or v_rdev might be NULL).
2189  */
2190 cdev_t
2191 vn_todev(struct vnode *vp)
2192 {
2193 	if (vp->v_type != VBLK && vp->v_type != VCHR)
2194 		return (NULL);
2195 	KKASSERT(vp->v_rdev != NULL);
2196 	return (vp->v_rdev);
2197 }
2198 
2199 /*
2200  * Check if vnode represents a disk device.  The vnode does not need to be
2201  * opened.
2202  *
2203  * MPALMOSTSAFE
2204  */
2205 int
2206 vn_isdisk(struct vnode *vp, int *errp)
2207 {
2208 	cdev_t dev;
2209 
2210 	if (vp->v_type != VCHR) {
2211 		if (errp != NULL)
2212 			*errp = ENOTBLK;
2213 		return (0);
2214 	}
2215 
2216 	dev = vp->v_rdev;
2217 
2218 	if (dev == NULL) {
2219 		if (errp != NULL)
2220 			*errp = ENXIO;
2221 		return (0);
2222 	}
2223 	if (dev_is_good(dev) == 0) {
2224 		if (errp != NULL)
2225 			*errp = ENXIO;
2226 		return (0);
2227 	}
2228 	if ((dev_dflags(dev) & D_DISK) == 0) {
2229 		if (errp != NULL)
2230 			*errp = ENOTBLK;
2231 		return (0);
2232 	}
2233 	if (errp != NULL)
2234 		*errp = 0;
2235 	return (1);
2236 }
2237 
2238 int
2239 vn_get_namelen(struct vnode *vp, int *namelen)
2240 {
2241 	int error;
2242 	register_t retval[2];
2243 
2244 	error = VOP_PATHCONF(vp, _PC_NAME_MAX, retval);
2245 	if (error)
2246 		return (error);
2247 	*namelen = (int)retval[0];
2248 	return (0);
2249 }
2250 
2251 int
2252 vop_write_dirent(int *error, struct uio *uio, ino_t d_ino, uint8_t d_type,
2253 		uint16_t d_namlen, const char *d_name)
2254 {
2255 	struct dirent *dp;
2256 	size_t len;
2257 
2258 	len = _DIRENT_RECLEN(d_namlen);
2259 	if (len > uio->uio_resid)
2260 		return(1);
2261 
2262 	dp = kmalloc(len, M_TEMP, M_WAITOK | M_ZERO);
2263 
2264 	dp->d_ino = d_ino;
2265 	dp->d_namlen = d_namlen;
2266 	dp->d_type = d_type;
2267 	bcopy(d_name, dp->d_name, d_namlen);
2268 
2269 	*error = uiomove((caddr_t)dp, len, uio);
2270 
2271 	kfree(dp, M_TEMP);
2272 
2273 	return(0);
2274 }
2275 
2276 void
2277 vn_mark_atime(struct vnode *vp, struct thread *td)
2278 {
2279 	struct proc *p = td->td_proc;
2280 	struct ucred *cred = p ? p->p_ucred : proc0.p_ucred;
2281 
2282 	if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
2283 		VOP_MARKATIME(vp, cred);
2284 	}
2285 }
2286