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