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