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