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