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