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