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