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