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 destroy_vpollinfo(struct vpollinfo *vi);
118 static int v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
119 daddr_t startlbn, daddr_t endlbn);
120 static void vnlru_recalc(void);
123 * These fences are intended for cases where some synchronization is
124 * needed between access of v_iflags and lockless vnode refcount (v_holdcnt
125 * and v_usecount) updates. Access to v_iflags is generally synchronized
126 * by the interlock, but we have some internal assertions that check vnode
127 * flags without acquiring the lock. Thus, these fences are INVARIANTS-only
131 #define VNODE_REFCOUNT_FENCE_ACQ() atomic_thread_fence_acq()
132 #define VNODE_REFCOUNT_FENCE_REL() atomic_thread_fence_rel()
134 #define VNODE_REFCOUNT_FENCE_ACQ()
135 #define VNODE_REFCOUNT_FENCE_REL()
139 * Number of vnodes in existence. Increased whenever getnewvnode()
140 * allocates a new vnode, decreased in vdropl() for VIRF_DOOMED vnode.
142 static u_long __exclusive_cache_line numvnodes;
144 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
145 "Number of vnodes in existence");
147 static counter_u64_t vnodes_created;
148 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
149 "Number of vnodes created by getnewvnode");
152 * Conversion tables for conversion from vnode types to inode formats
155 enum vtype iftovt_tab[16] = {
156 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
157 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
159 int vttoif_tab[10] = {
160 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
161 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
165 * List of allocates vnodes in the system.
167 static TAILQ_HEAD(freelst, vnode) vnode_list;
168 static struct vnode *vnode_list_free_marker;
169 static struct vnode *vnode_list_reclaim_marker;
172 * "Free" vnode target. Free vnodes are rarely completely free, but are
173 * just ones that are cheap to recycle. Usually they are for files which
174 * have been stat'd but not read; these usually have inode and namecache
175 * data attached to them. This target is the preferred minimum size of a
176 * sub-cache consisting mostly of such files. The system balances the size
177 * of this sub-cache with its complement to try to prevent either from
178 * thrashing while the other is relatively inactive. The targets express
179 * a preference for the best balance.
181 * "Above" this target there are 2 further targets (watermarks) related
182 * to recyling of free vnodes. In the best-operating case, the cache is
183 * exactly full, the free list has size between vlowat and vhiwat above the
184 * free target, and recycling from it and normal use maintains this state.
185 * Sometimes the free list is below vlowat or even empty, but this state
186 * is even better for immediate use provided the cache is not full.
187 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
188 * ones) to reach one of these states. The watermarks are currently hard-
189 * coded as 4% and 9% of the available space higher. These and the default
190 * of 25% for wantfreevnodes are too large if the memory size is large.
191 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
192 * whenever vnlru_proc() becomes active.
194 static long wantfreevnodes;
195 static long __exclusive_cache_line freevnodes;
196 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
197 &freevnodes, 0, "Number of \"free\" vnodes");
198 static long freevnodes_old;
200 static counter_u64_t recycles_count;
201 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
202 "Number of vnodes recycled to meet vnode cache targets");
204 static counter_u64_t recycles_free_count;
205 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD, &recycles_free_count,
206 "Number of free vnodes recycled to meet vnode cache targets");
209 * Various variables used for debugging the new implementation of
211 * XXX these are probably of (very) limited utility now.
213 static int reassignbufcalls;
214 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW | CTLFLAG_STATS,
215 &reassignbufcalls, 0, "Number of calls to reassignbuf");
217 static counter_u64_t deferred_inact;
218 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, deferred_inact, CTLFLAG_RD, &deferred_inact,
219 "Number of times inactive processing was deferred");
221 /* To keep more than one thread at a time from running vfs_getnewfsid */
222 static struct mtx mntid_mtx;
225 * Lock for any access to the following:
230 static struct mtx __exclusive_cache_line vnode_list_mtx;
232 /* Publicly exported FS */
233 struct nfs_public nfs_pub;
235 static uma_zone_t buf_trie_zone;
237 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
238 static uma_zone_t vnode_zone;
239 static uma_zone_t vnodepoll_zone;
242 * The workitem queue.
244 * It is useful to delay writes of file data and filesystem metadata
245 * for tens of seconds so that quickly created and deleted files need
246 * not waste disk bandwidth being created and removed. To realize this,
247 * we append vnodes to a "workitem" queue. When running with a soft
248 * updates implementation, most pending metadata dependencies should
249 * not wait for more than a few seconds. Thus, mounted on block devices
250 * are delayed only about a half the time that file data is delayed.
251 * Similarly, directory updates are more critical, so are only delayed
252 * about a third the time that file data is delayed. Thus, there are
253 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
254 * one each second (driven off the filesystem syncer process). The
255 * syncer_delayno variable indicates the next queue that is to be processed.
256 * Items that need to be processed soon are placed in this queue:
258 * syncer_workitem_pending[syncer_delayno]
260 * A delay of fifteen seconds is done by placing the request fifteen
261 * entries later in the queue:
263 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
266 static int syncer_delayno;
267 static long syncer_mask;
268 LIST_HEAD(synclist, bufobj);
269 static struct synclist *syncer_workitem_pending;
271 * The sync_mtx protects:
276 * syncer_workitem_pending
277 * syncer_worklist_len
280 static struct mtx sync_mtx;
281 static struct cv sync_wakeup;
283 #define SYNCER_MAXDELAY 32
284 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
285 static int syncdelay = 30; /* max time to delay syncing data */
286 static int filedelay = 30; /* time to delay syncing files */
287 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
288 "Time to delay syncing files (in seconds)");
289 static int dirdelay = 29; /* time to delay syncing directories */
290 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
291 "Time to delay syncing directories (in seconds)");
292 static int metadelay = 28; /* time to delay syncing metadata */
293 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
294 "Time to delay syncing metadata (in seconds)");
295 static int rushjob; /* number of slots to run ASAP */
296 static int stat_rush_requests; /* number of times I/O speeded up */
297 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
298 "Number of times I/O speeded up (rush requests)");
300 #define VDBATCH_SIZE 8
305 struct vnode *tab[VDBATCH_SIZE];
307 DPCPU_DEFINE_STATIC(struct vdbatch, vd);
309 static void vdbatch_dequeue(struct vnode *vp);
312 * When shutting down the syncer, run it at four times normal speed.
314 #define SYNCER_SHUTDOWN_SPEEDUP 4
315 static int sync_vnode_count;
316 static int syncer_worklist_len;
317 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
320 /* Target for maximum number of vnodes. */
321 u_long desiredvnodes;
322 static u_long gapvnodes; /* gap between wanted and desired */
323 static u_long vhiwat; /* enough extras after expansion */
324 static u_long vlowat; /* minimal extras before expansion */
325 static u_long vstir; /* nonzero to stir non-free vnodes */
326 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
328 static u_long vnlru_read_freevnodes(void);
331 * Note that no attempt is made to sanitize these parameters.
334 sysctl_maxvnodes(SYSCTL_HANDLER_ARGS)
340 error = sysctl_handle_long(oidp, &val, 0, req);
341 if (error != 0 || req->newptr == NULL)
344 if (val == desiredvnodes)
346 mtx_lock(&vnode_list_mtx);
348 wantfreevnodes = desiredvnodes / 4;
350 mtx_unlock(&vnode_list_mtx);
352 * XXX There is no protection against multiple threads changing
353 * desiredvnodes at the same time. Locking above only helps vnlru and
356 vfs_hash_changesize(desiredvnodes);
357 cache_changesize(desiredvnodes);
361 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
362 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
363 "LU", "Target for maximum number of vnodes");
366 sysctl_wantfreevnodes(SYSCTL_HANDLER_ARGS)
371 val = wantfreevnodes;
372 error = sysctl_handle_long(oidp, &val, 0, req);
373 if (error != 0 || req->newptr == NULL)
376 if (val == wantfreevnodes)
378 mtx_lock(&vnode_list_mtx);
379 wantfreevnodes = val;
381 mtx_unlock(&vnode_list_mtx);
385 SYSCTL_PROC(_vfs, OID_AUTO, wantfreevnodes,
386 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
387 "LU", "Target for minimum number of \"free\" vnodes");
389 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
390 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
391 static int vnlru_nowhere;
392 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
393 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
396 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
401 unsigned long ndflags;
404 if (req->newptr == NULL)
406 if (req->newlen >= PATH_MAX)
409 buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
410 error = SYSCTL_IN(req, buf, req->newlen);
414 buf[req->newlen] = '\0';
416 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | NOCACHE | SAVENAME;
417 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
418 if ((error = namei(&nd)) != 0)
422 if (VN_IS_DOOMED(vp)) {
424 * This vnode is being recycled. Return != 0 to let the caller
425 * know that the sysctl had no effect. Return EAGAIN because a
426 * subsequent call will likely succeed (since namei will create
427 * a new vnode if necessary)
433 counter_u64_add(recycles_count, 1);
443 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
445 struct thread *td = curthread;
451 if (req->newptr == NULL)
454 error = sysctl_handle_int(oidp, &fd, 0, req);
457 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
462 error = vn_lock(vp, LK_EXCLUSIVE);
466 counter_u64_add(recycles_count, 1);
474 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
475 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
476 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
477 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
478 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
479 sysctl_ftry_reclaim_vnode, "I",
480 "Try to reclaim a vnode by its file descriptor");
482 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
486 * Support for the bufobj clean & dirty pctrie.
489 buf_trie_alloc(struct pctrie *ptree)
492 return uma_zalloc(buf_trie_zone, M_NOWAIT);
496 buf_trie_free(struct pctrie *ptree, void *node)
499 uma_zfree(buf_trie_zone, node);
501 PCTRIE_DEFINE(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free);
504 * Initialize the vnode management data structures.
506 * Reevaluate the following cap on the number of vnodes after the physical
507 * memory size exceeds 512GB. In the limit, as the physical memory size
508 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
510 #ifndef MAXVNODES_MAX
511 #define MAXVNODES_MAX (512UL * 1024 * 1024 / 64) /* 8M */
514 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
516 static struct vnode *
517 vn_alloc_marker(struct mount *mp)
521 vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
522 vp->v_type = VMARKER;
529 vn_free_marker(struct vnode *vp)
532 MPASS(vp->v_type == VMARKER);
533 free(vp, M_VNODE_MARKER);
537 * Initialize a vnode as it first enters the zone.
540 vnode_init(void *mem, int size, int flags)
549 vp->v_vnlock = &vp->v_lock;
550 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
552 * By default, don't allow shared locks unless filesystems opt-in.
554 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
555 LK_NOSHARE | LK_IS_VNODE);
559 bufobj_init(&vp->v_bufobj, vp);
561 * Initialize namecache.
563 LIST_INIT(&vp->v_cache_src);
564 TAILQ_INIT(&vp->v_cache_dst);
566 * Initialize rangelocks.
568 rangelock_init(&vp->v_rl);
570 vp->v_dbatchcpu = NOCPU;
572 mtx_lock(&vnode_list_mtx);
573 TAILQ_INSERT_BEFORE(vnode_list_free_marker, vp, v_vnodelist);
574 mtx_unlock(&vnode_list_mtx);
579 * Free a vnode when it is cleared from the zone.
582 vnode_fini(void *mem, int size)
589 mtx_lock(&vnode_list_mtx);
590 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
591 mtx_unlock(&vnode_list_mtx);
592 rangelock_destroy(&vp->v_rl);
593 lockdestroy(vp->v_vnlock);
594 mtx_destroy(&vp->v_interlock);
596 rw_destroy(BO_LOCKPTR(bo));
600 * Provide the size of NFS nclnode and NFS fh for calculation of the
601 * vnode memory consumption. The size is specified directly to
602 * eliminate dependency on NFS-private header.
604 * Other filesystems may use bigger or smaller (like UFS and ZFS)
605 * private inode data, but the NFS-based estimation is ample enough.
606 * Still, we care about differences in the size between 64- and 32-bit
609 * Namecache structure size is heuristically
610 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
613 #define NFS_NCLNODE_SZ (528 + 64)
616 #define NFS_NCLNODE_SZ (360 + 32)
621 vntblinit(void *dummy __unused)
624 int cpu, physvnodes, virtvnodes;
628 * Desiredvnodes is a function of the physical memory size and the
629 * kernel's heap size. Generally speaking, it scales with the
630 * physical memory size. The ratio of desiredvnodes to the physical
631 * memory size is 1:16 until desiredvnodes exceeds 98,304.
633 * marginal ratio of desiredvnodes to the physical memory size is
634 * 1:64. However, desiredvnodes is limited by the kernel's heap
635 * size. The memory required by desiredvnodes vnodes and vm objects
636 * must not exceed 1/10th of the kernel's heap size.
638 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
639 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
640 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
641 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
642 desiredvnodes = min(physvnodes, virtvnodes);
643 if (desiredvnodes > MAXVNODES_MAX) {
645 printf("Reducing kern.maxvnodes %lu -> %lu\n",
646 desiredvnodes, MAXVNODES_MAX);
647 desiredvnodes = MAXVNODES_MAX;
649 wantfreevnodes = desiredvnodes / 4;
650 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
651 TAILQ_INIT(&vnode_list);
652 mtx_init(&vnode_list_mtx, "vnode_list", NULL, MTX_DEF);
654 * The lock is taken to appease WITNESS.
656 mtx_lock(&vnode_list_mtx);
658 mtx_unlock(&vnode_list_mtx);
659 vnode_list_free_marker = vn_alloc_marker(NULL);
660 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_free_marker, v_vnodelist);
661 vnode_list_reclaim_marker = vn_alloc_marker(NULL);
662 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_reclaim_marker, v_vnodelist);
663 vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
664 vnode_init, vnode_fini, UMA_ALIGN_PTR, 0);
665 vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
666 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
668 * Preallocate enough nodes to support one-per buf so that
669 * we can not fail an insert. reassignbuf() callers can not
670 * tolerate the insertion failure.
672 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
673 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
675 uma_prealloc(buf_trie_zone, nbuf);
677 vnodes_created = counter_u64_alloc(M_WAITOK);
678 recycles_count = counter_u64_alloc(M_WAITOK);
679 recycles_free_count = counter_u64_alloc(M_WAITOK);
680 deferred_inact = counter_u64_alloc(M_WAITOK);
683 * Initialize the filesystem syncer.
685 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
687 syncer_maxdelay = syncer_mask + 1;
688 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
689 cv_init(&sync_wakeup, "syncer");
690 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
695 vd = DPCPU_ID_PTR((cpu), vd);
696 bzero(vd, sizeof(*vd));
697 mtx_init(&vd->lock, "vdbatch", NULL, MTX_DEF);
700 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
703 * Mark a mount point as busy. Used to synchronize access and to delay
704 * unmounting. Eventually, mountlist_mtx is not released on failure.
706 * vfs_busy() is a custom lock, it can block the caller.
707 * vfs_busy() only sleeps if the unmount is active on the mount point.
708 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
709 * vnode belonging to mp.
711 * Lookup uses vfs_busy() to traverse mount points.
713 * / vnode lock A / vnode lock (/var) D
714 * /var vnode lock B /log vnode lock(/var/log) E
715 * vfs_busy lock C vfs_busy lock F
717 * Within each file system, the lock order is C->A->B and F->D->E.
719 * When traversing across mounts, the system follows that lock order:
725 * The lookup() process for namei("/var") illustrates the process:
726 * VOP_LOOKUP() obtains B while A is held
727 * vfs_busy() obtains a shared lock on F while A and B are held
728 * vput() releases lock on B
729 * vput() releases lock on A
730 * VFS_ROOT() obtains lock on D while shared lock on F is held
731 * vfs_unbusy() releases shared lock on F
732 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
733 * Attempt to lock A (instead of vp_crossmp) while D is held would
734 * violate the global order, causing deadlocks.
736 * dounmount() locks B while F is drained.
739 vfs_busy(struct mount *mp, int flags)
742 MPASS((flags & ~MBF_MASK) == 0);
743 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
745 if (vfs_op_thread_enter(mp)) {
746 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
747 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
748 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
749 vfs_mp_count_add_pcpu(mp, ref, 1);
750 vfs_mp_count_add_pcpu(mp, lockref, 1);
751 vfs_op_thread_exit(mp);
752 if (flags & MBF_MNTLSTLOCK)
753 mtx_unlock(&mountlist_mtx);
758 vfs_assert_mount_counters(mp);
761 * If mount point is currently being unmounted, sleep until the
762 * mount point fate is decided. If thread doing the unmounting fails,
763 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
764 * that this mount point has survived the unmount attempt and vfs_busy
765 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
766 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
767 * about to be really destroyed. vfs_busy needs to release its
768 * reference on the mount point in this case and return with ENOENT,
769 * telling the caller that mount mount it tried to busy is no longer
772 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
773 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
776 CTR1(KTR_VFS, "%s: failed busying before sleeping",
780 if (flags & MBF_MNTLSTLOCK)
781 mtx_unlock(&mountlist_mtx);
782 mp->mnt_kern_flag |= MNTK_MWAIT;
783 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
784 if (flags & MBF_MNTLSTLOCK)
785 mtx_lock(&mountlist_mtx);
788 if (flags & MBF_MNTLSTLOCK)
789 mtx_unlock(&mountlist_mtx);
796 * Free a busy filesystem.
799 vfs_unbusy(struct mount *mp)
803 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
805 if (vfs_op_thread_enter(mp)) {
806 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
807 vfs_mp_count_sub_pcpu(mp, lockref, 1);
808 vfs_mp_count_sub_pcpu(mp, ref, 1);
809 vfs_op_thread_exit(mp);
814 vfs_assert_mount_counters(mp);
816 c = --mp->mnt_lockref;
817 if (mp->mnt_vfs_ops == 0) {
818 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
823 vfs_dump_mount_counters(mp);
824 if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
825 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
826 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
827 mp->mnt_kern_flag &= ~MNTK_DRAINING;
828 wakeup(&mp->mnt_lockref);
834 * Lookup a mount point by filesystem identifier.
837 vfs_getvfs(fsid_t *fsid)
841 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
842 mtx_lock(&mountlist_mtx);
843 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
844 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
846 mtx_unlock(&mountlist_mtx);
850 mtx_unlock(&mountlist_mtx);
851 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
852 return ((struct mount *) 0);
856 * Lookup a mount point by filesystem identifier, busying it before
859 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
860 * cache for popular filesystem identifiers. The cache is lockess, using
861 * the fact that struct mount's are never freed. In worst case we may
862 * get pointer to unmounted or even different filesystem, so we have to
863 * check what we got, and go slow way if so.
866 vfs_busyfs(fsid_t *fsid)
868 #define FSID_CACHE_SIZE 256
869 typedef struct mount * volatile vmp_t;
870 static vmp_t cache[FSID_CACHE_SIZE];
875 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
876 hash = fsid->val[0] ^ fsid->val[1];
877 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
879 if (mp == NULL || fsidcmp(&mp->mnt_stat.f_fsid, fsid) != 0)
881 if (vfs_busy(mp, 0) != 0) {
885 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0)
891 mtx_lock(&mountlist_mtx);
892 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
893 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
894 error = vfs_busy(mp, MBF_MNTLSTLOCK);
897 mtx_unlock(&mountlist_mtx);
904 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
905 mtx_unlock(&mountlist_mtx);
906 return ((struct mount *) 0);
910 * Check if a user can access privileged mount options.
913 vfs_suser(struct mount *mp, struct thread *td)
917 if (jailed(td->td_ucred)) {
919 * If the jail of the calling thread lacks permission for
920 * this type of file system, deny immediately.
922 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
926 * If the file system was mounted outside the jail of the
927 * calling thread, deny immediately.
929 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
934 * If file system supports delegated administration, we don't check
935 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
936 * by the file system itself.
937 * If this is not the user that did original mount, we check for
938 * the PRIV_VFS_MOUNT_OWNER privilege.
940 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
941 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
942 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
949 * Get a new unique fsid. Try to make its val[0] unique, since this value
950 * will be used to create fake device numbers for stat(). Also try (but
951 * not so hard) make its val[0] unique mod 2^16, since some emulators only
952 * support 16-bit device numbers. We end up with unique val[0]'s for the
953 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
955 * Keep in mind that several mounts may be running in parallel. Starting
956 * the search one past where the previous search terminated is both a
957 * micro-optimization and a defense against returning the same fsid to
961 vfs_getnewfsid(struct mount *mp)
963 static uint16_t mntid_base;
968 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
969 mtx_lock(&mntid_mtx);
970 mtype = mp->mnt_vfc->vfc_typenum;
971 tfsid.val[1] = mtype;
972 mtype = (mtype & 0xFF) << 24;
974 tfsid.val[0] = makedev(255,
975 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
977 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
981 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
982 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
983 mtx_unlock(&mntid_mtx);
987 * Knob to control the precision of file timestamps:
989 * 0 = seconds only; nanoseconds zeroed.
990 * 1 = seconds and nanoseconds, accurate within 1/HZ.
991 * 2 = seconds and nanoseconds, truncated to microseconds.
992 * >=3 = seconds and nanoseconds, maximum precision.
994 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
996 static int timestamp_precision = TSP_USEC;
997 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
998 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
999 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
1000 "3+: sec + ns (max. precision))");
1003 * Get a current timestamp.
1006 vfs_timestamp(struct timespec *tsp)
1010 switch (timestamp_precision) {
1012 tsp->tv_sec = time_second;
1020 TIMEVAL_TO_TIMESPEC(&tv, tsp);
1030 * Set vnode attributes to VNOVAL
1033 vattr_null(struct vattr *vap)
1036 vap->va_type = VNON;
1037 vap->va_size = VNOVAL;
1038 vap->va_bytes = VNOVAL;
1039 vap->va_mode = VNOVAL;
1040 vap->va_nlink = VNOVAL;
1041 vap->va_uid = VNOVAL;
1042 vap->va_gid = VNOVAL;
1043 vap->va_fsid = VNOVAL;
1044 vap->va_fileid = VNOVAL;
1045 vap->va_blocksize = VNOVAL;
1046 vap->va_rdev = VNOVAL;
1047 vap->va_atime.tv_sec = VNOVAL;
1048 vap->va_atime.tv_nsec = VNOVAL;
1049 vap->va_mtime.tv_sec = VNOVAL;
1050 vap->va_mtime.tv_nsec = VNOVAL;
1051 vap->va_ctime.tv_sec = VNOVAL;
1052 vap->va_ctime.tv_nsec = VNOVAL;
1053 vap->va_birthtime.tv_sec = VNOVAL;
1054 vap->va_birthtime.tv_nsec = VNOVAL;
1055 vap->va_flags = VNOVAL;
1056 vap->va_gen = VNOVAL;
1057 vap->va_vaflags = 0;
1061 * Try to reduce the total number of vnodes.
1063 * This routine (and its user) are buggy in at least the following ways:
1064 * - all parameters were picked years ago when RAM sizes were significantly
1066 * - it can pick vnodes based on pages used by the vm object, but filesystems
1067 * like ZFS don't use it making the pick broken
1068 * - since ZFS has its own aging policy it gets partially combated by this one
1069 * - a dedicated method should be provided for filesystems to let them decide
1070 * whether the vnode should be recycled
1072 * This routine is called when we have too many vnodes. It attempts
1073 * to free <count> vnodes and will potentially free vnodes that still
1074 * have VM backing store (VM backing store is typically the cause
1075 * of a vnode blowout so we want to do this). Therefore, this operation
1076 * is not considered cheap.
1078 * A number of conditions may prevent a vnode from being reclaimed.
1079 * the buffer cache may have references on the vnode, a directory
1080 * vnode may still have references due to the namei cache representing
1081 * underlying files, or the vnode may be in active use. It is not
1082 * desirable to reuse such vnodes. These conditions may cause the
1083 * number of vnodes to reach some minimum value regardless of what
1084 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
1086 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1087 * entries if this argument is strue
1088 * @param trigger Only reclaim vnodes with fewer than this many resident
1090 * @param target How many vnodes to reclaim.
1091 * @return The number of vnodes that were reclaimed.
1094 vlrureclaim(bool reclaim_nc_src, int trigger, u_long target)
1096 struct vnode *vp, *mvp;
1098 struct vm_object *object;
1102 mtx_assert(&vnode_list_mtx, MA_OWNED);
1107 mvp = vnode_list_reclaim_marker;
1110 while (done < target) {
1111 vp = TAILQ_NEXT(vp, v_vnodelist);
1112 if (__predict_false(vp == NULL))
1115 if (__predict_false(vp->v_type == VMARKER))
1119 * If it's been deconstructed already, it's still
1120 * referenced, or it exceeds the trigger, skip it.
1121 * Also skip free vnodes. We are trying to make space
1122 * to expand the free list, not reduce it.
1124 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1125 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)))
1128 if (vp->v_type == VBAD || vp->v_type == VNON)
1131 if (!VI_TRYLOCK(vp))
1134 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1135 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1136 VN_IS_DOOMED(vp) || vp->v_type == VNON) {
1141 object = atomic_load_ptr(&vp->v_object);
1142 if (object == NULL || object->resident_page_count > trigger) {
1149 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1150 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1151 mtx_unlock(&vnode_list_mtx);
1153 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1155 goto next_iter_unlocked;
1157 if (VOP_LOCK(vp, LK_EXCLUSIVE|LK_NOWAIT) != 0) {
1159 vn_finished_write(mp);
1160 goto next_iter_unlocked;
1164 if (vp->v_usecount > 0 ||
1165 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1166 (vp->v_object != NULL &&
1167 vp->v_object->resident_page_count > trigger)) {
1170 vn_finished_write(mp);
1171 goto next_iter_unlocked;
1173 counter_u64_add(recycles_count, 1);
1177 vn_finished_write(mp);
1181 kern_yield(PRI_USER);
1182 mtx_lock(&vnode_list_mtx);
1185 MPASS(vp->v_type != VMARKER);
1186 if (!should_yield())
1188 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1189 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1190 mtx_unlock(&vnode_list_mtx);
1191 kern_yield(PRI_USER);
1192 mtx_lock(&vnode_list_mtx);
1195 if (done == 0 && !retried) {
1196 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1197 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1204 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1205 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1207 "limit on vnode free requests per call to the vnlru_free routine");
1210 * Attempt to reduce the free list by the requested amount.
1213 vnlru_free_locked(int count, struct vfsops *mnt_op)
1215 struct vnode *vp, *mvp;
1219 mtx_assert(&vnode_list_mtx, MA_OWNED);
1220 if (count > max_vnlru_free)
1221 count = max_vnlru_free;
1223 mvp = vnode_list_free_marker;
1227 vp = TAILQ_NEXT(vp, v_vnodelist);
1228 if (__predict_false(vp == NULL)) {
1229 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1230 TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1233 if (__predict_false(vp->v_type == VMARKER))
1237 * Don't recycle if our vnode is from different type
1238 * of mount point. Note that mp is type-safe, the
1239 * check does not reach unmapped address even if
1240 * vnode is reclaimed.
1241 * Don't recycle if we can't get the interlock without
1244 if (vp->v_holdcnt > 0 || (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1245 mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
1248 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1249 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1250 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1256 mtx_unlock(&vnode_list_mtx);
1260 mtx_lock(&vnode_list_mtx);
1263 return (ocount - count);
1267 vnlru_free(int count, struct vfsops *mnt_op)
1270 mtx_lock(&vnode_list_mtx);
1271 vnlru_free_locked(count, mnt_op);
1272 mtx_unlock(&vnode_list_mtx);
1279 mtx_assert(&vnode_list_mtx, MA_OWNED);
1280 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1281 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1282 vlowat = vhiwat / 2;
1286 * Attempt to recycle vnodes in a context that is always safe to block.
1287 * Calling vlrurecycle() from the bowels of filesystem code has some
1288 * interesting deadlock problems.
1290 static struct proc *vnlruproc;
1291 static int vnlruproc_sig;
1294 * The main freevnodes counter is only updated when threads requeue their vnode
1295 * batches. CPUs are conditionally walked to compute a more accurate total.
1297 * Limit how much of a slop are we willing to tolerate. Note: the actual value
1298 * at any given moment can still exceed slop, but it should not be by significant
1299 * margin in practice.
1301 #define VNLRU_FREEVNODES_SLOP 128
1304 vnlru_read_freevnodes(void)
1310 mtx_assert(&vnode_list_mtx, MA_OWNED);
1311 if (freevnodes > freevnodes_old)
1312 slop = freevnodes - freevnodes_old;
1314 slop = freevnodes_old - freevnodes;
1315 if (slop < VNLRU_FREEVNODES_SLOP)
1316 return (freevnodes >= 0 ? freevnodes : 0);
1317 freevnodes_old = freevnodes;
1319 vd = DPCPU_ID_PTR((cpu), vd);
1320 freevnodes_old += vd->freevnodes;
1322 return (freevnodes_old >= 0 ? freevnodes_old : 0);
1326 vnlru_under(u_long rnumvnodes, u_long limit)
1328 u_long rfreevnodes, space;
1330 if (__predict_false(rnumvnodes > desiredvnodes))
1333 space = desiredvnodes - rnumvnodes;
1334 if (space < limit) {
1335 rfreevnodes = vnlru_read_freevnodes();
1336 if (rfreevnodes > wantfreevnodes)
1337 space += rfreevnodes - wantfreevnodes;
1339 return (space < limit);
1343 vnlru_under_unlocked(u_long rnumvnodes, u_long limit)
1345 long rfreevnodes, space;
1347 if (__predict_false(rnumvnodes > desiredvnodes))
1350 space = desiredvnodes - rnumvnodes;
1351 if (space < limit) {
1352 rfreevnodes = atomic_load_long(&freevnodes);
1353 if (rfreevnodes > wantfreevnodes)
1354 space += rfreevnodes - wantfreevnodes;
1356 return (space < limit);
1363 mtx_assert(&vnode_list_mtx, MA_OWNED);
1364 if (vnlruproc_sig == 0) {
1373 u_long rnumvnodes, rfreevnodes, target;
1374 unsigned long onumvnodes;
1375 int done, force, trigger, usevnodes;
1376 bool reclaim_nc_src, want_reread;
1378 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1379 SHUTDOWN_PRI_FIRST);
1382 want_reread = false;
1384 kproc_suspend_check(vnlruproc);
1385 mtx_lock(&vnode_list_mtx);
1386 rnumvnodes = atomic_load_long(&numvnodes);
1389 force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1390 want_reread = false;
1394 * If numvnodes is too large (due to desiredvnodes being
1395 * adjusted using its sysctl, or emergency growth), first
1396 * try to reduce it by discarding from the free list.
1398 if (rnumvnodes > desiredvnodes) {
1399 vnlru_free_locked(rnumvnodes - desiredvnodes, NULL);
1400 rnumvnodes = atomic_load_long(&numvnodes);
1403 * Sleep if the vnode cache is in a good state. This is
1404 * when it is not over-full and has space for about a 4%
1405 * or 9% expansion (by growing its size or inexcessively
1406 * reducing its free list). Otherwise, try to reclaim
1407 * space for a 10% expansion.
1409 if (vstir && force == 0) {
1413 if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1415 wakeup(&vnlruproc_sig);
1416 msleep(vnlruproc, &vnode_list_mtx,
1417 PVFS|PDROP, "vlruwt", hz);
1420 rfreevnodes = vnlru_read_freevnodes();
1422 onumvnodes = rnumvnodes;
1424 * Calculate parameters for recycling. These are the same
1425 * throughout the loop to give some semblance of fairness.
1426 * The trigger point is to avoid recycling vnodes with lots
1427 * of resident pages. We aren't trying to free memory; we
1428 * are trying to recycle or at least free vnodes.
1430 if (rnumvnodes <= desiredvnodes)
1431 usevnodes = rnumvnodes - rfreevnodes;
1433 usevnodes = rnumvnodes;
1437 * The trigger value is is chosen to give a conservatively
1438 * large value to ensure that it alone doesn't prevent
1439 * making progress. The value can easily be so large that
1440 * it is effectively infinite in some congested and
1441 * misconfigured cases, and this is necessary. Normally
1442 * it is about 8 to 100 (pages), which is quite large.
1444 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1446 trigger = vsmalltrigger;
1447 reclaim_nc_src = force >= 3;
1448 target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1449 target = target / 10 + 1;
1450 done = vlrureclaim(reclaim_nc_src, trigger, target);
1451 mtx_unlock(&vnode_list_mtx);
1452 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1453 uma_reclaim(UMA_RECLAIM_DRAIN);
1455 if (force == 0 || force == 1) {
1466 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1469 kern_yield(PRI_USER);
1474 static struct kproc_desc vnlru_kp = {
1479 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1483 * Routines having to do with the management of the vnode table.
1487 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1488 * before we actually vgone(). This function must be called with the vnode
1489 * held to prevent the vnode from being returned to the free list midway
1493 vtryrecycle(struct vnode *vp)
1497 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1498 VNASSERT(vp->v_holdcnt, vp,
1499 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1501 * This vnode may found and locked via some other list, if so we
1502 * can't recycle it yet.
1504 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1506 "%s: impossible to recycle, vp %p lock is already held",
1508 return (EWOULDBLOCK);
1511 * Don't recycle if its filesystem is being suspended.
1513 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1516 "%s: impossible to recycle, cannot start the write for %p",
1521 * If we got this far, we need to acquire the interlock and see if
1522 * anyone picked up this vnode from another list. If not, we will
1523 * mark it with DOOMED via vgonel() so that anyone who does find it
1524 * will skip over it.
1527 if (vp->v_usecount) {
1530 vn_finished_write(vnmp);
1532 "%s: impossible to recycle, %p is already referenced",
1536 if (!VN_IS_DOOMED(vp)) {
1537 counter_u64_add(recycles_free_count, 1);
1542 vn_finished_write(vnmp);
1547 * Allocate a new vnode.
1549 * The operation never returns an error. Returning an error was disabled
1550 * in r145385 (dated 2005) with the following comment:
1552 * XXX Not all VFS_VGET/ffs_vget callers check returns.
1554 * Given the age of this commit (almost 15 years at the time of writing this
1555 * comment) restoring the ability to fail requires a significant audit of
1558 * The routine can try to free a vnode or stall for up to 1 second waiting for
1559 * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1561 static u_long vn_alloc_cyclecount;
1563 static struct vnode * __noinline
1564 vn_alloc_hard(struct mount *mp)
1566 u_long rnumvnodes, rfreevnodes;
1568 mtx_lock(&vnode_list_mtx);
1569 rnumvnodes = atomic_load_long(&numvnodes);
1570 if (rnumvnodes + 1 < desiredvnodes) {
1571 vn_alloc_cyclecount = 0;
1574 rfreevnodes = vnlru_read_freevnodes();
1575 if (vn_alloc_cyclecount++ >= rfreevnodes) {
1576 vn_alloc_cyclecount = 0;
1580 * Grow the vnode cache if it will not be above its target max
1581 * after growing. Otherwise, if the free list is nonempty, try
1582 * to reclaim 1 item from it before growing the cache (possibly
1583 * above its target max if the reclamation failed or is delayed).
1584 * Otherwise, wait for some space. In all cases, schedule
1585 * vnlru_proc() if we are getting short of space. The watermarks
1586 * should be chosen so that we never wait or even reclaim from
1587 * the free list to below its target minimum.
1589 if (vnlru_free_locked(1, NULL) > 0)
1591 if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1593 * Wait for space for a new vnode.
1596 msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1597 if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1598 vnlru_read_freevnodes() > 1)
1599 vnlru_free_locked(1, NULL);
1602 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1603 if (vnlru_under(rnumvnodes, vlowat))
1605 mtx_unlock(&vnode_list_mtx);
1606 return (uma_zalloc(vnode_zone, M_WAITOK));
1609 static struct vnode *
1610 vn_alloc(struct mount *mp)
1614 if (__predict_false(vn_alloc_cyclecount != 0))
1615 return (vn_alloc_hard(mp));
1616 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1617 if (__predict_false(vnlru_under_unlocked(rnumvnodes, vlowat))) {
1618 atomic_subtract_long(&numvnodes, 1);
1619 return (vn_alloc_hard(mp));
1622 return (uma_zalloc(vnode_zone, M_WAITOK));
1626 vn_free(struct vnode *vp)
1629 atomic_subtract_long(&numvnodes, 1);
1630 uma_zfree(vnode_zone, vp);
1634 * Return the next vnode from the free list.
1637 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1642 struct lock_object *lo;
1644 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1646 KASSERT(vops->registered,
1647 ("%s: not registered vector op %p\n", __func__, vops));
1650 if (td->td_vp_reserved != NULL) {
1651 vp = td->td_vp_reserved;
1652 td->td_vp_reserved = NULL;
1656 counter_u64_add(vnodes_created, 1);
1658 * Locks are given the generic name "vnode" when created.
1659 * Follow the historic practice of using the filesystem
1660 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1662 * Locks live in a witness group keyed on their name. Thus,
1663 * when a lock is renamed, it must also move from the witness
1664 * group of its old name to the witness group of its new name.
1666 * The change only needs to be made when the vnode moves
1667 * from one filesystem type to another. We ensure that each
1668 * filesystem use a single static name pointer for its tag so
1669 * that we can compare pointers rather than doing a strcmp().
1671 lo = &vp->v_vnlock->lock_object;
1673 if (lo->lo_name != tag) {
1677 WITNESS_DESTROY(lo);
1678 WITNESS_INIT(lo, tag);
1682 * By default, don't allow shared locks unless filesystems opt-in.
1684 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1686 * Finalize various vnode identity bits.
1688 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1689 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1690 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1693 v_init_counters(vp);
1694 vp->v_bufobj.bo_ops = &buf_ops_bio;
1696 if (mp == NULL && vops != &dead_vnodeops)
1697 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1701 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1702 mac_vnode_associate_singlelabel(mp, vp);
1705 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1706 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1707 vp->v_vflag |= VV_NOKNOTE;
1711 * For the filesystems which do not use vfs_hash_insert(),
1712 * still initialize v_hash to have vfs_hash_index() useful.
1713 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1716 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1723 getnewvnode_reserve(void)
1728 MPASS(td->td_vp_reserved == NULL);
1729 td->td_vp_reserved = vn_alloc(NULL);
1733 getnewvnode_drop_reserve(void)
1738 if (td->td_vp_reserved != NULL) {
1739 vn_free(td->td_vp_reserved);
1740 td->td_vp_reserved = NULL;
1745 freevnode(struct vnode *vp)
1750 * The vnode has been marked for destruction, so free it.
1752 * The vnode will be returned to the zone where it will
1753 * normally remain until it is needed for another vnode. We
1754 * need to cleanup (or verify that the cleanup has already
1755 * been done) any residual data left from its current use
1756 * so as not to contaminate the freshly allocated vnode.
1758 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1760 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1761 VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
1762 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1763 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1764 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1765 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1766 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1767 ("clean blk trie not empty"));
1768 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1769 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1770 ("dirty blk trie not empty"));
1771 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1772 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1773 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1774 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1775 ("Dangling rangelock waiters"));
1778 mac_vnode_destroy(vp);
1780 if (vp->v_pollinfo != NULL) {
1781 destroy_vpollinfo(vp->v_pollinfo);
1782 vp->v_pollinfo = NULL;
1785 /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
1788 vp->v_mountedhere = NULL;
1791 vp->v_fifoinfo = NULL;
1792 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
1801 * Delete from old mount point vnode list, if on one.
1804 delmntque(struct vnode *vp)
1808 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
1817 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1818 ("bad mount point vnode list size"));
1819 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1820 mp->mnt_nvnodelistsize--;
1826 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1830 vp->v_op = &dead_vnodeops;
1836 * Insert into list of vnodes for the new mount point, if available.
1839 insmntque1(struct vnode *vp, struct mount *mp,
1840 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1843 KASSERT(vp->v_mount == NULL,
1844 ("insmntque: vnode already on per mount vnode list"));
1845 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1846 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1849 * We acquire the vnode interlock early to ensure that the
1850 * vnode cannot be recycled by another process releasing a
1851 * holdcnt on it before we get it on both the vnode list
1852 * and the active vnode list. The mount mutex protects only
1853 * manipulation of the vnode list and the vnode freelist
1854 * mutex protects only manipulation of the active vnode list.
1855 * Hence the need to hold the vnode interlock throughout.
1859 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1860 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1861 mp->mnt_nvnodelistsize == 0)) &&
1862 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1871 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1872 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1873 ("neg mount point vnode list size"));
1874 mp->mnt_nvnodelistsize++;
1881 insmntque(struct vnode *vp, struct mount *mp)
1884 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1888 * Flush out and invalidate all buffers associated with a bufobj
1889 * Called with the underlying object locked.
1892 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1897 if (flags & V_SAVE) {
1898 error = bufobj_wwait(bo, slpflag, slptimeo);
1903 if (bo->bo_dirty.bv_cnt > 0) {
1905 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1908 * XXX We could save a lock/unlock if this was only
1909 * enabled under INVARIANTS
1912 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1913 panic("vinvalbuf: dirty bufs");
1917 * If you alter this loop please notice that interlock is dropped and
1918 * reacquired in flushbuflist. Special care is needed to ensure that
1919 * no race conditions occur from this.
1922 error = flushbuflist(&bo->bo_clean,
1923 flags, bo, slpflag, slptimeo);
1924 if (error == 0 && !(flags & V_CLEANONLY))
1925 error = flushbuflist(&bo->bo_dirty,
1926 flags, bo, slpflag, slptimeo);
1927 if (error != 0 && error != EAGAIN) {
1931 } while (error != 0);
1934 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1935 * have write I/O in-progress but if there is a VM object then the
1936 * VM object can also have read-I/O in-progress.
1939 bufobj_wwait(bo, 0, 0);
1940 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
1942 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
1945 } while (bo->bo_numoutput > 0);
1949 * Destroy the copy in the VM cache, too.
1951 if (bo->bo_object != NULL &&
1952 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1953 VM_OBJECT_WLOCK(bo->bo_object);
1954 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1955 OBJPR_CLEANONLY : 0);
1956 VM_OBJECT_WUNLOCK(bo->bo_object);
1961 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1962 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1963 bo->bo_clean.bv_cnt > 0))
1964 panic("vinvalbuf: flush failed");
1965 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1966 bo->bo_dirty.bv_cnt > 0)
1967 panic("vinvalbuf: flush dirty failed");
1974 * Flush out and invalidate all buffers associated with a vnode.
1975 * Called with the underlying object locked.
1978 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1981 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1982 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1983 if (vp->v_object != NULL && vp->v_object->handle != vp)
1985 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1989 * Flush out buffers on the specified list.
1993 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1996 struct buf *bp, *nbp;
2001 ASSERT_BO_WLOCKED(bo);
2004 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2006 * If we are flushing both V_NORMAL and V_ALT buffers then
2007 * do not skip any buffers. If we are flushing only V_NORMAL
2008 * buffers then skip buffers marked as BX_ALTDATA. If we are
2009 * flushing only V_ALT buffers then skip buffers not marked
2012 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2013 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2014 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2018 lblkno = nbp->b_lblkno;
2019 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2022 error = BUF_TIMELOCK(bp,
2023 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2024 "flushbuf", slpflag, slptimeo);
2027 return (error != ENOLCK ? error : EAGAIN);
2029 KASSERT(bp->b_bufobj == bo,
2030 ("bp %p wrong b_bufobj %p should be %p",
2031 bp, bp->b_bufobj, bo));
2033 * XXX Since there are no node locks for NFS, I
2034 * believe there is a slight chance that a delayed
2035 * write will occur while sleeping just above, so
2038 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2041 bp->b_flags |= B_ASYNC;
2044 return (EAGAIN); /* XXX: why not loop ? */
2047 bp->b_flags |= (B_INVAL | B_RELBUF);
2048 bp->b_flags &= ~B_ASYNC;
2053 nbp = gbincore(bo, lblkno);
2054 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2056 break; /* nbp invalid */
2062 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2068 ASSERT_BO_LOCKED(bo);
2070 for (lblkno = startn;;) {
2072 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2073 if (bp == NULL || bp->b_lblkno >= endn ||
2074 bp->b_lblkno < startn)
2076 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2077 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2080 if (error == ENOLCK)
2084 KASSERT(bp->b_bufobj == bo,
2085 ("bp %p wrong b_bufobj %p should be %p",
2086 bp, bp->b_bufobj, bo));
2087 lblkno = bp->b_lblkno + 1;
2088 if ((bp->b_flags & B_MANAGED) == 0)
2090 bp->b_flags |= B_RELBUF;
2092 * In the VMIO case, use the B_NOREUSE flag to hint that the
2093 * pages backing each buffer in the range are unlikely to be
2094 * reused. Dirty buffers will have the hint applied once
2095 * they've been written.
2097 if ((bp->b_flags & B_VMIO) != 0)
2098 bp->b_flags |= B_NOREUSE;
2106 * Truncate a file's buffer and pages to a specified length. This
2107 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2111 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2113 struct buf *bp, *nbp;
2117 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2118 vp, blksize, (uintmax_t)length);
2121 * Round up to the *next* lbn.
2123 startlbn = howmany(length, blksize);
2125 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2131 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2136 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2137 if (bp->b_lblkno > 0)
2140 * Since we hold the vnode lock this should only
2141 * fail if we're racing with the buf daemon.
2144 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2145 BO_LOCKPTR(bo)) == ENOLCK)
2146 goto restart_unlocked;
2148 VNASSERT((bp->b_flags & B_DELWRI), vp,
2149 ("buf(%p) on dirty queue without DELWRI", bp));
2158 bufobj_wwait(bo, 0, 0);
2160 vnode_pager_setsize(vp, length);
2166 * Invalidate the cached pages of a file's buffer within the range of block
2167 * numbers [startlbn, endlbn).
2170 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2176 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2178 start = blksize * startlbn;
2179 end = blksize * endlbn;
2183 MPASS(blksize == bo->bo_bsize);
2185 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2189 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2193 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2194 daddr_t startlbn, daddr_t endlbn)
2196 struct buf *bp, *nbp;
2199 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2200 ASSERT_BO_LOCKED(bo);
2204 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2205 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2208 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2209 BO_LOCKPTR(bo)) == ENOLCK) {
2215 bp->b_flags |= B_INVAL | B_RELBUF;
2216 bp->b_flags &= ~B_ASYNC;
2222 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2224 (nbp->b_flags & B_DELWRI) != 0))
2228 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2229 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2232 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2233 BO_LOCKPTR(bo)) == ENOLCK) {
2238 bp->b_flags |= B_INVAL | B_RELBUF;
2239 bp->b_flags &= ~B_ASYNC;
2245 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2246 (nbp->b_vp != vp) ||
2247 (nbp->b_flags & B_DELWRI) == 0))
2255 buf_vlist_remove(struct buf *bp)
2259 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2260 ASSERT_BO_WLOCKED(bp->b_bufobj);
2261 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
2262 (BX_VNDIRTY|BX_VNCLEAN),
2263 ("buf_vlist_remove: Buf %p is on two lists", bp));
2264 if (bp->b_xflags & BX_VNDIRTY)
2265 bv = &bp->b_bufobj->bo_dirty;
2267 bv = &bp->b_bufobj->bo_clean;
2268 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2269 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2271 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2275 * Add the buffer to the sorted clean or dirty block list.
2277 * NOTE: xflags is passed as a constant, optimizing this inline function!
2280 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2286 ASSERT_BO_WLOCKED(bo);
2287 KASSERT((bo->bo_flag & BO_NOBUFS) == 0,
2288 ("buf_vlist_add: bo %p does not allow bufs", bo));
2289 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2290 ("dead bo %p", bo));
2291 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2292 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2293 bp->b_xflags |= xflags;
2294 if (xflags & BX_VNDIRTY)
2300 * Keep the list ordered. Optimize empty list insertion. Assume
2301 * we tend to grow at the tail so lookup_le should usually be cheaper
2304 if (bv->bv_cnt == 0 ||
2305 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2306 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2307 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2308 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2310 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2311 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2313 panic("buf_vlist_add: Preallocated nodes insufficient.");
2318 * Look up a buffer using the buffer tries.
2321 gbincore(struct bufobj *bo, daddr_t lblkno)
2325 ASSERT_BO_LOCKED(bo);
2326 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2329 return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
2333 * Associate a buffer with a vnode.
2336 bgetvp(struct vnode *vp, struct buf *bp)
2341 ASSERT_BO_WLOCKED(bo);
2342 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2344 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2345 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2346 ("bgetvp: bp already attached! %p", bp));
2352 * Insert onto list for new vnode.
2354 buf_vlist_add(bp, bo, BX_VNCLEAN);
2358 * Disassociate a buffer from a vnode.
2361 brelvp(struct buf *bp)
2366 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2367 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2370 * Delete from old vnode list, if on one.
2372 vp = bp->b_vp; /* XXX */
2375 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2376 buf_vlist_remove(bp);
2378 panic("brelvp: Buffer %p not on queue.", bp);
2379 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2380 bo->bo_flag &= ~BO_ONWORKLST;
2381 mtx_lock(&sync_mtx);
2382 LIST_REMOVE(bo, bo_synclist);
2383 syncer_worklist_len--;
2384 mtx_unlock(&sync_mtx);
2387 bp->b_bufobj = NULL;
2393 * Add an item to the syncer work queue.
2396 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2400 ASSERT_BO_WLOCKED(bo);
2402 mtx_lock(&sync_mtx);
2403 if (bo->bo_flag & BO_ONWORKLST)
2404 LIST_REMOVE(bo, bo_synclist);
2406 bo->bo_flag |= BO_ONWORKLST;
2407 syncer_worklist_len++;
2410 if (delay > syncer_maxdelay - 2)
2411 delay = syncer_maxdelay - 2;
2412 slot = (syncer_delayno + delay) & syncer_mask;
2414 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2415 mtx_unlock(&sync_mtx);
2419 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2423 mtx_lock(&sync_mtx);
2424 len = syncer_worklist_len - sync_vnode_count;
2425 mtx_unlock(&sync_mtx);
2426 error = SYSCTL_OUT(req, &len, sizeof(len));
2430 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2431 CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2432 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2434 static struct proc *updateproc;
2435 static void sched_sync(void);
2436 static struct kproc_desc up_kp = {
2441 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2444 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2449 *bo = LIST_FIRST(slp);
2453 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2456 * We use vhold in case the vnode does not
2457 * successfully sync. vhold prevents the vnode from
2458 * going away when we unlock the sync_mtx so that
2459 * we can acquire the vnode interlock.
2462 mtx_unlock(&sync_mtx);
2464 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2466 mtx_lock(&sync_mtx);
2467 return (*bo == LIST_FIRST(slp));
2469 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2470 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2472 vn_finished_write(mp);
2474 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2476 * Put us back on the worklist. The worklist
2477 * routine will remove us from our current
2478 * position and then add us back in at a later
2481 vn_syncer_add_to_worklist(*bo, syncdelay);
2485 mtx_lock(&sync_mtx);
2489 static int first_printf = 1;
2492 * System filesystem synchronizer daemon.
2497 struct synclist *next, *slp;
2500 struct thread *td = curthread;
2502 int net_worklist_len;
2503 int syncer_final_iter;
2507 syncer_final_iter = 0;
2508 syncer_state = SYNCER_RUNNING;
2509 starttime = time_uptime;
2510 td->td_pflags |= TDP_NORUNNINGBUF;
2512 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2515 mtx_lock(&sync_mtx);
2517 if (syncer_state == SYNCER_FINAL_DELAY &&
2518 syncer_final_iter == 0) {
2519 mtx_unlock(&sync_mtx);
2520 kproc_suspend_check(td->td_proc);
2521 mtx_lock(&sync_mtx);
2523 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2524 if (syncer_state != SYNCER_RUNNING &&
2525 starttime != time_uptime) {
2527 printf("\nSyncing disks, vnodes remaining... ");
2530 printf("%d ", net_worklist_len);
2532 starttime = time_uptime;
2535 * Push files whose dirty time has expired. Be careful
2536 * of interrupt race on slp queue.
2538 * Skip over empty worklist slots when shutting down.
2541 slp = &syncer_workitem_pending[syncer_delayno];
2542 syncer_delayno += 1;
2543 if (syncer_delayno == syncer_maxdelay)
2545 next = &syncer_workitem_pending[syncer_delayno];
2547 * If the worklist has wrapped since the
2548 * it was emptied of all but syncer vnodes,
2549 * switch to the FINAL_DELAY state and run
2550 * for one more second.
2552 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2553 net_worklist_len == 0 &&
2554 last_work_seen == syncer_delayno) {
2555 syncer_state = SYNCER_FINAL_DELAY;
2556 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2558 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2559 syncer_worklist_len > 0);
2562 * Keep track of the last time there was anything
2563 * on the worklist other than syncer vnodes.
2564 * Return to the SHUTTING_DOWN state if any
2567 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2568 last_work_seen = syncer_delayno;
2569 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2570 syncer_state = SYNCER_SHUTTING_DOWN;
2571 while (!LIST_EMPTY(slp)) {
2572 error = sync_vnode(slp, &bo, td);
2574 LIST_REMOVE(bo, bo_synclist);
2575 LIST_INSERT_HEAD(next, bo, bo_synclist);
2579 if (first_printf == 0) {
2581 * Drop the sync mutex, because some watchdog
2582 * drivers need to sleep while patting
2584 mtx_unlock(&sync_mtx);
2585 wdog_kern_pat(WD_LASTVAL);
2586 mtx_lock(&sync_mtx);
2590 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2591 syncer_final_iter--;
2593 * The variable rushjob allows the kernel to speed up the
2594 * processing of the filesystem syncer process. A rushjob
2595 * value of N tells the filesystem syncer to process the next
2596 * N seconds worth of work on its queue ASAP. Currently rushjob
2597 * is used by the soft update code to speed up the filesystem
2598 * syncer process when the incore state is getting so far
2599 * ahead of the disk that the kernel memory pool is being
2600 * threatened with exhaustion.
2607 * Just sleep for a short period of time between
2608 * iterations when shutting down to allow some I/O
2611 * If it has taken us less than a second to process the
2612 * current work, then wait. Otherwise start right over
2613 * again. We can still lose time if any single round
2614 * takes more than two seconds, but it does not really
2615 * matter as we are just trying to generally pace the
2616 * filesystem activity.
2618 if (syncer_state != SYNCER_RUNNING ||
2619 time_uptime == starttime) {
2621 sched_prio(td, PPAUSE);
2624 if (syncer_state != SYNCER_RUNNING)
2625 cv_timedwait(&sync_wakeup, &sync_mtx,
2626 hz / SYNCER_SHUTDOWN_SPEEDUP);
2627 else if (time_uptime == starttime)
2628 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2633 * Request the syncer daemon to speed up its work.
2634 * We never push it to speed up more than half of its
2635 * normal turn time, otherwise it could take over the cpu.
2638 speedup_syncer(void)
2642 mtx_lock(&sync_mtx);
2643 if (rushjob < syncdelay / 2) {
2645 stat_rush_requests += 1;
2648 mtx_unlock(&sync_mtx);
2649 cv_broadcast(&sync_wakeup);
2654 * Tell the syncer to speed up its work and run though its work
2655 * list several times, then tell it to shut down.
2658 syncer_shutdown(void *arg, int howto)
2661 if (howto & RB_NOSYNC)
2663 mtx_lock(&sync_mtx);
2664 syncer_state = SYNCER_SHUTTING_DOWN;
2666 mtx_unlock(&sync_mtx);
2667 cv_broadcast(&sync_wakeup);
2668 kproc_shutdown(arg, howto);
2672 syncer_suspend(void)
2675 syncer_shutdown(updateproc, 0);
2682 mtx_lock(&sync_mtx);
2684 syncer_state = SYNCER_RUNNING;
2685 mtx_unlock(&sync_mtx);
2686 cv_broadcast(&sync_wakeup);
2687 kproc_resume(updateproc);
2691 * Reassign a buffer from one vnode to another.
2692 * Used to assign file specific control information
2693 * (indirect blocks) to the vnode to which they belong.
2696 reassignbuf(struct buf *bp)
2709 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2710 bp, bp->b_vp, bp->b_flags);
2712 * B_PAGING flagged buffers cannot be reassigned because their vp
2713 * is not fully linked in.
2715 if (bp->b_flags & B_PAGING)
2716 panic("cannot reassign paging buffer");
2719 * Delete from old vnode list, if on one.
2722 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2723 buf_vlist_remove(bp);
2725 panic("reassignbuf: Buffer %p not on queue.", bp);
2727 * If dirty, put on list of dirty buffers; otherwise insert onto list
2730 if (bp->b_flags & B_DELWRI) {
2731 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2732 switch (vp->v_type) {
2742 vn_syncer_add_to_worklist(bo, delay);
2744 buf_vlist_add(bp, bo, BX_VNDIRTY);
2746 buf_vlist_add(bp, bo, BX_VNCLEAN);
2748 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2749 mtx_lock(&sync_mtx);
2750 LIST_REMOVE(bo, bo_synclist);
2751 syncer_worklist_len--;
2752 mtx_unlock(&sync_mtx);
2753 bo->bo_flag &= ~BO_ONWORKLST;
2758 bp = TAILQ_FIRST(&bv->bv_hd);
2759 KASSERT(bp == NULL || bp->b_bufobj == bo,
2760 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2761 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2762 KASSERT(bp == NULL || bp->b_bufobj == bo,
2763 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2765 bp = TAILQ_FIRST(&bv->bv_hd);
2766 KASSERT(bp == NULL || bp->b_bufobj == bo,
2767 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2768 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2769 KASSERT(bp == NULL || bp->b_bufobj == bo,
2770 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2776 v_init_counters(struct vnode *vp)
2779 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2780 vp, ("%s called for an initialized vnode", __FUNCTION__));
2781 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2783 refcount_init(&vp->v_holdcnt, 1);
2784 refcount_init(&vp->v_usecount, 1);
2788 * Increment si_usecount of the associated device, if any.
2791 v_incr_devcount(struct vnode *vp)
2794 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2795 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2797 vp->v_rdev->si_usecount++;
2803 * Decrement si_usecount of the associated device, if any.
2805 * The caller is required to hold the interlock when transitioning a VCHR use
2806 * count to zero. This prevents a race with devfs_reclaim_vchr() that would
2807 * leak a si_usecount reference. The vnode lock will also prevent this race
2808 * if it is held while dropping the last ref.
2813 * devfs_reclaim_vchr
2814 * make v_usecount == 0
2816 * sees v_usecount == 0, no updates
2817 * vp->v_rdev = NULL;
2822 * sees v_rdev == NULL, no updates
2824 * In this scenario si_devcount decrement is not performed.
2827 v_decr_devcount(struct vnode *vp)
2830 ASSERT_VOP_LOCKED(vp, __func__);
2831 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2832 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2834 VNPASS(vp->v_rdev->si_usecount > 0, vp);
2835 vp->v_rdev->si_usecount--;
2841 * Grab a particular vnode from the free list, increment its
2842 * reference count and lock it. VIRF_DOOMED is set if the vnode
2843 * is being destroyed. Only callers who specify LK_RETRY will
2844 * see doomed vnodes. If inactive processing was delayed in
2845 * vput try to do it here.
2847 * usecount is manipulated using atomics without holding any locks.
2849 * holdcnt can be manipulated using atomics without holding any locks,
2850 * except when transitioning 1<->0, in which case the interlock is held.
2853 vget_prep(struct vnode *vp)
2857 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2867 vget(struct vnode *vp, int flags, struct thread *td)
2871 MPASS(td == curthread);
2874 return (vget_finish(vp, flags, vs));
2877 static int __noinline
2878 vget_finish_vchr(struct vnode *vp)
2881 VNASSERT(vp->v_type == VCHR, vp, ("type != VCHR)"));
2884 * See the comment in vget_finish before usecount bump.
2886 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2888 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2889 VNASSERT(old > 0, vp, ("%s: wrong hold count %d", __func__, old));
2891 refcount_release(&vp->v_holdcnt);
2897 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2899 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2900 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2902 refcount_release(&vp->v_holdcnt);
2907 v_incr_devcount(vp);
2908 refcount_acquire(&vp->v_usecount);
2914 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
2918 if ((flags & LK_INTERLOCK) != 0)
2919 ASSERT_VI_LOCKED(vp, __func__);
2921 ASSERT_VI_UNLOCKED(vp, __func__);
2922 VNPASS(vp->v_holdcnt > 0, vp);
2923 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
2925 error = vn_lock(vp, flags);
2926 if (__predict_false(error != 0)) {
2927 if (vs == VGET_USECOUNT)
2931 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2936 if (vs == VGET_USECOUNT)
2939 if (__predict_false(vp->v_type == VCHR))
2940 return (vget_finish_vchr(vp));
2943 * We hold the vnode. If the usecount is 0 it will be utilized to keep
2944 * the vnode around. Otherwise someone else lended their hold count and
2945 * we have to drop ours.
2947 old = atomic_fetchadd_int(&vp->v_usecount, 1);
2948 VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
2951 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2952 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2954 refcount_release(&vp->v_holdcnt);
2961 * Increase the reference (use) and hold count of a vnode.
2962 * This will also remove the vnode from the free list if it is presently free.
2964 static void __noinline
2965 vref_vchr(struct vnode *vp, bool interlock)
2969 * See the comment in vget_finish before usecount bump.
2972 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2973 VNODE_REFCOUNT_FENCE_ACQ();
2974 VNASSERT(vp->v_holdcnt > 0, vp,
2975 ("%s: active vnode not held", __func__));
2980 * By the time we get here the vnode might have been doomed, at
2981 * which point the 0->1 use count transition is no longer
2982 * protected by the interlock. Since it can't bounce back to
2983 * VCHR and requires vref semantics, punt it back
2985 if (__predict_false(vp->v_type == VBAD)) {
2991 VNASSERT(vp->v_type == VCHR, vp, ("type != VCHR)"));
2992 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2993 VNODE_REFCOUNT_FENCE_ACQ();
2994 VNASSERT(vp->v_holdcnt > 0, vp,
2995 ("%s: active vnode not held", __func__));
3001 v_incr_devcount(vp);
3002 refcount_acquire(&vp->v_usecount);
3009 vref(struct vnode *vp)
3013 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3014 if (__predict_false(vp->v_type == VCHR)) {
3015 vref_vchr(vp, false);
3019 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3020 VNODE_REFCOUNT_FENCE_ACQ();
3021 VNASSERT(vp->v_holdcnt > 0, vp,
3022 ("%s: active vnode not held", __func__));
3027 * See the comment in vget_finish.
3029 old = atomic_fetchadd_int(&vp->v_usecount, 1);
3030 VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
3033 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
3034 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
3036 refcount_release(&vp->v_holdcnt);
3042 vrefl(struct vnode *vp)
3045 ASSERT_VI_LOCKED(vp, __func__);
3046 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3047 if (__predict_false(vp->v_type == VCHR)) {
3048 vref_vchr(vp, true);
3055 vrefact(struct vnode *vp)
3058 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3060 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
3061 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3063 refcount_acquire(&vp->v_usecount);
3068 vrefactn(struct vnode *vp, u_int n)
3071 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3073 int old = atomic_fetchadd_int(&vp->v_usecount, n);
3074 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3076 atomic_add_int(&vp->v_usecount, n);
3081 * Return reference count of a vnode.
3083 * The results of this call are only guaranteed when some mechanism is used to
3084 * stop other processes from gaining references to the vnode. This may be the
3085 * case if the caller holds the only reference. This is also useful when stale
3086 * data is acceptable as race conditions may be accounted for by some other
3090 vrefcnt(struct vnode *vp)
3093 return (vp->v_usecount);
3097 vlazy(struct vnode *vp)
3101 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
3103 if ((vp->v_mflag & VMP_LAZYLIST) != 0)
3106 * We may get here for inactive routines after the vnode got doomed.
3108 if (VN_IS_DOOMED(vp))
3111 mtx_lock(&mp->mnt_listmtx);
3112 if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
3113 vp->v_mflag |= VMP_LAZYLIST;
3114 TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3115 mp->mnt_lazyvnodelistsize++;
3117 mtx_unlock(&mp->mnt_listmtx);
3121 * This routine is only meant to be called from vgonel prior to dooming
3125 vunlazy_gone(struct vnode *vp)
3129 ASSERT_VOP_ELOCKED(vp, __func__);
3130 ASSERT_VI_LOCKED(vp, __func__);
3131 VNPASS(!VN_IS_DOOMED(vp), vp);
3133 if (vp->v_mflag & VMP_LAZYLIST) {
3135 mtx_lock(&mp->mnt_listmtx);
3136 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3137 vp->v_mflag &= ~VMP_LAZYLIST;
3138 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3139 mp->mnt_lazyvnodelistsize--;
3140 mtx_unlock(&mp->mnt_listmtx);
3145 vdefer_inactive(struct vnode *vp)
3148 ASSERT_VI_LOCKED(vp, __func__);
3149 VNASSERT(vp->v_holdcnt > 0, vp,
3150 ("%s: vnode without hold count", __func__));
3151 if (VN_IS_DOOMED(vp)) {
3155 if (vp->v_iflag & VI_DEFINACT) {
3156 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3160 if (vp->v_usecount > 0) {
3161 vp->v_iflag &= ~VI_OWEINACT;
3166 vp->v_iflag |= VI_DEFINACT;
3168 counter_u64_add(deferred_inact, 1);
3172 vdefer_inactive_unlocked(struct vnode *vp)
3176 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3180 vdefer_inactive(vp);
3183 enum vput_op { VRELE, VPUT, VUNREF };
3186 * Handle ->v_usecount transitioning to 0.
3188 * By releasing the last usecount we take ownership of the hold count which
3189 * provides liveness of the vnode, meaning we have to vdrop.
3191 * If the vnode is of type VCHR we may need to decrement si_usecount, see
3192 * v_decr_devcount for details.
3194 * For all vnodes we may need to perform inactive processing. It requires an
3195 * exclusive lock on the vnode, while it is legal to call here with only a
3196 * shared lock (or no locks). If locking the vnode in an expected manner fails,
3197 * inactive processing gets deferred to the syncer.
3199 * XXX Some filesystems pass in an exclusively locked vnode and strongly depend
3200 * on the lock being held all the way until VOP_INACTIVE. This in particular
3201 * happens with UFS which adds half-constructed vnodes to the hash, where they
3202 * can be found by other code.
3205 vput_final(struct vnode *vp, enum vput_op func)
3210 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3211 VNPASS(vp->v_holdcnt > 0, vp);
3214 if (__predict_false(vp->v_type == VCHR && func != VRELE))
3215 v_decr_devcount(vp);
3218 * By the time we got here someone else might have transitioned
3219 * the count back to > 0.
3221 if (vp->v_usecount > 0)
3225 * If the vnode is doomed vgone already performed inactive processing
3228 if (VN_IS_DOOMED(vp))
3231 if (__predict_true(VOP_NEED_INACTIVE(vp) == 0))
3234 if (vp->v_iflag & VI_DOINGINACT)
3238 * Locking operations here will drop the interlock and possibly the
3239 * vnode lock, opening a window where the vnode can get doomed all the
3240 * while ->v_usecount is 0. Set VI_OWEINACT to let vgone know to
3243 vp->v_iflag |= VI_OWEINACT;
3244 want_unlock = false;
3248 switch (VOP_ISLOCKED(vp)) {
3254 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3259 * The lock has at least one sharer, but we have no way
3260 * to conclude whether this is us. Play it safe and
3269 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3270 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3276 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3277 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3288 vdefer_inactive(vp);
3298 * Decrement ->v_usecount for a vnode.
3300 * Releasing the last use count requires additional processing, see vput_final
3301 * above for details.
3303 * Note that releasing use count without the vnode lock requires special casing
3304 * for VCHR, see v_decr_devcount for details.
3306 * Comment above each variant denotes lock state on entry and exit.
3309 static void __noinline
3310 vrele_vchr(struct vnode *vp)
3313 if (refcount_release_if_not_last(&vp->v_usecount))
3316 if (!refcount_release(&vp->v_usecount)) {
3320 v_decr_devcount(vp);
3322 vput_final(vp, VRELE);
3327 * out: same as passed in
3330 vrele(struct vnode *vp)
3333 ASSERT_VI_UNLOCKED(vp, __func__);
3334 if (__predict_false(vp->v_type == VCHR)) {
3338 if (!refcount_release(&vp->v_usecount))
3340 vput_final(vp, VRELE);
3348 vput(struct vnode *vp)
3351 ASSERT_VOP_LOCKED(vp, __func__);
3352 ASSERT_VI_UNLOCKED(vp, __func__);
3353 if (!refcount_release(&vp->v_usecount)) {
3357 vput_final(vp, VPUT);
3365 vunref(struct vnode *vp)
3368 ASSERT_VOP_LOCKED(vp, __func__);
3369 ASSERT_VI_UNLOCKED(vp, __func__);
3370 if (!refcount_release(&vp->v_usecount))
3372 vput_final(vp, VUNREF);
3376 vhold(struct vnode *vp)
3381 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3382 old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3383 VNASSERT(old >= 0, vp, ("%s: wrong hold count %d", __func__, old));
3393 vholdl(struct vnode *vp)
3396 ASSERT_VI_LOCKED(vp, __func__);
3397 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3402 vholdnz(struct vnode *vp)
3405 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3407 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3408 VNASSERT(old > 0, vp, ("%s: wrong hold count %d", __func__, old));
3410 atomic_add_int(&vp->v_holdcnt, 1);
3414 static void __noinline
3415 vdbatch_process(struct vdbatch *vd)
3420 mtx_assert(&vd->lock, MA_OWNED);
3421 MPASS(curthread->td_pinned > 0);
3422 MPASS(vd->index == VDBATCH_SIZE);
3424 mtx_lock(&vnode_list_mtx);
3426 freevnodes += vd->freevnodes;
3427 for (i = 0; i < VDBATCH_SIZE; i++) {
3429 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3430 TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3431 MPASS(vp->v_dbatchcpu != NOCPU);
3432 vp->v_dbatchcpu = NOCPU;
3434 mtx_unlock(&vnode_list_mtx);
3436 bzero(vd->tab, sizeof(vd->tab));
3442 vdbatch_enqueue(struct vnode *vp)
3446 ASSERT_VI_LOCKED(vp, __func__);
3447 VNASSERT(!VN_IS_DOOMED(vp), vp,
3448 ("%s: deferring requeue of a doomed vnode", __func__));
3453 if (vp->v_dbatchcpu != NOCPU) {
3461 mtx_lock(&vd->lock);
3462 MPASS(vd->index < VDBATCH_SIZE);
3463 MPASS(vd->tab[vd->index] == NULL);
3465 * A hack: we depend on being pinned so that we know what to put in
3468 vp->v_dbatchcpu = curcpu;
3469 vd->tab[vd->index] = vp;
3472 if (vd->index == VDBATCH_SIZE)
3473 vdbatch_process(vd);
3474 mtx_unlock(&vd->lock);
3479 * This routine must only be called for vnodes which are about to be
3480 * deallocated. Supporting dequeue for arbitrary vndoes would require
3481 * validating that the locked batch matches.
3484 vdbatch_dequeue(struct vnode *vp)
3490 VNASSERT(vp->v_type == VBAD || vp->v_type == VNON, vp,
3491 ("%s: called for a used vnode\n", __func__));
3493 cpu = vp->v_dbatchcpu;
3497 vd = DPCPU_ID_PTR(cpu, vd);
3498 mtx_lock(&vd->lock);
3499 for (i = 0; i < vd->index; i++) {
3500 if (vd->tab[i] != vp)
3502 vp->v_dbatchcpu = NOCPU;
3504 vd->tab[i] = vd->tab[vd->index];
3505 vd->tab[vd->index] = NULL;
3508 mtx_unlock(&vd->lock);
3510 * Either we dequeued the vnode above or the target CPU beat us to it.
3512 MPASS(vp->v_dbatchcpu == NOCPU);
3516 * Drop the hold count of the vnode. If this is the last reference to
3517 * the vnode we place it on the free list unless it has been vgone'd
3518 * (marked VIRF_DOOMED) in which case we will free it.
3520 * Because the vnode vm object keeps a hold reference on the vnode if
3521 * there is at least one resident non-cached page, the vnode cannot
3522 * leave the active list without the page cleanup done.
3525 vdrop_deactivate(struct vnode *vp)
3529 ASSERT_VI_LOCKED(vp, __func__);
3531 * Mark a vnode as free: remove it from its active list
3532 * and put it up for recycling on the freelist.
3534 VNASSERT(!VN_IS_DOOMED(vp), vp,
3535 ("vdrop: returning doomed vnode"));
3536 VNASSERT(vp->v_op != NULL, vp,
3537 ("vdrop: vnode already reclaimed."));
3538 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
3539 ("vnode with VI_OWEINACT set"));
3540 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp,
3541 ("vnode with VI_DEFINACT set"));
3542 if (vp->v_mflag & VMP_LAZYLIST) {
3544 mtx_lock(&mp->mnt_listmtx);
3545 VNASSERT(vp->v_mflag & VMP_LAZYLIST, vp, ("lost VMP_LAZYLIST"));
3547 * Don't remove the vnode from the lazy list if another thread
3548 * has increased the hold count. It may have re-enqueued the
3549 * vnode to the lazy list and is now responsible for its
3552 if (vp->v_holdcnt == 0) {
3553 vp->v_mflag &= ~VMP_LAZYLIST;
3554 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3555 mp->mnt_lazyvnodelistsize--;
3557 mtx_unlock(&mp->mnt_listmtx);
3559 vdbatch_enqueue(vp);
3563 vdrop(struct vnode *vp)
3566 ASSERT_VI_UNLOCKED(vp, __func__);
3567 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3568 if (refcount_release_if_not_last(&vp->v_holdcnt))
3575 vdropl(struct vnode *vp)
3578 ASSERT_VI_LOCKED(vp, __func__);
3579 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3580 if (!refcount_release(&vp->v_holdcnt)) {
3584 if (VN_IS_DOOMED(vp)) {
3588 vdrop_deactivate(vp);
3592 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3593 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3596 vinactivef(struct vnode *vp)
3598 struct vm_object *obj;
3600 ASSERT_VOP_ELOCKED(vp, "vinactive");
3601 ASSERT_VI_LOCKED(vp, "vinactive");
3602 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3603 ("vinactive: recursed on VI_DOINGINACT"));
3604 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3605 vp->v_iflag |= VI_DOINGINACT;
3606 vp->v_iflag &= ~VI_OWEINACT;
3609 * Before moving off the active list, we must be sure that any
3610 * modified pages are converted into the vnode's dirty
3611 * buffers, since these will no longer be checked once the
3612 * vnode is on the inactive list.
3614 * The write-out of the dirty pages is asynchronous. At the
3615 * point that VOP_INACTIVE() is called, there could still be
3616 * pending I/O and dirty pages in the object.
3618 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3619 vm_object_mightbedirty(obj)) {
3620 VM_OBJECT_WLOCK(obj);
3621 vm_object_page_clean(obj, 0, 0, 0);
3622 VM_OBJECT_WUNLOCK(obj);
3624 VOP_INACTIVE(vp, curthread);
3626 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3627 ("vinactive: lost VI_DOINGINACT"));
3628 vp->v_iflag &= ~VI_DOINGINACT;
3632 vinactive(struct vnode *vp)
3635 ASSERT_VOP_ELOCKED(vp, "vinactive");
3636 ASSERT_VI_LOCKED(vp, "vinactive");
3637 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3639 if ((vp->v_iflag & VI_OWEINACT) == 0)
3641 if (vp->v_iflag & VI_DOINGINACT)
3643 if (vp->v_usecount > 0) {
3644 vp->v_iflag &= ~VI_OWEINACT;
3651 * Remove any vnodes in the vnode table belonging to mount point mp.
3653 * If FORCECLOSE is not specified, there should not be any active ones,
3654 * return error if any are found (nb: this is a user error, not a
3655 * system error). If FORCECLOSE is specified, detach any active vnodes
3658 * If WRITECLOSE is set, only flush out regular file vnodes open for
3661 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3663 * `rootrefs' specifies the base reference count for the root vnode
3664 * of this filesystem. The root vnode is considered busy if its
3665 * v_usecount exceeds this value. On a successful return, vflush(, td)
3666 * will call vrele() on the root vnode exactly rootrefs times.
3667 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3671 static int busyprt = 0; /* print out busy vnodes */
3672 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3676 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3678 struct vnode *vp, *mvp, *rootvp = NULL;
3680 int busy = 0, error;
3682 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3685 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3686 ("vflush: bad args"));
3688 * Get the filesystem root vnode. We can vput() it
3689 * immediately, since with rootrefs > 0, it won't go away.
3691 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3692 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3699 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3701 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3704 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3708 * Skip over a vnodes marked VV_SYSTEM.
3710 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3716 * If WRITECLOSE is set, flush out unlinked but still open
3717 * files (even if open only for reading) and regular file
3718 * vnodes open for writing.
3720 if (flags & WRITECLOSE) {
3721 if (vp->v_object != NULL) {
3722 VM_OBJECT_WLOCK(vp->v_object);
3723 vm_object_page_clean(vp->v_object, 0, 0, 0);
3724 VM_OBJECT_WUNLOCK(vp->v_object);
3726 error = VOP_FSYNC(vp, MNT_WAIT, td);
3730 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3733 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3736 if ((vp->v_type == VNON ||
3737 (error == 0 && vattr.va_nlink > 0)) &&
3738 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3746 * With v_usecount == 0, all we need to do is clear out the
3747 * vnode data structures and we are done.
3749 * If FORCECLOSE is set, forcibly close the vnode.
3751 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3757 vn_printf(vp, "vflush: busy vnode ");
3763 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3765 * If just the root vnode is busy, and if its refcount
3766 * is equal to `rootrefs', then go ahead and kill it.
3769 KASSERT(busy > 0, ("vflush: not busy"));
3770 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3771 ("vflush: usecount %d < rootrefs %d",
3772 rootvp->v_usecount, rootrefs));
3773 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3774 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3782 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3786 for (; rootrefs > 0; rootrefs--)
3792 * Recycle an unused vnode to the front of the free list.
3795 vrecycle(struct vnode *vp)
3800 recycled = vrecyclel(vp);
3806 * vrecycle, with the vp interlock held.
3809 vrecyclel(struct vnode *vp)
3813 ASSERT_VOP_ELOCKED(vp, __func__);
3814 ASSERT_VI_LOCKED(vp, __func__);
3815 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3817 if (vp->v_usecount == 0) {
3825 * Eliminate all activity associated with a vnode
3826 * in preparation for reuse.
3829 vgone(struct vnode *vp)
3837 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3838 struct vnode *lowervp __unused)
3843 * Notify upper mounts about reclaimed or unlinked vnode.
3846 vfs_notify_upper(struct vnode *vp, int event)
3848 static struct vfsops vgonel_vfsops = {
3849 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3850 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3852 struct mount *mp, *ump, *mmp;
3857 if (TAILQ_EMPTY(&mp->mnt_uppers))
3860 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3861 mmp->mnt_op = &vgonel_vfsops;
3862 mmp->mnt_kern_flag |= MNTK_MARKER;
3864 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3865 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3866 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3867 ump = TAILQ_NEXT(ump, mnt_upper_link);
3870 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3873 case VFS_NOTIFY_UPPER_RECLAIM:
3874 VFS_RECLAIM_LOWERVP(ump, vp);
3876 case VFS_NOTIFY_UPPER_UNLINK:
3877 VFS_UNLINK_LOWERVP(ump, vp);
3880 KASSERT(0, ("invalid event %d", event));
3884 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3885 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3888 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3889 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3890 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3891 wakeup(&mp->mnt_uppers);
3897 * vgone, with the vp interlock held.
3900 vgonel(struct vnode *vp)
3905 bool active, oweinact;
3907 ASSERT_VOP_ELOCKED(vp, "vgonel");
3908 ASSERT_VI_LOCKED(vp, "vgonel");
3909 VNASSERT(vp->v_holdcnt, vp,
3910 ("vgonel: vp %p has no reference.", vp));
3911 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3915 * Don't vgonel if we're already doomed.
3917 if (vp->v_irflag & VIRF_DOOMED)
3920 vp->v_irflag |= VIRF_DOOMED;
3923 * Check to see if the vnode is in use. If so, we have to call
3924 * VOP_CLOSE() and VOP_INACTIVE().
3926 active = vp->v_usecount > 0;
3927 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
3929 * If we need to do inactive VI_OWEINACT will be set.
3931 if (vp->v_iflag & VI_DEFINACT) {
3932 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3933 vp->v_iflag &= ~VI_DEFINACT;
3936 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
3939 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
3942 * If purging an active vnode, it must be closed and
3943 * deactivated before being reclaimed.
3946 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
3947 if (oweinact || active) {
3952 if (vp->v_type == VSOCK)
3953 vfs_unp_reclaim(vp);
3956 * Clean out any buffers associated with the vnode.
3957 * If the flush fails, just toss the buffers.
3960 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
3961 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
3962 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
3963 while (vinvalbuf(vp, 0, 0, 0) != 0)
3967 BO_LOCK(&vp->v_bufobj);
3968 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
3969 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
3970 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
3971 vp->v_bufobj.bo_clean.bv_cnt == 0,
3972 ("vp %p bufobj not invalidated", vp));
3975 * For VMIO bufobj, BO_DEAD is set later, or in
3976 * vm_object_terminate() after the object's page queue is
3979 object = vp->v_bufobj.bo_object;
3981 vp->v_bufobj.bo_flag |= BO_DEAD;
3982 BO_UNLOCK(&vp->v_bufobj);
3985 * Handle the VM part. Tmpfs handles v_object on its own (the
3986 * OBJT_VNODE check). Nullfs or other bypassing filesystems
3987 * should not touch the object borrowed from the lower vnode
3988 * (the handle check).
3990 if (object != NULL && object->type == OBJT_VNODE &&
3991 object->handle == vp)
3992 vnode_destroy_vobject(vp);
3995 * Reclaim the vnode.
3997 if (VOP_RECLAIM(vp, td))
3998 panic("vgone: cannot reclaim");
4000 vn_finished_secondary_write(mp);
4001 VNASSERT(vp->v_object == NULL, vp,
4002 ("vop_reclaim left v_object vp=%p", vp));
4004 * Clear the advisory locks and wake up waiting threads.
4006 (void)VOP_ADVLOCKPURGE(vp);
4009 * Delete from old mount point vnode list.
4014 * Done with purge, reset to the standard lock and invalidate
4018 vp->v_vnlock = &vp->v_lock;
4019 vp->v_op = &dead_vnodeops;
4024 * Calculate the total number of references to a special device.
4027 vcount(struct vnode *vp)
4032 count = vp->v_rdev->si_usecount;
4038 * Print out a description of a vnode.
4040 static const char * const typename[] =
4041 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
4045 vn_printf(struct vnode *vp, const char *fmt, ...)
4048 char buf[256], buf2[16];
4054 printf("%p: ", (void *)vp);
4055 printf("type %s\n", typename[vp->v_type]);
4056 printf(" usecount %d, writecount %d, refcount %d",
4057 vp->v_usecount, vp->v_writecount, vp->v_holdcnt);
4058 switch (vp->v_type) {
4060 printf(" mountedhere %p\n", vp->v_mountedhere);
4063 printf(" rdev %p\n", vp->v_rdev);
4066 printf(" socket %p\n", vp->v_unpcb);
4069 printf(" fifoinfo %p\n", vp->v_fifoinfo);
4077 if (vp->v_irflag & VIRF_DOOMED)
4078 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
4079 flags = vp->v_irflag & ~(VIRF_DOOMED);
4081 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
4082 strlcat(buf, buf2, sizeof(buf));
4084 if (vp->v_vflag & VV_ROOT)
4085 strlcat(buf, "|VV_ROOT", sizeof(buf));
4086 if (vp->v_vflag & VV_ISTTY)
4087 strlcat(buf, "|VV_ISTTY", sizeof(buf));
4088 if (vp->v_vflag & VV_NOSYNC)
4089 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
4090 if (vp->v_vflag & VV_ETERNALDEV)
4091 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
4092 if (vp->v_vflag & VV_CACHEDLABEL)
4093 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
4094 if (vp->v_vflag & VV_VMSIZEVNLOCK)
4095 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
4096 if (vp->v_vflag & VV_COPYONWRITE)
4097 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
4098 if (vp->v_vflag & VV_SYSTEM)
4099 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
4100 if (vp->v_vflag & VV_PROCDEP)
4101 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
4102 if (vp->v_vflag & VV_NOKNOTE)
4103 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
4104 if (vp->v_vflag & VV_DELETED)
4105 strlcat(buf, "|VV_DELETED", sizeof(buf));
4106 if (vp->v_vflag & VV_MD)
4107 strlcat(buf, "|VV_MD", sizeof(buf));
4108 if (vp->v_vflag & VV_FORCEINSMQ)
4109 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
4110 if (vp->v_vflag & VV_READLINK)
4111 strlcat(buf, "|VV_READLINK", sizeof(buf));
4112 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4113 VV_CACHEDLABEL | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
4114 VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
4116 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4117 strlcat(buf, buf2, sizeof(buf));
4119 if (vp->v_iflag & VI_TEXT_REF)
4120 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
4121 if (vp->v_iflag & VI_MOUNT)
4122 strlcat(buf, "|VI_MOUNT", sizeof(buf));
4123 if (vp->v_iflag & VI_DOINGINACT)
4124 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4125 if (vp->v_iflag & VI_OWEINACT)
4126 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4127 if (vp->v_iflag & VI_DEFINACT)
4128 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4129 flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOINGINACT |
4130 VI_OWEINACT | VI_DEFINACT);
4132 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4133 strlcat(buf, buf2, sizeof(buf));
4135 if (vp->v_mflag & VMP_LAZYLIST)
4136 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4137 flags = vp->v_mflag & ~(VMP_LAZYLIST);
4139 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4140 strlcat(buf, buf2, sizeof(buf));
4142 printf(" flags (%s)\n", buf + 1);
4143 if (mtx_owned(VI_MTX(vp)))
4144 printf(" VI_LOCKed");
4145 if (vp->v_object != NULL)
4146 printf(" v_object %p ref %d pages %d "
4147 "cleanbuf %d dirtybuf %d\n",
4148 vp->v_object, vp->v_object->ref_count,
4149 vp->v_object->resident_page_count,
4150 vp->v_bufobj.bo_clean.bv_cnt,
4151 vp->v_bufobj.bo_dirty.bv_cnt);
4153 lockmgr_printinfo(vp->v_vnlock);
4154 if (vp->v_data != NULL)
4160 * List all of the locked vnodes in the system.
4161 * Called when debugging the kernel.
4163 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
4169 * Note: because this is DDB, we can't obey the locking semantics
4170 * for these structures, which means we could catch an inconsistent
4171 * state and dereference a nasty pointer. Not much to be done
4174 db_printf("Locked vnodes\n");
4175 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4176 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4177 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4178 vn_printf(vp, "vnode ");
4184 * Show details about the given vnode.
4186 DB_SHOW_COMMAND(vnode, db_show_vnode)
4192 vp = (struct vnode *)addr;
4193 vn_printf(vp, "vnode ");
4197 * Show details about the given mount point.
4199 DB_SHOW_COMMAND(mount, db_show_mount)
4210 /* No address given, print short info about all mount points. */
4211 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4212 db_printf("%p %s on %s (%s)\n", mp,
4213 mp->mnt_stat.f_mntfromname,
4214 mp->mnt_stat.f_mntonname,
4215 mp->mnt_stat.f_fstypename);
4219 db_printf("\nMore info: show mount <addr>\n");
4223 mp = (struct mount *)addr;
4224 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4225 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4228 mflags = mp->mnt_flag;
4229 #define MNT_FLAG(flag) do { \
4230 if (mflags & (flag)) { \
4231 if (buf[0] != '\0') \
4232 strlcat(buf, ", ", sizeof(buf)); \
4233 strlcat(buf, (#flag) + 4, sizeof(buf)); \
4234 mflags &= ~(flag); \
4237 MNT_FLAG(MNT_RDONLY);
4238 MNT_FLAG(MNT_SYNCHRONOUS);
4239 MNT_FLAG(MNT_NOEXEC);
4240 MNT_FLAG(MNT_NOSUID);
4241 MNT_FLAG(MNT_NFS4ACLS);
4242 MNT_FLAG(MNT_UNION);
4243 MNT_FLAG(MNT_ASYNC);
4244 MNT_FLAG(MNT_SUIDDIR);
4245 MNT_FLAG(MNT_SOFTDEP);
4246 MNT_FLAG(MNT_NOSYMFOLLOW);
4247 MNT_FLAG(MNT_GJOURNAL);
4248 MNT_FLAG(MNT_MULTILABEL);
4250 MNT_FLAG(MNT_NOATIME);
4251 MNT_FLAG(MNT_NOCLUSTERR);
4252 MNT_FLAG(MNT_NOCLUSTERW);
4254 MNT_FLAG(MNT_EXRDONLY);
4255 MNT_FLAG(MNT_EXPORTED);
4256 MNT_FLAG(MNT_DEFEXPORTED);
4257 MNT_FLAG(MNT_EXPORTANON);
4258 MNT_FLAG(MNT_EXKERB);
4259 MNT_FLAG(MNT_EXPUBLIC);
4260 MNT_FLAG(MNT_LOCAL);
4261 MNT_FLAG(MNT_QUOTA);
4262 MNT_FLAG(MNT_ROOTFS);
4264 MNT_FLAG(MNT_IGNORE);
4265 MNT_FLAG(MNT_UPDATE);
4266 MNT_FLAG(MNT_DELEXPORT);
4267 MNT_FLAG(MNT_RELOAD);
4268 MNT_FLAG(MNT_FORCE);
4269 MNT_FLAG(MNT_SNAPSHOT);
4270 MNT_FLAG(MNT_BYFSID);
4274 strlcat(buf, ", ", sizeof(buf));
4275 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4276 "0x%016jx", mflags);
4278 db_printf(" mnt_flag = %s\n", buf);
4281 flags = mp->mnt_kern_flag;
4282 #define MNT_KERN_FLAG(flag) do { \
4283 if (flags & (flag)) { \
4284 if (buf[0] != '\0') \
4285 strlcat(buf, ", ", sizeof(buf)); \
4286 strlcat(buf, (#flag) + 5, sizeof(buf)); \
4290 MNT_KERN_FLAG(MNTK_UNMOUNTF);
4291 MNT_KERN_FLAG(MNTK_ASYNC);
4292 MNT_KERN_FLAG(MNTK_SOFTDEP);
4293 MNT_KERN_FLAG(MNTK_DRAINING);
4294 MNT_KERN_FLAG(MNTK_REFEXPIRE);
4295 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4296 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4297 MNT_KERN_FLAG(MNTK_NO_IOPF);
4298 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4299 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4300 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4301 MNT_KERN_FLAG(MNTK_MARKER);
4302 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4303 MNT_KERN_FLAG(MNTK_NOASYNC);
4304 MNT_KERN_FLAG(MNTK_UNMOUNT);
4305 MNT_KERN_FLAG(MNTK_MWAIT);
4306 MNT_KERN_FLAG(MNTK_SUSPEND);
4307 MNT_KERN_FLAG(MNTK_SUSPEND2);
4308 MNT_KERN_FLAG(MNTK_SUSPENDED);
4309 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4310 MNT_KERN_FLAG(MNTK_NOKNOTE);
4311 #undef MNT_KERN_FLAG
4314 strlcat(buf, ", ", sizeof(buf));
4315 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4318 db_printf(" mnt_kern_flag = %s\n", buf);
4320 db_printf(" mnt_opt = ");
4321 opt = TAILQ_FIRST(mp->mnt_opt);
4323 db_printf("%s", opt->name);
4324 opt = TAILQ_NEXT(opt, link);
4325 while (opt != NULL) {
4326 db_printf(", %s", opt->name);
4327 opt = TAILQ_NEXT(opt, link);
4333 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4334 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4335 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4336 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4337 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4338 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4339 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4340 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4341 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4342 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4343 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4344 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4346 db_printf(" mnt_cred = { uid=%u ruid=%u",
4347 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4348 if (jailed(mp->mnt_cred))
4349 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4351 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4352 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4353 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4354 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4355 db_printf(" mnt_lazyvnodelistsize = %d\n",
4356 mp->mnt_lazyvnodelistsize);
4357 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4358 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4359 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
4360 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4361 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4362 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4363 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4364 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4365 db_printf(" mnt_secondary_accwrites = %d\n",
4366 mp->mnt_secondary_accwrites);
4367 db_printf(" mnt_gjprovider = %s\n",
4368 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4369 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4371 db_printf("\n\nList of active vnodes\n");
4372 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4373 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4374 vn_printf(vp, "vnode ");
4379 db_printf("\n\nList of inactive vnodes\n");
4380 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4381 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4382 vn_printf(vp, "vnode ");
4391 * Fill in a struct xvfsconf based on a struct vfsconf.
4394 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4396 struct xvfsconf xvfsp;
4398 bzero(&xvfsp, sizeof(xvfsp));
4399 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4400 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4401 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4402 xvfsp.vfc_flags = vfsp->vfc_flags;
4404 * These are unused in userland, we keep them
4405 * to not break binary compatibility.
4407 xvfsp.vfc_vfsops = NULL;
4408 xvfsp.vfc_next = NULL;
4409 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4412 #ifdef COMPAT_FREEBSD32
4414 uint32_t vfc_vfsops;
4415 char vfc_name[MFSNAMELEN];
4416 int32_t vfc_typenum;
4417 int32_t vfc_refcount;
4423 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4425 struct xvfsconf32 xvfsp;
4427 bzero(&xvfsp, sizeof(xvfsp));
4428 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4429 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4430 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4431 xvfsp.vfc_flags = vfsp->vfc_flags;
4432 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4437 * Top level filesystem related information gathering.
4440 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4442 struct vfsconf *vfsp;
4447 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4448 #ifdef COMPAT_FREEBSD32
4449 if (req->flags & SCTL_MASK32)
4450 error = vfsconf2x32(req, vfsp);
4453 error = vfsconf2x(req, vfsp);
4461 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4462 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4463 "S,xvfsconf", "List of all configured filesystems");
4465 #ifndef BURN_BRIDGES
4466 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4469 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4471 int *name = (int *)arg1 - 1; /* XXX */
4472 u_int namelen = arg2 + 1; /* XXX */
4473 struct vfsconf *vfsp;
4475 log(LOG_WARNING, "userland calling deprecated sysctl, "
4476 "please rebuild world\n");
4478 #if 1 || defined(COMPAT_PRELITE2)
4479 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4481 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4485 case VFS_MAXTYPENUM:
4488 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4491 return (ENOTDIR); /* overloaded */
4493 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4494 if (vfsp->vfc_typenum == name[2])
4499 return (EOPNOTSUPP);
4500 #ifdef COMPAT_FREEBSD32
4501 if (req->flags & SCTL_MASK32)
4502 return (vfsconf2x32(req, vfsp));
4505 return (vfsconf2x(req, vfsp));
4507 return (EOPNOTSUPP);
4510 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4511 CTLFLAG_MPSAFE, vfs_sysctl,
4512 "Generic filesystem");
4514 #if 1 || defined(COMPAT_PRELITE2)
4517 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4520 struct vfsconf *vfsp;
4521 struct ovfsconf ovfs;
4524 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4525 bzero(&ovfs, sizeof(ovfs));
4526 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4527 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4528 ovfs.vfc_index = vfsp->vfc_typenum;
4529 ovfs.vfc_refcount = vfsp->vfc_refcount;
4530 ovfs.vfc_flags = vfsp->vfc_flags;
4531 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4541 #endif /* 1 || COMPAT_PRELITE2 */
4542 #endif /* !BURN_BRIDGES */
4544 #define KINFO_VNODESLOP 10
4547 * Dump vnode list (via sysctl).
4551 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4559 * Stale numvnodes access is not fatal here.
4562 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4564 /* Make an estimate */
4565 return (SYSCTL_OUT(req, 0, len));
4567 error = sysctl_wire_old_buffer(req, 0);
4570 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4572 mtx_lock(&mountlist_mtx);
4573 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4574 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4577 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4581 xvn[n].xv_size = sizeof *xvn;
4582 xvn[n].xv_vnode = vp;
4583 xvn[n].xv_id = 0; /* XXX compat */
4584 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4586 XV_COPY(writecount);
4592 xvn[n].xv_flag = vp->v_vflag;
4594 switch (vp->v_type) {
4601 if (vp->v_rdev == NULL) {
4605 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4608 xvn[n].xv_socket = vp->v_socket;
4611 xvn[n].xv_fifo = vp->v_fifoinfo;
4616 /* shouldn't happen? */
4624 mtx_lock(&mountlist_mtx);
4629 mtx_unlock(&mountlist_mtx);
4631 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4636 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4637 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4642 unmount_or_warn(struct mount *mp)
4646 error = dounmount(mp, MNT_FORCE, curthread);
4648 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4652 printf("%d)\n", error);
4657 * Unmount all filesystems. The list is traversed in reverse order
4658 * of mounting to avoid dependencies.
4661 vfs_unmountall(void)
4663 struct mount *mp, *tmp;
4665 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4668 * Since this only runs when rebooting, it is not interlocked.
4670 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4674 * Forcibly unmounting "/dev" before "/" would prevent clean
4675 * unmount of the latter.
4677 if (mp == rootdevmp)
4680 unmount_or_warn(mp);
4683 if (rootdevmp != NULL)
4684 unmount_or_warn(rootdevmp);
4688 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4691 ASSERT_VI_LOCKED(vp, __func__);
4692 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4693 if ((vp->v_iflag & VI_OWEINACT) == 0) {
4697 if (vn_lock(vp, lkflags) == 0) {
4704 vdefer_inactive_unlocked(vp);
4708 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4711 return (vp->v_iflag & VI_DEFINACT);
4714 static void __noinline
4715 vfs_periodic_inactive(struct mount *mp, int flags)
4717 struct vnode *vp, *mvp;
4720 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4721 if (flags != MNT_WAIT)
4722 lkflags |= LK_NOWAIT;
4724 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4725 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4729 vp->v_iflag &= ~VI_DEFINACT;
4730 vfs_deferred_inactive(vp, lkflags);
4735 vfs_want_msync(struct vnode *vp)
4737 struct vm_object *obj;
4740 * This test may be performed without any locks held.
4741 * We rely on vm_object's type stability.
4743 if (vp->v_vflag & VV_NOSYNC)
4746 return (obj != NULL && vm_object_mightbedirty(obj));
4750 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4753 if (vp->v_vflag & VV_NOSYNC)
4755 if (vp->v_iflag & VI_DEFINACT)
4757 return (vfs_want_msync(vp));
4760 static void __noinline
4761 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4763 struct vnode *vp, *mvp;
4764 struct vm_object *obj;
4766 int lkflags, objflags;
4771 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4772 if (flags != MNT_WAIT) {
4773 lkflags |= LK_NOWAIT;
4774 objflags = OBJPC_NOSYNC;
4776 objflags = OBJPC_SYNC;
4779 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4781 if (vp->v_iflag & VI_DEFINACT) {
4782 vp->v_iflag &= ~VI_DEFINACT;
4785 if (!vfs_want_msync(vp)) {
4787 vfs_deferred_inactive(vp, lkflags);
4792 if (vget(vp, lkflags, td) == 0) {
4794 if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4795 VM_OBJECT_WLOCK(obj);
4796 vm_object_page_clean(obj, 0, 0, objflags);
4797 VM_OBJECT_WUNLOCK(obj);
4804 vdefer_inactive_unlocked(vp);
4810 vfs_periodic(struct mount *mp, int flags)
4813 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4815 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4816 vfs_periodic_inactive(mp, flags);
4818 vfs_periodic_msync_inactive(mp, flags);
4822 destroy_vpollinfo_free(struct vpollinfo *vi)
4825 knlist_destroy(&vi->vpi_selinfo.si_note);
4826 mtx_destroy(&vi->vpi_lock);
4827 uma_zfree(vnodepoll_zone, vi);
4831 destroy_vpollinfo(struct vpollinfo *vi)
4834 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4835 seldrain(&vi->vpi_selinfo);
4836 destroy_vpollinfo_free(vi);
4840 * Initialize per-vnode helper structure to hold poll-related state.
4843 v_addpollinfo(struct vnode *vp)
4845 struct vpollinfo *vi;
4847 if (vp->v_pollinfo != NULL)
4849 vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4850 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4851 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4852 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4854 if (vp->v_pollinfo != NULL) {
4856 destroy_vpollinfo_free(vi);
4859 vp->v_pollinfo = vi;
4864 * Record a process's interest in events which might happen to
4865 * a vnode. Because poll uses the historic select-style interface
4866 * internally, this routine serves as both the ``check for any
4867 * pending events'' and the ``record my interest in future events''
4868 * functions. (These are done together, while the lock is held,
4869 * to avoid race conditions.)
4872 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4876 mtx_lock(&vp->v_pollinfo->vpi_lock);
4877 if (vp->v_pollinfo->vpi_revents & events) {
4879 * This leaves events we are not interested
4880 * in available for the other process which
4881 * which presumably had requested them
4882 * (otherwise they would never have been
4885 events &= vp->v_pollinfo->vpi_revents;
4886 vp->v_pollinfo->vpi_revents &= ~events;
4888 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4891 vp->v_pollinfo->vpi_events |= events;
4892 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4893 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4898 * Routine to create and manage a filesystem syncer vnode.
4900 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4901 static int sync_fsync(struct vop_fsync_args *);
4902 static int sync_inactive(struct vop_inactive_args *);
4903 static int sync_reclaim(struct vop_reclaim_args *);
4905 static struct vop_vector sync_vnodeops = {
4906 .vop_bypass = VOP_EOPNOTSUPP,
4907 .vop_close = sync_close, /* close */
4908 .vop_fsync = sync_fsync, /* fsync */
4909 .vop_inactive = sync_inactive, /* inactive */
4910 .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
4911 .vop_reclaim = sync_reclaim, /* reclaim */
4912 .vop_lock1 = vop_stdlock, /* lock */
4913 .vop_unlock = vop_stdunlock, /* unlock */
4914 .vop_islocked = vop_stdislocked, /* islocked */
4916 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
4919 * Create a new filesystem syncer vnode for the specified mount point.
4922 vfs_allocate_syncvnode(struct mount *mp)
4926 static long start, incr, next;
4929 /* Allocate a new vnode */
4930 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
4932 panic("vfs_allocate_syncvnode: getnewvnode() failed");
4934 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4935 vp->v_vflag |= VV_FORCEINSMQ;
4936 error = insmntque(vp, mp);
4938 panic("vfs_allocate_syncvnode: insmntque() failed");
4939 vp->v_vflag &= ~VV_FORCEINSMQ;
4942 * Place the vnode onto the syncer worklist. We attempt to
4943 * scatter them about on the list so that they will go off
4944 * at evenly distributed times even if all the filesystems
4945 * are mounted at once.
4948 if (next == 0 || next > syncer_maxdelay) {
4952 start = syncer_maxdelay / 2;
4953 incr = syncer_maxdelay;
4959 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
4960 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
4961 mtx_lock(&sync_mtx);
4963 if (mp->mnt_syncer == NULL) {
4964 mp->mnt_syncer = vp;
4967 mtx_unlock(&sync_mtx);
4970 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4977 vfs_deallocate_syncvnode(struct mount *mp)
4981 mtx_lock(&sync_mtx);
4982 vp = mp->mnt_syncer;
4984 mp->mnt_syncer = NULL;
4985 mtx_unlock(&sync_mtx);
4991 * Do a lazy sync of the filesystem.
4994 sync_fsync(struct vop_fsync_args *ap)
4996 struct vnode *syncvp = ap->a_vp;
4997 struct mount *mp = syncvp->v_mount;
5002 * We only need to do something if this is a lazy evaluation.
5004 if (ap->a_waitfor != MNT_LAZY)
5008 * Move ourselves to the back of the sync list.
5010 bo = &syncvp->v_bufobj;
5012 vn_syncer_add_to_worklist(bo, syncdelay);
5016 * Walk the list of vnodes pushing all that are dirty and
5017 * not already on the sync list.
5019 if (vfs_busy(mp, MBF_NOWAIT) != 0)
5021 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
5025 save = curthread_pflags_set(TDP_SYNCIO);
5027 * The filesystem at hand may be idle with free vnodes stored in the
5028 * batch. Return them instead of letting them stay there indefinitely.
5030 vfs_periodic(mp, MNT_NOWAIT);
5031 error = VFS_SYNC(mp, MNT_LAZY);
5032 curthread_pflags_restore(save);
5033 vn_finished_write(mp);
5039 * The syncer vnode is no referenced.
5042 sync_inactive(struct vop_inactive_args *ap)
5050 * The syncer vnode is no longer needed and is being decommissioned.
5052 * Modifications to the worklist must be protected by sync_mtx.
5055 sync_reclaim(struct vop_reclaim_args *ap)
5057 struct vnode *vp = ap->a_vp;
5062 mtx_lock(&sync_mtx);
5063 if (vp->v_mount->mnt_syncer == vp)
5064 vp->v_mount->mnt_syncer = NULL;
5065 if (bo->bo_flag & BO_ONWORKLST) {
5066 LIST_REMOVE(bo, bo_synclist);
5067 syncer_worklist_len--;
5069 bo->bo_flag &= ~BO_ONWORKLST;
5071 mtx_unlock(&sync_mtx);
5078 vn_need_pageq_flush(struct vnode *vp)
5080 struct vm_object *obj;
5083 MPASS(mtx_owned(VI_MTX(vp)));
5085 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
5086 vm_object_mightbedirty(obj))
5092 * Check if vnode represents a disk device
5095 vn_isdisk(struct vnode *vp, int *errp)
5099 if (vp->v_type != VCHR) {
5105 if (vp->v_rdev == NULL)
5107 else if (vp->v_rdev->si_devsw == NULL)
5109 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5115 return (error == 0);
5119 * Common filesystem object access control check routine. Accepts a
5120 * vnode's type, "mode", uid and gid, requested access mode, credentials,
5121 * and optional call-by-reference privused argument allowing vaccess()
5122 * to indicate to the caller whether privilege was used to satisfy the
5123 * request (obsoleted). Returns 0 on success, or an errno on failure.
5126 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5127 accmode_t accmode, struct ucred *cred, int *privused)
5129 accmode_t dac_granted;
5130 accmode_t priv_granted;
5132 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5133 ("invalid bit in accmode"));
5134 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5135 ("VAPPEND without VWRITE"));
5138 * Look for a normal, non-privileged way to access the file/directory
5139 * as requested. If it exists, go with that.
5142 if (privused != NULL)
5147 /* Check the owner. */
5148 if (cred->cr_uid == file_uid) {
5149 dac_granted |= VADMIN;
5150 if (file_mode & S_IXUSR)
5151 dac_granted |= VEXEC;
5152 if (file_mode & S_IRUSR)
5153 dac_granted |= VREAD;
5154 if (file_mode & S_IWUSR)
5155 dac_granted |= (VWRITE | VAPPEND);
5157 if ((accmode & dac_granted) == accmode)
5163 /* Otherwise, check the groups (first match) */
5164 if (groupmember(file_gid, cred)) {
5165 if (file_mode & S_IXGRP)
5166 dac_granted |= VEXEC;
5167 if (file_mode & S_IRGRP)
5168 dac_granted |= VREAD;
5169 if (file_mode & S_IWGRP)
5170 dac_granted |= (VWRITE | VAPPEND);
5172 if ((accmode & dac_granted) == accmode)
5178 /* Otherwise, check everyone else. */
5179 if (file_mode & S_IXOTH)
5180 dac_granted |= VEXEC;
5181 if (file_mode & S_IROTH)
5182 dac_granted |= VREAD;
5183 if (file_mode & S_IWOTH)
5184 dac_granted |= (VWRITE | VAPPEND);
5185 if ((accmode & dac_granted) == accmode)
5190 * Build a privilege mask to determine if the set of privileges
5191 * satisfies the requirements when combined with the granted mask
5192 * from above. For each privilege, if the privilege is required,
5193 * bitwise or the request type onto the priv_granted mask.
5199 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5200 * requests, instead of PRIV_VFS_EXEC.
5202 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5203 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5204 priv_granted |= VEXEC;
5207 * Ensure that at least one execute bit is on. Otherwise,
5208 * a privileged user will always succeed, and we don't want
5209 * this to happen unless the file really is executable.
5211 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5212 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5213 !priv_check_cred(cred, PRIV_VFS_EXEC))
5214 priv_granted |= VEXEC;
5217 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5218 !priv_check_cred(cred, PRIV_VFS_READ))
5219 priv_granted |= VREAD;
5221 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5222 !priv_check_cred(cred, PRIV_VFS_WRITE))
5223 priv_granted |= (VWRITE | VAPPEND);
5225 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5226 !priv_check_cred(cred, PRIV_VFS_ADMIN))
5227 priv_granted |= VADMIN;
5229 if ((accmode & (priv_granted | dac_granted)) == accmode) {
5230 /* XXX audit: privilege used */
5231 if (privused != NULL)
5236 return ((accmode & VADMIN) ? EPERM : EACCES);
5240 * Credential check based on process requesting service, and per-attribute
5244 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5245 struct thread *td, accmode_t accmode)
5249 * Kernel-invoked always succeeds.
5255 * Do not allow privileged processes in jail to directly manipulate
5256 * system attributes.
5258 switch (attrnamespace) {
5259 case EXTATTR_NAMESPACE_SYSTEM:
5260 /* Potentially should be: return (EPERM); */
5261 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5262 case EXTATTR_NAMESPACE_USER:
5263 return (VOP_ACCESS(vp, accmode, cred, td));
5269 #ifdef DEBUG_VFS_LOCKS
5271 * This only exists to suppress warnings from unlocked specfs accesses. It is
5272 * no longer ok to have an unlocked VFS.
5274 #define IGNORE_LOCK(vp) (KERNEL_PANICKED() || (vp) == NULL || \
5275 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
5277 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
5278 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5279 "Drop into debugger on lock violation");
5281 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
5282 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5283 0, "Check for interlock across VOPs");
5285 int vfs_badlock_print = 1; /* Print lock violations. */
5286 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5287 0, "Print lock violations");
5289 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
5290 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5291 0, "Print vnode details on lock violations");
5294 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
5295 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5296 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5300 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5304 if (vfs_badlock_backtrace)
5307 if (vfs_badlock_vnode)
5308 vn_printf(vp, "vnode ");
5309 if (vfs_badlock_print)
5310 printf("%s: %p %s\n", str, (void *)vp, msg);
5311 if (vfs_badlock_ddb)
5312 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5316 assert_vi_locked(struct vnode *vp, const char *str)
5319 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5320 vfs_badlock("interlock is not locked but should be", str, vp);
5324 assert_vi_unlocked(struct vnode *vp, const char *str)
5327 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5328 vfs_badlock("interlock is locked but should not be", str, vp);
5332 assert_vop_locked(struct vnode *vp, const char *str)
5336 if (!IGNORE_LOCK(vp)) {
5337 locked = VOP_ISLOCKED(vp);
5338 if (locked == 0 || locked == LK_EXCLOTHER)
5339 vfs_badlock("is not locked but should be", str, vp);
5344 assert_vop_unlocked(struct vnode *vp, const char *str)
5347 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5348 vfs_badlock("is locked but should not be", str, vp);
5352 assert_vop_elocked(struct vnode *vp, const char *str)
5355 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5356 vfs_badlock("is not exclusive locked but should be", str, vp);
5358 #endif /* DEBUG_VFS_LOCKS */
5361 vop_rename_fail(struct vop_rename_args *ap)
5364 if (ap->a_tvp != NULL)
5366 if (ap->a_tdvp == ap->a_tvp)
5375 vop_rename_pre(void *ap)
5377 struct vop_rename_args *a = ap;
5379 #ifdef DEBUG_VFS_LOCKS
5381 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5382 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5383 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5384 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5386 /* Check the source (from). */
5387 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5388 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5389 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5390 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5391 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5393 /* Check the target. */
5395 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5396 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5398 if (a->a_tdvp != a->a_fdvp)
5400 if (a->a_tvp != a->a_fvp)
5407 #ifdef DEBUG_VFS_LOCKS
5409 vop_strategy_pre(void *ap)
5411 struct vop_strategy_args *a;
5418 * Cluster ops lock their component buffers but not the IO container.
5420 if ((bp->b_flags & B_CLUSTER) != 0)
5423 if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5424 if (vfs_badlock_print)
5426 "VOP_STRATEGY: bp is not locked but should be\n");
5427 if (vfs_badlock_ddb)
5428 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5433 vop_lock_pre(void *ap)
5435 struct vop_lock1_args *a = ap;
5437 if ((a->a_flags & LK_INTERLOCK) == 0)
5438 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5440 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5444 vop_lock_post(void *ap, int rc)
5446 struct vop_lock1_args *a = ap;
5448 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5449 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5450 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5454 vop_unlock_pre(void *ap)
5456 struct vop_unlock_args *a = ap;
5458 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5462 vop_need_inactive_pre(void *ap)
5464 struct vop_need_inactive_args *a = ap;
5466 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5470 vop_need_inactive_post(void *ap, int rc)
5472 struct vop_need_inactive_args *a = ap;
5474 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5479 vop_create_post(void *ap, int rc)
5481 struct vop_create_args *a = ap;
5484 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5488 vop_deleteextattr_post(void *ap, int rc)
5490 struct vop_deleteextattr_args *a = ap;
5493 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5497 vop_link_post(void *ap, int rc)
5499 struct vop_link_args *a = ap;
5502 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
5503 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
5508 vop_mkdir_post(void *ap, int rc)
5510 struct vop_mkdir_args *a = ap;
5513 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5517 vop_mknod_post(void *ap, int rc)
5519 struct vop_mknod_args *a = ap;
5522 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5526 vop_reclaim_post(void *ap, int rc)
5528 struct vop_reclaim_args *a = ap;
5531 VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
5535 vop_remove_post(void *ap, int rc)
5537 struct vop_remove_args *a = ap;
5540 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5541 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5546 vop_rename_post(void *ap, int rc)
5548 struct vop_rename_args *a = ap;
5553 if (a->a_fdvp == a->a_tdvp) {
5554 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5556 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5557 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5559 hint |= NOTE_EXTEND;
5560 if (a->a_fvp->v_type == VDIR)
5562 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5564 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5565 a->a_tvp->v_type == VDIR)
5567 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5570 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5572 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5574 if (a->a_tdvp != a->a_fdvp)
5576 if (a->a_tvp != a->a_fvp)
5584 vop_rmdir_post(void *ap, int rc)
5586 struct vop_rmdir_args *a = ap;
5589 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5590 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5595 vop_setattr_post(void *ap, int rc)
5597 struct vop_setattr_args *a = ap;
5600 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5604 vop_setextattr_post(void *ap, int rc)
5606 struct vop_setextattr_args *a = ap;
5609 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5613 vop_symlink_post(void *ap, int rc)
5615 struct vop_symlink_args *a = ap;
5618 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5622 vop_open_post(void *ap, int rc)
5624 struct vop_open_args *a = ap;
5627 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
5631 vop_close_post(void *ap, int rc)
5633 struct vop_close_args *a = ap;
5635 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
5636 !VN_IS_DOOMED(a->a_vp))) {
5637 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
5638 NOTE_CLOSE_WRITE : NOTE_CLOSE);
5643 vop_read_post(void *ap, int rc)
5645 struct vop_read_args *a = ap;
5648 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5652 vop_readdir_post(void *ap, int rc)
5654 struct vop_readdir_args *a = ap;
5657 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5660 static struct knlist fs_knlist;
5663 vfs_event_init(void *arg)
5665 knlist_init_mtx(&fs_knlist, NULL);
5667 /* XXX - correct order? */
5668 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
5671 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
5674 KNOTE_UNLOCKED(&fs_knlist, event);
5677 static int filt_fsattach(struct knote *kn);
5678 static void filt_fsdetach(struct knote *kn);
5679 static int filt_fsevent(struct knote *kn, long hint);
5681 struct filterops fs_filtops = {
5683 .f_attach = filt_fsattach,
5684 .f_detach = filt_fsdetach,
5685 .f_event = filt_fsevent
5689 filt_fsattach(struct knote *kn)
5692 kn->kn_flags |= EV_CLEAR;
5693 knlist_add(&fs_knlist, kn, 0);
5698 filt_fsdetach(struct knote *kn)
5701 knlist_remove(&fs_knlist, kn, 0);
5705 filt_fsevent(struct knote *kn, long hint)
5708 kn->kn_fflags |= hint;
5709 return (kn->kn_fflags != 0);
5713 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
5719 error = SYSCTL_IN(req, &vc, sizeof(vc));
5722 if (vc.vc_vers != VFS_CTL_VERS1)
5724 mp = vfs_getvfs(&vc.vc_fsid);
5727 /* ensure that a specific sysctl goes to the right filesystem. */
5728 if (strcmp(vc.vc_fstypename, "*") != 0 &&
5729 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
5733 VCTLTOREQ(&vc, req);
5734 error = VFS_SYSCTL(mp, vc.vc_op, req);
5739 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
5740 NULL, 0, sysctl_vfs_ctl, "",
5744 * Function to initialize a va_filerev field sensibly.
5745 * XXX: Wouldn't a random number make a lot more sense ??
5748 init_va_filerev(void)
5753 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
5756 static int filt_vfsread(struct knote *kn, long hint);
5757 static int filt_vfswrite(struct knote *kn, long hint);
5758 static int filt_vfsvnode(struct knote *kn, long hint);
5759 static void filt_vfsdetach(struct knote *kn);
5760 static struct filterops vfsread_filtops = {
5762 .f_detach = filt_vfsdetach,
5763 .f_event = filt_vfsread
5765 static struct filterops vfswrite_filtops = {
5767 .f_detach = filt_vfsdetach,
5768 .f_event = filt_vfswrite
5770 static struct filterops vfsvnode_filtops = {
5772 .f_detach = filt_vfsdetach,
5773 .f_event = filt_vfsvnode
5777 vfs_knllock(void *arg)
5779 struct vnode *vp = arg;
5781 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5785 vfs_knlunlock(void *arg)
5787 struct vnode *vp = arg;
5793 vfs_knl_assert_locked(void *arg)
5795 #ifdef DEBUG_VFS_LOCKS
5796 struct vnode *vp = arg;
5798 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
5803 vfs_knl_assert_unlocked(void *arg)
5805 #ifdef DEBUG_VFS_LOCKS
5806 struct vnode *vp = arg;
5808 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
5813 vfs_kqfilter(struct vop_kqfilter_args *ap)
5815 struct vnode *vp = ap->a_vp;
5816 struct knote *kn = ap->a_kn;
5819 switch (kn->kn_filter) {
5821 kn->kn_fop = &vfsread_filtops;
5824 kn->kn_fop = &vfswrite_filtops;
5827 kn->kn_fop = &vfsvnode_filtops;
5833 kn->kn_hook = (caddr_t)vp;
5836 if (vp->v_pollinfo == NULL)
5838 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5840 knlist_add(knl, kn, 0);
5846 * Detach knote from vnode
5849 filt_vfsdetach(struct knote *kn)
5851 struct vnode *vp = (struct vnode *)kn->kn_hook;
5853 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
5854 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
5860 filt_vfsread(struct knote *kn, long hint)
5862 struct vnode *vp = (struct vnode *)kn->kn_hook;
5867 * filesystem is gone, so set the EOF flag and schedule
5868 * the knote for deletion.
5870 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5872 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5877 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
5881 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
5882 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
5889 filt_vfswrite(struct knote *kn, long hint)
5891 struct vnode *vp = (struct vnode *)kn->kn_hook;
5896 * filesystem is gone, so set the EOF flag and schedule
5897 * the knote for deletion.
5899 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
5900 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5908 filt_vfsvnode(struct knote *kn, long hint)
5910 struct vnode *vp = (struct vnode *)kn->kn_hook;
5914 if (kn->kn_sfflags & hint)
5915 kn->kn_fflags |= hint;
5916 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5917 kn->kn_flags |= EV_EOF;
5921 res = (kn->kn_fflags != 0);
5927 * Returns whether the directory is empty or not.
5928 * If it is empty, the return value is 0; otherwise
5929 * the return value is an error value (which may
5933 vfs_emptydir(struct vnode *vp)
5937 struct dirent *dirent, *dp, *endp;
5943 ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
5945 dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
5946 iov.iov_base = dirent;
5947 iov.iov_len = sizeof(struct dirent);
5952 uio.uio_resid = sizeof(struct dirent);
5953 uio.uio_segflg = UIO_SYSSPACE;
5954 uio.uio_rw = UIO_READ;
5955 uio.uio_td = curthread;
5957 while (eof == 0 && error == 0) {
5958 error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
5962 endp = (void *)((uint8_t *)dirent +
5963 sizeof(struct dirent) - uio.uio_resid);
5964 for (dp = dirent; dp < endp;
5965 dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
5966 if (dp->d_type == DT_WHT)
5968 if (dp->d_namlen == 0)
5970 if (dp->d_type != DT_DIR &&
5971 dp->d_type != DT_UNKNOWN) {
5975 if (dp->d_namlen > 2) {
5979 if (dp->d_namlen == 1 &&
5980 dp->d_name[0] != '.') {
5984 if (dp->d_namlen == 2 &&
5985 dp->d_name[1] != '.') {
5989 uio.uio_resid = sizeof(struct dirent);
5992 free(dirent, M_TEMP);
5997 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6001 if (dp->d_reclen > ap->a_uio->uio_resid)
6002 return (ENAMETOOLONG);
6003 error = uiomove(dp, dp->d_reclen, ap->a_uio);
6005 if (ap->a_ncookies != NULL) {
6006 if (ap->a_cookies != NULL)
6007 free(ap->a_cookies, M_TEMP);
6008 ap->a_cookies = NULL;
6009 *ap->a_ncookies = 0;
6013 if (ap->a_ncookies == NULL)
6016 KASSERT(ap->a_cookies,
6017 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6019 *ap->a_cookies = realloc(*ap->a_cookies,
6020 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
6021 (*ap->a_cookies)[*ap->a_ncookies] = off;
6022 *ap->a_ncookies += 1;
6027 * The purpose of this routine is to remove granularity from accmode_t,
6028 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6029 * VADMIN and VAPPEND.
6031 * If it returns 0, the caller is supposed to continue with the usual
6032 * access checks using 'accmode' as modified by this routine. If it
6033 * returns nonzero value, the caller is supposed to return that value
6036 * Note that after this routine runs, accmode may be zero.
6039 vfs_unixify_accmode(accmode_t *accmode)
6042 * There is no way to specify explicit "deny" rule using
6043 * file mode or POSIX.1e ACLs.
6045 if (*accmode & VEXPLICIT_DENY) {
6051 * None of these can be translated into usual access bits.
6052 * Also, the common case for NFSv4 ACLs is to not contain
6053 * either of these bits. Caller should check for VWRITE
6054 * on the containing directory instead.
6056 if (*accmode & (VDELETE_CHILD | VDELETE))
6059 if (*accmode & VADMIN_PERMS) {
6060 *accmode &= ~VADMIN_PERMS;
6065 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6066 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6068 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6074 * Clear out a doomed vnode (if any) and replace it with a new one as long
6075 * as the fs is not being unmounted. Return the root vnode to the caller.
6077 static int __noinline
6078 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6084 if (mp->mnt_rootvnode != NULL) {
6086 vp = mp->mnt_rootvnode;
6088 if (!VN_IS_DOOMED(vp)) {
6091 error = vn_lock(vp, flags);
6100 * Clear the old one.
6102 mp->mnt_rootvnode = NULL;
6106 vfs_op_barrier_wait(mp);
6110 error = VFS_CACHEDROOT(mp, flags, vpp);
6113 if (mp->mnt_vfs_ops == 0) {
6115 if (mp->mnt_vfs_ops != 0) {
6119 if (mp->mnt_rootvnode == NULL) {
6121 mp->mnt_rootvnode = *vpp;
6123 if (mp->mnt_rootvnode != *vpp) {
6124 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6125 panic("%s: mismatch between vnode returned "
6126 " by VFS_CACHEDROOT and the one cached "
6128 __func__, *vpp, mp->mnt_rootvnode);
6138 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6143 if (!vfs_op_thread_enter(mp))
6144 return (vfs_cache_root_fallback(mp, flags, vpp));
6145 vp = atomic_load_ptr(&mp->mnt_rootvnode);
6146 if (vp == NULL || VN_IS_DOOMED(vp)) {
6147 vfs_op_thread_exit(mp);
6148 return (vfs_cache_root_fallback(mp, flags, vpp));
6151 vfs_op_thread_exit(mp);
6152 error = vn_lock(vp, flags);
6155 return (vfs_cache_root_fallback(mp, flags, vpp));
6162 vfs_cache_root_clear(struct mount *mp)
6167 * ops > 0 guarantees there is nobody who can see this vnode
6169 MPASS(mp->mnt_vfs_ops > 0);
6170 vp = mp->mnt_rootvnode;
6171 mp->mnt_rootvnode = NULL;
6176 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6179 MPASS(mp->mnt_vfs_ops > 0);
6181 mp->mnt_rootvnode = vp;
6185 * These are helper functions for filesystems to traverse all
6186 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6188 * This interface replaces MNT_VNODE_FOREACH.
6192 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6197 kern_yield(PRI_USER);
6199 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6200 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6201 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6202 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6203 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6206 if (VN_IS_DOOMED(vp)) {
6213 __mnt_vnode_markerfree_all(mvp, mp);
6214 /* MNT_IUNLOCK(mp); -- done in above function */
6215 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6218 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6219 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6225 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6229 *mvp = vn_alloc_marker(mp);
6233 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6234 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6235 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6238 if (VN_IS_DOOMED(vp)) {
6247 vn_free_marker(*mvp);
6251 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6257 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6265 mtx_assert(MNT_MTX(mp), MA_OWNED);
6267 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6268 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6271 vn_free_marker(*mvp);
6276 * These are helper functions for filesystems to traverse their
6277 * lazy vnodes. See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6280 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6283 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6288 vn_free_marker(*mvp);
6293 * Relock the mp mount vnode list lock with the vp vnode interlock in the
6294 * conventional lock order during mnt_vnode_next_lazy iteration.
6296 * On entry, the mount vnode list lock is held and the vnode interlock is not.
6297 * The list lock is dropped and reacquired. On success, both locks are held.
6298 * On failure, the mount vnode list lock is held but the vnode interlock is
6299 * not, and the procedure may have yielded.
6302 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6306 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6307 TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6308 ("%s: bad marker", __func__));
6309 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6310 ("%s: inappropriate vnode", __func__));
6311 ASSERT_VI_UNLOCKED(vp, __func__);
6312 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6314 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6315 TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6318 * Note we may be racing against vdrop which transitioned the hold
6319 * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
6320 * if we are the only user after we get the interlock we will just
6324 mtx_unlock(&mp->mnt_listmtx);
6326 if (VN_IS_DOOMED(vp)) {
6327 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
6330 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
6332 * There is nothing to do if we are the last user.
6334 if (!refcount_release_if_not_last(&vp->v_holdcnt))
6336 mtx_lock(&mp->mnt_listmtx);
6341 mtx_lock(&mp->mnt_listmtx);
6345 static struct vnode *
6346 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6351 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6352 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6354 vp = TAILQ_NEXT(*mvp, v_lazylist);
6355 while (vp != NULL) {
6356 if (vp->v_type == VMARKER) {
6357 vp = TAILQ_NEXT(vp, v_lazylist);
6361 * See if we want to process the vnode. Note we may encounter a
6362 * long string of vnodes we don't care about and hog the list
6363 * as a result. Check for it and requeue the marker.
6365 VNPASS(!VN_IS_DOOMED(vp), vp);
6366 if (!cb(vp, cbarg)) {
6367 if (!should_yield()) {
6368 vp = TAILQ_NEXT(vp, v_lazylist);
6371 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6373 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6375 mtx_unlock(&mp->mnt_listmtx);
6376 kern_yield(PRI_USER);
6377 mtx_lock(&mp->mnt_listmtx);
6381 * Try-lock because this is the wrong lock order.
6383 if (!VI_TRYLOCK(vp) &&
6384 !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6386 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6387 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6388 ("alien vnode on the lazy list %p %p", vp, mp));
6389 VNPASS(vp->v_mount == mp, vp);
6390 VNPASS(!VN_IS_DOOMED(vp), vp);
6393 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6395 /* Check if we are done */
6397 mtx_unlock(&mp->mnt_listmtx);
6398 mnt_vnode_markerfree_lazy(mvp, mp);
6401 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6402 mtx_unlock(&mp->mnt_listmtx);
6403 ASSERT_VI_LOCKED(vp, "lazy iter");
6408 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6413 kern_yield(PRI_USER);
6414 mtx_lock(&mp->mnt_listmtx);
6415 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6419 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6424 if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
6427 *mvp = vn_alloc_marker(mp);
6432 mtx_lock(&mp->mnt_listmtx);
6433 vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6435 mtx_unlock(&mp->mnt_listmtx);
6436 mnt_vnode_markerfree_lazy(mvp, mp);
6439 TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6440 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6444 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6450 mtx_lock(&mp->mnt_listmtx);
6451 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6452 mtx_unlock(&mp->mnt_listmtx);
6453 mnt_vnode_markerfree_lazy(mvp, mp);
6457 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
6460 if ((cnp->cn_flags & NOEXECCHECK) != 0) {
6461 cnp->cn_flags &= ~NOEXECCHECK;
6465 return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, cnp->cn_thread));