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