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