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>
81 #include <sys/sysctl.h>
82 #include <sys/syslog.h>
83 #include <sys/vmmeter.h>
84 #include <sys/vnode.h>
85 #include <sys/watchdog.h>
87 #include <machine/stdarg.h>
89 #include <security/mac/mac_framework.h>
92 #include <vm/vm_object.h>
93 #include <vm/vm_extern.h>
95 #include <vm/vm_map.h>
96 #include <vm/vm_page.h>
97 #include <vm/vm_kern.h>
104 static void delmntque(struct vnode *vp);
105 static int flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
106 int slpflag, int slptimeo);
107 static void syncer_shutdown(void *arg, int howto);
108 static int vtryrecycle(struct vnode *vp);
109 static void v_init_counters(struct vnode *);
110 static void v_incr_devcount(struct vnode *);
111 static void v_decr_devcount(struct vnode *);
112 static void vgonel(struct vnode *);
113 static void vfs_knllock(void *arg);
114 static void vfs_knlunlock(void *arg);
115 static void vfs_knl_assert_locked(void *arg);
116 static void vfs_knl_assert_unlocked(void *arg);
117 static void vnlru_return_batches(struct vfsops *mnt_op);
118 static void destroy_vpollinfo(struct vpollinfo *vi);
119 static int v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
120 daddr_t startlbn, daddr_t endlbn);
121 static void vnlru_recalc(void);
124 * These fences are intended for cases where some synchronization is
125 * needed between access of v_iflags and lockless vnode refcount (v_holdcnt
126 * and v_usecount) updates. Access to v_iflags is generally synchronized
127 * by the interlock, but we have some internal assertions that check vnode
128 * flags without acquiring the lock. Thus, these fences are INVARIANTS-only
132 #define VNODE_REFCOUNT_FENCE_ACQ() atomic_thread_fence_acq()
133 #define VNODE_REFCOUNT_FENCE_REL() atomic_thread_fence_rel()
135 #define VNODE_REFCOUNT_FENCE_ACQ()
136 #define VNODE_REFCOUNT_FENCE_REL()
140 * Number of vnodes in existence. Increased whenever getnewvnode()
141 * allocates a new vnode, decreased in vdropl() for VIRF_DOOMED vnode.
143 static u_long __exclusive_cache_line numvnodes;
145 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
146 "Number of vnodes in existence");
148 static counter_u64_t vnodes_created;
149 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
150 "Number of vnodes created by getnewvnode");
152 static u_long mnt_free_list_batch = 128;
153 SYSCTL_ULONG(_vfs, OID_AUTO, mnt_free_list_batch, CTLFLAG_RW,
154 &mnt_free_list_batch, 0, "Limit of vnodes held on mnt's free list");
157 * Conversion tables for conversion from vnode types to inode formats
160 enum vtype iftovt_tab[16] = {
161 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
162 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
164 int vttoif_tab[10] = {
165 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
166 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
170 * List of vnodes that are ready for recycling.
172 static TAILQ_HEAD(freelst, vnode) vnode_free_list;
175 * "Free" vnode target. Free vnodes are rarely completely free, but are
176 * just ones that are cheap to recycle. Usually they are for files which
177 * have been stat'd but not read; these usually have inode and namecache
178 * data attached to them. This target is the preferred minimum size of a
179 * sub-cache consisting mostly of such files. The system balances the size
180 * of this sub-cache with its complement to try to prevent either from
181 * thrashing while the other is relatively inactive. The targets express
182 * a preference for the best balance.
184 * "Above" this target there are 2 further targets (watermarks) related
185 * to recyling of free vnodes. In the best-operating case, the cache is
186 * exactly full, the free list has size between vlowat and vhiwat above the
187 * free target, and recycling from it and normal use maintains this state.
188 * Sometimes the free list is below vlowat or even empty, but this state
189 * is even better for immediate use provided the cache is not full.
190 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
191 * ones) to reach one of these states. The watermarks are currently hard-
192 * coded as 4% and 9% of the available space higher. These and the default
193 * of 25% for wantfreevnodes are too large if the memory size is large.
194 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
195 * whenever vnlru_proc() becomes active.
197 static u_long wantfreevnodes;
198 static u_long freevnodes;
199 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
200 &freevnodes, 0, "Number of \"free\" vnodes");
202 static counter_u64_t recycles_count;
203 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
204 "Number of vnodes recycled to meet vnode cache targets");
206 static counter_u64_t recycles_free_count;
207 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD, &recycles_free_count,
208 "Number of free vnodes recycled to meet vnode cache targets");
211 * Various variables used for debugging the new implementation of
213 * XXX these are probably of (very) limited utility now.
215 static int reassignbufcalls;
216 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW | CTLFLAG_STATS,
217 &reassignbufcalls, 0, "Number of calls to reassignbuf");
219 static counter_u64_t deferred_inact;
220 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, deferred_inact, CTLFLAG_RD, &deferred_inact,
221 "Number of times inactive processing was deferred");
223 /* To keep more than one thread at a time from running vfs_getnewfsid */
224 static struct mtx mntid_mtx;
227 * Lock for any access to the following:
232 static struct mtx __exclusive_cache_line vnode_free_list_mtx;
234 /* Publicly exported FS */
235 struct nfs_public nfs_pub;
237 static uma_zone_t buf_trie_zone;
239 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
240 static uma_zone_t vnode_zone;
241 static uma_zone_t vnodepoll_zone;
244 * The workitem queue.
246 * It is useful to delay writes of file data and filesystem metadata
247 * for tens of seconds so that quickly created and deleted files need
248 * not waste disk bandwidth being created and removed. To realize this,
249 * we append vnodes to a "workitem" queue. When running with a soft
250 * updates implementation, most pending metadata dependencies should
251 * not wait for more than a few seconds. Thus, mounted on block devices
252 * are delayed only about a half the time that file data is delayed.
253 * Similarly, directory updates are more critical, so are only delayed
254 * about a third the time that file data is delayed. Thus, there are
255 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
256 * one each second (driven off the filesystem syncer process). The
257 * syncer_delayno variable indicates the next queue that is to be processed.
258 * Items that need to be processed soon are placed in this queue:
260 * syncer_workitem_pending[syncer_delayno]
262 * A delay of fifteen seconds is done by placing the request fifteen
263 * entries later in the queue:
265 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
268 static int syncer_delayno;
269 static long syncer_mask;
270 LIST_HEAD(synclist, bufobj);
271 static struct synclist *syncer_workitem_pending;
273 * The sync_mtx protects:
278 * syncer_workitem_pending
279 * syncer_worklist_len
282 static struct mtx sync_mtx;
283 static struct cv sync_wakeup;
285 #define SYNCER_MAXDELAY 32
286 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
287 static int syncdelay = 30; /* max time to delay syncing data */
288 static int filedelay = 30; /* time to delay syncing files */
289 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
290 "Time to delay syncing files (in seconds)");
291 static int dirdelay = 29; /* time to delay syncing directories */
292 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
293 "Time to delay syncing directories (in seconds)");
294 static int metadelay = 28; /* time to delay syncing metadata */
295 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
296 "Time to delay syncing metadata (in seconds)");
297 static int rushjob; /* number of slots to run ASAP */
298 static int stat_rush_requests; /* number of times I/O speeded up */
299 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
300 "Number of times I/O speeded up (rush requests)");
303 * When shutting down the syncer, run it at four times normal speed.
305 #define SYNCER_SHUTDOWN_SPEEDUP 4
306 static int sync_vnode_count;
307 static int syncer_worklist_len;
308 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
311 /* Target for maximum number of vnodes. */
312 u_long desiredvnodes;
313 static u_long gapvnodes; /* gap between wanted and desired */
314 static u_long vhiwat; /* enough extras after expansion */
315 static u_long vlowat; /* minimal extras before expansion */
316 static u_long vstir; /* nonzero to stir non-free vnodes */
317 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
320 * Note that no attempt is made to sanitize these parameters.
323 sysctl_maxvnodes(SYSCTL_HANDLER_ARGS)
329 error = sysctl_handle_long(oidp, &val, 0, req);
330 if (error != 0 || req->newptr == NULL)
333 if (val == desiredvnodes)
335 mtx_lock(&vnode_free_list_mtx);
337 wantfreevnodes = desiredvnodes / 4;
339 mtx_unlock(&vnode_free_list_mtx);
341 * XXX There is no protection against multiple threads changing
342 * desiredvnodes at the same time. Locking above only helps vnlru and
345 vfs_hash_changesize(desiredvnodes);
346 cache_changesize(desiredvnodes);
350 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
351 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
352 "UL", "Target for maximum number of vnodes");
355 sysctl_wantfreevnodes(SYSCTL_HANDLER_ARGS)
360 val = wantfreevnodes;
361 error = sysctl_handle_long(oidp, &val, 0, req);
362 if (error != 0 || req->newptr == NULL)
365 if (val == wantfreevnodes)
367 mtx_lock(&vnode_free_list_mtx);
368 wantfreevnodes = val;
370 mtx_unlock(&vnode_free_list_mtx);
374 SYSCTL_PROC(_vfs, OID_AUTO, wantfreevnodes,
375 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
376 "UL", "Target for minimum number of \"free\" vnodes");
378 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
379 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
380 static int vnlru_nowhere;
381 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
382 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
385 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
390 unsigned long ndflags;
393 if (req->newptr == NULL)
395 if (req->newlen >= PATH_MAX)
398 buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
399 error = SYSCTL_IN(req, buf, req->newlen);
403 buf[req->newlen] = '\0';
405 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | NOCACHE | SAVENAME;
406 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
407 if ((error = namei(&nd)) != 0)
411 if (VN_IS_DOOMED(vp)) {
413 * This vnode is being recycled. Return != 0 to let the caller
414 * know that the sysctl had no effect. Return EAGAIN because a
415 * subsequent call will likely succeed (since namei will create
416 * a new vnode if necessary)
422 counter_u64_add(recycles_count, 1);
432 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
434 struct thread *td = curthread;
440 if (req->newptr == NULL)
443 error = sysctl_handle_int(oidp, &fd, 0, req);
446 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
451 error = vn_lock(vp, LK_EXCLUSIVE);
455 counter_u64_add(recycles_count, 1);
463 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
464 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
465 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
466 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
467 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
468 sysctl_ftry_reclaim_vnode, "I",
469 "Try to reclaim a vnode by its file descriptor");
471 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
475 * Support for the bufobj clean & dirty pctrie.
478 buf_trie_alloc(struct pctrie *ptree)
481 return uma_zalloc(buf_trie_zone, M_NOWAIT);
485 buf_trie_free(struct pctrie *ptree, void *node)
488 uma_zfree(buf_trie_zone, node);
490 PCTRIE_DEFINE(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free);
493 * Initialize the vnode management data structures.
495 * Reevaluate the following cap on the number of vnodes after the physical
496 * memory size exceeds 512GB. In the limit, as the physical memory size
497 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
499 #ifndef MAXVNODES_MAX
500 #define MAXVNODES_MAX (512UL * 1024 * 1024 / 64) /* 8M */
503 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
505 static struct vnode *
506 vn_alloc_marker(struct mount *mp)
510 vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
511 vp->v_type = VMARKER;
518 vn_free_marker(struct vnode *vp)
521 MPASS(vp->v_type == VMARKER);
522 free(vp, M_VNODE_MARKER);
526 * Initialize a vnode as it first enters the zone.
529 vnode_init(void *mem, int size, int flags)
538 vp->v_vnlock = &vp->v_lock;
539 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
541 * By default, don't allow shared locks unless filesystems opt-in.
543 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
544 LK_NOSHARE | LK_IS_VNODE);
548 bufobj_init(&vp->v_bufobj, vp);
550 * Initialize namecache.
552 LIST_INIT(&vp->v_cache_src);
553 TAILQ_INIT(&vp->v_cache_dst);
555 * Initialize rangelocks.
557 rangelock_init(&vp->v_rl);
562 * Free a vnode when it is cleared from the zone.
565 vnode_fini(void *mem, int size)
571 rangelock_destroy(&vp->v_rl);
572 lockdestroy(vp->v_vnlock);
573 mtx_destroy(&vp->v_interlock);
575 rw_destroy(BO_LOCKPTR(bo));
579 * Provide the size of NFS nclnode and NFS fh for calculation of the
580 * vnode memory consumption. The size is specified directly to
581 * eliminate dependency on NFS-private header.
583 * Other filesystems may use bigger or smaller (like UFS and ZFS)
584 * private inode data, but the NFS-based estimation is ample enough.
585 * Still, we care about differences in the size between 64- and 32-bit
588 * Namecache structure size is heuristically
589 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
592 #define NFS_NCLNODE_SZ (528 + 64)
595 #define NFS_NCLNODE_SZ (360 + 32)
600 vntblinit(void *dummy __unused)
603 int physvnodes, virtvnodes;
606 * Desiredvnodes is a function of the physical memory size and the
607 * kernel's heap size. Generally speaking, it scales with the
608 * physical memory size. The ratio of desiredvnodes to the physical
609 * memory size is 1:16 until desiredvnodes exceeds 98,304.
611 * marginal ratio of desiredvnodes to the physical memory size is
612 * 1:64. However, desiredvnodes is limited by the kernel's heap
613 * size. The memory required by desiredvnodes vnodes and vm objects
614 * must not exceed 1/10th of the kernel's heap size.
616 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
617 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
618 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
619 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
620 desiredvnodes = min(physvnodes, virtvnodes);
621 if (desiredvnodes > MAXVNODES_MAX) {
623 printf("Reducing kern.maxvnodes %lu -> %lu\n",
624 desiredvnodes, MAXVNODES_MAX);
625 desiredvnodes = MAXVNODES_MAX;
627 wantfreevnodes = desiredvnodes / 4;
628 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
629 TAILQ_INIT(&vnode_free_list);
630 mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
632 * The lock is taken to appease WITNESS.
634 mtx_lock(&vnode_free_list_mtx);
636 mtx_unlock(&vnode_free_list_mtx);
637 vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
638 vnode_init, vnode_fini, UMA_ALIGN_PTR, 0);
639 vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
640 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
642 * Preallocate enough nodes to support one-per buf so that
643 * we can not fail an insert. reassignbuf() callers can not
644 * tolerate the insertion failure.
646 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
647 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
648 UMA_ZONE_NOFREE | UMA_ZONE_VM);
649 uma_prealloc(buf_trie_zone, nbuf);
651 vnodes_created = counter_u64_alloc(M_WAITOK);
652 recycles_count = counter_u64_alloc(M_WAITOK);
653 recycles_free_count = counter_u64_alloc(M_WAITOK);
654 deferred_inact = counter_u64_alloc(M_WAITOK);
657 * Initialize the filesystem syncer.
659 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
661 syncer_maxdelay = syncer_mask + 1;
662 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
663 cv_init(&sync_wakeup, "syncer");
664 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
668 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
672 * Mark a mount point as busy. Used to synchronize access and to delay
673 * unmounting. Eventually, mountlist_mtx is not released on failure.
675 * vfs_busy() is a custom lock, it can block the caller.
676 * vfs_busy() only sleeps if the unmount is active on the mount point.
677 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
678 * vnode belonging to mp.
680 * Lookup uses vfs_busy() to traverse mount points.
682 * / vnode lock A / vnode lock (/var) D
683 * /var vnode lock B /log vnode lock(/var/log) E
684 * vfs_busy lock C vfs_busy lock F
686 * Within each file system, the lock order is C->A->B and F->D->E.
688 * When traversing across mounts, the system follows that lock order:
694 * The lookup() process for namei("/var") illustrates the process:
695 * VOP_LOOKUP() obtains B while A is held
696 * vfs_busy() obtains a shared lock on F while A and B are held
697 * vput() releases lock on B
698 * vput() releases lock on A
699 * VFS_ROOT() obtains lock on D while shared lock on F is held
700 * vfs_unbusy() releases shared lock on F
701 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
702 * Attempt to lock A (instead of vp_crossmp) while D is held would
703 * violate the global order, causing deadlocks.
705 * dounmount() locks B while F is drained.
708 vfs_busy(struct mount *mp, int flags)
711 MPASS((flags & ~MBF_MASK) == 0);
712 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
714 if (vfs_op_thread_enter(mp)) {
715 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
716 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
717 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
718 vfs_mp_count_add_pcpu(mp, ref, 1);
719 vfs_mp_count_add_pcpu(mp, lockref, 1);
720 vfs_op_thread_exit(mp);
721 if (flags & MBF_MNTLSTLOCK)
722 mtx_unlock(&mountlist_mtx);
727 vfs_assert_mount_counters(mp);
730 * If mount point is currently being unmounted, sleep until the
731 * mount point fate is decided. If thread doing the unmounting fails,
732 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
733 * that this mount point has survived the unmount attempt and vfs_busy
734 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
735 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
736 * about to be really destroyed. vfs_busy needs to release its
737 * reference on the mount point in this case and return with ENOENT,
738 * telling the caller that mount mount it tried to busy is no longer
741 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
742 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
745 CTR1(KTR_VFS, "%s: failed busying before sleeping",
749 if (flags & MBF_MNTLSTLOCK)
750 mtx_unlock(&mountlist_mtx);
751 mp->mnt_kern_flag |= MNTK_MWAIT;
752 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
753 if (flags & MBF_MNTLSTLOCK)
754 mtx_lock(&mountlist_mtx);
757 if (flags & MBF_MNTLSTLOCK)
758 mtx_unlock(&mountlist_mtx);
765 * Free a busy filesystem.
768 vfs_unbusy(struct mount *mp)
772 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
774 if (vfs_op_thread_enter(mp)) {
775 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
776 vfs_mp_count_sub_pcpu(mp, lockref, 1);
777 vfs_mp_count_sub_pcpu(mp, ref, 1);
778 vfs_op_thread_exit(mp);
783 vfs_assert_mount_counters(mp);
785 c = --mp->mnt_lockref;
786 if (mp->mnt_vfs_ops == 0) {
787 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
792 vfs_dump_mount_counters(mp);
793 if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
794 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
795 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
796 mp->mnt_kern_flag &= ~MNTK_DRAINING;
797 wakeup(&mp->mnt_lockref);
803 * Lookup a mount point by filesystem identifier.
806 vfs_getvfs(fsid_t *fsid)
810 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
811 mtx_lock(&mountlist_mtx);
812 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
813 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
814 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
816 mtx_unlock(&mountlist_mtx);
820 mtx_unlock(&mountlist_mtx);
821 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
822 return ((struct mount *) 0);
826 * Lookup a mount point by filesystem identifier, busying it before
829 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
830 * cache for popular filesystem identifiers. The cache is lockess, using
831 * the fact that struct mount's are never freed. In worst case we may
832 * get pointer to unmounted or even different filesystem, so we have to
833 * check what we got, and go slow way if so.
836 vfs_busyfs(fsid_t *fsid)
838 #define FSID_CACHE_SIZE 256
839 typedef struct mount * volatile vmp_t;
840 static vmp_t cache[FSID_CACHE_SIZE];
845 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
846 hash = fsid->val[0] ^ fsid->val[1];
847 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
850 mp->mnt_stat.f_fsid.val[0] != fsid->val[0] ||
851 mp->mnt_stat.f_fsid.val[1] != fsid->val[1])
853 if (vfs_busy(mp, 0) != 0) {
857 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
858 mp->mnt_stat.f_fsid.val[1] == fsid->val[1])
864 mtx_lock(&mountlist_mtx);
865 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
866 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
867 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
868 error = vfs_busy(mp, MBF_MNTLSTLOCK);
871 mtx_unlock(&mountlist_mtx);
878 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
879 mtx_unlock(&mountlist_mtx);
880 return ((struct mount *) 0);
884 * Check if a user can access privileged mount options.
887 vfs_suser(struct mount *mp, struct thread *td)
891 if (jailed(td->td_ucred)) {
893 * If the jail of the calling thread lacks permission for
894 * this type of file system, deny immediately.
896 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
900 * If the file system was mounted outside the jail of the
901 * calling thread, deny immediately.
903 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
908 * If file system supports delegated administration, we don't check
909 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
910 * by the file system itself.
911 * If this is not the user that did original mount, we check for
912 * the PRIV_VFS_MOUNT_OWNER privilege.
914 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
915 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
916 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
923 * Get a new unique fsid. Try to make its val[0] unique, since this value
924 * will be used to create fake device numbers for stat(). Also try (but
925 * not so hard) make its val[0] unique mod 2^16, since some emulators only
926 * support 16-bit device numbers. We end up with unique val[0]'s for the
927 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
929 * Keep in mind that several mounts may be running in parallel. Starting
930 * the search one past where the previous search terminated is both a
931 * micro-optimization and a defense against returning the same fsid to
935 vfs_getnewfsid(struct mount *mp)
937 static uint16_t mntid_base;
942 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
943 mtx_lock(&mntid_mtx);
944 mtype = mp->mnt_vfc->vfc_typenum;
945 tfsid.val[1] = mtype;
946 mtype = (mtype & 0xFF) << 24;
948 tfsid.val[0] = makedev(255,
949 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
951 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
955 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
956 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
957 mtx_unlock(&mntid_mtx);
961 * Knob to control the precision of file timestamps:
963 * 0 = seconds only; nanoseconds zeroed.
964 * 1 = seconds and nanoseconds, accurate within 1/HZ.
965 * 2 = seconds and nanoseconds, truncated to microseconds.
966 * >=3 = seconds and nanoseconds, maximum precision.
968 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
970 static int timestamp_precision = TSP_USEC;
971 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
972 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
973 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
974 "3+: sec + ns (max. precision))");
977 * Get a current timestamp.
980 vfs_timestamp(struct timespec *tsp)
984 switch (timestamp_precision) {
986 tsp->tv_sec = time_second;
994 TIMEVAL_TO_TIMESPEC(&tv, tsp);
1004 * Set vnode attributes to VNOVAL
1007 vattr_null(struct vattr *vap)
1010 vap->va_type = VNON;
1011 vap->va_size = VNOVAL;
1012 vap->va_bytes = VNOVAL;
1013 vap->va_mode = VNOVAL;
1014 vap->va_nlink = VNOVAL;
1015 vap->va_uid = VNOVAL;
1016 vap->va_gid = VNOVAL;
1017 vap->va_fsid = VNOVAL;
1018 vap->va_fileid = VNOVAL;
1019 vap->va_blocksize = VNOVAL;
1020 vap->va_rdev = VNOVAL;
1021 vap->va_atime.tv_sec = VNOVAL;
1022 vap->va_atime.tv_nsec = VNOVAL;
1023 vap->va_mtime.tv_sec = VNOVAL;
1024 vap->va_mtime.tv_nsec = VNOVAL;
1025 vap->va_ctime.tv_sec = VNOVAL;
1026 vap->va_ctime.tv_nsec = VNOVAL;
1027 vap->va_birthtime.tv_sec = VNOVAL;
1028 vap->va_birthtime.tv_nsec = VNOVAL;
1029 vap->va_flags = VNOVAL;
1030 vap->va_gen = VNOVAL;
1031 vap->va_vaflags = 0;
1035 * This routine is called when we have too many vnodes. It attempts
1036 * to free <count> vnodes and will potentially free vnodes that still
1037 * have VM backing store (VM backing store is typically the cause
1038 * of a vnode blowout so we want to do this). Therefore, this operation
1039 * is not considered cheap.
1041 * A number of conditions may prevent a vnode from being reclaimed.
1042 * the buffer cache may have references on the vnode, a directory
1043 * vnode may still have references due to the namei cache representing
1044 * underlying files, or the vnode may be in active use. It is not
1045 * desirable to reuse such vnodes. These conditions may cause the
1046 * number of vnodes to reach some minimum value regardless of what
1047 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
1049 * @param mp Try to reclaim vnodes from this mountpoint
1050 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1051 * entries if this argument is strue
1052 * @param trigger Only reclaim vnodes with fewer than this many resident
1054 * @return The number of vnodes that were reclaimed.
1057 vlrureclaim(struct mount *mp, bool reclaim_nc_src, int trigger)
1060 int count, done, target;
1063 vn_start_write(NULL, &mp, V_WAIT);
1065 count = mp->mnt_nvnodelistsize;
1066 target = count * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1067 target = target / 10 + 1;
1068 while (count != 0 && done < target) {
1069 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
1070 while (vp != NULL && vp->v_type == VMARKER)
1071 vp = TAILQ_NEXT(vp, v_nmntvnodes);
1075 * XXX LRU is completely broken for non-free vnodes. First
1076 * by calling here in mountpoint order, then by moving
1077 * unselected vnodes to the end here, and most grossly by
1078 * removing the vlruvp() function that was supposed to
1079 * maintain the order. (This function was born broken
1080 * since syncer problems prevented it doing anything.) The
1081 * order is closer to LRC (C = Created).
1083 * LRU reclaiming of vnodes seems to have last worked in
1084 * FreeBSD-3 where LRU wasn't mentioned under any spelling.
1085 * Then there was no hold count, and inactive vnodes were
1086 * simply put on the free list in LRU order. The separate
1087 * lists also break LRU. We prefer to reclaim from the
1088 * free list for technical reasons. This tends to thrash
1089 * the free list to keep very unrecently used held vnodes.
1090 * The problem is mitigated by keeping the free list large.
1092 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1093 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1095 if (!VI_TRYLOCK(vp))
1098 * If it's been deconstructed already, it's still
1099 * referenced, or it exceeds the trigger, skip it.
1100 * Also skip free vnodes. We are trying to make space
1101 * to expand the free list, not reduce it.
1103 if (vp->v_usecount ||
1104 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1105 ((vp->v_iflag & VI_FREE) != 0) ||
1106 VN_IS_DOOMED(vp) || (vp->v_object != NULL &&
1107 vp->v_object->resident_page_count > trigger)) {
1113 if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT)) {
1115 goto next_iter_mntunlocked;
1119 * v_usecount may have been bumped after VOP_LOCK() dropped
1120 * the vnode interlock and before it was locked again.
1122 * It is not necessary to recheck VIRF_DOOMED because it can
1123 * only be set by another thread that holds both the vnode
1124 * lock and vnode interlock. If another thread has the
1125 * vnode lock before we get to VOP_LOCK() and obtains the
1126 * vnode interlock after VOP_LOCK() drops the vnode
1127 * interlock, the other thread will be unable to drop the
1128 * vnode lock before our VOP_LOCK() call fails.
1130 if (vp->v_usecount ||
1131 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1132 (vp->v_object != NULL &&
1133 vp->v_object->resident_page_count > trigger)) {
1136 goto next_iter_mntunlocked;
1138 KASSERT(!VN_IS_DOOMED(vp),
1139 ("VIRF_DOOMED unexpectedly detected in vlrureclaim()"));
1140 counter_u64_add(recycles_count, 1);
1145 next_iter_mntunlocked:
1146 if (!should_yield())
1150 if (!should_yield())
1154 kern_yield(PRI_USER);
1159 vn_finished_write(mp);
1163 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1164 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1166 "limit on vnode free requests per call to the vnlru_free routine");
1169 * Attempt to reduce the free list by the requested amount.
1172 vnlru_free_locked(int count, struct vfsops *mnt_op)
1178 tried_batches = false;
1179 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
1180 if (count > max_vnlru_free)
1181 count = max_vnlru_free;
1182 for (; count > 0; count--) {
1183 vp = TAILQ_FIRST(&vnode_free_list);
1185 * The list can be modified while the free_list_mtx
1186 * has been dropped and vp could be NULL here.
1191 mtx_unlock(&vnode_free_list_mtx);
1192 vnlru_return_batches(mnt_op);
1193 tried_batches = true;
1194 mtx_lock(&vnode_free_list_mtx);
1198 VNASSERT(vp->v_op != NULL, vp,
1199 ("vnlru_free: vnode already reclaimed."));
1200 KASSERT((vp->v_iflag & VI_FREE) != 0,
1201 ("Removing vnode not on freelist"));
1202 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1203 ("Mangling active vnode"));
1204 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
1207 * Don't recycle if our vnode is from different type
1208 * of mount point. Note that mp is type-safe, the
1209 * check does not reach unmapped address even if
1210 * vnode is reclaimed.
1211 * Don't recycle if we can't get the interlock without
1214 if ((mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1215 mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
1216 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_actfreelist);
1219 VNASSERT((vp->v_iflag & VI_FREE) != 0 && vp->v_holdcnt == 0,
1220 vp, ("vp inconsistent on freelist"));
1223 * The clear of VI_FREE prevents activation of the
1224 * vnode. There is no sense in putting the vnode on
1225 * the mount point active list, only to remove it
1226 * later during recycling. Inline the relevant part
1227 * of vholdl(), to avoid triggering assertions or
1231 vp->v_iflag &= ~VI_FREE;
1232 VNODE_REFCOUNT_FENCE_REL();
1233 refcount_acquire(&vp->v_holdcnt);
1235 mtx_unlock(&vnode_free_list_mtx);
1239 * If the recycled succeeded this vdrop will actually free
1240 * the vnode. If not it will simply place it back on
1244 mtx_lock(&vnode_free_list_mtx);
1249 vnlru_free(int count, struct vfsops *mnt_op)
1252 mtx_lock(&vnode_free_list_mtx);
1253 vnlru_free_locked(count, mnt_op);
1254 mtx_unlock(&vnode_free_list_mtx);
1261 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
1262 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1263 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1264 vlowat = vhiwat / 2;
1267 /* XXX some names and initialization are bad for limits and watermarks. */
1271 u_long rnumvnodes, rfreevnodes;
1274 rnumvnodes = atomic_load_long(&numvnodes);
1275 rfreevnodes = atomic_load_long(&freevnodes);
1276 if (rnumvnodes > desiredvnodes)
1278 space = desiredvnodes - rnumvnodes;
1279 if (freevnodes > wantfreevnodes)
1280 space += rfreevnodes - wantfreevnodes;
1285 vnlru_return_batch_locked(struct mount *mp)
1289 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
1291 if (mp->mnt_tmpfreevnodelistsize == 0)
1294 TAILQ_FOREACH(vp, &mp->mnt_tmpfreevnodelist, v_actfreelist) {
1295 VNASSERT((vp->v_mflag & VMP_TMPMNTFREELIST) != 0, vp,
1296 ("vnode without VMP_TMPMNTFREELIST on mnt_tmpfreevnodelist"));
1297 vp->v_mflag &= ~VMP_TMPMNTFREELIST;
1299 mtx_lock(&vnode_free_list_mtx);
1300 TAILQ_CONCAT(&vnode_free_list, &mp->mnt_tmpfreevnodelist, v_actfreelist);
1301 freevnodes += mp->mnt_tmpfreevnodelistsize;
1302 mtx_unlock(&vnode_free_list_mtx);
1303 mp->mnt_tmpfreevnodelistsize = 0;
1307 vnlru_return_batch(struct mount *mp)
1310 mtx_lock(&mp->mnt_listmtx);
1311 vnlru_return_batch_locked(mp);
1312 mtx_unlock(&mp->mnt_listmtx);
1316 vnlru_return_batches(struct vfsops *mnt_op)
1318 struct mount *mp, *nmp;
1321 mtx_lock(&mountlist_mtx);
1322 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1323 need_unbusy = false;
1324 if (mnt_op != NULL && mp->mnt_op != mnt_op)
1326 if (mp->mnt_tmpfreevnodelistsize == 0)
1328 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK) == 0) {
1329 vnlru_return_batch(mp);
1331 mtx_lock(&mountlist_mtx);
1334 nmp = TAILQ_NEXT(mp, mnt_list);
1338 mtx_unlock(&mountlist_mtx);
1342 * Attempt to recycle vnodes in a context that is always safe to block.
1343 * Calling vlrurecycle() from the bowels of filesystem code has some
1344 * interesting deadlock problems.
1346 static struct proc *vnlruproc;
1347 static int vnlruproc_sig;
1352 u_long rnumvnodes, rfreevnodes;
1353 struct mount *mp, *nmp;
1354 unsigned long onumvnodes;
1355 int done, force, trigger, usevnodes, vsp;
1356 bool reclaim_nc_src;
1358 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1359 SHUTDOWN_PRI_FIRST);
1363 kproc_suspend_check(vnlruproc);
1364 mtx_lock(&vnode_free_list_mtx);
1365 rnumvnodes = atomic_load_long(&numvnodes);
1367 * If numvnodes is too large (due to desiredvnodes being
1368 * adjusted using its sysctl, or emergency growth), first
1369 * try to reduce it by discarding from the free list.
1371 if (rnumvnodes > desiredvnodes)
1372 vnlru_free_locked(rnumvnodes - desiredvnodes, NULL);
1374 * Sleep if the vnode cache is in a good state. This is
1375 * when it is not over-full and has space for about a 4%
1376 * or 9% expansion (by growing its size or inexcessively
1377 * reducing its free list). Otherwise, try to reclaim
1378 * space for a 10% expansion.
1380 if (vstir && force == 0) {
1385 if (vsp >= vlowat && force == 0) {
1387 wakeup(&vnlruproc_sig);
1388 msleep(vnlruproc, &vnode_free_list_mtx,
1389 PVFS|PDROP, "vlruwt", hz);
1392 mtx_unlock(&vnode_free_list_mtx);
1394 rnumvnodes = atomic_load_long(&numvnodes);
1395 rfreevnodes = atomic_load_long(&freevnodes);
1397 onumvnodes = rnumvnodes;
1399 * Calculate parameters for recycling. These are the same
1400 * throughout the loop to give some semblance of fairness.
1401 * The trigger point is to avoid recycling vnodes with lots
1402 * of resident pages. We aren't trying to free memory; we
1403 * are trying to recycle or at least free vnodes.
1405 if (rnumvnodes <= desiredvnodes)
1406 usevnodes = rnumvnodes - rfreevnodes;
1408 usevnodes = rnumvnodes;
1412 * The trigger value is is chosen to give a conservatively
1413 * large value to ensure that it alone doesn't prevent
1414 * making progress. The value can easily be so large that
1415 * it is effectively infinite in some congested and
1416 * misconfigured cases, and this is necessary. Normally
1417 * it is about 8 to 100 (pages), which is quite large.
1419 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1421 trigger = vsmalltrigger;
1422 reclaim_nc_src = force >= 3;
1423 mtx_lock(&mountlist_mtx);
1424 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1425 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK)) {
1426 nmp = TAILQ_NEXT(mp, mnt_list);
1429 done += vlrureclaim(mp, reclaim_nc_src, trigger);
1430 mtx_lock(&mountlist_mtx);
1431 nmp = TAILQ_NEXT(mp, mnt_list);
1434 mtx_unlock(&mountlist_mtx);
1435 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1436 uma_reclaim(UMA_RECLAIM_DRAIN);
1438 if (force == 0 || force == 1) {
1448 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1450 kern_yield(PRI_USER);
1452 * After becoming active to expand above low water, keep
1453 * active until above high water.
1456 force = vsp < vhiwat;
1460 static struct kproc_desc vnlru_kp = {
1465 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1469 * Routines having to do with the management of the vnode table.
1473 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1474 * before we actually vgone(). This function must be called with the vnode
1475 * held to prevent the vnode from being returned to the free list midway
1479 vtryrecycle(struct vnode *vp)
1483 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1484 VNASSERT(vp->v_holdcnt, vp,
1485 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1487 * This vnode may found and locked via some other list, if so we
1488 * can't recycle it yet.
1490 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1492 "%s: impossible to recycle, vp %p lock is already held",
1494 return (EWOULDBLOCK);
1497 * Don't recycle if its filesystem is being suspended.
1499 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1502 "%s: impossible to recycle, cannot start the write for %p",
1507 * If we got this far, we need to acquire the interlock and see if
1508 * anyone picked up this vnode from another list. If not, we will
1509 * mark it with DOOMED via vgonel() so that anyone who does find it
1510 * will skip over it.
1513 if (vp->v_usecount) {
1516 vn_finished_write(vnmp);
1518 "%s: impossible to recycle, %p is already referenced",
1522 if (!VN_IS_DOOMED(vp)) {
1523 counter_u64_add(recycles_free_count, 1);
1528 vn_finished_write(vnmp);
1538 if (vsp < vlowat && vnlruproc_sig == 0) {
1545 * Wait if necessary for space for a new vnode.
1548 vn_alloc_wait(int suspended)
1551 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
1552 if (numvnodes >= desiredvnodes) {
1555 * The file system is being suspended. We cannot
1556 * risk a deadlock here, so allow allocation of
1557 * another vnode even if this would give too many.
1561 if (vnlruproc_sig == 0) {
1562 vnlruproc_sig = 1; /* avoid unnecessary wakeups */
1565 msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
1568 /* Post-adjust like the pre-adjust in getnewvnode(). */
1569 if (numvnodes + 1 > desiredvnodes && freevnodes > 1)
1570 vnlru_free_locked(1, NULL);
1571 return (numvnodes >= desiredvnodes ? ENFILE : 0);
1574 static struct vnode *
1575 vn_alloc(struct mount *mp)
1577 static int cyclecount;
1580 mtx_lock(&vnode_free_list_mtx);
1581 if (numvnodes < desiredvnodes)
1583 else if (cyclecount++ >= freevnodes) {
1588 * Grow the vnode cache if it will not be above its target max
1589 * after growing. Otherwise, if the free list is nonempty, try
1590 * to reclaim 1 item from it before growing the cache (possibly
1591 * above its target max if the reclamation failed or is delayed).
1592 * Otherwise, wait for some space. In all cases, schedule
1593 * vnlru_proc() if we are getting short of space. The watermarks
1594 * should be chosen so that we never wait or even reclaim from
1595 * the free list to below its target minimum.
1597 if (numvnodes + 1 <= desiredvnodes)
1599 else if (freevnodes > 0)
1600 vnlru_free_locked(1, NULL);
1602 error = vn_alloc_wait(mp != NULL && (mp->mnt_kern_flag &
1604 #if 0 /* XXX Not all VFS_VGET/ffs_vget callers check returns. */
1606 mtx_unlock(&vnode_free_list_mtx);
1612 atomic_add_long(&numvnodes, 1);
1613 mtx_unlock(&vnode_free_list_mtx);
1614 return (uma_zalloc(vnode_zone, M_WAITOK));
1618 vn_free(struct vnode *vp)
1621 atomic_subtract_long(&numvnodes, 1);
1622 uma_zfree(vnode_zone, vp);
1626 * Return the next vnode from the free list.
1629 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1634 struct lock_object *lo;
1636 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1638 KASSERT(vops->registered,
1639 ("%s: not registered vector op %p\n", __func__, vops));
1642 if (td->td_vp_reserved != NULL) {
1643 vp = td->td_vp_reserved;
1644 td->td_vp_reserved = NULL;
1648 counter_u64_add(vnodes_created, 1);
1650 * Locks are given the generic name "vnode" when created.
1651 * Follow the historic practice of using the filesystem
1652 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1654 * Locks live in a witness group keyed on their name. Thus,
1655 * when a lock is renamed, it must also move from the witness
1656 * group of its old name to the witness group of its new name.
1658 * The change only needs to be made when the vnode moves
1659 * from one filesystem type to another. We ensure that each
1660 * filesystem use a single static name pointer for its tag so
1661 * that we can compare pointers rather than doing a strcmp().
1663 lo = &vp->v_vnlock->lock_object;
1664 if (lo->lo_name != tag) {
1666 WITNESS_DESTROY(lo);
1667 WITNESS_INIT(lo, tag);
1670 * By default, don't allow shared locks unless filesystems opt-in.
1672 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1674 * Finalize various vnode identity bits.
1676 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1677 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1678 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1681 v_init_counters(vp);
1682 vp->v_bufobj.bo_ops = &buf_ops_bio;
1684 if (mp == NULL && vops != &dead_vnodeops)
1685 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1689 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1690 mac_vnode_associate_singlelabel(mp, vp);
1693 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1694 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1695 vp->v_vflag |= VV_NOKNOTE;
1699 * For the filesystems which do not use vfs_hash_insert(),
1700 * still initialize v_hash to have vfs_hash_index() useful.
1701 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1704 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1711 getnewvnode_reserve(void)
1716 MPASS(td->td_vp_reserved == NULL);
1717 td->td_vp_reserved = vn_alloc(NULL);
1721 getnewvnode_drop_reserve(void)
1726 if (td->td_vp_reserved != NULL) {
1727 vn_free(td->td_vp_reserved);
1728 td->td_vp_reserved = NULL;
1733 freevnode(struct vnode *vp)
1738 * The vnode has been marked for destruction, so free it.
1740 * The vnode will be returned to the zone where it will
1741 * normally remain until it is needed for another vnode. We
1742 * need to cleanup (or verify that the cleanup has already
1743 * been done) any residual data left from its current use
1744 * so as not to contaminate the freshly allocated vnode.
1746 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1748 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
1749 ("cleaned vnode still on the free list."));
1750 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1751 VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
1752 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1753 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1754 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1755 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1756 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1757 ("clean blk trie not empty"));
1758 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1759 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1760 ("dirty blk trie not empty"));
1761 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1762 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1763 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1764 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1765 ("Dangling rangelock waiters"));
1768 mac_vnode_destroy(vp);
1770 if (vp->v_pollinfo != NULL) {
1771 destroy_vpollinfo(vp->v_pollinfo);
1772 vp->v_pollinfo = NULL;
1775 /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
1778 vp->v_mountedhere = NULL;
1781 vp->v_fifoinfo = NULL;
1782 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
1791 * Delete from old mount point vnode list, if on one.
1794 delmntque(struct vnode *vp)
1803 KASSERT(mp->mnt_activevnodelistsize <= mp->mnt_nvnodelistsize,
1804 ("Active vnode list size %d > Vnode list size %d",
1805 mp->mnt_activevnodelistsize, mp->mnt_nvnodelistsize));
1806 if (vp->v_iflag & VI_ACTIVE) {
1807 vp->v_iflag &= ~VI_ACTIVE;
1808 mtx_lock(&mp->mnt_listmtx);
1809 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp, v_actfreelist);
1810 mp->mnt_activevnodelistsize--;
1811 mtx_unlock(&mp->mnt_listmtx);
1815 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1816 ("bad mount point vnode list size"));
1817 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1818 mp->mnt_nvnodelistsize--;
1824 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1828 vp->v_op = &dead_vnodeops;
1834 * Insert into list of vnodes for the new mount point, if available.
1837 insmntque1(struct vnode *vp, struct mount *mp,
1838 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1841 KASSERT(vp->v_mount == NULL,
1842 ("insmntque: vnode already on per mount vnode list"));
1843 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1844 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1847 * We acquire the vnode interlock early to ensure that the
1848 * vnode cannot be recycled by another process releasing a
1849 * holdcnt on it before we get it on both the vnode list
1850 * and the active vnode list. The mount mutex protects only
1851 * manipulation of the vnode list and the vnode freelist
1852 * mutex protects only manipulation of the active vnode list.
1853 * Hence the need to hold the vnode interlock throughout.
1857 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1858 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1859 mp->mnt_nvnodelistsize == 0)) &&
1860 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1869 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1870 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1871 ("neg mount point vnode list size"));
1872 mp->mnt_nvnodelistsize++;
1873 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1874 ("Activating already active vnode"));
1875 vp->v_iflag |= VI_ACTIVE;
1876 mtx_lock(&mp->mnt_listmtx);
1877 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
1878 mp->mnt_activevnodelistsize++;
1879 mtx_unlock(&mp->mnt_listmtx);
1886 insmntque(struct vnode *vp, struct mount *mp)
1889 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1893 * Flush out and invalidate all buffers associated with a bufobj
1894 * Called with the underlying object locked.
1897 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1902 if (flags & V_SAVE) {
1903 error = bufobj_wwait(bo, slpflag, slptimeo);
1908 if (bo->bo_dirty.bv_cnt > 0) {
1910 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1913 * XXX We could save a lock/unlock if this was only
1914 * enabled under INVARIANTS
1917 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1918 panic("vinvalbuf: dirty bufs");
1922 * If you alter this loop please notice that interlock is dropped and
1923 * reacquired in flushbuflist. Special care is needed to ensure that
1924 * no race conditions occur from this.
1927 error = flushbuflist(&bo->bo_clean,
1928 flags, bo, slpflag, slptimeo);
1929 if (error == 0 && !(flags & V_CLEANONLY))
1930 error = flushbuflist(&bo->bo_dirty,
1931 flags, bo, slpflag, slptimeo);
1932 if (error != 0 && error != EAGAIN) {
1936 } while (error != 0);
1939 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1940 * have write I/O in-progress but if there is a VM object then the
1941 * VM object can also have read-I/O in-progress.
1944 bufobj_wwait(bo, 0, 0);
1945 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
1947 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
1950 } while (bo->bo_numoutput > 0);
1954 * Destroy the copy in the VM cache, too.
1956 if (bo->bo_object != NULL &&
1957 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1958 VM_OBJECT_WLOCK(bo->bo_object);
1959 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1960 OBJPR_CLEANONLY : 0);
1961 VM_OBJECT_WUNLOCK(bo->bo_object);
1966 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1967 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1968 bo->bo_clean.bv_cnt > 0))
1969 panic("vinvalbuf: flush failed");
1970 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1971 bo->bo_dirty.bv_cnt > 0)
1972 panic("vinvalbuf: flush dirty failed");
1979 * Flush out and invalidate all buffers associated with a vnode.
1980 * Called with the underlying object locked.
1983 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1986 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1987 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1988 if (vp->v_object != NULL && vp->v_object->handle != vp)
1990 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1994 * Flush out buffers on the specified list.
1998 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
2001 struct buf *bp, *nbp;
2006 ASSERT_BO_WLOCKED(bo);
2009 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2011 * If we are flushing both V_NORMAL and V_ALT buffers then
2012 * do not skip any buffers. If we are flushing only V_NORMAL
2013 * buffers then skip buffers marked as BX_ALTDATA. If we are
2014 * flushing only V_ALT buffers then skip buffers not marked
2017 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2018 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2019 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2023 lblkno = nbp->b_lblkno;
2024 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2027 error = BUF_TIMELOCK(bp,
2028 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2029 "flushbuf", slpflag, slptimeo);
2032 return (error != ENOLCK ? error : EAGAIN);
2034 KASSERT(bp->b_bufobj == bo,
2035 ("bp %p wrong b_bufobj %p should be %p",
2036 bp, bp->b_bufobj, bo));
2038 * XXX Since there are no node locks for NFS, I
2039 * believe there is a slight chance that a delayed
2040 * write will occur while sleeping just above, so
2043 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2046 bp->b_flags |= B_ASYNC;
2049 return (EAGAIN); /* XXX: why not loop ? */
2052 bp->b_flags |= (B_INVAL | B_RELBUF);
2053 bp->b_flags &= ~B_ASYNC;
2058 nbp = gbincore(bo, lblkno);
2059 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2061 break; /* nbp invalid */
2067 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2073 ASSERT_BO_LOCKED(bo);
2075 for (lblkno = startn;;) {
2077 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2078 if (bp == NULL || bp->b_lblkno >= endn ||
2079 bp->b_lblkno < startn)
2081 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2082 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2085 if (error == ENOLCK)
2089 KASSERT(bp->b_bufobj == bo,
2090 ("bp %p wrong b_bufobj %p should be %p",
2091 bp, bp->b_bufobj, bo));
2092 lblkno = bp->b_lblkno + 1;
2093 if ((bp->b_flags & B_MANAGED) == 0)
2095 bp->b_flags |= B_RELBUF;
2097 * In the VMIO case, use the B_NOREUSE flag to hint that the
2098 * pages backing each buffer in the range are unlikely to be
2099 * reused. Dirty buffers will have the hint applied once
2100 * they've been written.
2102 if ((bp->b_flags & B_VMIO) != 0)
2103 bp->b_flags |= B_NOREUSE;
2111 * Truncate a file's buffer and pages to a specified length. This
2112 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2116 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2118 struct buf *bp, *nbp;
2122 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2123 vp, blksize, (uintmax_t)length);
2126 * Round up to the *next* lbn.
2128 startlbn = howmany(length, blksize);
2130 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2136 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2141 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2142 if (bp->b_lblkno > 0)
2145 * Since we hold the vnode lock this should only
2146 * fail if we're racing with the buf daemon.
2149 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2150 BO_LOCKPTR(bo)) == ENOLCK)
2151 goto restart_unlocked;
2153 VNASSERT((bp->b_flags & B_DELWRI), vp,
2154 ("buf(%p) on dirty queue without DELWRI", bp));
2163 bufobj_wwait(bo, 0, 0);
2165 vnode_pager_setsize(vp, length);
2171 * Invalidate the cached pages of a file's buffer within the range of block
2172 * numbers [startlbn, endlbn).
2175 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2181 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2183 start = blksize * startlbn;
2184 end = blksize * endlbn;
2188 MPASS(blksize == bo->bo_bsize);
2190 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2194 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2198 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2199 daddr_t startlbn, daddr_t endlbn)
2201 struct buf *bp, *nbp;
2204 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2205 ASSERT_BO_LOCKED(bo);
2209 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2210 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2213 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2214 BO_LOCKPTR(bo)) == ENOLCK) {
2220 bp->b_flags |= B_INVAL | B_RELBUF;
2221 bp->b_flags &= ~B_ASYNC;
2227 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2229 (nbp->b_flags & B_DELWRI) != 0))
2233 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2234 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2237 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2238 BO_LOCKPTR(bo)) == ENOLCK) {
2243 bp->b_flags |= B_INVAL | B_RELBUF;
2244 bp->b_flags &= ~B_ASYNC;
2250 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2251 (nbp->b_vp != vp) ||
2252 (nbp->b_flags & B_DELWRI) == 0))
2260 buf_vlist_remove(struct buf *bp)
2264 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2265 ASSERT_BO_WLOCKED(bp->b_bufobj);
2266 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
2267 (BX_VNDIRTY|BX_VNCLEAN),
2268 ("buf_vlist_remove: Buf %p is on two lists", bp));
2269 if (bp->b_xflags & BX_VNDIRTY)
2270 bv = &bp->b_bufobj->bo_dirty;
2272 bv = &bp->b_bufobj->bo_clean;
2273 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2274 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2276 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2280 * Add the buffer to the sorted clean or dirty block list.
2282 * NOTE: xflags is passed as a constant, optimizing this inline function!
2285 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2291 ASSERT_BO_WLOCKED(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 * Associate a buffer with a vnode.
2339 bgetvp(struct vnode *vp, struct buf *bp)
2344 ASSERT_BO_WLOCKED(bo);
2345 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2347 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2348 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2349 ("bgetvp: bp already attached! %p", bp));
2355 * Insert onto list for new vnode.
2357 buf_vlist_add(bp, bo, BX_VNCLEAN);
2361 * Disassociate a buffer from a vnode.
2364 brelvp(struct buf *bp)
2369 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2370 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2373 * Delete from old vnode list, if on one.
2375 vp = bp->b_vp; /* XXX */
2378 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2379 buf_vlist_remove(bp);
2381 panic("brelvp: Buffer %p not on queue.", bp);
2382 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2383 bo->bo_flag &= ~BO_ONWORKLST;
2384 mtx_lock(&sync_mtx);
2385 LIST_REMOVE(bo, bo_synclist);
2386 syncer_worklist_len--;
2387 mtx_unlock(&sync_mtx);
2390 bp->b_bufobj = NULL;
2396 * Add an item to the syncer work queue.
2399 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2403 ASSERT_BO_WLOCKED(bo);
2405 mtx_lock(&sync_mtx);
2406 if (bo->bo_flag & BO_ONWORKLST)
2407 LIST_REMOVE(bo, bo_synclist);
2409 bo->bo_flag |= BO_ONWORKLST;
2410 syncer_worklist_len++;
2413 if (delay > syncer_maxdelay - 2)
2414 delay = syncer_maxdelay - 2;
2415 slot = (syncer_delayno + delay) & syncer_mask;
2417 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2418 mtx_unlock(&sync_mtx);
2422 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2426 mtx_lock(&sync_mtx);
2427 len = syncer_worklist_len - sync_vnode_count;
2428 mtx_unlock(&sync_mtx);
2429 error = SYSCTL_OUT(req, &len, sizeof(len));
2433 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2434 CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2435 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2437 static struct proc *updateproc;
2438 static void sched_sync(void);
2439 static struct kproc_desc up_kp = {
2444 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2447 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2452 *bo = LIST_FIRST(slp);
2456 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2459 * We use vhold in case the vnode does not
2460 * successfully sync. vhold prevents the vnode from
2461 * going away when we unlock the sync_mtx so that
2462 * we can acquire the vnode interlock.
2465 mtx_unlock(&sync_mtx);
2467 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2469 mtx_lock(&sync_mtx);
2470 return (*bo == LIST_FIRST(slp));
2472 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2473 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2475 vn_finished_write(mp);
2477 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2479 * Put us back on the worklist. The worklist
2480 * routine will remove us from our current
2481 * position and then add us back in at a later
2484 vn_syncer_add_to_worklist(*bo, syncdelay);
2488 mtx_lock(&sync_mtx);
2492 static int first_printf = 1;
2495 * System filesystem synchronizer daemon.
2500 struct synclist *next, *slp;
2503 struct thread *td = curthread;
2505 int net_worklist_len;
2506 int syncer_final_iter;
2510 syncer_final_iter = 0;
2511 syncer_state = SYNCER_RUNNING;
2512 starttime = time_uptime;
2513 td->td_pflags |= TDP_NORUNNINGBUF;
2515 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2518 mtx_lock(&sync_mtx);
2520 if (syncer_state == SYNCER_FINAL_DELAY &&
2521 syncer_final_iter == 0) {
2522 mtx_unlock(&sync_mtx);
2523 kproc_suspend_check(td->td_proc);
2524 mtx_lock(&sync_mtx);
2526 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2527 if (syncer_state != SYNCER_RUNNING &&
2528 starttime != time_uptime) {
2530 printf("\nSyncing disks, vnodes remaining... ");
2533 printf("%d ", net_worklist_len);
2535 starttime = time_uptime;
2538 * Push files whose dirty time has expired. Be careful
2539 * of interrupt race on slp queue.
2541 * Skip over empty worklist slots when shutting down.
2544 slp = &syncer_workitem_pending[syncer_delayno];
2545 syncer_delayno += 1;
2546 if (syncer_delayno == syncer_maxdelay)
2548 next = &syncer_workitem_pending[syncer_delayno];
2550 * If the worklist has wrapped since the
2551 * it was emptied of all but syncer vnodes,
2552 * switch to the FINAL_DELAY state and run
2553 * for one more second.
2555 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2556 net_worklist_len == 0 &&
2557 last_work_seen == syncer_delayno) {
2558 syncer_state = SYNCER_FINAL_DELAY;
2559 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2561 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2562 syncer_worklist_len > 0);
2565 * Keep track of the last time there was anything
2566 * on the worklist other than syncer vnodes.
2567 * Return to the SHUTTING_DOWN state if any
2570 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2571 last_work_seen = syncer_delayno;
2572 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2573 syncer_state = SYNCER_SHUTTING_DOWN;
2574 while (!LIST_EMPTY(slp)) {
2575 error = sync_vnode(slp, &bo, td);
2577 LIST_REMOVE(bo, bo_synclist);
2578 LIST_INSERT_HEAD(next, bo, bo_synclist);
2582 if (first_printf == 0) {
2584 * Drop the sync mutex, because some watchdog
2585 * drivers need to sleep while patting
2587 mtx_unlock(&sync_mtx);
2588 wdog_kern_pat(WD_LASTVAL);
2589 mtx_lock(&sync_mtx);
2593 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2594 syncer_final_iter--;
2596 * The variable rushjob allows the kernel to speed up the
2597 * processing of the filesystem syncer process. A rushjob
2598 * value of N tells the filesystem syncer to process the next
2599 * N seconds worth of work on its queue ASAP. Currently rushjob
2600 * is used by the soft update code to speed up the filesystem
2601 * syncer process when the incore state is getting so far
2602 * ahead of the disk that the kernel memory pool is being
2603 * threatened with exhaustion.
2610 * Just sleep for a short period of time between
2611 * iterations when shutting down to allow some I/O
2614 * If it has taken us less than a second to process the
2615 * current work, then wait. Otherwise start right over
2616 * again. We can still lose time if any single round
2617 * takes more than two seconds, but it does not really
2618 * matter as we are just trying to generally pace the
2619 * filesystem activity.
2621 if (syncer_state != SYNCER_RUNNING ||
2622 time_uptime == starttime) {
2624 sched_prio(td, PPAUSE);
2627 if (syncer_state != SYNCER_RUNNING)
2628 cv_timedwait(&sync_wakeup, &sync_mtx,
2629 hz / SYNCER_SHUTDOWN_SPEEDUP);
2630 else if (time_uptime == starttime)
2631 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2636 * Request the syncer daemon to speed up its work.
2637 * We never push it to speed up more than half of its
2638 * normal turn time, otherwise it could take over the cpu.
2641 speedup_syncer(void)
2645 mtx_lock(&sync_mtx);
2646 if (rushjob < syncdelay / 2) {
2648 stat_rush_requests += 1;
2651 mtx_unlock(&sync_mtx);
2652 cv_broadcast(&sync_wakeup);
2657 * Tell the syncer to speed up its work and run though its work
2658 * list several times, then tell it to shut down.
2661 syncer_shutdown(void *arg, int howto)
2664 if (howto & RB_NOSYNC)
2666 mtx_lock(&sync_mtx);
2667 syncer_state = SYNCER_SHUTTING_DOWN;
2669 mtx_unlock(&sync_mtx);
2670 cv_broadcast(&sync_wakeup);
2671 kproc_shutdown(arg, howto);
2675 syncer_suspend(void)
2678 syncer_shutdown(updateproc, 0);
2685 mtx_lock(&sync_mtx);
2687 syncer_state = SYNCER_RUNNING;
2688 mtx_unlock(&sync_mtx);
2689 cv_broadcast(&sync_wakeup);
2690 kproc_resume(updateproc);
2694 * Reassign a buffer from one vnode to another.
2695 * Used to assign file specific control information
2696 * (indirect blocks) to the vnode to which they belong.
2699 reassignbuf(struct buf *bp)
2712 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2713 bp, bp->b_vp, bp->b_flags);
2715 * B_PAGING flagged buffers cannot be reassigned because their vp
2716 * is not fully linked in.
2718 if (bp->b_flags & B_PAGING)
2719 panic("cannot reassign paging buffer");
2722 * Delete from old vnode list, if on one.
2725 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2726 buf_vlist_remove(bp);
2728 panic("reassignbuf: Buffer %p not on queue.", bp);
2730 * If dirty, put on list of dirty buffers; otherwise insert onto list
2733 if (bp->b_flags & B_DELWRI) {
2734 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2735 switch (vp->v_type) {
2745 vn_syncer_add_to_worklist(bo, delay);
2747 buf_vlist_add(bp, bo, BX_VNDIRTY);
2749 buf_vlist_add(bp, bo, BX_VNCLEAN);
2751 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2752 mtx_lock(&sync_mtx);
2753 LIST_REMOVE(bo, bo_synclist);
2754 syncer_worklist_len--;
2755 mtx_unlock(&sync_mtx);
2756 bo->bo_flag &= ~BO_ONWORKLST;
2761 bp = TAILQ_FIRST(&bv->bv_hd);
2762 KASSERT(bp == NULL || bp->b_bufobj == bo,
2763 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2764 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2765 KASSERT(bp == NULL || bp->b_bufobj == bo,
2766 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2768 bp = TAILQ_FIRST(&bv->bv_hd);
2769 KASSERT(bp == NULL || bp->b_bufobj == bo,
2770 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2771 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2772 KASSERT(bp == NULL || bp->b_bufobj == bo,
2773 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2779 v_init_counters(struct vnode *vp)
2782 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2783 vp, ("%s called for an initialized vnode", __FUNCTION__));
2784 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2786 refcount_init(&vp->v_holdcnt, 1);
2787 refcount_init(&vp->v_usecount, 1);
2791 * Increment si_usecount of the associated device, if any.
2794 v_incr_devcount(struct vnode *vp)
2797 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2798 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2800 vp->v_rdev->si_usecount++;
2806 * Decrement si_usecount of the associated device, if any.
2809 v_decr_devcount(struct vnode *vp)
2812 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2813 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2815 vp->v_rdev->si_usecount--;
2821 * Grab a particular vnode from the free list, increment its
2822 * reference count and lock it. VIRF_DOOMED is set if the vnode
2823 * is being destroyed. Only callers who specify LK_RETRY will
2824 * see doomed vnodes. If inactive processing was delayed in
2825 * vput try to do it here.
2827 * Both holdcnt and usecount can be manipulated using atomics without holding
2828 * any locks except in these cases which require the vnode interlock:
2829 * holdcnt: 1->0 and 0->1
2832 * usecount is permitted to transition 1->0 without the interlock because
2833 * vnode is kept live by holdcnt.
2835 static enum vgetstate __always_inline
2836 _vget_prep(struct vnode *vp, bool interlock)
2840 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2853 vget_prep(struct vnode *vp)
2856 return (_vget_prep(vp, false));
2860 vget(struct vnode *vp, int flags, struct thread *td)
2864 MPASS(td == curthread);
2866 vs = _vget_prep(vp, (flags & LK_INTERLOCK) != 0);
2867 return (vget_finish(vp, flags, vs));
2871 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
2873 int error, oweinact;
2875 VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2876 ("%s: invalid lock operation", __func__));
2878 if ((flags & LK_INTERLOCK) != 0)
2879 ASSERT_VI_LOCKED(vp, __func__);
2881 ASSERT_VI_UNLOCKED(vp, __func__);
2882 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
2883 if (vs == VGET_USECOUNT) {
2884 VNASSERT(vp->v_usecount > 0, vp,
2885 ("%s: vnode without usecount when VGET_USECOUNT was passed",
2889 if ((error = vn_lock(vp, flags)) != 0) {
2890 if (vs == VGET_USECOUNT)
2894 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2899 if (vs == VGET_USECOUNT) {
2900 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2901 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2906 * We hold the vnode. If the usecount is 0 it will be utilized to keep
2907 * the vnode around. Otherwise someone else lended their hold count and
2908 * we have to drop ours.
2910 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2912 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2913 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2915 refcount_release(&vp->v_holdcnt);
2917 VNODE_REFCOUNT_FENCE_ACQ();
2918 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2919 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2924 * We don't guarantee that any particular close will
2925 * trigger inactive processing so just make a best effort
2926 * here at preventing a reference to a removed file. If
2927 * we don't succeed no harm is done.
2929 * Upgrade our holdcnt to a usecount.
2933 * See the previous section. By the time we get here we may find
2934 * ourselves in the same spot.
2936 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2938 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2939 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2941 refcount_release(&vp->v_holdcnt);
2943 VNODE_REFCOUNT_FENCE_ACQ();
2944 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2945 ("%s: vnode with usecount and VI_OWEINACT set",
2950 if ((vp->v_iflag & VI_OWEINACT) == 0) {
2954 vp->v_iflag &= ~VI_OWEINACT;
2955 VNODE_REFCOUNT_FENCE_REL();
2957 v_incr_devcount(vp);
2958 refcount_acquire(&vp->v_usecount);
2959 if (oweinact && VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2960 (flags & LK_NOWAIT) == 0)
2967 * Increase the reference (use) and hold count of a vnode.
2968 * This will also remove the vnode from the free list if it is presently free.
2971 vref(struct vnode *vp)
2974 ASSERT_VI_UNLOCKED(vp, __func__);
2975 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2976 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2977 VNODE_REFCOUNT_FENCE_ACQ();
2978 VNASSERT(vp->v_holdcnt > 0, vp,
2979 ("%s: active vnode not held", __func__));
2980 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2981 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2990 vrefl(struct vnode *vp)
2993 ASSERT_VI_LOCKED(vp, __func__);
2994 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2995 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2996 VNODE_REFCOUNT_FENCE_ACQ();
2997 VNASSERT(vp->v_holdcnt > 0, vp,
2998 ("%s: active vnode not held", __func__));
2999 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
3000 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
3004 if ((vp->v_iflag & VI_OWEINACT) != 0) {
3005 vp->v_iflag &= ~VI_OWEINACT;
3006 VNODE_REFCOUNT_FENCE_REL();
3008 v_incr_devcount(vp);
3009 refcount_acquire(&vp->v_usecount);
3013 vrefact(struct vnode *vp)
3016 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3018 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
3019 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3021 refcount_acquire(&vp->v_usecount);
3026 * Return reference count of a vnode.
3028 * The results of this call are only guaranteed when some mechanism is used to
3029 * stop other processes from gaining references to the vnode. This may be the
3030 * case if the caller holds the only reference. This is also useful when stale
3031 * data is acceptable as race conditions may be accounted for by some other
3035 vrefcnt(struct vnode *vp)
3038 return (vp->v_usecount);
3042 vdefer_inactive(struct vnode *vp)
3045 ASSERT_VI_LOCKED(vp, __func__);
3046 VNASSERT(vp->v_iflag & VI_OWEINACT, vp,
3047 ("%s: vnode without VI_OWEINACT", __func__));
3048 if (VN_IS_DOOMED(vp)) {
3052 if (vp->v_iflag & VI_DEFINACT) {
3053 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3057 vp->v_iflag |= VI_DEFINACT;
3059 counter_u64_add(deferred_inact, 1);
3063 vdefer_inactive_cond(struct vnode *vp)
3067 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
3068 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3072 vdefer_inactive(vp);
3075 enum vputx_op { VPUTX_VRELE, VPUTX_VPUT, VPUTX_VUNREF };
3078 * Decrement the use and hold counts for a vnode.
3080 * See an explanation near vget() as to why atomic operation is safe.
3083 vputx(struct vnode *vp, enum vputx_op func)
3087 KASSERT(vp != NULL, ("vputx: null vp"));
3088 if (func == VPUTX_VUNREF)
3089 ASSERT_VOP_LOCKED(vp, "vunref");
3090 ASSERT_VI_UNLOCKED(vp, __func__);
3091 VNASSERT(vp->v_holdcnt > 0 && vp->v_usecount > 0, vp,
3092 ("%s: wrong ref counts", __func__));
3094 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3097 * We want to hold the vnode until the inactive finishes to
3098 * prevent vgone() races. We drop the use count here and the
3099 * hold count below when we're done.
3101 * If we release the last usecount we take ownership of the hold
3102 * count which provides liveness of the vnode, in which case we
3105 if (!refcount_release(&vp->v_usecount))
3108 v_decr_devcount(vp);
3110 * By the time we got here someone else might have transitioned
3111 * the count back to > 0.
3113 if (vp->v_usecount > 0) {
3117 if (vp->v_iflag & VI_DOINGINACT) {
3123 * Check if the fs wants to perform inactive processing. Note we
3124 * may be only holding the interlock, in which case it is possible
3125 * someone else called vgone on the vnode and ->v_data is now NULL.
3126 * Since vgone performs inactive on its own there is nothing to do
3127 * here but to drop our hold count.
3129 if (__predict_false(VN_IS_DOOMED(vp)) ||
3130 VOP_NEED_INACTIVE(vp) == 0) {
3136 * We must call VOP_INACTIVE with the node locked. Mark
3137 * as VI_DOINGINACT to avoid recursion.
3139 vp->v_iflag |= VI_OWEINACT;
3142 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3146 error = VOP_LOCK(vp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT);
3151 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3152 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3157 VNASSERT(vp->v_usecount == 0 || (vp->v_iflag & VI_OWEINACT) == 0, vp,
3158 ("vnode with usecount and VI_OWEINACT set"));
3160 if (vp->v_iflag & VI_OWEINACT)
3162 if (func != VPUTX_VUNREF)
3165 } else if (vp->v_iflag & VI_OWEINACT) {
3166 vdefer_inactive(vp);
3173 * Vnode put/release.
3174 * If count drops to zero, call inactive routine and return to freelist.
3177 vrele(struct vnode *vp)
3180 vputx(vp, VPUTX_VRELE);
3184 * Release an already locked vnode. This give the same effects as
3185 * unlock+vrele(), but takes less time and avoids releasing and
3186 * re-aquiring the lock (as vrele() acquires the lock internally.)
3188 * It is an invariant that all VOP_* calls operate on a held vnode.
3189 * We may be only having an implicit hold stemming from our usecount,
3190 * which we are about to release. If we unlock the vnode afterwards we
3191 * open a time window where someone else dropped the last usecount and
3192 * proceeded to free the vnode before our unlock finished. For this
3193 * reason we unlock the vnode early. This is a little bit wasteful as
3194 * it may be the vnode is exclusively locked and inactive processing is
3195 * needed, in which case we are adding work.
3198 vput(struct vnode *vp)
3202 vputx(vp, VPUTX_VPUT);
3206 * Release an exclusively locked vnode. Do not unlock the vnode lock.
3209 vunref(struct vnode *vp)
3212 vputx(vp, VPUTX_VUNREF);
3216 * Increase the hold count and activate if this is the first reference.
3219 vhold_activate(struct vnode *vp)
3223 ASSERT_VI_LOCKED(vp, __func__);
3224 VNASSERT(vp->v_holdcnt == 0, vp,
3225 ("%s: wrong hold count", __func__));
3226 VNASSERT(vp->v_op != NULL, vp,
3227 ("%s: vnode already reclaimed.", __func__));
3229 * Remove a vnode from the free list, mark it as in use,
3230 * and put it on the active list.
3232 VNASSERT(vp->v_mount != NULL, vp,
3233 ("_vhold: vnode not on per mount vnode list"));
3235 mtx_lock(&mp->mnt_listmtx);
3236 if ((vp->v_mflag & VMP_TMPMNTFREELIST) != 0) {
3237 TAILQ_REMOVE(&mp->mnt_tmpfreevnodelist, vp, v_actfreelist);
3238 mp->mnt_tmpfreevnodelistsize--;
3239 vp->v_mflag &= ~VMP_TMPMNTFREELIST;
3241 mtx_lock(&vnode_free_list_mtx);
3242 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
3244 mtx_unlock(&vnode_free_list_mtx);
3246 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
3247 ("Activating already active vnode"));
3248 vp->v_iflag &= ~VI_FREE;
3249 vp->v_iflag |= VI_ACTIVE;
3250 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
3251 mp->mnt_activevnodelistsize++;
3252 mtx_unlock(&mp->mnt_listmtx);
3253 refcount_acquire(&vp->v_holdcnt);
3257 vhold(struct vnode *vp)
3260 ASSERT_VI_UNLOCKED(vp, __func__);
3261 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3262 if (refcount_acquire_if_not_zero(&vp->v_holdcnt)) {
3263 VNODE_REFCOUNT_FENCE_ACQ();
3264 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
3265 ("vhold: vnode with holdcnt is free"));
3274 vholdl(struct vnode *vp)
3277 ASSERT_VI_LOCKED(vp, __func__);
3278 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3279 if ((vp->v_iflag & VI_FREE) == 0) {
3280 refcount_acquire(&vp->v_holdcnt);
3287 vholdnz(struct vnode *vp)
3290 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3292 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3293 VNASSERT(old > 0, vp, ("%s: wrong hold count %d", __func__, old));
3295 atomic_add_int(&vp->v_holdcnt, 1);
3300 * Drop the hold count of the vnode. If this is the last reference to
3301 * the vnode we place it on the free list unless it has been vgone'd
3302 * (marked VIRF_DOOMED) in which case we will free it.
3304 * Because the vnode vm object keeps a hold reference on the vnode if
3305 * there is at least one resident non-cached page, the vnode cannot
3306 * leave the active list without the page cleanup done.
3309 vdrop_deactivate(struct vnode *vp)
3313 ASSERT_VI_LOCKED(vp, __func__);
3315 * Mark a vnode as free: remove it from its active list
3316 * and put it up for recycling on the freelist.
3318 VNASSERT(!VN_IS_DOOMED(vp), vp,
3319 ("vdrop: returning doomed vnode"));
3320 VNASSERT(vp->v_op != NULL, vp,
3321 ("vdrop: vnode already reclaimed."));
3322 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
3323 ("vnode already free"));
3324 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
3325 ("vnode with VI_OWEINACT set"));
3326 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp,
3327 ("vnode with VI_DEFINACT set"));
3328 VNASSERT(vp->v_holdcnt == 0, vp,
3329 ("vdrop: freeing when we shouldn't"));
3331 mtx_lock(&mp->mnt_listmtx);
3332 if (vp->v_iflag & VI_ACTIVE) {
3333 vp->v_iflag &= ~VI_ACTIVE;
3334 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp, v_actfreelist);
3335 mp->mnt_activevnodelistsize--;
3337 TAILQ_INSERT_TAIL(&mp->mnt_tmpfreevnodelist, vp, v_actfreelist);
3338 mp->mnt_tmpfreevnodelistsize++;
3339 vp->v_iflag |= VI_FREE;
3340 vp->v_mflag |= VMP_TMPMNTFREELIST;
3342 if (mp->mnt_tmpfreevnodelistsize >= mnt_free_list_batch)
3343 vnlru_return_batch_locked(mp);
3344 mtx_unlock(&mp->mnt_listmtx);
3348 vdrop(struct vnode *vp)
3351 ASSERT_VI_UNLOCKED(vp, __func__);
3352 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3353 if (refcount_release_if_not_last(&vp->v_holdcnt))
3360 vdropl(struct vnode *vp)
3363 ASSERT_VI_LOCKED(vp, __func__);
3364 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3365 if (!refcount_release(&vp->v_holdcnt)) {
3369 if (VN_IS_DOOMED(vp)) {
3373 vdrop_deactivate(vp);
3377 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3378 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3379 * OWEINACT tracks whether a vnode missed a call to inactive due to a
3380 * failed lock upgrade.
3383 vinactive(struct vnode *vp)
3385 struct vm_object *obj;
3387 ASSERT_VOP_ELOCKED(vp, "vinactive");
3388 ASSERT_VI_LOCKED(vp, "vinactive");
3389 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3390 ("vinactive: recursed on VI_DOINGINACT"));
3391 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3392 vp->v_iflag |= VI_DOINGINACT;
3393 vp->v_iflag &= ~VI_OWEINACT;
3396 * Before moving off the active list, we must be sure that any
3397 * modified pages are converted into the vnode's dirty
3398 * buffers, since these will no longer be checked once the
3399 * vnode is on the inactive list.
3401 * The write-out of the dirty pages is asynchronous. At the
3402 * point that VOP_INACTIVE() is called, there could still be
3403 * pending I/O and dirty pages in the object.
3405 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3406 vm_object_mightbedirty(obj)) {
3407 VM_OBJECT_WLOCK(obj);
3408 vm_object_page_clean(obj, 0, 0, 0);
3409 VM_OBJECT_WUNLOCK(obj);
3411 VOP_INACTIVE(vp, curthread);
3413 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3414 ("vinactive: lost VI_DOINGINACT"));
3415 vp->v_iflag &= ~VI_DOINGINACT;
3419 * Remove any vnodes in the vnode table belonging to mount point mp.
3421 * If FORCECLOSE is not specified, there should not be any active ones,
3422 * return error if any are found (nb: this is a user error, not a
3423 * system error). If FORCECLOSE is specified, detach any active vnodes
3426 * If WRITECLOSE is set, only flush out regular file vnodes open for
3429 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3431 * `rootrefs' specifies the base reference count for the root vnode
3432 * of this filesystem. The root vnode is considered busy if its
3433 * v_usecount exceeds this value. On a successful return, vflush(, td)
3434 * will call vrele() on the root vnode exactly rootrefs times.
3435 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3439 static int busyprt = 0; /* print out busy vnodes */
3440 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3444 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3446 struct vnode *vp, *mvp, *rootvp = NULL;
3448 int busy = 0, error;
3450 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3453 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3454 ("vflush: bad args"));
3456 * Get the filesystem root vnode. We can vput() it
3457 * immediately, since with rootrefs > 0, it won't go away.
3459 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3460 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3467 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3469 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3472 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3476 * Skip over a vnodes marked VV_SYSTEM.
3478 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3484 * If WRITECLOSE is set, flush out unlinked but still open
3485 * files (even if open only for reading) and regular file
3486 * vnodes open for writing.
3488 if (flags & WRITECLOSE) {
3489 if (vp->v_object != NULL) {
3490 VM_OBJECT_WLOCK(vp->v_object);
3491 vm_object_page_clean(vp->v_object, 0, 0, 0);
3492 VM_OBJECT_WUNLOCK(vp->v_object);
3494 error = VOP_FSYNC(vp, MNT_WAIT, td);
3498 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3501 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3504 if ((vp->v_type == VNON ||
3505 (error == 0 && vattr.va_nlink > 0)) &&
3506 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3514 * With v_usecount == 0, all we need to do is clear out the
3515 * vnode data structures and we are done.
3517 * If FORCECLOSE is set, forcibly close the vnode.
3519 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3525 vn_printf(vp, "vflush: busy vnode ");
3531 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3533 * If just the root vnode is busy, and if its refcount
3534 * is equal to `rootrefs', then go ahead and kill it.
3537 KASSERT(busy > 0, ("vflush: not busy"));
3538 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3539 ("vflush: usecount %d < rootrefs %d",
3540 rootvp->v_usecount, rootrefs));
3541 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3542 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3550 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3554 for (; rootrefs > 0; rootrefs--)
3560 * Recycle an unused vnode to the front of the free list.
3563 vrecycle(struct vnode *vp)
3568 recycled = vrecyclel(vp);
3574 * vrecycle, with the vp interlock held.
3577 vrecyclel(struct vnode *vp)
3581 ASSERT_VOP_ELOCKED(vp, __func__);
3582 ASSERT_VI_LOCKED(vp, __func__);
3583 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3585 if (vp->v_usecount == 0) {
3593 * Eliminate all activity associated with a vnode
3594 * in preparation for reuse.
3597 vgone(struct vnode *vp)
3605 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3606 struct vnode *lowervp __unused)
3611 * Notify upper mounts about reclaimed or unlinked vnode.
3614 vfs_notify_upper(struct vnode *vp, int event)
3616 static struct vfsops vgonel_vfsops = {
3617 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3618 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3620 struct mount *mp, *ump, *mmp;
3625 if (TAILQ_EMPTY(&mp->mnt_uppers))
3628 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3629 mmp->mnt_op = &vgonel_vfsops;
3630 mmp->mnt_kern_flag |= MNTK_MARKER;
3632 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3633 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3634 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3635 ump = TAILQ_NEXT(ump, mnt_upper_link);
3638 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3641 case VFS_NOTIFY_UPPER_RECLAIM:
3642 VFS_RECLAIM_LOWERVP(ump, vp);
3644 case VFS_NOTIFY_UPPER_UNLINK:
3645 VFS_UNLINK_LOWERVP(ump, vp);
3648 KASSERT(0, ("invalid event %d", event));
3652 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3653 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3656 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3657 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3658 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3659 wakeup(&mp->mnt_uppers);
3665 * vgone, with the vp interlock held.
3668 vgonel(struct vnode *vp)
3673 bool active, oweinact;
3675 ASSERT_VOP_ELOCKED(vp, "vgonel");
3676 ASSERT_VI_LOCKED(vp, "vgonel");
3677 VNASSERT(vp->v_holdcnt, vp,
3678 ("vgonel: vp %p has no reference.", vp));
3679 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3683 * Don't vgonel if we're already doomed.
3685 if (vp->v_irflag & VIRF_DOOMED)
3687 vp->v_irflag |= VIRF_DOOMED;
3690 * Check to see if the vnode is in use. If so, we have to call
3691 * VOP_CLOSE() and VOP_INACTIVE().
3693 active = vp->v_usecount > 0;
3694 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
3696 * If we need to do inactive VI_OWEINACT will be set.
3698 if (vp->v_iflag & VI_DEFINACT) {
3699 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3700 vp->v_iflag &= ~VI_DEFINACT;
3703 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
3706 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
3709 * If purging an active vnode, it must be closed and
3710 * deactivated before being reclaimed.
3713 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
3714 if (oweinact || active) {
3716 if ((vp->v_iflag & VI_DOINGINACT) == 0)
3720 if (vp->v_type == VSOCK)
3721 vfs_unp_reclaim(vp);
3724 * Clean out any buffers associated with the vnode.
3725 * If the flush fails, just toss the buffers.
3728 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
3729 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
3730 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
3731 while (vinvalbuf(vp, 0, 0, 0) != 0)
3735 BO_LOCK(&vp->v_bufobj);
3736 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
3737 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
3738 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
3739 vp->v_bufobj.bo_clean.bv_cnt == 0,
3740 ("vp %p bufobj not invalidated", vp));
3743 * For VMIO bufobj, BO_DEAD is set later, or in
3744 * vm_object_terminate() after the object's page queue is
3747 object = vp->v_bufobj.bo_object;
3749 vp->v_bufobj.bo_flag |= BO_DEAD;
3750 BO_UNLOCK(&vp->v_bufobj);
3753 * Handle the VM part. Tmpfs handles v_object on its own (the
3754 * OBJT_VNODE check). Nullfs or other bypassing filesystems
3755 * should not touch the object borrowed from the lower vnode
3756 * (the handle check).
3758 if (object != NULL && object->type == OBJT_VNODE &&
3759 object->handle == vp)
3760 vnode_destroy_vobject(vp);
3763 * Reclaim the vnode.
3765 if (VOP_RECLAIM(vp, td))
3766 panic("vgone: cannot reclaim");
3768 vn_finished_secondary_write(mp);
3769 VNASSERT(vp->v_object == NULL, vp,
3770 ("vop_reclaim left v_object vp=%p", vp));
3772 * Clear the advisory locks and wake up waiting threads.
3774 (void)VOP_ADVLOCKPURGE(vp);
3777 * Delete from old mount point vnode list.
3782 * Done with purge, reset to the standard lock and invalidate
3786 vp->v_vnlock = &vp->v_lock;
3787 vp->v_op = &dead_vnodeops;
3792 * Calculate the total number of references to a special device.
3795 vcount(struct vnode *vp)
3800 count = vp->v_rdev->si_usecount;
3806 * Print out a description of a vnode.
3808 static char *typename[] =
3809 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
3813 vn_printf(struct vnode *vp, const char *fmt, ...)
3816 char buf[256], buf2[16];
3822 printf("%p: ", (void *)vp);
3823 printf("type %s\n", typename[vp->v_type]);
3824 printf(" usecount %d, writecount %d, refcount %d",
3825 vp->v_usecount, vp->v_writecount, vp->v_holdcnt);
3826 switch (vp->v_type) {
3828 printf(" mountedhere %p\n", vp->v_mountedhere);
3831 printf(" rdev %p\n", vp->v_rdev);
3834 printf(" socket %p\n", vp->v_unpcb);
3837 printf(" fifoinfo %p\n", vp->v_fifoinfo);
3845 if (vp->v_irflag & VIRF_DOOMED)
3846 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
3847 flags = vp->v_irflag & ~(VIRF_DOOMED);
3849 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
3850 strlcat(buf, buf2, sizeof(buf));
3852 if (vp->v_vflag & VV_ROOT)
3853 strlcat(buf, "|VV_ROOT", sizeof(buf));
3854 if (vp->v_vflag & VV_ISTTY)
3855 strlcat(buf, "|VV_ISTTY", sizeof(buf));
3856 if (vp->v_vflag & VV_NOSYNC)
3857 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
3858 if (vp->v_vflag & VV_ETERNALDEV)
3859 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
3860 if (vp->v_vflag & VV_CACHEDLABEL)
3861 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
3862 if (vp->v_vflag & VV_VMSIZEVNLOCK)
3863 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
3864 if (vp->v_vflag & VV_COPYONWRITE)
3865 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
3866 if (vp->v_vflag & VV_SYSTEM)
3867 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
3868 if (vp->v_vflag & VV_PROCDEP)
3869 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
3870 if (vp->v_vflag & VV_NOKNOTE)
3871 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
3872 if (vp->v_vflag & VV_DELETED)
3873 strlcat(buf, "|VV_DELETED", sizeof(buf));
3874 if (vp->v_vflag & VV_MD)
3875 strlcat(buf, "|VV_MD", sizeof(buf));
3876 if (vp->v_vflag & VV_FORCEINSMQ)
3877 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
3878 if (vp->v_vflag & VV_READLINK)
3879 strlcat(buf, "|VV_READLINK", sizeof(buf));
3880 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
3881 VV_CACHEDLABEL | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
3882 VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
3884 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
3885 strlcat(buf, buf2, sizeof(buf));
3887 if (vp->v_iflag & VI_TEXT_REF)
3888 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
3889 if (vp->v_iflag & VI_MOUNT)
3890 strlcat(buf, "|VI_MOUNT", sizeof(buf));
3891 if (vp->v_iflag & VI_FREE)
3892 strlcat(buf, "|VI_FREE", sizeof(buf));
3893 if (vp->v_iflag & VI_ACTIVE)
3894 strlcat(buf, "|VI_ACTIVE", sizeof(buf));
3895 if (vp->v_iflag & VI_DOINGINACT)
3896 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
3897 if (vp->v_iflag & VI_OWEINACT)
3898 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
3899 if (vp->v_iflag & VI_DEFINACT)
3900 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
3901 flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_FREE | VI_ACTIVE |
3902 VI_DOINGINACT | VI_OWEINACT | VI_DEFINACT);
3904 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
3905 strlcat(buf, buf2, sizeof(buf));
3907 if (vp->v_mflag & VMP_TMPMNTFREELIST)
3908 strlcat(buf, "|VMP_TMPMNTFREELIST", sizeof(buf));
3909 flags = vp->v_mflag & ~(VMP_TMPMNTFREELIST);
3911 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
3912 strlcat(buf, buf2, sizeof(buf));
3914 printf(" flags (%s)\n", buf + 1);
3915 if (mtx_owned(VI_MTX(vp)))
3916 printf(" VI_LOCKed");
3917 if (vp->v_object != NULL)
3918 printf(" v_object %p ref %d pages %d "
3919 "cleanbuf %d dirtybuf %d\n",
3920 vp->v_object, vp->v_object->ref_count,
3921 vp->v_object->resident_page_count,
3922 vp->v_bufobj.bo_clean.bv_cnt,
3923 vp->v_bufobj.bo_dirty.bv_cnt);
3925 lockmgr_printinfo(vp->v_vnlock);
3926 if (vp->v_data != NULL)
3932 * List all of the locked vnodes in the system.
3933 * Called when debugging the kernel.
3935 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
3941 * Note: because this is DDB, we can't obey the locking semantics
3942 * for these structures, which means we could catch an inconsistent
3943 * state and dereference a nasty pointer. Not much to be done
3946 db_printf("Locked vnodes\n");
3947 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3948 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3949 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
3950 vn_printf(vp, "vnode ");
3956 * Show details about the given vnode.
3958 DB_SHOW_COMMAND(vnode, db_show_vnode)
3964 vp = (struct vnode *)addr;
3965 vn_printf(vp, "vnode ");
3969 * Show details about the given mount point.
3971 DB_SHOW_COMMAND(mount, db_show_mount)
3982 /* No address given, print short info about all mount points. */
3983 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3984 db_printf("%p %s on %s (%s)\n", mp,
3985 mp->mnt_stat.f_mntfromname,
3986 mp->mnt_stat.f_mntonname,
3987 mp->mnt_stat.f_fstypename);
3991 db_printf("\nMore info: show mount <addr>\n");
3995 mp = (struct mount *)addr;
3996 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
3997 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4000 mflags = mp->mnt_flag;
4001 #define MNT_FLAG(flag) do { \
4002 if (mflags & (flag)) { \
4003 if (buf[0] != '\0') \
4004 strlcat(buf, ", ", sizeof(buf)); \
4005 strlcat(buf, (#flag) + 4, sizeof(buf)); \
4006 mflags &= ~(flag); \
4009 MNT_FLAG(MNT_RDONLY);
4010 MNT_FLAG(MNT_SYNCHRONOUS);
4011 MNT_FLAG(MNT_NOEXEC);
4012 MNT_FLAG(MNT_NOSUID);
4013 MNT_FLAG(MNT_NFS4ACLS);
4014 MNT_FLAG(MNT_UNION);
4015 MNT_FLAG(MNT_ASYNC);
4016 MNT_FLAG(MNT_SUIDDIR);
4017 MNT_FLAG(MNT_SOFTDEP);
4018 MNT_FLAG(MNT_NOSYMFOLLOW);
4019 MNT_FLAG(MNT_GJOURNAL);
4020 MNT_FLAG(MNT_MULTILABEL);
4022 MNT_FLAG(MNT_NOATIME);
4023 MNT_FLAG(MNT_NOCLUSTERR);
4024 MNT_FLAG(MNT_NOCLUSTERW);
4026 MNT_FLAG(MNT_EXRDONLY);
4027 MNT_FLAG(MNT_EXPORTED);
4028 MNT_FLAG(MNT_DEFEXPORTED);
4029 MNT_FLAG(MNT_EXPORTANON);
4030 MNT_FLAG(MNT_EXKERB);
4031 MNT_FLAG(MNT_EXPUBLIC);
4032 MNT_FLAG(MNT_LOCAL);
4033 MNT_FLAG(MNT_QUOTA);
4034 MNT_FLAG(MNT_ROOTFS);
4036 MNT_FLAG(MNT_IGNORE);
4037 MNT_FLAG(MNT_UPDATE);
4038 MNT_FLAG(MNT_DELEXPORT);
4039 MNT_FLAG(MNT_RELOAD);
4040 MNT_FLAG(MNT_FORCE);
4041 MNT_FLAG(MNT_SNAPSHOT);
4042 MNT_FLAG(MNT_BYFSID);
4046 strlcat(buf, ", ", sizeof(buf));
4047 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4048 "0x%016jx", mflags);
4050 db_printf(" mnt_flag = %s\n", buf);
4053 flags = mp->mnt_kern_flag;
4054 #define MNT_KERN_FLAG(flag) do { \
4055 if (flags & (flag)) { \
4056 if (buf[0] != '\0') \
4057 strlcat(buf, ", ", sizeof(buf)); \
4058 strlcat(buf, (#flag) + 5, sizeof(buf)); \
4062 MNT_KERN_FLAG(MNTK_UNMOUNTF);
4063 MNT_KERN_FLAG(MNTK_ASYNC);
4064 MNT_KERN_FLAG(MNTK_SOFTDEP);
4065 MNT_KERN_FLAG(MNTK_DRAINING);
4066 MNT_KERN_FLAG(MNTK_REFEXPIRE);
4067 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4068 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4069 MNT_KERN_FLAG(MNTK_NO_IOPF);
4070 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4071 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4072 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4073 MNT_KERN_FLAG(MNTK_MARKER);
4074 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4075 MNT_KERN_FLAG(MNTK_NOASYNC);
4076 MNT_KERN_FLAG(MNTK_UNMOUNT);
4077 MNT_KERN_FLAG(MNTK_MWAIT);
4078 MNT_KERN_FLAG(MNTK_SUSPEND);
4079 MNT_KERN_FLAG(MNTK_SUSPEND2);
4080 MNT_KERN_FLAG(MNTK_SUSPENDED);
4081 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4082 MNT_KERN_FLAG(MNTK_NOKNOTE);
4083 #undef MNT_KERN_FLAG
4086 strlcat(buf, ", ", sizeof(buf));
4087 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4090 db_printf(" mnt_kern_flag = %s\n", buf);
4092 db_printf(" mnt_opt = ");
4093 opt = TAILQ_FIRST(mp->mnt_opt);
4095 db_printf("%s", opt->name);
4096 opt = TAILQ_NEXT(opt, link);
4097 while (opt != NULL) {
4098 db_printf(", %s", opt->name);
4099 opt = TAILQ_NEXT(opt, link);
4105 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4106 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4107 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4108 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4109 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4110 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4111 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4112 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4113 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4114 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4115 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4116 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4118 db_printf(" mnt_cred = { uid=%u ruid=%u",
4119 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4120 if (jailed(mp->mnt_cred))
4121 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4123 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4124 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4125 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4126 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4127 db_printf(" mnt_activevnodelistsize = %d\n",
4128 mp->mnt_activevnodelistsize);
4129 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4130 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4131 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
4132 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4133 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4134 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4135 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4136 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4137 db_printf(" mnt_secondary_accwrites = %d\n",
4138 mp->mnt_secondary_accwrites);
4139 db_printf(" mnt_gjprovider = %s\n",
4140 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4141 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4143 db_printf("\n\nList of active vnodes\n");
4144 TAILQ_FOREACH(vp, &mp->mnt_activevnodelist, v_actfreelist) {
4145 if (vp->v_type != VMARKER) {
4146 vn_printf(vp, "vnode ");
4151 db_printf("\n\nList of inactive vnodes\n");
4152 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4153 if (vp->v_type != VMARKER && (vp->v_iflag & VI_ACTIVE) == 0) {
4154 vn_printf(vp, "vnode ");
4163 * Fill in a struct xvfsconf based on a struct vfsconf.
4166 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4168 struct xvfsconf xvfsp;
4170 bzero(&xvfsp, sizeof(xvfsp));
4171 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4172 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4173 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4174 xvfsp.vfc_flags = vfsp->vfc_flags;
4176 * These are unused in userland, we keep them
4177 * to not break binary compatibility.
4179 xvfsp.vfc_vfsops = NULL;
4180 xvfsp.vfc_next = NULL;
4181 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4184 #ifdef COMPAT_FREEBSD32
4186 uint32_t vfc_vfsops;
4187 char vfc_name[MFSNAMELEN];
4188 int32_t vfc_typenum;
4189 int32_t vfc_refcount;
4195 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4197 struct xvfsconf32 xvfsp;
4199 bzero(&xvfsp, sizeof(xvfsp));
4200 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4201 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4202 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4203 xvfsp.vfc_flags = vfsp->vfc_flags;
4204 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4209 * Top level filesystem related information gathering.
4212 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4214 struct vfsconf *vfsp;
4219 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4220 #ifdef COMPAT_FREEBSD32
4221 if (req->flags & SCTL_MASK32)
4222 error = vfsconf2x32(req, vfsp);
4225 error = vfsconf2x(req, vfsp);
4233 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4234 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4235 "S,xvfsconf", "List of all configured filesystems");
4237 #ifndef BURN_BRIDGES
4238 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4241 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4243 int *name = (int *)arg1 - 1; /* XXX */
4244 u_int namelen = arg2 + 1; /* XXX */
4245 struct vfsconf *vfsp;
4247 log(LOG_WARNING, "userland calling deprecated sysctl, "
4248 "please rebuild world\n");
4250 #if 1 || defined(COMPAT_PRELITE2)
4251 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4253 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4257 case VFS_MAXTYPENUM:
4260 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4263 return (ENOTDIR); /* overloaded */
4265 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4266 if (vfsp->vfc_typenum == name[2])
4271 return (EOPNOTSUPP);
4272 #ifdef COMPAT_FREEBSD32
4273 if (req->flags & SCTL_MASK32)
4274 return (vfsconf2x32(req, vfsp));
4277 return (vfsconf2x(req, vfsp));
4279 return (EOPNOTSUPP);
4282 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4283 CTLFLAG_MPSAFE, vfs_sysctl,
4284 "Generic filesystem");
4286 #if 1 || defined(COMPAT_PRELITE2)
4289 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4292 struct vfsconf *vfsp;
4293 struct ovfsconf ovfs;
4296 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4297 bzero(&ovfs, sizeof(ovfs));
4298 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4299 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4300 ovfs.vfc_index = vfsp->vfc_typenum;
4301 ovfs.vfc_refcount = vfsp->vfc_refcount;
4302 ovfs.vfc_flags = vfsp->vfc_flags;
4303 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4313 #endif /* 1 || COMPAT_PRELITE2 */
4314 #endif /* !BURN_BRIDGES */
4316 #define KINFO_VNODESLOP 10
4319 * Dump vnode list (via sysctl).
4323 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4331 * Stale numvnodes access is not fatal here.
4334 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4336 /* Make an estimate */
4337 return (SYSCTL_OUT(req, 0, len));
4339 error = sysctl_wire_old_buffer(req, 0);
4342 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4344 mtx_lock(&mountlist_mtx);
4345 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4346 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4349 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4353 xvn[n].xv_size = sizeof *xvn;
4354 xvn[n].xv_vnode = vp;
4355 xvn[n].xv_id = 0; /* XXX compat */
4356 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4358 XV_COPY(writecount);
4364 xvn[n].xv_flag = vp->v_vflag;
4366 switch (vp->v_type) {
4373 if (vp->v_rdev == NULL) {
4377 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4380 xvn[n].xv_socket = vp->v_socket;
4383 xvn[n].xv_fifo = vp->v_fifoinfo;
4388 /* shouldn't happen? */
4396 mtx_lock(&mountlist_mtx);
4401 mtx_unlock(&mountlist_mtx);
4403 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4408 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4409 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4414 unmount_or_warn(struct mount *mp)
4418 error = dounmount(mp, MNT_FORCE, curthread);
4420 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4424 printf("%d)\n", error);
4429 * Unmount all filesystems. The list is traversed in reverse order
4430 * of mounting to avoid dependencies.
4433 vfs_unmountall(void)
4435 struct mount *mp, *tmp;
4437 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4440 * Since this only runs when rebooting, it is not interlocked.
4442 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4446 * Forcibly unmounting "/dev" before "/" would prevent clean
4447 * unmount of the latter.
4449 if (mp == rootdevmp)
4452 unmount_or_warn(mp);
4455 if (rootdevmp != NULL)
4456 unmount_or_warn(rootdevmp);
4460 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4463 ASSERT_VI_LOCKED(vp, __func__);
4464 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4465 if ((vp->v_iflag & VI_OWEINACT) == 0) {
4469 if (vn_lock(vp, lkflags) == 0) {
4471 if ((vp->v_iflag & (VI_OWEINACT | VI_DOINGINACT)) == VI_OWEINACT)
4477 vdefer_inactive_cond(vp);
4480 static void __noinline
4481 vfs_periodic_inactive(struct mount *mp, int flags)
4483 struct vnode *vp, *mvp;
4486 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4487 if (flags != MNT_WAIT)
4488 lkflags |= LK_NOWAIT;
4490 MNT_VNODE_FOREACH_ACTIVE(vp, mp, mvp) {
4491 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4495 vp->v_iflag &= ~VI_DEFINACT;
4496 vfs_deferred_inactive(vp, lkflags);
4501 vfs_want_msync(struct vnode *vp)
4503 struct vm_object *obj;
4505 if (vp->v_vflag & VV_NOSYNC)
4508 return (obj != NULL && vm_object_mightbedirty(obj));
4511 static void __noinline
4512 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4514 struct vnode *vp, *mvp;
4515 struct vm_object *obj;
4517 int lkflags, objflags;
4522 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4523 if (flags != MNT_WAIT) {
4524 lkflags |= LK_NOWAIT;
4525 objflags = OBJPC_NOSYNC;
4527 objflags = OBJPC_SYNC;
4530 MNT_VNODE_FOREACH_ACTIVE(vp, mp, mvp) {
4532 if (vp->v_iflag & VI_DEFINACT) {
4533 vp->v_iflag &= ~VI_DEFINACT;
4536 if (!vfs_want_msync(vp)) {
4538 vfs_deferred_inactive(vp, lkflags);
4543 if (vget(vp, lkflags, td) == 0) {
4545 if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4546 VM_OBJECT_WLOCK(obj);
4547 vm_object_page_clean(obj, 0, 0, objflags);
4548 VM_OBJECT_WUNLOCK(obj);
4555 vdefer_inactive_cond(vp);
4561 vfs_periodic(struct mount *mp, int flags)
4564 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4566 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4567 vfs_periodic_inactive(mp, flags);
4569 vfs_periodic_msync_inactive(mp, flags);
4573 destroy_vpollinfo_free(struct vpollinfo *vi)
4576 knlist_destroy(&vi->vpi_selinfo.si_note);
4577 mtx_destroy(&vi->vpi_lock);
4578 uma_zfree(vnodepoll_zone, vi);
4582 destroy_vpollinfo(struct vpollinfo *vi)
4585 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4586 seldrain(&vi->vpi_selinfo);
4587 destroy_vpollinfo_free(vi);
4591 * Initialize per-vnode helper structure to hold poll-related state.
4594 v_addpollinfo(struct vnode *vp)
4596 struct vpollinfo *vi;
4598 if (vp->v_pollinfo != NULL)
4600 vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4601 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4602 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4603 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4605 if (vp->v_pollinfo != NULL) {
4607 destroy_vpollinfo_free(vi);
4610 vp->v_pollinfo = vi;
4615 * Record a process's interest in events which might happen to
4616 * a vnode. Because poll uses the historic select-style interface
4617 * internally, this routine serves as both the ``check for any
4618 * pending events'' and the ``record my interest in future events''
4619 * functions. (These are done together, while the lock is held,
4620 * to avoid race conditions.)
4623 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4627 mtx_lock(&vp->v_pollinfo->vpi_lock);
4628 if (vp->v_pollinfo->vpi_revents & events) {
4630 * This leaves events we are not interested
4631 * in available for the other process which
4632 * which presumably had requested them
4633 * (otherwise they would never have been
4636 events &= vp->v_pollinfo->vpi_revents;
4637 vp->v_pollinfo->vpi_revents &= ~events;
4639 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4642 vp->v_pollinfo->vpi_events |= events;
4643 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4644 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4649 * Routine to create and manage a filesystem syncer vnode.
4651 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4652 static int sync_fsync(struct vop_fsync_args *);
4653 static int sync_inactive(struct vop_inactive_args *);
4654 static int sync_reclaim(struct vop_reclaim_args *);
4656 static struct vop_vector sync_vnodeops = {
4657 .vop_bypass = VOP_EOPNOTSUPP,
4658 .vop_close = sync_close, /* close */
4659 .vop_fsync = sync_fsync, /* fsync */
4660 .vop_inactive = sync_inactive, /* inactive */
4661 .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
4662 .vop_reclaim = sync_reclaim, /* reclaim */
4663 .vop_lock1 = vop_stdlock, /* lock */
4664 .vop_unlock = vop_stdunlock, /* unlock */
4665 .vop_islocked = vop_stdislocked, /* islocked */
4667 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
4670 * Create a new filesystem syncer vnode for the specified mount point.
4673 vfs_allocate_syncvnode(struct mount *mp)
4677 static long start, incr, next;
4680 /* Allocate a new vnode */
4681 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
4683 panic("vfs_allocate_syncvnode: getnewvnode() failed");
4685 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4686 vp->v_vflag |= VV_FORCEINSMQ;
4687 error = insmntque(vp, mp);
4689 panic("vfs_allocate_syncvnode: insmntque() failed");
4690 vp->v_vflag &= ~VV_FORCEINSMQ;
4693 * Place the vnode onto the syncer worklist. We attempt to
4694 * scatter them about on the list so that they will go off
4695 * at evenly distributed times even if all the filesystems
4696 * are mounted at once.
4699 if (next == 0 || next > syncer_maxdelay) {
4703 start = syncer_maxdelay / 2;
4704 incr = syncer_maxdelay;
4710 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
4711 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
4712 mtx_lock(&sync_mtx);
4714 if (mp->mnt_syncer == NULL) {
4715 mp->mnt_syncer = vp;
4718 mtx_unlock(&sync_mtx);
4721 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4728 vfs_deallocate_syncvnode(struct mount *mp)
4732 mtx_lock(&sync_mtx);
4733 vp = mp->mnt_syncer;
4735 mp->mnt_syncer = NULL;
4736 mtx_unlock(&sync_mtx);
4742 * Do a lazy sync of the filesystem.
4745 sync_fsync(struct vop_fsync_args *ap)
4747 struct vnode *syncvp = ap->a_vp;
4748 struct mount *mp = syncvp->v_mount;
4753 * We only need to do something if this is a lazy evaluation.
4755 if (ap->a_waitfor != MNT_LAZY)
4759 * Move ourselves to the back of the sync list.
4761 bo = &syncvp->v_bufobj;
4763 vn_syncer_add_to_worklist(bo, syncdelay);
4767 * Walk the list of vnodes pushing all that are dirty and
4768 * not already on the sync list.
4770 if (vfs_busy(mp, MBF_NOWAIT) != 0)
4772 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
4776 save = curthread_pflags_set(TDP_SYNCIO);
4778 * The filesystem at hand may be idle with free vnodes stored in the
4779 * batch. Return them instead of letting them stay there indefinitely.
4781 vnlru_return_batch(mp);
4782 vfs_periodic(mp, MNT_NOWAIT);
4783 error = VFS_SYNC(mp, MNT_LAZY);
4784 curthread_pflags_restore(save);
4785 vn_finished_write(mp);
4791 * The syncer vnode is no referenced.
4794 sync_inactive(struct vop_inactive_args *ap)
4802 * The syncer vnode is no longer needed and is being decommissioned.
4804 * Modifications to the worklist must be protected by sync_mtx.
4807 sync_reclaim(struct vop_reclaim_args *ap)
4809 struct vnode *vp = ap->a_vp;
4814 mtx_lock(&sync_mtx);
4815 if (vp->v_mount->mnt_syncer == vp)
4816 vp->v_mount->mnt_syncer = NULL;
4817 if (bo->bo_flag & BO_ONWORKLST) {
4818 LIST_REMOVE(bo, bo_synclist);
4819 syncer_worklist_len--;
4821 bo->bo_flag &= ~BO_ONWORKLST;
4823 mtx_unlock(&sync_mtx);
4830 vn_need_pageq_flush(struct vnode *vp)
4832 struct vm_object *obj;
4835 MPASS(mtx_owned(VI_MTX(vp)));
4837 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
4838 vm_object_mightbedirty(obj))
4844 * Check if vnode represents a disk device
4847 vn_isdisk(struct vnode *vp, int *errp)
4851 if (vp->v_type != VCHR) {
4857 if (vp->v_rdev == NULL)
4859 else if (vp->v_rdev->si_devsw == NULL)
4861 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
4867 return (error == 0);
4871 * Common filesystem object access control check routine. Accepts a
4872 * vnode's type, "mode", uid and gid, requested access mode, credentials,
4873 * and optional call-by-reference privused argument allowing vaccess()
4874 * to indicate to the caller whether privilege was used to satisfy the
4875 * request (obsoleted). Returns 0 on success, or an errno on failure.
4878 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
4879 accmode_t accmode, struct ucred *cred, int *privused)
4881 accmode_t dac_granted;
4882 accmode_t priv_granted;
4884 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
4885 ("invalid bit in accmode"));
4886 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
4887 ("VAPPEND without VWRITE"));
4890 * Look for a normal, non-privileged way to access the file/directory
4891 * as requested. If it exists, go with that.
4894 if (privused != NULL)
4899 /* Check the owner. */
4900 if (cred->cr_uid == file_uid) {
4901 dac_granted |= VADMIN;
4902 if (file_mode & S_IXUSR)
4903 dac_granted |= VEXEC;
4904 if (file_mode & S_IRUSR)
4905 dac_granted |= VREAD;
4906 if (file_mode & S_IWUSR)
4907 dac_granted |= (VWRITE | VAPPEND);
4909 if ((accmode & dac_granted) == accmode)
4915 /* Otherwise, check the groups (first match) */
4916 if (groupmember(file_gid, cred)) {
4917 if (file_mode & S_IXGRP)
4918 dac_granted |= VEXEC;
4919 if (file_mode & S_IRGRP)
4920 dac_granted |= VREAD;
4921 if (file_mode & S_IWGRP)
4922 dac_granted |= (VWRITE | VAPPEND);
4924 if ((accmode & dac_granted) == accmode)
4930 /* Otherwise, check everyone else. */
4931 if (file_mode & S_IXOTH)
4932 dac_granted |= VEXEC;
4933 if (file_mode & S_IROTH)
4934 dac_granted |= VREAD;
4935 if (file_mode & S_IWOTH)
4936 dac_granted |= (VWRITE | VAPPEND);
4937 if ((accmode & dac_granted) == accmode)
4942 * Build a privilege mask to determine if the set of privileges
4943 * satisfies the requirements when combined with the granted mask
4944 * from above. For each privilege, if the privilege is required,
4945 * bitwise or the request type onto the priv_granted mask.
4951 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
4952 * requests, instead of PRIV_VFS_EXEC.
4954 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4955 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
4956 priv_granted |= VEXEC;
4959 * Ensure that at least one execute bit is on. Otherwise,
4960 * a privileged user will always succeed, and we don't want
4961 * this to happen unless the file really is executable.
4963 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4964 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
4965 !priv_check_cred(cred, PRIV_VFS_EXEC))
4966 priv_granted |= VEXEC;
4969 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
4970 !priv_check_cred(cred, PRIV_VFS_READ))
4971 priv_granted |= VREAD;
4973 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
4974 !priv_check_cred(cred, PRIV_VFS_WRITE))
4975 priv_granted |= (VWRITE | VAPPEND);
4977 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
4978 !priv_check_cred(cred, PRIV_VFS_ADMIN))
4979 priv_granted |= VADMIN;
4981 if ((accmode & (priv_granted | dac_granted)) == accmode) {
4982 /* XXX audit: privilege used */
4983 if (privused != NULL)
4988 return ((accmode & VADMIN) ? EPERM : EACCES);
4992 * Credential check based on process requesting service, and per-attribute
4996 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
4997 struct thread *td, accmode_t accmode)
5001 * Kernel-invoked always succeeds.
5007 * Do not allow privileged processes in jail to directly manipulate
5008 * system attributes.
5010 switch (attrnamespace) {
5011 case EXTATTR_NAMESPACE_SYSTEM:
5012 /* Potentially should be: return (EPERM); */
5013 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5014 case EXTATTR_NAMESPACE_USER:
5015 return (VOP_ACCESS(vp, accmode, cred, td));
5021 #ifdef DEBUG_VFS_LOCKS
5023 * This only exists to suppress warnings from unlocked specfs accesses. It is
5024 * no longer ok to have an unlocked VFS.
5026 #define IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL || \
5027 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
5029 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
5030 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5031 "Drop into debugger on lock violation");
5033 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
5034 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5035 0, "Check for interlock across VOPs");
5037 int vfs_badlock_print = 1; /* Print lock violations. */
5038 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5039 0, "Print lock violations");
5041 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
5042 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5043 0, "Print vnode details on lock violations");
5046 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
5047 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5048 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5052 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5056 if (vfs_badlock_backtrace)
5059 if (vfs_badlock_vnode)
5060 vn_printf(vp, "vnode ");
5061 if (vfs_badlock_print)
5062 printf("%s: %p %s\n", str, (void *)vp, msg);
5063 if (vfs_badlock_ddb)
5064 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5068 assert_vi_locked(struct vnode *vp, const char *str)
5071 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5072 vfs_badlock("interlock is not locked but should be", str, vp);
5076 assert_vi_unlocked(struct vnode *vp, const char *str)
5079 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5080 vfs_badlock("interlock is locked but should not be", str, vp);
5084 assert_vop_locked(struct vnode *vp, const char *str)
5088 if (!IGNORE_LOCK(vp)) {
5089 locked = VOP_ISLOCKED(vp);
5090 if (locked == 0 || locked == LK_EXCLOTHER)
5091 vfs_badlock("is not locked but should be", str, vp);
5096 assert_vop_unlocked(struct vnode *vp, const char *str)
5099 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5100 vfs_badlock("is locked but should not be", str, vp);
5104 assert_vop_elocked(struct vnode *vp, const char *str)
5107 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5108 vfs_badlock("is not exclusive locked but should be", str, vp);
5110 #endif /* DEBUG_VFS_LOCKS */
5113 vop_rename_fail(struct vop_rename_args *ap)
5116 if (ap->a_tvp != NULL)
5118 if (ap->a_tdvp == ap->a_tvp)
5127 vop_rename_pre(void *ap)
5129 struct vop_rename_args *a = ap;
5131 #ifdef DEBUG_VFS_LOCKS
5133 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5134 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5135 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5136 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5138 /* Check the source (from). */
5139 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5140 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5141 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5142 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5143 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5145 /* Check the target. */
5147 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5148 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5150 if (a->a_tdvp != a->a_fdvp)
5152 if (a->a_tvp != a->a_fvp)
5159 #ifdef DEBUG_VFS_LOCKS
5161 vop_strategy_pre(void *ap)
5163 struct vop_strategy_args *a;
5170 * Cluster ops lock their component buffers but not the IO container.
5172 if ((bp->b_flags & B_CLUSTER) != 0)
5175 if (panicstr == NULL && !BUF_ISLOCKED(bp)) {
5176 if (vfs_badlock_print)
5178 "VOP_STRATEGY: bp is not locked but should be\n");
5179 if (vfs_badlock_ddb)
5180 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5185 vop_lock_pre(void *ap)
5187 struct vop_lock1_args *a = ap;
5189 if ((a->a_flags & LK_INTERLOCK) == 0)
5190 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5192 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5196 vop_lock_post(void *ap, int rc)
5198 struct vop_lock1_args *a = ap;
5200 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5201 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5202 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5206 vop_unlock_pre(void *ap)
5208 struct vop_unlock_args *a = ap;
5210 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5214 vop_unlock_post(void *ap, int rc)
5220 vop_need_inactive_pre(void *ap)
5222 struct vop_need_inactive_args *a = ap;
5224 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5228 vop_need_inactive_post(void *ap, int rc)
5230 struct vop_need_inactive_args *a = ap;
5232 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5237 vop_create_post(void *ap, int rc)
5239 struct vop_create_args *a = ap;
5242 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5246 vop_deleteextattr_post(void *ap, int rc)
5248 struct vop_deleteextattr_args *a = ap;
5251 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5255 vop_link_post(void *ap, int rc)
5257 struct vop_link_args *a = ap;
5260 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
5261 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
5266 vop_mkdir_post(void *ap, int rc)
5268 struct vop_mkdir_args *a = ap;
5271 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5275 vop_mknod_post(void *ap, int rc)
5277 struct vop_mknod_args *a = ap;
5280 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5284 vop_reclaim_post(void *ap, int rc)
5286 struct vop_reclaim_args *a = ap;
5289 VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
5293 vop_remove_post(void *ap, int rc)
5295 struct vop_remove_args *a = ap;
5298 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5299 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5304 vop_rename_post(void *ap, int rc)
5306 struct vop_rename_args *a = ap;
5311 if (a->a_fdvp == a->a_tdvp) {
5312 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5314 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5315 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5317 hint |= NOTE_EXTEND;
5318 if (a->a_fvp->v_type == VDIR)
5320 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5322 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5323 a->a_tvp->v_type == VDIR)
5325 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5328 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5330 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5332 if (a->a_tdvp != a->a_fdvp)
5334 if (a->a_tvp != a->a_fvp)
5342 vop_rmdir_post(void *ap, int rc)
5344 struct vop_rmdir_args *a = ap;
5347 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5348 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5353 vop_setattr_post(void *ap, int rc)
5355 struct vop_setattr_args *a = ap;
5358 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5362 vop_setextattr_post(void *ap, int rc)
5364 struct vop_setextattr_args *a = ap;
5367 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5371 vop_symlink_post(void *ap, int rc)
5373 struct vop_symlink_args *a = ap;
5376 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5380 vop_open_post(void *ap, int rc)
5382 struct vop_open_args *a = ap;
5385 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
5389 vop_close_post(void *ap, int rc)
5391 struct vop_close_args *a = ap;
5393 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
5394 !VN_IS_DOOMED(a->a_vp))) {
5395 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
5396 NOTE_CLOSE_WRITE : NOTE_CLOSE);
5401 vop_read_post(void *ap, int rc)
5403 struct vop_read_args *a = ap;
5406 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5410 vop_readdir_post(void *ap, int rc)
5412 struct vop_readdir_args *a = ap;
5415 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5418 static struct knlist fs_knlist;
5421 vfs_event_init(void *arg)
5423 knlist_init_mtx(&fs_knlist, NULL);
5425 /* XXX - correct order? */
5426 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
5429 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
5432 KNOTE_UNLOCKED(&fs_knlist, event);
5435 static int filt_fsattach(struct knote *kn);
5436 static void filt_fsdetach(struct knote *kn);
5437 static int filt_fsevent(struct knote *kn, long hint);
5439 struct filterops fs_filtops = {
5441 .f_attach = filt_fsattach,
5442 .f_detach = filt_fsdetach,
5443 .f_event = filt_fsevent
5447 filt_fsattach(struct knote *kn)
5450 kn->kn_flags |= EV_CLEAR;
5451 knlist_add(&fs_knlist, kn, 0);
5456 filt_fsdetach(struct knote *kn)
5459 knlist_remove(&fs_knlist, kn, 0);
5463 filt_fsevent(struct knote *kn, long hint)
5466 kn->kn_fflags |= hint;
5467 return (kn->kn_fflags != 0);
5471 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
5477 error = SYSCTL_IN(req, &vc, sizeof(vc));
5480 if (vc.vc_vers != VFS_CTL_VERS1)
5482 mp = vfs_getvfs(&vc.vc_fsid);
5485 /* ensure that a specific sysctl goes to the right filesystem. */
5486 if (strcmp(vc.vc_fstypename, "*") != 0 &&
5487 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
5491 VCTLTOREQ(&vc, req);
5492 error = VFS_SYSCTL(mp, vc.vc_op, req);
5497 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
5498 NULL, 0, sysctl_vfs_ctl, "",
5502 * Function to initialize a va_filerev field sensibly.
5503 * XXX: Wouldn't a random number make a lot more sense ??
5506 init_va_filerev(void)
5511 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
5514 static int filt_vfsread(struct knote *kn, long hint);
5515 static int filt_vfswrite(struct knote *kn, long hint);
5516 static int filt_vfsvnode(struct knote *kn, long hint);
5517 static void filt_vfsdetach(struct knote *kn);
5518 static struct filterops vfsread_filtops = {
5520 .f_detach = filt_vfsdetach,
5521 .f_event = filt_vfsread
5523 static struct filterops vfswrite_filtops = {
5525 .f_detach = filt_vfsdetach,
5526 .f_event = filt_vfswrite
5528 static struct filterops vfsvnode_filtops = {
5530 .f_detach = filt_vfsdetach,
5531 .f_event = filt_vfsvnode
5535 vfs_knllock(void *arg)
5537 struct vnode *vp = arg;
5539 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5543 vfs_knlunlock(void *arg)
5545 struct vnode *vp = arg;
5551 vfs_knl_assert_locked(void *arg)
5553 #ifdef DEBUG_VFS_LOCKS
5554 struct vnode *vp = arg;
5556 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
5561 vfs_knl_assert_unlocked(void *arg)
5563 #ifdef DEBUG_VFS_LOCKS
5564 struct vnode *vp = arg;
5566 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
5571 vfs_kqfilter(struct vop_kqfilter_args *ap)
5573 struct vnode *vp = ap->a_vp;
5574 struct knote *kn = ap->a_kn;
5577 switch (kn->kn_filter) {
5579 kn->kn_fop = &vfsread_filtops;
5582 kn->kn_fop = &vfswrite_filtops;
5585 kn->kn_fop = &vfsvnode_filtops;
5591 kn->kn_hook = (caddr_t)vp;
5594 if (vp->v_pollinfo == NULL)
5596 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5598 knlist_add(knl, kn, 0);
5604 * Detach knote from vnode
5607 filt_vfsdetach(struct knote *kn)
5609 struct vnode *vp = (struct vnode *)kn->kn_hook;
5611 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
5612 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
5618 filt_vfsread(struct knote *kn, long hint)
5620 struct vnode *vp = (struct vnode *)kn->kn_hook;
5625 * filesystem is gone, so set the EOF flag and schedule
5626 * the knote for deletion.
5628 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5630 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5635 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
5639 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
5640 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
5647 filt_vfswrite(struct knote *kn, long hint)
5649 struct vnode *vp = (struct vnode *)kn->kn_hook;
5654 * filesystem is gone, so set the EOF flag and schedule
5655 * the knote for deletion.
5657 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
5658 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5666 filt_vfsvnode(struct knote *kn, long hint)
5668 struct vnode *vp = (struct vnode *)kn->kn_hook;
5672 if (kn->kn_sfflags & hint)
5673 kn->kn_fflags |= hint;
5674 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5675 kn->kn_flags |= EV_EOF;
5679 res = (kn->kn_fflags != 0);
5685 * Returns whether the directory is empty or not.
5686 * If it is empty, the return value is 0; otherwise
5687 * the return value is an error value (which may
5691 vfs_emptydir(struct vnode *vp)
5695 struct dirent *dirent, *dp, *endp;
5701 ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
5703 dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
5704 iov.iov_base = dirent;
5705 iov.iov_len = sizeof(struct dirent);
5710 uio.uio_resid = sizeof(struct dirent);
5711 uio.uio_segflg = UIO_SYSSPACE;
5712 uio.uio_rw = UIO_READ;
5713 uio.uio_td = curthread;
5715 while (eof == 0 && error == 0) {
5716 error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
5720 endp = (void *)((uint8_t *)dirent +
5721 sizeof(struct dirent) - uio.uio_resid);
5722 for (dp = dirent; dp < endp;
5723 dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
5724 if (dp->d_type == DT_WHT)
5726 if (dp->d_namlen == 0)
5728 if (dp->d_type != DT_DIR &&
5729 dp->d_type != DT_UNKNOWN) {
5733 if (dp->d_namlen > 2) {
5737 if (dp->d_namlen == 1 &&
5738 dp->d_name[0] != '.') {
5742 if (dp->d_namlen == 2 &&
5743 dp->d_name[1] != '.') {
5747 uio.uio_resid = sizeof(struct dirent);
5750 free(dirent, M_TEMP);
5755 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
5759 if (dp->d_reclen > ap->a_uio->uio_resid)
5760 return (ENAMETOOLONG);
5761 error = uiomove(dp, dp->d_reclen, ap->a_uio);
5763 if (ap->a_ncookies != NULL) {
5764 if (ap->a_cookies != NULL)
5765 free(ap->a_cookies, M_TEMP);
5766 ap->a_cookies = NULL;
5767 *ap->a_ncookies = 0;
5771 if (ap->a_ncookies == NULL)
5774 KASSERT(ap->a_cookies,
5775 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
5777 *ap->a_cookies = realloc(*ap->a_cookies,
5778 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
5779 (*ap->a_cookies)[*ap->a_ncookies] = off;
5780 *ap->a_ncookies += 1;
5785 * Mark for update the access time of the file if the filesystem
5786 * supports VOP_MARKATIME. This functionality is used by execve and
5787 * mmap, so we want to avoid the I/O implied by directly setting
5788 * va_atime for the sake of efficiency.
5791 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
5796 ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
5797 if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
5798 (void)VOP_MARKATIME(vp);
5802 * The purpose of this routine is to remove granularity from accmode_t,
5803 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
5804 * VADMIN and VAPPEND.
5806 * If it returns 0, the caller is supposed to continue with the usual
5807 * access checks using 'accmode' as modified by this routine. If it
5808 * returns nonzero value, the caller is supposed to return that value
5811 * Note that after this routine runs, accmode may be zero.
5814 vfs_unixify_accmode(accmode_t *accmode)
5817 * There is no way to specify explicit "deny" rule using
5818 * file mode or POSIX.1e ACLs.
5820 if (*accmode & VEXPLICIT_DENY) {
5826 * None of these can be translated into usual access bits.
5827 * Also, the common case for NFSv4 ACLs is to not contain
5828 * either of these bits. Caller should check for VWRITE
5829 * on the containing directory instead.
5831 if (*accmode & (VDELETE_CHILD | VDELETE))
5834 if (*accmode & VADMIN_PERMS) {
5835 *accmode &= ~VADMIN_PERMS;
5840 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
5841 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
5843 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
5849 * Clear out a doomed vnode (if any) and replace it with a new one as long
5850 * as the fs is not being unmounted. Return the root vnode to the caller.
5852 static int __noinline
5853 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
5859 if (mp->mnt_rootvnode != NULL) {
5861 vp = mp->mnt_rootvnode;
5863 if (!VN_IS_DOOMED(vp)) {
5866 error = vn_lock(vp, flags);
5875 * Clear the old one.
5877 mp->mnt_rootvnode = NULL;
5882 * Paired with a fence in vfs_op_thread_exit().
5884 atomic_thread_fence_acq();
5885 vfs_op_barrier_wait(mp);
5889 error = VFS_CACHEDROOT(mp, flags, vpp);
5892 if (mp->mnt_vfs_ops == 0) {
5894 if (mp->mnt_vfs_ops != 0) {
5898 if (mp->mnt_rootvnode == NULL) {
5900 mp->mnt_rootvnode = *vpp;
5902 if (mp->mnt_rootvnode != *vpp) {
5903 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
5904 panic("%s: mismatch between vnode returned "
5905 " by VFS_CACHEDROOT and the one cached "
5907 __func__, *vpp, mp->mnt_rootvnode);
5917 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
5922 if (!vfs_op_thread_enter(mp))
5923 return (vfs_cache_root_fallback(mp, flags, vpp));
5924 vp = (struct vnode *)atomic_load_ptr(&mp->mnt_rootvnode);
5925 if (vp == NULL || VN_IS_DOOMED(vp)) {
5926 vfs_op_thread_exit(mp);
5927 return (vfs_cache_root_fallback(mp, flags, vpp));
5930 vfs_op_thread_exit(mp);
5931 error = vn_lock(vp, flags);
5934 return (vfs_cache_root_fallback(mp, flags, vpp));
5941 vfs_cache_root_clear(struct mount *mp)
5946 * ops > 0 guarantees there is nobody who can see this vnode
5948 MPASS(mp->mnt_vfs_ops > 0);
5949 vp = mp->mnt_rootvnode;
5950 mp->mnt_rootvnode = NULL;
5955 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
5958 MPASS(mp->mnt_vfs_ops > 0);
5960 mp->mnt_rootvnode = vp;
5964 * These are helper functions for filesystems to traverse all
5965 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
5967 * This interface replaces MNT_VNODE_FOREACH.
5972 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
5977 kern_yield(PRI_USER);
5979 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5980 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
5981 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
5982 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
5983 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
5986 if (VN_IS_DOOMED(vp)) {
5993 __mnt_vnode_markerfree_all(mvp, mp);
5994 /* MNT_IUNLOCK(mp); -- done in above function */
5995 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
5998 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5999 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6005 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6009 *mvp = vn_alloc_marker(mp);
6013 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6014 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6015 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6018 if (VN_IS_DOOMED(vp)) {
6027 vn_free_marker(*mvp);
6031 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6037 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6045 mtx_assert(MNT_MTX(mp), MA_OWNED);
6047 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6048 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6051 vn_free_marker(*mvp);
6056 * These are helper functions for filesystems to traverse their
6057 * active vnodes. See MNT_VNODE_FOREACH_ACTIVE() in sys/mount.h
6060 mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
6063 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6068 vn_free_marker(*mvp);
6073 * Relock the mp mount vnode list lock with the vp vnode interlock in the
6074 * conventional lock order during mnt_vnode_next_active iteration.
6076 * On entry, the mount vnode list lock is held and the vnode interlock is not.
6077 * The list lock is dropped and reacquired. On success, both locks are held.
6078 * On failure, the mount vnode list lock is held but the vnode interlock is
6079 * not, and the procedure may have yielded.
6082 mnt_vnode_next_active_relock(struct vnode *mvp, struct mount *mp,
6085 const struct vnode *tmp;
6088 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6089 TAILQ_NEXT(mvp, v_actfreelist) != NULL, mvp,
6090 ("%s: bad marker", __func__));
6091 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6092 ("%s: inappropriate vnode", __func__));
6093 ASSERT_VI_UNLOCKED(vp, __func__);
6094 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6098 TAILQ_REMOVE(&mp->mnt_activevnodelist, mvp, v_actfreelist);
6099 TAILQ_INSERT_BEFORE(vp, mvp, v_actfreelist);
6102 * Use a hold to prevent vp from disappearing while the mount vnode
6103 * list lock is dropped and reacquired. Normally a hold would be
6104 * acquired with vhold(), but that might try to acquire the vnode
6105 * interlock, which would be a LOR with the mount vnode list lock.
6107 held = refcount_acquire_if_not_zero(&vp->v_holdcnt);
6108 mtx_unlock(&mp->mnt_listmtx);
6112 if (!refcount_release_if_not_last(&vp->v_holdcnt)) {
6116 mtx_lock(&mp->mnt_listmtx);
6119 * Determine whether the vnode is still the next one after the marker,
6120 * excepting any other markers. If the vnode has not been doomed by
6121 * vgone() then the hold should have ensured that it remained on the
6122 * active list. If it has been doomed but is still on the active list,
6123 * don't abort, but rather skip over it (avoid spinning on doomed
6128 tmp = TAILQ_NEXT(tmp, v_actfreelist);
6129 } while (tmp != NULL && tmp->v_type == VMARKER);
6131 mtx_unlock(&mp->mnt_listmtx);
6140 mtx_lock(&mp->mnt_listmtx);
6143 ASSERT_VI_LOCKED(vp, __func__);
6145 ASSERT_VI_UNLOCKED(vp, __func__);
6146 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6150 static struct vnode *
6151 mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
6153 struct vnode *vp, *nvp;
6155 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6156 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6158 vp = TAILQ_NEXT(*mvp, v_actfreelist);
6159 while (vp != NULL) {
6160 if (vp->v_type == VMARKER) {
6161 vp = TAILQ_NEXT(vp, v_actfreelist);
6165 * Try-lock because this is the wrong lock order. If that does
6166 * not succeed, drop the mount vnode list lock and try to
6167 * reacquire it and the vnode interlock in the right order.
6169 if (!VI_TRYLOCK(vp) &&
6170 !mnt_vnode_next_active_relock(*mvp, mp, vp))
6172 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6173 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6174 ("alien vnode on the active list %p %p", vp, mp));
6175 if (vp->v_mount == mp && !VN_IS_DOOMED(vp))
6177 nvp = TAILQ_NEXT(vp, v_actfreelist);
6181 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
6183 /* Check if we are done */
6185 mtx_unlock(&mp->mnt_listmtx);
6186 mnt_vnode_markerfree_active(mvp, mp);
6189 TAILQ_INSERT_AFTER(&mp->mnt_activevnodelist, vp, *mvp, v_actfreelist);
6190 mtx_unlock(&mp->mnt_listmtx);
6191 ASSERT_VI_LOCKED(vp, "active iter");
6192 KASSERT((vp->v_iflag & VI_ACTIVE) != 0, ("Non-active vp %p", vp));
6197 __mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
6201 kern_yield(PRI_USER);
6202 mtx_lock(&mp->mnt_listmtx);
6203 return (mnt_vnode_next_active(mvp, mp));
6207 __mnt_vnode_first_active(struct vnode **mvp, struct mount *mp)
6211 *mvp = vn_alloc_marker(mp);
6216 mtx_lock(&mp->mnt_listmtx);
6217 vp = TAILQ_FIRST(&mp->mnt_activevnodelist);
6219 mtx_unlock(&mp->mnt_listmtx);
6220 mnt_vnode_markerfree_active(mvp, mp);
6223 TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
6224 return (mnt_vnode_next_active(mvp, mp));
6228 __mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
6234 mtx_lock(&mp->mnt_listmtx);
6235 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
6236 mtx_unlock(&mp->mnt_listmtx);
6237 mnt_vnode_markerfree_active(mvp, mp);