2 * SPDX-License-Identifier: BSD-3-Clause
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.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
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.
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
36 * @(#)vfs_subr.c 8.31 (Berkeley) 5/26/95
40 * External virtual filesystem routines
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
47 #include "opt_watchdog.h"
49 #include <sys/param.h>
50 #include <sys/systm.h>
53 #include <sys/capsicum.h>
54 #include <sys/condvar.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>
62 #include <sys/fcntl.h>
65 #include <sys/kernel.h>
66 #include <sys/kthread.h>
68 #include <sys/lockf.h>
69 #include <sys/malloc.h>
70 #include <sys/mount.h>
71 #include <sys/namei.h>
72 #include <sys/pctrie.h>
74 #include <sys/reboot.h>
75 #include <sys/refcount.h>
76 #include <sys/rwlock.h>
77 #include <sys/sched.h>
78 #include <sys/sleepqueue.h>
82 #include <sys/sysctl.h>
83 #include <sys/syslog.h>
84 #include <sys/vmmeter.h>
85 #include <sys/vnode.h>
86 #include <sys/watchdog.h>
88 #include <machine/stdarg.h>
90 #include <security/mac/mac_framework.h>
93 #include <vm/vm_object.h>
94 #include <vm/vm_extern.h>
96 #include <vm/vm_map.h>
97 #include <vm/vm_page.h>
98 #include <vm/vm_kern.h>
105 static void delmntque(struct vnode *vp);
106 static int flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
107 int slpflag, int slptimeo);
108 static void syncer_shutdown(void *arg, int howto);
109 static int vtryrecycle(struct vnode *vp);
110 static void v_init_counters(struct vnode *);
111 static void vgonel(struct vnode *);
112 static void vfs_knllock(void *arg);
113 static void vfs_knlunlock(void *arg);
114 static void vfs_knl_assert_locked(void *arg);
115 static void vfs_knl_assert_unlocked(void *arg);
116 static void destroy_vpollinfo(struct vpollinfo *vi);
117 static int v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
118 daddr_t startlbn, daddr_t endlbn);
119 static void vnlru_recalc(void);
122 * These fences are intended for cases where some synchronization is
123 * needed between access of v_iflags and lockless vnode refcount (v_holdcnt
124 * and v_usecount) updates. Access to v_iflags is generally synchronized
125 * by the interlock, but we have some internal assertions that check vnode
126 * flags without acquiring the lock. Thus, these fences are INVARIANTS-only
130 #define VNODE_REFCOUNT_FENCE_ACQ() atomic_thread_fence_acq()
131 #define VNODE_REFCOUNT_FENCE_REL() atomic_thread_fence_rel()
133 #define VNODE_REFCOUNT_FENCE_ACQ()
134 #define VNODE_REFCOUNT_FENCE_REL()
138 * Number of vnodes in existence. Increased whenever getnewvnode()
139 * allocates a new vnode, decreased in vdropl() for VIRF_DOOMED vnode.
141 static u_long __exclusive_cache_line numvnodes;
143 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
144 "Number of vnodes in existence");
146 static counter_u64_t vnodes_created;
147 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
148 "Number of vnodes created by getnewvnode");
151 * Conversion tables for conversion from vnode types to inode formats
154 enum vtype iftovt_tab[16] = {
155 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
156 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
158 int vttoif_tab[10] = {
159 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
160 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
164 * List of allocates vnodes in the system.
166 static TAILQ_HEAD(freelst, vnode) vnode_list;
167 static struct vnode *vnode_list_free_marker;
168 static struct vnode *vnode_list_reclaim_marker;
171 * "Free" vnode target. Free vnodes are rarely completely free, but are
172 * just ones that are cheap to recycle. Usually they are for files which
173 * have been stat'd but not read; these usually have inode and namecache
174 * data attached to them. This target is the preferred minimum size of a
175 * sub-cache consisting mostly of such files. The system balances the size
176 * of this sub-cache with its complement to try to prevent either from
177 * thrashing while the other is relatively inactive. The targets express
178 * a preference for the best balance.
180 * "Above" this target there are 2 further targets (watermarks) related
181 * to recyling of free vnodes. In the best-operating case, the cache is
182 * exactly full, the free list has size between vlowat and vhiwat above the
183 * free target, and recycling from it and normal use maintains this state.
184 * Sometimes the free list is below vlowat or even empty, but this state
185 * is even better for immediate use provided the cache is not full.
186 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
187 * ones) to reach one of these states. The watermarks are currently hard-
188 * coded as 4% and 9% of the available space higher. These and the default
189 * of 25% for wantfreevnodes are too large if the memory size is large.
190 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
191 * whenever vnlru_proc() becomes active.
193 static long wantfreevnodes;
194 static long __exclusive_cache_line freevnodes;
195 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
196 &freevnodes, 0, "Number of \"free\" vnodes");
197 static long freevnodes_old;
199 static counter_u64_t recycles_count;
200 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
201 "Number of vnodes recycled to meet vnode cache targets");
203 static counter_u64_t recycles_free_count;
204 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD, &recycles_free_count,
205 "Number of free vnodes recycled to meet vnode cache targets");
207 static counter_u64_t deferred_inact;
208 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, deferred_inact, CTLFLAG_RD, &deferred_inact,
209 "Number of times inactive processing was deferred");
211 /* To keep more than one thread at a time from running vfs_getnewfsid */
212 static struct mtx mntid_mtx;
215 * Lock for any access to the following:
220 static struct mtx __exclusive_cache_line vnode_list_mtx;
222 /* Publicly exported FS */
223 struct nfs_public nfs_pub;
225 static uma_zone_t buf_trie_zone;
226 static smr_t buf_trie_smr;
228 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
229 static uma_zone_t vnode_zone;
230 static uma_zone_t vnodepoll_zone;
232 __read_frequently smr_t vfs_smr;
235 * The workitem queue.
237 * It is useful to delay writes of file data and filesystem metadata
238 * for tens of seconds so that quickly created and deleted files need
239 * not waste disk bandwidth being created and removed. To realize this,
240 * we append vnodes to a "workitem" queue. When running with a soft
241 * updates implementation, most pending metadata dependencies should
242 * not wait for more than a few seconds. Thus, mounted on block devices
243 * are delayed only about a half the time that file data is delayed.
244 * Similarly, directory updates are more critical, so are only delayed
245 * about a third the time that file data is delayed. Thus, there are
246 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
247 * one each second (driven off the filesystem syncer process). The
248 * syncer_delayno variable indicates the next queue that is to be processed.
249 * Items that need to be processed soon are placed in this queue:
251 * syncer_workitem_pending[syncer_delayno]
253 * A delay of fifteen seconds is done by placing the request fifteen
254 * entries later in the queue:
256 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
259 static int syncer_delayno;
260 static long syncer_mask;
261 LIST_HEAD(synclist, bufobj);
262 static struct synclist *syncer_workitem_pending;
264 * The sync_mtx protects:
269 * syncer_workitem_pending
270 * syncer_worklist_len
273 static struct mtx sync_mtx;
274 static struct cv sync_wakeup;
276 #define SYNCER_MAXDELAY 32
277 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
278 static int syncdelay = 30; /* max time to delay syncing data */
279 static int filedelay = 30; /* time to delay syncing files */
280 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
281 "Time to delay syncing files (in seconds)");
282 static int dirdelay = 29; /* time to delay syncing directories */
283 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
284 "Time to delay syncing directories (in seconds)");
285 static int metadelay = 28; /* time to delay syncing metadata */
286 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
287 "Time to delay syncing metadata (in seconds)");
288 static int rushjob; /* number of slots to run ASAP */
289 static int stat_rush_requests; /* number of times I/O speeded up */
290 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
291 "Number of times I/O speeded up (rush requests)");
293 #define VDBATCH_SIZE 8
298 struct vnode *tab[VDBATCH_SIZE];
300 DPCPU_DEFINE_STATIC(struct vdbatch, vd);
302 static void vdbatch_dequeue(struct vnode *vp);
305 * When shutting down the syncer, run it at four times normal speed.
307 #define SYNCER_SHUTDOWN_SPEEDUP 4
308 static int sync_vnode_count;
309 static int syncer_worklist_len;
310 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
313 /* Target for maximum number of vnodes. */
314 u_long desiredvnodes;
315 static u_long gapvnodes; /* gap between wanted and desired */
316 static u_long vhiwat; /* enough extras after expansion */
317 static u_long vlowat; /* minimal extras before expansion */
318 static u_long vstir; /* nonzero to stir non-free vnodes */
319 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
321 static u_long vnlru_read_freevnodes(void);
324 * Note that no attempt is made to sanitize these parameters.
327 sysctl_maxvnodes(SYSCTL_HANDLER_ARGS)
333 error = sysctl_handle_long(oidp, &val, 0, req);
334 if (error != 0 || req->newptr == NULL)
337 if (val == desiredvnodes)
339 mtx_lock(&vnode_list_mtx);
341 wantfreevnodes = desiredvnodes / 4;
343 mtx_unlock(&vnode_list_mtx);
345 * XXX There is no protection against multiple threads changing
346 * desiredvnodes at the same time. Locking above only helps vnlru and
349 vfs_hash_changesize(desiredvnodes);
350 cache_changesize(desiredvnodes);
354 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
355 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
356 "LU", "Target for maximum number of vnodes");
359 sysctl_wantfreevnodes(SYSCTL_HANDLER_ARGS)
364 val = wantfreevnodes;
365 error = sysctl_handle_long(oidp, &val, 0, req);
366 if (error != 0 || req->newptr == NULL)
369 if (val == wantfreevnodes)
371 mtx_lock(&vnode_list_mtx);
372 wantfreevnodes = val;
374 mtx_unlock(&vnode_list_mtx);
378 SYSCTL_PROC(_vfs, OID_AUTO, wantfreevnodes,
379 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
380 "LU", "Target for minimum number of \"free\" vnodes");
382 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
383 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
384 static int vnlru_nowhere;
385 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
386 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
389 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
394 unsigned long ndflags;
397 if (req->newptr == NULL)
399 if (req->newlen >= PATH_MAX)
402 buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
403 error = SYSCTL_IN(req, buf, req->newlen);
407 buf[req->newlen] = '\0';
409 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | SAVENAME;
410 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
411 if ((error = namei(&nd)) != 0)
415 if (VN_IS_DOOMED(vp)) {
417 * This vnode is being recycled. Return != 0 to let the caller
418 * know that the sysctl had no effect. Return EAGAIN because a
419 * subsequent call will likely succeed (since namei will create
420 * a new vnode if necessary)
426 counter_u64_add(recycles_count, 1);
436 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
438 struct thread *td = curthread;
444 if (req->newptr == NULL)
447 error = sysctl_handle_int(oidp, &fd, 0, req);
450 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
455 error = vn_lock(vp, LK_EXCLUSIVE);
459 counter_u64_add(recycles_count, 1);
467 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
468 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
469 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
470 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
471 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
472 sysctl_ftry_reclaim_vnode, "I",
473 "Try to reclaim a vnode by its file descriptor");
475 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
479 * Support for the bufobj clean & dirty pctrie.
482 buf_trie_alloc(struct pctrie *ptree)
484 return (uma_zalloc_smr(buf_trie_zone, M_NOWAIT));
488 buf_trie_free(struct pctrie *ptree, void *node)
490 uma_zfree_smr(buf_trie_zone, node);
492 PCTRIE_DEFINE_SMR(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free,
496 * Initialize the vnode management data structures.
498 * Reevaluate the following cap on the number of vnodes after the physical
499 * memory size exceeds 512GB. In the limit, as the physical memory size
500 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
502 #ifndef MAXVNODES_MAX
503 #define MAXVNODES_MAX (512UL * 1024 * 1024 / 64) /* 8M */
506 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
508 static struct vnode *
509 vn_alloc_marker(struct mount *mp)
513 vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
514 vp->v_type = VMARKER;
521 vn_free_marker(struct vnode *vp)
524 MPASS(vp->v_type == VMARKER);
525 free(vp, M_VNODE_MARKER);
529 * Initialize a vnode as it first enters the zone.
532 vnode_init(void *mem, int size, int flags)
541 vp->v_vnlock = &vp->v_lock;
542 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
544 * By default, don't allow shared locks unless filesystems opt-in.
546 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
547 LK_NOSHARE | LK_IS_VNODE);
551 bufobj_init(&vp->v_bufobj, vp);
553 * Initialize namecache.
555 cache_vnode_init(vp);
557 * Initialize rangelocks.
559 rangelock_init(&vp->v_rl);
561 vp->v_dbatchcpu = NOCPU;
563 mtx_lock(&vnode_list_mtx);
564 TAILQ_INSERT_BEFORE(vnode_list_free_marker, vp, v_vnodelist);
565 mtx_unlock(&vnode_list_mtx);
570 * Free a vnode when it is cleared from the zone.
573 vnode_fini(void *mem, int size)
580 mtx_lock(&vnode_list_mtx);
581 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
582 mtx_unlock(&vnode_list_mtx);
583 rangelock_destroy(&vp->v_rl);
584 lockdestroy(vp->v_vnlock);
585 mtx_destroy(&vp->v_interlock);
587 rw_destroy(BO_LOCKPTR(bo));
591 * Provide the size of NFS nclnode and NFS fh for calculation of the
592 * vnode memory consumption. The size is specified directly to
593 * eliminate dependency on NFS-private header.
595 * Other filesystems may use bigger or smaller (like UFS and ZFS)
596 * private inode data, but the NFS-based estimation is ample enough.
597 * Still, we care about differences in the size between 64- and 32-bit
600 * Namecache structure size is heuristically
601 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
604 #define NFS_NCLNODE_SZ (528 + 64)
607 #define NFS_NCLNODE_SZ (360 + 32)
612 vntblinit(void *dummy __unused)
615 int cpu, physvnodes, virtvnodes;
619 * Desiredvnodes is a function of the physical memory size and the
620 * kernel's heap size. Generally speaking, it scales with the
621 * physical memory size. The ratio of desiredvnodes to the physical
622 * memory size is 1:16 until desiredvnodes exceeds 98,304.
624 * marginal ratio of desiredvnodes to the physical memory size is
625 * 1:64. However, desiredvnodes is limited by the kernel's heap
626 * size. The memory required by desiredvnodes vnodes and vm objects
627 * must not exceed 1/10th of the kernel's heap size.
629 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
630 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
631 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
632 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
633 desiredvnodes = min(physvnodes, virtvnodes);
634 if (desiredvnodes > MAXVNODES_MAX) {
636 printf("Reducing kern.maxvnodes %lu -> %lu\n",
637 desiredvnodes, MAXVNODES_MAX);
638 desiredvnodes = MAXVNODES_MAX;
640 wantfreevnodes = desiredvnodes / 4;
641 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
642 TAILQ_INIT(&vnode_list);
643 mtx_init(&vnode_list_mtx, "vnode_list", NULL, MTX_DEF);
645 * The lock is taken to appease WITNESS.
647 mtx_lock(&vnode_list_mtx);
649 mtx_unlock(&vnode_list_mtx);
650 vnode_list_free_marker = vn_alloc_marker(NULL);
651 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_free_marker, v_vnodelist);
652 vnode_list_reclaim_marker = vn_alloc_marker(NULL);
653 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_reclaim_marker, v_vnodelist);
654 vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
655 vnode_init, vnode_fini, UMA_ALIGN_PTR, 0);
656 uma_zone_set_smr(vnode_zone, vfs_smr);
657 vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
658 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
660 * Preallocate enough nodes to support one-per buf so that
661 * we can not fail an insert. reassignbuf() callers can not
662 * tolerate the insertion failure.
664 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
665 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
666 UMA_ZONE_NOFREE | UMA_ZONE_SMR);
667 buf_trie_smr = uma_zone_get_smr(buf_trie_zone);
668 uma_prealloc(buf_trie_zone, nbuf);
670 vnodes_created = counter_u64_alloc(M_WAITOK);
671 recycles_count = counter_u64_alloc(M_WAITOK);
672 recycles_free_count = counter_u64_alloc(M_WAITOK);
673 deferred_inact = counter_u64_alloc(M_WAITOK);
676 * Initialize the filesystem syncer.
678 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
680 syncer_maxdelay = syncer_mask + 1;
681 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
682 cv_init(&sync_wakeup, "syncer");
683 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
688 vd = DPCPU_ID_PTR((cpu), vd);
689 bzero(vd, sizeof(*vd));
690 mtx_init(&vd->lock, "vdbatch", NULL, MTX_DEF);
693 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
696 * Mark a mount point as busy. Used to synchronize access and to delay
697 * unmounting. Eventually, mountlist_mtx is not released on failure.
699 * vfs_busy() is a custom lock, it can block the caller.
700 * vfs_busy() only sleeps if the unmount is active on the mount point.
701 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
702 * vnode belonging to mp.
704 * Lookup uses vfs_busy() to traverse mount points.
706 * / vnode lock A / vnode lock (/var) D
707 * /var vnode lock B /log vnode lock(/var/log) E
708 * vfs_busy lock C vfs_busy lock F
710 * Within each file system, the lock order is C->A->B and F->D->E.
712 * When traversing across mounts, the system follows that lock order:
718 * The lookup() process for namei("/var") illustrates the process:
719 * VOP_LOOKUP() obtains B while A is held
720 * vfs_busy() obtains a shared lock on F while A and B are held
721 * vput() releases lock on B
722 * vput() releases lock on A
723 * VFS_ROOT() obtains lock on D while shared lock on F is held
724 * vfs_unbusy() releases shared lock on F
725 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
726 * Attempt to lock A (instead of vp_crossmp) while D is held would
727 * violate the global order, causing deadlocks.
729 * dounmount() locks B while F is drained.
732 vfs_busy(struct mount *mp, int flags)
735 MPASS((flags & ~MBF_MASK) == 0);
736 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
738 if (vfs_op_thread_enter(mp)) {
739 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
740 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
741 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
742 vfs_mp_count_add_pcpu(mp, ref, 1);
743 vfs_mp_count_add_pcpu(mp, lockref, 1);
744 vfs_op_thread_exit(mp);
745 if (flags & MBF_MNTLSTLOCK)
746 mtx_unlock(&mountlist_mtx);
751 vfs_assert_mount_counters(mp);
754 * If mount point is currently being unmounted, sleep until the
755 * mount point fate is decided. If thread doing the unmounting fails,
756 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
757 * that this mount point has survived the unmount attempt and vfs_busy
758 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
759 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
760 * about to be really destroyed. vfs_busy needs to release its
761 * reference on the mount point in this case and return with ENOENT,
762 * telling the caller that mount mount it tried to busy is no longer
765 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
766 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
769 CTR1(KTR_VFS, "%s: failed busying before sleeping",
773 if (flags & MBF_MNTLSTLOCK)
774 mtx_unlock(&mountlist_mtx);
775 mp->mnt_kern_flag |= MNTK_MWAIT;
776 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
777 if (flags & MBF_MNTLSTLOCK)
778 mtx_lock(&mountlist_mtx);
781 if (flags & MBF_MNTLSTLOCK)
782 mtx_unlock(&mountlist_mtx);
789 * Free a busy filesystem.
792 vfs_unbusy(struct mount *mp)
796 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
798 if (vfs_op_thread_enter(mp)) {
799 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
800 vfs_mp_count_sub_pcpu(mp, lockref, 1);
801 vfs_mp_count_sub_pcpu(mp, ref, 1);
802 vfs_op_thread_exit(mp);
807 vfs_assert_mount_counters(mp);
809 c = --mp->mnt_lockref;
810 if (mp->mnt_vfs_ops == 0) {
811 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
816 vfs_dump_mount_counters(mp);
817 if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
818 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
819 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
820 mp->mnt_kern_flag &= ~MNTK_DRAINING;
821 wakeup(&mp->mnt_lockref);
827 * Lookup a mount point by filesystem identifier.
830 vfs_getvfs(fsid_t *fsid)
834 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
835 mtx_lock(&mountlist_mtx);
836 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
837 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
839 mtx_unlock(&mountlist_mtx);
843 mtx_unlock(&mountlist_mtx);
844 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
845 return ((struct mount *) 0);
849 * Lookup a mount point by filesystem identifier, busying it before
852 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
853 * cache for popular filesystem identifiers. The cache is lockess, using
854 * the fact that struct mount's are never freed. In worst case we may
855 * get pointer to unmounted or even different filesystem, so we have to
856 * check what we got, and go slow way if so.
859 vfs_busyfs(fsid_t *fsid)
861 #define FSID_CACHE_SIZE 256
862 typedef struct mount * volatile vmp_t;
863 static vmp_t cache[FSID_CACHE_SIZE];
868 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
869 hash = fsid->val[0] ^ fsid->val[1];
870 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
872 if (mp == NULL || fsidcmp(&mp->mnt_stat.f_fsid, fsid) != 0)
874 if (vfs_busy(mp, 0) != 0) {
878 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0)
884 mtx_lock(&mountlist_mtx);
885 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
886 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
887 error = vfs_busy(mp, MBF_MNTLSTLOCK);
890 mtx_unlock(&mountlist_mtx);
897 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
898 mtx_unlock(&mountlist_mtx);
899 return ((struct mount *) 0);
903 * Check if a user can access privileged mount options.
906 vfs_suser(struct mount *mp, struct thread *td)
910 if (jailed(td->td_ucred)) {
912 * If the jail of the calling thread lacks permission for
913 * this type of file system, deny immediately.
915 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
919 * If the file system was mounted outside the jail of the
920 * calling thread, deny immediately.
922 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
927 * If file system supports delegated administration, we don't check
928 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
929 * by the file system itself.
930 * If this is not the user that did original mount, we check for
931 * the PRIV_VFS_MOUNT_OWNER privilege.
933 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
934 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
935 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
942 * Get a new unique fsid. Try to make its val[0] unique, since this value
943 * will be used to create fake device numbers for stat(). Also try (but
944 * not so hard) make its val[0] unique mod 2^16, since some emulators only
945 * support 16-bit device numbers. We end up with unique val[0]'s for the
946 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
948 * Keep in mind that several mounts may be running in parallel. Starting
949 * the search one past where the previous search terminated is both a
950 * micro-optimization and a defense against returning the same fsid to
954 vfs_getnewfsid(struct mount *mp)
956 static uint16_t mntid_base;
961 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
962 mtx_lock(&mntid_mtx);
963 mtype = mp->mnt_vfc->vfc_typenum;
964 tfsid.val[1] = mtype;
965 mtype = (mtype & 0xFF) << 24;
967 tfsid.val[0] = makedev(255,
968 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
970 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
974 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
975 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
976 mtx_unlock(&mntid_mtx);
980 * Knob to control the precision of file timestamps:
982 * 0 = seconds only; nanoseconds zeroed.
983 * 1 = seconds and nanoseconds, accurate within 1/HZ.
984 * 2 = seconds and nanoseconds, truncated to microseconds.
985 * >=3 = seconds and nanoseconds, maximum precision.
987 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
989 static int timestamp_precision = TSP_USEC;
990 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
991 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
992 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
993 "3+: sec + ns (max. precision))");
996 * Get a current timestamp.
999 vfs_timestamp(struct timespec *tsp)
1003 switch (timestamp_precision) {
1005 tsp->tv_sec = time_second;
1013 TIMEVAL_TO_TIMESPEC(&tv, tsp);
1023 * Set vnode attributes to VNOVAL
1026 vattr_null(struct vattr *vap)
1029 vap->va_type = VNON;
1030 vap->va_size = VNOVAL;
1031 vap->va_bytes = VNOVAL;
1032 vap->va_mode = VNOVAL;
1033 vap->va_nlink = VNOVAL;
1034 vap->va_uid = VNOVAL;
1035 vap->va_gid = VNOVAL;
1036 vap->va_fsid = VNOVAL;
1037 vap->va_fileid = VNOVAL;
1038 vap->va_blocksize = VNOVAL;
1039 vap->va_rdev = VNOVAL;
1040 vap->va_atime.tv_sec = VNOVAL;
1041 vap->va_atime.tv_nsec = VNOVAL;
1042 vap->va_mtime.tv_sec = VNOVAL;
1043 vap->va_mtime.tv_nsec = VNOVAL;
1044 vap->va_ctime.tv_sec = VNOVAL;
1045 vap->va_ctime.tv_nsec = VNOVAL;
1046 vap->va_birthtime.tv_sec = VNOVAL;
1047 vap->va_birthtime.tv_nsec = VNOVAL;
1048 vap->va_flags = VNOVAL;
1049 vap->va_gen = VNOVAL;
1050 vap->va_vaflags = 0;
1054 * Try to reduce the total number of vnodes.
1056 * This routine (and its user) are buggy in at least the following ways:
1057 * - all parameters were picked years ago when RAM sizes were significantly
1059 * - it can pick vnodes based on pages used by the vm object, but filesystems
1060 * like ZFS don't use it making the pick broken
1061 * - since ZFS has its own aging policy it gets partially combated by this one
1062 * - a dedicated method should be provided for filesystems to let them decide
1063 * whether the vnode should be recycled
1065 * This routine is called when we have too many vnodes. It attempts
1066 * to free <count> vnodes and will potentially free vnodes that still
1067 * have VM backing store (VM backing store is typically the cause
1068 * of a vnode blowout so we want to do this). Therefore, this operation
1069 * is not considered cheap.
1071 * A number of conditions may prevent a vnode from being reclaimed.
1072 * the buffer cache may have references on the vnode, a directory
1073 * vnode may still have references due to the namei cache representing
1074 * underlying files, or the vnode may be in active use. It is not
1075 * desirable to reuse such vnodes. These conditions may cause the
1076 * number of vnodes to reach some minimum value regardless of what
1077 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
1079 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1080 * entries if this argument is strue
1081 * @param trigger Only reclaim vnodes with fewer than this many resident
1083 * @param target How many vnodes to reclaim.
1084 * @return The number of vnodes that were reclaimed.
1087 vlrureclaim(bool reclaim_nc_src, int trigger, u_long target)
1089 struct vnode *vp, *mvp;
1091 struct vm_object *object;
1095 mtx_assert(&vnode_list_mtx, MA_OWNED);
1100 mvp = vnode_list_reclaim_marker;
1103 while (done < target) {
1104 vp = TAILQ_NEXT(vp, v_vnodelist);
1105 if (__predict_false(vp == NULL))
1108 if (__predict_false(vp->v_type == VMARKER))
1112 * If it's been deconstructed already, it's still
1113 * referenced, or it exceeds the trigger, skip it.
1114 * Also skip free vnodes. We are trying to make space
1115 * to expand the free list, not reduce it.
1117 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1118 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)))
1121 if (vp->v_type == VBAD || vp->v_type == VNON)
1124 if (!VI_TRYLOCK(vp))
1127 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1128 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1129 VN_IS_DOOMED(vp) || vp->v_type == VNON) {
1134 object = atomic_load_ptr(&vp->v_object);
1135 if (object == NULL || object->resident_page_count > trigger) {
1142 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1143 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1144 mtx_unlock(&vnode_list_mtx);
1146 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1148 goto next_iter_unlocked;
1150 if (VOP_LOCK(vp, LK_EXCLUSIVE|LK_NOWAIT) != 0) {
1152 vn_finished_write(mp);
1153 goto next_iter_unlocked;
1157 if (vp->v_usecount > 0 ||
1158 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1159 (vp->v_object != NULL &&
1160 vp->v_object->resident_page_count > trigger)) {
1163 vn_finished_write(mp);
1164 goto next_iter_unlocked;
1166 counter_u64_add(recycles_count, 1);
1170 vn_finished_write(mp);
1174 kern_yield(PRI_USER);
1175 mtx_lock(&vnode_list_mtx);
1178 MPASS(vp->v_type != VMARKER);
1179 if (!should_yield())
1181 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1182 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1183 mtx_unlock(&vnode_list_mtx);
1184 kern_yield(PRI_USER);
1185 mtx_lock(&vnode_list_mtx);
1188 if (done == 0 && !retried) {
1189 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1190 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1197 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1198 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1200 "limit on vnode free requests per call to the vnlru_free routine");
1203 * Attempt to reduce the free list by the requested amount.
1206 vnlru_free_locked(int count, struct vfsops *mnt_op)
1208 struct vnode *vp, *mvp;
1212 mtx_assert(&vnode_list_mtx, MA_OWNED);
1213 if (count > max_vnlru_free)
1214 count = max_vnlru_free;
1216 mvp = vnode_list_free_marker;
1220 vp = TAILQ_NEXT(vp, v_vnodelist);
1221 if (__predict_false(vp == NULL)) {
1222 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1223 TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1226 if (__predict_false(vp->v_type == VMARKER))
1230 * Don't recycle if our vnode is from different type
1231 * of mount point. Note that mp is type-safe, the
1232 * check does not reach unmapped address even if
1233 * vnode is reclaimed.
1234 * Don't recycle if we can't get the interlock without
1237 if (vp->v_holdcnt > 0 || (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1238 mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
1241 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1242 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1243 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1249 mtx_unlock(&vnode_list_mtx);
1253 mtx_lock(&vnode_list_mtx);
1256 return (ocount - count);
1260 vnlru_free(int count, struct vfsops *mnt_op)
1263 mtx_lock(&vnode_list_mtx);
1264 vnlru_free_locked(count, mnt_op);
1265 mtx_unlock(&vnode_list_mtx);
1272 mtx_assert(&vnode_list_mtx, MA_OWNED);
1273 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1274 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1275 vlowat = vhiwat / 2;
1279 * Attempt to recycle vnodes in a context that is always safe to block.
1280 * Calling vlrurecycle() from the bowels of filesystem code has some
1281 * interesting deadlock problems.
1283 static struct proc *vnlruproc;
1284 static int vnlruproc_sig;
1287 * The main freevnodes counter is only updated when threads requeue their vnode
1288 * batches. CPUs are conditionally walked to compute a more accurate total.
1290 * Limit how much of a slop are we willing to tolerate. Note: the actual value
1291 * at any given moment can still exceed slop, but it should not be by significant
1292 * margin in practice.
1294 #define VNLRU_FREEVNODES_SLOP 128
1297 vnlru_read_freevnodes(void)
1303 mtx_assert(&vnode_list_mtx, MA_OWNED);
1304 if (freevnodes > freevnodes_old)
1305 slop = freevnodes - freevnodes_old;
1307 slop = freevnodes_old - freevnodes;
1308 if (slop < VNLRU_FREEVNODES_SLOP)
1309 return (freevnodes >= 0 ? freevnodes : 0);
1310 freevnodes_old = freevnodes;
1312 vd = DPCPU_ID_PTR((cpu), vd);
1313 freevnodes_old += vd->freevnodes;
1315 return (freevnodes_old >= 0 ? freevnodes_old : 0);
1319 vnlru_under(u_long rnumvnodes, u_long limit)
1321 u_long rfreevnodes, space;
1323 if (__predict_false(rnumvnodes > desiredvnodes))
1326 space = desiredvnodes - rnumvnodes;
1327 if (space < limit) {
1328 rfreevnodes = vnlru_read_freevnodes();
1329 if (rfreevnodes > wantfreevnodes)
1330 space += rfreevnodes - wantfreevnodes;
1332 return (space < limit);
1336 vnlru_under_unlocked(u_long rnumvnodes, u_long limit)
1338 long rfreevnodes, space;
1340 if (__predict_false(rnumvnodes > desiredvnodes))
1343 space = desiredvnodes - rnumvnodes;
1344 if (space < limit) {
1345 rfreevnodes = atomic_load_long(&freevnodes);
1346 if (rfreevnodes > wantfreevnodes)
1347 space += rfreevnodes - wantfreevnodes;
1349 return (space < limit);
1356 mtx_assert(&vnode_list_mtx, MA_OWNED);
1357 if (vnlruproc_sig == 0) {
1366 u_long rnumvnodes, rfreevnodes, target;
1367 unsigned long onumvnodes;
1368 int done, force, trigger, usevnodes;
1369 bool reclaim_nc_src, want_reread;
1371 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1372 SHUTDOWN_PRI_FIRST);
1375 want_reread = false;
1377 kproc_suspend_check(vnlruproc);
1378 mtx_lock(&vnode_list_mtx);
1379 rnumvnodes = atomic_load_long(&numvnodes);
1382 force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1383 want_reread = false;
1387 * If numvnodes is too large (due to desiredvnodes being
1388 * adjusted using its sysctl, or emergency growth), first
1389 * try to reduce it by discarding from the free list.
1391 if (rnumvnodes > desiredvnodes) {
1392 vnlru_free_locked(rnumvnodes - desiredvnodes, NULL);
1393 rnumvnodes = atomic_load_long(&numvnodes);
1396 * Sleep if the vnode cache is in a good state. This is
1397 * when it is not over-full and has space for about a 4%
1398 * or 9% expansion (by growing its size or inexcessively
1399 * reducing its free list). Otherwise, try to reclaim
1400 * space for a 10% expansion.
1402 if (vstir && force == 0) {
1406 if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1408 wakeup(&vnlruproc_sig);
1409 msleep(vnlruproc, &vnode_list_mtx,
1410 PVFS|PDROP, "vlruwt", hz);
1413 rfreevnodes = vnlru_read_freevnodes();
1415 onumvnodes = rnumvnodes;
1417 * Calculate parameters for recycling. These are the same
1418 * throughout the loop to give some semblance of fairness.
1419 * The trigger point is to avoid recycling vnodes with lots
1420 * of resident pages. We aren't trying to free memory; we
1421 * are trying to recycle or at least free vnodes.
1423 if (rnumvnodes <= desiredvnodes)
1424 usevnodes = rnumvnodes - rfreevnodes;
1426 usevnodes = rnumvnodes;
1430 * The trigger value is is chosen to give a conservatively
1431 * large value to ensure that it alone doesn't prevent
1432 * making progress. The value can easily be so large that
1433 * it is effectively infinite in some congested and
1434 * misconfigured cases, and this is necessary. Normally
1435 * it is about 8 to 100 (pages), which is quite large.
1437 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1439 trigger = vsmalltrigger;
1440 reclaim_nc_src = force >= 3;
1441 target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1442 target = target / 10 + 1;
1443 done = vlrureclaim(reclaim_nc_src, trigger, target);
1444 mtx_unlock(&vnode_list_mtx);
1445 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1446 uma_reclaim(UMA_RECLAIM_DRAIN);
1448 if (force == 0 || force == 1) {
1459 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1462 kern_yield(PRI_USER);
1467 static struct kproc_desc vnlru_kp = {
1472 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1476 * Routines having to do with the management of the vnode table.
1480 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1481 * before we actually vgone(). This function must be called with the vnode
1482 * held to prevent the vnode from being returned to the free list midway
1486 vtryrecycle(struct vnode *vp)
1490 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1491 VNASSERT(vp->v_holdcnt, vp,
1492 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1494 * This vnode may found and locked via some other list, if so we
1495 * can't recycle it yet.
1497 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1499 "%s: impossible to recycle, vp %p lock is already held",
1501 return (EWOULDBLOCK);
1504 * Don't recycle if its filesystem is being suspended.
1506 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1509 "%s: impossible to recycle, cannot start the write for %p",
1514 * If we got this far, we need to acquire the interlock and see if
1515 * anyone picked up this vnode from another list. If not, we will
1516 * mark it with DOOMED via vgonel() so that anyone who does find it
1517 * will skip over it.
1520 if (vp->v_usecount) {
1523 vn_finished_write(vnmp);
1525 "%s: impossible to recycle, %p is already referenced",
1529 if (!VN_IS_DOOMED(vp)) {
1530 counter_u64_add(recycles_free_count, 1);
1535 vn_finished_write(vnmp);
1540 * Allocate a new vnode.
1542 * The operation never returns an error. Returning an error was disabled
1543 * in r145385 (dated 2005) with the following comment:
1545 * XXX Not all VFS_VGET/ffs_vget callers check returns.
1547 * Given the age of this commit (almost 15 years at the time of writing this
1548 * comment) restoring the ability to fail requires a significant audit of
1551 * The routine can try to free a vnode or stall for up to 1 second waiting for
1552 * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1554 static u_long vn_alloc_cyclecount;
1556 static struct vnode * __noinline
1557 vn_alloc_hard(struct mount *mp)
1559 u_long rnumvnodes, rfreevnodes;
1561 mtx_lock(&vnode_list_mtx);
1562 rnumvnodes = atomic_load_long(&numvnodes);
1563 if (rnumvnodes + 1 < desiredvnodes) {
1564 vn_alloc_cyclecount = 0;
1567 rfreevnodes = vnlru_read_freevnodes();
1568 if (vn_alloc_cyclecount++ >= rfreevnodes) {
1569 vn_alloc_cyclecount = 0;
1573 * Grow the vnode cache if it will not be above its target max
1574 * after growing. Otherwise, if the free list is nonempty, try
1575 * to reclaim 1 item from it before growing the cache (possibly
1576 * above its target max if the reclamation failed or is delayed).
1577 * Otherwise, wait for some space. In all cases, schedule
1578 * vnlru_proc() if we are getting short of space. The watermarks
1579 * should be chosen so that we never wait or even reclaim from
1580 * the free list to below its target minimum.
1582 if (vnlru_free_locked(1, NULL) > 0)
1584 if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1586 * Wait for space for a new vnode.
1589 msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1590 if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1591 vnlru_read_freevnodes() > 1)
1592 vnlru_free_locked(1, NULL);
1595 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1596 if (vnlru_under(rnumvnodes, vlowat))
1598 mtx_unlock(&vnode_list_mtx);
1599 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1602 static struct vnode *
1603 vn_alloc(struct mount *mp)
1607 if (__predict_false(vn_alloc_cyclecount != 0))
1608 return (vn_alloc_hard(mp));
1609 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1610 if (__predict_false(vnlru_under_unlocked(rnumvnodes, vlowat))) {
1611 atomic_subtract_long(&numvnodes, 1);
1612 return (vn_alloc_hard(mp));
1615 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1619 vn_free(struct vnode *vp)
1622 atomic_subtract_long(&numvnodes, 1);
1623 uma_zfree_smr(vnode_zone, vp);
1627 * Return the next vnode from the free list.
1630 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1635 struct lock_object *lo;
1637 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1639 KASSERT(vops->registered,
1640 ("%s: not registered vector op %p\n", __func__, vops));
1643 if (td->td_vp_reserved != NULL) {
1644 vp = td->td_vp_reserved;
1645 td->td_vp_reserved = NULL;
1649 counter_u64_add(vnodes_created, 1);
1651 * Locks are given the generic name "vnode" when created.
1652 * Follow the historic practice of using the filesystem
1653 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1655 * Locks live in a witness group keyed on their name. Thus,
1656 * when a lock is renamed, it must also move from the witness
1657 * group of its old name to the witness group of its new name.
1659 * The change only needs to be made when the vnode moves
1660 * from one filesystem type to another. We ensure that each
1661 * filesystem use a single static name pointer for its tag so
1662 * that we can compare pointers rather than doing a strcmp().
1664 lo = &vp->v_vnlock->lock_object;
1666 if (lo->lo_name != tag) {
1670 WITNESS_DESTROY(lo);
1671 WITNESS_INIT(lo, tag);
1675 * By default, don't allow shared locks unless filesystems opt-in.
1677 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1679 * Finalize various vnode identity bits.
1681 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1682 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1683 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1686 v_init_counters(vp);
1687 vp->v_bufobj.bo_ops = &buf_ops_bio;
1689 if (mp == NULL && vops != &dead_vnodeops)
1690 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1694 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1695 mac_vnode_associate_singlelabel(mp, vp);
1698 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1699 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1700 vp->v_vflag |= VV_NOKNOTE;
1704 * For the filesystems which do not use vfs_hash_insert(),
1705 * still initialize v_hash to have vfs_hash_index() useful.
1706 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1709 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1716 getnewvnode_reserve(void)
1721 MPASS(td->td_vp_reserved == NULL);
1722 td->td_vp_reserved = vn_alloc(NULL);
1726 getnewvnode_drop_reserve(void)
1731 if (td->td_vp_reserved != NULL) {
1732 vn_free(td->td_vp_reserved);
1733 td->td_vp_reserved = NULL;
1738 freevnode(struct vnode *vp)
1743 * The vnode has been marked for destruction, so free it.
1745 * The vnode will be returned to the zone where it will
1746 * normally remain until it is needed for another vnode. We
1747 * need to cleanup (or verify that the cleanup has already
1748 * been done) any residual data left from its current use
1749 * so as not to contaminate the freshly allocated vnode.
1751 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1753 * Paired with vgone.
1755 vn_seqc_write_end_locked(vp);
1756 VNPASS(vp->v_seqc_users == 0, vp);
1759 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1760 VNPASS(vp->v_holdcnt == VHOLD_NO_SMR, vp);
1761 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1762 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1763 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1764 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1765 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1766 ("clean blk trie not empty"));
1767 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1768 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1769 ("dirty blk trie not empty"));
1770 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1771 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1772 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1773 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1774 ("Dangling rangelock waiters"));
1777 mac_vnode_destroy(vp);
1779 if (vp->v_pollinfo != NULL) {
1780 destroy_vpollinfo(vp->v_pollinfo);
1781 vp->v_pollinfo = NULL;
1784 /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
1787 vp->v_mountedhere = NULL;
1790 vp->v_fifoinfo = NULL;
1791 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
1800 * Delete from old mount point vnode list, if on one.
1803 delmntque(struct vnode *vp)
1807 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
1816 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1817 ("bad mount point vnode list size"));
1818 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1819 mp->mnt_nvnodelistsize--;
1825 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1829 vp->v_op = &dead_vnodeops;
1835 * Insert into list of vnodes for the new mount point, if available.
1838 insmntque1(struct vnode *vp, struct mount *mp,
1839 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1842 KASSERT(vp->v_mount == NULL,
1843 ("insmntque: vnode already on per mount vnode list"));
1844 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1845 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1848 * We acquire the vnode interlock early to ensure that the
1849 * vnode cannot be recycled by another process releasing a
1850 * holdcnt on it before we get it on both the vnode list
1851 * and the active vnode list. The mount mutex protects only
1852 * manipulation of the vnode list and the vnode freelist
1853 * mutex protects only manipulation of the active vnode list.
1854 * Hence the need to hold the vnode interlock throughout.
1858 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1859 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1860 mp->mnt_nvnodelistsize == 0)) &&
1861 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1870 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1871 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1872 ("neg mount point vnode list size"));
1873 mp->mnt_nvnodelistsize++;
1880 insmntque(struct vnode *vp, struct mount *mp)
1883 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1887 * Flush out and invalidate all buffers associated with a bufobj
1888 * Called with the underlying object locked.
1891 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1896 if (flags & V_SAVE) {
1897 error = bufobj_wwait(bo, slpflag, slptimeo);
1902 if (bo->bo_dirty.bv_cnt > 0) {
1904 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1907 * XXX We could save a lock/unlock if this was only
1908 * enabled under INVARIANTS
1911 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1912 panic("vinvalbuf: dirty bufs");
1916 * If you alter this loop please notice that interlock is dropped and
1917 * reacquired in flushbuflist. Special care is needed to ensure that
1918 * no race conditions occur from this.
1921 error = flushbuflist(&bo->bo_clean,
1922 flags, bo, slpflag, slptimeo);
1923 if (error == 0 && !(flags & V_CLEANONLY))
1924 error = flushbuflist(&bo->bo_dirty,
1925 flags, bo, slpflag, slptimeo);
1926 if (error != 0 && error != EAGAIN) {
1930 } while (error != 0);
1933 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1934 * have write I/O in-progress but if there is a VM object then the
1935 * VM object can also have read-I/O in-progress.
1938 bufobj_wwait(bo, 0, 0);
1939 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
1941 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
1944 } while (bo->bo_numoutput > 0);
1948 * Destroy the copy in the VM cache, too.
1950 if (bo->bo_object != NULL &&
1951 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1952 VM_OBJECT_WLOCK(bo->bo_object);
1953 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1954 OBJPR_CLEANONLY : 0);
1955 VM_OBJECT_WUNLOCK(bo->bo_object);
1960 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1961 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1962 bo->bo_clean.bv_cnt > 0))
1963 panic("vinvalbuf: flush failed");
1964 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1965 bo->bo_dirty.bv_cnt > 0)
1966 panic("vinvalbuf: flush dirty failed");
1973 * Flush out and invalidate all buffers associated with a vnode.
1974 * Called with the underlying object locked.
1977 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1980 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1981 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1982 if (vp->v_object != NULL && vp->v_object->handle != vp)
1984 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1988 * Flush out buffers on the specified list.
1992 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1995 struct buf *bp, *nbp;
2000 ASSERT_BO_WLOCKED(bo);
2003 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2005 * If we are flushing both V_NORMAL and V_ALT buffers then
2006 * do not skip any buffers. If we are flushing only V_NORMAL
2007 * buffers then skip buffers marked as BX_ALTDATA. If we are
2008 * flushing only V_ALT buffers then skip buffers not marked
2011 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2012 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2013 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2017 lblkno = nbp->b_lblkno;
2018 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2021 error = BUF_TIMELOCK(bp,
2022 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2023 "flushbuf", slpflag, slptimeo);
2026 return (error != ENOLCK ? error : EAGAIN);
2028 KASSERT(bp->b_bufobj == bo,
2029 ("bp %p wrong b_bufobj %p should be %p",
2030 bp, bp->b_bufobj, bo));
2032 * XXX Since there are no node locks for NFS, I
2033 * believe there is a slight chance that a delayed
2034 * write will occur while sleeping just above, so
2037 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2040 bp->b_flags |= B_ASYNC;
2043 return (EAGAIN); /* XXX: why not loop ? */
2046 bp->b_flags |= (B_INVAL | B_RELBUF);
2047 bp->b_flags &= ~B_ASYNC;
2052 nbp = gbincore(bo, lblkno);
2053 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2055 break; /* nbp invalid */
2061 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2067 ASSERT_BO_LOCKED(bo);
2069 for (lblkno = startn;;) {
2071 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2072 if (bp == NULL || bp->b_lblkno >= endn ||
2073 bp->b_lblkno < startn)
2075 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2076 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2079 if (error == ENOLCK)
2083 KASSERT(bp->b_bufobj == bo,
2084 ("bp %p wrong b_bufobj %p should be %p",
2085 bp, bp->b_bufobj, bo));
2086 lblkno = bp->b_lblkno + 1;
2087 if ((bp->b_flags & B_MANAGED) == 0)
2089 bp->b_flags |= B_RELBUF;
2091 * In the VMIO case, use the B_NOREUSE flag to hint that the
2092 * pages backing each buffer in the range are unlikely to be
2093 * reused. Dirty buffers will have the hint applied once
2094 * they've been written.
2096 if ((bp->b_flags & B_VMIO) != 0)
2097 bp->b_flags |= B_NOREUSE;
2105 * Truncate a file's buffer and pages to a specified length. This
2106 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2110 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2112 struct buf *bp, *nbp;
2116 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2117 vp, blksize, (uintmax_t)length);
2120 * Round up to the *next* lbn.
2122 startlbn = howmany(length, blksize);
2124 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2130 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2135 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2136 if (bp->b_lblkno > 0)
2139 * Since we hold the vnode lock this should only
2140 * fail if we're racing with the buf daemon.
2143 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2144 BO_LOCKPTR(bo)) == ENOLCK)
2145 goto restart_unlocked;
2147 VNASSERT((bp->b_flags & B_DELWRI), vp,
2148 ("buf(%p) on dirty queue without DELWRI", bp));
2157 bufobj_wwait(bo, 0, 0);
2159 vnode_pager_setsize(vp, length);
2165 * Invalidate the cached pages of a file's buffer within the range of block
2166 * numbers [startlbn, endlbn).
2169 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2175 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2177 start = blksize * startlbn;
2178 end = blksize * endlbn;
2182 MPASS(blksize == bo->bo_bsize);
2184 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2188 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2192 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2193 daddr_t startlbn, daddr_t endlbn)
2195 struct buf *bp, *nbp;
2198 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2199 ASSERT_BO_LOCKED(bo);
2203 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2204 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2207 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2208 BO_LOCKPTR(bo)) == ENOLCK) {
2214 bp->b_flags |= B_INVAL | B_RELBUF;
2215 bp->b_flags &= ~B_ASYNC;
2221 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2223 (nbp->b_flags & B_DELWRI) != 0))
2227 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2228 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2231 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2232 BO_LOCKPTR(bo)) == ENOLCK) {
2237 bp->b_flags |= B_INVAL | B_RELBUF;
2238 bp->b_flags &= ~B_ASYNC;
2244 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2245 (nbp->b_vp != vp) ||
2246 (nbp->b_flags & B_DELWRI) == 0))
2254 buf_vlist_remove(struct buf *bp)
2259 flags = bp->b_xflags;
2261 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2262 ASSERT_BO_WLOCKED(bp->b_bufobj);
2263 KASSERT((flags & (BX_VNDIRTY | BX_VNCLEAN)) != 0 &&
2264 (flags & (BX_VNDIRTY | BX_VNCLEAN)) != (BX_VNDIRTY | BX_VNCLEAN),
2265 ("%s: buffer %p has invalid queue state", __func__, bp));
2267 if ((flags & BX_VNDIRTY) != 0)
2268 bv = &bp->b_bufobj->bo_dirty;
2270 bv = &bp->b_bufobj->bo_clean;
2271 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2272 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2274 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2278 * Add the buffer to the sorted clean or dirty block list.
2280 * NOTE: xflags is passed as a constant, optimizing this inline function!
2283 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2289 ASSERT_BO_WLOCKED(bo);
2290 KASSERT((bo->bo_flag & BO_NOBUFS) == 0,
2291 ("buf_vlist_add: bo %p does not allow bufs", bo));
2292 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2293 ("dead bo %p", bo));
2294 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2295 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2296 bp->b_xflags |= xflags;
2297 if (xflags & BX_VNDIRTY)
2303 * Keep the list ordered. Optimize empty list insertion. Assume
2304 * we tend to grow at the tail so lookup_le should usually be cheaper
2307 if (bv->bv_cnt == 0 ||
2308 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2309 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2310 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2311 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2313 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2314 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2316 panic("buf_vlist_add: Preallocated nodes insufficient.");
2321 * Look up a buffer using the buffer tries.
2324 gbincore(struct bufobj *bo, daddr_t lblkno)
2328 ASSERT_BO_LOCKED(bo);
2329 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2332 return (BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno));
2336 * Look up a buf using the buffer tries, without the bufobj lock. This relies
2337 * on SMR for safe lookup, and bufs being in a no-free zone to provide type
2338 * stability of the result. Like other lockless lookups, the found buf may
2339 * already be invalid by the time this function returns.
2342 gbincore_unlocked(struct bufobj *bo, daddr_t lblkno)
2346 ASSERT_BO_UNLOCKED(bo);
2347 bp = BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_clean.bv_root, lblkno);
2350 return (BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_dirty.bv_root, lblkno));
2354 * Associate a buffer with a vnode.
2357 bgetvp(struct vnode *vp, struct buf *bp)
2362 ASSERT_BO_WLOCKED(bo);
2363 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2365 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2366 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2367 ("bgetvp: bp already attached! %p", bp));
2373 * Insert onto list for new vnode.
2375 buf_vlist_add(bp, bo, BX_VNCLEAN);
2379 * Disassociate a buffer from a vnode.
2382 brelvp(struct buf *bp)
2387 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2388 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2391 * Delete from old vnode list, if on one.
2393 vp = bp->b_vp; /* XXX */
2396 buf_vlist_remove(bp);
2397 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2398 bo->bo_flag &= ~BO_ONWORKLST;
2399 mtx_lock(&sync_mtx);
2400 LIST_REMOVE(bo, bo_synclist);
2401 syncer_worklist_len--;
2402 mtx_unlock(&sync_mtx);
2405 bp->b_bufobj = NULL;
2411 * Add an item to the syncer work queue.
2414 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2418 ASSERT_BO_WLOCKED(bo);
2420 mtx_lock(&sync_mtx);
2421 if (bo->bo_flag & BO_ONWORKLST)
2422 LIST_REMOVE(bo, bo_synclist);
2424 bo->bo_flag |= BO_ONWORKLST;
2425 syncer_worklist_len++;
2428 if (delay > syncer_maxdelay - 2)
2429 delay = syncer_maxdelay - 2;
2430 slot = (syncer_delayno + delay) & syncer_mask;
2432 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2433 mtx_unlock(&sync_mtx);
2437 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2441 mtx_lock(&sync_mtx);
2442 len = syncer_worklist_len - sync_vnode_count;
2443 mtx_unlock(&sync_mtx);
2444 error = SYSCTL_OUT(req, &len, sizeof(len));
2448 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2449 CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2450 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2452 static struct proc *updateproc;
2453 static void sched_sync(void);
2454 static struct kproc_desc up_kp = {
2459 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2462 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2467 *bo = LIST_FIRST(slp);
2471 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2474 * We use vhold in case the vnode does not
2475 * successfully sync. vhold prevents the vnode from
2476 * going away when we unlock the sync_mtx so that
2477 * we can acquire the vnode interlock.
2480 mtx_unlock(&sync_mtx);
2482 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2484 mtx_lock(&sync_mtx);
2485 return (*bo == LIST_FIRST(slp));
2487 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2488 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2490 vn_finished_write(mp);
2492 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2494 * Put us back on the worklist. The worklist
2495 * routine will remove us from our current
2496 * position and then add us back in at a later
2499 vn_syncer_add_to_worklist(*bo, syncdelay);
2503 mtx_lock(&sync_mtx);
2507 static int first_printf = 1;
2510 * System filesystem synchronizer daemon.
2515 struct synclist *next, *slp;
2518 struct thread *td = curthread;
2520 int net_worklist_len;
2521 int syncer_final_iter;
2525 syncer_final_iter = 0;
2526 syncer_state = SYNCER_RUNNING;
2527 starttime = time_uptime;
2528 td->td_pflags |= TDP_NORUNNINGBUF;
2530 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2533 mtx_lock(&sync_mtx);
2535 if (syncer_state == SYNCER_FINAL_DELAY &&
2536 syncer_final_iter == 0) {
2537 mtx_unlock(&sync_mtx);
2538 kproc_suspend_check(td->td_proc);
2539 mtx_lock(&sync_mtx);
2541 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2542 if (syncer_state != SYNCER_RUNNING &&
2543 starttime != time_uptime) {
2545 printf("\nSyncing disks, vnodes remaining... ");
2548 printf("%d ", net_worklist_len);
2550 starttime = time_uptime;
2553 * Push files whose dirty time has expired. Be careful
2554 * of interrupt race on slp queue.
2556 * Skip over empty worklist slots when shutting down.
2559 slp = &syncer_workitem_pending[syncer_delayno];
2560 syncer_delayno += 1;
2561 if (syncer_delayno == syncer_maxdelay)
2563 next = &syncer_workitem_pending[syncer_delayno];
2565 * If the worklist has wrapped since the
2566 * it was emptied of all but syncer vnodes,
2567 * switch to the FINAL_DELAY state and run
2568 * for one more second.
2570 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2571 net_worklist_len == 0 &&
2572 last_work_seen == syncer_delayno) {
2573 syncer_state = SYNCER_FINAL_DELAY;
2574 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2576 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2577 syncer_worklist_len > 0);
2580 * Keep track of the last time there was anything
2581 * on the worklist other than syncer vnodes.
2582 * Return to the SHUTTING_DOWN state if any
2585 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2586 last_work_seen = syncer_delayno;
2587 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2588 syncer_state = SYNCER_SHUTTING_DOWN;
2589 while (!LIST_EMPTY(slp)) {
2590 error = sync_vnode(slp, &bo, td);
2592 LIST_REMOVE(bo, bo_synclist);
2593 LIST_INSERT_HEAD(next, bo, bo_synclist);
2597 if (first_printf == 0) {
2599 * Drop the sync mutex, because some watchdog
2600 * drivers need to sleep while patting
2602 mtx_unlock(&sync_mtx);
2603 wdog_kern_pat(WD_LASTVAL);
2604 mtx_lock(&sync_mtx);
2608 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2609 syncer_final_iter--;
2611 * The variable rushjob allows the kernel to speed up the
2612 * processing of the filesystem syncer process. A rushjob
2613 * value of N tells the filesystem syncer to process the next
2614 * N seconds worth of work on its queue ASAP. Currently rushjob
2615 * is used by the soft update code to speed up the filesystem
2616 * syncer process when the incore state is getting so far
2617 * ahead of the disk that the kernel memory pool is being
2618 * threatened with exhaustion.
2625 * Just sleep for a short period of time between
2626 * iterations when shutting down to allow some I/O
2629 * If it has taken us less than a second to process the
2630 * current work, then wait. Otherwise start right over
2631 * again. We can still lose time if any single round
2632 * takes more than two seconds, but it does not really
2633 * matter as we are just trying to generally pace the
2634 * filesystem activity.
2636 if (syncer_state != SYNCER_RUNNING ||
2637 time_uptime == starttime) {
2639 sched_prio(td, PPAUSE);
2642 if (syncer_state != SYNCER_RUNNING)
2643 cv_timedwait(&sync_wakeup, &sync_mtx,
2644 hz / SYNCER_SHUTDOWN_SPEEDUP);
2645 else if (time_uptime == starttime)
2646 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2651 * Request the syncer daemon to speed up its work.
2652 * We never push it to speed up more than half of its
2653 * normal turn time, otherwise it could take over the cpu.
2656 speedup_syncer(void)
2660 mtx_lock(&sync_mtx);
2661 if (rushjob < syncdelay / 2) {
2663 stat_rush_requests += 1;
2666 mtx_unlock(&sync_mtx);
2667 cv_broadcast(&sync_wakeup);
2672 * Tell the syncer to speed up its work and run though its work
2673 * list several times, then tell it to shut down.
2676 syncer_shutdown(void *arg, int howto)
2679 if (howto & RB_NOSYNC)
2681 mtx_lock(&sync_mtx);
2682 syncer_state = SYNCER_SHUTTING_DOWN;
2684 mtx_unlock(&sync_mtx);
2685 cv_broadcast(&sync_wakeup);
2686 kproc_shutdown(arg, howto);
2690 syncer_suspend(void)
2693 syncer_shutdown(updateproc, 0);
2700 mtx_lock(&sync_mtx);
2702 syncer_state = SYNCER_RUNNING;
2703 mtx_unlock(&sync_mtx);
2704 cv_broadcast(&sync_wakeup);
2705 kproc_resume(updateproc);
2709 * Move the buffer between the clean and dirty lists of its vnode.
2712 reassignbuf(struct buf *bp)
2724 KASSERT((bp->b_flags & B_PAGING) == 0,
2725 ("%s: cannot reassign paging buffer %p", __func__, bp));
2727 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2728 bp, bp->b_vp, bp->b_flags);
2731 buf_vlist_remove(bp);
2734 * If dirty, put on list of dirty buffers; otherwise insert onto list
2737 if (bp->b_flags & B_DELWRI) {
2738 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2739 switch (vp->v_type) {
2749 vn_syncer_add_to_worklist(bo, delay);
2751 buf_vlist_add(bp, bo, BX_VNDIRTY);
2753 buf_vlist_add(bp, bo, BX_VNCLEAN);
2755 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2756 mtx_lock(&sync_mtx);
2757 LIST_REMOVE(bo, bo_synclist);
2758 syncer_worklist_len--;
2759 mtx_unlock(&sync_mtx);
2760 bo->bo_flag &= ~BO_ONWORKLST;
2765 bp = TAILQ_FIRST(&bv->bv_hd);
2766 KASSERT(bp == NULL || bp->b_bufobj == bo,
2767 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2768 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2769 KASSERT(bp == NULL || bp->b_bufobj == bo,
2770 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2772 bp = TAILQ_FIRST(&bv->bv_hd);
2773 KASSERT(bp == NULL || bp->b_bufobj == bo,
2774 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2775 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2776 KASSERT(bp == NULL || bp->b_bufobj == bo,
2777 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2783 v_init_counters(struct vnode *vp)
2786 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2787 vp, ("%s called for an initialized vnode", __FUNCTION__));
2788 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2790 refcount_init(&vp->v_holdcnt, 1);
2791 refcount_init(&vp->v_usecount, 1);
2795 * Grab a particular vnode from the free list, increment its
2796 * reference count and lock it. VIRF_DOOMED is set if the vnode
2797 * is being destroyed. Only callers who specify LK_RETRY will
2798 * see doomed vnodes. If inactive processing was delayed in
2799 * vput try to do it here.
2801 * usecount is manipulated using atomics without holding any locks.
2803 * holdcnt can be manipulated using atomics without holding any locks,
2804 * except when transitioning 1<->0, in which case the interlock is held.
2806 * Consumers which don't guarantee liveness of the vnode can use SMR to
2807 * try to get a reference. Note this operation can fail since the vnode
2808 * may be awaiting getting freed by the time they get to it.
2811 vget_prep_smr(struct vnode *vp)
2815 VFS_SMR_ASSERT_ENTERED();
2817 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2829 vget_prep(struct vnode *vp)
2833 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2843 vget_abort(struct vnode *vp, enum vgetstate vs)
2854 __assert_unreachable();
2859 vget(struct vnode *vp, int flags, struct thread *td)
2863 MPASS(td == curthread);
2866 return (vget_finish(vp, flags, vs));
2870 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
2874 if ((flags & LK_INTERLOCK) != 0)
2875 ASSERT_VI_LOCKED(vp, __func__);
2877 ASSERT_VI_UNLOCKED(vp, __func__);
2878 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
2879 VNPASS(vp->v_holdcnt > 0, vp);
2880 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
2882 error = vn_lock(vp, flags);
2883 if (__predict_false(error != 0)) {
2885 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2890 vget_finish_ref(vp, vs);
2895 vget_finish_ref(struct vnode *vp, enum vgetstate vs)
2899 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
2900 VNPASS(vp->v_holdcnt > 0, vp);
2901 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
2903 if (vs == VGET_USECOUNT)
2907 * We hold the vnode. If the usecount is 0 it will be utilized to keep
2908 * the vnode around. Otherwise someone else lended their hold count and
2909 * we have to drop ours.
2911 old = atomic_fetchadd_int(&vp->v_usecount, 1);
2912 VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
2915 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2916 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2918 refcount_release(&vp->v_holdcnt);
2924 vref(struct vnode *vp)
2928 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2930 vget_finish_ref(vp, vs);
2934 vrefl(struct vnode *vp)
2937 ASSERT_VI_LOCKED(vp, __func__);
2938 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2943 vrefact(struct vnode *vp)
2946 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2948 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
2949 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
2951 refcount_acquire(&vp->v_usecount);
2956 vlazy(struct vnode *vp)
2960 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
2962 if ((vp->v_mflag & VMP_LAZYLIST) != 0)
2965 * We may get here for inactive routines after the vnode got doomed.
2967 if (VN_IS_DOOMED(vp))
2970 mtx_lock(&mp->mnt_listmtx);
2971 if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
2972 vp->v_mflag |= VMP_LAZYLIST;
2973 TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
2974 mp->mnt_lazyvnodelistsize++;
2976 mtx_unlock(&mp->mnt_listmtx);
2980 * This routine is only meant to be called from vgonel prior to dooming
2984 vunlazy_gone(struct vnode *vp)
2988 ASSERT_VOP_ELOCKED(vp, __func__);
2989 ASSERT_VI_LOCKED(vp, __func__);
2990 VNPASS(!VN_IS_DOOMED(vp), vp);
2992 if (vp->v_mflag & VMP_LAZYLIST) {
2994 mtx_lock(&mp->mnt_listmtx);
2995 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
2996 vp->v_mflag &= ~VMP_LAZYLIST;
2997 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
2998 mp->mnt_lazyvnodelistsize--;
2999 mtx_unlock(&mp->mnt_listmtx);
3004 vdefer_inactive(struct vnode *vp)
3007 ASSERT_VI_LOCKED(vp, __func__);
3008 VNASSERT(vp->v_holdcnt > 0, vp,
3009 ("%s: vnode without hold count", __func__));
3010 if (VN_IS_DOOMED(vp)) {
3014 if (vp->v_iflag & VI_DEFINACT) {
3015 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3019 if (vp->v_usecount > 0) {
3020 vp->v_iflag &= ~VI_OWEINACT;
3025 vp->v_iflag |= VI_DEFINACT;
3027 counter_u64_add(deferred_inact, 1);
3031 vdefer_inactive_unlocked(struct vnode *vp)
3035 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3039 vdefer_inactive(vp);
3042 enum vput_op { VRELE, VPUT, VUNREF };
3045 * Handle ->v_usecount transitioning to 0.
3047 * By releasing the last usecount we take ownership of the hold count which
3048 * provides liveness of the vnode, meaning we have to vdrop.
3050 * For all vnodes we may need to perform inactive processing. It requires an
3051 * exclusive lock on the vnode, while it is legal to call here with only a
3052 * shared lock (or no locks). If locking the vnode in an expected manner fails,
3053 * inactive processing gets deferred to the syncer.
3055 * XXX Some filesystems pass in an exclusively locked vnode and strongly depend
3056 * on the lock being held all the way until VOP_INACTIVE. This in particular
3057 * happens with UFS which adds half-constructed vnodes to the hash, where they
3058 * can be found by other code.
3061 vput_final(struct vnode *vp, enum vput_op func)
3066 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3067 VNPASS(vp->v_holdcnt > 0, vp);
3072 * By the time we got here someone else might have transitioned
3073 * the count back to > 0.
3075 if (vp->v_usecount > 0)
3079 * If the vnode is doomed vgone already performed inactive processing
3082 if (VN_IS_DOOMED(vp))
3085 if (__predict_true(VOP_NEED_INACTIVE(vp) == 0))
3088 if (vp->v_iflag & VI_DOINGINACT)
3092 * Locking operations here will drop the interlock and possibly the
3093 * vnode lock, opening a window where the vnode can get doomed all the
3094 * while ->v_usecount is 0. Set VI_OWEINACT to let vgone know to
3097 vp->v_iflag |= VI_OWEINACT;
3098 want_unlock = false;
3102 switch (VOP_ISLOCKED(vp)) {
3108 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3113 * The lock has at least one sharer, but we have no way
3114 * to conclude whether this is us. Play it safe and
3123 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3124 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3130 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3131 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3142 vdefer_inactive(vp);
3152 * Decrement ->v_usecount for a vnode.
3154 * Releasing the last use count requires additional processing, see vput_final
3155 * above for details.
3157 * Comment above each variant denotes lock state on entry and exit.
3162 * out: same as passed in
3165 vrele(struct vnode *vp)
3168 ASSERT_VI_UNLOCKED(vp, __func__);
3169 if (!refcount_release(&vp->v_usecount))
3171 vput_final(vp, VRELE);
3179 vput(struct vnode *vp)
3182 ASSERT_VOP_LOCKED(vp, __func__);
3183 ASSERT_VI_UNLOCKED(vp, __func__);
3184 if (!refcount_release(&vp->v_usecount)) {
3188 vput_final(vp, VPUT);
3196 vunref(struct vnode *vp)
3199 ASSERT_VOP_LOCKED(vp, __func__);
3200 ASSERT_VI_UNLOCKED(vp, __func__);
3201 if (!refcount_release(&vp->v_usecount))
3203 vput_final(vp, VUNREF);
3207 vhold(struct vnode *vp)
3212 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3213 old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3214 VNASSERT(old >= 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3215 ("%s: wrong hold count %d", __func__, old));
3225 vholdl(struct vnode *vp)
3228 ASSERT_VI_LOCKED(vp, __func__);
3229 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3234 vholdnz(struct vnode *vp)
3237 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3239 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3240 VNASSERT(old > 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3241 ("%s: wrong hold count %d", __func__, old));
3243 atomic_add_int(&vp->v_holdcnt, 1);
3248 * Grab a hold count unless the vnode is freed.
3250 * Only use this routine if vfs smr is the only protection you have against
3251 * freeing the vnode.
3253 * The code loops trying to add a hold count as long as the VHOLD_NO_SMR flag
3254 * is not set. After the flag is set the vnode becomes immutable to anyone but
3255 * the thread which managed to set the flag.
3257 * It may be tempting to replace the loop with:
3258 * count = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3259 * if (count & VHOLD_NO_SMR) {
3260 * backpedal and error out;
3263 * However, while this is more performant, it hinders debugging by eliminating
3264 * the previously mentioned invariant.
3267 vhold_smr(struct vnode *vp)
3271 VFS_SMR_ASSERT_ENTERED();
3273 count = atomic_load_int(&vp->v_holdcnt);
3275 if (count & VHOLD_NO_SMR) {
3276 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3277 ("non-zero hold count with flags %d\n", count));
3281 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3282 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1))
3287 static void __noinline
3288 vdbatch_process(struct vdbatch *vd)
3293 mtx_assert(&vd->lock, MA_OWNED);
3294 MPASS(curthread->td_pinned > 0);
3295 MPASS(vd->index == VDBATCH_SIZE);
3297 mtx_lock(&vnode_list_mtx);
3299 freevnodes += vd->freevnodes;
3300 for (i = 0; i < VDBATCH_SIZE; i++) {
3302 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3303 TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3304 MPASS(vp->v_dbatchcpu != NOCPU);
3305 vp->v_dbatchcpu = NOCPU;
3307 mtx_unlock(&vnode_list_mtx);
3309 bzero(vd->tab, sizeof(vd->tab));
3315 vdbatch_enqueue(struct vnode *vp)
3319 ASSERT_VI_LOCKED(vp, __func__);
3320 VNASSERT(!VN_IS_DOOMED(vp), vp,
3321 ("%s: deferring requeue of a doomed vnode", __func__));
3326 if (vp->v_dbatchcpu != NOCPU) {
3334 mtx_lock(&vd->lock);
3335 MPASS(vd->index < VDBATCH_SIZE);
3336 MPASS(vd->tab[vd->index] == NULL);
3338 * A hack: we depend on being pinned so that we know what to put in
3341 vp->v_dbatchcpu = curcpu;
3342 vd->tab[vd->index] = vp;
3345 if (vd->index == VDBATCH_SIZE)
3346 vdbatch_process(vd);
3347 mtx_unlock(&vd->lock);
3352 * This routine must only be called for vnodes which are about to be
3353 * deallocated. Supporting dequeue for arbitrary vndoes would require
3354 * validating that the locked batch matches.
3357 vdbatch_dequeue(struct vnode *vp)
3363 VNASSERT(vp->v_type == VBAD || vp->v_type == VNON, vp,
3364 ("%s: called for a used vnode\n", __func__));
3366 cpu = vp->v_dbatchcpu;
3370 vd = DPCPU_ID_PTR(cpu, vd);
3371 mtx_lock(&vd->lock);
3372 for (i = 0; i < vd->index; i++) {
3373 if (vd->tab[i] != vp)
3375 vp->v_dbatchcpu = NOCPU;
3377 vd->tab[i] = vd->tab[vd->index];
3378 vd->tab[vd->index] = NULL;
3381 mtx_unlock(&vd->lock);
3383 * Either we dequeued the vnode above or the target CPU beat us to it.
3385 MPASS(vp->v_dbatchcpu == NOCPU);
3389 * Drop the hold count of the vnode. If this is the last reference to
3390 * the vnode we place it on the free list unless it has been vgone'd
3391 * (marked VIRF_DOOMED) in which case we will free it.
3393 * Because the vnode vm object keeps a hold reference on the vnode if
3394 * there is at least one resident non-cached page, the vnode cannot
3395 * leave the active list without the page cleanup done.
3398 vdrop_deactivate(struct vnode *vp)
3402 ASSERT_VI_LOCKED(vp, __func__);
3404 * Mark a vnode as free: remove it from its active list
3405 * and put it up for recycling on the freelist.
3407 VNASSERT(!VN_IS_DOOMED(vp), vp,
3408 ("vdrop: returning doomed vnode"));
3409 VNASSERT(vp->v_op != NULL, vp,
3410 ("vdrop: vnode already reclaimed."));
3411 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
3412 ("vnode with VI_OWEINACT set"));
3413 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp,
3414 ("vnode with VI_DEFINACT set"));
3415 if (vp->v_mflag & VMP_LAZYLIST) {
3417 mtx_lock(&mp->mnt_listmtx);
3418 VNASSERT(vp->v_mflag & VMP_LAZYLIST, vp, ("lost VMP_LAZYLIST"));
3420 * Don't remove the vnode from the lazy list if another thread
3421 * has increased the hold count. It may have re-enqueued the
3422 * vnode to the lazy list and is now responsible for its
3425 if (vp->v_holdcnt == 0) {
3426 vp->v_mflag &= ~VMP_LAZYLIST;
3427 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3428 mp->mnt_lazyvnodelistsize--;
3430 mtx_unlock(&mp->mnt_listmtx);
3432 vdbatch_enqueue(vp);
3436 vdrop(struct vnode *vp)
3439 ASSERT_VI_UNLOCKED(vp, __func__);
3440 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3441 if (refcount_release_if_not_last(&vp->v_holdcnt))
3448 vdropl(struct vnode *vp)
3451 ASSERT_VI_LOCKED(vp, __func__);
3452 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3453 if (!refcount_release(&vp->v_holdcnt)) {
3457 if (!VN_IS_DOOMED(vp)) {
3458 vdrop_deactivate(vp);
3460 * Also unlocks the interlock. We can't assert on it as we
3461 * released our hold and by now the vnode might have been
3467 * Set the VHOLD_NO_SMR flag.
3469 * We may be racing against vhold_smr. If they win we can just pretend
3470 * we never got this far, they will vdrop later.
3472 if (!atomic_cmpset_int(&vp->v_holdcnt, 0, VHOLD_NO_SMR)) {
3475 * We lost the aforementioned race. Any subsequent access is
3476 * invalid as they might have managed to vdropl on their own.
3484 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3485 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3488 vinactivef(struct vnode *vp)
3490 struct vm_object *obj;
3492 ASSERT_VOP_ELOCKED(vp, "vinactive");
3493 ASSERT_VI_LOCKED(vp, "vinactive");
3494 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3495 ("vinactive: recursed on VI_DOINGINACT"));
3496 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3497 vp->v_iflag |= VI_DOINGINACT;
3498 vp->v_iflag &= ~VI_OWEINACT;
3501 * Before moving off the active list, we must be sure that any
3502 * modified pages are converted into the vnode's dirty
3503 * buffers, since these will no longer be checked once the
3504 * vnode is on the inactive list.
3506 * The write-out of the dirty pages is asynchronous. At the
3507 * point that VOP_INACTIVE() is called, there could still be
3508 * pending I/O and dirty pages in the object.
3510 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3511 vm_object_mightbedirty(obj)) {
3512 VM_OBJECT_WLOCK(obj);
3513 vm_object_page_clean(obj, 0, 0, 0);
3514 VM_OBJECT_WUNLOCK(obj);
3516 VOP_INACTIVE(vp, curthread);
3518 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3519 ("vinactive: lost VI_DOINGINACT"));
3520 vp->v_iflag &= ~VI_DOINGINACT;
3524 vinactive(struct vnode *vp)
3527 ASSERT_VOP_ELOCKED(vp, "vinactive");
3528 ASSERT_VI_LOCKED(vp, "vinactive");
3529 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3531 if ((vp->v_iflag & VI_OWEINACT) == 0)
3533 if (vp->v_iflag & VI_DOINGINACT)
3535 if (vp->v_usecount > 0) {
3536 vp->v_iflag &= ~VI_OWEINACT;
3543 * Remove any vnodes in the vnode table belonging to mount point mp.
3545 * If FORCECLOSE is not specified, there should not be any active ones,
3546 * return error if any are found (nb: this is a user error, not a
3547 * system error). If FORCECLOSE is specified, detach any active vnodes
3550 * If WRITECLOSE is set, only flush out regular file vnodes open for
3553 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3555 * `rootrefs' specifies the base reference count for the root vnode
3556 * of this filesystem. The root vnode is considered busy if its
3557 * v_usecount exceeds this value. On a successful return, vflush(, td)
3558 * will call vrele() on the root vnode exactly rootrefs times.
3559 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3563 static int busyprt = 0; /* print out busy vnodes */
3564 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3568 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3570 struct vnode *vp, *mvp, *rootvp = NULL;
3572 int busy = 0, error;
3574 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3577 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3578 ("vflush: bad args"));
3580 * Get the filesystem root vnode. We can vput() it
3581 * immediately, since with rootrefs > 0, it won't go away.
3583 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3584 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3591 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3593 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3596 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3600 * Skip over a vnodes marked VV_SYSTEM.
3602 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3608 * If WRITECLOSE is set, flush out unlinked but still open
3609 * files (even if open only for reading) and regular file
3610 * vnodes open for writing.
3612 if (flags & WRITECLOSE) {
3613 if (vp->v_object != NULL) {
3614 VM_OBJECT_WLOCK(vp->v_object);
3615 vm_object_page_clean(vp->v_object, 0, 0, 0);
3616 VM_OBJECT_WUNLOCK(vp->v_object);
3618 error = VOP_FSYNC(vp, MNT_WAIT, td);
3622 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3625 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3628 if ((vp->v_type == VNON ||
3629 (error == 0 && vattr.va_nlink > 0)) &&
3630 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3638 * With v_usecount == 0, all we need to do is clear out the
3639 * vnode data structures and we are done.
3641 * If FORCECLOSE is set, forcibly close the vnode.
3643 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3649 vn_printf(vp, "vflush: busy vnode ");
3655 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3657 * If just the root vnode is busy, and if its refcount
3658 * is equal to `rootrefs', then go ahead and kill it.
3661 KASSERT(busy > 0, ("vflush: not busy"));
3662 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3663 ("vflush: usecount %d < rootrefs %d",
3664 rootvp->v_usecount, rootrefs));
3665 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3666 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3674 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3678 for (; rootrefs > 0; rootrefs--)
3684 * Recycle an unused vnode to the front of the free list.
3687 vrecycle(struct vnode *vp)
3692 recycled = vrecyclel(vp);
3698 * vrecycle, with the vp interlock held.
3701 vrecyclel(struct vnode *vp)
3705 ASSERT_VOP_ELOCKED(vp, __func__);
3706 ASSERT_VI_LOCKED(vp, __func__);
3707 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3709 if (vp->v_usecount == 0) {
3717 * Eliminate all activity associated with a vnode
3718 * in preparation for reuse.
3721 vgone(struct vnode *vp)
3729 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3730 struct vnode *lowervp __unused)
3735 * Notify upper mounts about reclaimed or unlinked vnode.
3738 vfs_notify_upper(struct vnode *vp, int event)
3740 static struct vfsops vgonel_vfsops = {
3741 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3742 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3744 struct mount *mp, *ump, *mmp;
3749 if (TAILQ_EMPTY(&mp->mnt_uppers))
3752 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3753 mmp->mnt_op = &vgonel_vfsops;
3754 mmp->mnt_kern_flag |= MNTK_MARKER;
3756 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3757 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3758 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3759 ump = TAILQ_NEXT(ump, mnt_upper_link);
3762 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3765 case VFS_NOTIFY_UPPER_RECLAIM:
3766 VFS_RECLAIM_LOWERVP(ump, vp);
3768 case VFS_NOTIFY_UPPER_UNLINK:
3769 VFS_UNLINK_LOWERVP(ump, vp);
3772 KASSERT(0, ("invalid event %d", event));
3776 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3777 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3780 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3781 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3782 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3783 wakeup(&mp->mnt_uppers);
3789 * vgone, with the vp interlock held.
3792 vgonel(struct vnode *vp)
3797 bool active, oweinact;
3799 ASSERT_VOP_ELOCKED(vp, "vgonel");
3800 ASSERT_VI_LOCKED(vp, "vgonel");
3801 VNASSERT(vp->v_holdcnt, vp,
3802 ("vgonel: vp %p has no reference.", vp));
3803 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3807 * Don't vgonel if we're already doomed.
3809 if (vp->v_irflag & VIRF_DOOMED)
3812 * Paired with freevnode.
3814 vn_seqc_write_begin_locked(vp);
3816 vp->v_irflag |= VIRF_DOOMED;
3819 * Check to see if the vnode is in use. If so, we have to call
3820 * VOP_CLOSE() and VOP_INACTIVE().
3822 active = vp->v_usecount > 0;
3823 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
3825 * If we need to do inactive VI_OWEINACT will be set.
3827 if (vp->v_iflag & VI_DEFINACT) {
3828 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3829 vp->v_iflag &= ~VI_DEFINACT;
3832 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
3835 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
3838 * If purging an active vnode, it must be closed and
3839 * deactivated before being reclaimed.
3842 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
3843 if (oweinact || active) {
3848 if (vp->v_type == VSOCK)
3849 vfs_unp_reclaim(vp);
3852 * Clean out any buffers associated with the vnode.
3853 * If the flush fails, just toss the buffers.
3856 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
3857 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
3858 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
3859 while (vinvalbuf(vp, 0, 0, 0) != 0)
3863 BO_LOCK(&vp->v_bufobj);
3864 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
3865 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
3866 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
3867 vp->v_bufobj.bo_clean.bv_cnt == 0,
3868 ("vp %p bufobj not invalidated", vp));
3871 * For VMIO bufobj, BO_DEAD is set later, or in
3872 * vm_object_terminate() after the object's page queue is
3875 object = vp->v_bufobj.bo_object;
3877 vp->v_bufobj.bo_flag |= BO_DEAD;
3878 BO_UNLOCK(&vp->v_bufobj);
3881 * Handle the VM part. Tmpfs handles v_object on its own (the
3882 * OBJT_VNODE check). Nullfs or other bypassing filesystems
3883 * should not touch the object borrowed from the lower vnode
3884 * (the handle check).
3886 if (object != NULL && object->type == OBJT_VNODE &&
3887 object->handle == vp)
3888 vnode_destroy_vobject(vp);
3891 * Reclaim the vnode.
3893 if (VOP_RECLAIM(vp, td))
3894 panic("vgone: cannot reclaim");
3896 vn_finished_secondary_write(mp);
3897 VNASSERT(vp->v_object == NULL, vp,
3898 ("vop_reclaim left v_object vp=%p", vp));
3900 * Clear the advisory locks and wake up waiting threads.
3902 (void)VOP_ADVLOCKPURGE(vp);
3905 * Delete from old mount point vnode list.
3908 cache_purge_vgone(vp);
3910 * Done with purge, reset to the standard lock and invalidate
3914 vp->v_vnlock = &vp->v_lock;
3915 vp->v_op = &dead_vnodeops;
3920 * Print out a description of a vnode.
3922 static const char * const typename[] =
3923 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
3926 _Static_assert((VHOLD_ALL_FLAGS & ~VHOLD_NO_SMR) == 0,
3927 "new hold count flag not added to vn_printf");
3930 vn_printf(struct vnode *vp, const char *fmt, ...)
3933 char buf[256], buf2[16];
3940 printf("%p: ", (void *)vp);
3941 printf("type %s\n", typename[vp->v_type]);
3942 holdcnt = atomic_load_int(&vp->v_holdcnt);
3943 printf(" usecount %d, writecount %d, refcount %d seqc users %d",
3944 vp->v_usecount, vp->v_writecount, holdcnt & ~VHOLD_ALL_FLAGS,
3946 switch (vp->v_type) {
3948 printf(" mountedhere %p\n", vp->v_mountedhere);
3951 printf(" rdev %p\n", vp->v_rdev);
3954 printf(" socket %p\n", vp->v_unpcb);
3957 printf(" fifoinfo %p\n", vp->v_fifoinfo);
3965 if (holdcnt & VHOLD_NO_SMR)
3966 strlcat(buf, "|VHOLD_NO_SMR", sizeof(buf));
3967 printf(" hold count flags (%s)\n", buf + 1);
3971 if (vp->v_irflag & VIRF_DOOMED)
3972 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
3973 flags = vp->v_irflag & ~(VIRF_DOOMED);
3975 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
3976 strlcat(buf, buf2, sizeof(buf));
3978 if (vp->v_vflag & VV_ROOT)
3979 strlcat(buf, "|VV_ROOT", sizeof(buf));
3980 if (vp->v_vflag & VV_ISTTY)
3981 strlcat(buf, "|VV_ISTTY", sizeof(buf));
3982 if (vp->v_vflag & VV_NOSYNC)
3983 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
3984 if (vp->v_vflag & VV_ETERNALDEV)
3985 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
3986 if (vp->v_vflag & VV_CACHEDLABEL)
3987 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
3988 if (vp->v_vflag & VV_VMSIZEVNLOCK)
3989 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
3990 if (vp->v_vflag & VV_COPYONWRITE)
3991 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
3992 if (vp->v_vflag & VV_SYSTEM)
3993 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
3994 if (vp->v_vflag & VV_PROCDEP)
3995 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
3996 if (vp->v_vflag & VV_NOKNOTE)
3997 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
3998 if (vp->v_vflag & VV_DELETED)
3999 strlcat(buf, "|VV_DELETED", sizeof(buf));
4000 if (vp->v_vflag & VV_MD)
4001 strlcat(buf, "|VV_MD", sizeof(buf));
4002 if (vp->v_vflag & VV_FORCEINSMQ)
4003 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
4004 if (vp->v_vflag & VV_READLINK)
4005 strlcat(buf, "|VV_READLINK", sizeof(buf));
4006 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4007 VV_CACHEDLABEL | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
4008 VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
4010 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4011 strlcat(buf, buf2, sizeof(buf));
4013 if (vp->v_iflag & VI_TEXT_REF)
4014 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
4015 if (vp->v_iflag & VI_MOUNT)
4016 strlcat(buf, "|VI_MOUNT", sizeof(buf));
4017 if (vp->v_iflag & VI_DOINGINACT)
4018 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4019 if (vp->v_iflag & VI_OWEINACT)
4020 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4021 if (vp->v_iflag & VI_DEFINACT)
4022 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4023 flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOINGINACT |
4024 VI_OWEINACT | VI_DEFINACT);
4026 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4027 strlcat(buf, buf2, sizeof(buf));
4029 if (vp->v_mflag & VMP_LAZYLIST)
4030 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4031 flags = vp->v_mflag & ~(VMP_LAZYLIST);
4033 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4034 strlcat(buf, buf2, sizeof(buf));
4036 printf(" flags (%s)\n", buf + 1);
4037 if (mtx_owned(VI_MTX(vp)))
4038 printf(" VI_LOCKed");
4039 if (vp->v_object != NULL)
4040 printf(" v_object %p ref %d pages %d "
4041 "cleanbuf %d dirtybuf %d\n",
4042 vp->v_object, vp->v_object->ref_count,
4043 vp->v_object->resident_page_count,
4044 vp->v_bufobj.bo_clean.bv_cnt,
4045 vp->v_bufobj.bo_dirty.bv_cnt);
4047 lockmgr_printinfo(vp->v_vnlock);
4048 if (vp->v_data != NULL)
4054 * List all of the locked vnodes in the system.
4055 * Called when debugging the kernel.
4057 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
4063 * Note: because this is DDB, we can't obey the locking semantics
4064 * for these structures, which means we could catch an inconsistent
4065 * state and dereference a nasty pointer. Not much to be done
4068 db_printf("Locked vnodes\n");
4069 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4070 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4071 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4072 vn_printf(vp, "vnode ");
4078 * Show details about the given vnode.
4080 DB_SHOW_COMMAND(vnode, db_show_vnode)
4086 vp = (struct vnode *)addr;
4087 vn_printf(vp, "vnode ");
4091 * Show details about the given mount point.
4093 DB_SHOW_COMMAND(mount, db_show_mount)
4104 /* No address given, print short info about all mount points. */
4105 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4106 db_printf("%p %s on %s (%s)\n", mp,
4107 mp->mnt_stat.f_mntfromname,
4108 mp->mnt_stat.f_mntonname,
4109 mp->mnt_stat.f_fstypename);
4113 db_printf("\nMore info: show mount <addr>\n");
4117 mp = (struct mount *)addr;
4118 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4119 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4122 mflags = mp->mnt_flag;
4123 #define MNT_FLAG(flag) do { \
4124 if (mflags & (flag)) { \
4125 if (buf[0] != '\0') \
4126 strlcat(buf, ", ", sizeof(buf)); \
4127 strlcat(buf, (#flag) + 4, sizeof(buf)); \
4128 mflags &= ~(flag); \
4131 MNT_FLAG(MNT_RDONLY);
4132 MNT_FLAG(MNT_SYNCHRONOUS);
4133 MNT_FLAG(MNT_NOEXEC);
4134 MNT_FLAG(MNT_NOSUID);
4135 MNT_FLAG(MNT_NFS4ACLS);
4136 MNT_FLAG(MNT_UNION);
4137 MNT_FLAG(MNT_ASYNC);
4138 MNT_FLAG(MNT_SUIDDIR);
4139 MNT_FLAG(MNT_SOFTDEP);
4140 MNT_FLAG(MNT_NOSYMFOLLOW);
4141 MNT_FLAG(MNT_GJOURNAL);
4142 MNT_FLAG(MNT_MULTILABEL);
4144 MNT_FLAG(MNT_NOATIME);
4145 MNT_FLAG(MNT_NOCLUSTERR);
4146 MNT_FLAG(MNT_NOCLUSTERW);
4148 MNT_FLAG(MNT_EXRDONLY);
4149 MNT_FLAG(MNT_EXPORTED);
4150 MNT_FLAG(MNT_DEFEXPORTED);
4151 MNT_FLAG(MNT_EXPORTANON);
4152 MNT_FLAG(MNT_EXKERB);
4153 MNT_FLAG(MNT_EXPUBLIC);
4154 MNT_FLAG(MNT_LOCAL);
4155 MNT_FLAG(MNT_QUOTA);
4156 MNT_FLAG(MNT_ROOTFS);
4158 MNT_FLAG(MNT_IGNORE);
4159 MNT_FLAG(MNT_UPDATE);
4160 MNT_FLAG(MNT_DELEXPORT);
4161 MNT_FLAG(MNT_RELOAD);
4162 MNT_FLAG(MNT_FORCE);
4163 MNT_FLAG(MNT_SNAPSHOT);
4164 MNT_FLAG(MNT_BYFSID);
4168 strlcat(buf, ", ", sizeof(buf));
4169 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4170 "0x%016jx", mflags);
4172 db_printf(" mnt_flag = %s\n", buf);
4175 flags = mp->mnt_kern_flag;
4176 #define MNT_KERN_FLAG(flag) do { \
4177 if (flags & (flag)) { \
4178 if (buf[0] != '\0') \
4179 strlcat(buf, ", ", sizeof(buf)); \
4180 strlcat(buf, (#flag) + 5, sizeof(buf)); \
4184 MNT_KERN_FLAG(MNTK_UNMOUNTF);
4185 MNT_KERN_FLAG(MNTK_ASYNC);
4186 MNT_KERN_FLAG(MNTK_SOFTDEP);
4187 MNT_KERN_FLAG(MNTK_DRAINING);
4188 MNT_KERN_FLAG(MNTK_REFEXPIRE);
4189 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4190 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4191 MNT_KERN_FLAG(MNTK_NO_IOPF);
4192 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4193 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4194 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4195 MNT_KERN_FLAG(MNTK_MARKER);
4196 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4197 MNT_KERN_FLAG(MNTK_FPLOOKUP);
4198 MNT_KERN_FLAG(MNTK_NOASYNC);
4199 MNT_KERN_FLAG(MNTK_UNMOUNT);
4200 MNT_KERN_FLAG(MNTK_MWAIT);
4201 MNT_KERN_FLAG(MNTK_SUSPEND);
4202 MNT_KERN_FLAG(MNTK_SUSPEND2);
4203 MNT_KERN_FLAG(MNTK_SUSPENDED);
4204 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4205 MNT_KERN_FLAG(MNTK_NOKNOTE);
4206 #undef MNT_KERN_FLAG
4209 strlcat(buf, ", ", sizeof(buf));
4210 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4213 db_printf(" mnt_kern_flag = %s\n", buf);
4215 db_printf(" mnt_opt = ");
4216 opt = TAILQ_FIRST(mp->mnt_opt);
4218 db_printf("%s", opt->name);
4219 opt = TAILQ_NEXT(opt, link);
4220 while (opt != NULL) {
4221 db_printf(", %s", opt->name);
4222 opt = TAILQ_NEXT(opt, link);
4228 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4229 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4230 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4231 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4232 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4233 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4234 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4235 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4236 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4237 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4238 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4239 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4241 db_printf(" mnt_cred = { uid=%u ruid=%u",
4242 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4243 if (jailed(mp->mnt_cred))
4244 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4246 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4247 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4248 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4249 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4250 db_printf(" mnt_lazyvnodelistsize = %d\n",
4251 mp->mnt_lazyvnodelistsize);
4252 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4253 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4254 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
4255 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4256 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4257 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4258 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4259 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4260 db_printf(" mnt_secondary_accwrites = %d\n",
4261 mp->mnt_secondary_accwrites);
4262 db_printf(" mnt_gjprovider = %s\n",
4263 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4264 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4266 db_printf("\n\nList of active vnodes\n");
4267 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4268 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4269 vn_printf(vp, "vnode ");
4274 db_printf("\n\nList of inactive vnodes\n");
4275 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4276 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4277 vn_printf(vp, "vnode ");
4286 * Fill in a struct xvfsconf based on a struct vfsconf.
4289 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4291 struct xvfsconf xvfsp;
4293 bzero(&xvfsp, sizeof(xvfsp));
4294 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4295 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4296 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4297 xvfsp.vfc_flags = vfsp->vfc_flags;
4299 * These are unused in userland, we keep them
4300 * to not break binary compatibility.
4302 xvfsp.vfc_vfsops = NULL;
4303 xvfsp.vfc_next = NULL;
4304 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4307 #ifdef COMPAT_FREEBSD32
4309 uint32_t vfc_vfsops;
4310 char vfc_name[MFSNAMELEN];
4311 int32_t vfc_typenum;
4312 int32_t vfc_refcount;
4318 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4320 struct xvfsconf32 xvfsp;
4322 bzero(&xvfsp, sizeof(xvfsp));
4323 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4324 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4325 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4326 xvfsp.vfc_flags = vfsp->vfc_flags;
4327 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4332 * Top level filesystem related information gathering.
4335 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4337 struct vfsconf *vfsp;
4342 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4343 #ifdef COMPAT_FREEBSD32
4344 if (req->flags & SCTL_MASK32)
4345 error = vfsconf2x32(req, vfsp);
4348 error = vfsconf2x(req, vfsp);
4356 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4357 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4358 "S,xvfsconf", "List of all configured filesystems");
4360 #ifndef BURN_BRIDGES
4361 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4364 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4366 int *name = (int *)arg1 - 1; /* XXX */
4367 u_int namelen = arg2 + 1; /* XXX */
4368 struct vfsconf *vfsp;
4370 log(LOG_WARNING, "userland calling deprecated sysctl, "
4371 "please rebuild world\n");
4373 #if 1 || defined(COMPAT_PRELITE2)
4374 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4376 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4380 case VFS_MAXTYPENUM:
4383 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4386 return (ENOTDIR); /* overloaded */
4388 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4389 if (vfsp->vfc_typenum == name[2])
4394 return (EOPNOTSUPP);
4395 #ifdef COMPAT_FREEBSD32
4396 if (req->flags & SCTL_MASK32)
4397 return (vfsconf2x32(req, vfsp));
4400 return (vfsconf2x(req, vfsp));
4402 return (EOPNOTSUPP);
4405 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4406 CTLFLAG_MPSAFE, vfs_sysctl,
4407 "Generic filesystem");
4409 #if 1 || defined(COMPAT_PRELITE2)
4412 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4415 struct vfsconf *vfsp;
4416 struct ovfsconf ovfs;
4419 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4420 bzero(&ovfs, sizeof(ovfs));
4421 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4422 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4423 ovfs.vfc_index = vfsp->vfc_typenum;
4424 ovfs.vfc_refcount = vfsp->vfc_refcount;
4425 ovfs.vfc_flags = vfsp->vfc_flags;
4426 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4436 #endif /* 1 || COMPAT_PRELITE2 */
4437 #endif /* !BURN_BRIDGES */
4439 #define KINFO_VNODESLOP 10
4442 * Dump vnode list (via sysctl).
4446 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4454 * Stale numvnodes access is not fatal here.
4457 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4459 /* Make an estimate */
4460 return (SYSCTL_OUT(req, 0, len));
4462 error = sysctl_wire_old_buffer(req, 0);
4465 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4467 mtx_lock(&mountlist_mtx);
4468 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4469 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4472 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4476 xvn[n].xv_size = sizeof *xvn;
4477 xvn[n].xv_vnode = vp;
4478 xvn[n].xv_id = 0; /* XXX compat */
4479 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4481 XV_COPY(writecount);
4487 xvn[n].xv_flag = vp->v_vflag;
4489 switch (vp->v_type) {
4496 if (vp->v_rdev == NULL) {
4500 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4503 xvn[n].xv_socket = vp->v_socket;
4506 xvn[n].xv_fifo = vp->v_fifoinfo;
4511 /* shouldn't happen? */
4519 mtx_lock(&mountlist_mtx);
4524 mtx_unlock(&mountlist_mtx);
4526 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4531 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4532 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4537 unmount_or_warn(struct mount *mp)
4541 error = dounmount(mp, MNT_FORCE, curthread);
4543 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4547 printf("%d)\n", error);
4552 * Unmount all filesystems. The list is traversed in reverse order
4553 * of mounting to avoid dependencies.
4556 vfs_unmountall(void)
4558 struct mount *mp, *tmp;
4560 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4563 * Since this only runs when rebooting, it is not interlocked.
4565 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4569 * Forcibly unmounting "/dev" before "/" would prevent clean
4570 * unmount of the latter.
4572 if (mp == rootdevmp)
4575 unmount_or_warn(mp);
4578 if (rootdevmp != NULL)
4579 unmount_or_warn(rootdevmp);
4583 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4586 ASSERT_VI_LOCKED(vp, __func__);
4587 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4588 if ((vp->v_iflag & VI_OWEINACT) == 0) {
4592 if (vn_lock(vp, lkflags) == 0) {
4599 vdefer_inactive_unlocked(vp);
4603 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4606 return (vp->v_iflag & VI_DEFINACT);
4609 static void __noinline
4610 vfs_periodic_inactive(struct mount *mp, int flags)
4612 struct vnode *vp, *mvp;
4615 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4616 if (flags != MNT_WAIT)
4617 lkflags |= LK_NOWAIT;
4619 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4620 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4624 vp->v_iflag &= ~VI_DEFINACT;
4625 vfs_deferred_inactive(vp, lkflags);
4630 vfs_want_msync(struct vnode *vp)
4632 struct vm_object *obj;
4635 * This test may be performed without any locks held.
4636 * We rely on vm_object's type stability.
4638 if (vp->v_vflag & VV_NOSYNC)
4641 return (obj != NULL && vm_object_mightbedirty(obj));
4645 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4648 if (vp->v_vflag & VV_NOSYNC)
4650 if (vp->v_iflag & VI_DEFINACT)
4652 return (vfs_want_msync(vp));
4655 static void __noinline
4656 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4658 struct vnode *vp, *mvp;
4659 struct vm_object *obj;
4661 int lkflags, objflags;
4666 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4667 if (flags != MNT_WAIT) {
4668 lkflags |= LK_NOWAIT;
4669 objflags = OBJPC_NOSYNC;
4671 objflags = OBJPC_SYNC;
4674 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4676 if (vp->v_iflag & VI_DEFINACT) {
4677 vp->v_iflag &= ~VI_DEFINACT;
4680 if (!vfs_want_msync(vp)) {
4682 vfs_deferred_inactive(vp, lkflags);
4687 if (vget(vp, lkflags, td) == 0) {
4689 if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4690 VM_OBJECT_WLOCK(obj);
4691 vm_object_page_clean(obj, 0, 0, objflags);
4692 VM_OBJECT_WUNLOCK(obj);
4699 vdefer_inactive_unlocked(vp);
4705 vfs_periodic(struct mount *mp, int flags)
4708 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4710 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4711 vfs_periodic_inactive(mp, flags);
4713 vfs_periodic_msync_inactive(mp, flags);
4717 destroy_vpollinfo_free(struct vpollinfo *vi)
4720 knlist_destroy(&vi->vpi_selinfo.si_note);
4721 mtx_destroy(&vi->vpi_lock);
4722 uma_zfree(vnodepoll_zone, vi);
4726 destroy_vpollinfo(struct vpollinfo *vi)
4729 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4730 seldrain(&vi->vpi_selinfo);
4731 destroy_vpollinfo_free(vi);
4735 * Initialize per-vnode helper structure to hold poll-related state.
4738 v_addpollinfo(struct vnode *vp)
4740 struct vpollinfo *vi;
4742 if (vp->v_pollinfo != NULL)
4744 vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4745 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4746 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4747 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4749 if (vp->v_pollinfo != NULL) {
4751 destroy_vpollinfo_free(vi);
4754 vp->v_pollinfo = vi;
4759 * Record a process's interest in events which might happen to
4760 * a vnode. Because poll uses the historic select-style interface
4761 * internally, this routine serves as both the ``check for any
4762 * pending events'' and the ``record my interest in future events''
4763 * functions. (These are done together, while the lock is held,
4764 * to avoid race conditions.)
4767 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4771 mtx_lock(&vp->v_pollinfo->vpi_lock);
4772 if (vp->v_pollinfo->vpi_revents & events) {
4774 * This leaves events we are not interested
4775 * in available for the other process which
4776 * which presumably had requested them
4777 * (otherwise they would never have been
4780 events &= vp->v_pollinfo->vpi_revents;
4781 vp->v_pollinfo->vpi_revents &= ~events;
4783 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4786 vp->v_pollinfo->vpi_events |= events;
4787 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4788 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4793 * Routine to create and manage a filesystem syncer vnode.
4795 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4796 static int sync_fsync(struct vop_fsync_args *);
4797 static int sync_inactive(struct vop_inactive_args *);
4798 static int sync_reclaim(struct vop_reclaim_args *);
4800 static struct vop_vector sync_vnodeops = {
4801 .vop_bypass = VOP_EOPNOTSUPP,
4802 .vop_close = sync_close, /* close */
4803 .vop_fsync = sync_fsync, /* fsync */
4804 .vop_inactive = sync_inactive, /* inactive */
4805 .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
4806 .vop_reclaim = sync_reclaim, /* reclaim */
4807 .vop_lock1 = vop_stdlock, /* lock */
4808 .vop_unlock = vop_stdunlock, /* unlock */
4809 .vop_islocked = vop_stdislocked, /* islocked */
4811 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
4814 * Create a new filesystem syncer vnode for the specified mount point.
4817 vfs_allocate_syncvnode(struct mount *mp)
4821 static long start, incr, next;
4824 /* Allocate a new vnode */
4825 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
4827 panic("vfs_allocate_syncvnode: getnewvnode() failed");
4829 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4830 vp->v_vflag |= VV_FORCEINSMQ;
4831 error = insmntque(vp, mp);
4833 panic("vfs_allocate_syncvnode: insmntque() failed");
4834 vp->v_vflag &= ~VV_FORCEINSMQ;
4837 * Place the vnode onto the syncer worklist. We attempt to
4838 * scatter them about on the list so that they will go off
4839 * at evenly distributed times even if all the filesystems
4840 * are mounted at once.
4843 if (next == 0 || next > syncer_maxdelay) {
4847 start = syncer_maxdelay / 2;
4848 incr = syncer_maxdelay;
4854 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
4855 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
4856 mtx_lock(&sync_mtx);
4858 if (mp->mnt_syncer == NULL) {
4859 mp->mnt_syncer = vp;
4862 mtx_unlock(&sync_mtx);
4865 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4872 vfs_deallocate_syncvnode(struct mount *mp)
4876 mtx_lock(&sync_mtx);
4877 vp = mp->mnt_syncer;
4879 mp->mnt_syncer = NULL;
4880 mtx_unlock(&sync_mtx);
4886 * Do a lazy sync of the filesystem.
4889 sync_fsync(struct vop_fsync_args *ap)
4891 struct vnode *syncvp = ap->a_vp;
4892 struct mount *mp = syncvp->v_mount;
4897 * We only need to do something if this is a lazy evaluation.
4899 if (ap->a_waitfor != MNT_LAZY)
4903 * Move ourselves to the back of the sync list.
4905 bo = &syncvp->v_bufobj;
4907 vn_syncer_add_to_worklist(bo, syncdelay);
4911 * Walk the list of vnodes pushing all that are dirty and
4912 * not already on the sync list.
4914 if (vfs_busy(mp, MBF_NOWAIT) != 0)
4916 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
4920 save = curthread_pflags_set(TDP_SYNCIO);
4922 * The filesystem at hand may be idle with free vnodes stored in the
4923 * batch. Return them instead of letting them stay there indefinitely.
4925 vfs_periodic(mp, MNT_NOWAIT);
4926 error = VFS_SYNC(mp, MNT_LAZY);
4927 curthread_pflags_restore(save);
4928 vn_finished_write(mp);
4934 * The syncer vnode is no referenced.
4937 sync_inactive(struct vop_inactive_args *ap)
4945 * The syncer vnode is no longer needed and is being decommissioned.
4947 * Modifications to the worklist must be protected by sync_mtx.
4950 sync_reclaim(struct vop_reclaim_args *ap)
4952 struct vnode *vp = ap->a_vp;
4957 mtx_lock(&sync_mtx);
4958 if (vp->v_mount->mnt_syncer == vp)
4959 vp->v_mount->mnt_syncer = NULL;
4960 if (bo->bo_flag & BO_ONWORKLST) {
4961 LIST_REMOVE(bo, bo_synclist);
4962 syncer_worklist_len--;
4964 bo->bo_flag &= ~BO_ONWORKLST;
4966 mtx_unlock(&sync_mtx);
4973 vn_need_pageq_flush(struct vnode *vp)
4975 struct vm_object *obj;
4978 MPASS(mtx_owned(VI_MTX(vp)));
4980 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
4981 vm_object_mightbedirty(obj))
4987 * Check if vnode represents a disk device
4990 vn_isdisk(struct vnode *vp, int *errp)
4994 if (vp->v_type != VCHR) {
5000 if (vp->v_rdev == NULL)
5002 else if (vp->v_rdev->si_devsw == NULL)
5004 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5010 return (error == 0);
5014 * VOP_FPLOOKUP_VEXEC routines are subject to special circumstances, see
5015 * the comment above cache_fplookup for details.
5017 * We never deny as priv_check_cred calls are not yet supported, see vaccess.
5020 vaccess_vexec_smr(mode_t file_mode, uid_t file_uid, gid_t file_gid, struct ucred *cred)
5023 VFS_SMR_ASSERT_ENTERED();
5025 /* Check the owner. */
5026 if (cred->cr_uid == file_uid) {
5027 if (file_mode & S_IXUSR)
5032 /* Otherwise, check the groups (first match) */
5033 if (groupmember(file_gid, cred)) {
5034 if (file_mode & S_IXGRP)
5039 /* Otherwise, check everyone else. */
5040 if (file_mode & S_IXOTH)
5046 * Common filesystem object access control check routine. Accepts a
5047 * vnode's type, "mode", uid and gid, requested access mode, and credentials.
5048 * Returns 0 on success, or an errno on failure.
5051 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5052 accmode_t accmode, struct ucred *cred)
5054 accmode_t dac_granted;
5055 accmode_t priv_granted;
5057 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5058 ("invalid bit in accmode"));
5059 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5060 ("VAPPEND without VWRITE"));
5063 * Look for a normal, non-privileged way to access the file/directory
5064 * as requested. If it exists, go with that.
5069 /* Check the owner. */
5070 if (cred->cr_uid == file_uid) {
5071 dac_granted |= VADMIN;
5072 if (file_mode & S_IXUSR)
5073 dac_granted |= VEXEC;
5074 if (file_mode & S_IRUSR)
5075 dac_granted |= VREAD;
5076 if (file_mode & S_IWUSR)
5077 dac_granted |= (VWRITE | VAPPEND);
5079 if ((accmode & dac_granted) == accmode)
5085 /* Otherwise, check the groups (first match) */
5086 if (groupmember(file_gid, cred)) {
5087 if (file_mode & S_IXGRP)
5088 dac_granted |= VEXEC;
5089 if (file_mode & S_IRGRP)
5090 dac_granted |= VREAD;
5091 if (file_mode & S_IWGRP)
5092 dac_granted |= (VWRITE | VAPPEND);
5094 if ((accmode & dac_granted) == accmode)
5100 /* Otherwise, check everyone else. */
5101 if (file_mode & S_IXOTH)
5102 dac_granted |= VEXEC;
5103 if (file_mode & S_IROTH)
5104 dac_granted |= VREAD;
5105 if (file_mode & S_IWOTH)
5106 dac_granted |= (VWRITE | VAPPEND);
5107 if ((accmode & dac_granted) == accmode)
5112 * Build a privilege mask to determine if the set of privileges
5113 * satisfies the requirements when combined with the granted mask
5114 * from above. For each privilege, if the privilege is required,
5115 * bitwise or the request type onto the priv_granted mask.
5121 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5122 * requests, instead of PRIV_VFS_EXEC.
5124 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5125 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5126 priv_granted |= VEXEC;
5129 * Ensure that at least one execute bit is on. Otherwise,
5130 * a privileged user will always succeed, and we don't want
5131 * this to happen unless the file really is executable.
5133 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5134 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5135 !priv_check_cred(cred, PRIV_VFS_EXEC))
5136 priv_granted |= VEXEC;
5139 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5140 !priv_check_cred(cred, PRIV_VFS_READ))
5141 priv_granted |= VREAD;
5143 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5144 !priv_check_cred(cred, PRIV_VFS_WRITE))
5145 priv_granted |= (VWRITE | VAPPEND);
5147 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5148 !priv_check_cred(cred, PRIV_VFS_ADMIN))
5149 priv_granted |= VADMIN;
5151 if ((accmode & (priv_granted | dac_granted)) == accmode) {
5155 return ((accmode & VADMIN) ? EPERM : EACCES);
5159 * Credential check based on process requesting service, and per-attribute
5163 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5164 struct thread *td, accmode_t accmode)
5168 * Kernel-invoked always succeeds.
5174 * Do not allow privileged processes in jail to directly manipulate
5175 * system attributes.
5177 switch (attrnamespace) {
5178 case EXTATTR_NAMESPACE_SYSTEM:
5179 /* Potentially should be: return (EPERM); */
5180 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5181 case EXTATTR_NAMESPACE_USER:
5182 return (VOP_ACCESS(vp, accmode, cred, td));
5188 #ifdef DEBUG_VFS_LOCKS
5190 * This only exists to suppress warnings from unlocked specfs accesses. It is
5191 * no longer ok to have an unlocked VFS.
5193 #define IGNORE_LOCK(vp) (KERNEL_PANICKED() || (vp) == NULL || \
5194 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
5196 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
5197 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5198 "Drop into debugger on lock violation");
5200 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
5201 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5202 0, "Check for interlock across VOPs");
5204 int vfs_badlock_print = 1; /* Print lock violations. */
5205 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5206 0, "Print lock violations");
5208 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
5209 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5210 0, "Print vnode details on lock violations");
5213 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
5214 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5215 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5219 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5223 if (vfs_badlock_backtrace)
5226 if (vfs_badlock_vnode)
5227 vn_printf(vp, "vnode ");
5228 if (vfs_badlock_print)
5229 printf("%s: %p %s\n", str, (void *)vp, msg);
5230 if (vfs_badlock_ddb)
5231 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5235 assert_vi_locked(struct vnode *vp, const char *str)
5238 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5239 vfs_badlock("interlock is not locked but should be", str, vp);
5243 assert_vi_unlocked(struct vnode *vp, const char *str)
5246 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5247 vfs_badlock("interlock is locked but should not be", str, vp);
5251 assert_vop_locked(struct vnode *vp, const char *str)
5255 if (!IGNORE_LOCK(vp)) {
5256 locked = VOP_ISLOCKED(vp);
5257 if (locked == 0 || locked == LK_EXCLOTHER)
5258 vfs_badlock("is not locked but should be", str, vp);
5263 assert_vop_unlocked(struct vnode *vp, const char *str)
5266 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5267 vfs_badlock("is locked but should not be", str, vp);
5271 assert_vop_elocked(struct vnode *vp, const char *str)
5274 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5275 vfs_badlock("is not exclusive locked but should be", str, vp);
5277 #endif /* DEBUG_VFS_LOCKS */
5280 vop_rename_fail(struct vop_rename_args *ap)
5283 if (ap->a_tvp != NULL)
5285 if (ap->a_tdvp == ap->a_tvp)
5294 vop_rename_pre(void *ap)
5296 struct vop_rename_args *a = ap;
5298 #ifdef DEBUG_VFS_LOCKS
5300 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5301 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5302 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5303 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5305 /* Check the source (from). */
5306 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5307 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5308 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5309 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5310 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5312 /* Check the target. */
5314 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5315 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5318 * It may be tempting to add vn_seqc_write_begin/end calls here and
5319 * in vop_rename_post but that's not going to work out since some
5320 * filesystems relookup vnodes mid-rename. This is probably a bug.
5322 * For now filesystems are expected to do the relevant calls after they
5323 * decide what vnodes to operate on.
5325 if (a->a_tdvp != a->a_fdvp)
5327 if (a->a_tvp != a->a_fvp)
5334 #ifdef DEBUG_VFS_LOCKS
5336 vop_fplookup_vexec_debugpre(void *ap __unused)
5339 VFS_SMR_ASSERT_ENTERED();
5343 vop_fplookup_vexec_debugpost(void *ap __unused, int rc __unused)
5346 VFS_SMR_ASSERT_ENTERED();
5350 vop_strategy_debugpre(void *ap)
5352 struct vop_strategy_args *a;
5359 * Cluster ops lock their component buffers but not the IO container.
5361 if ((bp->b_flags & B_CLUSTER) != 0)
5364 if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5365 if (vfs_badlock_print)
5367 "VOP_STRATEGY: bp is not locked but should be\n");
5368 if (vfs_badlock_ddb)
5369 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5374 vop_lock_debugpre(void *ap)
5376 struct vop_lock1_args *a = ap;
5378 if ((a->a_flags & LK_INTERLOCK) == 0)
5379 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5381 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5385 vop_lock_debugpost(void *ap, int rc)
5387 struct vop_lock1_args *a = ap;
5389 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5390 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5391 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5395 vop_unlock_debugpre(void *ap)
5397 struct vop_unlock_args *a = ap;
5399 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5403 vop_need_inactive_debugpre(void *ap)
5405 struct vop_need_inactive_args *a = ap;
5407 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5411 vop_need_inactive_debugpost(void *ap, int rc)
5413 struct vop_need_inactive_args *a = ap;
5415 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5420 vop_create_pre(void *ap)
5422 struct vop_create_args *a;
5427 vn_seqc_write_begin(dvp);
5431 vop_create_post(void *ap, int rc)
5433 struct vop_create_args *a;
5438 vn_seqc_write_end(dvp);
5440 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5444 vop_whiteout_pre(void *ap)
5446 struct vop_whiteout_args *a;
5451 vn_seqc_write_begin(dvp);
5455 vop_whiteout_post(void *ap, int rc)
5457 struct vop_whiteout_args *a;
5462 vn_seqc_write_end(dvp);
5466 vop_deleteextattr_pre(void *ap)
5468 struct vop_deleteextattr_args *a;
5473 vn_seqc_write_begin(vp);
5477 vop_deleteextattr_post(void *ap, int rc)
5479 struct vop_deleteextattr_args *a;
5484 vn_seqc_write_end(vp);
5486 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5490 vop_link_pre(void *ap)
5492 struct vop_link_args *a;
5493 struct vnode *vp, *tdvp;
5498 vn_seqc_write_begin(vp);
5499 vn_seqc_write_begin(tdvp);
5503 vop_link_post(void *ap, int rc)
5505 struct vop_link_args *a;
5506 struct vnode *vp, *tdvp;
5511 vn_seqc_write_end(vp);
5512 vn_seqc_write_end(tdvp);
5514 VFS_KNOTE_LOCKED(vp, NOTE_LINK);
5515 VFS_KNOTE_LOCKED(tdvp, NOTE_WRITE);
5520 vop_mkdir_pre(void *ap)
5522 struct vop_mkdir_args *a;
5527 vn_seqc_write_begin(dvp);
5531 vop_mkdir_post(void *ap, int rc)
5533 struct vop_mkdir_args *a;
5538 vn_seqc_write_end(dvp);
5540 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5544 vop_mknod_pre(void *ap)
5546 struct vop_mknod_args *a;
5551 vn_seqc_write_begin(dvp);
5555 vop_mknod_post(void *ap, int rc)
5557 struct vop_mknod_args *a;
5562 vn_seqc_write_end(dvp);
5564 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5568 vop_reclaim_post(void *ap, int rc)
5570 struct vop_reclaim_args *a;
5575 ASSERT_VOP_IN_SEQC(vp);
5577 VFS_KNOTE_LOCKED(vp, NOTE_REVOKE);
5581 vop_remove_pre(void *ap)
5583 struct vop_remove_args *a;
5584 struct vnode *dvp, *vp;
5589 vn_seqc_write_begin(dvp);
5590 vn_seqc_write_begin(vp);
5594 vop_remove_post(void *ap, int rc)
5596 struct vop_remove_args *a;
5597 struct vnode *dvp, *vp;
5602 vn_seqc_write_end(dvp);
5603 vn_seqc_write_end(vp);
5605 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5606 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5611 vop_rename_post(void *ap, int rc)
5613 struct vop_rename_args *a = ap;
5618 if (a->a_fdvp == a->a_tdvp) {
5619 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5621 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5622 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5624 hint |= NOTE_EXTEND;
5625 if (a->a_fvp->v_type == VDIR)
5627 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5629 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5630 a->a_tvp->v_type == VDIR)
5632 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5635 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5637 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5639 if (a->a_tdvp != a->a_fdvp)
5641 if (a->a_tvp != a->a_fvp)
5649 vop_rmdir_pre(void *ap)
5651 struct vop_rmdir_args *a;
5652 struct vnode *dvp, *vp;
5657 vn_seqc_write_begin(dvp);
5658 vn_seqc_write_begin(vp);
5662 vop_rmdir_post(void *ap, int rc)
5664 struct vop_rmdir_args *a;
5665 struct vnode *dvp, *vp;
5670 vn_seqc_write_end(dvp);
5671 vn_seqc_write_end(vp);
5673 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5674 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5679 vop_setattr_pre(void *ap)
5681 struct vop_setattr_args *a;
5686 vn_seqc_write_begin(vp);
5690 vop_setattr_post(void *ap, int rc)
5692 struct vop_setattr_args *a;
5697 vn_seqc_write_end(vp);
5699 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
5703 vop_setacl_pre(void *ap)
5705 struct vop_setacl_args *a;
5710 vn_seqc_write_begin(vp);
5714 vop_setacl_post(void *ap, int rc __unused)
5716 struct vop_setacl_args *a;
5721 vn_seqc_write_end(vp);
5725 vop_setextattr_pre(void *ap)
5727 struct vop_setextattr_args *a;
5732 vn_seqc_write_begin(vp);
5736 vop_setextattr_post(void *ap, int rc)
5738 struct vop_setextattr_args *a;
5743 vn_seqc_write_end(vp);
5745 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
5749 vop_symlink_pre(void *ap)
5751 struct vop_symlink_args *a;
5756 vn_seqc_write_begin(dvp);
5760 vop_symlink_post(void *ap, int rc)
5762 struct vop_symlink_args *a;
5767 vn_seqc_write_end(dvp);
5769 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5773 vop_open_post(void *ap, int rc)
5775 struct vop_open_args *a = ap;
5778 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
5782 vop_close_post(void *ap, int rc)
5784 struct vop_close_args *a = ap;
5786 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
5787 !VN_IS_DOOMED(a->a_vp))) {
5788 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
5789 NOTE_CLOSE_WRITE : NOTE_CLOSE);
5794 vop_read_post(void *ap, int rc)
5796 struct vop_read_args *a = ap;
5799 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5803 vop_readdir_post(void *ap, int rc)
5805 struct vop_readdir_args *a = ap;
5808 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5811 static struct knlist fs_knlist;
5814 vfs_event_init(void *arg)
5816 knlist_init_mtx(&fs_knlist, NULL);
5818 /* XXX - correct order? */
5819 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
5822 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
5825 KNOTE_UNLOCKED(&fs_knlist, event);
5828 static int filt_fsattach(struct knote *kn);
5829 static void filt_fsdetach(struct knote *kn);
5830 static int filt_fsevent(struct knote *kn, long hint);
5832 struct filterops fs_filtops = {
5834 .f_attach = filt_fsattach,
5835 .f_detach = filt_fsdetach,
5836 .f_event = filt_fsevent
5840 filt_fsattach(struct knote *kn)
5843 kn->kn_flags |= EV_CLEAR;
5844 knlist_add(&fs_knlist, kn, 0);
5849 filt_fsdetach(struct knote *kn)
5852 knlist_remove(&fs_knlist, kn, 0);
5856 filt_fsevent(struct knote *kn, long hint)
5859 kn->kn_fflags |= hint;
5860 return (kn->kn_fflags != 0);
5864 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
5870 error = SYSCTL_IN(req, &vc, sizeof(vc));
5873 if (vc.vc_vers != VFS_CTL_VERS1)
5875 mp = vfs_getvfs(&vc.vc_fsid);
5878 /* ensure that a specific sysctl goes to the right filesystem. */
5879 if (strcmp(vc.vc_fstypename, "*") != 0 &&
5880 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
5884 VCTLTOREQ(&vc, req);
5885 error = VFS_SYSCTL(mp, vc.vc_op, req);
5890 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
5891 NULL, 0, sysctl_vfs_ctl, "",
5895 * Function to initialize a va_filerev field sensibly.
5896 * XXX: Wouldn't a random number make a lot more sense ??
5899 init_va_filerev(void)
5904 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
5907 static int filt_vfsread(struct knote *kn, long hint);
5908 static int filt_vfswrite(struct knote *kn, long hint);
5909 static int filt_vfsvnode(struct knote *kn, long hint);
5910 static void filt_vfsdetach(struct knote *kn);
5911 static struct filterops vfsread_filtops = {
5913 .f_detach = filt_vfsdetach,
5914 .f_event = filt_vfsread
5916 static struct filterops vfswrite_filtops = {
5918 .f_detach = filt_vfsdetach,
5919 .f_event = filt_vfswrite
5921 static struct filterops vfsvnode_filtops = {
5923 .f_detach = filt_vfsdetach,
5924 .f_event = filt_vfsvnode
5928 vfs_knllock(void *arg)
5930 struct vnode *vp = arg;
5932 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5936 vfs_knlunlock(void *arg)
5938 struct vnode *vp = arg;
5944 vfs_knl_assert_locked(void *arg)
5946 #ifdef DEBUG_VFS_LOCKS
5947 struct vnode *vp = arg;
5949 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
5954 vfs_knl_assert_unlocked(void *arg)
5956 #ifdef DEBUG_VFS_LOCKS
5957 struct vnode *vp = arg;
5959 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
5964 vfs_kqfilter(struct vop_kqfilter_args *ap)
5966 struct vnode *vp = ap->a_vp;
5967 struct knote *kn = ap->a_kn;
5970 switch (kn->kn_filter) {
5972 kn->kn_fop = &vfsread_filtops;
5975 kn->kn_fop = &vfswrite_filtops;
5978 kn->kn_fop = &vfsvnode_filtops;
5984 kn->kn_hook = (caddr_t)vp;
5987 if (vp->v_pollinfo == NULL)
5989 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5991 knlist_add(knl, kn, 0);
5997 * Detach knote from vnode
6000 filt_vfsdetach(struct knote *kn)
6002 struct vnode *vp = (struct vnode *)kn->kn_hook;
6004 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
6005 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
6011 filt_vfsread(struct knote *kn, long hint)
6013 struct vnode *vp = (struct vnode *)kn->kn_hook;
6018 * filesystem is gone, so set the EOF flag and schedule
6019 * the knote for deletion.
6021 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6023 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6028 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
6032 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
6033 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
6040 filt_vfswrite(struct knote *kn, long hint)
6042 struct vnode *vp = (struct vnode *)kn->kn_hook;
6047 * filesystem is gone, so set the EOF flag and schedule
6048 * the knote for deletion.
6050 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
6051 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6059 filt_vfsvnode(struct knote *kn, long hint)
6061 struct vnode *vp = (struct vnode *)kn->kn_hook;
6065 if (kn->kn_sfflags & hint)
6066 kn->kn_fflags |= hint;
6067 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6068 kn->kn_flags |= EV_EOF;
6072 res = (kn->kn_fflags != 0);
6078 * Returns whether the directory is empty or not.
6079 * If it is empty, the return value is 0; otherwise
6080 * the return value is an error value (which may
6084 vfs_emptydir(struct vnode *vp)
6088 struct dirent *dirent, *dp, *endp;
6094 ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
6096 dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
6097 iov.iov_base = dirent;
6098 iov.iov_len = sizeof(struct dirent);
6103 uio.uio_resid = sizeof(struct dirent);
6104 uio.uio_segflg = UIO_SYSSPACE;
6105 uio.uio_rw = UIO_READ;
6106 uio.uio_td = curthread;
6108 while (eof == 0 && error == 0) {
6109 error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
6113 endp = (void *)((uint8_t *)dirent +
6114 sizeof(struct dirent) - uio.uio_resid);
6115 for (dp = dirent; dp < endp;
6116 dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
6117 if (dp->d_type == DT_WHT)
6119 if (dp->d_namlen == 0)
6121 if (dp->d_type != DT_DIR &&
6122 dp->d_type != DT_UNKNOWN) {
6126 if (dp->d_namlen > 2) {
6130 if (dp->d_namlen == 1 &&
6131 dp->d_name[0] != '.') {
6135 if (dp->d_namlen == 2 &&
6136 dp->d_name[1] != '.') {
6140 uio.uio_resid = sizeof(struct dirent);
6143 free(dirent, M_TEMP);
6148 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6152 if (dp->d_reclen > ap->a_uio->uio_resid)
6153 return (ENAMETOOLONG);
6154 error = uiomove(dp, dp->d_reclen, ap->a_uio);
6156 if (ap->a_ncookies != NULL) {
6157 if (ap->a_cookies != NULL)
6158 free(ap->a_cookies, M_TEMP);
6159 ap->a_cookies = NULL;
6160 *ap->a_ncookies = 0;
6164 if (ap->a_ncookies == NULL)
6167 KASSERT(ap->a_cookies,
6168 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6170 *ap->a_cookies = realloc(*ap->a_cookies,
6171 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
6172 (*ap->a_cookies)[*ap->a_ncookies] = off;
6173 *ap->a_ncookies += 1;
6178 * The purpose of this routine is to remove granularity from accmode_t,
6179 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6180 * VADMIN and VAPPEND.
6182 * If it returns 0, the caller is supposed to continue with the usual
6183 * access checks using 'accmode' as modified by this routine. If it
6184 * returns nonzero value, the caller is supposed to return that value
6187 * Note that after this routine runs, accmode may be zero.
6190 vfs_unixify_accmode(accmode_t *accmode)
6193 * There is no way to specify explicit "deny" rule using
6194 * file mode or POSIX.1e ACLs.
6196 if (*accmode & VEXPLICIT_DENY) {
6202 * None of these can be translated into usual access bits.
6203 * Also, the common case for NFSv4 ACLs is to not contain
6204 * either of these bits. Caller should check for VWRITE
6205 * on the containing directory instead.
6207 if (*accmode & (VDELETE_CHILD | VDELETE))
6210 if (*accmode & VADMIN_PERMS) {
6211 *accmode &= ~VADMIN_PERMS;
6216 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6217 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6219 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6225 * Clear out a doomed vnode (if any) and replace it with a new one as long
6226 * as the fs is not being unmounted. Return the root vnode to the caller.
6228 static int __noinline
6229 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6235 if (mp->mnt_rootvnode != NULL) {
6237 vp = mp->mnt_rootvnode;
6239 if (!VN_IS_DOOMED(vp)) {
6242 error = vn_lock(vp, flags);
6251 * Clear the old one.
6253 mp->mnt_rootvnode = NULL;
6257 vfs_op_barrier_wait(mp);
6261 error = VFS_CACHEDROOT(mp, flags, vpp);
6264 if (mp->mnt_vfs_ops == 0) {
6266 if (mp->mnt_vfs_ops != 0) {
6270 if (mp->mnt_rootvnode == NULL) {
6272 mp->mnt_rootvnode = *vpp;
6274 if (mp->mnt_rootvnode != *vpp) {
6275 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6276 panic("%s: mismatch between vnode returned "
6277 " by VFS_CACHEDROOT and the one cached "
6279 __func__, *vpp, mp->mnt_rootvnode);
6289 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6294 if (!vfs_op_thread_enter(mp))
6295 return (vfs_cache_root_fallback(mp, flags, vpp));
6296 vp = atomic_load_ptr(&mp->mnt_rootvnode);
6297 if (vp == NULL || VN_IS_DOOMED(vp)) {
6298 vfs_op_thread_exit(mp);
6299 return (vfs_cache_root_fallback(mp, flags, vpp));
6302 vfs_op_thread_exit(mp);
6303 error = vn_lock(vp, flags);
6306 return (vfs_cache_root_fallback(mp, flags, vpp));
6313 vfs_cache_root_clear(struct mount *mp)
6318 * ops > 0 guarantees there is nobody who can see this vnode
6320 MPASS(mp->mnt_vfs_ops > 0);
6321 vp = mp->mnt_rootvnode;
6323 vn_seqc_write_begin(vp);
6324 mp->mnt_rootvnode = NULL;
6329 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6332 MPASS(mp->mnt_vfs_ops > 0);
6334 mp->mnt_rootvnode = vp;
6338 * These are helper functions for filesystems to traverse all
6339 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6341 * This interface replaces MNT_VNODE_FOREACH.
6345 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6350 kern_yield(PRI_USER);
6352 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6353 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6354 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6355 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6356 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6359 if (VN_IS_DOOMED(vp)) {
6366 __mnt_vnode_markerfree_all(mvp, mp);
6367 /* MNT_IUNLOCK(mp); -- done in above function */
6368 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6371 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6372 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6378 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6382 *mvp = vn_alloc_marker(mp);
6386 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6387 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6388 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6391 if (VN_IS_DOOMED(vp)) {
6400 vn_free_marker(*mvp);
6404 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6410 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6418 mtx_assert(MNT_MTX(mp), MA_OWNED);
6420 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6421 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6424 vn_free_marker(*mvp);
6429 * These are helper functions for filesystems to traverse their
6430 * lazy vnodes. See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6433 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6436 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6441 vn_free_marker(*mvp);
6446 * Relock the mp mount vnode list lock with the vp vnode interlock in the
6447 * conventional lock order during mnt_vnode_next_lazy iteration.
6449 * On entry, the mount vnode list lock is held and the vnode interlock is not.
6450 * The list lock is dropped and reacquired. On success, both locks are held.
6451 * On failure, the mount vnode list lock is held but the vnode interlock is
6452 * not, and the procedure may have yielded.
6455 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6459 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6460 TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6461 ("%s: bad marker", __func__));
6462 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6463 ("%s: inappropriate vnode", __func__));
6464 ASSERT_VI_UNLOCKED(vp, __func__);
6465 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6467 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6468 TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6471 * Note we may be racing against vdrop which transitioned the hold
6472 * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
6473 * if we are the only user after we get the interlock we will just
6477 mtx_unlock(&mp->mnt_listmtx);
6479 if (VN_IS_DOOMED(vp)) {
6480 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
6483 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
6485 * There is nothing to do if we are the last user.
6487 if (!refcount_release_if_not_last(&vp->v_holdcnt))
6489 mtx_lock(&mp->mnt_listmtx);
6494 mtx_lock(&mp->mnt_listmtx);
6498 static struct vnode *
6499 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6504 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6505 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6507 vp = TAILQ_NEXT(*mvp, v_lazylist);
6508 while (vp != NULL) {
6509 if (vp->v_type == VMARKER) {
6510 vp = TAILQ_NEXT(vp, v_lazylist);
6514 * See if we want to process the vnode. Note we may encounter a
6515 * long string of vnodes we don't care about and hog the list
6516 * as a result. Check for it and requeue the marker.
6518 VNPASS(!VN_IS_DOOMED(vp), vp);
6519 if (!cb(vp, cbarg)) {
6520 if (!should_yield()) {
6521 vp = TAILQ_NEXT(vp, v_lazylist);
6524 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6526 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6528 mtx_unlock(&mp->mnt_listmtx);
6529 kern_yield(PRI_USER);
6530 mtx_lock(&mp->mnt_listmtx);
6534 * Try-lock because this is the wrong lock order.
6536 if (!VI_TRYLOCK(vp) &&
6537 !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6539 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6540 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6541 ("alien vnode on the lazy list %p %p", vp, mp));
6542 VNPASS(vp->v_mount == mp, vp);
6543 VNPASS(!VN_IS_DOOMED(vp), vp);
6546 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6548 /* Check if we are done */
6550 mtx_unlock(&mp->mnt_listmtx);
6551 mnt_vnode_markerfree_lazy(mvp, mp);
6554 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6555 mtx_unlock(&mp->mnt_listmtx);
6556 ASSERT_VI_LOCKED(vp, "lazy iter");
6561 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6566 kern_yield(PRI_USER);
6567 mtx_lock(&mp->mnt_listmtx);
6568 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6572 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6577 if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
6580 *mvp = vn_alloc_marker(mp);
6585 mtx_lock(&mp->mnt_listmtx);
6586 vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6588 mtx_unlock(&mp->mnt_listmtx);
6589 mnt_vnode_markerfree_lazy(mvp, mp);
6592 TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6593 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6597 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6603 mtx_lock(&mp->mnt_listmtx);
6604 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6605 mtx_unlock(&mp->mnt_listmtx);
6606 mnt_vnode_markerfree_lazy(mvp, mp);
6610 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
6613 if ((cnp->cn_flags & NOEXECCHECK) != 0) {
6614 cnp->cn_flags &= ~NOEXECCHECK;
6618 return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, cnp->cn_thread));
6622 * Do not use this variant unless you have means other than the hold count
6623 * to prevent the vnode from getting freed.
6626 vn_seqc_write_begin_unheld_locked(struct vnode *vp)
6629 ASSERT_VI_LOCKED(vp, __func__);
6630 VNPASS(vp->v_seqc_users >= 0, vp);
6632 if (vp->v_seqc_users == 1)
6633 seqc_sleepable_write_begin(&vp->v_seqc);
6637 vn_seqc_write_begin_locked(struct vnode *vp)
6640 ASSERT_VI_LOCKED(vp, __func__);
6641 VNPASS(vp->v_holdcnt > 0, vp);
6642 vn_seqc_write_begin_unheld_locked(vp);
6646 vn_seqc_write_begin(struct vnode *vp)
6650 vn_seqc_write_begin_locked(vp);
6655 vn_seqc_write_begin_unheld(struct vnode *vp)
6659 vn_seqc_write_begin_unheld_locked(vp);
6664 vn_seqc_write_end_locked(struct vnode *vp)
6667 ASSERT_VI_LOCKED(vp, __func__);
6668 VNPASS(vp->v_seqc_users > 0, vp);
6670 if (vp->v_seqc_users == 0)
6671 seqc_sleepable_write_end(&vp->v_seqc);
6675 vn_seqc_write_end(struct vnode *vp)
6679 vn_seqc_write_end_locked(vp);