xref: /freebsd/sys/kern/vfs_subr.c (revision b0ee263dbd3552d5b1776be0efc1c2d105f873b1)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)vfs_subr.c	8.31 (Berkeley) 5/26/95
37  */
38 
39 /*
40  * External virtual filesystem routines
41  */
42 
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45 
46 #include "opt_ddb.h"
47 #include "opt_watchdog.h"
48 
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/bio.h>
52 #include <sys/buf.h>
53 #include <sys/capsicum.h>
54 #include <sys/condvar.h>
55 #include <sys/conf.h>
56 #include <sys/counter.h>
57 #include <sys/dirent.h>
58 #include <sys/event.h>
59 #include <sys/eventhandler.h>
60 #include <sys/extattr.h>
61 #include <sys/file.h>
62 #include <sys/fcntl.h>
63 #include <sys/jail.h>
64 #include <sys/kdb.h>
65 #include <sys/kernel.h>
66 #include <sys/kthread.h>
67 #include <sys/ktr.h>
68 #include <sys/lockf.h>
69 #include <sys/malloc.h>
70 #include <sys/mount.h>
71 #include <sys/namei.h>
72 #include <sys/pctrie.h>
73 #include <sys/priv.h>
74 #include <sys/reboot.h>
75 #include <sys/refcount.h>
76 #include <sys/rwlock.h>
77 #include <sys/sched.h>
78 #include <sys/sleepqueue.h>
79 #include <sys/smr.h>
80 #include <sys/smp.h>
81 #include <sys/stat.h>
82 #include <sys/sysctl.h>
83 #include <sys/syslog.h>
84 #include <sys/vmmeter.h>
85 #include <sys/vnode.h>
86 #include <sys/watchdog.h>
87 
88 #include <machine/stdarg.h>
89 
90 #include <security/mac/mac_framework.h>
91 
92 #include <vm/vm.h>
93 #include <vm/vm_object.h>
94 #include <vm/vm_extern.h>
95 #include <vm/pmap.h>
96 #include <vm/vm_map.h>
97 #include <vm/vm_page.h>
98 #include <vm/vm_kern.h>
99 #include <vm/uma.h>
100 
101 #ifdef DDB
102 #include <ddb/ddb.h>
103 #endif
104 
105 static void	delmntque(struct vnode *vp);
106 static int	flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
107 		    int slpflag, int slptimeo);
108 static void	syncer_shutdown(void *arg, int howto);
109 static int	vtryrecycle(struct vnode *vp);
110 static void	v_init_counters(struct vnode *);
111 static void	v_incr_devcount(struct vnode *);
112 static void	v_decr_devcount(struct vnode *);
113 static void	vgonel(struct vnode *);
114 static void	vfs_knllock(void *arg);
115 static void	vfs_knlunlock(void *arg);
116 static void	vfs_knl_assert_locked(void *arg);
117 static void	vfs_knl_assert_unlocked(void *arg);
118 static void	destroy_vpollinfo(struct vpollinfo *vi);
119 static int	v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
120 		    daddr_t startlbn, daddr_t endlbn);
121 static void	vnlru_recalc(void);
122 
123 /*
124  * These fences are intended for cases where some synchronization is
125  * needed between access of v_iflags and lockless vnode refcount (v_holdcnt
126  * and v_usecount) updates.  Access to v_iflags is generally synchronized
127  * by the interlock, but we have some internal assertions that check vnode
128  * flags without acquiring the lock.  Thus, these fences are INVARIANTS-only
129  * for now.
130  */
131 #ifdef INVARIANTS
132 #define	VNODE_REFCOUNT_FENCE_ACQ()	atomic_thread_fence_acq()
133 #define	VNODE_REFCOUNT_FENCE_REL()	atomic_thread_fence_rel()
134 #else
135 #define	VNODE_REFCOUNT_FENCE_ACQ()
136 #define	VNODE_REFCOUNT_FENCE_REL()
137 #endif
138 
139 /*
140  * Number of vnodes in existence.  Increased whenever getnewvnode()
141  * allocates a new vnode, decreased in vdropl() for VIRF_DOOMED vnode.
142  */
143 static u_long __exclusive_cache_line numvnodes;
144 
145 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
146     "Number of vnodes in existence");
147 
148 static counter_u64_t vnodes_created;
149 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
150     "Number of vnodes created by getnewvnode");
151 
152 /*
153  * Conversion tables for conversion from vnode types to inode formats
154  * and back.
155  */
156 enum vtype iftovt_tab[16] = {
157 	VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
158 	VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
159 };
160 int vttoif_tab[10] = {
161 	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
162 	S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
163 };
164 
165 /*
166  * List of allocates vnodes in the system.
167  */
168 static TAILQ_HEAD(freelst, vnode) vnode_list;
169 static struct vnode *vnode_list_free_marker;
170 static struct vnode *vnode_list_reclaim_marker;
171 
172 /*
173  * "Free" vnode target.  Free vnodes are rarely completely free, but are
174  * just ones that are cheap to recycle.  Usually they are for files which
175  * have been stat'd but not read; these usually have inode and namecache
176  * data attached to them.  This target is the preferred minimum size of a
177  * sub-cache consisting mostly of such files. The system balances the size
178  * of this sub-cache with its complement to try to prevent either from
179  * thrashing while the other is relatively inactive.  The targets express
180  * a preference for the best balance.
181  *
182  * "Above" this target there are 2 further targets (watermarks) related
183  * to recyling of free vnodes.  In the best-operating case, the cache is
184  * exactly full, the free list has size between vlowat and vhiwat above the
185  * free target, and recycling from it and normal use maintains this state.
186  * Sometimes the free list is below vlowat or even empty, but this state
187  * is even better for immediate use provided the cache is not full.
188  * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
189  * ones) to reach one of these states.  The watermarks are currently hard-
190  * coded as 4% and 9% of the available space higher.  These and the default
191  * of 25% for wantfreevnodes are too large if the memory size is large.
192  * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
193  * whenever vnlru_proc() becomes active.
194  */
195 static long wantfreevnodes;
196 static long __exclusive_cache_line freevnodes;
197 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
198     &freevnodes, 0, "Number of \"free\" vnodes");
199 static long freevnodes_old;
200 
201 static counter_u64_t recycles_count;
202 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
203     "Number of vnodes recycled to meet vnode cache targets");
204 
205 static counter_u64_t recycles_free_count;
206 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD, &recycles_free_count,
207     "Number of free vnodes recycled to meet vnode cache targets");
208 
209 /*
210  * Various variables used for debugging the new implementation of
211  * reassignbuf().
212  * XXX these are probably of (very) limited utility now.
213  */
214 static int reassignbufcalls;
215 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW | CTLFLAG_STATS,
216     &reassignbufcalls, 0, "Number of calls to reassignbuf");
217 
218 static counter_u64_t deferred_inact;
219 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, deferred_inact, CTLFLAG_RD, &deferred_inact,
220     "Number of times inactive processing was deferred");
221 
222 /* To keep more than one thread at a time from running vfs_getnewfsid */
223 static struct mtx mntid_mtx;
224 
225 /*
226  * Lock for any access to the following:
227  *	vnode_list
228  *	numvnodes
229  *	freevnodes
230  */
231 static struct mtx __exclusive_cache_line vnode_list_mtx;
232 
233 /* Publicly exported FS */
234 struct nfs_public nfs_pub;
235 
236 static uma_zone_t buf_trie_zone;
237 
238 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
239 static uma_zone_t vnode_zone;
240 static uma_zone_t vnodepoll_zone;
241 
242 __read_frequently smr_t vfs_smr;
243 
244 /*
245  * The workitem queue.
246  *
247  * It is useful to delay writes of file data and filesystem metadata
248  * for tens of seconds so that quickly created and deleted files need
249  * not waste disk bandwidth being created and removed. To realize this,
250  * we append vnodes to a "workitem" queue. When running with a soft
251  * updates implementation, most pending metadata dependencies should
252  * not wait for more than a few seconds. Thus, mounted on block devices
253  * are delayed only about a half the time that file data is delayed.
254  * Similarly, directory updates are more critical, so are only delayed
255  * about a third the time that file data is delayed. Thus, there are
256  * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
257  * one each second (driven off the filesystem syncer process). The
258  * syncer_delayno variable indicates the next queue that is to be processed.
259  * Items that need to be processed soon are placed in this queue:
260  *
261  *	syncer_workitem_pending[syncer_delayno]
262  *
263  * A delay of fifteen seconds is done by placing the request fifteen
264  * entries later in the queue:
265  *
266  *	syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
267  *
268  */
269 static int syncer_delayno;
270 static long syncer_mask;
271 LIST_HEAD(synclist, bufobj);
272 static struct synclist *syncer_workitem_pending;
273 /*
274  * The sync_mtx protects:
275  *	bo->bo_synclist
276  *	sync_vnode_count
277  *	syncer_delayno
278  *	syncer_state
279  *	syncer_workitem_pending
280  *	syncer_worklist_len
281  *	rushjob
282  */
283 static struct mtx sync_mtx;
284 static struct cv sync_wakeup;
285 
286 #define SYNCER_MAXDELAY		32
287 static int syncer_maxdelay = SYNCER_MAXDELAY;	/* maximum delay time */
288 static int syncdelay = 30;		/* max time to delay syncing data */
289 static int filedelay = 30;		/* time to delay syncing files */
290 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
291     "Time to delay syncing files (in seconds)");
292 static int dirdelay = 29;		/* time to delay syncing directories */
293 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
294     "Time to delay syncing directories (in seconds)");
295 static int metadelay = 28;		/* time to delay syncing metadata */
296 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
297     "Time to delay syncing metadata (in seconds)");
298 static int rushjob;		/* number of slots to run ASAP */
299 static int stat_rush_requests;	/* number of times I/O speeded up */
300 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
301     "Number of times I/O speeded up (rush requests)");
302 
303 #define	VDBATCH_SIZE 8
304 struct vdbatch {
305 	u_int index;
306 	long freevnodes;
307 	struct mtx lock;
308 	struct vnode *tab[VDBATCH_SIZE];
309 };
310 DPCPU_DEFINE_STATIC(struct vdbatch, vd);
311 
312 static void	vdbatch_dequeue(struct vnode *vp);
313 
314 /*
315  * When shutting down the syncer, run it at four times normal speed.
316  */
317 #define SYNCER_SHUTDOWN_SPEEDUP		4
318 static int sync_vnode_count;
319 static int syncer_worklist_len;
320 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
321     syncer_state;
322 
323 /* Target for maximum number of vnodes. */
324 u_long desiredvnodes;
325 static u_long gapvnodes;		/* gap between wanted and desired */
326 static u_long vhiwat;		/* enough extras after expansion */
327 static u_long vlowat;		/* minimal extras before expansion */
328 static u_long vstir;		/* nonzero to stir non-free vnodes */
329 static volatile int vsmalltrigger = 8;	/* pref to keep if > this many pages */
330 
331 static u_long vnlru_read_freevnodes(void);
332 
333 /*
334  * Note that no attempt is made to sanitize these parameters.
335  */
336 static int
337 sysctl_maxvnodes(SYSCTL_HANDLER_ARGS)
338 {
339 	u_long val;
340 	int error;
341 
342 	val = desiredvnodes;
343 	error = sysctl_handle_long(oidp, &val, 0, req);
344 	if (error != 0 || req->newptr == NULL)
345 		return (error);
346 
347 	if (val == desiredvnodes)
348 		return (0);
349 	mtx_lock(&vnode_list_mtx);
350 	desiredvnodes = val;
351 	wantfreevnodes = desiredvnodes / 4;
352 	vnlru_recalc();
353 	mtx_unlock(&vnode_list_mtx);
354 	/*
355 	 * XXX There is no protection against multiple threads changing
356 	 * desiredvnodes at the same time. Locking above only helps vnlru and
357 	 * getnewvnode.
358 	 */
359 	vfs_hash_changesize(desiredvnodes);
360 	cache_changesize(desiredvnodes);
361 	return (0);
362 }
363 
364 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
365     CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
366     "LU", "Target for maximum number of vnodes");
367 
368 static int
369 sysctl_wantfreevnodes(SYSCTL_HANDLER_ARGS)
370 {
371 	u_long val;
372 	int error;
373 
374 	val = wantfreevnodes;
375 	error = sysctl_handle_long(oidp, &val, 0, req);
376 	if (error != 0 || req->newptr == NULL)
377 		return (error);
378 
379 	if (val == wantfreevnodes)
380 		return (0);
381 	mtx_lock(&vnode_list_mtx);
382 	wantfreevnodes = val;
383 	vnlru_recalc();
384 	mtx_unlock(&vnode_list_mtx);
385 	return (0);
386 }
387 
388 SYSCTL_PROC(_vfs, OID_AUTO, wantfreevnodes,
389     CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
390     "LU", "Target for minimum number of \"free\" vnodes");
391 
392 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
393     &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
394 static int vnlru_nowhere;
395 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
396     &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
397 
398 static int
399 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
400 {
401 	struct vnode *vp;
402 	struct nameidata nd;
403 	char *buf;
404 	unsigned long ndflags;
405 	int error;
406 
407 	if (req->newptr == NULL)
408 		return (EINVAL);
409 	if (req->newlen >= PATH_MAX)
410 		return (E2BIG);
411 
412 	buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
413 	error = SYSCTL_IN(req, buf, req->newlen);
414 	if (error != 0)
415 		goto out;
416 
417 	buf[req->newlen] = '\0';
418 
419 	ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | NOCACHE | SAVENAME;
420 	NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
421 	if ((error = namei(&nd)) != 0)
422 		goto out;
423 	vp = nd.ni_vp;
424 
425 	if (VN_IS_DOOMED(vp)) {
426 		/*
427 		 * This vnode is being recycled.  Return != 0 to let the caller
428 		 * know that the sysctl had no effect.  Return EAGAIN because a
429 		 * subsequent call will likely succeed (since namei will create
430 		 * a new vnode if necessary)
431 		 */
432 		error = EAGAIN;
433 		goto putvnode;
434 	}
435 
436 	counter_u64_add(recycles_count, 1);
437 	vgone(vp);
438 putvnode:
439 	NDFREE(&nd, 0);
440 out:
441 	free(buf, M_TEMP);
442 	return (error);
443 }
444 
445 static int
446 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
447 {
448 	struct thread *td = curthread;
449 	struct vnode *vp;
450 	struct file *fp;
451 	int error;
452 	int fd;
453 
454 	if (req->newptr == NULL)
455 		return (EBADF);
456 
457         error = sysctl_handle_int(oidp, &fd, 0, req);
458         if (error != 0)
459                 return (error);
460 	error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
461 	if (error != 0)
462 		return (error);
463 	vp = fp->f_vnode;
464 
465 	error = vn_lock(vp, LK_EXCLUSIVE);
466 	if (error != 0)
467 		goto drop;
468 
469 	counter_u64_add(recycles_count, 1);
470 	vgone(vp);
471 	VOP_UNLOCK(vp);
472 drop:
473 	fdrop(fp, td);
474 	return (error);
475 }
476 
477 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
478     CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
479     sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
480 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
481     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
482     sysctl_ftry_reclaim_vnode, "I",
483     "Try to reclaim a vnode by its file descriptor");
484 
485 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
486 static int vnsz2log;
487 
488 /*
489  * Support for the bufobj clean & dirty pctrie.
490  */
491 static void *
492 buf_trie_alloc(struct pctrie *ptree)
493 {
494 
495 	return uma_zalloc(buf_trie_zone, M_NOWAIT);
496 }
497 
498 static void
499 buf_trie_free(struct pctrie *ptree, void *node)
500 {
501 
502 	uma_zfree(buf_trie_zone, node);
503 }
504 PCTRIE_DEFINE(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free);
505 
506 /*
507  * Initialize the vnode management data structures.
508  *
509  * Reevaluate the following cap on the number of vnodes after the physical
510  * memory size exceeds 512GB.  In the limit, as the physical memory size
511  * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
512  */
513 #ifndef	MAXVNODES_MAX
514 #define	MAXVNODES_MAX	(512UL * 1024 * 1024 / 64)	/* 8M */
515 #endif
516 
517 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
518 
519 static struct vnode *
520 vn_alloc_marker(struct mount *mp)
521 {
522 	struct vnode *vp;
523 
524 	vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
525 	vp->v_type = VMARKER;
526 	vp->v_mount = mp;
527 
528 	return (vp);
529 }
530 
531 static void
532 vn_free_marker(struct vnode *vp)
533 {
534 
535 	MPASS(vp->v_type == VMARKER);
536 	free(vp, M_VNODE_MARKER);
537 }
538 
539 /*
540  * Initialize a vnode as it first enters the zone.
541  */
542 static int
543 vnode_init(void *mem, int size, int flags)
544 {
545 	struct vnode *vp;
546 
547 	vp = mem;
548 	bzero(vp, size);
549 	/*
550 	 * Setup locks.
551 	 */
552 	vp->v_vnlock = &vp->v_lock;
553 	mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
554 	/*
555 	 * By default, don't allow shared locks unless filesystems opt-in.
556 	 */
557 	lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
558 	    LK_NOSHARE | LK_IS_VNODE);
559 	/*
560 	 * Initialize bufobj.
561 	 */
562 	bufobj_init(&vp->v_bufobj, vp);
563 	/*
564 	 * Initialize namecache.
565 	 */
566 	LIST_INIT(&vp->v_cache_src);
567 	TAILQ_INIT(&vp->v_cache_dst);
568 	/*
569 	 * Initialize rangelocks.
570 	 */
571 	rangelock_init(&vp->v_rl);
572 
573 	vp->v_dbatchcpu = NOCPU;
574 
575 	mtx_lock(&vnode_list_mtx);
576 	TAILQ_INSERT_BEFORE(vnode_list_free_marker, vp, v_vnodelist);
577 	mtx_unlock(&vnode_list_mtx);
578 	return (0);
579 }
580 
581 /*
582  * Free a vnode when it is cleared from the zone.
583  */
584 static void
585 vnode_fini(void *mem, int size)
586 {
587 	struct vnode *vp;
588 	struct bufobj *bo;
589 
590 	vp = mem;
591 	vdbatch_dequeue(vp);
592 	mtx_lock(&vnode_list_mtx);
593 	TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
594 	mtx_unlock(&vnode_list_mtx);
595 	rangelock_destroy(&vp->v_rl);
596 	lockdestroy(vp->v_vnlock);
597 	mtx_destroy(&vp->v_interlock);
598 	bo = &vp->v_bufobj;
599 	rw_destroy(BO_LOCKPTR(bo));
600 }
601 
602 /*
603  * Provide the size of NFS nclnode and NFS fh for calculation of the
604  * vnode memory consumption.  The size is specified directly to
605  * eliminate dependency on NFS-private header.
606  *
607  * Other filesystems may use bigger or smaller (like UFS and ZFS)
608  * private inode data, but the NFS-based estimation is ample enough.
609  * Still, we care about differences in the size between 64- and 32-bit
610  * platforms.
611  *
612  * Namecache structure size is heuristically
613  * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
614  */
615 #ifdef _LP64
616 #define	NFS_NCLNODE_SZ	(528 + 64)
617 #define	NC_SZ		148
618 #else
619 #define	NFS_NCLNODE_SZ	(360 + 32)
620 #define	NC_SZ		92
621 #endif
622 
623 static void
624 vntblinit(void *dummy __unused)
625 {
626 	struct vdbatch *vd;
627 	int cpu, physvnodes, virtvnodes;
628 	u_int i;
629 
630 	/*
631 	 * Desiredvnodes is a function of the physical memory size and the
632 	 * kernel's heap size.  Generally speaking, it scales with the
633 	 * physical memory size.  The ratio of desiredvnodes to the physical
634 	 * memory size is 1:16 until desiredvnodes exceeds 98,304.
635 	 * Thereafter, the
636 	 * marginal ratio of desiredvnodes to the physical memory size is
637 	 * 1:64.  However, desiredvnodes is limited by the kernel's heap
638 	 * size.  The memory required by desiredvnodes vnodes and vm objects
639 	 * must not exceed 1/10th of the kernel's heap size.
640 	 */
641 	physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
642 	    3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
643 	virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
644 	    sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
645 	desiredvnodes = min(physvnodes, virtvnodes);
646 	if (desiredvnodes > MAXVNODES_MAX) {
647 		if (bootverbose)
648 			printf("Reducing kern.maxvnodes %lu -> %lu\n",
649 			    desiredvnodes, MAXVNODES_MAX);
650 		desiredvnodes = MAXVNODES_MAX;
651 	}
652 	wantfreevnodes = desiredvnodes / 4;
653 	mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
654 	TAILQ_INIT(&vnode_list);
655 	mtx_init(&vnode_list_mtx, "vnode_list", NULL, MTX_DEF);
656 	/*
657 	 * The lock is taken to appease WITNESS.
658 	 */
659 	mtx_lock(&vnode_list_mtx);
660 	vnlru_recalc();
661 	mtx_unlock(&vnode_list_mtx);
662 	vnode_list_free_marker = vn_alloc_marker(NULL);
663 	TAILQ_INSERT_HEAD(&vnode_list, vnode_list_free_marker, v_vnodelist);
664 	vnode_list_reclaim_marker = vn_alloc_marker(NULL);
665 	TAILQ_INSERT_HEAD(&vnode_list, vnode_list_reclaim_marker, v_vnodelist);
666 	vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
667 	    vnode_init, vnode_fini, UMA_ALIGN_PTR, UMA_ZONE_SMR);
668 	vfs_smr = uma_zone_get_smr(vnode_zone);
669 	vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
670 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
671 	/*
672 	 * Preallocate enough nodes to support one-per buf so that
673 	 * we can not fail an insert.  reassignbuf() callers can not
674 	 * tolerate the insertion failure.
675 	 */
676 	buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
677 	    NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
678 	    UMA_ZONE_NOFREE);
679 	uma_prealloc(buf_trie_zone, nbuf);
680 
681 	vnodes_created = counter_u64_alloc(M_WAITOK);
682 	recycles_count = counter_u64_alloc(M_WAITOK);
683 	recycles_free_count = counter_u64_alloc(M_WAITOK);
684 	deferred_inact = counter_u64_alloc(M_WAITOK);
685 
686 	/*
687 	 * Initialize the filesystem syncer.
688 	 */
689 	syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
690 	    &syncer_mask);
691 	syncer_maxdelay = syncer_mask + 1;
692 	mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
693 	cv_init(&sync_wakeup, "syncer");
694 	for (i = 1; i <= sizeof(struct vnode); i <<= 1)
695 		vnsz2log++;
696 	vnsz2log--;
697 
698 	CPU_FOREACH(cpu) {
699 		vd = DPCPU_ID_PTR((cpu), vd);
700 		bzero(vd, sizeof(*vd));
701 		mtx_init(&vd->lock, "vdbatch", NULL, MTX_DEF);
702 	}
703 }
704 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
705 
706 /*
707  * Mark a mount point as busy. Used to synchronize access and to delay
708  * unmounting. Eventually, mountlist_mtx is not released on failure.
709  *
710  * vfs_busy() is a custom lock, it can block the caller.
711  * vfs_busy() only sleeps if the unmount is active on the mount point.
712  * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
713  * vnode belonging to mp.
714  *
715  * Lookup uses vfs_busy() to traverse mount points.
716  * root fs			var fs
717  * / vnode lock		A	/ vnode lock (/var)		D
718  * /var vnode lock	B	/log vnode lock(/var/log)	E
719  * vfs_busy lock	C	vfs_busy lock			F
720  *
721  * Within each file system, the lock order is C->A->B and F->D->E.
722  *
723  * When traversing across mounts, the system follows that lock order:
724  *
725  *        C->A->B
726  *              |
727  *              +->F->D->E
728  *
729  * The lookup() process for namei("/var") illustrates the process:
730  *  VOP_LOOKUP() obtains B while A is held
731  *  vfs_busy() obtains a shared lock on F while A and B are held
732  *  vput() releases lock on B
733  *  vput() releases lock on A
734  *  VFS_ROOT() obtains lock on D while shared lock on F is held
735  *  vfs_unbusy() releases shared lock on F
736  *  vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
737  *    Attempt to lock A (instead of vp_crossmp) while D is held would
738  *    violate the global order, causing deadlocks.
739  *
740  * dounmount() locks B while F is drained.
741  */
742 int
743 vfs_busy(struct mount *mp, int flags)
744 {
745 
746 	MPASS((flags & ~MBF_MASK) == 0);
747 	CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
748 
749 	if (vfs_op_thread_enter(mp)) {
750 		MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
751 		MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
752 		MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
753 		vfs_mp_count_add_pcpu(mp, ref, 1);
754 		vfs_mp_count_add_pcpu(mp, lockref, 1);
755 		vfs_op_thread_exit(mp);
756 		if (flags & MBF_MNTLSTLOCK)
757 			mtx_unlock(&mountlist_mtx);
758 		return (0);
759 	}
760 
761 	MNT_ILOCK(mp);
762 	vfs_assert_mount_counters(mp);
763 	MNT_REF(mp);
764 	/*
765 	 * If mount point is currently being unmounted, sleep until the
766 	 * mount point fate is decided.  If thread doing the unmounting fails,
767 	 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
768 	 * that this mount point has survived the unmount attempt and vfs_busy
769 	 * should retry.  Otherwise the unmounter thread will set MNTK_REFEXPIRE
770 	 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
771 	 * about to be really destroyed.  vfs_busy needs to release its
772 	 * reference on the mount point in this case and return with ENOENT,
773 	 * telling the caller that mount mount it tried to busy is no longer
774 	 * valid.
775 	 */
776 	while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
777 		if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
778 			MNT_REL(mp);
779 			MNT_IUNLOCK(mp);
780 			CTR1(KTR_VFS, "%s: failed busying before sleeping",
781 			    __func__);
782 			return (ENOENT);
783 		}
784 		if (flags & MBF_MNTLSTLOCK)
785 			mtx_unlock(&mountlist_mtx);
786 		mp->mnt_kern_flag |= MNTK_MWAIT;
787 		msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
788 		if (flags & MBF_MNTLSTLOCK)
789 			mtx_lock(&mountlist_mtx);
790 		MNT_ILOCK(mp);
791 	}
792 	if (flags & MBF_MNTLSTLOCK)
793 		mtx_unlock(&mountlist_mtx);
794 	mp->mnt_lockref++;
795 	MNT_IUNLOCK(mp);
796 	return (0);
797 }
798 
799 /*
800  * Free a busy filesystem.
801  */
802 void
803 vfs_unbusy(struct mount *mp)
804 {
805 	int c;
806 
807 	CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
808 
809 	if (vfs_op_thread_enter(mp)) {
810 		MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
811 		vfs_mp_count_sub_pcpu(mp, lockref, 1);
812 		vfs_mp_count_sub_pcpu(mp, ref, 1);
813 		vfs_op_thread_exit(mp);
814 		return;
815 	}
816 
817 	MNT_ILOCK(mp);
818 	vfs_assert_mount_counters(mp);
819 	MNT_REL(mp);
820 	c = --mp->mnt_lockref;
821 	if (mp->mnt_vfs_ops == 0) {
822 		MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
823 		MNT_IUNLOCK(mp);
824 		return;
825 	}
826 	if (c < 0)
827 		vfs_dump_mount_counters(mp);
828 	if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
829 		MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
830 		CTR1(KTR_VFS, "%s: waking up waiters", __func__);
831 		mp->mnt_kern_flag &= ~MNTK_DRAINING;
832 		wakeup(&mp->mnt_lockref);
833 	}
834 	MNT_IUNLOCK(mp);
835 }
836 
837 /*
838  * Lookup a mount point by filesystem identifier.
839  */
840 struct mount *
841 vfs_getvfs(fsid_t *fsid)
842 {
843 	struct mount *mp;
844 
845 	CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
846 	mtx_lock(&mountlist_mtx);
847 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
848 		if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
849 			vfs_ref(mp);
850 			mtx_unlock(&mountlist_mtx);
851 			return (mp);
852 		}
853 	}
854 	mtx_unlock(&mountlist_mtx);
855 	CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
856 	return ((struct mount *) 0);
857 }
858 
859 /*
860  * Lookup a mount point by filesystem identifier, busying it before
861  * returning.
862  *
863  * To avoid congestion on mountlist_mtx, implement simple direct-mapped
864  * cache for popular filesystem identifiers.  The cache is lockess, using
865  * the fact that struct mount's are never freed.  In worst case we may
866  * get pointer to unmounted or even different filesystem, so we have to
867  * check what we got, and go slow way if so.
868  */
869 struct mount *
870 vfs_busyfs(fsid_t *fsid)
871 {
872 #define	FSID_CACHE_SIZE	256
873 	typedef struct mount * volatile vmp_t;
874 	static vmp_t cache[FSID_CACHE_SIZE];
875 	struct mount *mp;
876 	int error;
877 	uint32_t hash;
878 
879 	CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
880 	hash = fsid->val[0] ^ fsid->val[1];
881 	hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
882 	mp = cache[hash];
883 	if (mp == NULL || fsidcmp(&mp->mnt_stat.f_fsid, fsid) != 0)
884 		goto slow;
885 	if (vfs_busy(mp, 0) != 0) {
886 		cache[hash] = NULL;
887 		goto slow;
888 	}
889 	if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0)
890 		return (mp);
891 	else
892 	    vfs_unbusy(mp);
893 
894 slow:
895 	mtx_lock(&mountlist_mtx);
896 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
897 		if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
898 			error = vfs_busy(mp, MBF_MNTLSTLOCK);
899 			if (error) {
900 				cache[hash] = NULL;
901 				mtx_unlock(&mountlist_mtx);
902 				return (NULL);
903 			}
904 			cache[hash] = mp;
905 			return (mp);
906 		}
907 	}
908 	CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
909 	mtx_unlock(&mountlist_mtx);
910 	return ((struct mount *) 0);
911 }
912 
913 /*
914  * Check if a user can access privileged mount options.
915  */
916 int
917 vfs_suser(struct mount *mp, struct thread *td)
918 {
919 	int error;
920 
921 	if (jailed(td->td_ucred)) {
922 		/*
923 		 * If the jail of the calling thread lacks permission for
924 		 * this type of file system, deny immediately.
925 		 */
926 		if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
927 			return (EPERM);
928 
929 		/*
930 		 * If the file system was mounted outside the jail of the
931 		 * calling thread, deny immediately.
932 		 */
933 		if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
934 			return (EPERM);
935 	}
936 
937 	/*
938 	 * If file system supports delegated administration, we don't check
939 	 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
940 	 * by the file system itself.
941 	 * If this is not the user that did original mount, we check for
942 	 * the PRIV_VFS_MOUNT_OWNER privilege.
943 	 */
944 	if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
945 	    mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
946 		if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
947 			return (error);
948 	}
949 	return (0);
950 }
951 
952 /*
953  * Get a new unique fsid.  Try to make its val[0] unique, since this value
954  * will be used to create fake device numbers for stat().  Also try (but
955  * not so hard) make its val[0] unique mod 2^16, since some emulators only
956  * support 16-bit device numbers.  We end up with unique val[0]'s for the
957  * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
958  *
959  * Keep in mind that several mounts may be running in parallel.  Starting
960  * the search one past where the previous search terminated is both a
961  * micro-optimization and a defense against returning the same fsid to
962  * different mounts.
963  */
964 void
965 vfs_getnewfsid(struct mount *mp)
966 {
967 	static uint16_t mntid_base;
968 	struct mount *nmp;
969 	fsid_t tfsid;
970 	int mtype;
971 
972 	CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
973 	mtx_lock(&mntid_mtx);
974 	mtype = mp->mnt_vfc->vfc_typenum;
975 	tfsid.val[1] = mtype;
976 	mtype = (mtype & 0xFF) << 24;
977 	for (;;) {
978 		tfsid.val[0] = makedev(255,
979 		    mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
980 		mntid_base++;
981 		if ((nmp = vfs_getvfs(&tfsid)) == NULL)
982 			break;
983 		vfs_rel(nmp);
984 	}
985 	mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
986 	mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
987 	mtx_unlock(&mntid_mtx);
988 }
989 
990 /*
991  * Knob to control the precision of file timestamps:
992  *
993  *   0 = seconds only; nanoseconds zeroed.
994  *   1 = seconds and nanoseconds, accurate within 1/HZ.
995  *   2 = seconds and nanoseconds, truncated to microseconds.
996  * >=3 = seconds and nanoseconds, maximum precision.
997  */
998 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
999 
1000 static int timestamp_precision = TSP_USEC;
1001 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
1002     &timestamp_precision, 0, "File timestamp precision (0: seconds, "
1003     "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
1004     "3+: sec + ns (max. precision))");
1005 
1006 /*
1007  * Get a current timestamp.
1008  */
1009 void
1010 vfs_timestamp(struct timespec *tsp)
1011 {
1012 	struct timeval tv;
1013 
1014 	switch (timestamp_precision) {
1015 	case TSP_SEC:
1016 		tsp->tv_sec = time_second;
1017 		tsp->tv_nsec = 0;
1018 		break;
1019 	case TSP_HZ:
1020 		getnanotime(tsp);
1021 		break;
1022 	case TSP_USEC:
1023 		microtime(&tv);
1024 		TIMEVAL_TO_TIMESPEC(&tv, tsp);
1025 		break;
1026 	case TSP_NSEC:
1027 	default:
1028 		nanotime(tsp);
1029 		break;
1030 	}
1031 }
1032 
1033 /*
1034  * Set vnode attributes to VNOVAL
1035  */
1036 void
1037 vattr_null(struct vattr *vap)
1038 {
1039 
1040 	vap->va_type = VNON;
1041 	vap->va_size = VNOVAL;
1042 	vap->va_bytes = VNOVAL;
1043 	vap->va_mode = VNOVAL;
1044 	vap->va_nlink = VNOVAL;
1045 	vap->va_uid = VNOVAL;
1046 	vap->va_gid = VNOVAL;
1047 	vap->va_fsid = VNOVAL;
1048 	vap->va_fileid = VNOVAL;
1049 	vap->va_blocksize = VNOVAL;
1050 	vap->va_rdev = VNOVAL;
1051 	vap->va_atime.tv_sec = VNOVAL;
1052 	vap->va_atime.tv_nsec = VNOVAL;
1053 	vap->va_mtime.tv_sec = VNOVAL;
1054 	vap->va_mtime.tv_nsec = VNOVAL;
1055 	vap->va_ctime.tv_sec = VNOVAL;
1056 	vap->va_ctime.tv_nsec = VNOVAL;
1057 	vap->va_birthtime.tv_sec = VNOVAL;
1058 	vap->va_birthtime.tv_nsec = VNOVAL;
1059 	vap->va_flags = VNOVAL;
1060 	vap->va_gen = VNOVAL;
1061 	vap->va_vaflags = 0;
1062 }
1063 
1064 /*
1065  * Try to reduce the total number of vnodes.
1066  *
1067  * This routine (and its user) are buggy in at least the following ways:
1068  * - all parameters were picked years ago when RAM sizes were significantly
1069  *   smaller
1070  * - it can pick vnodes based on pages used by the vm object, but filesystems
1071  *   like ZFS don't use it making the pick broken
1072  * - since ZFS has its own aging policy it gets partially combated by this one
1073  * - a dedicated method should be provided for filesystems to let them decide
1074  *   whether the vnode should be recycled
1075  *
1076  * This routine is called when we have too many vnodes.  It attempts
1077  * to free <count> vnodes and will potentially free vnodes that still
1078  * have VM backing store (VM backing store is typically the cause
1079  * of a vnode blowout so we want to do this).  Therefore, this operation
1080  * is not considered cheap.
1081  *
1082  * A number of conditions may prevent a vnode from being reclaimed.
1083  * the buffer cache may have references on the vnode, a directory
1084  * vnode may still have references due to the namei cache representing
1085  * underlying files, or the vnode may be in active use.   It is not
1086  * desirable to reuse such vnodes.  These conditions may cause the
1087  * number of vnodes to reach some minimum value regardless of what
1088  * you set kern.maxvnodes to.  Do not set kern.maxvnodes too low.
1089  *
1090  * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1091  * 			 entries if this argument is strue
1092  * @param trigger	 Only reclaim vnodes with fewer than this many resident
1093  *			 pages.
1094  * @param target	 How many vnodes to reclaim.
1095  * @return		 The number of vnodes that were reclaimed.
1096  */
1097 static int
1098 vlrureclaim(bool reclaim_nc_src, int trigger, u_long target)
1099 {
1100 	struct vnode *vp, *mvp;
1101 	struct mount *mp;
1102 	struct vm_object *object;
1103 	u_long done;
1104 	bool retried;
1105 
1106 	mtx_assert(&vnode_list_mtx, MA_OWNED);
1107 
1108 	retried = false;
1109 	done = 0;
1110 
1111 	mvp = vnode_list_reclaim_marker;
1112 restart:
1113 	vp = mvp;
1114 	while (done < target) {
1115 		vp = TAILQ_NEXT(vp, v_vnodelist);
1116 		if (__predict_false(vp == NULL))
1117 			break;
1118 
1119 		if (__predict_false(vp->v_type == VMARKER))
1120 			continue;
1121 
1122 		/*
1123 		 * If it's been deconstructed already, it's still
1124 		 * referenced, or it exceeds the trigger, skip it.
1125 		 * Also skip free vnodes.  We are trying to make space
1126 		 * to expand the free list, not reduce it.
1127 		 */
1128 		if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1129 		    (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)))
1130 			goto next_iter;
1131 
1132 		if (vp->v_type == VBAD || vp->v_type == VNON)
1133 			goto next_iter;
1134 
1135 		if (!VI_TRYLOCK(vp))
1136 			goto next_iter;
1137 
1138 		if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1139 		    (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1140 		    VN_IS_DOOMED(vp) || vp->v_type == VNON) {
1141 			VI_UNLOCK(vp);
1142 			goto next_iter;
1143 		}
1144 
1145 		object = atomic_load_ptr(&vp->v_object);
1146 		if (object == NULL || object->resident_page_count > trigger) {
1147 			VI_UNLOCK(vp);
1148 			goto next_iter;
1149 		}
1150 
1151 		vholdl(vp);
1152 		VI_UNLOCK(vp);
1153 		TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1154 		TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1155 		mtx_unlock(&vnode_list_mtx);
1156 
1157 		if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1158 			vdrop(vp);
1159 			goto next_iter_unlocked;
1160 		}
1161 		if (VOP_LOCK(vp, LK_EXCLUSIVE|LK_NOWAIT) != 0) {
1162 			vdrop(vp);
1163 			vn_finished_write(mp);
1164 			goto next_iter_unlocked;
1165 		}
1166 
1167 		VI_LOCK(vp);
1168 		if (vp->v_usecount > 0 ||
1169 		    (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1170 		    (vp->v_object != NULL &&
1171 		    vp->v_object->resident_page_count > trigger)) {
1172 			VOP_UNLOCK(vp);
1173 			vdropl(vp);
1174 			vn_finished_write(mp);
1175 			goto next_iter_unlocked;
1176 		}
1177 		counter_u64_add(recycles_count, 1);
1178 		vgonel(vp);
1179 		VOP_UNLOCK(vp);
1180 		vdropl(vp);
1181 		vn_finished_write(mp);
1182 		done++;
1183 next_iter_unlocked:
1184 		if (should_yield())
1185 			kern_yield(PRI_USER);
1186 		mtx_lock(&vnode_list_mtx);
1187 		goto restart;
1188 next_iter:
1189 		MPASS(vp->v_type != VMARKER);
1190 		if (!should_yield())
1191 			continue;
1192 		TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1193 		TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1194 		mtx_unlock(&vnode_list_mtx);
1195 		kern_yield(PRI_USER);
1196 		mtx_lock(&vnode_list_mtx);
1197 		goto restart;
1198 	}
1199 	if (done == 0 && !retried) {
1200 		TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1201 		TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1202 		retried = true;
1203 		goto restart;
1204 	}
1205 	return (done);
1206 }
1207 
1208 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1209 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1210     0,
1211     "limit on vnode free requests per call to the vnlru_free routine");
1212 
1213 /*
1214  * Attempt to reduce the free list by the requested amount.
1215  */
1216 static int
1217 vnlru_free_locked(int count, struct vfsops *mnt_op)
1218 {
1219 	struct vnode *vp, *mvp;
1220 	struct mount *mp;
1221 	int ocount;
1222 
1223 	mtx_assert(&vnode_list_mtx, MA_OWNED);
1224 	if (count > max_vnlru_free)
1225 		count = max_vnlru_free;
1226 	ocount = count;
1227 	mvp = vnode_list_free_marker;
1228 restart:
1229 	vp = mvp;
1230 	while (count > 0) {
1231 		vp = TAILQ_NEXT(vp, v_vnodelist);
1232 		if (__predict_false(vp == NULL)) {
1233 			TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1234 			TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1235 			break;
1236 		}
1237 		if (__predict_false(vp->v_type == VMARKER))
1238 			continue;
1239 
1240 		/*
1241 		 * Don't recycle if our vnode is from different type
1242 		 * of mount point.  Note that mp is type-safe, the
1243 		 * check does not reach unmapped address even if
1244 		 * vnode is reclaimed.
1245 		 * Don't recycle if we can't get the interlock without
1246 		 * blocking.
1247 		 */
1248 		if (vp->v_holdcnt > 0 || (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1249 		    mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
1250 			continue;
1251 		}
1252 		TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1253 		TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1254 		if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1255 			VI_UNLOCK(vp);
1256 			continue;
1257 		}
1258 		vholdl(vp);
1259 		count--;
1260 		mtx_unlock(&vnode_list_mtx);
1261 		VI_UNLOCK(vp);
1262 		vtryrecycle(vp);
1263 		vdrop(vp);
1264 		mtx_lock(&vnode_list_mtx);
1265 		goto restart;
1266 	}
1267 	return (ocount - count);
1268 }
1269 
1270 void
1271 vnlru_free(int count, struct vfsops *mnt_op)
1272 {
1273 
1274 	mtx_lock(&vnode_list_mtx);
1275 	vnlru_free_locked(count, mnt_op);
1276 	mtx_unlock(&vnode_list_mtx);
1277 }
1278 
1279 static void
1280 vnlru_recalc(void)
1281 {
1282 
1283 	mtx_assert(&vnode_list_mtx, MA_OWNED);
1284 	gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1285 	vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1286 	vlowat = vhiwat / 2;
1287 }
1288 
1289 /*
1290  * Attempt to recycle vnodes in a context that is always safe to block.
1291  * Calling vlrurecycle() from the bowels of filesystem code has some
1292  * interesting deadlock problems.
1293  */
1294 static struct proc *vnlruproc;
1295 static int vnlruproc_sig;
1296 
1297 /*
1298  * The main freevnodes counter is only updated when threads requeue their vnode
1299  * batches. CPUs are conditionally walked to compute a more accurate total.
1300  *
1301  * Limit how much of a slop are we willing to tolerate. Note: the actual value
1302  * at any given moment can still exceed slop, but it should not be by significant
1303  * margin in practice.
1304  */
1305 #define VNLRU_FREEVNODES_SLOP 128
1306 
1307 static u_long
1308 vnlru_read_freevnodes(void)
1309 {
1310 	struct vdbatch *vd;
1311 	long slop;
1312 	int cpu;
1313 
1314 	mtx_assert(&vnode_list_mtx, MA_OWNED);
1315 	if (freevnodes > freevnodes_old)
1316 		slop = freevnodes - freevnodes_old;
1317 	else
1318 		slop = freevnodes_old - freevnodes;
1319 	if (slop < VNLRU_FREEVNODES_SLOP)
1320 		return (freevnodes >= 0 ? freevnodes : 0);
1321 	freevnodes_old = freevnodes;
1322 	CPU_FOREACH(cpu) {
1323 		vd = DPCPU_ID_PTR((cpu), vd);
1324 		freevnodes_old += vd->freevnodes;
1325 	}
1326 	return (freevnodes_old >= 0 ? freevnodes_old : 0);
1327 }
1328 
1329 static bool
1330 vnlru_under(u_long rnumvnodes, u_long limit)
1331 {
1332 	u_long rfreevnodes, space;
1333 
1334 	if (__predict_false(rnumvnodes > desiredvnodes))
1335 		return (true);
1336 
1337 	space = desiredvnodes - rnumvnodes;
1338 	if (space < limit) {
1339 		rfreevnodes = vnlru_read_freevnodes();
1340 		if (rfreevnodes > wantfreevnodes)
1341 			space += rfreevnodes - wantfreevnodes;
1342 	}
1343 	return (space < limit);
1344 }
1345 
1346 static bool
1347 vnlru_under_unlocked(u_long rnumvnodes, u_long limit)
1348 {
1349 	long rfreevnodes, space;
1350 
1351 	if (__predict_false(rnumvnodes > desiredvnodes))
1352 		return (true);
1353 
1354 	space = desiredvnodes - rnumvnodes;
1355 	if (space < limit) {
1356 		rfreevnodes = atomic_load_long(&freevnodes);
1357 		if (rfreevnodes > wantfreevnodes)
1358 			space += rfreevnodes - wantfreevnodes;
1359 	}
1360 	return (space < limit);
1361 }
1362 
1363 static void
1364 vnlru_kick(void)
1365 {
1366 
1367 	mtx_assert(&vnode_list_mtx, MA_OWNED);
1368 	if (vnlruproc_sig == 0) {
1369 		vnlruproc_sig = 1;
1370 		wakeup(vnlruproc);
1371 	}
1372 }
1373 
1374 static void
1375 vnlru_proc(void)
1376 {
1377 	u_long rnumvnodes, rfreevnodes, target;
1378 	unsigned long onumvnodes;
1379 	int done, force, trigger, usevnodes;
1380 	bool reclaim_nc_src, want_reread;
1381 
1382 	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1383 	    SHUTDOWN_PRI_FIRST);
1384 
1385 	force = 0;
1386 	want_reread = false;
1387 	for (;;) {
1388 		kproc_suspend_check(vnlruproc);
1389 		mtx_lock(&vnode_list_mtx);
1390 		rnumvnodes = atomic_load_long(&numvnodes);
1391 
1392 		if (want_reread) {
1393 			force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1394 			want_reread = false;
1395 		}
1396 
1397 		/*
1398 		 * If numvnodes is too large (due to desiredvnodes being
1399 		 * adjusted using its sysctl, or emergency growth), first
1400 		 * try to reduce it by discarding from the free list.
1401 		 */
1402 		if (rnumvnodes > desiredvnodes) {
1403 			vnlru_free_locked(rnumvnodes - desiredvnodes, NULL);
1404 			rnumvnodes = atomic_load_long(&numvnodes);
1405 		}
1406 		/*
1407 		 * Sleep if the vnode cache is in a good state.  This is
1408 		 * when it is not over-full and has space for about a 4%
1409 		 * or 9% expansion (by growing its size or inexcessively
1410 		 * reducing its free list).  Otherwise, try to reclaim
1411 		 * space for a 10% expansion.
1412 		 */
1413 		if (vstir && force == 0) {
1414 			force = 1;
1415 			vstir = 0;
1416 		}
1417 		if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1418 			vnlruproc_sig = 0;
1419 			wakeup(&vnlruproc_sig);
1420 			msleep(vnlruproc, &vnode_list_mtx,
1421 			    PVFS|PDROP, "vlruwt", hz);
1422 			continue;
1423 		}
1424 		rfreevnodes = vnlru_read_freevnodes();
1425 
1426 		onumvnodes = rnumvnodes;
1427 		/*
1428 		 * Calculate parameters for recycling.  These are the same
1429 		 * throughout the loop to give some semblance of fairness.
1430 		 * The trigger point is to avoid recycling vnodes with lots
1431 		 * of resident pages.  We aren't trying to free memory; we
1432 		 * are trying to recycle or at least free vnodes.
1433 		 */
1434 		if (rnumvnodes <= desiredvnodes)
1435 			usevnodes = rnumvnodes - rfreevnodes;
1436 		else
1437 			usevnodes = rnumvnodes;
1438 		if (usevnodes <= 0)
1439 			usevnodes = 1;
1440 		/*
1441 		 * The trigger value is is chosen to give a conservatively
1442 		 * large value to ensure that it alone doesn't prevent
1443 		 * making progress.  The value can easily be so large that
1444 		 * it is effectively infinite in some congested and
1445 		 * misconfigured cases, and this is necessary.  Normally
1446 		 * it is about 8 to 100 (pages), which is quite large.
1447 		 */
1448 		trigger = vm_cnt.v_page_count * 2 / usevnodes;
1449 		if (force < 2)
1450 			trigger = vsmalltrigger;
1451 		reclaim_nc_src = force >= 3;
1452 		target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1453 		target = target / 10 + 1;
1454 		done = vlrureclaim(reclaim_nc_src, trigger, target);
1455 		mtx_unlock(&vnode_list_mtx);
1456 		if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1457 			uma_reclaim(UMA_RECLAIM_DRAIN);
1458 		if (done == 0) {
1459 			if (force == 0 || force == 1) {
1460 				force = 2;
1461 				continue;
1462 			}
1463 			if (force == 2) {
1464 				force = 3;
1465 				continue;
1466 			}
1467 			want_reread = true;
1468 			force = 0;
1469 			vnlru_nowhere++;
1470 			tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1471 		} else {
1472 			want_reread = true;
1473 			kern_yield(PRI_USER);
1474 		}
1475 	}
1476 }
1477 
1478 static struct kproc_desc vnlru_kp = {
1479 	"vnlru",
1480 	vnlru_proc,
1481 	&vnlruproc
1482 };
1483 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1484     &vnlru_kp);
1485 
1486 /*
1487  * Routines having to do with the management of the vnode table.
1488  */
1489 
1490 /*
1491  * Try to recycle a freed vnode.  We abort if anyone picks up a reference
1492  * before we actually vgone().  This function must be called with the vnode
1493  * held to prevent the vnode from being returned to the free list midway
1494  * through vgone().
1495  */
1496 static int
1497 vtryrecycle(struct vnode *vp)
1498 {
1499 	struct mount *vnmp;
1500 
1501 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1502 	VNASSERT(vp->v_holdcnt, vp,
1503 	    ("vtryrecycle: Recycling vp %p without a reference.", vp));
1504 	/*
1505 	 * This vnode may found and locked via some other list, if so we
1506 	 * can't recycle it yet.
1507 	 */
1508 	if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1509 		CTR2(KTR_VFS,
1510 		    "%s: impossible to recycle, vp %p lock is already held",
1511 		    __func__, vp);
1512 		return (EWOULDBLOCK);
1513 	}
1514 	/*
1515 	 * Don't recycle if its filesystem is being suspended.
1516 	 */
1517 	if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1518 		VOP_UNLOCK(vp);
1519 		CTR2(KTR_VFS,
1520 		    "%s: impossible to recycle, cannot start the write for %p",
1521 		    __func__, vp);
1522 		return (EBUSY);
1523 	}
1524 	/*
1525 	 * If we got this far, we need to acquire the interlock and see if
1526 	 * anyone picked up this vnode from another list.  If not, we will
1527 	 * mark it with DOOMED via vgonel() so that anyone who does find it
1528 	 * will skip over it.
1529 	 */
1530 	VI_LOCK(vp);
1531 	if (vp->v_usecount) {
1532 		VOP_UNLOCK(vp);
1533 		VI_UNLOCK(vp);
1534 		vn_finished_write(vnmp);
1535 		CTR2(KTR_VFS,
1536 		    "%s: impossible to recycle, %p is already referenced",
1537 		    __func__, vp);
1538 		return (EBUSY);
1539 	}
1540 	if (!VN_IS_DOOMED(vp)) {
1541 		counter_u64_add(recycles_free_count, 1);
1542 		vgonel(vp);
1543 	}
1544 	VOP_UNLOCK(vp);
1545 	VI_UNLOCK(vp);
1546 	vn_finished_write(vnmp);
1547 	return (0);
1548 }
1549 
1550 /*
1551  * Allocate a new vnode.
1552  *
1553  * The operation never returns an error. Returning an error was disabled
1554  * in r145385 (dated 2005) with the following comment:
1555  *
1556  * XXX Not all VFS_VGET/ffs_vget callers check returns.
1557  *
1558  * Given the age of this commit (almost 15 years at the time of writing this
1559  * comment) restoring the ability to fail requires a significant audit of
1560  * all codepaths.
1561  *
1562  * The routine can try to free a vnode or stall for up to 1 second waiting for
1563  * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1564  */
1565 static u_long vn_alloc_cyclecount;
1566 
1567 static struct vnode * __noinline
1568 vn_alloc_hard(struct mount *mp)
1569 {
1570 	u_long rnumvnodes, rfreevnodes;
1571 
1572 	mtx_lock(&vnode_list_mtx);
1573 	rnumvnodes = atomic_load_long(&numvnodes);
1574 	if (rnumvnodes + 1 < desiredvnodes) {
1575 		vn_alloc_cyclecount = 0;
1576 		goto alloc;
1577 	}
1578 	rfreevnodes = vnlru_read_freevnodes();
1579 	if (vn_alloc_cyclecount++ >= rfreevnodes) {
1580 		vn_alloc_cyclecount = 0;
1581 		vstir = 1;
1582 	}
1583 	/*
1584 	 * Grow the vnode cache if it will not be above its target max
1585 	 * after growing.  Otherwise, if the free list is nonempty, try
1586 	 * to reclaim 1 item from it before growing the cache (possibly
1587 	 * above its target max if the reclamation failed or is delayed).
1588 	 * Otherwise, wait for some space.  In all cases, schedule
1589 	 * vnlru_proc() if we are getting short of space.  The watermarks
1590 	 * should be chosen so that we never wait or even reclaim from
1591 	 * the free list to below its target minimum.
1592 	 */
1593 	if (vnlru_free_locked(1, NULL) > 0)
1594 		goto alloc;
1595 	if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1596 		/*
1597 		 * Wait for space for a new vnode.
1598 		 */
1599 		vnlru_kick();
1600 		msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1601 		if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1602 		    vnlru_read_freevnodes() > 1)
1603 			vnlru_free_locked(1, NULL);
1604 	}
1605 alloc:
1606 	rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1607 	if (vnlru_under(rnumvnodes, vlowat))
1608 		vnlru_kick();
1609 	mtx_unlock(&vnode_list_mtx);
1610 	return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1611 }
1612 
1613 static struct vnode *
1614 vn_alloc(struct mount *mp)
1615 {
1616 	u_long rnumvnodes;
1617 
1618 	if (__predict_false(vn_alloc_cyclecount != 0))
1619 		return (vn_alloc_hard(mp));
1620 	rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1621 	if (__predict_false(vnlru_under_unlocked(rnumvnodes, vlowat))) {
1622 		atomic_subtract_long(&numvnodes, 1);
1623 		return (vn_alloc_hard(mp));
1624 	}
1625 
1626 	return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1627 }
1628 
1629 static void
1630 vn_free(struct vnode *vp)
1631 {
1632 
1633 	atomic_subtract_long(&numvnodes, 1);
1634 	uma_zfree_smr(vnode_zone, vp);
1635 }
1636 
1637 /*
1638  * Return the next vnode from the free list.
1639  */
1640 int
1641 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1642     struct vnode **vpp)
1643 {
1644 	struct vnode *vp;
1645 	struct thread *td;
1646 	struct lock_object *lo;
1647 
1648 	CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1649 
1650 	KASSERT(vops->registered,
1651 	    ("%s: not registered vector op %p\n", __func__, vops));
1652 
1653 	td = curthread;
1654 	if (td->td_vp_reserved != NULL) {
1655 		vp = td->td_vp_reserved;
1656 		td->td_vp_reserved = NULL;
1657 	} else {
1658 		vp = vn_alloc(mp);
1659 	}
1660 	counter_u64_add(vnodes_created, 1);
1661 	/*
1662 	 * Locks are given the generic name "vnode" when created.
1663 	 * Follow the historic practice of using the filesystem
1664 	 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1665 	 *
1666 	 * Locks live in a witness group keyed on their name. Thus,
1667 	 * when a lock is renamed, it must also move from the witness
1668 	 * group of its old name to the witness group of its new name.
1669 	 *
1670 	 * The change only needs to be made when the vnode moves
1671 	 * from one filesystem type to another. We ensure that each
1672 	 * filesystem use a single static name pointer for its tag so
1673 	 * that we can compare pointers rather than doing a strcmp().
1674 	 */
1675 	lo = &vp->v_vnlock->lock_object;
1676 #ifdef WITNESS
1677 	if (lo->lo_name != tag) {
1678 #endif
1679 		lo->lo_name = tag;
1680 #ifdef WITNESS
1681 		WITNESS_DESTROY(lo);
1682 		WITNESS_INIT(lo, tag);
1683 	}
1684 #endif
1685 	/*
1686 	 * By default, don't allow shared locks unless filesystems opt-in.
1687 	 */
1688 	vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1689 	/*
1690 	 * Finalize various vnode identity bits.
1691 	 */
1692 	KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1693 	KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1694 	KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1695 	vp->v_type = VNON;
1696 	vp->v_op = vops;
1697 	v_init_counters(vp);
1698 	vp->v_bufobj.bo_ops = &buf_ops_bio;
1699 #ifdef DIAGNOSTIC
1700 	if (mp == NULL && vops != &dead_vnodeops)
1701 		printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1702 #endif
1703 #ifdef MAC
1704 	mac_vnode_init(vp);
1705 	if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1706 		mac_vnode_associate_singlelabel(mp, vp);
1707 #endif
1708 	if (mp != NULL) {
1709 		vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1710 		if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1711 			vp->v_vflag |= VV_NOKNOTE;
1712 	}
1713 
1714 	/*
1715 	 * For the filesystems which do not use vfs_hash_insert(),
1716 	 * still initialize v_hash to have vfs_hash_index() useful.
1717 	 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1718 	 * its own hashing.
1719 	 */
1720 	vp->v_hash = (uintptr_t)vp >> vnsz2log;
1721 
1722 	*vpp = vp;
1723 	return (0);
1724 }
1725 
1726 void
1727 getnewvnode_reserve(void)
1728 {
1729 	struct thread *td;
1730 
1731 	td = curthread;
1732 	MPASS(td->td_vp_reserved == NULL);
1733 	td->td_vp_reserved = vn_alloc(NULL);
1734 }
1735 
1736 void
1737 getnewvnode_drop_reserve(void)
1738 {
1739 	struct thread *td;
1740 
1741 	td = curthread;
1742 	if (td->td_vp_reserved != NULL) {
1743 		vn_free(td->td_vp_reserved);
1744 		td->td_vp_reserved = NULL;
1745 	}
1746 }
1747 
1748 static void
1749 freevnode(struct vnode *vp)
1750 {
1751 	struct bufobj *bo;
1752 
1753 	/*
1754 	 * The vnode has been marked for destruction, so free it.
1755 	 *
1756 	 * The vnode will be returned to the zone where it will
1757 	 * normally remain until it is needed for another vnode. We
1758 	 * need to cleanup (or verify that the cleanup has already
1759 	 * been done) any residual data left from its current use
1760 	 * so as not to contaminate the freshly allocated vnode.
1761 	 */
1762 	CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1763 	bo = &vp->v_bufobj;
1764 	VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1765 	VNPASS(vp->v_holdcnt == VHOLD_NO_SMR, vp);
1766 	VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1767 	VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1768 	VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1769 	VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1770 	VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1771 	    ("clean blk trie not empty"));
1772 	VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1773 	VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1774 	    ("dirty blk trie not empty"));
1775 	VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1776 	VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1777 	VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1778 	VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1779 	    ("Dangling rangelock waiters"));
1780 	VI_UNLOCK(vp);
1781 #ifdef MAC
1782 	mac_vnode_destroy(vp);
1783 #endif
1784 	if (vp->v_pollinfo != NULL) {
1785 		destroy_vpollinfo(vp->v_pollinfo);
1786 		vp->v_pollinfo = NULL;
1787 	}
1788 #ifdef INVARIANTS
1789 	/* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
1790 	vp->v_op = NULL;
1791 #endif
1792 	vp->v_mountedhere = NULL;
1793 	vp->v_unpcb = NULL;
1794 	vp->v_rdev = NULL;
1795 	vp->v_fifoinfo = NULL;
1796 	vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
1797 	vp->v_irflag = 0;
1798 	vp->v_iflag = 0;
1799 	vp->v_vflag = 0;
1800 	bo->bo_flag = 0;
1801 	vn_free(vp);
1802 }
1803 
1804 /*
1805  * Delete from old mount point vnode list, if on one.
1806  */
1807 static void
1808 delmntque(struct vnode *vp)
1809 {
1810 	struct mount *mp;
1811 
1812 	VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
1813 
1814 	mp = vp->v_mount;
1815 	if (mp == NULL)
1816 		return;
1817 	MNT_ILOCK(mp);
1818 	VI_LOCK(vp);
1819 	vp->v_mount = NULL;
1820 	VI_UNLOCK(vp);
1821 	VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1822 		("bad mount point vnode list size"));
1823 	TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1824 	mp->mnt_nvnodelistsize--;
1825 	MNT_REL(mp);
1826 	MNT_IUNLOCK(mp);
1827 }
1828 
1829 static void
1830 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1831 {
1832 
1833 	vp->v_data = NULL;
1834 	vp->v_op = &dead_vnodeops;
1835 	vgone(vp);
1836 	vput(vp);
1837 }
1838 
1839 /*
1840  * Insert into list of vnodes for the new mount point, if available.
1841  */
1842 int
1843 insmntque1(struct vnode *vp, struct mount *mp,
1844 	void (*dtr)(struct vnode *, void *), void *dtr_arg)
1845 {
1846 
1847 	KASSERT(vp->v_mount == NULL,
1848 		("insmntque: vnode already on per mount vnode list"));
1849 	VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1850 	ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1851 
1852 	/*
1853 	 * We acquire the vnode interlock early to ensure that the
1854 	 * vnode cannot be recycled by another process releasing a
1855 	 * holdcnt on it before we get it on both the vnode list
1856 	 * and the active vnode list. The mount mutex protects only
1857 	 * manipulation of the vnode list and the vnode freelist
1858 	 * mutex protects only manipulation of the active vnode list.
1859 	 * Hence the need to hold the vnode interlock throughout.
1860 	 */
1861 	MNT_ILOCK(mp);
1862 	VI_LOCK(vp);
1863 	if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1864 	    ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1865 	    mp->mnt_nvnodelistsize == 0)) &&
1866 	    (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1867 		VI_UNLOCK(vp);
1868 		MNT_IUNLOCK(mp);
1869 		if (dtr != NULL)
1870 			dtr(vp, dtr_arg);
1871 		return (EBUSY);
1872 	}
1873 	vp->v_mount = mp;
1874 	MNT_REF(mp);
1875 	TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1876 	VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1877 		("neg mount point vnode list size"));
1878 	mp->mnt_nvnodelistsize++;
1879 	VI_UNLOCK(vp);
1880 	MNT_IUNLOCK(mp);
1881 	return (0);
1882 }
1883 
1884 int
1885 insmntque(struct vnode *vp, struct mount *mp)
1886 {
1887 
1888 	return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1889 }
1890 
1891 /*
1892  * Flush out and invalidate all buffers associated with a bufobj
1893  * Called with the underlying object locked.
1894  */
1895 int
1896 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1897 {
1898 	int error;
1899 
1900 	BO_LOCK(bo);
1901 	if (flags & V_SAVE) {
1902 		error = bufobj_wwait(bo, slpflag, slptimeo);
1903 		if (error) {
1904 			BO_UNLOCK(bo);
1905 			return (error);
1906 		}
1907 		if (bo->bo_dirty.bv_cnt > 0) {
1908 			BO_UNLOCK(bo);
1909 			if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1910 				return (error);
1911 			/*
1912 			 * XXX We could save a lock/unlock if this was only
1913 			 * enabled under INVARIANTS
1914 			 */
1915 			BO_LOCK(bo);
1916 			if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1917 				panic("vinvalbuf: dirty bufs");
1918 		}
1919 	}
1920 	/*
1921 	 * If you alter this loop please notice that interlock is dropped and
1922 	 * reacquired in flushbuflist.  Special care is needed to ensure that
1923 	 * no race conditions occur from this.
1924 	 */
1925 	do {
1926 		error = flushbuflist(&bo->bo_clean,
1927 		    flags, bo, slpflag, slptimeo);
1928 		if (error == 0 && !(flags & V_CLEANONLY))
1929 			error = flushbuflist(&bo->bo_dirty,
1930 			    flags, bo, slpflag, slptimeo);
1931 		if (error != 0 && error != EAGAIN) {
1932 			BO_UNLOCK(bo);
1933 			return (error);
1934 		}
1935 	} while (error != 0);
1936 
1937 	/*
1938 	 * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
1939 	 * have write I/O in-progress but if there is a VM object then the
1940 	 * VM object can also have read-I/O in-progress.
1941 	 */
1942 	do {
1943 		bufobj_wwait(bo, 0, 0);
1944 		if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
1945 			BO_UNLOCK(bo);
1946 			vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
1947 			BO_LOCK(bo);
1948 		}
1949 	} while (bo->bo_numoutput > 0);
1950 	BO_UNLOCK(bo);
1951 
1952 	/*
1953 	 * Destroy the copy in the VM cache, too.
1954 	 */
1955 	if (bo->bo_object != NULL &&
1956 	    (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1957 		VM_OBJECT_WLOCK(bo->bo_object);
1958 		vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1959 		    OBJPR_CLEANONLY : 0);
1960 		VM_OBJECT_WUNLOCK(bo->bo_object);
1961 	}
1962 
1963 #ifdef INVARIANTS
1964 	BO_LOCK(bo);
1965 	if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1966 	    V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1967 	    bo->bo_clean.bv_cnt > 0))
1968 		panic("vinvalbuf: flush failed");
1969 	if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1970 	    bo->bo_dirty.bv_cnt > 0)
1971 		panic("vinvalbuf: flush dirty failed");
1972 	BO_UNLOCK(bo);
1973 #endif
1974 	return (0);
1975 }
1976 
1977 /*
1978  * Flush out and invalidate all buffers associated with a vnode.
1979  * Called with the underlying object locked.
1980  */
1981 int
1982 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1983 {
1984 
1985 	CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1986 	ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1987 	if (vp->v_object != NULL && vp->v_object->handle != vp)
1988 		return (0);
1989 	return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1990 }
1991 
1992 /*
1993  * Flush out buffers on the specified list.
1994  *
1995  */
1996 static int
1997 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1998     int slptimeo)
1999 {
2000 	struct buf *bp, *nbp;
2001 	int retval, error;
2002 	daddr_t lblkno;
2003 	b_xflags_t xflags;
2004 
2005 	ASSERT_BO_WLOCKED(bo);
2006 
2007 	retval = 0;
2008 	TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2009 		/*
2010 		 * If we are flushing both V_NORMAL and V_ALT buffers then
2011 		 * do not skip any buffers. If we are flushing only V_NORMAL
2012 		 * buffers then skip buffers marked as BX_ALTDATA. If we are
2013 		 * flushing only V_ALT buffers then skip buffers not marked
2014 		 * as BX_ALTDATA.
2015 		 */
2016 		if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2017 		   (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2018 		    ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2019 			continue;
2020 		}
2021 		if (nbp != NULL) {
2022 			lblkno = nbp->b_lblkno;
2023 			xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2024 		}
2025 		retval = EAGAIN;
2026 		error = BUF_TIMELOCK(bp,
2027 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2028 		    "flushbuf", slpflag, slptimeo);
2029 		if (error) {
2030 			BO_LOCK(bo);
2031 			return (error != ENOLCK ? error : EAGAIN);
2032 		}
2033 		KASSERT(bp->b_bufobj == bo,
2034 		    ("bp %p wrong b_bufobj %p should be %p",
2035 		    bp, bp->b_bufobj, bo));
2036 		/*
2037 		 * XXX Since there are no node locks for NFS, I
2038 		 * believe there is a slight chance that a delayed
2039 		 * write will occur while sleeping just above, so
2040 		 * check for it.
2041 		 */
2042 		if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2043 		    (flags & V_SAVE)) {
2044 			bremfree(bp);
2045 			bp->b_flags |= B_ASYNC;
2046 			bwrite(bp);
2047 			BO_LOCK(bo);
2048 			return (EAGAIN);	/* XXX: why not loop ? */
2049 		}
2050 		bremfree(bp);
2051 		bp->b_flags |= (B_INVAL | B_RELBUF);
2052 		bp->b_flags &= ~B_ASYNC;
2053 		brelse(bp);
2054 		BO_LOCK(bo);
2055 		if (nbp == NULL)
2056 			break;
2057 		nbp = gbincore(bo, lblkno);
2058 		if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2059 		    != xflags)
2060 			break;			/* nbp invalid */
2061 	}
2062 	return (retval);
2063 }
2064 
2065 int
2066 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2067 {
2068 	struct buf *bp;
2069 	int error;
2070 	daddr_t lblkno;
2071 
2072 	ASSERT_BO_LOCKED(bo);
2073 
2074 	for (lblkno = startn;;) {
2075 again:
2076 		bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2077 		if (bp == NULL || bp->b_lblkno >= endn ||
2078 		    bp->b_lblkno < startn)
2079 			break;
2080 		error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2081 		    LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2082 		if (error != 0) {
2083 			BO_RLOCK(bo);
2084 			if (error == ENOLCK)
2085 				goto again;
2086 			return (error);
2087 		}
2088 		KASSERT(bp->b_bufobj == bo,
2089 		    ("bp %p wrong b_bufobj %p should be %p",
2090 		    bp, bp->b_bufobj, bo));
2091 		lblkno = bp->b_lblkno + 1;
2092 		if ((bp->b_flags & B_MANAGED) == 0)
2093 			bremfree(bp);
2094 		bp->b_flags |= B_RELBUF;
2095 		/*
2096 		 * In the VMIO case, use the B_NOREUSE flag to hint that the
2097 		 * pages backing each buffer in the range are unlikely to be
2098 		 * reused.  Dirty buffers will have the hint applied once
2099 		 * they've been written.
2100 		 */
2101 		if ((bp->b_flags & B_VMIO) != 0)
2102 			bp->b_flags |= B_NOREUSE;
2103 		brelse(bp);
2104 		BO_RLOCK(bo);
2105 	}
2106 	return (0);
2107 }
2108 
2109 /*
2110  * Truncate a file's buffer and pages to a specified length.  This
2111  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2112  * sync activity.
2113  */
2114 int
2115 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2116 {
2117 	struct buf *bp, *nbp;
2118 	struct bufobj *bo;
2119 	daddr_t startlbn;
2120 
2121 	CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2122 	    vp, blksize, (uintmax_t)length);
2123 
2124 	/*
2125 	 * Round up to the *next* lbn.
2126 	 */
2127 	startlbn = howmany(length, blksize);
2128 
2129 	ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2130 
2131 	bo = &vp->v_bufobj;
2132 restart_unlocked:
2133 	BO_LOCK(bo);
2134 
2135 	while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2136 		;
2137 
2138 	if (length > 0) {
2139 restartsync:
2140 		TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2141 			if (bp->b_lblkno > 0)
2142 				continue;
2143 			/*
2144 			 * Since we hold the vnode lock this should only
2145 			 * fail if we're racing with the buf daemon.
2146 			 */
2147 			if (BUF_LOCK(bp,
2148 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2149 			    BO_LOCKPTR(bo)) == ENOLCK)
2150 				goto restart_unlocked;
2151 
2152 			VNASSERT((bp->b_flags & B_DELWRI), vp,
2153 			    ("buf(%p) on dirty queue without DELWRI", bp));
2154 
2155 			bremfree(bp);
2156 			bawrite(bp);
2157 			BO_LOCK(bo);
2158 			goto restartsync;
2159 		}
2160 	}
2161 
2162 	bufobj_wwait(bo, 0, 0);
2163 	BO_UNLOCK(bo);
2164 	vnode_pager_setsize(vp, length);
2165 
2166 	return (0);
2167 }
2168 
2169 /*
2170  * Invalidate the cached pages of a file's buffer within the range of block
2171  * numbers [startlbn, endlbn).
2172  */
2173 void
2174 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2175     int blksize)
2176 {
2177 	struct bufobj *bo;
2178 	off_t start, end;
2179 
2180 	ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2181 
2182 	start = blksize * startlbn;
2183 	end = blksize * endlbn;
2184 
2185 	bo = &vp->v_bufobj;
2186 	BO_LOCK(bo);
2187 	MPASS(blksize == bo->bo_bsize);
2188 
2189 	while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2190 		;
2191 
2192 	BO_UNLOCK(bo);
2193 	vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2194 }
2195 
2196 static int
2197 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2198     daddr_t startlbn, daddr_t endlbn)
2199 {
2200 	struct buf *bp, *nbp;
2201 	bool anyfreed;
2202 
2203 	ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2204 	ASSERT_BO_LOCKED(bo);
2205 
2206 	do {
2207 		anyfreed = false;
2208 		TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2209 			if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2210 				continue;
2211 			if (BUF_LOCK(bp,
2212 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2213 			    BO_LOCKPTR(bo)) == ENOLCK) {
2214 				BO_LOCK(bo);
2215 				return (EAGAIN);
2216 			}
2217 
2218 			bremfree(bp);
2219 			bp->b_flags |= B_INVAL | B_RELBUF;
2220 			bp->b_flags &= ~B_ASYNC;
2221 			brelse(bp);
2222 			anyfreed = true;
2223 
2224 			BO_LOCK(bo);
2225 			if (nbp != NULL &&
2226 			    (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2227 			    nbp->b_vp != vp ||
2228 			    (nbp->b_flags & B_DELWRI) != 0))
2229 				return (EAGAIN);
2230 		}
2231 
2232 		TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2233 			if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2234 				continue;
2235 			if (BUF_LOCK(bp,
2236 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2237 			    BO_LOCKPTR(bo)) == ENOLCK) {
2238 				BO_LOCK(bo);
2239 				return (EAGAIN);
2240 			}
2241 			bremfree(bp);
2242 			bp->b_flags |= B_INVAL | B_RELBUF;
2243 			bp->b_flags &= ~B_ASYNC;
2244 			brelse(bp);
2245 			anyfreed = true;
2246 
2247 			BO_LOCK(bo);
2248 			if (nbp != NULL &&
2249 			    (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2250 			    (nbp->b_vp != vp) ||
2251 			    (nbp->b_flags & B_DELWRI) == 0))
2252 				return (EAGAIN);
2253 		}
2254 	} while (anyfreed);
2255 	return (0);
2256 }
2257 
2258 static void
2259 buf_vlist_remove(struct buf *bp)
2260 {
2261 	struct bufv *bv;
2262 
2263 	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2264 	ASSERT_BO_WLOCKED(bp->b_bufobj);
2265 	KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
2266 	    (BX_VNDIRTY|BX_VNCLEAN),
2267 	    ("buf_vlist_remove: Buf %p is on two lists", bp));
2268 	if (bp->b_xflags & BX_VNDIRTY)
2269 		bv = &bp->b_bufobj->bo_dirty;
2270 	else
2271 		bv = &bp->b_bufobj->bo_clean;
2272 	BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2273 	TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2274 	bv->bv_cnt--;
2275 	bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2276 }
2277 
2278 /*
2279  * Add the buffer to the sorted clean or dirty block list.
2280  *
2281  * NOTE: xflags is passed as a constant, optimizing this inline function!
2282  */
2283 static void
2284 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2285 {
2286 	struct bufv *bv;
2287 	struct buf *n;
2288 	int error;
2289 
2290 	ASSERT_BO_WLOCKED(bo);
2291 	KASSERT((bo->bo_flag & BO_NOBUFS) == 0,
2292 	    ("buf_vlist_add: bo %p does not allow bufs", bo));
2293 	KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2294 	    ("dead bo %p", bo));
2295 	KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2296 	    ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2297 	bp->b_xflags |= xflags;
2298 	if (xflags & BX_VNDIRTY)
2299 		bv = &bo->bo_dirty;
2300 	else
2301 		bv = &bo->bo_clean;
2302 
2303 	/*
2304 	 * Keep the list ordered.  Optimize empty list insertion.  Assume
2305 	 * we tend to grow at the tail so lookup_le should usually be cheaper
2306 	 * than _ge.
2307 	 */
2308 	if (bv->bv_cnt == 0 ||
2309 	    bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2310 		TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2311 	else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2312 		TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2313 	else
2314 		TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2315 	error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2316 	if (error)
2317 		panic("buf_vlist_add:  Preallocated nodes insufficient.");
2318 	bv->bv_cnt++;
2319 }
2320 
2321 /*
2322  * Look up a buffer using the buffer tries.
2323  */
2324 struct buf *
2325 gbincore(struct bufobj *bo, daddr_t lblkno)
2326 {
2327 	struct buf *bp;
2328 
2329 	ASSERT_BO_LOCKED(bo);
2330 	bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2331 	if (bp != NULL)
2332 		return (bp);
2333 	return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
2334 }
2335 
2336 /*
2337  * Associate a buffer with a vnode.
2338  */
2339 void
2340 bgetvp(struct vnode *vp, struct buf *bp)
2341 {
2342 	struct bufobj *bo;
2343 
2344 	bo = &vp->v_bufobj;
2345 	ASSERT_BO_WLOCKED(bo);
2346 	VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2347 
2348 	CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2349 	VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2350 	    ("bgetvp: bp already attached! %p", bp));
2351 
2352 	vhold(vp);
2353 	bp->b_vp = vp;
2354 	bp->b_bufobj = bo;
2355 	/*
2356 	 * Insert onto list for new vnode.
2357 	 */
2358 	buf_vlist_add(bp, bo, BX_VNCLEAN);
2359 }
2360 
2361 /*
2362  * Disassociate a buffer from a vnode.
2363  */
2364 void
2365 brelvp(struct buf *bp)
2366 {
2367 	struct bufobj *bo;
2368 	struct vnode *vp;
2369 
2370 	CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2371 	KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2372 
2373 	/*
2374 	 * Delete from old vnode list, if on one.
2375 	 */
2376 	vp = bp->b_vp;		/* XXX */
2377 	bo = bp->b_bufobj;
2378 	BO_LOCK(bo);
2379 	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2380 		buf_vlist_remove(bp);
2381 	else
2382 		panic("brelvp: Buffer %p not on queue.", bp);
2383 	if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2384 		bo->bo_flag &= ~BO_ONWORKLST;
2385 		mtx_lock(&sync_mtx);
2386 		LIST_REMOVE(bo, bo_synclist);
2387 		syncer_worklist_len--;
2388 		mtx_unlock(&sync_mtx);
2389 	}
2390 	bp->b_vp = NULL;
2391 	bp->b_bufobj = NULL;
2392 	BO_UNLOCK(bo);
2393 	vdrop(vp);
2394 }
2395 
2396 /*
2397  * Add an item to the syncer work queue.
2398  */
2399 static void
2400 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2401 {
2402 	int slot;
2403 
2404 	ASSERT_BO_WLOCKED(bo);
2405 
2406 	mtx_lock(&sync_mtx);
2407 	if (bo->bo_flag & BO_ONWORKLST)
2408 		LIST_REMOVE(bo, bo_synclist);
2409 	else {
2410 		bo->bo_flag |= BO_ONWORKLST;
2411 		syncer_worklist_len++;
2412 	}
2413 
2414 	if (delay > syncer_maxdelay - 2)
2415 		delay = syncer_maxdelay - 2;
2416 	slot = (syncer_delayno + delay) & syncer_mask;
2417 
2418 	LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2419 	mtx_unlock(&sync_mtx);
2420 }
2421 
2422 static int
2423 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2424 {
2425 	int error, len;
2426 
2427 	mtx_lock(&sync_mtx);
2428 	len = syncer_worklist_len - sync_vnode_count;
2429 	mtx_unlock(&sync_mtx);
2430 	error = SYSCTL_OUT(req, &len, sizeof(len));
2431 	return (error);
2432 }
2433 
2434 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2435     CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2436     sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2437 
2438 static struct proc *updateproc;
2439 static void sched_sync(void);
2440 static struct kproc_desc up_kp = {
2441 	"syncer",
2442 	sched_sync,
2443 	&updateproc
2444 };
2445 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2446 
2447 static int
2448 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2449 {
2450 	struct vnode *vp;
2451 	struct mount *mp;
2452 
2453 	*bo = LIST_FIRST(slp);
2454 	if (*bo == NULL)
2455 		return (0);
2456 	vp = bo2vnode(*bo);
2457 	if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2458 		return (1);
2459 	/*
2460 	 * We use vhold in case the vnode does not
2461 	 * successfully sync.  vhold prevents the vnode from
2462 	 * going away when we unlock the sync_mtx so that
2463 	 * we can acquire the vnode interlock.
2464 	 */
2465 	vholdl(vp);
2466 	mtx_unlock(&sync_mtx);
2467 	VI_UNLOCK(vp);
2468 	if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2469 		vdrop(vp);
2470 		mtx_lock(&sync_mtx);
2471 		return (*bo == LIST_FIRST(slp));
2472 	}
2473 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2474 	(void) VOP_FSYNC(vp, MNT_LAZY, td);
2475 	VOP_UNLOCK(vp);
2476 	vn_finished_write(mp);
2477 	BO_LOCK(*bo);
2478 	if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2479 		/*
2480 		 * Put us back on the worklist.  The worklist
2481 		 * routine will remove us from our current
2482 		 * position and then add us back in at a later
2483 		 * position.
2484 		 */
2485 		vn_syncer_add_to_worklist(*bo, syncdelay);
2486 	}
2487 	BO_UNLOCK(*bo);
2488 	vdrop(vp);
2489 	mtx_lock(&sync_mtx);
2490 	return (0);
2491 }
2492 
2493 static int first_printf = 1;
2494 
2495 /*
2496  * System filesystem synchronizer daemon.
2497  */
2498 static void
2499 sched_sync(void)
2500 {
2501 	struct synclist *next, *slp;
2502 	struct bufobj *bo;
2503 	long starttime;
2504 	struct thread *td = curthread;
2505 	int last_work_seen;
2506 	int net_worklist_len;
2507 	int syncer_final_iter;
2508 	int error;
2509 
2510 	last_work_seen = 0;
2511 	syncer_final_iter = 0;
2512 	syncer_state = SYNCER_RUNNING;
2513 	starttime = time_uptime;
2514 	td->td_pflags |= TDP_NORUNNINGBUF;
2515 
2516 	EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2517 	    SHUTDOWN_PRI_LAST);
2518 
2519 	mtx_lock(&sync_mtx);
2520 	for (;;) {
2521 		if (syncer_state == SYNCER_FINAL_DELAY &&
2522 		    syncer_final_iter == 0) {
2523 			mtx_unlock(&sync_mtx);
2524 			kproc_suspend_check(td->td_proc);
2525 			mtx_lock(&sync_mtx);
2526 		}
2527 		net_worklist_len = syncer_worklist_len - sync_vnode_count;
2528 		if (syncer_state != SYNCER_RUNNING &&
2529 		    starttime != time_uptime) {
2530 			if (first_printf) {
2531 				printf("\nSyncing disks, vnodes remaining... ");
2532 				first_printf = 0;
2533 			}
2534 			printf("%d ", net_worklist_len);
2535 		}
2536 		starttime = time_uptime;
2537 
2538 		/*
2539 		 * Push files whose dirty time has expired.  Be careful
2540 		 * of interrupt race on slp queue.
2541 		 *
2542 		 * Skip over empty worklist slots when shutting down.
2543 		 */
2544 		do {
2545 			slp = &syncer_workitem_pending[syncer_delayno];
2546 			syncer_delayno += 1;
2547 			if (syncer_delayno == syncer_maxdelay)
2548 				syncer_delayno = 0;
2549 			next = &syncer_workitem_pending[syncer_delayno];
2550 			/*
2551 			 * If the worklist has wrapped since the
2552 			 * it was emptied of all but syncer vnodes,
2553 			 * switch to the FINAL_DELAY state and run
2554 			 * for one more second.
2555 			 */
2556 			if (syncer_state == SYNCER_SHUTTING_DOWN &&
2557 			    net_worklist_len == 0 &&
2558 			    last_work_seen == syncer_delayno) {
2559 				syncer_state = SYNCER_FINAL_DELAY;
2560 				syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2561 			}
2562 		} while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2563 		    syncer_worklist_len > 0);
2564 
2565 		/*
2566 		 * Keep track of the last time there was anything
2567 		 * on the worklist other than syncer vnodes.
2568 		 * Return to the SHUTTING_DOWN state if any
2569 		 * new work appears.
2570 		 */
2571 		if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2572 			last_work_seen = syncer_delayno;
2573 		if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2574 			syncer_state = SYNCER_SHUTTING_DOWN;
2575 		while (!LIST_EMPTY(slp)) {
2576 			error = sync_vnode(slp, &bo, td);
2577 			if (error == 1) {
2578 				LIST_REMOVE(bo, bo_synclist);
2579 				LIST_INSERT_HEAD(next, bo, bo_synclist);
2580 				continue;
2581 			}
2582 
2583 			if (first_printf == 0) {
2584 				/*
2585 				 * Drop the sync mutex, because some watchdog
2586 				 * drivers need to sleep while patting
2587 				 */
2588 				mtx_unlock(&sync_mtx);
2589 				wdog_kern_pat(WD_LASTVAL);
2590 				mtx_lock(&sync_mtx);
2591 			}
2592 
2593 		}
2594 		if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2595 			syncer_final_iter--;
2596 		/*
2597 		 * The variable rushjob allows the kernel to speed up the
2598 		 * processing of the filesystem syncer process. A rushjob
2599 		 * value of N tells the filesystem syncer to process the next
2600 		 * N seconds worth of work on its queue ASAP. Currently rushjob
2601 		 * is used by the soft update code to speed up the filesystem
2602 		 * syncer process when the incore state is getting so far
2603 		 * ahead of the disk that the kernel memory pool is being
2604 		 * threatened with exhaustion.
2605 		 */
2606 		if (rushjob > 0) {
2607 			rushjob -= 1;
2608 			continue;
2609 		}
2610 		/*
2611 		 * Just sleep for a short period of time between
2612 		 * iterations when shutting down to allow some I/O
2613 		 * to happen.
2614 		 *
2615 		 * If it has taken us less than a second to process the
2616 		 * current work, then wait. Otherwise start right over
2617 		 * again. We can still lose time if any single round
2618 		 * takes more than two seconds, but it does not really
2619 		 * matter as we are just trying to generally pace the
2620 		 * filesystem activity.
2621 		 */
2622 		if (syncer_state != SYNCER_RUNNING ||
2623 		    time_uptime == starttime) {
2624 			thread_lock(td);
2625 			sched_prio(td, PPAUSE);
2626 			thread_unlock(td);
2627 		}
2628 		if (syncer_state != SYNCER_RUNNING)
2629 			cv_timedwait(&sync_wakeup, &sync_mtx,
2630 			    hz / SYNCER_SHUTDOWN_SPEEDUP);
2631 		else if (time_uptime == starttime)
2632 			cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2633 	}
2634 }
2635 
2636 /*
2637  * Request the syncer daemon to speed up its work.
2638  * We never push it to speed up more than half of its
2639  * normal turn time, otherwise it could take over the cpu.
2640  */
2641 int
2642 speedup_syncer(void)
2643 {
2644 	int ret = 0;
2645 
2646 	mtx_lock(&sync_mtx);
2647 	if (rushjob < syncdelay / 2) {
2648 		rushjob += 1;
2649 		stat_rush_requests += 1;
2650 		ret = 1;
2651 	}
2652 	mtx_unlock(&sync_mtx);
2653 	cv_broadcast(&sync_wakeup);
2654 	return (ret);
2655 }
2656 
2657 /*
2658  * Tell the syncer to speed up its work and run though its work
2659  * list several times, then tell it to shut down.
2660  */
2661 static void
2662 syncer_shutdown(void *arg, int howto)
2663 {
2664 
2665 	if (howto & RB_NOSYNC)
2666 		return;
2667 	mtx_lock(&sync_mtx);
2668 	syncer_state = SYNCER_SHUTTING_DOWN;
2669 	rushjob = 0;
2670 	mtx_unlock(&sync_mtx);
2671 	cv_broadcast(&sync_wakeup);
2672 	kproc_shutdown(arg, howto);
2673 }
2674 
2675 void
2676 syncer_suspend(void)
2677 {
2678 
2679 	syncer_shutdown(updateproc, 0);
2680 }
2681 
2682 void
2683 syncer_resume(void)
2684 {
2685 
2686 	mtx_lock(&sync_mtx);
2687 	first_printf = 1;
2688 	syncer_state = SYNCER_RUNNING;
2689 	mtx_unlock(&sync_mtx);
2690 	cv_broadcast(&sync_wakeup);
2691 	kproc_resume(updateproc);
2692 }
2693 
2694 /*
2695  * Reassign a buffer from one vnode to another.
2696  * Used to assign file specific control information
2697  * (indirect blocks) to the vnode to which they belong.
2698  */
2699 void
2700 reassignbuf(struct buf *bp)
2701 {
2702 	struct vnode *vp;
2703 	struct bufobj *bo;
2704 	int delay;
2705 #ifdef INVARIANTS
2706 	struct bufv *bv;
2707 #endif
2708 
2709 	vp = bp->b_vp;
2710 	bo = bp->b_bufobj;
2711 	++reassignbufcalls;
2712 
2713 	CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2714 	    bp, bp->b_vp, bp->b_flags);
2715 	/*
2716 	 * B_PAGING flagged buffers cannot be reassigned because their vp
2717 	 * is not fully linked in.
2718 	 */
2719 	if (bp->b_flags & B_PAGING)
2720 		panic("cannot reassign paging buffer");
2721 
2722 	/*
2723 	 * Delete from old vnode list, if on one.
2724 	 */
2725 	BO_LOCK(bo);
2726 	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2727 		buf_vlist_remove(bp);
2728 	else
2729 		panic("reassignbuf: Buffer %p not on queue.", bp);
2730 	/*
2731 	 * If dirty, put on list of dirty buffers; otherwise insert onto list
2732 	 * of clean buffers.
2733 	 */
2734 	if (bp->b_flags & B_DELWRI) {
2735 		if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2736 			switch (vp->v_type) {
2737 			case VDIR:
2738 				delay = dirdelay;
2739 				break;
2740 			case VCHR:
2741 				delay = metadelay;
2742 				break;
2743 			default:
2744 				delay = filedelay;
2745 			}
2746 			vn_syncer_add_to_worklist(bo, delay);
2747 		}
2748 		buf_vlist_add(bp, bo, BX_VNDIRTY);
2749 	} else {
2750 		buf_vlist_add(bp, bo, BX_VNCLEAN);
2751 
2752 		if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2753 			mtx_lock(&sync_mtx);
2754 			LIST_REMOVE(bo, bo_synclist);
2755 			syncer_worklist_len--;
2756 			mtx_unlock(&sync_mtx);
2757 			bo->bo_flag &= ~BO_ONWORKLST;
2758 		}
2759 	}
2760 #ifdef INVARIANTS
2761 	bv = &bo->bo_clean;
2762 	bp = TAILQ_FIRST(&bv->bv_hd);
2763 	KASSERT(bp == NULL || bp->b_bufobj == bo,
2764 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2765 	bp = TAILQ_LAST(&bv->bv_hd, buflists);
2766 	KASSERT(bp == NULL || bp->b_bufobj == bo,
2767 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2768 	bv = &bo->bo_dirty;
2769 	bp = TAILQ_FIRST(&bv->bv_hd);
2770 	KASSERT(bp == NULL || bp->b_bufobj == bo,
2771 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2772 	bp = TAILQ_LAST(&bv->bv_hd, buflists);
2773 	KASSERT(bp == NULL || bp->b_bufobj == bo,
2774 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2775 #endif
2776 	BO_UNLOCK(bo);
2777 }
2778 
2779 static void
2780 v_init_counters(struct vnode *vp)
2781 {
2782 
2783 	VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2784 	    vp, ("%s called for an initialized vnode", __FUNCTION__));
2785 	ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2786 
2787 	refcount_init(&vp->v_holdcnt, 1);
2788 	refcount_init(&vp->v_usecount, 1);
2789 }
2790 
2791 /*
2792  * Increment si_usecount of the associated device, if any.
2793  */
2794 static void
2795 v_incr_devcount(struct vnode *vp)
2796 {
2797 
2798 	ASSERT_VI_LOCKED(vp, __FUNCTION__);
2799 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2800 		dev_lock();
2801 		vp->v_rdev->si_usecount++;
2802 		dev_unlock();
2803 	}
2804 }
2805 
2806 /*
2807  * Decrement si_usecount of the associated device, if any.
2808  *
2809  * The caller is required to hold the interlock when transitioning a VCHR use
2810  * count to zero. This prevents a race with devfs_reclaim_vchr() that would
2811  * leak a si_usecount reference. The vnode lock will also prevent this race
2812  * if it is held while dropping the last ref.
2813  *
2814  * The race is:
2815  *
2816  * CPU1					CPU2
2817  *				  	devfs_reclaim_vchr
2818  * make v_usecount == 0
2819  * 				    	  VI_LOCK
2820  * 				    	  sees v_usecount == 0, no updates
2821  * 				    	  vp->v_rdev = NULL;
2822  * 				    	  ...
2823  * 				    	  VI_UNLOCK
2824  * VI_LOCK
2825  * v_decr_devcount
2826  *   sees v_rdev == NULL, no updates
2827  *
2828  * In this scenario si_devcount decrement is not performed.
2829  */
2830 static void
2831 v_decr_devcount(struct vnode *vp)
2832 {
2833 
2834 	ASSERT_VOP_LOCKED(vp, __func__);
2835 	ASSERT_VI_LOCKED(vp, __FUNCTION__);
2836 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2837 		dev_lock();
2838 		VNPASS(vp->v_rdev->si_usecount > 0, vp);
2839 		vp->v_rdev->si_usecount--;
2840 		dev_unlock();
2841 	}
2842 }
2843 
2844 /*
2845  * Grab a particular vnode from the free list, increment its
2846  * reference count and lock it.  VIRF_DOOMED is set if the vnode
2847  * is being destroyed.  Only callers who specify LK_RETRY will
2848  * see doomed vnodes.  If inactive processing was delayed in
2849  * vput try to do it here.
2850  *
2851  * usecount is manipulated using atomics without holding any locks.
2852  *
2853  * holdcnt can be manipulated using atomics without holding any locks,
2854  * except when transitioning 1<->0, in which case the interlock is held.
2855  *
2856  * Consumers which don't guarantee liveness of the vnode can use SMR to
2857  * try to get a reference. Note this operation can fail since the vnode
2858  * may be awaiting getting freed by the time they get to it.
2859  */
2860 enum vgetstate
2861 vget_prep_smr(struct vnode *vp)
2862 {
2863 	enum vgetstate vs;
2864 
2865 	VFS_SMR_ASSERT_ENTERED();
2866 
2867 	if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2868 		vs = VGET_USECOUNT;
2869 	} else {
2870 		if (vhold_smr(vp))
2871 			vs = VGET_HOLDCNT;
2872 		else
2873 			vs = VGET_NONE;
2874 	}
2875 	return (vs);
2876 }
2877 
2878 enum vgetstate
2879 vget_prep(struct vnode *vp)
2880 {
2881 	enum vgetstate vs;
2882 
2883 	if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2884 		vs = VGET_USECOUNT;
2885 	} else {
2886 		vhold(vp);
2887 		vs = VGET_HOLDCNT;
2888 	}
2889 	return (vs);
2890 }
2891 
2892 int
2893 vget(struct vnode *vp, int flags, struct thread *td)
2894 {
2895 	enum vgetstate vs;
2896 
2897 	MPASS(td == curthread);
2898 
2899 	vs = vget_prep(vp);
2900 	return (vget_finish(vp, flags, vs));
2901 }
2902 
2903 static int __noinline
2904 vget_finish_vchr(struct vnode *vp)
2905 {
2906 
2907 	VNASSERT(vp->v_type == VCHR, vp, ("type != VCHR)"));
2908 
2909 	/*
2910 	 * See the comment in vget_finish before usecount bump.
2911 	 */
2912 	if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2913 #ifdef INVARIANTS
2914 		int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2915 		VNASSERT(old > 0, vp, ("%s: wrong hold count %d", __func__, old));
2916 #else
2917 		refcount_release(&vp->v_holdcnt);
2918 #endif
2919 		return (0);
2920 	}
2921 
2922 	VI_LOCK(vp);
2923 	if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2924 #ifdef INVARIANTS
2925 		int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2926 		VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2927 #else
2928 		refcount_release(&vp->v_holdcnt);
2929 #endif
2930 		VI_UNLOCK(vp);
2931 		return (0);
2932 	}
2933 	v_incr_devcount(vp);
2934 	refcount_acquire(&vp->v_usecount);
2935 	VI_UNLOCK(vp);
2936 	return (0);
2937 }
2938 
2939 int
2940 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
2941 {
2942 	int error, old;
2943 
2944 	if ((flags & LK_INTERLOCK) != 0)
2945 		ASSERT_VI_LOCKED(vp, __func__);
2946 	else
2947 		ASSERT_VI_UNLOCKED(vp, __func__);
2948 	VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
2949 	VNPASS(vp->v_holdcnt > 0, vp);
2950 	VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
2951 
2952 	error = vn_lock(vp, flags);
2953 	if (__predict_false(error != 0)) {
2954 		if (vs == VGET_USECOUNT)
2955 			vrele(vp);
2956 		else
2957 			vdrop(vp);
2958 		CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2959 		    vp);
2960 		return (error);
2961 	}
2962 
2963 	if (vs == VGET_USECOUNT)
2964 		return (0);
2965 
2966 	if (__predict_false(vp->v_type == VCHR))
2967 		return (vget_finish_vchr(vp));
2968 
2969 	/*
2970 	 * We hold the vnode. If the usecount is 0 it will be utilized to keep
2971 	 * the vnode around. Otherwise someone else lended their hold count and
2972 	 * we have to drop ours.
2973 	 */
2974 	old = atomic_fetchadd_int(&vp->v_usecount, 1);
2975 	VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
2976 	if (old != 0) {
2977 #ifdef INVARIANTS
2978 		old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2979 		VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2980 #else
2981 		refcount_release(&vp->v_holdcnt);
2982 #endif
2983 	}
2984 	return (0);
2985 }
2986 
2987 /*
2988  * Increase the reference (use) and hold count of a vnode.
2989  * This will also remove the vnode from the free list if it is presently free.
2990  */
2991 static void __noinline
2992 vref_vchr(struct vnode *vp, bool interlock)
2993 {
2994 
2995 	/*
2996 	 * See the comment in vget_finish before usecount bump.
2997 	 */
2998 	if (!interlock) {
2999 		if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3000 			VNODE_REFCOUNT_FENCE_ACQ();
3001 			VNASSERT(vp->v_holdcnt > 0, vp,
3002 			    ("%s: active vnode not held", __func__));
3003 			return;
3004 		}
3005 		VI_LOCK(vp);
3006 		/*
3007 		 * By the time we get here the vnode might have been doomed, at
3008 		 * which point the 0->1 use count transition is no longer
3009 		 * protected by the interlock. Since it can't bounce back to
3010 		 * VCHR and requires vref semantics, punt it back
3011 		 */
3012 		if (__predict_false(vp->v_type == VBAD)) {
3013 			VI_UNLOCK(vp);
3014 			vref(vp);
3015 			return;
3016 		}
3017 	}
3018 	VNASSERT(vp->v_type == VCHR, vp, ("type != VCHR)"));
3019 	if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3020 		VNODE_REFCOUNT_FENCE_ACQ();
3021 		VNASSERT(vp->v_holdcnt > 0, vp,
3022 		    ("%s: active vnode not held", __func__));
3023 		if (!interlock)
3024 			VI_UNLOCK(vp);
3025 		return;
3026 	}
3027 	vhold(vp);
3028 	v_incr_devcount(vp);
3029 	refcount_acquire(&vp->v_usecount);
3030 	if (!interlock)
3031 		VI_UNLOCK(vp);
3032 	return;
3033 }
3034 
3035 void
3036 vref(struct vnode *vp)
3037 {
3038 	int old;
3039 
3040 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3041 	if (__predict_false(vp->v_type == VCHR)) {
3042 		 vref_vchr(vp, false);
3043 		 return;
3044 	}
3045 
3046 	if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3047 		VNODE_REFCOUNT_FENCE_ACQ();
3048 		VNASSERT(vp->v_holdcnt > 0, vp,
3049 		    ("%s: active vnode not held", __func__));
3050 		return;
3051 	}
3052 	vhold(vp);
3053 	/*
3054 	 * See the comment in vget_finish.
3055 	 */
3056 	old = atomic_fetchadd_int(&vp->v_usecount, 1);
3057 	VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
3058 	if (old != 0) {
3059 #ifdef INVARIANTS
3060 		old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
3061 		VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
3062 #else
3063 		refcount_release(&vp->v_holdcnt);
3064 #endif
3065 	}
3066 }
3067 
3068 void
3069 vrefl(struct vnode *vp)
3070 {
3071 
3072 	ASSERT_VI_LOCKED(vp, __func__);
3073 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3074 	if (__predict_false(vp->v_type == VCHR)) {
3075 		vref_vchr(vp, true);
3076 		return;
3077 	}
3078 	vref(vp);
3079 }
3080 
3081 void
3082 vrefact(struct vnode *vp)
3083 {
3084 
3085 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3086 #ifdef INVARIANTS
3087 	int old = atomic_fetchadd_int(&vp->v_usecount, 1);
3088 	VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3089 #else
3090 	refcount_acquire(&vp->v_usecount);
3091 #endif
3092 }
3093 
3094 void
3095 vrefactn(struct vnode *vp, u_int n)
3096 {
3097 
3098 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3099 #ifdef INVARIANTS
3100 	int old = atomic_fetchadd_int(&vp->v_usecount, n);
3101 	VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3102 #else
3103 	atomic_add_int(&vp->v_usecount, n);
3104 #endif
3105 }
3106 
3107 /*
3108  * Return reference count of a vnode.
3109  *
3110  * The results of this call are only guaranteed when some mechanism is used to
3111  * stop other processes from gaining references to the vnode.  This may be the
3112  * case if the caller holds the only reference.  This is also useful when stale
3113  * data is acceptable as race conditions may be accounted for by some other
3114  * means.
3115  */
3116 int
3117 vrefcnt(struct vnode *vp)
3118 {
3119 
3120 	return (vp->v_usecount);
3121 }
3122 
3123 void
3124 vlazy(struct vnode *vp)
3125 {
3126 	struct mount *mp;
3127 
3128 	VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
3129 
3130 	if ((vp->v_mflag & VMP_LAZYLIST) != 0)
3131 		return;
3132 	/*
3133 	 * We may get here for inactive routines after the vnode got doomed.
3134 	 */
3135 	if (VN_IS_DOOMED(vp))
3136 		return;
3137 	mp = vp->v_mount;
3138 	mtx_lock(&mp->mnt_listmtx);
3139 	if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
3140 		vp->v_mflag |= VMP_LAZYLIST;
3141 		TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3142 		mp->mnt_lazyvnodelistsize++;
3143 	}
3144 	mtx_unlock(&mp->mnt_listmtx);
3145 }
3146 
3147 /*
3148  * This routine is only meant to be called from vgonel prior to dooming
3149  * the vnode.
3150  */
3151 static void
3152 vunlazy_gone(struct vnode *vp)
3153 {
3154 	struct mount *mp;
3155 
3156 	ASSERT_VOP_ELOCKED(vp, __func__);
3157 	ASSERT_VI_LOCKED(vp, __func__);
3158 	VNPASS(!VN_IS_DOOMED(vp), vp);
3159 
3160 	if (vp->v_mflag & VMP_LAZYLIST) {
3161 		mp = vp->v_mount;
3162 		mtx_lock(&mp->mnt_listmtx);
3163 		VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3164 		vp->v_mflag &= ~VMP_LAZYLIST;
3165 		TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3166 		mp->mnt_lazyvnodelistsize--;
3167 		mtx_unlock(&mp->mnt_listmtx);
3168 	}
3169 }
3170 
3171 static void
3172 vdefer_inactive(struct vnode *vp)
3173 {
3174 
3175 	ASSERT_VI_LOCKED(vp, __func__);
3176 	VNASSERT(vp->v_holdcnt > 0, vp,
3177 	    ("%s: vnode without hold count", __func__));
3178 	if (VN_IS_DOOMED(vp)) {
3179 		vdropl(vp);
3180 		return;
3181 	}
3182 	if (vp->v_iflag & VI_DEFINACT) {
3183 		VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3184 		vdropl(vp);
3185 		return;
3186 	}
3187 	if (vp->v_usecount > 0) {
3188 		vp->v_iflag &= ~VI_OWEINACT;
3189 		vdropl(vp);
3190 		return;
3191 	}
3192 	vlazy(vp);
3193 	vp->v_iflag |= VI_DEFINACT;
3194 	VI_UNLOCK(vp);
3195 	counter_u64_add(deferred_inact, 1);
3196 }
3197 
3198 static void
3199 vdefer_inactive_unlocked(struct vnode *vp)
3200 {
3201 
3202 	VI_LOCK(vp);
3203 	if ((vp->v_iflag & VI_OWEINACT) == 0) {
3204 		vdropl(vp);
3205 		return;
3206 	}
3207 	vdefer_inactive(vp);
3208 }
3209 
3210 enum vput_op { VRELE, VPUT, VUNREF };
3211 
3212 /*
3213  * Handle ->v_usecount transitioning to 0.
3214  *
3215  * By releasing the last usecount we take ownership of the hold count which
3216  * provides liveness of the vnode, meaning we have to vdrop.
3217  *
3218  * If the vnode is of type VCHR we may need to decrement si_usecount, see
3219  * v_decr_devcount for details.
3220  *
3221  * For all vnodes we may need to perform inactive processing. It requires an
3222  * exclusive lock on the vnode, while it is legal to call here with only a
3223  * shared lock (or no locks). If locking the vnode in an expected manner fails,
3224  * inactive processing gets deferred to the syncer.
3225  *
3226  * XXX Some filesystems pass in an exclusively locked vnode and strongly depend
3227  * on the lock being held all the way until VOP_INACTIVE. This in particular
3228  * happens with UFS which adds half-constructed vnodes to the hash, where they
3229  * can be found by other code.
3230  */
3231 static void
3232 vput_final(struct vnode *vp, enum vput_op func)
3233 {
3234 	int error;
3235 	bool want_unlock;
3236 
3237 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3238 	VNPASS(vp->v_holdcnt > 0, vp);
3239 
3240 	VI_LOCK(vp);
3241 	if (__predict_false(vp->v_type == VCHR && func != VRELE))
3242 		v_decr_devcount(vp);
3243 
3244 	/*
3245 	 * By the time we got here someone else might have transitioned
3246 	 * the count back to > 0.
3247 	 */
3248 	if (vp->v_usecount > 0)
3249 		goto out;
3250 
3251 	/*
3252 	 * If the vnode is doomed vgone already performed inactive processing
3253 	 * (if needed).
3254 	 */
3255 	if (VN_IS_DOOMED(vp))
3256 		goto out;
3257 
3258 	if (__predict_true(VOP_NEED_INACTIVE(vp) == 0))
3259 		goto out;
3260 
3261 	if (vp->v_iflag & VI_DOINGINACT)
3262 		goto out;
3263 
3264 	/*
3265 	 * Locking operations here will drop the interlock and possibly the
3266 	 * vnode lock, opening a window where the vnode can get doomed all the
3267 	 * while ->v_usecount is 0. Set VI_OWEINACT to let vgone know to
3268 	 * perform inactive.
3269 	 */
3270 	vp->v_iflag |= VI_OWEINACT;
3271 	want_unlock = false;
3272 	error = 0;
3273 	switch (func) {
3274 	case VRELE:
3275 		switch (VOP_ISLOCKED(vp)) {
3276 		case LK_EXCLUSIVE:
3277 			break;
3278 		case LK_EXCLOTHER:
3279 		case 0:
3280 			want_unlock = true;
3281 			error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3282 			VI_LOCK(vp);
3283 			break;
3284 		default:
3285 			/*
3286 			 * The lock has at least one sharer, but we have no way
3287 			 * to conclude whether this is us. Play it safe and
3288 			 * defer processing.
3289 			 */
3290 			error = EAGAIN;
3291 			break;
3292 		}
3293 		break;
3294 	case VPUT:
3295 		want_unlock = true;
3296 		if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3297 			error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3298 			    LK_NOWAIT);
3299 			VI_LOCK(vp);
3300 		}
3301 		break;
3302 	case VUNREF:
3303 		if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3304 			error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3305 			VI_LOCK(vp);
3306 		}
3307 		break;
3308 	}
3309 	if (error == 0) {
3310 		vinactive(vp);
3311 		if (want_unlock)
3312 			VOP_UNLOCK(vp);
3313 		vdropl(vp);
3314 	} else {
3315 		vdefer_inactive(vp);
3316 	}
3317 	return;
3318 out:
3319 	if (func == VPUT)
3320 		VOP_UNLOCK(vp);
3321 	vdropl(vp);
3322 }
3323 
3324 /*
3325  * Decrement ->v_usecount for a vnode.
3326  *
3327  * Releasing the last use count requires additional processing, see vput_final
3328  * above for details.
3329  *
3330  * Note that releasing use count without the vnode lock requires special casing
3331  * for VCHR, see v_decr_devcount for details.
3332  *
3333  * Comment above each variant denotes lock state on entry and exit.
3334  */
3335 
3336 static void __noinline
3337 vrele_vchr(struct vnode *vp)
3338 {
3339 
3340 	if (refcount_release_if_not_last(&vp->v_usecount))
3341 		return;
3342 	VI_LOCK(vp);
3343 	if (!refcount_release(&vp->v_usecount)) {
3344 		VI_UNLOCK(vp);
3345 		return;
3346 	}
3347 	v_decr_devcount(vp);
3348 	VI_UNLOCK(vp);
3349 	vput_final(vp, VRELE);
3350 }
3351 
3352 /*
3353  * in: any
3354  * out: same as passed in
3355  */
3356 void
3357 vrele(struct vnode *vp)
3358 {
3359 
3360 	ASSERT_VI_UNLOCKED(vp, __func__);
3361 	if (__predict_false(vp->v_type == VCHR)) {
3362 		vrele_vchr(vp);
3363 		return;
3364 	}
3365 	if (!refcount_release(&vp->v_usecount))
3366 		return;
3367 	vput_final(vp, VRELE);
3368 }
3369 
3370 /*
3371  * in: locked
3372  * out: unlocked
3373  */
3374 void
3375 vput(struct vnode *vp)
3376 {
3377 
3378 	ASSERT_VOP_LOCKED(vp, __func__);
3379 	ASSERT_VI_UNLOCKED(vp, __func__);
3380 	if (!refcount_release(&vp->v_usecount)) {
3381 		VOP_UNLOCK(vp);
3382 		return;
3383 	}
3384 	vput_final(vp, VPUT);
3385 }
3386 
3387 /*
3388  * in: locked
3389  * out: locked
3390  */
3391 void
3392 vunref(struct vnode *vp)
3393 {
3394 
3395 	ASSERT_VOP_LOCKED(vp, __func__);
3396 	ASSERT_VI_UNLOCKED(vp, __func__);
3397 	if (!refcount_release(&vp->v_usecount))
3398 		return;
3399 	vput_final(vp, VUNREF);
3400 }
3401 
3402 void
3403 vhold(struct vnode *vp)
3404 {
3405 	struct vdbatch *vd;
3406 	int old;
3407 
3408 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3409 	old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3410 	VNASSERT(old >= 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3411 	    ("%s: wrong hold count %d", __func__, old));
3412 	if (old != 0)
3413 		return;
3414 	critical_enter();
3415 	vd = DPCPU_PTR(vd);
3416 	vd->freevnodes--;
3417 	critical_exit();
3418 }
3419 
3420 void
3421 vholdl(struct vnode *vp)
3422 {
3423 
3424 	ASSERT_VI_LOCKED(vp, __func__);
3425 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3426 	vhold(vp);
3427 }
3428 
3429 void
3430 vholdnz(struct vnode *vp)
3431 {
3432 
3433 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3434 #ifdef INVARIANTS
3435 	int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3436 	VNASSERT(old > 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3437 	    ("%s: wrong hold count %d", __func__, old));
3438 #else
3439 	atomic_add_int(&vp->v_holdcnt, 1);
3440 #endif
3441 }
3442 
3443 /*
3444  * Grab a hold count as long as the vnode is not getting freed.
3445  *
3446  * Only use this routine if vfs smr is the only protection you have against
3447  * freeing the vnode.
3448  */
3449 bool
3450 vhold_smr(struct vnode *vp)
3451 {
3452 	int count;
3453 
3454 	VFS_SMR_ASSERT_ENTERED();
3455 
3456 	count = atomic_load_int(&vp->v_holdcnt);
3457 	for (;;) {
3458 		if (count & VHOLD_NO_SMR) {
3459 			VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3460 			    ("non-zero hold count with flags %d\n", count));
3461 			return (false);
3462 		}
3463 
3464 		VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3465 		if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1))
3466 			return (true);
3467 	}
3468 }
3469 
3470 static void __noinline
3471 vdbatch_process(struct vdbatch *vd)
3472 {
3473 	struct vnode *vp;
3474 	int i;
3475 
3476 	mtx_assert(&vd->lock, MA_OWNED);
3477 	MPASS(curthread->td_pinned > 0);
3478 	MPASS(vd->index == VDBATCH_SIZE);
3479 
3480 	mtx_lock(&vnode_list_mtx);
3481 	critical_enter();
3482 	freevnodes += vd->freevnodes;
3483 	for (i = 0; i < VDBATCH_SIZE; i++) {
3484 		vp = vd->tab[i];
3485 		TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3486 		TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3487 		MPASS(vp->v_dbatchcpu != NOCPU);
3488 		vp->v_dbatchcpu = NOCPU;
3489 	}
3490 	mtx_unlock(&vnode_list_mtx);
3491 	vd->freevnodes = 0;
3492 	bzero(vd->tab, sizeof(vd->tab));
3493 	vd->index = 0;
3494 	critical_exit();
3495 }
3496 
3497 static void
3498 vdbatch_enqueue(struct vnode *vp)
3499 {
3500 	struct vdbatch *vd;
3501 
3502 	ASSERT_VI_LOCKED(vp, __func__);
3503 	VNASSERT(!VN_IS_DOOMED(vp), vp,
3504 	    ("%s: deferring requeue of a doomed vnode", __func__));
3505 
3506 	critical_enter();
3507 	vd = DPCPU_PTR(vd);
3508 	vd->freevnodes++;
3509 	if (vp->v_dbatchcpu != NOCPU) {
3510 		VI_UNLOCK(vp);
3511 		critical_exit();
3512 		return;
3513 	}
3514 
3515 	sched_pin();
3516 	critical_exit();
3517 	mtx_lock(&vd->lock);
3518 	MPASS(vd->index < VDBATCH_SIZE);
3519 	MPASS(vd->tab[vd->index] == NULL);
3520 	/*
3521 	 * A hack: we depend on being pinned so that we know what to put in
3522 	 * ->v_dbatchcpu.
3523 	 */
3524 	vp->v_dbatchcpu = curcpu;
3525 	vd->tab[vd->index] = vp;
3526 	vd->index++;
3527 	VI_UNLOCK(vp);
3528 	if (vd->index == VDBATCH_SIZE)
3529 		vdbatch_process(vd);
3530 	mtx_unlock(&vd->lock);
3531 	sched_unpin();
3532 }
3533 
3534 /*
3535  * This routine must only be called for vnodes which are about to be
3536  * deallocated. Supporting dequeue for arbitrary vndoes would require
3537  * validating that the locked batch matches.
3538  */
3539 static void
3540 vdbatch_dequeue(struct vnode *vp)
3541 {
3542 	struct vdbatch *vd;
3543 	int i;
3544 	short cpu;
3545 
3546 	VNASSERT(vp->v_type == VBAD || vp->v_type == VNON, vp,
3547 	    ("%s: called for a used vnode\n", __func__));
3548 
3549 	cpu = vp->v_dbatchcpu;
3550 	if (cpu == NOCPU)
3551 		return;
3552 
3553 	vd = DPCPU_ID_PTR(cpu, vd);
3554 	mtx_lock(&vd->lock);
3555 	for (i = 0; i < vd->index; i++) {
3556 		if (vd->tab[i] != vp)
3557 			continue;
3558 		vp->v_dbatchcpu = NOCPU;
3559 		vd->index--;
3560 		vd->tab[i] = vd->tab[vd->index];
3561 		vd->tab[vd->index] = NULL;
3562 		break;
3563 	}
3564 	mtx_unlock(&vd->lock);
3565 	/*
3566 	 * Either we dequeued the vnode above or the target CPU beat us to it.
3567 	 */
3568 	MPASS(vp->v_dbatchcpu == NOCPU);
3569 }
3570 
3571 /*
3572  * Drop the hold count of the vnode.  If this is the last reference to
3573  * the vnode we place it on the free list unless it has been vgone'd
3574  * (marked VIRF_DOOMED) in which case we will free it.
3575  *
3576  * Because the vnode vm object keeps a hold reference on the vnode if
3577  * there is at least one resident non-cached page, the vnode cannot
3578  * leave the active list without the page cleanup done.
3579  */
3580 static void
3581 vdrop_deactivate(struct vnode *vp)
3582 {
3583 	struct mount *mp;
3584 
3585 	ASSERT_VI_LOCKED(vp, __func__);
3586 	/*
3587 	 * Mark a vnode as free: remove it from its active list
3588 	 * and put it up for recycling on the freelist.
3589 	 */
3590 	VNASSERT(!VN_IS_DOOMED(vp), vp,
3591 	    ("vdrop: returning doomed vnode"));
3592 	VNASSERT(vp->v_op != NULL, vp,
3593 	    ("vdrop: vnode already reclaimed."));
3594 	VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
3595 	    ("vnode with VI_OWEINACT set"));
3596 	VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp,
3597 	    ("vnode with VI_DEFINACT set"));
3598 	if (vp->v_mflag & VMP_LAZYLIST) {
3599 		mp = vp->v_mount;
3600 		mtx_lock(&mp->mnt_listmtx);
3601 		VNASSERT(vp->v_mflag & VMP_LAZYLIST, vp, ("lost VMP_LAZYLIST"));
3602 		/*
3603 		 * Don't remove the vnode from the lazy list if another thread
3604 		 * has increased the hold count. It may have re-enqueued the
3605 		 * vnode to the lazy list and is now responsible for its
3606 		 * removal.
3607 		 */
3608 		if (vp->v_holdcnt == 0) {
3609 			vp->v_mflag &= ~VMP_LAZYLIST;
3610 			TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3611 			mp->mnt_lazyvnodelistsize--;
3612 		}
3613 		mtx_unlock(&mp->mnt_listmtx);
3614 	}
3615 	vdbatch_enqueue(vp);
3616 }
3617 
3618 void
3619 vdrop(struct vnode *vp)
3620 {
3621 
3622 	ASSERT_VI_UNLOCKED(vp, __func__);
3623 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3624 	if (refcount_release_if_not_last(&vp->v_holdcnt))
3625 		return;
3626 	VI_LOCK(vp);
3627 	vdropl(vp);
3628 }
3629 
3630 void
3631 vdropl(struct vnode *vp)
3632 {
3633 
3634 	ASSERT_VI_LOCKED(vp, __func__);
3635 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3636 	if (!refcount_release(&vp->v_holdcnt)) {
3637 		VI_UNLOCK(vp);
3638 		return;
3639 	}
3640 	if (!VN_IS_DOOMED(vp)) {
3641 		vdrop_deactivate(vp);
3642 		return;
3643 	}
3644 	/*
3645 	 * We may be racing against vhold_smr.
3646 	 *
3647 	 * If they win we can just pretend we never got this far, they will
3648 	 * vdrop later.
3649 	 */
3650 	if (!atomic_cmpset_int(&vp->v_holdcnt, 0, VHOLD_NO_SMR)) {
3651 		/*
3652 		 * We lost the aforementioned race. Note that any subsequent
3653 		 * access is invalid as they might have managed to vdropl on
3654 		 * their own.
3655 		 */
3656 		return;
3657 	}
3658 	freevnode(vp);
3659 }
3660 
3661 /*
3662  * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3663  * flags.  DOINGINACT prevents us from recursing in calls to vinactive.
3664  */
3665 static void
3666 vinactivef(struct vnode *vp)
3667 {
3668 	struct vm_object *obj;
3669 
3670 	ASSERT_VOP_ELOCKED(vp, "vinactive");
3671 	ASSERT_VI_LOCKED(vp, "vinactive");
3672 	VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3673 	    ("vinactive: recursed on VI_DOINGINACT"));
3674 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3675 	vp->v_iflag |= VI_DOINGINACT;
3676 	vp->v_iflag &= ~VI_OWEINACT;
3677 	VI_UNLOCK(vp);
3678 	/*
3679 	 * Before moving off the active list, we must be sure that any
3680 	 * modified pages are converted into the vnode's dirty
3681 	 * buffers, since these will no longer be checked once the
3682 	 * vnode is on the inactive list.
3683 	 *
3684 	 * The write-out of the dirty pages is asynchronous.  At the
3685 	 * point that VOP_INACTIVE() is called, there could still be
3686 	 * pending I/O and dirty pages in the object.
3687 	 */
3688 	if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3689 	    vm_object_mightbedirty(obj)) {
3690 		VM_OBJECT_WLOCK(obj);
3691 		vm_object_page_clean(obj, 0, 0, 0);
3692 		VM_OBJECT_WUNLOCK(obj);
3693 	}
3694 	VOP_INACTIVE(vp, curthread);
3695 	VI_LOCK(vp);
3696 	VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3697 	    ("vinactive: lost VI_DOINGINACT"));
3698 	vp->v_iflag &= ~VI_DOINGINACT;
3699 }
3700 
3701 void
3702 vinactive(struct vnode *vp)
3703 {
3704 
3705 	ASSERT_VOP_ELOCKED(vp, "vinactive");
3706 	ASSERT_VI_LOCKED(vp, "vinactive");
3707 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3708 
3709 	if ((vp->v_iflag & VI_OWEINACT) == 0)
3710 		return;
3711 	if (vp->v_iflag & VI_DOINGINACT)
3712 		return;
3713 	if (vp->v_usecount > 0) {
3714 		vp->v_iflag &= ~VI_OWEINACT;
3715 		return;
3716 	}
3717 	vinactivef(vp);
3718 }
3719 
3720 /*
3721  * Remove any vnodes in the vnode table belonging to mount point mp.
3722  *
3723  * If FORCECLOSE is not specified, there should not be any active ones,
3724  * return error if any are found (nb: this is a user error, not a
3725  * system error). If FORCECLOSE is specified, detach any active vnodes
3726  * that are found.
3727  *
3728  * If WRITECLOSE is set, only flush out regular file vnodes open for
3729  * writing.
3730  *
3731  * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3732  *
3733  * `rootrefs' specifies the base reference count for the root vnode
3734  * of this filesystem. The root vnode is considered busy if its
3735  * v_usecount exceeds this value. On a successful return, vflush(, td)
3736  * will call vrele() on the root vnode exactly rootrefs times.
3737  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3738  * be zero.
3739  */
3740 #ifdef DIAGNOSTIC
3741 static int busyprt = 0;		/* print out busy vnodes */
3742 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3743 #endif
3744 
3745 int
3746 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3747 {
3748 	struct vnode *vp, *mvp, *rootvp = NULL;
3749 	struct vattr vattr;
3750 	int busy = 0, error;
3751 
3752 	CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3753 	    rootrefs, flags);
3754 	if (rootrefs > 0) {
3755 		KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3756 		    ("vflush: bad args"));
3757 		/*
3758 		 * Get the filesystem root vnode. We can vput() it
3759 		 * immediately, since with rootrefs > 0, it won't go away.
3760 		 */
3761 		if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3762 			CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3763 			    __func__, error);
3764 			return (error);
3765 		}
3766 		vput(rootvp);
3767 	}
3768 loop:
3769 	MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3770 		vholdl(vp);
3771 		error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3772 		if (error) {
3773 			vdrop(vp);
3774 			MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3775 			goto loop;
3776 		}
3777 		/*
3778 		 * Skip over a vnodes marked VV_SYSTEM.
3779 		 */
3780 		if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3781 			VOP_UNLOCK(vp);
3782 			vdrop(vp);
3783 			continue;
3784 		}
3785 		/*
3786 		 * If WRITECLOSE is set, flush out unlinked but still open
3787 		 * files (even if open only for reading) and regular file
3788 		 * vnodes open for writing.
3789 		 */
3790 		if (flags & WRITECLOSE) {
3791 			if (vp->v_object != NULL) {
3792 				VM_OBJECT_WLOCK(vp->v_object);
3793 				vm_object_page_clean(vp->v_object, 0, 0, 0);
3794 				VM_OBJECT_WUNLOCK(vp->v_object);
3795 			}
3796 			error = VOP_FSYNC(vp, MNT_WAIT, td);
3797 			if (error != 0) {
3798 				VOP_UNLOCK(vp);
3799 				vdrop(vp);
3800 				MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3801 				return (error);
3802 			}
3803 			error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3804 			VI_LOCK(vp);
3805 
3806 			if ((vp->v_type == VNON ||
3807 			    (error == 0 && vattr.va_nlink > 0)) &&
3808 			    (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3809 				VOP_UNLOCK(vp);
3810 				vdropl(vp);
3811 				continue;
3812 			}
3813 		} else
3814 			VI_LOCK(vp);
3815 		/*
3816 		 * With v_usecount == 0, all we need to do is clear out the
3817 		 * vnode data structures and we are done.
3818 		 *
3819 		 * If FORCECLOSE is set, forcibly close the vnode.
3820 		 */
3821 		if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3822 			vgonel(vp);
3823 		} else {
3824 			busy++;
3825 #ifdef DIAGNOSTIC
3826 			if (busyprt)
3827 				vn_printf(vp, "vflush: busy vnode ");
3828 #endif
3829 		}
3830 		VOP_UNLOCK(vp);
3831 		vdropl(vp);
3832 	}
3833 	if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3834 		/*
3835 		 * If just the root vnode is busy, and if its refcount
3836 		 * is equal to `rootrefs', then go ahead and kill it.
3837 		 */
3838 		VI_LOCK(rootvp);
3839 		KASSERT(busy > 0, ("vflush: not busy"));
3840 		VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3841 		    ("vflush: usecount %d < rootrefs %d",
3842 		     rootvp->v_usecount, rootrefs));
3843 		if (busy == 1 && rootvp->v_usecount == rootrefs) {
3844 			VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3845 			vgone(rootvp);
3846 			VOP_UNLOCK(rootvp);
3847 			busy = 0;
3848 		} else
3849 			VI_UNLOCK(rootvp);
3850 	}
3851 	if (busy) {
3852 		CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3853 		    busy);
3854 		return (EBUSY);
3855 	}
3856 	for (; rootrefs > 0; rootrefs--)
3857 		vrele(rootvp);
3858 	return (0);
3859 }
3860 
3861 /*
3862  * Recycle an unused vnode to the front of the free list.
3863  */
3864 int
3865 vrecycle(struct vnode *vp)
3866 {
3867 	int recycled;
3868 
3869 	VI_LOCK(vp);
3870 	recycled = vrecyclel(vp);
3871 	VI_UNLOCK(vp);
3872 	return (recycled);
3873 }
3874 
3875 /*
3876  * vrecycle, with the vp interlock held.
3877  */
3878 int
3879 vrecyclel(struct vnode *vp)
3880 {
3881 	int recycled;
3882 
3883 	ASSERT_VOP_ELOCKED(vp, __func__);
3884 	ASSERT_VI_LOCKED(vp, __func__);
3885 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3886 	recycled = 0;
3887 	if (vp->v_usecount == 0) {
3888 		recycled = 1;
3889 		vgonel(vp);
3890 	}
3891 	return (recycled);
3892 }
3893 
3894 /*
3895  * Eliminate all activity associated with a vnode
3896  * in preparation for reuse.
3897  */
3898 void
3899 vgone(struct vnode *vp)
3900 {
3901 	VI_LOCK(vp);
3902 	vgonel(vp);
3903 	VI_UNLOCK(vp);
3904 }
3905 
3906 static void
3907 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3908     struct vnode *lowervp __unused)
3909 {
3910 }
3911 
3912 /*
3913  * Notify upper mounts about reclaimed or unlinked vnode.
3914  */
3915 void
3916 vfs_notify_upper(struct vnode *vp, int event)
3917 {
3918 	static struct vfsops vgonel_vfsops = {
3919 		.vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3920 		.vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3921 	};
3922 	struct mount *mp, *ump, *mmp;
3923 
3924 	mp = vp->v_mount;
3925 	if (mp == NULL)
3926 		return;
3927 	if (TAILQ_EMPTY(&mp->mnt_uppers))
3928 		return;
3929 
3930 	mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3931 	mmp->mnt_op = &vgonel_vfsops;
3932 	mmp->mnt_kern_flag |= MNTK_MARKER;
3933 	MNT_ILOCK(mp);
3934 	mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3935 	for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3936 		if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3937 			ump = TAILQ_NEXT(ump, mnt_upper_link);
3938 			continue;
3939 		}
3940 		TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3941 		MNT_IUNLOCK(mp);
3942 		switch (event) {
3943 		case VFS_NOTIFY_UPPER_RECLAIM:
3944 			VFS_RECLAIM_LOWERVP(ump, vp);
3945 			break;
3946 		case VFS_NOTIFY_UPPER_UNLINK:
3947 			VFS_UNLINK_LOWERVP(ump, vp);
3948 			break;
3949 		default:
3950 			KASSERT(0, ("invalid event %d", event));
3951 			break;
3952 		}
3953 		MNT_ILOCK(mp);
3954 		ump = TAILQ_NEXT(mmp, mnt_upper_link);
3955 		TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3956 	}
3957 	free(mmp, M_TEMP);
3958 	mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3959 	if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3960 		mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3961 		wakeup(&mp->mnt_uppers);
3962 	}
3963 	MNT_IUNLOCK(mp);
3964 }
3965 
3966 /*
3967  * vgone, with the vp interlock held.
3968  */
3969 static void
3970 vgonel(struct vnode *vp)
3971 {
3972 	struct thread *td;
3973 	struct mount *mp;
3974 	vm_object_t object;
3975 	bool active, oweinact;
3976 
3977 	ASSERT_VOP_ELOCKED(vp, "vgonel");
3978 	ASSERT_VI_LOCKED(vp, "vgonel");
3979 	VNASSERT(vp->v_holdcnt, vp,
3980 	    ("vgonel: vp %p has no reference.", vp));
3981 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3982 	td = curthread;
3983 
3984 	/*
3985 	 * Don't vgonel if we're already doomed.
3986 	 */
3987 	if (vp->v_irflag & VIRF_DOOMED)
3988 		return;
3989 	vunlazy_gone(vp);
3990 	vp->v_irflag |= VIRF_DOOMED;
3991 
3992 	/*
3993 	 * Check to see if the vnode is in use.  If so, we have to call
3994 	 * VOP_CLOSE() and VOP_INACTIVE().
3995 	 */
3996 	active = vp->v_usecount > 0;
3997 	oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
3998 	/*
3999 	 * If we need to do inactive VI_OWEINACT will be set.
4000 	 */
4001 	if (vp->v_iflag & VI_DEFINACT) {
4002 		VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
4003 		vp->v_iflag &= ~VI_DEFINACT;
4004 		vdropl(vp);
4005 	} else {
4006 		VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
4007 		VI_UNLOCK(vp);
4008 	}
4009 	vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
4010 
4011 	/*
4012 	 * If purging an active vnode, it must be closed and
4013 	 * deactivated before being reclaimed.
4014 	 */
4015 	if (active)
4016 		VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
4017 	if (oweinact || active) {
4018 		VI_LOCK(vp);
4019 		vinactivef(vp);
4020 		VI_UNLOCK(vp);
4021 	}
4022 	if (vp->v_type == VSOCK)
4023 		vfs_unp_reclaim(vp);
4024 
4025 	/*
4026 	 * Clean out any buffers associated with the vnode.
4027 	 * If the flush fails, just toss the buffers.
4028 	 */
4029 	mp = NULL;
4030 	if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
4031 		(void) vn_start_secondary_write(vp, &mp, V_WAIT);
4032 	if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
4033 		while (vinvalbuf(vp, 0, 0, 0) != 0)
4034 			;
4035 	}
4036 
4037 	BO_LOCK(&vp->v_bufobj);
4038 	KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
4039 	    vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
4040 	    TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
4041 	    vp->v_bufobj.bo_clean.bv_cnt == 0,
4042 	    ("vp %p bufobj not invalidated", vp));
4043 
4044 	/*
4045 	 * For VMIO bufobj, BO_DEAD is set later, or in
4046 	 * vm_object_terminate() after the object's page queue is
4047 	 * flushed.
4048 	 */
4049 	object = vp->v_bufobj.bo_object;
4050 	if (object == NULL)
4051 		vp->v_bufobj.bo_flag |= BO_DEAD;
4052 	BO_UNLOCK(&vp->v_bufobj);
4053 
4054 	/*
4055 	 * Handle the VM part.  Tmpfs handles v_object on its own (the
4056 	 * OBJT_VNODE check).  Nullfs or other bypassing filesystems
4057 	 * should not touch the object borrowed from the lower vnode
4058 	 * (the handle check).
4059 	 */
4060 	if (object != NULL && object->type == OBJT_VNODE &&
4061 	    object->handle == vp)
4062 		vnode_destroy_vobject(vp);
4063 
4064 	/*
4065 	 * Reclaim the vnode.
4066 	 */
4067 	if (VOP_RECLAIM(vp, td))
4068 		panic("vgone: cannot reclaim");
4069 	if (mp != NULL)
4070 		vn_finished_secondary_write(mp);
4071 	VNASSERT(vp->v_object == NULL, vp,
4072 	    ("vop_reclaim left v_object vp=%p", vp));
4073 	/*
4074 	 * Clear the advisory locks and wake up waiting threads.
4075 	 */
4076 	(void)VOP_ADVLOCKPURGE(vp);
4077 	vp->v_lockf = NULL;
4078 	/*
4079 	 * Delete from old mount point vnode list.
4080 	 */
4081 	delmntque(vp);
4082 	cache_purge(vp);
4083 	/*
4084 	 * Done with purge, reset to the standard lock and invalidate
4085 	 * the vnode.
4086 	 */
4087 	VI_LOCK(vp);
4088 	vp->v_vnlock = &vp->v_lock;
4089 	vp->v_op = &dead_vnodeops;
4090 	vp->v_type = VBAD;
4091 }
4092 
4093 /*
4094  * Calculate the total number of references to a special device.
4095  */
4096 int
4097 vcount(struct vnode *vp)
4098 {
4099 	int count;
4100 
4101 	dev_lock();
4102 	count = vp->v_rdev->si_usecount;
4103 	dev_unlock();
4104 	return (count);
4105 }
4106 
4107 /*
4108  * Print out a description of a vnode.
4109  */
4110 static const char * const typename[] =
4111 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
4112  "VMARKER"};
4113 
4114 _Static_assert((VHOLD_ALL_FLAGS & ~VHOLD_NO_SMR) == 0,
4115     "new hold count flag not added to vn_printf");
4116 
4117 void
4118 vn_printf(struct vnode *vp, const char *fmt, ...)
4119 {
4120 	va_list ap;
4121 	char buf[256], buf2[16];
4122 	u_long flags;
4123 	u_int holdcnt;
4124 
4125 	va_start(ap, fmt);
4126 	vprintf(fmt, ap);
4127 	va_end(ap);
4128 	printf("%p: ", (void *)vp);
4129 	printf("type %s\n", typename[vp->v_type]);
4130 	holdcnt = atomic_load_int(&vp->v_holdcnt);
4131 	printf("    usecount %d, writecount %d, refcount %d",
4132 	    vp->v_usecount, vp->v_writecount, holdcnt & ~VHOLD_ALL_FLAGS);
4133 	switch (vp->v_type) {
4134 	case VDIR:
4135 		printf(" mountedhere %p\n", vp->v_mountedhere);
4136 		break;
4137 	case VCHR:
4138 		printf(" rdev %p\n", vp->v_rdev);
4139 		break;
4140 	case VSOCK:
4141 		printf(" socket %p\n", vp->v_unpcb);
4142 		break;
4143 	case VFIFO:
4144 		printf(" fifoinfo %p\n", vp->v_fifoinfo);
4145 		break;
4146 	default:
4147 		printf("\n");
4148 		break;
4149 	}
4150 	buf[0] = '\0';
4151 	buf[1] = '\0';
4152 	if (holdcnt & VHOLD_NO_SMR)
4153 		strlcat(buf, "|VHOLD_NO_SMR", sizeof(buf));
4154 	printf("    hold count flags (%s)\n", buf + 1);
4155 
4156 	buf[0] = '\0';
4157 	buf[1] = '\0';
4158 	if (vp->v_irflag & VIRF_DOOMED)
4159 		strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
4160 	flags = vp->v_irflag & ~(VIRF_DOOMED);
4161 	if (flags != 0) {
4162 		snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
4163 		strlcat(buf, buf2, sizeof(buf));
4164 	}
4165 	if (vp->v_vflag & VV_ROOT)
4166 		strlcat(buf, "|VV_ROOT", sizeof(buf));
4167 	if (vp->v_vflag & VV_ISTTY)
4168 		strlcat(buf, "|VV_ISTTY", sizeof(buf));
4169 	if (vp->v_vflag & VV_NOSYNC)
4170 		strlcat(buf, "|VV_NOSYNC", sizeof(buf));
4171 	if (vp->v_vflag & VV_ETERNALDEV)
4172 		strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
4173 	if (vp->v_vflag & VV_CACHEDLABEL)
4174 		strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
4175 	if (vp->v_vflag & VV_VMSIZEVNLOCK)
4176 		strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
4177 	if (vp->v_vflag & VV_COPYONWRITE)
4178 		strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
4179 	if (vp->v_vflag & VV_SYSTEM)
4180 		strlcat(buf, "|VV_SYSTEM", sizeof(buf));
4181 	if (vp->v_vflag & VV_PROCDEP)
4182 		strlcat(buf, "|VV_PROCDEP", sizeof(buf));
4183 	if (vp->v_vflag & VV_NOKNOTE)
4184 		strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
4185 	if (vp->v_vflag & VV_DELETED)
4186 		strlcat(buf, "|VV_DELETED", sizeof(buf));
4187 	if (vp->v_vflag & VV_MD)
4188 		strlcat(buf, "|VV_MD", sizeof(buf));
4189 	if (vp->v_vflag & VV_FORCEINSMQ)
4190 		strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
4191 	if (vp->v_vflag & VV_READLINK)
4192 		strlcat(buf, "|VV_READLINK", sizeof(buf));
4193 	flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4194 	    VV_CACHEDLABEL | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
4195 	    VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
4196 	if (flags != 0) {
4197 		snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4198 		strlcat(buf, buf2, sizeof(buf));
4199 	}
4200 	if (vp->v_iflag & VI_TEXT_REF)
4201 		strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
4202 	if (vp->v_iflag & VI_MOUNT)
4203 		strlcat(buf, "|VI_MOUNT", sizeof(buf));
4204 	if (vp->v_iflag & VI_DOINGINACT)
4205 		strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4206 	if (vp->v_iflag & VI_OWEINACT)
4207 		strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4208 	if (vp->v_iflag & VI_DEFINACT)
4209 		strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4210 	flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOINGINACT |
4211 	    VI_OWEINACT | VI_DEFINACT);
4212 	if (flags != 0) {
4213 		snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4214 		strlcat(buf, buf2, sizeof(buf));
4215 	}
4216 	if (vp->v_mflag & VMP_LAZYLIST)
4217 		strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4218 	flags = vp->v_mflag & ~(VMP_LAZYLIST);
4219 	if (flags != 0) {
4220 		snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4221 		strlcat(buf, buf2, sizeof(buf));
4222 	}
4223 	printf("    flags (%s)\n", buf + 1);
4224 	if (mtx_owned(VI_MTX(vp)))
4225 		printf(" VI_LOCKed");
4226 	if (vp->v_object != NULL)
4227 		printf("    v_object %p ref %d pages %d "
4228 		    "cleanbuf %d dirtybuf %d\n",
4229 		    vp->v_object, vp->v_object->ref_count,
4230 		    vp->v_object->resident_page_count,
4231 		    vp->v_bufobj.bo_clean.bv_cnt,
4232 		    vp->v_bufobj.bo_dirty.bv_cnt);
4233 	printf("    ");
4234 	lockmgr_printinfo(vp->v_vnlock);
4235 	if (vp->v_data != NULL)
4236 		VOP_PRINT(vp);
4237 }
4238 
4239 #ifdef DDB
4240 /*
4241  * List all of the locked vnodes in the system.
4242  * Called when debugging the kernel.
4243  */
4244 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
4245 {
4246 	struct mount *mp;
4247 	struct vnode *vp;
4248 
4249 	/*
4250 	 * Note: because this is DDB, we can't obey the locking semantics
4251 	 * for these structures, which means we could catch an inconsistent
4252 	 * state and dereference a nasty pointer.  Not much to be done
4253 	 * about that.
4254 	 */
4255 	db_printf("Locked vnodes\n");
4256 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4257 		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4258 			if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4259 				vn_printf(vp, "vnode ");
4260 		}
4261 	}
4262 }
4263 
4264 /*
4265  * Show details about the given vnode.
4266  */
4267 DB_SHOW_COMMAND(vnode, db_show_vnode)
4268 {
4269 	struct vnode *vp;
4270 
4271 	if (!have_addr)
4272 		return;
4273 	vp = (struct vnode *)addr;
4274 	vn_printf(vp, "vnode ");
4275 }
4276 
4277 /*
4278  * Show details about the given mount point.
4279  */
4280 DB_SHOW_COMMAND(mount, db_show_mount)
4281 {
4282 	struct mount *mp;
4283 	struct vfsopt *opt;
4284 	struct statfs *sp;
4285 	struct vnode *vp;
4286 	char buf[512];
4287 	uint64_t mflags;
4288 	u_int flags;
4289 
4290 	if (!have_addr) {
4291 		/* No address given, print short info about all mount points. */
4292 		TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4293 			db_printf("%p %s on %s (%s)\n", mp,
4294 			    mp->mnt_stat.f_mntfromname,
4295 			    mp->mnt_stat.f_mntonname,
4296 			    mp->mnt_stat.f_fstypename);
4297 			if (db_pager_quit)
4298 				break;
4299 		}
4300 		db_printf("\nMore info: show mount <addr>\n");
4301 		return;
4302 	}
4303 
4304 	mp = (struct mount *)addr;
4305 	db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4306 	    mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4307 
4308 	buf[0] = '\0';
4309 	mflags = mp->mnt_flag;
4310 #define	MNT_FLAG(flag)	do {						\
4311 	if (mflags & (flag)) {						\
4312 		if (buf[0] != '\0')					\
4313 			strlcat(buf, ", ", sizeof(buf));		\
4314 		strlcat(buf, (#flag) + 4, sizeof(buf));			\
4315 		mflags &= ~(flag);					\
4316 	}								\
4317 } while (0)
4318 	MNT_FLAG(MNT_RDONLY);
4319 	MNT_FLAG(MNT_SYNCHRONOUS);
4320 	MNT_FLAG(MNT_NOEXEC);
4321 	MNT_FLAG(MNT_NOSUID);
4322 	MNT_FLAG(MNT_NFS4ACLS);
4323 	MNT_FLAG(MNT_UNION);
4324 	MNT_FLAG(MNT_ASYNC);
4325 	MNT_FLAG(MNT_SUIDDIR);
4326 	MNT_FLAG(MNT_SOFTDEP);
4327 	MNT_FLAG(MNT_NOSYMFOLLOW);
4328 	MNT_FLAG(MNT_GJOURNAL);
4329 	MNT_FLAG(MNT_MULTILABEL);
4330 	MNT_FLAG(MNT_ACLS);
4331 	MNT_FLAG(MNT_NOATIME);
4332 	MNT_FLAG(MNT_NOCLUSTERR);
4333 	MNT_FLAG(MNT_NOCLUSTERW);
4334 	MNT_FLAG(MNT_SUJ);
4335 	MNT_FLAG(MNT_EXRDONLY);
4336 	MNT_FLAG(MNT_EXPORTED);
4337 	MNT_FLAG(MNT_DEFEXPORTED);
4338 	MNT_FLAG(MNT_EXPORTANON);
4339 	MNT_FLAG(MNT_EXKERB);
4340 	MNT_FLAG(MNT_EXPUBLIC);
4341 	MNT_FLAG(MNT_LOCAL);
4342 	MNT_FLAG(MNT_QUOTA);
4343 	MNT_FLAG(MNT_ROOTFS);
4344 	MNT_FLAG(MNT_USER);
4345 	MNT_FLAG(MNT_IGNORE);
4346 	MNT_FLAG(MNT_UPDATE);
4347 	MNT_FLAG(MNT_DELEXPORT);
4348 	MNT_FLAG(MNT_RELOAD);
4349 	MNT_FLAG(MNT_FORCE);
4350 	MNT_FLAG(MNT_SNAPSHOT);
4351 	MNT_FLAG(MNT_BYFSID);
4352 #undef MNT_FLAG
4353 	if (mflags != 0) {
4354 		if (buf[0] != '\0')
4355 			strlcat(buf, ", ", sizeof(buf));
4356 		snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4357 		    "0x%016jx", mflags);
4358 	}
4359 	db_printf("    mnt_flag = %s\n", buf);
4360 
4361 	buf[0] = '\0';
4362 	flags = mp->mnt_kern_flag;
4363 #define	MNT_KERN_FLAG(flag)	do {					\
4364 	if (flags & (flag)) {						\
4365 		if (buf[0] != '\0')					\
4366 			strlcat(buf, ", ", sizeof(buf));		\
4367 		strlcat(buf, (#flag) + 5, sizeof(buf));			\
4368 		flags &= ~(flag);					\
4369 	}								\
4370 } while (0)
4371 	MNT_KERN_FLAG(MNTK_UNMOUNTF);
4372 	MNT_KERN_FLAG(MNTK_ASYNC);
4373 	MNT_KERN_FLAG(MNTK_SOFTDEP);
4374 	MNT_KERN_FLAG(MNTK_DRAINING);
4375 	MNT_KERN_FLAG(MNTK_REFEXPIRE);
4376 	MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4377 	MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4378 	MNT_KERN_FLAG(MNTK_NO_IOPF);
4379 	MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4380 	MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4381 	MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4382 	MNT_KERN_FLAG(MNTK_MARKER);
4383 	MNT_KERN_FLAG(MNTK_USES_BCACHE);
4384 	MNT_KERN_FLAG(MNTK_NOASYNC);
4385 	MNT_KERN_FLAG(MNTK_UNMOUNT);
4386 	MNT_KERN_FLAG(MNTK_MWAIT);
4387 	MNT_KERN_FLAG(MNTK_SUSPEND);
4388 	MNT_KERN_FLAG(MNTK_SUSPEND2);
4389 	MNT_KERN_FLAG(MNTK_SUSPENDED);
4390 	MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4391 	MNT_KERN_FLAG(MNTK_NOKNOTE);
4392 #undef MNT_KERN_FLAG
4393 	if (flags != 0) {
4394 		if (buf[0] != '\0')
4395 			strlcat(buf, ", ", sizeof(buf));
4396 		snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4397 		    "0x%08x", flags);
4398 	}
4399 	db_printf("    mnt_kern_flag = %s\n", buf);
4400 
4401 	db_printf("    mnt_opt = ");
4402 	opt = TAILQ_FIRST(mp->mnt_opt);
4403 	if (opt != NULL) {
4404 		db_printf("%s", opt->name);
4405 		opt = TAILQ_NEXT(opt, link);
4406 		while (opt != NULL) {
4407 			db_printf(", %s", opt->name);
4408 			opt = TAILQ_NEXT(opt, link);
4409 		}
4410 	}
4411 	db_printf("\n");
4412 
4413 	sp = &mp->mnt_stat;
4414 	db_printf("    mnt_stat = { version=%u type=%u flags=0x%016jx "
4415 	    "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4416 	    "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4417 	    "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4418 	    (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4419 	    (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4420 	    (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4421 	    (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4422 	    (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4423 	    (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4424 	    (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4425 	    (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4426 
4427 	db_printf("    mnt_cred = { uid=%u ruid=%u",
4428 	    (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4429 	if (jailed(mp->mnt_cred))
4430 		db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4431 	db_printf(" }\n");
4432 	db_printf("    mnt_ref = %d (with %d in the struct)\n",
4433 	    vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4434 	db_printf("    mnt_gen = %d\n", mp->mnt_gen);
4435 	db_printf("    mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4436 	db_printf("    mnt_lazyvnodelistsize = %d\n",
4437 	    mp->mnt_lazyvnodelistsize);
4438 	db_printf("    mnt_writeopcount = %d (with %d in the struct)\n",
4439 	    vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4440 	db_printf("    mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
4441 	db_printf("    mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4442 	db_printf("    mnt_hashseed = %u\n", mp->mnt_hashseed);
4443 	db_printf("    mnt_lockref = %d (with %d in the struct)\n",
4444 	    vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4445 	db_printf("    mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4446 	db_printf("    mnt_secondary_accwrites = %d\n",
4447 	    mp->mnt_secondary_accwrites);
4448 	db_printf("    mnt_gjprovider = %s\n",
4449 	    mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4450 	db_printf("    mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4451 
4452 	db_printf("\n\nList of active vnodes\n");
4453 	TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4454 		if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4455 			vn_printf(vp, "vnode ");
4456 			if (db_pager_quit)
4457 				break;
4458 		}
4459 	}
4460 	db_printf("\n\nList of inactive vnodes\n");
4461 	TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4462 		if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4463 			vn_printf(vp, "vnode ");
4464 			if (db_pager_quit)
4465 				break;
4466 		}
4467 	}
4468 }
4469 #endif	/* DDB */
4470 
4471 /*
4472  * Fill in a struct xvfsconf based on a struct vfsconf.
4473  */
4474 static int
4475 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4476 {
4477 	struct xvfsconf xvfsp;
4478 
4479 	bzero(&xvfsp, sizeof(xvfsp));
4480 	strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4481 	xvfsp.vfc_typenum = vfsp->vfc_typenum;
4482 	xvfsp.vfc_refcount = vfsp->vfc_refcount;
4483 	xvfsp.vfc_flags = vfsp->vfc_flags;
4484 	/*
4485 	 * These are unused in userland, we keep them
4486 	 * to not break binary compatibility.
4487 	 */
4488 	xvfsp.vfc_vfsops = NULL;
4489 	xvfsp.vfc_next = NULL;
4490 	return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4491 }
4492 
4493 #ifdef COMPAT_FREEBSD32
4494 struct xvfsconf32 {
4495 	uint32_t	vfc_vfsops;
4496 	char		vfc_name[MFSNAMELEN];
4497 	int32_t		vfc_typenum;
4498 	int32_t		vfc_refcount;
4499 	int32_t		vfc_flags;
4500 	uint32_t	vfc_next;
4501 };
4502 
4503 static int
4504 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4505 {
4506 	struct xvfsconf32 xvfsp;
4507 
4508 	bzero(&xvfsp, sizeof(xvfsp));
4509 	strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4510 	xvfsp.vfc_typenum = vfsp->vfc_typenum;
4511 	xvfsp.vfc_refcount = vfsp->vfc_refcount;
4512 	xvfsp.vfc_flags = vfsp->vfc_flags;
4513 	return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4514 }
4515 #endif
4516 
4517 /*
4518  * Top level filesystem related information gathering.
4519  */
4520 static int
4521 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4522 {
4523 	struct vfsconf *vfsp;
4524 	int error;
4525 
4526 	error = 0;
4527 	vfsconf_slock();
4528 	TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4529 #ifdef COMPAT_FREEBSD32
4530 		if (req->flags & SCTL_MASK32)
4531 			error = vfsconf2x32(req, vfsp);
4532 		else
4533 #endif
4534 			error = vfsconf2x(req, vfsp);
4535 		if (error)
4536 			break;
4537 	}
4538 	vfsconf_sunlock();
4539 	return (error);
4540 }
4541 
4542 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4543     CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4544     "S,xvfsconf", "List of all configured filesystems");
4545 
4546 #ifndef BURN_BRIDGES
4547 static int	sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4548 
4549 static int
4550 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4551 {
4552 	int *name = (int *)arg1 - 1;	/* XXX */
4553 	u_int namelen = arg2 + 1;	/* XXX */
4554 	struct vfsconf *vfsp;
4555 
4556 	log(LOG_WARNING, "userland calling deprecated sysctl, "
4557 	    "please rebuild world\n");
4558 
4559 #if 1 || defined(COMPAT_PRELITE2)
4560 	/* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4561 	if (namelen == 1)
4562 		return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4563 #endif
4564 
4565 	switch (name[1]) {
4566 	case VFS_MAXTYPENUM:
4567 		if (namelen != 2)
4568 			return (ENOTDIR);
4569 		return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4570 	case VFS_CONF:
4571 		if (namelen != 3)
4572 			return (ENOTDIR);	/* overloaded */
4573 		vfsconf_slock();
4574 		TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4575 			if (vfsp->vfc_typenum == name[2])
4576 				break;
4577 		}
4578 		vfsconf_sunlock();
4579 		if (vfsp == NULL)
4580 			return (EOPNOTSUPP);
4581 #ifdef COMPAT_FREEBSD32
4582 		if (req->flags & SCTL_MASK32)
4583 			return (vfsconf2x32(req, vfsp));
4584 		else
4585 #endif
4586 			return (vfsconf2x(req, vfsp));
4587 	}
4588 	return (EOPNOTSUPP);
4589 }
4590 
4591 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4592     CTLFLAG_MPSAFE, vfs_sysctl,
4593     "Generic filesystem");
4594 
4595 #if 1 || defined(COMPAT_PRELITE2)
4596 
4597 static int
4598 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4599 {
4600 	int error;
4601 	struct vfsconf *vfsp;
4602 	struct ovfsconf ovfs;
4603 
4604 	vfsconf_slock();
4605 	TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4606 		bzero(&ovfs, sizeof(ovfs));
4607 		ovfs.vfc_vfsops = vfsp->vfc_vfsops;	/* XXX used as flag */
4608 		strcpy(ovfs.vfc_name, vfsp->vfc_name);
4609 		ovfs.vfc_index = vfsp->vfc_typenum;
4610 		ovfs.vfc_refcount = vfsp->vfc_refcount;
4611 		ovfs.vfc_flags = vfsp->vfc_flags;
4612 		error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4613 		if (error != 0) {
4614 			vfsconf_sunlock();
4615 			return (error);
4616 		}
4617 	}
4618 	vfsconf_sunlock();
4619 	return (0);
4620 }
4621 
4622 #endif /* 1 || COMPAT_PRELITE2 */
4623 #endif /* !BURN_BRIDGES */
4624 
4625 #define KINFO_VNODESLOP		10
4626 #ifdef notyet
4627 /*
4628  * Dump vnode list (via sysctl).
4629  */
4630 /* ARGSUSED */
4631 static int
4632 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4633 {
4634 	struct xvnode *xvn;
4635 	struct mount *mp;
4636 	struct vnode *vp;
4637 	int error, len, n;
4638 
4639 	/*
4640 	 * Stale numvnodes access is not fatal here.
4641 	 */
4642 	req->lock = 0;
4643 	len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4644 	if (!req->oldptr)
4645 		/* Make an estimate */
4646 		return (SYSCTL_OUT(req, 0, len));
4647 
4648 	error = sysctl_wire_old_buffer(req, 0);
4649 	if (error != 0)
4650 		return (error);
4651 	xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4652 	n = 0;
4653 	mtx_lock(&mountlist_mtx);
4654 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4655 		if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4656 			continue;
4657 		MNT_ILOCK(mp);
4658 		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4659 			if (n == len)
4660 				break;
4661 			vref(vp);
4662 			xvn[n].xv_size = sizeof *xvn;
4663 			xvn[n].xv_vnode = vp;
4664 			xvn[n].xv_id = 0;	/* XXX compat */
4665 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4666 			XV_COPY(usecount);
4667 			XV_COPY(writecount);
4668 			XV_COPY(holdcnt);
4669 			XV_COPY(mount);
4670 			XV_COPY(numoutput);
4671 			XV_COPY(type);
4672 #undef XV_COPY
4673 			xvn[n].xv_flag = vp->v_vflag;
4674 
4675 			switch (vp->v_type) {
4676 			case VREG:
4677 			case VDIR:
4678 			case VLNK:
4679 				break;
4680 			case VBLK:
4681 			case VCHR:
4682 				if (vp->v_rdev == NULL) {
4683 					vrele(vp);
4684 					continue;
4685 				}
4686 				xvn[n].xv_dev = dev2udev(vp->v_rdev);
4687 				break;
4688 			case VSOCK:
4689 				xvn[n].xv_socket = vp->v_socket;
4690 				break;
4691 			case VFIFO:
4692 				xvn[n].xv_fifo = vp->v_fifoinfo;
4693 				break;
4694 			case VNON:
4695 			case VBAD:
4696 			default:
4697 				/* shouldn't happen? */
4698 				vrele(vp);
4699 				continue;
4700 			}
4701 			vrele(vp);
4702 			++n;
4703 		}
4704 		MNT_IUNLOCK(mp);
4705 		mtx_lock(&mountlist_mtx);
4706 		vfs_unbusy(mp);
4707 		if (n == len)
4708 			break;
4709 	}
4710 	mtx_unlock(&mountlist_mtx);
4711 
4712 	error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4713 	free(xvn, M_TEMP);
4714 	return (error);
4715 }
4716 
4717 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4718     CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4719     "");
4720 #endif
4721 
4722 static void
4723 unmount_or_warn(struct mount *mp)
4724 {
4725 	int error;
4726 
4727 	error = dounmount(mp, MNT_FORCE, curthread);
4728 	if (error != 0) {
4729 		printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4730 		if (error == EBUSY)
4731 			printf("BUSY)\n");
4732 		else
4733 			printf("%d)\n", error);
4734 	}
4735 }
4736 
4737 /*
4738  * Unmount all filesystems. The list is traversed in reverse order
4739  * of mounting to avoid dependencies.
4740  */
4741 void
4742 vfs_unmountall(void)
4743 {
4744 	struct mount *mp, *tmp;
4745 
4746 	CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4747 
4748 	/*
4749 	 * Since this only runs when rebooting, it is not interlocked.
4750 	 */
4751 	TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4752 		vfs_ref(mp);
4753 
4754 		/*
4755 		 * Forcibly unmounting "/dev" before "/" would prevent clean
4756 		 * unmount of the latter.
4757 		 */
4758 		if (mp == rootdevmp)
4759 			continue;
4760 
4761 		unmount_or_warn(mp);
4762 	}
4763 
4764 	if (rootdevmp != NULL)
4765 		unmount_or_warn(rootdevmp);
4766 }
4767 
4768 static void
4769 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4770 {
4771 
4772 	ASSERT_VI_LOCKED(vp, __func__);
4773 	VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4774 	if ((vp->v_iflag & VI_OWEINACT) == 0) {
4775 		vdropl(vp);
4776 		return;
4777 	}
4778 	if (vn_lock(vp, lkflags) == 0) {
4779 		VI_LOCK(vp);
4780 		vinactive(vp);
4781 		VOP_UNLOCK(vp);
4782 		vdropl(vp);
4783 		return;
4784 	}
4785 	vdefer_inactive_unlocked(vp);
4786 }
4787 
4788 static int
4789 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4790 {
4791 
4792 	return (vp->v_iflag & VI_DEFINACT);
4793 }
4794 
4795 static void __noinline
4796 vfs_periodic_inactive(struct mount *mp, int flags)
4797 {
4798 	struct vnode *vp, *mvp;
4799 	int lkflags;
4800 
4801 	lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4802 	if (flags != MNT_WAIT)
4803 		lkflags |= LK_NOWAIT;
4804 
4805 	MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4806 		if ((vp->v_iflag & VI_DEFINACT) == 0) {
4807 			VI_UNLOCK(vp);
4808 			continue;
4809 		}
4810 		vp->v_iflag &= ~VI_DEFINACT;
4811 		vfs_deferred_inactive(vp, lkflags);
4812 	}
4813 }
4814 
4815 static inline bool
4816 vfs_want_msync(struct vnode *vp)
4817 {
4818 	struct vm_object *obj;
4819 
4820 	/*
4821 	 * This test may be performed without any locks held.
4822 	 * We rely on vm_object's type stability.
4823 	 */
4824 	if (vp->v_vflag & VV_NOSYNC)
4825 		return (false);
4826 	obj = vp->v_object;
4827 	return (obj != NULL && vm_object_mightbedirty(obj));
4828 }
4829 
4830 static int
4831 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4832 {
4833 
4834 	if (vp->v_vflag & VV_NOSYNC)
4835 		return (false);
4836 	if (vp->v_iflag & VI_DEFINACT)
4837 		return (true);
4838 	return (vfs_want_msync(vp));
4839 }
4840 
4841 static void __noinline
4842 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4843 {
4844 	struct vnode *vp, *mvp;
4845 	struct vm_object *obj;
4846 	struct thread *td;
4847 	int lkflags, objflags;
4848 	bool seen_defer;
4849 
4850 	td = curthread;
4851 
4852 	lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4853 	if (flags != MNT_WAIT) {
4854 		lkflags |= LK_NOWAIT;
4855 		objflags = OBJPC_NOSYNC;
4856 	} else {
4857 		objflags = OBJPC_SYNC;
4858 	}
4859 
4860 	MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4861 		seen_defer = false;
4862 		if (vp->v_iflag & VI_DEFINACT) {
4863 			vp->v_iflag &= ~VI_DEFINACT;
4864 			seen_defer = true;
4865 		}
4866 		if (!vfs_want_msync(vp)) {
4867 			if (seen_defer)
4868 				vfs_deferred_inactive(vp, lkflags);
4869 			else
4870 				VI_UNLOCK(vp);
4871 			continue;
4872 		}
4873 		if (vget(vp, lkflags, td) == 0) {
4874 			obj = vp->v_object;
4875 			if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4876 				VM_OBJECT_WLOCK(obj);
4877 				vm_object_page_clean(obj, 0, 0, objflags);
4878 				VM_OBJECT_WUNLOCK(obj);
4879 			}
4880 			vput(vp);
4881 			if (seen_defer)
4882 				vdrop(vp);
4883 		} else {
4884 			if (seen_defer)
4885 				vdefer_inactive_unlocked(vp);
4886 		}
4887 	}
4888 }
4889 
4890 void
4891 vfs_periodic(struct mount *mp, int flags)
4892 {
4893 
4894 	CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4895 
4896 	if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4897 		vfs_periodic_inactive(mp, flags);
4898 	else
4899 		vfs_periodic_msync_inactive(mp, flags);
4900 }
4901 
4902 static void
4903 destroy_vpollinfo_free(struct vpollinfo *vi)
4904 {
4905 
4906 	knlist_destroy(&vi->vpi_selinfo.si_note);
4907 	mtx_destroy(&vi->vpi_lock);
4908 	uma_zfree(vnodepoll_zone, vi);
4909 }
4910 
4911 static void
4912 destroy_vpollinfo(struct vpollinfo *vi)
4913 {
4914 
4915 	knlist_clear(&vi->vpi_selinfo.si_note, 1);
4916 	seldrain(&vi->vpi_selinfo);
4917 	destroy_vpollinfo_free(vi);
4918 }
4919 
4920 /*
4921  * Initialize per-vnode helper structure to hold poll-related state.
4922  */
4923 void
4924 v_addpollinfo(struct vnode *vp)
4925 {
4926 	struct vpollinfo *vi;
4927 
4928 	if (vp->v_pollinfo != NULL)
4929 		return;
4930 	vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4931 	mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4932 	knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4933 	    vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4934 	VI_LOCK(vp);
4935 	if (vp->v_pollinfo != NULL) {
4936 		VI_UNLOCK(vp);
4937 		destroy_vpollinfo_free(vi);
4938 		return;
4939 	}
4940 	vp->v_pollinfo = vi;
4941 	VI_UNLOCK(vp);
4942 }
4943 
4944 /*
4945  * Record a process's interest in events which might happen to
4946  * a vnode.  Because poll uses the historic select-style interface
4947  * internally, this routine serves as both the ``check for any
4948  * pending events'' and the ``record my interest in future events''
4949  * functions.  (These are done together, while the lock is held,
4950  * to avoid race conditions.)
4951  */
4952 int
4953 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4954 {
4955 
4956 	v_addpollinfo(vp);
4957 	mtx_lock(&vp->v_pollinfo->vpi_lock);
4958 	if (vp->v_pollinfo->vpi_revents & events) {
4959 		/*
4960 		 * This leaves events we are not interested
4961 		 * in available for the other process which
4962 		 * which presumably had requested them
4963 		 * (otherwise they would never have been
4964 		 * recorded).
4965 		 */
4966 		events &= vp->v_pollinfo->vpi_revents;
4967 		vp->v_pollinfo->vpi_revents &= ~events;
4968 
4969 		mtx_unlock(&vp->v_pollinfo->vpi_lock);
4970 		return (events);
4971 	}
4972 	vp->v_pollinfo->vpi_events |= events;
4973 	selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4974 	mtx_unlock(&vp->v_pollinfo->vpi_lock);
4975 	return (0);
4976 }
4977 
4978 /*
4979  * Routine to create and manage a filesystem syncer vnode.
4980  */
4981 #define sync_close ((int (*)(struct  vop_close_args *))nullop)
4982 static int	sync_fsync(struct  vop_fsync_args *);
4983 static int	sync_inactive(struct  vop_inactive_args *);
4984 static int	sync_reclaim(struct  vop_reclaim_args *);
4985 
4986 static struct vop_vector sync_vnodeops = {
4987 	.vop_bypass =	VOP_EOPNOTSUPP,
4988 	.vop_close =	sync_close,		/* close */
4989 	.vop_fsync =	sync_fsync,		/* fsync */
4990 	.vop_inactive =	sync_inactive,	/* inactive */
4991 	.vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
4992 	.vop_reclaim =	sync_reclaim,	/* reclaim */
4993 	.vop_lock1 =	vop_stdlock,	/* lock */
4994 	.vop_unlock =	vop_stdunlock,	/* unlock */
4995 	.vop_islocked =	vop_stdislocked,	/* islocked */
4996 };
4997 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
4998 
4999 /*
5000  * Create a new filesystem syncer vnode for the specified mount point.
5001  */
5002 void
5003 vfs_allocate_syncvnode(struct mount *mp)
5004 {
5005 	struct vnode *vp;
5006 	struct bufobj *bo;
5007 	static long start, incr, next;
5008 	int error;
5009 
5010 	/* Allocate a new vnode */
5011 	error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
5012 	if (error != 0)
5013 		panic("vfs_allocate_syncvnode: getnewvnode() failed");
5014 	vp->v_type = VNON;
5015 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5016 	vp->v_vflag |= VV_FORCEINSMQ;
5017 	error = insmntque(vp, mp);
5018 	if (error != 0)
5019 		panic("vfs_allocate_syncvnode: insmntque() failed");
5020 	vp->v_vflag &= ~VV_FORCEINSMQ;
5021 	VOP_UNLOCK(vp);
5022 	/*
5023 	 * Place the vnode onto the syncer worklist. We attempt to
5024 	 * scatter them about on the list so that they will go off
5025 	 * at evenly distributed times even if all the filesystems
5026 	 * are mounted at once.
5027 	 */
5028 	next += incr;
5029 	if (next == 0 || next > syncer_maxdelay) {
5030 		start /= 2;
5031 		incr /= 2;
5032 		if (start == 0) {
5033 			start = syncer_maxdelay / 2;
5034 			incr = syncer_maxdelay;
5035 		}
5036 		next = start;
5037 	}
5038 	bo = &vp->v_bufobj;
5039 	BO_LOCK(bo);
5040 	vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
5041 	/* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
5042 	mtx_lock(&sync_mtx);
5043 	sync_vnode_count++;
5044 	if (mp->mnt_syncer == NULL) {
5045 		mp->mnt_syncer = vp;
5046 		vp = NULL;
5047 	}
5048 	mtx_unlock(&sync_mtx);
5049 	BO_UNLOCK(bo);
5050 	if (vp != NULL) {
5051 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5052 		vgone(vp);
5053 		vput(vp);
5054 	}
5055 }
5056 
5057 void
5058 vfs_deallocate_syncvnode(struct mount *mp)
5059 {
5060 	struct vnode *vp;
5061 
5062 	mtx_lock(&sync_mtx);
5063 	vp = mp->mnt_syncer;
5064 	if (vp != NULL)
5065 		mp->mnt_syncer = NULL;
5066 	mtx_unlock(&sync_mtx);
5067 	if (vp != NULL)
5068 		vrele(vp);
5069 }
5070 
5071 /*
5072  * Do a lazy sync of the filesystem.
5073  */
5074 static int
5075 sync_fsync(struct vop_fsync_args *ap)
5076 {
5077 	struct vnode *syncvp = ap->a_vp;
5078 	struct mount *mp = syncvp->v_mount;
5079 	int error, save;
5080 	struct bufobj *bo;
5081 
5082 	/*
5083 	 * We only need to do something if this is a lazy evaluation.
5084 	 */
5085 	if (ap->a_waitfor != MNT_LAZY)
5086 		return (0);
5087 
5088 	/*
5089 	 * Move ourselves to the back of the sync list.
5090 	 */
5091 	bo = &syncvp->v_bufobj;
5092 	BO_LOCK(bo);
5093 	vn_syncer_add_to_worklist(bo, syncdelay);
5094 	BO_UNLOCK(bo);
5095 
5096 	/*
5097 	 * Walk the list of vnodes pushing all that are dirty and
5098 	 * not already on the sync list.
5099 	 */
5100 	if (vfs_busy(mp, MBF_NOWAIT) != 0)
5101 		return (0);
5102 	if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
5103 		vfs_unbusy(mp);
5104 		return (0);
5105 	}
5106 	save = curthread_pflags_set(TDP_SYNCIO);
5107 	/*
5108 	 * The filesystem at hand may be idle with free vnodes stored in the
5109 	 * batch.  Return them instead of letting them stay there indefinitely.
5110 	 */
5111 	vfs_periodic(mp, MNT_NOWAIT);
5112 	error = VFS_SYNC(mp, MNT_LAZY);
5113 	curthread_pflags_restore(save);
5114 	vn_finished_write(mp);
5115 	vfs_unbusy(mp);
5116 	return (error);
5117 }
5118 
5119 /*
5120  * The syncer vnode is no referenced.
5121  */
5122 static int
5123 sync_inactive(struct vop_inactive_args *ap)
5124 {
5125 
5126 	vgone(ap->a_vp);
5127 	return (0);
5128 }
5129 
5130 /*
5131  * The syncer vnode is no longer needed and is being decommissioned.
5132  *
5133  * Modifications to the worklist must be protected by sync_mtx.
5134  */
5135 static int
5136 sync_reclaim(struct vop_reclaim_args *ap)
5137 {
5138 	struct vnode *vp = ap->a_vp;
5139 	struct bufobj *bo;
5140 
5141 	bo = &vp->v_bufobj;
5142 	BO_LOCK(bo);
5143 	mtx_lock(&sync_mtx);
5144 	if (vp->v_mount->mnt_syncer == vp)
5145 		vp->v_mount->mnt_syncer = NULL;
5146 	if (bo->bo_flag & BO_ONWORKLST) {
5147 		LIST_REMOVE(bo, bo_synclist);
5148 		syncer_worklist_len--;
5149 		sync_vnode_count--;
5150 		bo->bo_flag &= ~BO_ONWORKLST;
5151 	}
5152 	mtx_unlock(&sync_mtx);
5153 	BO_UNLOCK(bo);
5154 
5155 	return (0);
5156 }
5157 
5158 int
5159 vn_need_pageq_flush(struct vnode *vp)
5160 {
5161 	struct vm_object *obj;
5162 	int need;
5163 
5164 	MPASS(mtx_owned(VI_MTX(vp)));
5165 	need = 0;
5166 	if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
5167 	    vm_object_mightbedirty(obj))
5168 		need = 1;
5169 	return (need);
5170 }
5171 
5172 /*
5173  * Check if vnode represents a disk device
5174  */
5175 int
5176 vn_isdisk(struct vnode *vp, int *errp)
5177 {
5178 	int error;
5179 
5180 	if (vp->v_type != VCHR) {
5181 		error = ENOTBLK;
5182 		goto out;
5183 	}
5184 	error = 0;
5185 	dev_lock();
5186 	if (vp->v_rdev == NULL)
5187 		error = ENXIO;
5188 	else if (vp->v_rdev->si_devsw == NULL)
5189 		error = ENXIO;
5190 	else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5191 		error = ENOTBLK;
5192 	dev_unlock();
5193 out:
5194 	if (errp != NULL)
5195 		*errp = error;
5196 	return (error == 0);
5197 }
5198 
5199 /*
5200  * Common filesystem object access control check routine.  Accepts a
5201  * vnode's type, "mode", uid and gid, requested access mode, credentials,
5202  * and optional call-by-reference privused argument allowing vaccess()
5203  * to indicate to the caller whether privilege was used to satisfy the
5204  * request (obsoleted).  Returns 0 on success, or an errno on failure.
5205  */
5206 int
5207 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5208     accmode_t accmode, struct ucred *cred, int *privused)
5209 {
5210 	accmode_t dac_granted;
5211 	accmode_t priv_granted;
5212 
5213 	KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5214 	    ("invalid bit in accmode"));
5215 	KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5216 	    ("VAPPEND without VWRITE"));
5217 
5218 	/*
5219 	 * Look for a normal, non-privileged way to access the file/directory
5220 	 * as requested.  If it exists, go with that.
5221 	 */
5222 
5223 	if (privused != NULL)
5224 		*privused = 0;
5225 
5226 	dac_granted = 0;
5227 
5228 	/* Check the owner. */
5229 	if (cred->cr_uid == file_uid) {
5230 		dac_granted |= VADMIN;
5231 		if (file_mode & S_IXUSR)
5232 			dac_granted |= VEXEC;
5233 		if (file_mode & S_IRUSR)
5234 			dac_granted |= VREAD;
5235 		if (file_mode & S_IWUSR)
5236 			dac_granted |= (VWRITE | VAPPEND);
5237 
5238 		if ((accmode & dac_granted) == accmode)
5239 			return (0);
5240 
5241 		goto privcheck;
5242 	}
5243 
5244 	/* Otherwise, check the groups (first match) */
5245 	if (groupmember(file_gid, cred)) {
5246 		if (file_mode & S_IXGRP)
5247 			dac_granted |= VEXEC;
5248 		if (file_mode & S_IRGRP)
5249 			dac_granted |= VREAD;
5250 		if (file_mode & S_IWGRP)
5251 			dac_granted |= (VWRITE | VAPPEND);
5252 
5253 		if ((accmode & dac_granted) == accmode)
5254 			return (0);
5255 
5256 		goto privcheck;
5257 	}
5258 
5259 	/* Otherwise, check everyone else. */
5260 	if (file_mode & S_IXOTH)
5261 		dac_granted |= VEXEC;
5262 	if (file_mode & S_IROTH)
5263 		dac_granted |= VREAD;
5264 	if (file_mode & S_IWOTH)
5265 		dac_granted |= (VWRITE | VAPPEND);
5266 	if ((accmode & dac_granted) == accmode)
5267 		return (0);
5268 
5269 privcheck:
5270 	/*
5271 	 * Build a privilege mask to determine if the set of privileges
5272 	 * satisfies the requirements when combined with the granted mask
5273 	 * from above.  For each privilege, if the privilege is required,
5274 	 * bitwise or the request type onto the priv_granted mask.
5275 	 */
5276 	priv_granted = 0;
5277 
5278 	if (type == VDIR) {
5279 		/*
5280 		 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5281 		 * requests, instead of PRIV_VFS_EXEC.
5282 		 */
5283 		if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5284 		    !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5285 			priv_granted |= VEXEC;
5286 	} else {
5287 		/*
5288 		 * Ensure that at least one execute bit is on. Otherwise,
5289 		 * a privileged user will always succeed, and we don't want
5290 		 * this to happen unless the file really is executable.
5291 		 */
5292 		if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5293 		    (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5294 		    !priv_check_cred(cred, PRIV_VFS_EXEC))
5295 			priv_granted |= VEXEC;
5296 	}
5297 
5298 	if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5299 	    !priv_check_cred(cred, PRIV_VFS_READ))
5300 		priv_granted |= VREAD;
5301 
5302 	if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5303 	    !priv_check_cred(cred, PRIV_VFS_WRITE))
5304 		priv_granted |= (VWRITE | VAPPEND);
5305 
5306 	if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5307 	    !priv_check_cred(cred, PRIV_VFS_ADMIN))
5308 		priv_granted |= VADMIN;
5309 
5310 	if ((accmode & (priv_granted | dac_granted)) == accmode) {
5311 		/* XXX audit: privilege used */
5312 		if (privused != NULL)
5313 			*privused = 1;
5314 		return (0);
5315 	}
5316 
5317 	return ((accmode & VADMIN) ? EPERM : EACCES);
5318 }
5319 
5320 /*
5321  * Credential check based on process requesting service, and per-attribute
5322  * permissions.
5323  */
5324 int
5325 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5326     struct thread *td, accmode_t accmode)
5327 {
5328 
5329 	/*
5330 	 * Kernel-invoked always succeeds.
5331 	 */
5332 	if (cred == NOCRED)
5333 		return (0);
5334 
5335 	/*
5336 	 * Do not allow privileged processes in jail to directly manipulate
5337 	 * system attributes.
5338 	 */
5339 	switch (attrnamespace) {
5340 	case EXTATTR_NAMESPACE_SYSTEM:
5341 		/* Potentially should be: return (EPERM); */
5342 		return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5343 	case EXTATTR_NAMESPACE_USER:
5344 		return (VOP_ACCESS(vp, accmode, cred, td));
5345 	default:
5346 		return (EPERM);
5347 	}
5348 }
5349 
5350 #ifdef DEBUG_VFS_LOCKS
5351 /*
5352  * This only exists to suppress warnings from unlocked specfs accesses.  It is
5353  * no longer ok to have an unlocked VFS.
5354  */
5355 #define	IGNORE_LOCK(vp) (KERNEL_PANICKED() || (vp) == NULL ||		\
5356 	(vp)->v_type == VCHR ||	(vp)->v_type == VBAD)
5357 
5358 int vfs_badlock_ddb = 1;	/* Drop into debugger on violation. */
5359 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5360     "Drop into debugger on lock violation");
5361 
5362 int vfs_badlock_mutex = 1;	/* Check for interlock across VOPs. */
5363 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5364     0, "Check for interlock across VOPs");
5365 
5366 int vfs_badlock_print = 1;	/* Print lock violations. */
5367 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5368     0, "Print lock violations");
5369 
5370 int vfs_badlock_vnode = 1;	/* Print vnode details on lock violations. */
5371 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5372     0, "Print vnode details on lock violations");
5373 
5374 #ifdef KDB
5375 int vfs_badlock_backtrace = 1;	/* Print backtrace at lock violations. */
5376 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5377     &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5378 #endif
5379 
5380 static void
5381 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5382 {
5383 
5384 #ifdef KDB
5385 	if (vfs_badlock_backtrace)
5386 		kdb_backtrace();
5387 #endif
5388 	if (vfs_badlock_vnode)
5389 		vn_printf(vp, "vnode ");
5390 	if (vfs_badlock_print)
5391 		printf("%s: %p %s\n", str, (void *)vp, msg);
5392 	if (vfs_badlock_ddb)
5393 		kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5394 }
5395 
5396 void
5397 assert_vi_locked(struct vnode *vp, const char *str)
5398 {
5399 
5400 	if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5401 		vfs_badlock("interlock is not locked but should be", str, vp);
5402 }
5403 
5404 void
5405 assert_vi_unlocked(struct vnode *vp, const char *str)
5406 {
5407 
5408 	if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5409 		vfs_badlock("interlock is locked but should not be", str, vp);
5410 }
5411 
5412 void
5413 assert_vop_locked(struct vnode *vp, const char *str)
5414 {
5415 	int locked;
5416 
5417 	if (!IGNORE_LOCK(vp)) {
5418 		locked = VOP_ISLOCKED(vp);
5419 		if (locked == 0 || locked == LK_EXCLOTHER)
5420 			vfs_badlock("is not locked but should be", str, vp);
5421 	}
5422 }
5423 
5424 void
5425 assert_vop_unlocked(struct vnode *vp, const char *str)
5426 {
5427 
5428 	if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5429 		vfs_badlock("is locked but should not be", str, vp);
5430 }
5431 
5432 void
5433 assert_vop_elocked(struct vnode *vp, const char *str)
5434 {
5435 
5436 	if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5437 		vfs_badlock("is not exclusive locked but should be", str, vp);
5438 }
5439 #endif /* DEBUG_VFS_LOCKS */
5440 
5441 void
5442 vop_rename_fail(struct vop_rename_args *ap)
5443 {
5444 
5445 	if (ap->a_tvp != NULL)
5446 		vput(ap->a_tvp);
5447 	if (ap->a_tdvp == ap->a_tvp)
5448 		vrele(ap->a_tdvp);
5449 	else
5450 		vput(ap->a_tdvp);
5451 	vrele(ap->a_fdvp);
5452 	vrele(ap->a_fvp);
5453 }
5454 
5455 void
5456 vop_rename_pre(void *ap)
5457 {
5458 	struct vop_rename_args *a = ap;
5459 
5460 #ifdef DEBUG_VFS_LOCKS
5461 	if (a->a_tvp)
5462 		ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5463 	ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5464 	ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5465 	ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5466 
5467 	/* Check the source (from). */
5468 	if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5469 	    (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5470 		ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5471 	if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5472 		ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5473 
5474 	/* Check the target. */
5475 	if (a->a_tvp)
5476 		ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5477 	ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5478 #endif
5479 	if (a->a_tdvp != a->a_fdvp)
5480 		vhold(a->a_fdvp);
5481 	if (a->a_tvp != a->a_fvp)
5482 		vhold(a->a_fvp);
5483 	vhold(a->a_tdvp);
5484 	if (a->a_tvp)
5485 		vhold(a->a_tvp);
5486 }
5487 
5488 #ifdef DEBUG_VFS_LOCKS
5489 void
5490 vop_strategy_pre(void *ap)
5491 {
5492 	struct vop_strategy_args *a;
5493 	struct buf *bp;
5494 
5495 	a = ap;
5496 	bp = a->a_bp;
5497 
5498 	/*
5499 	 * Cluster ops lock their component buffers but not the IO container.
5500 	 */
5501 	if ((bp->b_flags & B_CLUSTER) != 0)
5502 		return;
5503 
5504 	if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5505 		if (vfs_badlock_print)
5506 			printf(
5507 			    "VOP_STRATEGY: bp is not locked but should be\n");
5508 		if (vfs_badlock_ddb)
5509 			kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5510 	}
5511 }
5512 
5513 void
5514 vop_lock_pre(void *ap)
5515 {
5516 	struct vop_lock1_args *a = ap;
5517 
5518 	if ((a->a_flags & LK_INTERLOCK) == 0)
5519 		ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5520 	else
5521 		ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5522 }
5523 
5524 void
5525 vop_lock_post(void *ap, int rc)
5526 {
5527 	struct vop_lock1_args *a = ap;
5528 
5529 	ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5530 	if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5531 		ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5532 }
5533 
5534 void
5535 vop_unlock_pre(void *ap)
5536 {
5537 	struct vop_unlock_args *a = ap;
5538 
5539 	ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5540 }
5541 
5542 void
5543 vop_need_inactive_pre(void *ap)
5544 {
5545 	struct vop_need_inactive_args *a = ap;
5546 
5547 	ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5548 }
5549 
5550 void
5551 vop_need_inactive_post(void *ap, int rc)
5552 {
5553 	struct vop_need_inactive_args *a = ap;
5554 
5555 	ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5556 }
5557 #endif
5558 
5559 void
5560 vop_create_post(void *ap, int rc)
5561 {
5562 	struct vop_create_args *a = ap;
5563 
5564 	if (!rc)
5565 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5566 }
5567 
5568 void
5569 vop_deleteextattr_post(void *ap, int rc)
5570 {
5571 	struct vop_deleteextattr_args *a = ap;
5572 
5573 	if (!rc)
5574 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5575 }
5576 
5577 void
5578 vop_link_post(void *ap, int rc)
5579 {
5580 	struct vop_link_args *a = ap;
5581 
5582 	if (!rc) {
5583 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
5584 		VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
5585 	}
5586 }
5587 
5588 void
5589 vop_mkdir_post(void *ap, int rc)
5590 {
5591 	struct vop_mkdir_args *a = ap;
5592 
5593 	if (!rc)
5594 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5595 }
5596 
5597 void
5598 vop_mknod_post(void *ap, int rc)
5599 {
5600 	struct vop_mknod_args *a = ap;
5601 
5602 	if (!rc)
5603 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5604 }
5605 
5606 void
5607 vop_reclaim_post(void *ap, int rc)
5608 {
5609 	struct vop_reclaim_args *a = ap;
5610 
5611 	if (!rc)
5612 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
5613 }
5614 
5615 void
5616 vop_remove_post(void *ap, int rc)
5617 {
5618 	struct vop_remove_args *a = ap;
5619 
5620 	if (!rc) {
5621 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5622 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5623 	}
5624 }
5625 
5626 void
5627 vop_rename_post(void *ap, int rc)
5628 {
5629 	struct vop_rename_args *a = ap;
5630 	long hint;
5631 
5632 	if (!rc) {
5633 		hint = NOTE_WRITE;
5634 		if (a->a_fdvp == a->a_tdvp) {
5635 			if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5636 				hint |= NOTE_LINK;
5637 			VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5638 			VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5639 		} else {
5640 			hint |= NOTE_EXTEND;
5641 			if (a->a_fvp->v_type == VDIR)
5642 				hint |= NOTE_LINK;
5643 			VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5644 
5645 			if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5646 			    a->a_tvp->v_type == VDIR)
5647 				hint &= ~NOTE_LINK;
5648 			VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5649 		}
5650 
5651 		VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5652 		if (a->a_tvp)
5653 			VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5654 	}
5655 	if (a->a_tdvp != a->a_fdvp)
5656 		vdrop(a->a_fdvp);
5657 	if (a->a_tvp != a->a_fvp)
5658 		vdrop(a->a_fvp);
5659 	vdrop(a->a_tdvp);
5660 	if (a->a_tvp)
5661 		vdrop(a->a_tvp);
5662 }
5663 
5664 void
5665 vop_rmdir_post(void *ap, int rc)
5666 {
5667 	struct vop_rmdir_args *a = ap;
5668 
5669 	if (!rc) {
5670 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5671 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5672 	}
5673 }
5674 
5675 void
5676 vop_setattr_post(void *ap, int rc)
5677 {
5678 	struct vop_setattr_args *a = ap;
5679 
5680 	if (!rc)
5681 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5682 }
5683 
5684 void
5685 vop_setextattr_post(void *ap, int rc)
5686 {
5687 	struct vop_setextattr_args *a = ap;
5688 
5689 	if (!rc)
5690 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5691 }
5692 
5693 void
5694 vop_symlink_post(void *ap, int rc)
5695 {
5696 	struct vop_symlink_args *a = ap;
5697 
5698 	if (!rc)
5699 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5700 }
5701 
5702 void
5703 vop_open_post(void *ap, int rc)
5704 {
5705 	struct vop_open_args *a = ap;
5706 
5707 	if (!rc)
5708 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
5709 }
5710 
5711 void
5712 vop_close_post(void *ap, int rc)
5713 {
5714 	struct vop_close_args *a = ap;
5715 
5716 	if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
5717 	    !VN_IS_DOOMED(a->a_vp))) {
5718 		VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
5719 		    NOTE_CLOSE_WRITE : NOTE_CLOSE);
5720 	}
5721 }
5722 
5723 void
5724 vop_read_post(void *ap, int rc)
5725 {
5726 	struct vop_read_args *a = ap;
5727 
5728 	if (!rc)
5729 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5730 }
5731 
5732 void
5733 vop_readdir_post(void *ap, int rc)
5734 {
5735 	struct vop_readdir_args *a = ap;
5736 
5737 	if (!rc)
5738 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5739 }
5740 
5741 static struct knlist fs_knlist;
5742 
5743 static void
5744 vfs_event_init(void *arg)
5745 {
5746 	knlist_init_mtx(&fs_knlist, NULL);
5747 }
5748 /* XXX - correct order? */
5749 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
5750 
5751 void
5752 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
5753 {
5754 
5755 	KNOTE_UNLOCKED(&fs_knlist, event);
5756 }
5757 
5758 static int	filt_fsattach(struct knote *kn);
5759 static void	filt_fsdetach(struct knote *kn);
5760 static int	filt_fsevent(struct knote *kn, long hint);
5761 
5762 struct filterops fs_filtops = {
5763 	.f_isfd = 0,
5764 	.f_attach = filt_fsattach,
5765 	.f_detach = filt_fsdetach,
5766 	.f_event = filt_fsevent
5767 };
5768 
5769 static int
5770 filt_fsattach(struct knote *kn)
5771 {
5772 
5773 	kn->kn_flags |= EV_CLEAR;
5774 	knlist_add(&fs_knlist, kn, 0);
5775 	return (0);
5776 }
5777 
5778 static void
5779 filt_fsdetach(struct knote *kn)
5780 {
5781 
5782 	knlist_remove(&fs_knlist, kn, 0);
5783 }
5784 
5785 static int
5786 filt_fsevent(struct knote *kn, long hint)
5787 {
5788 
5789 	kn->kn_fflags |= hint;
5790 	return (kn->kn_fflags != 0);
5791 }
5792 
5793 static int
5794 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
5795 {
5796 	struct vfsidctl vc;
5797 	int error;
5798 	struct mount *mp;
5799 
5800 	error = SYSCTL_IN(req, &vc, sizeof(vc));
5801 	if (error)
5802 		return (error);
5803 	if (vc.vc_vers != VFS_CTL_VERS1)
5804 		return (EINVAL);
5805 	mp = vfs_getvfs(&vc.vc_fsid);
5806 	if (mp == NULL)
5807 		return (ENOENT);
5808 	/* ensure that a specific sysctl goes to the right filesystem. */
5809 	if (strcmp(vc.vc_fstypename, "*") != 0 &&
5810 	    strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
5811 		vfs_rel(mp);
5812 		return (EINVAL);
5813 	}
5814 	VCTLTOREQ(&vc, req);
5815 	error = VFS_SYSCTL(mp, vc.vc_op, req);
5816 	vfs_rel(mp);
5817 	return (error);
5818 }
5819 
5820 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
5821     NULL, 0, sysctl_vfs_ctl, "",
5822     "Sysctl by fsid");
5823 
5824 /*
5825  * Function to initialize a va_filerev field sensibly.
5826  * XXX: Wouldn't a random number make a lot more sense ??
5827  */
5828 u_quad_t
5829 init_va_filerev(void)
5830 {
5831 	struct bintime bt;
5832 
5833 	getbinuptime(&bt);
5834 	return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
5835 }
5836 
5837 static int	filt_vfsread(struct knote *kn, long hint);
5838 static int	filt_vfswrite(struct knote *kn, long hint);
5839 static int	filt_vfsvnode(struct knote *kn, long hint);
5840 static void	filt_vfsdetach(struct knote *kn);
5841 static struct filterops vfsread_filtops = {
5842 	.f_isfd = 1,
5843 	.f_detach = filt_vfsdetach,
5844 	.f_event = filt_vfsread
5845 };
5846 static struct filterops vfswrite_filtops = {
5847 	.f_isfd = 1,
5848 	.f_detach = filt_vfsdetach,
5849 	.f_event = filt_vfswrite
5850 };
5851 static struct filterops vfsvnode_filtops = {
5852 	.f_isfd = 1,
5853 	.f_detach = filt_vfsdetach,
5854 	.f_event = filt_vfsvnode
5855 };
5856 
5857 static void
5858 vfs_knllock(void *arg)
5859 {
5860 	struct vnode *vp = arg;
5861 
5862 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5863 }
5864 
5865 static void
5866 vfs_knlunlock(void *arg)
5867 {
5868 	struct vnode *vp = arg;
5869 
5870 	VOP_UNLOCK(vp);
5871 }
5872 
5873 static void
5874 vfs_knl_assert_locked(void *arg)
5875 {
5876 #ifdef DEBUG_VFS_LOCKS
5877 	struct vnode *vp = arg;
5878 
5879 	ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
5880 #endif
5881 }
5882 
5883 static void
5884 vfs_knl_assert_unlocked(void *arg)
5885 {
5886 #ifdef DEBUG_VFS_LOCKS
5887 	struct vnode *vp = arg;
5888 
5889 	ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
5890 #endif
5891 }
5892 
5893 int
5894 vfs_kqfilter(struct vop_kqfilter_args *ap)
5895 {
5896 	struct vnode *vp = ap->a_vp;
5897 	struct knote *kn = ap->a_kn;
5898 	struct knlist *knl;
5899 
5900 	switch (kn->kn_filter) {
5901 	case EVFILT_READ:
5902 		kn->kn_fop = &vfsread_filtops;
5903 		break;
5904 	case EVFILT_WRITE:
5905 		kn->kn_fop = &vfswrite_filtops;
5906 		break;
5907 	case EVFILT_VNODE:
5908 		kn->kn_fop = &vfsvnode_filtops;
5909 		break;
5910 	default:
5911 		return (EINVAL);
5912 	}
5913 
5914 	kn->kn_hook = (caddr_t)vp;
5915 
5916 	v_addpollinfo(vp);
5917 	if (vp->v_pollinfo == NULL)
5918 		return (ENOMEM);
5919 	knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5920 	vhold(vp);
5921 	knlist_add(knl, kn, 0);
5922 
5923 	return (0);
5924 }
5925 
5926 /*
5927  * Detach knote from vnode
5928  */
5929 static void
5930 filt_vfsdetach(struct knote *kn)
5931 {
5932 	struct vnode *vp = (struct vnode *)kn->kn_hook;
5933 
5934 	KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
5935 	knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
5936 	vdrop(vp);
5937 }
5938 
5939 /*ARGSUSED*/
5940 static int
5941 filt_vfsread(struct knote *kn, long hint)
5942 {
5943 	struct vnode *vp = (struct vnode *)kn->kn_hook;
5944 	struct vattr va;
5945 	int res;
5946 
5947 	/*
5948 	 * filesystem is gone, so set the EOF flag and schedule
5949 	 * the knote for deletion.
5950 	 */
5951 	if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5952 		VI_LOCK(vp);
5953 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5954 		VI_UNLOCK(vp);
5955 		return (1);
5956 	}
5957 
5958 	if (VOP_GETATTR(vp, &va, curthread->td_ucred))
5959 		return (0);
5960 
5961 	VI_LOCK(vp);
5962 	kn->kn_data = va.va_size - kn->kn_fp->f_offset;
5963 	res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
5964 	VI_UNLOCK(vp);
5965 	return (res);
5966 }
5967 
5968 /*ARGSUSED*/
5969 static int
5970 filt_vfswrite(struct knote *kn, long hint)
5971 {
5972 	struct vnode *vp = (struct vnode *)kn->kn_hook;
5973 
5974 	VI_LOCK(vp);
5975 
5976 	/*
5977 	 * filesystem is gone, so set the EOF flag and schedule
5978 	 * the knote for deletion.
5979 	 */
5980 	if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
5981 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5982 
5983 	kn->kn_data = 0;
5984 	VI_UNLOCK(vp);
5985 	return (1);
5986 }
5987 
5988 static int
5989 filt_vfsvnode(struct knote *kn, long hint)
5990 {
5991 	struct vnode *vp = (struct vnode *)kn->kn_hook;
5992 	int res;
5993 
5994 	VI_LOCK(vp);
5995 	if (kn->kn_sfflags & hint)
5996 		kn->kn_fflags |= hint;
5997 	if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5998 		kn->kn_flags |= EV_EOF;
5999 		VI_UNLOCK(vp);
6000 		return (1);
6001 	}
6002 	res = (kn->kn_fflags != 0);
6003 	VI_UNLOCK(vp);
6004 	return (res);
6005 }
6006 
6007 /*
6008  * Returns whether the directory is empty or not.
6009  * If it is empty, the return value is 0; otherwise
6010  * the return value is an error value (which may
6011  * be ENOTEMPTY).
6012  */
6013 int
6014 vfs_emptydir(struct vnode *vp)
6015 {
6016 	struct uio uio;
6017 	struct iovec iov;
6018 	struct dirent *dirent, *dp, *endp;
6019 	int error, eof;
6020 
6021 	error = 0;
6022 	eof = 0;
6023 
6024 	ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
6025 
6026 	dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
6027 	iov.iov_base = dirent;
6028 	iov.iov_len = sizeof(struct dirent);
6029 
6030 	uio.uio_iov = &iov;
6031 	uio.uio_iovcnt = 1;
6032 	uio.uio_offset = 0;
6033 	uio.uio_resid = sizeof(struct dirent);
6034 	uio.uio_segflg = UIO_SYSSPACE;
6035 	uio.uio_rw = UIO_READ;
6036 	uio.uio_td = curthread;
6037 
6038 	while (eof == 0 && error == 0) {
6039 		error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
6040 		    NULL, NULL);
6041 		if (error != 0)
6042 			break;
6043 		endp = (void *)((uint8_t *)dirent +
6044 		    sizeof(struct dirent) - uio.uio_resid);
6045 		for (dp = dirent; dp < endp;
6046 		     dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
6047 			if (dp->d_type == DT_WHT)
6048 				continue;
6049 			if (dp->d_namlen == 0)
6050 				continue;
6051 			if (dp->d_type != DT_DIR &&
6052 			    dp->d_type != DT_UNKNOWN) {
6053 				error = ENOTEMPTY;
6054 				break;
6055 			}
6056 			if (dp->d_namlen > 2) {
6057 				error = ENOTEMPTY;
6058 				break;
6059 			}
6060 			if (dp->d_namlen == 1 &&
6061 			    dp->d_name[0] != '.') {
6062 				error = ENOTEMPTY;
6063 				break;
6064 			}
6065 			if (dp->d_namlen == 2 &&
6066 			    dp->d_name[1] != '.') {
6067 				error = ENOTEMPTY;
6068 				break;
6069 			}
6070 			uio.uio_resid = sizeof(struct dirent);
6071 		}
6072 	}
6073 	free(dirent, M_TEMP);
6074 	return (error);
6075 }
6076 
6077 int
6078 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6079 {
6080 	int error;
6081 
6082 	if (dp->d_reclen > ap->a_uio->uio_resid)
6083 		return (ENAMETOOLONG);
6084 	error = uiomove(dp, dp->d_reclen, ap->a_uio);
6085 	if (error) {
6086 		if (ap->a_ncookies != NULL) {
6087 			if (ap->a_cookies != NULL)
6088 				free(ap->a_cookies, M_TEMP);
6089 			ap->a_cookies = NULL;
6090 			*ap->a_ncookies = 0;
6091 		}
6092 		return (error);
6093 	}
6094 	if (ap->a_ncookies == NULL)
6095 		return (0);
6096 
6097 	KASSERT(ap->a_cookies,
6098 	    ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6099 
6100 	*ap->a_cookies = realloc(*ap->a_cookies,
6101 	    (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
6102 	(*ap->a_cookies)[*ap->a_ncookies] = off;
6103 	*ap->a_ncookies += 1;
6104 	return (0);
6105 }
6106 
6107 /*
6108  * The purpose of this routine is to remove granularity from accmode_t,
6109  * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6110  * VADMIN and VAPPEND.
6111  *
6112  * If it returns 0, the caller is supposed to continue with the usual
6113  * access checks using 'accmode' as modified by this routine.  If it
6114  * returns nonzero value, the caller is supposed to return that value
6115  * as errno.
6116  *
6117  * Note that after this routine runs, accmode may be zero.
6118  */
6119 int
6120 vfs_unixify_accmode(accmode_t *accmode)
6121 {
6122 	/*
6123 	 * There is no way to specify explicit "deny" rule using
6124 	 * file mode or POSIX.1e ACLs.
6125 	 */
6126 	if (*accmode & VEXPLICIT_DENY) {
6127 		*accmode = 0;
6128 		return (0);
6129 	}
6130 
6131 	/*
6132 	 * None of these can be translated into usual access bits.
6133 	 * Also, the common case for NFSv4 ACLs is to not contain
6134 	 * either of these bits. Caller should check for VWRITE
6135 	 * on the containing directory instead.
6136 	 */
6137 	if (*accmode & (VDELETE_CHILD | VDELETE))
6138 		return (EPERM);
6139 
6140 	if (*accmode & VADMIN_PERMS) {
6141 		*accmode &= ~VADMIN_PERMS;
6142 		*accmode |= VADMIN;
6143 	}
6144 
6145 	/*
6146 	 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6147 	 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6148 	 */
6149 	*accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6150 
6151 	return (0);
6152 }
6153 
6154 /*
6155  * Clear out a doomed vnode (if any) and replace it with a new one as long
6156  * as the fs is not being unmounted. Return the root vnode to the caller.
6157  */
6158 static int __noinline
6159 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6160 {
6161 	struct vnode *vp;
6162 	int error;
6163 
6164 restart:
6165 	if (mp->mnt_rootvnode != NULL) {
6166 		MNT_ILOCK(mp);
6167 		vp = mp->mnt_rootvnode;
6168 		if (vp != NULL) {
6169 			if (!VN_IS_DOOMED(vp)) {
6170 				vrefact(vp);
6171 				MNT_IUNLOCK(mp);
6172 				error = vn_lock(vp, flags);
6173 				if (error == 0) {
6174 					*vpp = vp;
6175 					return (0);
6176 				}
6177 				vrele(vp);
6178 				goto restart;
6179 			}
6180 			/*
6181 			 * Clear the old one.
6182 			 */
6183 			mp->mnt_rootvnode = NULL;
6184 		}
6185 		MNT_IUNLOCK(mp);
6186 		if (vp != NULL) {
6187 			vfs_op_barrier_wait(mp);
6188 			vrele(vp);
6189 		}
6190 	}
6191 	error = VFS_CACHEDROOT(mp, flags, vpp);
6192 	if (error != 0)
6193 		return (error);
6194 	if (mp->mnt_vfs_ops == 0) {
6195 		MNT_ILOCK(mp);
6196 		if (mp->mnt_vfs_ops != 0) {
6197 			MNT_IUNLOCK(mp);
6198 			return (0);
6199 		}
6200 		if (mp->mnt_rootvnode == NULL) {
6201 			vrefact(*vpp);
6202 			mp->mnt_rootvnode = *vpp;
6203 		} else {
6204 			if (mp->mnt_rootvnode != *vpp) {
6205 				if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6206 					panic("%s: mismatch between vnode returned "
6207 					    " by VFS_CACHEDROOT and the one cached "
6208 					    " (%p != %p)",
6209 					    __func__, *vpp, mp->mnt_rootvnode);
6210 				}
6211 			}
6212 		}
6213 		MNT_IUNLOCK(mp);
6214 	}
6215 	return (0);
6216 }
6217 
6218 int
6219 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6220 {
6221 	struct vnode *vp;
6222 	int error;
6223 
6224 	if (!vfs_op_thread_enter(mp))
6225 		return (vfs_cache_root_fallback(mp, flags, vpp));
6226 	vp = atomic_load_ptr(&mp->mnt_rootvnode);
6227 	if (vp == NULL || VN_IS_DOOMED(vp)) {
6228 		vfs_op_thread_exit(mp);
6229 		return (vfs_cache_root_fallback(mp, flags, vpp));
6230 	}
6231 	vrefact(vp);
6232 	vfs_op_thread_exit(mp);
6233 	error = vn_lock(vp, flags);
6234 	if (error != 0) {
6235 		vrele(vp);
6236 		return (vfs_cache_root_fallback(mp, flags, vpp));
6237 	}
6238 	*vpp = vp;
6239 	return (0);
6240 }
6241 
6242 struct vnode *
6243 vfs_cache_root_clear(struct mount *mp)
6244 {
6245 	struct vnode *vp;
6246 
6247 	/*
6248 	 * ops > 0 guarantees there is nobody who can see this vnode
6249 	 */
6250 	MPASS(mp->mnt_vfs_ops > 0);
6251 	vp = mp->mnt_rootvnode;
6252 	mp->mnt_rootvnode = NULL;
6253 	return (vp);
6254 }
6255 
6256 void
6257 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6258 {
6259 
6260 	MPASS(mp->mnt_vfs_ops > 0);
6261 	vrefact(vp);
6262 	mp->mnt_rootvnode = vp;
6263 }
6264 
6265 /*
6266  * These are helper functions for filesystems to traverse all
6267  * their vnodes.  See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6268  *
6269  * This interface replaces MNT_VNODE_FOREACH.
6270  */
6271 
6272 struct vnode *
6273 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6274 {
6275 	struct vnode *vp;
6276 
6277 	if (should_yield())
6278 		kern_yield(PRI_USER);
6279 	MNT_ILOCK(mp);
6280 	KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6281 	for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6282 	    vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6283 		/* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6284 		if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6285 			continue;
6286 		VI_LOCK(vp);
6287 		if (VN_IS_DOOMED(vp)) {
6288 			VI_UNLOCK(vp);
6289 			continue;
6290 		}
6291 		break;
6292 	}
6293 	if (vp == NULL) {
6294 		__mnt_vnode_markerfree_all(mvp, mp);
6295 		/* MNT_IUNLOCK(mp); -- done in above function */
6296 		mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6297 		return (NULL);
6298 	}
6299 	TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6300 	TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6301 	MNT_IUNLOCK(mp);
6302 	return (vp);
6303 }
6304 
6305 struct vnode *
6306 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6307 {
6308 	struct vnode *vp;
6309 
6310 	*mvp = vn_alloc_marker(mp);
6311 	MNT_ILOCK(mp);
6312 	MNT_REF(mp);
6313 
6314 	TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6315 		/* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6316 		if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6317 			continue;
6318 		VI_LOCK(vp);
6319 		if (VN_IS_DOOMED(vp)) {
6320 			VI_UNLOCK(vp);
6321 			continue;
6322 		}
6323 		break;
6324 	}
6325 	if (vp == NULL) {
6326 		MNT_REL(mp);
6327 		MNT_IUNLOCK(mp);
6328 		vn_free_marker(*mvp);
6329 		*mvp = NULL;
6330 		return (NULL);
6331 	}
6332 	TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6333 	MNT_IUNLOCK(mp);
6334 	return (vp);
6335 }
6336 
6337 void
6338 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6339 {
6340 
6341 	if (*mvp == NULL) {
6342 		MNT_IUNLOCK(mp);
6343 		return;
6344 	}
6345 
6346 	mtx_assert(MNT_MTX(mp), MA_OWNED);
6347 
6348 	KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6349 	TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6350 	MNT_REL(mp);
6351 	MNT_IUNLOCK(mp);
6352 	vn_free_marker(*mvp);
6353 	*mvp = NULL;
6354 }
6355 
6356 /*
6357  * These are helper functions for filesystems to traverse their
6358  * lazy vnodes.  See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6359  */
6360 static void
6361 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6362 {
6363 
6364 	KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6365 
6366 	MNT_ILOCK(mp);
6367 	MNT_REL(mp);
6368 	MNT_IUNLOCK(mp);
6369 	vn_free_marker(*mvp);
6370 	*mvp = NULL;
6371 }
6372 
6373 /*
6374  * Relock the mp mount vnode list lock with the vp vnode interlock in the
6375  * conventional lock order during mnt_vnode_next_lazy iteration.
6376  *
6377  * On entry, the mount vnode list lock is held and the vnode interlock is not.
6378  * The list lock is dropped and reacquired.  On success, both locks are held.
6379  * On failure, the mount vnode list lock is held but the vnode interlock is
6380  * not, and the procedure may have yielded.
6381  */
6382 static bool
6383 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6384     struct vnode *vp)
6385 {
6386 
6387 	VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6388 	    TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6389 	    ("%s: bad marker", __func__));
6390 	VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6391 	    ("%s: inappropriate vnode", __func__));
6392 	ASSERT_VI_UNLOCKED(vp, __func__);
6393 	mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6394 
6395 	TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6396 	TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6397 
6398 	/*
6399 	 * Note we may be racing against vdrop which transitioned the hold
6400 	 * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
6401 	 * if we are the only user after we get the interlock we will just
6402 	 * vdrop.
6403 	 */
6404 	vhold(vp);
6405 	mtx_unlock(&mp->mnt_listmtx);
6406 	VI_LOCK(vp);
6407 	if (VN_IS_DOOMED(vp)) {
6408 		VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
6409 		goto out_lost;
6410 	}
6411 	VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
6412 	/*
6413 	 * There is nothing to do if we are the last user.
6414 	 */
6415 	if (!refcount_release_if_not_last(&vp->v_holdcnt))
6416 		goto out_lost;
6417 	mtx_lock(&mp->mnt_listmtx);
6418 	return (true);
6419 out_lost:
6420 	vdropl(vp);
6421 	maybe_yield();
6422 	mtx_lock(&mp->mnt_listmtx);
6423 	return (false);
6424 }
6425 
6426 static struct vnode *
6427 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6428     void *cbarg)
6429 {
6430 	struct vnode *vp;
6431 
6432 	mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6433 	KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6434 restart:
6435 	vp = TAILQ_NEXT(*mvp, v_lazylist);
6436 	while (vp != NULL) {
6437 		if (vp->v_type == VMARKER) {
6438 			vp = TAILQ_NEXT(vp, v_lazylist);
6439 			continue;
6440 		}
6441 		/*
6442 		 * See if we want to process the vnode. Note we may encounter a
6443 		 * long string of vnodes we don't care about and hog the list
6444 		 * as a result. Check for it and requeue the marker.
6445 		 */
6446 		VNPASS(!VN_IS_DOOMED(vp), vp);
6447 		if (!cb(vp, cbarg)) {
6448 			if (!should_yield()) {
6449 				vp = TAILQ_NEXT(vp, v_lazylist);
6450 				continue;
6451 			}
6452 			TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6453 			    v_lazylist);
6454 			TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6455 			    v_lazylist);
6456 			mtx_unlock(&mp->mnt_listmtx);
6457 			kern_yield(PRI_USER);
6458 			mtx_lock(&mp->mnt_listmtx);
6459 			goto restart;
6460 		}
6461 		/*
6462 		 * Try-lock because this is the wrong lock order.
6463 		 */
6464 		if (!VI_TRYLOCK(vp) &&
6465 		    !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6466 			goto restart;
6467 		KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6468 		KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6469 		    ("alien vnode on the lazy list %p %p", vp, mp));
6470 		VNPASS(vp->v_mount == mp, vp);
6471 		VNPASS(!VN_IS_DOOMED(vp), vp);
6472 		break;
6473 	}
6474 	TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6475 
6476 	/* Check if we are done */
6477 	if (vp == NULL) {
6478 		mtx_unlock(&mp->mnt_listmtx);
6479 		mnt_vnode_markerfree_lazy(mvp, mp);
6480 		return (NULL);
6481 	}
6482 	TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6483 	mtx_unlock(&mp->mnt_listmtx);
6484 	ASSERT_VI_LOCKED(vp, "lazy iter");
6485 	return (vp);
6486 }
6487 
6488 struct vnode *
6489 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6490     void *cbarg)
6491 {
6492 
6493 	if (should_yield())
6494 		kern_yield(PRI_USER);
6495 	mtx_lock(&mp->mnt_listmtx);
6496 	return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6497 }
6498 
6499 struct vnode *
6500 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6501     void *cbarg)
6502 {
6503 	struct vnode *vp;
6504 
6505 	if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
6506 		return (NULL);
6507 
6508 	*mvp = vn_alloc_marker(mp);
6509 	MNT_ILOCK(mp);
6510 	MNT_REF(mp);
6511 	MNT_IUNLOCK(mp);
6512 
6513 	mtx_lock(&mp->mnt_listmtx);
6514 	vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6515 	if (vp == NULL) {
6516 		mtx_unlock(&mp->mnt_listmtx);
6517 		mnt_vnode_markerfree_lazy(mvp, mp);
6518 		return (NULL);
6519 	}
6520 	TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6521 	return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6522 }
6523 
6524 void
6525 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6526 {
6527 
6528 	if (*mvp == NULL)
6529 		return;
6530 
6531 	mtx_lock(&mp->mnt_listmtx);
6532 	TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6533 	mtx_unlock(&mp->mnt_listmtx);
6534 	mnt_vnode_markerfree_lazy(mvp, mp);
6535 }
6536 
6537 int
6538 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
6539 {
6540 
6541 	if ((cnp->cn_flags & NOEXECCHECK) != 0) {
6542 		cnp->cn_flags &= ~NOEXECCHECK;
6543 		return (0);
6544 	}
6545 
6546 	return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, cnp->cn_thread));
6547 }
6548