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