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