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