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