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