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