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