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,
674 UMA_ZONE_NOFREE | UMA_ZONE_VM);
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 (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
845 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
847 mtx_unlock(&mountlist_mtx);
851 mtx_unlock(&mountlist_mtx);
852 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
853 return ((struct mount *) 0);
857 * Lookup a mount point by filesystem identifier, busying it before
860 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
861 * cache for popular filesystem identifiers. The cache is lockess, using
862 * the fact that struct mount's are never freed. In worst case we may
863 * get pointer to unmounted or even different filesystem, so we have to
864 * check what we got, and go slow way if so.
867 vfs_busyfs(fsid_t *fsid)
869 #define FSID_CACHE_SIZE 256
870 typedef struct mount * volatile vmp_t;
871 static vmp_t cache[FSID_CACHE_SIZE];
876 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
877 hash = fsid->val[0] ^ fsid->val[1];
878 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
881 mp->mnt_stat.f_fsid.val[0] != fsid->val[0] ||
882 mp->mnt_stat.f_fsid.val[1] != fsid->val[1])
884 if (vfs_busy(mp, 0) != 0) {
888 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
889 mp->mnt_stat.f_fsid.val[1] == fsid->val[1])
895 mtx_lock(&mountlist_mtx);
896 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
897 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
898 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
899 error = vfs_busy(mp, MBF_MNTLSTLOCK);
902 mtx_unlock(&mountlist_mtx);
909 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
910 mtx_unlock(&mountlist_mtx);
911 return ((struct mount *) 0);
915 * Check if a user can access privileged mount options.
918 vfs_suser(struct mount *mp, struct thread *td)
922 if (jailed(td->td_ucred)) {
924 * If the jail of the calling thread lacks permission for
925 * this type of file system, deny immediately.
927 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
931 * If the file system was mounted outside the jail of the
932 * calling thread, deny immediately.
934 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
939 * If file system supports delegated administration, we don't check
940 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
941 * by the file system itself.
942 * If this is not the user that did original mount, we check for
943 * the PRIV_VFS_MOUNT_OWNER privilege.
945 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
946 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
947 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
954 * Get a new unique fsid. Try to make its val[0] unique, since this value
955 * will be used to create fake device numbers for stat(). Also try (but
956 * not so hard) make its val[0] unique mod 2^16, since some emulators only
957 * support 16-bit device numbers. We end up with unique val[0]'s for the
958 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
960 * Keep in mind that several mounts may be running in parallel. Starting
961 * the search one past where the previous search terminated is both a
962 * micro-optimization and a defense against returning the same fsid to
966 vfs_getnewfsid(struct mount *mp)
968 static uint16_t mntid_base;
973 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
974 mtx_lock(&mntid_mtx);
975 mtype = mp->mnt_vfc->vfc_typenum;
976 tfsid.val[1] = mtype;
977 mtype = (mtype & 0xFF) << 24;
979 tfsid.val[0] = makedev(255,
980 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
982 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
986 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
987 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
988 mtx_unlock(&mntid_mtx);
992 * Knob to control the precision of file timestamps:
994 * 0 = seconds only; nanoseconds zeroed.
995 * 1 = seconds and nanoseconds, accurate within 1/HZ.
996 * 2 = seconds and nanoseconds, truncated to microseconds.
997 * >=3 = seconds and nanoseconds, maximum precision.
999 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
1001 static int timestamp_precision = TSP_USEC;
1002 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
1003 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
1004 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
1005 "3+: sec + ns (max. precision))");
1008 * Get a current timestamp.
1011 vfs_timestamp(struct timespec *tsp)
1015 switch (timestamp_precision) {
1017 tsp->tv_sec = time_second;
1025 TIMEVAL_TO_TIMESPEC(&tv, tsp);
1035 * Set vnode attributes to VNOVAL
1038 vattr_null(struct vattr *vap)
1041 vap->va_type = VNON;
1042 vap->va_size = VNOVAL;
1043 vap->va_bytes = VNOVAL;
1044 vap->va_mode = VNOVAL;
1045 vap->va_nlink = VNOVAL;
1046 vap->va_uid = VNOVAL;
1047 vap->va_gid = VNOVAL;
1048 vap->va_fsid = VNOVAL;
1049 vap->va_fileid = VNOVAL;
1050 vap->va_blocksize = VNOVAL;
1051 vap->va_rdev = VNOVAL;
1052 vap->va_atime.tv_sec = VNOVAL;
1053 vap->va_atime.tv_nsec = VNOVAL;
1054 vap->va_mtime.tv_sec = VNOVAL;
1055 vap->va_mtime.tv_nsec = VNOVAL;
1056 vap->va_ctime.tv_sec = VNOVAL;
1057 vap->va_ctime.tv_nsec = VNOVAL;
1058 vap->va_birthtime.tv_sec = VNOVAL;
1059 vap->va_birthtime.tv_nsec = VNOVAL;
1060 vap->va_flags = VNOVAL;
1061 vap->va_gen = VNOVAL;
1062 vap->va_vaflags = 0;
1066 * Try to reduce the total number of vnodes.
1068 * This routine (and its user) are buggy in at least the following ways:
1069 * - all parameters were picked years ago when RAM sizes were significantly
1071 * - it can pick vnodes based on pages used by the vm object, but filesystems
1072 * like ZFS don't use it making the pick broken
1073 * - since ZFS has its own aging policy it gets partially combated by this one
1074 * - a dedicated method should be provided for filesystems to let them decide
1075 * whether the vnode should be recycled
1077 * This routine is called when we have too many vnodes. It attempts
1078 * to free <count> vnodes and will potentially free vnodes that still
1079 * have VM backing store (VM backing store is typically the cause
1080 * of a vnode blowout so we want to do this). Therefore, this operation
1081 * is not considered cheap.
1083 * A number of conditions may prevent a vnode from being reclaimed.
1084 * the buffer cache may have references on the vnode, a directory
1085 * vnode may still have references due to the namei cache representing
1086 * underlying files, or the vnode may be in active use. It is not
1087 * desirable to reuse such vnodes. These conditions may cause the
1088 * number of vnodes to reach some minimum value regardless of what
1089 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
1091 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1092 * entries if this argument is strue
1093 * @param trigger Only reclaim vnodes with fewer than this many resident
1095 * @param target How many vnodes to reclaim.
1096 * @return The number of vnodes that were reclaimed.
1099 vlrureclaim(bool reclaim_nc_src, int trigger, u_long target)
1101 struct vnode *vp, *mvp;
1103 struct vm_object *object;
1107 mtx_assert(&vnode_list_mtx, MA_OWNED);
1112 mvp = vnode_list_reclaim_marker;
1115 while (done < target) {
1116 vp = TAILQ_NEXT(vp, v_vnodelist);
1117 if (__predict_false(vp == NULL))
1120 if (__predict_false(vp->v_type == VMARKER))
1124 * If it's been deconstructed already, it's still
1125 * referenced, or it exceeds the trigger, skip it.
1126 * Also skip free vnodes. We are trying to make space
1127 * to expand the free list, not reduce it.
1129 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1130 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)))
1133 if (vp->v_type == VBAD || vp->v_type == VNON)
1136 if (!VI_TRYLOCK(vp))
1139 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1140 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1141 VN_IS_DOOMED(vp) || vp->v_type == VNON) {
1146 object = atomic_load_ptr(&vp->v_object);
1147 if (object == NULL || object->resident_page_count > trigger) {
1154 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1155 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1156 mtx_unlock(&vnode_list_mtx);
1158 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1160 goto next_iter_unlocked;
1162 if (VOP_LOCK(vp, LK_EXCLUSIVE|LK_NOWAIT) != 0) {
1164 vn_finished_write(mp);
1165 goto next_iter_unlocked;
1169 if (vp->v_usecount > 0 ||
1170 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1171 (vp->v_object != NULL &&
1172 vp->v_object->resident_page_count > trigger)) {
1175 vn_finished_write(mp);
1176 goto next_iter_unlocked;
1178 counter_u64_add(recycles_count, 1);
1182 vn_finished_write(mp);
1186 kern_yield(PRI_USER);
1187 mtx_lock(&vnode_list_mtx);
1190 MPASS(vp->v_type != VMARKER);
1191 if (!should_yield())
1193 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1194 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1195 mtx_unlock(&vnode_list_mtx);
1196 kern_yield(PRI_USER);
1197 mtx_lock(&vnode_list_mtx);
1200 if (done == 0 && !retried) {
1201 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1202 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1209 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1210 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1212 "limit on vnode free requests per call to the vnlru_free routine");
1215 * Attempt to reduce the free list by the requested amount.
1218 vnlru_free_locked(int count, struct vfsops *mnt_op)
1220 struct vnode *vp, *mvp;
1224 mtx_assert(&vnode_list_mtx, MA_OWNED);
1225 if (count > max_vnlru_free)
1226 count = max_vnlru_free;
1228 mvp = vnode_list_free_marker;
1232 vp = TAILQ_NEXT(vp, v_vnodelist);
1233 if (__predict_false(vp == NULL)) {
1234 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1235 TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1238 if (__predict_false(vp->v_type == VMARKER))
1242 * Don't recycle if our vnode is from different type
1243 * of mount point. Note that mp is type-safe, the
1244 * check does not reach unmapped address even if
1245 * vnode is reclaimed.
1246 * Don't recycle if we can't get the interlock without
1249 if (vp->v_holdcnt > 0 || (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1250 mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
1253 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1254 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1255 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1261 mtx_unlock(&vnode_list_mtx);
1265 mtx_lock(&vnode_list_mtx);
1268 return (ocount - count);
1272 vnlru_free(int count, struct vfsops *mnt_op)
1275 mtx_lock(&vnode_list_mtx);
1276 vnlru_free_locked(count, mnt_op);
1277 mtx_unlock(&vnode_list_mtx);
1284 mtx_assert(&vnode_list_mtx, MA_OWNED);
1285 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1286 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1287 vlowat = vhiwat / 2;
1291 * Attempt to recycle vnodes in a context that is always safe to block.
1292 * Calling vlrurecycle() from the bowels of filesystem code has some
1293 * interesting deadlock problems.
1295 static struct proc *vnlruproc;
1296 static int vnlruproc_sig;
1299 * The main freevnodes counter is only updated when threads requeue their vnode
1300 * batches. CPUs are conditionally walked to compute a more accurate total.
1302 * Limit how much of a slop are we willing to tolerate. Note: the actual value
1303 * at any given moment can still exceed slop, but it should not be by significant
1304 * margin in practice.
1306 #define VNLRU_FREEVNODES_SLOP 128
1309 vnlru_read_freevnodes(void)
1315 mtx_assert(&vnode_list_mtx, MA_OWNED);
1316 if (freevnodes > freevnodes_old)
1317 slop = freevnodes - freevnodes_old;
1319 slop = freevnodes_old - freevnodes;
1320 if (slop < VNLRU_FREEVNODES_SLOP)
1321 return (freevnodes >= 0 ? freevnodes : 0);
1322 freevnodes_old = freevnodes;
1324 vd = DPCPU_ID_PTR((cpu), vd);
1325 freevnodes_old += vd->freevnodes;
1327 return (freevnodes_old >= 0 ? freevnodes_old : 0);
1331 vnlru_under(u_long rnumvnodes, u_long limit)
1333 u_long rfreevnodes, space;
1335 if (__predict_false(rnumvnodes > desiredvnodes))
1338 space = desiredvnodes - rnumvnodes;
1339 if (space < limit) {
1340 rfreevnodes = vnlru_read_freevnodes();
1341 if (rfreevnodes > wantfreevnodes)
1342 space += rfreevnodes - wantfreevnodes;
1344 return (space < limit);
1348 vnlru_under_unlocked(u_long rnumvnodes, u_long limit)
1350 long rfreevnodes, space;
1352 if (__predict_false(rnumvnodes > desiredvnodes))
1355 space = desiredvnodes - rnumvnodes;
1356 if (space < limit) {
1357 rfreevnodes = atomic_load_long(&freevnodes);
1358 if (rfreevnodes > wantfreevnodes)
1359 space += rfreevnodes - wantfreevnodes;
1361 return (space < limit);
1368 mtx_assert(&vnode_list_mtx, MA_OWNED);
1369 if (vnlruproc_sig == 0) {
1378 u_long rnumvnodes, rfreevnodes, target;
1379 unsigned long onumvnodes;
1380 int done, force, trigger, usevnodes;
1381 bool reclaim_nc_src, want_reread;
1383 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1384 SHUTDOWN_PRI_FIRST);
1387 want_reread = false;
1389 kproc_suspend_check(vnlruproc);
1390 mtx_lock(&vnode_list_mtx);
1391 rnumvnodes = atomic_load_long(&numvnodes);
1394 force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1395 want_reread = false;
1399 * If numvnodes is too large (due to desiredvnodes being
1400 * adjusted using its sysctl, or emergency growth), first
1401 * try to reduce it by discarding from the free list.
1403 if (rnumvnodes > desiredvnodes) {
1404 vnlru_free_locked(rnumvnodes - desiredvnodes, NULL);
1405 rnumvnodes = atomic_load_long(&numvnodes);
1408 * Sleep if the vnode cache is in a good state. This is
1409 * when it is not over-full and has space for about a 4%
1410 * or 9% expansion (by growing its size or inexcessively
1411 * reducing its free list). Otherwise, try to reclaim
1412 * space for a 10% expansion.
1414 if (vstir && force == 0) {
1418 if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1420 wakeup(&vnlruproc_sig);
1421 msleep(vnlruproc, &vnode_list_mtx,
1422 PVFS|PDROP, "vlruwt", hz);
1425 rfreevnodes = vnlru_read_freevnodes();
1427 onumvnodes = rnumvnodes;
1429 * Calculate parameters for recycling. These are the same
1430 * throughout the loop to give some semblance of fairness.
1431 * The trigger point is to avoid recycling vnodes with lots
1432 * of resident pages. We aren't trying to free memory; we
1433 * are trying to recycle or at least free vnodes.
1435 if (rnumvnodes <= desiredvnodes)
1436 usevnodes = rnumvnodes - rfreevnodes;
1438 usevnodes = rnumvnodes;
1442 * The trigger value is is chosen to give a conservatively
1443 * large value to ensure that it alone doesn't prevent
1444 * making progress. The value can easily be so large that
1445 * it is effectively infinite in some congested and
1446 * misconfigured cases, and this is necessary. Normally
1447 * it is about 8 to 100 (pages), which is quite large.
1449 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1451 trigger = vsmalltrigger;
1452 reclaim_nc_src = force >= 3;
1453 target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1454 target = target / 10 + 1;
1455 done = vlrureclaim(reclaim_nc_src, trigger, target);
1456 mtx_unlock(&vnode_list_mtx);
1457 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1458 uma_reclaim(UMA_RECLAIM_DRAIN);
1460 if (force == 0 || force == 1) {
1471 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1474 kern_yield(PRI_USER);
1479 static struct kproc_desc vnlru_kp = {
1484 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1488 * Routines having to do with the management of the vnode table.
1492 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1493 * before we actually vgone(). This function must be called with the vnode
1494 * held to prevent the vnode from being returned to the free list midway
1498 vtryrecycle(struct vnode *vp)
1502 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1503 VNASSERT(vp->v_holdcnt, vp,
1504 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1506 * This vnode may found and locked via some other list, if so we
1507 * can't recycle it yet.
1509 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1511 "%s: impossible to recycle, vp %p lock is already held",
1513 return (EWOULDBLOCK);
1516 * Don't recycle if its filesystem is being suspended.
1518 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1521 "%s: impossible to recycle, cannot start the write for %p",
1526 * If we got this far, we need to acquire the interlock and see if
1527 * anyone picked up this vnode from another list. If not, we will
1528 * mark it with DOOMED via vgonel() so that anyone who does find it
1529 * will skip over it.
1532 if (vp->v_usecount) {
1535 vn_finished_write(vnmp);
1537 "%s: impossible to recycle, %p is already referenced",
1541 if (!VN_IS_DOOMED(vp)) {
1542 counter_u64_add(recycles_free_count, 1);
1547 vn_finished_write(vnmp);
1552 * Allocate a new vnode.
1554 * The operation never returns an error. Returning an error was disabled
1555 * in r145385 (dated 2005) with the following comment:
1557 * XXX Not all VFS_VGET/ffs_vget callers check returns.
1559 * Given the age of this commit (almost 15 years at the time of writing this
1560 * comment) restoring the ability to fail requires a significant audit of
1563 * The routine can try to free a vnode or stall for up to 1 second waiting for
1564 * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1566 static u_long vn_alloc_cyclecount;
1568 static struct vnode * __noinline
1569 vn_alloc_hard(struct mount *mp)
1571 u_long rnumvnodes, rfreevnodes;
1573 mtx_lock(&vnode_list_mtx);
1574 rnumvnodes = atomic_load_long(&numvnodes);
1575 if (rnumvnodes + 1 < desiredvnodes) {
1576 vn_alloc_cyclecount = 0;
1579 rfreevnodes = vnlru_read_freevnodes();
1580 if (vn_alloc_cyclecount++ >= rfreevnodes) {
1581 vn_alloc_cyclecount = 0;
1585 * Grow the vnode cache if it will not be above its target max
1586 * after growing. Otherwise, if the free list is nonempty, try
1587 * to reclaim 1 item from it before growing the cache (possibly
1588 * above its target max if the reclamation failed or is delayed).
1589 * Otherwise, wait for some space. In all cases, schedule
1590 * vnlru_proc() if we are getting short of space. The watermarks
1591 * should be chosen so that we never wait or even reclaim from
1592 * the free list to below its target minimum.
1594 if (vnlru_free_locked(1, NULL) > 0)
1596 if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1598 * Wait for space for a new vnode.
1601 msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1602 if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1603 vnlru_read_freevnodes() > 1)
1604 vnlru_free_locked(1, NULL);
1607 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1608 if (vnlru_under(rnumvnodes, vlowat))
1610 mtx_unlock(&vnode_list_mtx);
1611 return (uma_zalloc(vnode_zone, M_WAITOK));
1614 static struct vnode *
1615 vn_alloc(struct mount *mp)
1619 if (__predict_false(vn_alloc_cyclecount != 0))
1620 return (vn_alloc_hard(mp));
1621 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1622 if (__predict_false(vnlru_under_unlocked(rnumvnodes, vlowat))) {
1623 atomic_subtract_long(&numvnodes, 1);
1624 return (vn_alloc_hard(mp));
1627 return (uma_zalloc(vnode_zone, M_WAITOK));
1631 vn_free(struct vnode *vp)
1634 atomic_subtract_long(&numvnodes, 1);
1635 uma_zfree(vnode_zone, vp);
1639 * Return the next vnode from the free list.
1642 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1647 struct lock_object *lo;
1649 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1651 KASSERT(vops->registered,
1652 ("%s: not registered vector op %p\n", __func__, vops));
1655 if (td->td_vp_reserved != NULL) {
1656 vp = td->td_vp_reserved;
1657 td->td_vp_reserved = NULL;
1661 counter_u64_add(vnodes_created, 1);
1663 * Locks are given the generic name "vnode" when created.
1664 * Follow the historic practice of using the filesystem
1665 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1667 * Locks live in a witness group keyed on their name. Thus,
1668 * when a lock is renamed, it must also move from the witness
1669 * group of its old name to the witness group of its new name.
1671 * The change only needs to be made when the vnode moves
1672 * from one filesystem type to another. We ensure that each
1673 * filesystem use a single static name pointer for its tag so
1674 * that we can compare pointers rather than doing a strcmp().
1676 lo = &vp->v_vnlock->lock_object;
1678 if (lo->lo_name != tag) {
1682 WITNESS_DESTROY(lo);
1683 WITNESS_INIT(lo, tag);
1687 * By default, don't allow shared locks unless filesystems opt-in.
1689 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1691 * Finalize various vnode identity bits.
1693 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1694 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1695 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1698 v_init_counters(vp);
1699 vp->v_bufobj.bo_ops = &buf_ops_bio;
1701 if (mp == NULL && vops != &dead_vnodeops)
1702 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1706 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1707 mac_vnode_associate_singlelabel(mp, vp);
1710 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1711 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1712 vp->v_vflag |= VV_NOKNOTE;
1716 * For the filesystems which do not use vfs_hash_insert(),
1717 * still initialize v_hash to have vfs_hash_index() useful.
1718 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1721 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1728 getnewvnode_reserve(void)
1733 MPASS(td->td_vp_reserved == NULL);
1734 td->td_vp_reserved = vn_alloc(NULL);
1738 getnewvnode_drop_reserve(void)
1743 if (td->td_vp_reserved != NULL) {
1744 vn_free(td->td_vp_reserved);
1745 td->td_vp_reserved = NULL;
1750 freevnode(struct vnode *vp)
1755 * The vnode has been marked for destruction, so free it.
1757 * The vnode will be returned to the zone where it will
1758 * normally remain until it is needed for another vnode. We
1759 * need to cleanup (or verify that the cleanup has already
1760 * been done) any residual data left from its current use
1761 * so as not to contaminate the freshly allocated vnode.
1763 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1765 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1766 VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
1767 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1768 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1769 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1770 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1771 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1772 ("clean blk trie not empty"));
1773 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1774 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1775 ("dirty blk trie not empty"));
1776 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1777 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1778 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1779 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1780 ("Dangling rangelock waiters"));
1783 mac_vnode_destroy(vp);
1785 if (vp->v_pollinfo != NULL) {
1786 destroy_vpollinfo(vp->v_pollinfo);
1787 vp->v_pollinfo = NULL;
1790 /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
1793 vp->v_mountedhere = NULL;
1796 vp->v_fifoinfo = NULL;
1797 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
1806 * Delete from old mount point vnode list, if on one.
1809 delmntque(struct vnode *vp)
1813 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
1822 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1823 ("bad mount point vnode list size"));
1824 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1825 mp->mnt_nvnodelistsize--;
1831 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1835 vp->v_op = &dead_vnodeops;
1841 * Insert into list of vnodes for the new mount point, if available.
1844 insmntque1(struct vnode *vp, struct mount *mp,
1845 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1848 KASSERT(vp->v_mount == NULL,
1849 ("insmntque: vnode already on per mount vnode list"));
1850 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1851 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1854 * We acquire the vnode interlock early to ensure that the
1855 * vnode cannot be recycled by another process releasing a
1856 * holdcnt on it before we get it on both the vnode list
1857 * and the active vnode list. The mount mutex protects only
1858 * manipulation of the vnode list and the vnode freelist
1859 * mutex protects only manipulation of the active vnode list.
1860 * Hence the need to hold the vnode interlock throughout.
1864 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1865 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1866 mp->mnt_nvnodelistsize == 0)) &&
1867 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1876 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1877 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1878 ("neg mount point vnode list size"));
1879 mp->mnt_nvnodelistsize++;
1886 insmntque(struct vnode *vp, struct mount *mp)
1889 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1893 * Flush out and invalidate all buffers associated with a bufobj
1894 * Called with the underlying object locked.
1897 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1902 if (flags & V_SAVE) {
1903 error = bufobj_wwait(bo, slpflag, slptimeo);
1908 if (bo->bo_dirty.bv_cnt > 0) {
1910 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1913 * XXX We could save a lock/unlock if this was only
1914 * enabled under INVARIANTS
1917 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1918 panic("vinvalbuf: dirty bufs");
1922 * If you alter this loop please notice that interlock is dropped and
1923 * reacquired in flushbuflist. Special care is needed to ensure that
1924 * no race conditions occur from this.
1927 error = flushbuflist(&bo->bo_clean,
1928 flags, bo, slpflag, slptimeo);
1929 if (error == 0 && !(flags & V_CLEANONLY))
1930 error = flushbuflist(&bo->bo_dirty,
1931 flags, bo, slpflag, slptimeo);
1932 if (error != 0 && error != EAGAIN) {
1936 } while (error != 0);
1939 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1940 * have write I/O in-progress but if there is a VM object then the
1941 * VM object can also have read-I/O in-progress.
1944 bufobj_wwait(bo, 0, 0);
1945 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
1947 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
1950 } while (bo->bo_numoutput > 0);
1954 * Destroy the copy in the VM cache, too.
1956 if (bo->bo_object != NULL &&
1957 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1958 VM_OBJECT_WLOCK(bo->bo_object);
1959 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1960 OBJPR_CLEANONLY : 0);
1961 VM_OBJECT_WUNLOCK(bo->bo_object);
1966 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1967 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1968 bo->bo_clean.bv_cnt > 0))
1969 panic("vinvalbuf: flush failed");
1970 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1971 bo->bo_dirty.bv_cnt > 0)
1972 panic("vinvalbuf: flush dirty failed");
1979 * Flush out and invalidate all buffers associated with a vnode.
1980 * Called with the underlying object locked.
1983 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1986 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1987 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1988 if (vp->v_object != NULL && vp->v_object->handle != vp)
1990 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1994 * Flush out buffers on the specified list.
1998 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
2001 struct buf *bp, *nbp;
2006 ASSERT_BO_WLOCKED(bo);
2009 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2011 * If we are flushing both V_NORMAL and V_ALT buffers then
2012 * do not skip any buffers. If we are flushing only V_NORMAL
2013 * buffers then skip buffers marked as BX_ALTDATA. If we are
2014 * flushing only V_ALT buffers then skip buffers not marked
2017 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2018 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2019 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2023 lblkno = nbp->b_lblkno;
2024 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2027 error = BUF_TIMELOCK(bp,
2028 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2029 "flushbuf", slpflag, slptimeo);
2032 return (error != ENOLCK ? error : EAGAIN);
2034 KASSERT(bp->b_bufobj == bo,
2035 ("bp %p wrong b_bufobj %p should be %p",
2036 bp, bp->b_bufobj, bo));
2038 * XXX Since there are no node locks for NFS, I
2039 * believe there is a slight chance that a delayed
2040 * write will occur while sleeping just above, so
2043 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2046 bp->b_flags |= B_ASYNC;
2049 return (EAGAIN); /* XXX: why not loop ? */
2052 bp->b_flags |= (B_INVAL | B_RELBUF);
2053 bp->b_flags &= ~B_ASYNC;
2058 nbp = gbincore(bo, lblkno);
2059 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2061 break; /* nbp invalid */
2067 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2073 ASSERT_BO_LOCKED(bo);
2075 for (lblkno = startn;;) {
2077 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2078 if (bp == NULL || bp->b_lblkno >= endn ||
2079 bp->b_lblkno < startn)
2081 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2082 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2085 if (error == ENOLCK)
2089 KASSERT(bp->b_bufobj == bo,
2090 ("bp %p wrong b_bufobj %p should be %p",
2091 bp, bp->b_bufobj, bo));
2092 lblkno = bp->b_lblkno + 1;
2093 if ((bp->b_flags & B_MANAGED) == 0)
2095 bp->b_flags |= B_RELBUF;
2097 * In the VMIO case, use the B_NOREUSE flag to hint that the
2098 * pages backing each buffer in the range are unlikely to be
2099 * reused. Dirty buffers will have the hint applied once
2100 * they've been written.
2102 if ((bp->b_flags & B_VMIO) != 0)
2103 bp->b_flags |= B_NOREUSE;
2111 * Truncate a file's buffer and pages to a specified length. This
2112 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2116 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2118 struct buf *bp, *nbp;
2122 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2123 vp, blksize, (uintmax_t)length);
2126 * Round up to the *next* lbn.
2128 startlbn = howmany(length, blksize);
2130 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2136 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2141 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2142 if (bp->b_lblkno > 0)
2145 * Since we hold the vnode lock this should only
2146 * fail if we're racing with the buf daemon.
2149 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2150 BO_LOCKPTR(bo)) == ENOLCK)
2151 goto restart_unlocked;
2153 VNASSERT((bp->b_flags & B_DELWRI), vp,
2154 ("buf(%p) on dirty queue without DELWRI", bp));
2163 bufobj_wwait(bo, 0, 0);
2165 vnode_pager_setsize(vp, length);
2171 * Invalidate the cached pages of a file's buffer within the range of block
2172 * numbers [startlbn, endlbn).
2175 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2181 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2183 start = blksize * startlbn;
2184 end = blksize * endlbn;
2188 MPASS(blksize == bo->bo_bsize);
2190 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2194 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2198 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2199 daddr_t startlbn, daddr_t endlbn)
2201 struct buf *bp, *nbp;
2204 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2205 ASSERT_BO_LOCKED(bo);
2209 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2210 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2213 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2214 BO_LOCKPTR(bo)) == ENOLCK) {
2220 bp->b_flags |= B_INVAL | B_RELBUF;
2221 bp->b_flags &= ~B_ASYNC;
2227 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2229 (nbp->b_flags & B_DELWRI) != 0))
2233 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2234 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2237 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2238 BO_LOCKPTR(bo)) == ENOLCK) {
2243 bp->b_flags |= B_INVAL | B_RELBUF;
2244 bp->b_flags &= ~B_ASYNC;
2250 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2251 (nbp->b_vp != vp) ||
2252 (nbp->b_flags & B_DELWRI) == 0))
2260 buf_vlist_remove(struct buf *bp)
2264 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2265 ASSERT_BO_WLOCKED(bp->b_bufobj);
2266 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
2267 (BX_VNDIRTY|BX_VNCLEAN),
2268 ("buf_vlist_remove: Buf %p is on two lists", bp));
2269 if (bp->b_xflags & BX_VNDIRTY)
2270 bv = &bp->b_bufobj->bo_dirty;
2272 bv = &bp->b_bufobj->bo_clean;
2273 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2274 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2276 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2280 * Add the buffer to the sorted clean or dirty block list.
2282 * NOTE: xflags is passed as a constant, optimizing this inline function!
2285 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2291 ASSERT_BO_WLOCKED(bo);
2292 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2293 ("dead bo %p", bo));
2294 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2295 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2296 bp->b_xflags |= xflags;
2297 if (xflags & BX_VNDIRTY)
2303 * Keep the list ordered. Optimize empty list insertion. Assume
2304 * we tend to grow at the tail so lookup_le should usually be cheaper
2307 if (bv->bv_cnt == 0 ||
2308 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2309 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2310 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2311 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2313 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2314 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2316 panic("buf_vlist_add: Preallocated nodes insufficient.");
2321 * Look up a buffer using the buffer tries.
2324 gbincore(struct bufobj *bo, daddr_t lblkno)
2328 ASSERT_BO_LOCKED(bo);
2329 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2332 return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
2336 * Associate a buffer with a vnode.
2339 bgetvp(struct vnode *vp, struct buf *bp)
2344 ASSERT_BO_WLOCKED(bo);
2345 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2347 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2348 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2349 ("bgetvp: bp already attached! %p", bp));
2355 * Insert onto list for new vnode.
2357 buf_vlist_add(bp, bo, BX_VNCLEAN);
2361 * Disassociate a buffer from a vnode.
2364 brelvp(struct buf *bp)
2369 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2370 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2373 * Delete from old vnode list, if on one.
2375 vp = bp->b_vp; /* XXX */
2378 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2379 buf_vlist_remove(bp);
2381 panic("brelvp: Buffer %p not on queue.", bp);
2382 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2383 bo->bo_flag &= ~BO_ONWORKLST;
2384 mtx_lock(&sync_mtx);
2385 LIST_REMOVE(bo, bo_synclist);
2386 syncer_worklist_len--;
2387 mtx_unlock(&sync_mtx);
2390 bp->b_bufobj = NULL;
2396 * Add an item to the syncer work queue.
2399 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2403 ASSERT_BO_WLOCKED(bo);
2405 mtx_lock(&sync_mtx);
2406 if (bo->bo_flag & BO_ONWORKLST)
2407 LIST_REMOVE(bo, bo_synclist);
2409 bo->bo_flag |= BO_ONWORKLST;
2410 syncer_worklist_len++;
2413 if (delay > syncer_maxdelay - 2)
2414 delay = syncer_maxdelay - 2;
2415 slot = (syncer_delayno + delay) & syncer_mask;
2417 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2418 mtx_unlock(&sync_mtx);
2422 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2426 mtx_lock(&sync_mtx);
2427 len = syncer_worklist_len - sync_vnode_count;
2428 mtx_unlock(&sync_mtx);
2429 error = SYSCTL_OUT(req, &len, sizeof(len));
2433 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2434 CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2435 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2437 static struct proc *updateproc;
2438 static void sched_sync(void);
2439 static struct kproc_desc up_kp = {
2444 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2447 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2452 *bo = LIST_FIRST(slp);
2456 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2459 * We use vhold in case the vnode does not
2460 * successfully sync. vhold prevents the vnode from
2461 * going away when we unlock the sync_mtx so that
2462 * we can acquire the vnode interlock.
2465 mtx_unlock(&sync_mtx);
2467 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2469 mtx_lock(&sync_mtx);
2470 return (*bo == LIST_FIRST(slp));
2472 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2473 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2475 vn_finished_write(mp);
2477 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2479 * Put us back on the worklist. The worklist
2480 * routine will remove us from our current
2481 * position and then add us back in at a later
2484 vn_syncer_add_to_worklist(*bo, syncdelay);
2488 mtx_lock(&sync_mtx);
2492 static int first_printf = 1;
2495 * System filesystem synchronizer daemon.
2500 struct synclist *next, *slp;
2503 struct thread *td = curthread;
2505 int net_worklist_len;
2506 int syncer_final_iter;
2510 syncer_final_iter = 0;
2511 syncer_state = SYNCER_RUNNING;
2512 starttime = time_uptime;
2513 td->td_pflags |= TDP_NORUNNINGBUF;
2515 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2518 mtx_lock(&sync_mtx);
2520 if (syncer_state == SYNCER_FINAL_DELAY &&
2521 syncer_final_iter == 0) {
2522 mtx_unlock(&sync_mtx);
2523 kproc_suspend_check(td->td_proc);
2524 mtx_lock(&sync_mtx);
2526 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2527 if (syncer_state != SYNCER_RUNNING &&
2528 starttime != time_uptime) {
2530 printf("\nSyncing disks, vnodes remaining... ");
2533 printf("%d ", net_worklist_len);
2535 starttime = time_uptime;
2538 * Push files whose dirty time has expired. Be careful
2539 * of interrupt race on slp queue.
2541 * Skip over empty worklist slots when shutting down.
2544 slp = &syncer_workitem_pending[syncer_delayno];
2545 syncer_delayno += 1;
2546 if (syncer_delayno == syncer_maxdelay)
2548 next = &syncer_workitem_pending[syncer_delayno];
2550 * If the worklist has wrapped since the
2551 * it was emptied of all but syncer vnodes,
2552 * switch to the FINAL_DELAY state and run
2553 * for one more second.
2555 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2556 net_worklist_len == 0 &&
2557 last_work_seen == syncer_delayno) {
2558 syncer_state = SYNCER_FINAL_DELAY;
2559 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2561 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2562 syncer_worklist_len > 0);
2565 * Keep track of the last time there was anything
2566 * on the worklist other than syncer vnodes.
2567 * Return to the SHUTTING_DOWN state if any
2570 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2571 last_work_seen = syncer_delayno;
2572 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2573 syncer_state = SYNCER_SHUTTING_DOWN;
2574 while (!LIST_EMPTY(slp)) {
2575 error = sync_vnode(slp, &bo, td);
2577 LIST_REMOVE(bo, bo_synclist);
2578 LIST_INSERT_HEAD(next, bo, bo_synclist);
2582 if (first_printf == 0) {
2584 * Drop the sync mutex, because some watchdog
2585 * drivers need to sleep while patting
2587 mtx_unlock(&sync_mtx);
2588 wdog_kern_pat(WD_LASTVAL);
2589 mtx_lock(&sync_mtx);
2593 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2594 syncer_final_iter--;
2596 * The variable rushjob allows the kernel to speed up the
2597 * processing of the filesystem syncer process. A rushjob
2598 * value of N tells the filesystem syncer to process the next
2599 * N seconds worth of work on its queue ASAP. Currently rushjob
2600 * is used by the soft update code to speed up the filesystem
2601 * syncer process when the incore state is getting so far
2602 * ahead of the disk that the kernel memory pool is being
2603 * threatened with exhaustion.
2610 * Just sleep for a short period of time between
2611 * iterations when shutting down to allow some I/O
2614 * If it has taken us less than a second to process the
2615 * current work, then wait. Otherwise start right over
2616 * again. We can still lose time if any single round
2617 * takes more than two seconds, but it does not really
2618 * matter as we are just trying to generally pace the
2619 * filesystem activity.
2621 if (syncer_state != SYNCER_RUNNING ||
2622 time_uptime == starttime) {
2624 sched_prio(td, PPAUSE);
2627 if (syncer_state != SYNCER_RUNNING)
2628 cv_timedwait(&sync_wakeup, &sync_mtx,
2629 hz / SYNCER_SHUTDOWN_SPEEDUP);
2630 else if (time_uptime == starttime)
2631 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2636 * Request the syncer daemon to speed up its work.
2637 * We never push it to speed up more than half of its
2638 * normal turn time, otherwise it could take over the cpu.
2641 speedup_syncer(void)
2645 mtx_lock(&sync_mtx);
2646 if (rushjob < syncdelay / 2) {
2648 stat_rush_requests += 1;
2651 mtx_unlock(&sync_mtx);
2652 cv_broadcast(&sync_wakeup);
2657 * Tell the syncer to speed up its work and run though its work
2658 * list several times, then tell it to shut down.
2661 syncer_shutdown(void *arg, int howto)
2664 if (howto & RB_NOSYNC)
2666 mtx_lock(&sync_mtx);
2667 syncer_state = SYNCER_SHUTTING_DOWN;
2669 mtx_unlock(&sync_mtx);
2670 cv_broadcast(&sync_wakeup);
2671 kproc_shutdown(arg, howto);
2675 syncer_suspend(void)
2678 syncer_shutdown(updateproc, 0);
2685 mtx_lock(&sync_mtx);
2687 syncer_state = SYNCER_RUNNING;
2688 mtx_unlock(&sync_mtx);
2689 cv_broadcast(&sync_wakeup);
2690 kproc_resume(updateproc);
2694 * Reassign a buffer from one vnode to another.
2695 * Used to assign file specific control information
2696 * (indirect blocks) to the vnode to which they belong.
2699 reassignbuf(struct buf *bp)
2712 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2713 bp, bp->b_vp, bp->b_flags);
2715 * B_PAGING flagged buffers cannot be reassigned because their vp
2716 * is not fully linked in.
2718 if (bp->b_flags & B_PAGING)
2719 panic("cannot reassign paging buffer");
2722 * Delete from old vnode list, if on one.
2725 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2726 buf_vlist_remove(bp);
2728 panic("reassignbuf: Buffer %p not on queue.", bp);
2730 * If dirty, put on list of dirty buffers; otherwise insert onto list
2733 if (bp->b_flags & B_DELWRI) {
2734 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2735 switch (vp->v_type) {
2745 vn_syncer_add_to_worklist(bo, delay);
2747 buf_vlist_add(bp, bo, BX_VNDIRTY);
2749 buf_vlist_add(bp, bo, BX_VNCLEAN);
2751 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2752 mtx_lock(&sync_mtx);
2753 LIST_REMOVE(bo, bo_synclist);
2754 syncer_worklist_len--;
2755 mtx_unlock(&sync_mtx);
2756 bo->bo_flag &= ~BO_ONWORKLST;
2761 bp = TAILQ_FIRST(&bv->bv_hd);
2762 KASSERT(bp == NULL || bp->b_bufobj == bo,
2763 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2764 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2765 KASSERT(bp == NULL || bp->b_bufobj == bo,
2766 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2768 bp = TAILQ_FIRST(&bv->bv_hd);
2769 KASSERT(bp == NULL || bp->b_bufobj == bo,
2770 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2771 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2772 KASSERT(bp == NULL || bp->b_bufobj == bo,
2773 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2779 v_init_counters(struct vnode *vp)
2782 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2783 vp, ("%s called for an initialized vnode", __FUNCTION__));
2784 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2786 refcount_init(&vp->v_holdcnt, 1);
2787 refcount_init(&vp->v_usecount, 1);
2791 * Increment si_usecount of the associated device, if any.
2794 v_incr_devcount(struct vnode *vp)
2797 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2798 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2800 vp->v_rdev->si_usecount++;
2806 * Decrement si_usecount of the associated device, if any.
2808 * The caller is required to hold the interlock when transitioning a VCHR use
2809 * count to zero. This prevents a race with devfs_reclaim_vchr() that would
2810 * leak a si_usecount reference. The vnode lock will also prevent this race
2811 * if it is held while dropping the last ref.
2816 * devfs_reclaim_vchr
2817 * make v_usecount == 0
2819 * sees v_usecount == 0, no updates
2820 * vp->v_rdev = NULL;
2825 * sees v_rdev == NULL, no updates
2827 * In this scenario si_devcount decrement is not performed.
2830 v_decr_devcount(struct vnode *vp)
2833 ASSERT_VOP_LOCKED(vp, __func__);
2834 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2835 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2837 VNPASS(vp->v_rdev->si_usecount > 0, vp);
2838 vp->v_rdev->si_usecount--;
2844 * Grab a particular vnode from the free list, increment its
2845 * reference count and lock it. VIRF_DOOMED is set if the vnode
2846 * is being destroyed. Only callers who specify LK_RETRY will
2847 * see doomed vnodes. If inactive processing was delayed in
2848 * vput try to do it here.
2850 * usecount is manipulated using atomics without holding any locks.
2852 * holdcnt can be manipulated using atomics without holding any locks,
2853 * except when transitioning 1<->0, in which case the interlock is held.
2856 vget_prep(struct vnode *vp)
2860 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2870 vget(struct vnode *vp, int flags, struct thread *td)
2874 MPASS(td == curthread);
2877 return (vget_finish(vp, flags, vs));
2880 static int __noinline
2881 vget_finish_vchr(struct vnode *vp)
2884 VNASSERT(vp->v_type == VCHR, vp, ("type != VCHR)"));
2887 * See the comment in vget_finish before usecount bump.
2889 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2891 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2892 VNASSERT(old > 0, vp, ("%s: wrong hold count %d", __func__, old));
2894 refcount_release(&vp->v_holdcnt);
2900 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2902 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2903 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2905 refcount_release(&vp->v_holdcnt);
2910 v_incr_devcount(vp);
2911 refcount_acquire(&vp->v_usecount);
2917 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
2921 if ((flags & LK_INTERLOCK) != 0)
2922 ASSERT_VI_LOCKED(vp, __func__);
2924 ASSERT_VI_UNLOCKED(vp, __func__);
2925 VNPASS(vp->v_holdcnt > 0, vp);
2926 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
2928 error = vn_lock(vp, flags);
2929 if (__predict_false(error != 0)) {
2930 if (vs == VGET_USECOUNT)
2934 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2939 if (vs == VGET_USECOUNT)
2942 if (__predict_false(vp->v_type == VCHR))
2943 return (vget_finish_vchr(vp));
2946 * We hold the vnode. If the usecount is 0 it will be utilized to keep
2947 * the vnode around. Otherwise someone else lended their hold count and
2948 * we have to drop ours.
2950 old = atomic_fetchadd_int(&vp->v_usecount, 1);
2951 VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
2954 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2955 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2957 refcount_release(&vp->v_holdcnt);
2964 * Increase the reference (use) and hold count of a vnode.
2965 * This will also remove the vnode from the free list if it is presently free.
2967 static void __noinline
2968 vref_vchr(struct vnode *vp, bool interlock)
2972 * See the comment in vget_finish before usecount bump.
2975 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2976 VNODE_REFCOUNT_FENCE_ACQ();
2977 VNASSERT(vp->v_holdcnt > 0, vp,
2978 ("%s: active vnode not held", __func__));
2983 * By the time we get here the vnode might have been doomed, at
2984 * which point the 0->1 use count transition is no longer
2985 * protected by the interlock. Since it can't bounce back to
2986 * VCHR and requires vref semantics, punt it back
2988 if (__predict_false(vp->v_type == VBAD)) {
2994 VNASSERT(vp->v_type == VCHR, vp, ("type != VCHR)"));
2995 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2996 VNODE_REFCOUNT_FENCE_ACQ();
2997 VNASSERT(vp->v_holdcnt > 0, vp,
2998 ("%s: active vnode not held", __func__));
3004 v_incr_devcount(vp);
3005 refcount_acquire(&vp->v_usecount);
3012 vref(struct vnode *vp)
3016 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3017 if (__predict_false(vp->v_type == VCHR)) {
3018 vref_vchr(vp, false);
3022 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3023 VNODE_REFCOUNT_FENCE_ACQ();
3024 VNASSERT(vp->v_holdcnt > 0, vp,
3025 ("%s: active vnode not held", __func__));
3030 * See the comment in vget_finish.
3032 old = atomic_fetchadd_int(&vp->v_usecount, 1);
3033 VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
3036 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
3037 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
3039 refcount_release(&vp->v_holdcnt);
3045 vrefl(struct vnode *vp)
3048 ASSERT_VI_LOCKED(vp, __func__);
3049 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3050 if (__predict_false(vp->v_type == VCHR)) {
3051 vref_vchr(vp, true);
3058 vrefact(struct vnode *vp)
3061 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3063 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
3064 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3066 refcount_acquire(&vp->v_usecount);
3071 vrefactn(struct vnode *vp, u_int n)
3074 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3076 int old = atomic_fetchadd_int(&vp->v_usecount, n);
3077 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3079 atomic_add_int(&vp->v_usecount, n);
3084 * Return reference count of a vnode.
3086 * The results of this call are only guaranteed when some mechanism is used to
3087 * stop other processes from gaining references to the vnode. This may be the
3088 * case if the caller holds the only reference. This is also useful when stale
3089 * data is acceptable as race conditions may be accounted for by some other
3093 vrefcnt(struct vnode *vp)
3096 return (vp->v_usecount);
3100 vlazy(struct vnode *vp)
3104 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
3106 if ((vp->v_mflag & VMP_LAZYLIST) != 0)
3109 * We may get here for inactive routines after the vnode got doomed.
3111 if (VN_IS_DOOMED(vp))
3114 mtx_lock(&mp->mnt_listmtx);
3115 if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
3116 vp->v_mflag |= VMP_LAZYLIST;
3117 TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3118 mp->mnt_lazyvnodelistsize++;
3120 mtx_unlock(&mp->mnt_listmtx);
3124 * This routine is only meant to be called from vgonel prior to dooming
3128 vunlazy_gone(struct vnode *vp)
3132 ASSERT_VOP_ELOCKED(vp, __func__);
3133 ASSERT_VI_LOCKED(vp, __func__);
3134 VNPASS(!VN_IS_DOOMED(vp), vp);
3136 if (vp->v_mflag & VMP_LAZYLIST) {
3138 mtx_lock(&mp->mnt_listmtx);
3139 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3140 vp->v_mflag &= ~VMP_LAZYLIST;
3141 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3142 mp->mnt_lazyvnodelistsize--;
3143 mtx_unlock(&mp->mnt_listmtx);
3148 vdefer_inactive(struct vnode *vp)
3151 ASSERT_VI_LOCKED(vp, __func__);
3152 VNASSERT(vp->v_holdcnt > 0, vp,
3153 ("%s: vnode without hold count", __func__));
3154 if (VN_IS_DOOMED(vp)) {
3158 if (vp->v_iflag & VI_DEFINACT) {
3159 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3163 if (vp->v_usecount > 0) {
3164 vp->v_iflag &= ~VI_OWEINACT;
3169 vp->v_iflag |= VI_DEFINACT;
3171 counter_u64_add(deferred_inact, 1);
3175 vdefer_inactive_unlocked(struct vnode *vp)
3179 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3183 vdefer_inactive(vp);
3186 enum vput_op { VRELE, VPUT, VUNREF };
3189 * Handle ->v_usecount transitioning to 0.
3191 * By releasing the last usecount we take ownership of the hold count which
3192 * provides liveness of the vnode, meaning we have to vdrop.
3194 * If the vnode is of type VCHR we may need to decrement si_usecount, see
3195 * v_decr_devcount for details.
3197 * For all vnodes we may need to perform inactive processing. It requires an
3198 * exclusive lock on the vnode, while it is legal to call here with only a
3199 * shared lock (or no locks). If locking the vnode in an expected manner fails,
3200 * inactive processing gets deferred to the syncer.
3202 * XXX Some filesystems pass in an exclusively locked vnode and strongly depend
3203 * on the lock being held all the way until VOP_INACTIVE. This in particular
3204 * happens with UFS which adds half-constructed vnodes to the hash, where they
3205 * can be found by other code.
3208 vput_final(struct vnode *vp, enum vput_op func)
3213 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3214 VNPASS(vp->v_holdcnt > 0, vp);
3217 if (__predict_false(vp->v_type == VCHR && func != VRELE))
3218 v_decr_devcount(vp);
3221 * By the time we got here someone else might have transitioned
3222 * the count back to > 0.
3224 if (vp->v_usecount > 0)
3228 * If the vnode is doomed vgone already performed inactive processing
3231 if (VN_IS_DOOMED(vp))
3234 if (__predict_true(VOP_NEED_INACTIVE(vp) == 0))
3237 if (vp->v_iflag & VI_DOINGINACT)
3241 * Locking operations here will drop the interlock and possibly the
3242 * vnode lock, opening a window where the vnode can get doomed all the
3243 * while ->v_usecount is 0. Set VI_OWEINACT to let vgone know to
3246 vp->v_iflag |= VI_OWEINACT;
3247 want_unlock = false;
3251 switch (VOP_ISLOCKED(vp)) {
3257 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3262 * The lock has at least one sharer, but we have no way
3263 * to conclude whether this is us. Play it safe and
3272 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3273 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3279 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3280 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3291 vdefer_inactive(vp);
3301 * Decrement ->v_usecount for a vnode.
3303 * Releasing the last use count requires additional processing, see vput_final
3304 * above for details.
3306 * Note that releasing use count without the vnode lock requires special casing
3307 * for VCHR, see v_decr_devcount for details.
3309 * Comment above each variant denotes lock state on entry and exit.
3312 static void __noinline
3313 vrele_vchr(struct vnode *vp)
3316 if (refcount_release_if_not_last(&vp->v_usecount))
3319 if (!refcount_release(&vp->v_usecount)) {
3323 v_decr_devcount(vp);
3325 vput_final(vp, VRELE);
3330 * out: same as passed in
3333 vrele(struct vnode *vp)
3336 ASSERT_VI_UNLOCKED(vp, __func__);
3337 if (__predict_false(vp->v_type == VCHR)) {
3341 if (!refcount_release(&vp->v_usecount))
3343 vput_final(vp, VRELE);
3351 vput(struct vnode *vp)
3354 ASSERT_VOP_LOCKED(vp, __func__);
3355 ASSERT_VI_UNLOCKED(vp, __func__);
3356 if (!refcount_release(&vp->v_usecount)) {
3360 vput_final(vp, VPUT);
3368 vunref(struct vnode *vp)
3371 ASSERT_VOP_LOCKED(vp, __func__);
3372 ASSERT_VI_UNLOCKED(vp, __func__);
3373 if (!refcount_release(&vp->v_usecount))
3375 vput_final(vp, VUNREF);
3379 vhold(struct vnode *vp)
3384 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3385 old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3386 VNASSERT(old >= 0, vp, ("%s: wrong hold count %d", __func__, old));
3396 vholdl(struct vnode *vp)
3399 ASSERT_VI_LOCKED(vp, __func__);
3400 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3405 vholdnz(struct vnode *vp)
3408 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3410 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3411 VNASSERT(old > 0, vp, ("%s: wrong hold count %d", __func__, old));
3413 atomic_add_int(&vp->v_holdcnt, 1);
3417 static void __noinline
3418 vdbatch_process(struct vdbatch *vd)
3423 mtx_assert(&vd->lock, MA_OWNED);
3424 MPASS(curthread->td_pinned > 0);
3425 MPASS(vd->index == VDBATCH_SIZE);
3427 mtx_lock(&vnode_list_mtx);
3429 freevnodes += vd->freevnodes;
3430 for (i = 0; i < VDBATCH_SIZE; i++) {
3432 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3433 TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3434 MPASS(vp->v_dbatchcpu != NOCPU);
3435 vp->v_dbatchcpu = NOCPU;
3437 mtx_unlock(&vnode_list_mtx);
3439 bzero(vd->tab, sizeof(vd->tab));
3445 vdbatch_enqueue(struct vnode *vp)
3449 ASSERT_VI_LOCKED(vp, __func__);
3450 VNASSERT(!VN_IS_DOOMED(vp), vp,
3451 ("%s: deferring requeue of a doomed vnode", __func__));
3456 if (vp->v_dbatchcpu != NOCPU) {
3464 mtx_lock(&vd->lock);
3465 MPASS(vd->index < VDBATCH_SIZE);
3466 MPASS(vd->tab[vd->index] == NULL);
3468 * A hack: we depend on being pinned so that we know what to put in
3471 vp->v_dbatchcpu = curcpu;
3472 vd->tab[vd->index] = vp;
3475 if (vd->index == VDBATCH_SIZE)
3476 vdbatch_process(vd);
3477 mtx_unlock(&vd->lock);
3482 * This routine must only be called for vnodes which are about to be
3483 * deallocated. Supporting dequeue for arbitrary vndoes would require
3484 * validating that the locked batch matches.
3487 vdbatch_dequeue(struct vnode *vp)
3493 VNASSERT(vp->v_type == VBAD || vp->v_type == VNON, vp,
3494 ("%s: called for a used vnode\n", __func__));
3496 cpu = vp->v_dbatchcpu;
3500 vd = DPCPU_ID_PTR(cpu, vd);
3501 mtx_lock(&vd->lock);
3502 for (i = 0; i < vd->index; i++) {
3503 if (vd->tab[i] != vp)
3505 vp->v_dbatchcpu = NOCPU;
3507 vd->tab[i] = vd->tab[vd->index];
3508 vd->tab[vd->index] = NULL;
3511 mtx_unlock(&vd->lock);
3513 * Either we dequeued the vnode above or the target CPU beat us to it.
3515 MPASS(vp->v_dbatchcpu == NOCPU);
3519 * Drop the hold count of the vnode. If this is the last reference to
3520 * the vnode we place it on the free list unless it has been vgone'd
3521 * (marked VIRF_DOOMED) in which case we will free it.
3523 * Because the vnode vm object keeps a hold reference on the vnode if
3524 * there is at least one resident non-cached page, the vnode cannot
3525 * leave the active list without the page cleanup done.
3528 vdrop_deactivate(struct vnode *vp)
3532 ASSERT_VI_LOCKED(vp, __func__);
3534 * Mark a vnode as free: remove it from its active list
3535 * and put it up for recycling on the freelist.
3537 VNASSERT(!VN_IS_DOOMED(vp), vp,
3538 ("vdrop: returning doomed vnode"));
3539 VNASSERT(vp->v_op != NULL, vp,
3540 ("vdrop: vnode already reclaimed."));
3541 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
3542 ("vnode with VI_OWEINACT set"));
3543 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp,
3544 ("vnode with VI_DEFINACT set"));
3545 if (vp->v_mflag & VMP_LAZYLIST) {
3547 mtx_lock(&mp->mnt_listmtx);
3548 VNASSERT(vp->v_mflag & VMP_LAZYLIST, vp, ("lost VMP_LAZYLIST"));
3550 * Don't remove the vnode from the lazy list if another thread
3551 * has increased the hold count. It may have re-enqueued the
3552 * vnode to the lazy list and is now responsible for its
3555 if (vp->v_holdcnt == 0) {
3556 vp->v_mflag &= ~VMP_LAZYLIST;
3557 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3558 mp->mnt_lazyvnodelistsize--;
3560 mtx_unlock(&mp->mnt_listmtx);
3562 vdbatch_enqueue(vp);
3566 vdrop(struct vnode *vp)
3569 ASSERT_VI_UNLOCKED(vp, __func__);
3570 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3571 if (refcount_release_if_not_last(&vp->v_holdcnt))
3578 vdropl(struct vnode *vp)
3581 ASSERT_VI_LOCKED(vp, __func__);
3582 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3583 if (!refcount_release(&vp->v_holdcnt)) {
3587 if (VN_IS_DOOMED(vp)) {
3591 vdrop_deactivate(vp);
3595 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3596 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3599 vinactivef(struct vnode *vp)
3601 struct vm_object *obj;
3603 ASSERT_VOP_ELOCKED(vp, "vinactive");
3604 ASSERT_VI_LOCKED(vp, "vinactive");
3605 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3606 ("vinactive: recursed on VI_DOINGINACT"));
3607 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3608 vp->v_iflag |= VI_DOINGINACT;
3609 vp->v_iflag &= ~VI_OWEINACT;
3612 * Before moving off the active list, we must be sure that any
3613 * modified pages are converted into the vnode's dirty
3614 * buffers, since these will no longer be checked once the
3615 * vnode is on the inactive list.
3617 * The write-out of the dirty pages is asynchronous. At the
3618 * point that VOP_INACTIVE() is called, there could still be
3619 * pending I/O and dirty pages in the object.
3621 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3622 vm_object_mightbedirty(obj)) {
3623 VM_OBJECT_WLOCK(obj);
3624 vm_object_page_clean(obj, 0, 0, 0);
3625 VM_OBJECT_WUNLOCK(obj);
3627 VOP_INACTIVE(vp, curthread);
3629 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3630 ("vinactive: lost VI_DOINGINACT"));
3631 vp->v_iflag &= ~VI_DOINGINACT;
3635 vinactive(struct vnode *vp)
3638 ASSERT_VOP_ELOCKED(vp, "vinactive");
3639 ASSERT_VI_LOCKED(vp, "vinactive");
3640 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3642 if ((vp->v_iflag & VI_OWEINACT) == 0)
3644 if (vp->v_iflag & VI_DOINGINACT)
3646 if (vp->v_usecount > 0) {
3647 vp->v_iflag &= ~VI_OWEINACT;
3654 * Remove any vnodes in the vnode table belonging to mount point mp.
3656 * If FORCECLOSE is not specified, there should not be any active ones,
3657 * return error if any are found (nb: this is a user error, not a
3658 * system error). If FORCECLOSE is specified, detach any active vnodes
3661 * If WRITECLOSE is set, only flush out regular file vnodes open for
3664 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3666 * `rootrefs' specifies the base reference count for the root vnode
3667 * of this filesystem. The root vnode is considered busy if its
3668 * v_usecount exceeds this value. On a successful return, vflush(, td)
3669 * will call vrele() on the root vnode exactly rootrefs times.
3670 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3674 static int busyprt = 0; /* print out busy vnodes */
3675 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3679 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3681 struct vnode *vp, *mvp, *rootvp = NULL;
3683 int busy = 0, error;
3685 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3688 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3689 ("vflush: bad args"));
3691 * Get the filesystem root vnode. We can vput() it
3692 * immediately, since with rootrefs > 0, it won't go away.
3694 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3695 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3702 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3704 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3707 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3711 * Skip over a vnodes marked VV_SYSTEM.
3713 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3719 * If WRITECLOSE is set, flush out unlinked but still open
3720 * files (even if open only for reading) and regular file
3721 * vnodes open for writing.
3723 if (flags & WRITECLOSE) {
3724 if (vp->v_object != NULL) {
3725 VM_OBJECT_WLOCK(vp->v_object);
3726 vm_object_page_clean(vp->v_object, 0, 0, 0);
3727 VM_OBJECT_WUNLOCK(vp->v_object);
3729 error = VOP_FSYNC(vp, MNT_WAIT, td);
3733 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3736 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3739 if ((vp->v_type == VNON ||
3740 (error == 0 && vattr.va_nlink > 0)) &&
3741 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3749 * With v_usecount == 0, all we need to do is clear out the
3750 * vnode data structures and we are done.
3752 * If FORCECLOSE is set, forcibly close the vnode.
3754 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3760 vn_printf(vp, "vflush: busy vnode ");
3766 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3768 * If just the root vnode is busy, and if its refcount
3769 * is equal to `rootrefs', then go ahead and kill it.
3772 KASSERT(busy > 0, ("vflush: not busy"));
3773 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3774 ("vflush: usecount %d < rootrefs %d",
3775 rootvp->v_usecount, rootrefs));
3776 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3777 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3785 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3789 for (; rootrefs > 0; rootrefs--)
3795 * Recycle an unused vnode to the front of the free list.
3798 vrecycle(struct vnode *vp)
3803 recycled = vrecyclel(vp);
3809 * vrecycle, with the vp interlock held.
3812 vrecyclel(struct vnode *vp)
3816 ASSERT_VOP_ELOCKED(vp, __func__);
3817 ASSERT_VI_LOCKED(vp, __func__);
3818 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3820 if (vp->v_usecount == 0) {
3828 * Eliminate all activity associated with a vnode
3829 * in preparation for reuse.
3832 vgone(struct vnode *vp)
3840 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3841 struct vnode *lowervp __unused)
3846 * Notify upper mounts about reclaimed or unlinked vnode.
3849 vfs_notify_upper(struct vnode *vp, int event)
3851 static struct vfsops vgonel_vfsops = {
3852 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3853 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3855 struct mount *mp, *ump, *mmp;
3860 if (TAILQ_EMPTY(&mp->mnt_uppers))
3863 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3864 mmp->mnt_op = &vgonel_vfsops;
3865 mmp->mnt_kern_flag |= MNTK_MARKER;
3867 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3868 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3869 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3870 ump = TAILQ_NEXT(ump, mnt_upper_link);
3873 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3876 case VFS_NOTIFY_UPPER_RECLAIM:
3877 VFS_RECLAIM_LOWERVP(ump, vp);
3879 case VFS_NOTIFY_UPPER_UNLINK:
3880 VFS_UNLINK_LOWERVP(ump, vp);
3883 KASSERT(0, ("invalid event %d", event));
3887 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3888 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3891 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3892 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3893 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3894 wakeup(&mp->mnt_uppers);
3900 * vgone, with the vp interlock held.
3903 vgonel(struct vnode *vp)
3908 bool active, oweinact;
3910 ASSERT_VOP_ELOCKED(vp, "vgonel");
3911 ASSERT_VI_LOCKED(vp, "vgonel");
3912 VNASSERT(vp->v_holdcnt, vp,
3913 ("vgonel: vp %p has no reference.", vp));
3914 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3918 * Don't vgonel if we're already doomed.
3920 if (vp->v_irflag & VIRF_DOOMED)
3923 vp->v_irflag |= VIRF_DOOMED;
3926 * Check to see if the vnode is in use. If so, we have to call
3927 * VOP_CLOSE() and VOP_INACTIVE().
3929 active = vp->v_usecount > 0;
3930 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
3932 * If we need to do inactive VI_OWEINACT will be set.
3934 if (vp->v_iflag & VI_DEFINACT) {
3935 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3936 vp->v_iflag &= ~VI_DEFINACT;
3939 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
3942 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
3945 * If purging an active vnode, it must be closed and
3946 * deactivated before being reclaimed.
3949 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
3950 if (oweinact || active) {
3955 if (vp->v_type == VSOCK)
3956 vfs_unp_reclaim(vp);
3959 * Clean out any buffers associated with the vnode.
3960 * If the flush fails, just toss the buffers.
3963 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
3964 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
3965 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
3966 while (vinvalbuf(vp, 0, 0, 0) != 0)
3970 BO_LOCK(&vp->v_bufobj);
3971 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
3972 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
3973 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
3974 vp->v_bufobj.bo_clean.bv_cnt == 0,
3975 ("vp %p bufobj not invalidated", vp));
3978 * For VMIO bufobj, BO_DEAD is set later, or in
3979 * vm_object_terminate() after the object's page queue is
3982 object = vp->v_bufobj.bo_object;
3984 vp->v_bufobj.bo_flag |= BO_DEAD;
3985 BO_UNLOCK(&vp->v_bufobj);
3988 * Handle the VM part. Tmpfs handles v_object on its own (the
3989 * OBJT_VNODE check). Nullfs or other bypassing filesystems
3990 * should not touch the object borrowed from the lower vnode
3991 * (the handle check).
3993 if (object != NULL && object->type == OBJT_VNODE &&
3994 object->handle == vp)
3995 vnode_destroy_vobject(vp);
3998 * Reclaim the vnode.
4000 if (VOP_RECLAIM(vp, td))
4001 panic("vgone: cannot reclaim");
4003 vn_finished_secondary_write(mp);
4004 VNASSERT(vp->v_object == NULL, vp,
4005 ("vop_reclaim left v_object vp=%p", vp));
4007 * Clear the advisory locks and wake up waiting threads.
4009 (void)VOP_ADVLOCKPURGE(vp);
4012 * Delete from old mount point vnode list.
4017 * Done with purge, reset to the standard lock and invalidate
4021 vp->v_vnlock = &vp->v_lock;
4022 vp->v_op = &dead_vnodeops;
4027 * Calculate the total number of references to a special device.
4030 vcount(struct vnode *vp)
4035 count = vp->v_rdev->si_usecount;
4041 * Print out a description of a vnode.
4043 static char *typename[] =
4044 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
4048 vn_printf(struct vnode *vp, const char *fmt, ...)
4051 char buf[256], buf2[16];
4057 printf("%p: ", (void *)vp);
4058 printf("type %s\n", typename[vp->v_type]);
4059 printf(" usecount %d, writecount %d, refcount %d",
4060 vp->v_usecount, vp->v_writecount, vp->v_holdcnt);
4061 switch (vp->v_type) {
4063 printf(" mountedhere %p\n", vp->v_mountedhere);
4066 printf(" rdev %p\n", vp->v_rdev);
4069 printf(" socket %p\n", vp->v_unpcb);
4072 printf(" fifoinfo %p\n", vp->v_fifoinfo);
4080 if (vp->v_irflag & VIRF_DOOMED)
4081 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
4082 flags = vp->v_irflag & ~(VIRF_DOOMED);
4084 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
4085 strlcat(buf, buf2, sizeof(buf));
4087 if (vp->v_vflag & VV_ROOT)
4088 strlcat(buf, "|VV_ROOT", sizeof(buf));
4089 if (vp->v_vflag & VV_ISTTY)
4090 strlcat(buf, "|VV_ISTTY", sizeof(buf));
4091 if (vp->v_vflag & VV_NOSYNC)
4092 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
4093 if (vp->v_vflag & VV_ETERNALDEV)
4094 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
4095 if (vp->v_vflag & VV_CACHEDLABEL)
4096 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
4097 if (vp->v_vflag & VV_VMSIZEVNLOCK)
4098 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
4099 if (vp->v_vflag & VV_COPYONWRITE)
4100 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
4101 if (vp->v_vflag & VV_SYSTEM)
4102 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
4103 if (vp->v_vflag & VV_PROCDEP)
4104 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
4105 if (vp->v_vflag & VV_NOKNOTE)
4106 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
4107 if (vp->v_vflag & VV_DELETED)
4108 strlcat(buf, "|VV_DELETED", sizeof(buf));
4109 if (vp->v_vflag & VV_MD)
4110 strlcat(buf, "|VV_MD", sizeof(buf));
4111 if (vp->v_vflag & VV_FORCEINSMQ)
4112 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
4113 if (vp->v_vflag & VV_READLINK)
4114 strlcat(buf, "|VV_READLINK", sizeof(buf));
4115 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4116 VV_CACHEDLABEL | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
4117 VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
4119 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4120 strlcat(buf, buf2, sizeof(buf));
4122 if (vp->v_iflag & VI_TEXT_REF)
4123 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
4124 if (vp->v_iflag & VI_MOUNT)
4125 strlcat(buf, "|VI_MOUNT", sizeof(buf));
4126 if (vp->v_iflag & VI_DOINGINACT)
4127 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4128 if (vp->v_iflag & VI_OWEINACT)
4129 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4130 if (vp->v_iflag & VI_DEFINACT)
4131 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4132 flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOINGINACT |
4133 VI_OWEINACT | VI_DEFINACT);
4135 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4136 strlcat(buf, buf2, sizeof(buf));
4138 if (vp->v_mflag & VMP_LAZYLIST)
4139 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4140 flags = vp->v_mflag & ~(VMP_LAZYLIST);
4142 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4143 strlcat(buf, buf2, sizeof(buf));
4145 printf(" flags (%s)\n", buf + 1);
4146 if (mtx_owned(VI_MTX(vp)))
4147 printf(" VI_LOCKed");
4148 if (vp->v_object != NULL)
4149 printf(" v_object %p ref %d pages %d "
4150 "cleanbuf %d dirtybuf %d\n",
4151 vp->v_object, vp->v_object->ref_count,
4152 vp->v_object->resident_page_count,
4153 vp->v_bufobj.bo_clean.bv_cnt,
4154 vp->v_bufobj.bo_dirty.bv_cnt);
4156 lockmgr_printinfo(vp->v_vnlock);
4157 if (vp->v_data != NULL)
4163 * List all of the locked vnodes in the system.
4164 * Called when debugging the kernel.
4166 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
4172 * Note: because this is DDB, we can't obey the locking semantics
4173 * for these structures, which means we could catch an inconsistent
4174 * state and dereference a nasty pointer. Not much to be done
4177 db_printf("Locked vnodes\n");
4178 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4179 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4180 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4181 vn_printf(vp, "vnode ");
4187 * Show details about the given vnode.
4189 DB_SHOW_COMMAND(vnode, db_show_vnode)
4195 vp = (struct vnode *)addr;
4196 vn_printf(vp, "vnode ");
4200 * Show details about the given mount point.
4202 DB_SHOW_COMMAND(mount, db_show_mount)
4213 /* No address given, print short info about all mount points. */
4214 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4215 db_printf("%p %s on %s (%s)\n", mp,
4216 mp->mnt_stat.f_mntfromname,
4217 mp->mnt_stat.f_mntonname,
4218 mp->mnt_stat.f_fstypename);
4222 db_printf("\nMore info: show mount <addr>\n");
4226 mp = (struct mount *)addr;
4227 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4228 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4231 mflags = mp->mnt_flag;
4232 #define MNT_FLAG(flag) do { \
4233 if (mflags & (flag)) { \
4234 if (buf[0] != '\0') \
4235 strlcat(buf, ", ", sizeof(buf)); \
4236 strlcat(buf, (#flag) + 4, sizeof(buf)); \
4237 mflags &= ~(flag); \
4240 MNT_FLAG(MNT_RDONLY);
4241 MNT_FLAG(MNT_SYNCHRONOUS);
4242 MNT_FLAG(MNT_NOEXEC);
4243 MNT_FLAG(MNT_NOSUID);
4244 MNT_FLAG(MNT_NFS4ACLS);
4245 MNT_FLAG(MNT_UNION);
4246 MNT_FLAG(MNT_ASYNC);
4247 MNT_FLAG(MNT_SUIDDIR);
4248 MNT_FLAG(MNT_SOFTDEP);
4249 MNT_FLAG(MNT_NOSYMFOLLOW);
4250 MNT_FLAG(MNT_GJOURNAL);
4251 MNT_FLAG(MNT_MULTILABEL);
4253 MNT_FLAG(MNT_NOATIME);
4254 MNT_FLAG(MNT_NOCLUSTERR);
4255 MNT_FLAG(MNT_NOCLUSTERW);
4257 MNT_FLAG(MNT_EXRDONLY);
4258 MNT_FLAG(MNT_EXPORTED);
4259 MNT_FLAG(MNT_DEFEXPORTED);
4260 MNT_FLAG(MNT_EXPORTANON);
4261 MNT_FLAG(MNT_EXKERB);
4262 MNT_FLAG(MNT_EXPUBLIC);
4263 MNT_FLAG(MNT_LOCAL);
4264 MNT_FLAG(MNT_QUOTA);
4265 MNT_FLAG(MNT_ROOTFS);
4267 MNT_FLAG(MNT_IGNORE);
4268 MNT_FLAG(MNT_UPDATE);
4269 MNT_FLAG(MNT_DELEXPORT);
4270 MNT_FLAG(MNT_RELOAD);
4271 MNT_FLAG(MNT_FORCE);
4272 MNT_FLAG(MNT_SNAPSHOT);
4273 MNT_FLAG(MNT_BYFSID);
4277 strlcat(buf, ", ", sizeof(buf));
4278 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4279 "0x%016jx", mflags);
4281 db_printf(" mnt_flag = %s\n", buf);
4284 flags = mp->mnt_kern_flag;
4285 #define MNT_KERN_FLAG(flag) do { \
4286 if (flags & (flag)) { \
4287 if (buf[0] != '\0') \
4288 strlcat(buf, ", ", sizeof(buf)); \
4289 strlcat(buf, (#flag) + 5, sizeof(buf)); \
4293 MNT_KERN_FLAG(MNTK_UNMOUNTF);
4294 MNT_KERN_FLAG(MNTK_ASYNC);
4295 MNT_KERN_FLAG(MNTK_SOFTDEP);
4296 MNT_KERN_FLAG(MNTK_DRAINING);
4297 MNT_KERN_FLAG(MNTK_REFEXPIRE);
4298 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4299 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4300 MNT_KERN_FLAG(MNTK_NO_IOPF);
4301 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4302 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4303 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4304 MNT_KERN_FLAG(MNTK_MARKER);
4305 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4306 MNT_KERN_FLAG(MNTK_NOASYNC);
4307 MNT_KERN_FLAG(MNTK_UNMOUNT);
4308 MNT_KERN_FLAG(MNTK_MWAIT);
4309 MNT_KERN_FLAG(MNTK_SUSPEND);
4310 MNT_KERN_FLAG(MNTK_SUSPEND2);
4311 MNT_KERN_FLAG(MNTK_SUSPENDED);
4312 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4313 MNT_KERN_FLAG(MNTK_NOKNOTE);
4314 #undef MNT_KERN_FLAG
4317 strlcat(buf, ", ", sizeof(buf));
4318 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4321 db_printf(" mnt_kern_flag = %s\n", buf);
4323 db_printf(" mnt_opt = ");
4324 opt = TAILQ_FIRST(mp->mnt_opt);
4326 db_printf("%s", opt->name);
4327 opt = TAILQ_NEXT(opt, link);
4328 while (opt != NULL) {
4329 db_printf(", %s", opt->name);
4330 opt = TAILQ_NEXT(opt, link);
4336 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4337 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4338 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4339 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4340 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4341 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4342 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4343 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4344 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4345 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4346 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4347 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4349 db_printf(" mnt_cred = { uid=%u ruid=%u",
4350 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4351 if (jailed(mp->mnt_cred))
4352 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4354 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4355 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4356 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4357 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4358 db_printf(" mnt_lazyvnodelistsize = %d\n",
4359 mp->mnt_lazyvnodelistsize);
4360 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4361 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4362 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
4363 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4364 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4365 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4366 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4367 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4368 db_printf(" mnt_secondary_accwrites = %d\n",
4369 mp->mnt_secondary_accwrites);
4370 db_printf(" mnt_gjprovider = %s\n",
4371 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4372 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4374 db_printf("\n\nList of active vnodes\n");
4375 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4376 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4377 vn_printf(vp, "vnode ");
4382 db_printf("\n\nList of inactive vnodes\n");
4383 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4384 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4385 vn_printf(vp, "vnode ");
4394 * Fill in a struct xvfsconf based on a struct vfsconf.
4397 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4399 struct xvfsconf xvfsp;
4401 bzero(&xvfsp, sizeof(xvfsp));
4402 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4403 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4404 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4405 xvfsp.vfc_flags = vfsp->vfc_flags;
4407 * These are unused in userland, we keep them
4408 * to not break binary compatibility.
4410 xvfsp.vfc_vfsops = NULL;
4411 xvfsp.vfc_next = NULL;
4412 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4415 #ifdef COMPAT_FREEBSD32
4417 uint32_t vfc_vfsops;
4418 char vfc_name[MFSNAMELEN];
4419 int32_t vfc_typenum;
4420 int32_t vfc_refcount;
4426 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4428 struct xvfsconf32 xvfsp;
4430 bzero(&xvfsp, sizeof(xvfsp));
4431 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4432 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4433 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4434 xvfsp.vfc_flags = vfsp->vfc_flags;
4435 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4440 * Top level filesystem related information gathering.
4443 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4445 struct vfsconf *vfsp;
4450 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4451 #ifdef COMPAT_FREEBSD32
4452 if (req->flags & SCTL_MASK32)
4453 error = vfsconf2x32(req, vfsp);
4456 error = vfsconf2x(req, vfsp);
4464 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4465 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4466 "S,xvfsconf", "List of all configured filesystems");
4468 #ifndef BURN_BRIDGES
4469 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4472 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4474 int *name = (int *)arg1 - 1; /* XXX */
4475 u_int namelen = arg2 + 1; /* XXX */
4476 struct vfsconf *vfsp;
4478 log(LOG_WARNING, "userland calling deprecated sysctl, "
4479 "please rebuild world\n");
4481 #if 1 || defined(COMPAT_PRELITE2)
4482 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4484 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4488 case VFS_MAXTYPENUM:
4491 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4494 return (ENOTDIR); /* overloaded */
4496 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4497 if (vfsp->vfc_typenum == name[2])
4502 return (EOPNOTSUPP);
4503 #ifdef COMPAT_FREEBSD32
4504 if (req->flags & SCTL_MASK32)
4505 return (vfsconf2x32(req, vfsp));
4508 return (vfsconf2x(req, vfsp));
4510 return (EOPNOTSUPP);
4513 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4514 CTLFLAG_MPSAFE, vfs_sysctl,
4515 "Generic filesystem");
4517 #if 1 || defined(COMPAT_PRELITE2)
4520 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4523 struct vfsconf *vfsp;
4524 struct ovfsconf ovfs;
4527 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4528 bzero(&ovfs, sizeof(ovfs));
4529 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4530 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4531 ovfs.vfc_index = vfsp->vfc_typenum;
4532 ovfs.vfc_refcount = vfsp->vfc_refcount;
4533 ovfs.vfc_flags = vfsp->vfc_flags;
4534 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4544 #endif /* 1 || COMPAT_PRELITE2 */
4545 #endif /* !BURN_BRIDGES */
4547 #define KINFO_VNODESLOP 10
4550 * Dump vnode list (via sysctl).
4554 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4562 * Stale numvnodes access is not fatal here.
4565 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4567 /* Make an estimate */
4568 return (SYSCTL_OUT(req, 0, len));
4570 error = sysctl_wire_old_buffer(req, 0);
4573 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4575 mtx_lock(&mountlist_mtx);
4576 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4577 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4580 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4584 xvn[n].xv_size = sizeof *xvn;
4585 xvn[n].xv_vnode = vp;
4586 xvn[n].xv_id = 0; /* XXX compat */
4587 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4589 XV_COPY(writecount);
4595 xvn[n].xv_flag = vp->v_vflag;
4597 switch (vp->v_type) {
4604 if (vp->v_rdev == NULL) {
4608 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4611 xvn[n].xv_socket = vp->v_socket;
4614 xvn[n].xv_fifo = vp->v_fifoinfo;
4619 /* shouldn't happen? */
4627 mtx_lock(&mountlist_mtx);
4632 mtx_unlock(&mountlist_mtx);
4634 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4639 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4640 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4645 unmount_or_warn(struct mount *mp)
4649 error = dounmount(mp, MNT_FORCE, curthread);
4651 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4655 printf("%d)\n", error);
4660 * Unmount all filesystems. The list is traversed in reverse order
4661 * of mounting to avoid dependencies.
4664 vfs_unmountall(void)
4666 struct mount *mp, *tmp;
4668 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4671 * Since this only runs when rebooting, it is not interlocked.
4673 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4677 * Forcibly unmounting "/dev" before "/" would prevent clean
4678 * unmount of the latter.
4680 if (mp == rootdevmp)
4683 unmount_or_warn(mp);
4686 if (rootdevmp != NULL)
4687 unmount_or_warn(rootdevmp);
4691 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4694 ASSERT_VI_LOCKED(vp, __func__);
4695 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4696 if ((vp->v_iflag & VI_OWEINACT) == 0) {
4700 if (vn_lock(vp, lkflags) == 0) {
4707 vdefer_inactive_unlocked(vp);
4711 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4714 return (vp->v_iflag & VI_DEFINACT);
4717 static void __noinline
4718 vfs_periodic_inactive(struct mount *mp, int flags)
4720 struct vnode *vp, *mvp;
4723 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4724 if (flags != MNT_WAIT)
4725 lkflags |= LK_NOWAIT;
4727 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4728 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4732 vp->v_iflag &= ~VI_DEFINACT;
4733 vfs_deferred_inactive(vp, lkflags);
4738 vfs_want_msync(struct vnode *vp)
4740 struct vm_object *obj;
4743 * This test may be performed without any locks held.
4744 * We rely on vm_object's type stability.
4746 if (vp->v_vflag & VV_NOSYNC)
4749 return (obj != NULL && vm_object_mightbedirty(obj));
4753 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4756 if (vp->v_vflag & VV_NOSYNC)
4758 if (vp->v_iflag & VI_DEFINACT)
4760 return (vfs_want_msync(vp));
4763 static void __noinline
4764 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4766 struct vnode *vp, *mvp;
4767 struct vm_object *obj;
4769 int lkflags, objflags;
4774 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4775 if (flags != MNT_WAIT) {
4776 lkflags |= LK_NOWAIT;
4777 objflags = OBJPC_NOSYNC;
4779 objflags = OBJPC_SYNC;
4782 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4784 if (vp->v_iflag & VI_DEFINACT) {
4785 vp->v_iflag &= ~VI_DEFINACT;
4788 if (!vfs_want_msync(vp)) {
4790 vfs_deferred_inactive(vp, lkflags);
4795 if (vget(vp, lkflags, td) == 0) {
4797 if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4798 VM_OBJECT_WLOCK(obj);
4799 vm_object_page_clean(obj, 0, 0, objflags);
4800 VM_OBJECT_WUNLOCK(obj);
4807 vdefer_inactive_unlocked(vp);
4813 vfs_periodic(struct mount *mp, int flags)
4816 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4818 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4819 vfs_periodic_inactive(mp, flags);
4821 vfs_periodic_msync_inactive(mp, flags);
4825 destroy_vpollinfo_free(struct vpollinfo *vi)
4828 knlist_destroy(&vi->vpi_selinfo.si_note);
4829 mtx_destroy(&vi->vpi_lock);
4830 uma_zfree(vnodepoll_zone, vi);
4834 destroy_vpollinfo(struct vpollinfo *vi)
4837 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4838 seldrain(&vi->vpi_selinfo);
4839 destroy_vpollinfo_free(vi);
4843 * Initialize per-vnode helper structure to hold poll-related state.
4846 v_addpollinfo(struct vnode *vp)
4848 struct vpollinfo *vi;
4850 if (vp->v_pollinfo != NULL)
4852 vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4853 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4854 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4855 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4857 if (vp->v_pollinfo != NULL) {
4859 destroy_vpollinfo_free(vi);
4862 vp->v_pollinfo = vi;
4867 * Record a process's interest in events which might happen to
4868 * a vnode. Because poll uses the historic select-style interface
4869 * internally, this routine serves as both the ``check for any
4870 * pending events'' and the ``record my interest in future events''
4871 * functions. (These are done together, while the lock is held,
4872 * to avoid race conditions.)
4875 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4879 mtx_lock(&vp->v_pollinfo->vpi_lock);
4880 if (vp->v_pollinfo->vpi_revents & events) {
4882 * This leaves events we are not interested
4883 * in available for the other process which
4884 * which presumably had requested them
4885 * (otherwise they would never have been
4888 events &= vp->v_pollinfo->vpi_revents;
4889 vp->v_pollinfo->vpi_revents &= ~events;
4891 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4894 vp->v_pollinfo->vpi_events |= events;
4895 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4896 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4901 * Routine to create and manage a filesystem syncer vnode.
4903 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4904 static int sync_fsync(struct vop_fsync_args *);
4905 static int sync_inactive(struct vop_inactive_args *);
4906 static int sync_reclaim(struct vop_reclaim_args *);
4908 static struct vop_vector sync_vnodeops = {
4909 .vop_bypass = VOP_EOPNOTSUPP,
4910 .vop_close = sync_close, /* close */
4911 .vop_fsync = sync_fsync, /* fsync */
4912 .vop_inactive = sync_inactive, /* inactive */
4913 .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
4914 .vop_reclaim = sync_reclaim, /* reclaim */
4915 .vop_lock1 = vop_stdlock, /* lock */
4916 .vop_unlock = vop_stdunlock, /* unlock */
4917 .vop_islocked = vop_stdislocked, /* islocked */
4919 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
4922 * Create a new filesystem syncer vnode for the specified mount point.
4925 vfs_allocate_syncvnode(struct mount *mp)
4929 static long start, incr, next;
4932 /* Allocate a new vnode */
4933 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
4935 panic("vfs_allocate_syncvnode: getnewvnode() failed");
4937 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4938 vp->v_vflag |= VV_FORCEINSMQ;
4939 error = insmntque(vp, mp);
4941 panic("vfs_allocate_syncvnode: insmntque() failed");
4942 vp->v_vflag &= ~VV_FORCEINSMQ;
4945 * Place the vnode onto the syncer worklist. We attempt to
4946 * scatter them about on the list so that they will go off
4947 * at evenly distributed times even if all the filesystems
4948 * are mounted at once.
4951 if (next == 0 || next > syncer_maxdelay) {
4955 start = syncer_maxdelay / 2;
4956 incr = syncer_maxdelay;
4962 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
4963 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
4964 mtx_lock(&sync_mtx);
4966 if (mp->mnt_syncer == NULL) {
4967 mp->mnt_syncer = vp;
4970 mtx_unlock(&sync_mtx);
4973 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4980 vfs_deallocate_syncvnode(struct mount *mp)
4984 mtx_lock(&sync_mtx);
4985 vp = mp->mnt_syncer;
4987 mp->mnt_syncer = NULL;
4988 mtx_unlock(&sync_mtx);
4994 * Do a lazy sync of the filesystem.
4997 sync_fsync(struct vop_fsync_args *ap)
4999 struct vnode *syncvp = ap->a_vp;
5000 struct mount *mp = syncvp->v_mount;
5005 * We only need to do something if this is a lazy evaluation.
5007 if (ap->a_waitfor != MNT_LAZY)
5011 * Move ourselves to the back of the sync list.
5013 bo = &syncvp->v_bufobj;
5015 vn_syncer_add_to_worklist(bo, syncdelay);
5019 * Walk the list of vnodes pushing all that are dirty and
5020 * not already on the sync list.
5022 if (vfs_busy(mp, MBF_NOWAIT) != 0)
5024 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
5028 save = curthread_pflags_set(TDP_SYNCIO);
5030 * The filesystem at hand may be idle with free vnodes stored in the
5031 * batch. Return them instead of letting them stay there indefinitely.
5033 vfs_periodic(mp, MNT_NOWAIT);
5034 error = VFS_SYNC(mp, MNT_LAZY);
5035 curthread_pflags_restore(save);
5036 vn_finished_write(mp);
5042 * The syncer vnode is no referenced.
5045 sync_inactive(struct vop_inactive_args *ap)
5053 * The syncer vnode is no longer needed and is being decommissioned.
5055 * Modifications to the worklist must be protected by sync_mtx.
5058 sync_reclaim(struct vop_reclaim_args *ap)
5060 struct vnode *vp = ap->a_vp;
5065 mtx_lock(&sync_mtx);
5066 if (vp->v_mount->mnt_syncer == vp)
5067 vp->v_mount->mnt_syncer = NULL;
5068 if (bo->bo_flag & BO_ONWORKLST) {
5069 LIST_REMOVE(bo, bo_synclist);
5070 syncer_worklist_len--;
5072 bo->bo_flag &= ~BO_ONWORKLST;
5074 mtx_unlock(&sync_mtx);
5081 vn_need_pageq_flush(struct vnode *vp)
5083 struct vm_object *obj;
5086 MPASS(mtx_owned(VI_MTX(vp)));
5088 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
5089 vm_object_mightbedirty(obj))
5095 * Check if vnode represents a disk device
5098 vn_isdisk(struct vnode *vp, int *errp)
5102 if (vp->v_type != VCHR) {
5108 if (vp->v_rdev == NULL)
5110 else if (vp->v_rdev->si_devsw == NULL)
5112 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5118 return (error == 0);
5122 * Common filesystem object access control check routine. Accepts a
5123 * vnode's type, "mode", uid and gid, requested access mode, credentials,
5124 * and optional call-by-reference privused argument allowing vaccess()
5125 * to indicate to the caller whether privilege was used to satisfy the
5126 * request (obsoleted). Returns 0 on success, or an errno on failure.
5129 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5130 accmode_t accmode, struct ucred *cred, int *privused)
5132 accmode_t dac_granted;
5133 accmode_t priv_granted;
5135 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5136 ("invalid bit in accmode"));
5137 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5138 ("VAPPEND without VWRITE"));
5141 * Look for a normal, non-privileged way to access the file/directory
5142 * as requested. If it exists, go with that.
5145 if (privused != NULL)
5150 /* Check the owner. */
5151 if (cred->cr_uid == file_uid) {
5152 dac_granted |= VADMIN;
5153 if (file_mode & S_IXUSR)
5154 dac_granted |= VEXEC;
5155 if (file_mode & S_IRUSR)
5156 dac_granted |= VREAD;
5157 if (file_mode & S_IWUSR)
5158 dac_granted |= (VWRITE | VAPPEND);
5160 if ((accmode & dac_granted) == accmode)
5166 /* Otherwise, check the groups (first match) */
5167 if (groupmember(file_gid, cred)) {
5168 if (file_mode & S_IXGRP)
5169 dac_granted |= VEXEC;
5170 if (file_mode & S_IRGRP)
5171 dac_granted |= VREAD;
5172 if (file_mode & S_IWGRP)
5173 dac_granted |= (VWRITE | VAPPEND);
5175 if ((accmode & dac_granted) == accmode)
5181 /* Otherwise, check everyone else. */
5182 if (file_mode & S_IXOTH)
5183 dac_granted |= VEXEC;
5184 if (file_mode & S_IROTH)
5185 dac_granted |= VREAD;
5186 if (file_mode & S_IWOTH)
5187 dac_granted |= (VWRITE | VAPPEND);
5188 if ((accmode & dac_granted) == accmode)
5193 * Build a privilege mask to determine if the set of privileges
5194 * satisfies the requirements when combined with the granted mask
5195 * from above. For each privilege, if the privilege is required,
5196 * bitwise or the request type onto the priv_granted mask.
5202 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5203 * requests, instead of PRIV_VFS_EXEC.
5205 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5206 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5207 priv_granted |= VEXEC;
5210 * Ensure that at least one execute bit is on. Otherwise,
5211 * a privileged user will always succeed, and we don't want
5212 * this to happen unless the file really is executable.
5214 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5215 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5216 !priv_check_cred(cred, PRIV_VFS_EXEC))
5217 priv_granted |= VEXEC;
5220 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5221 !priv_check_cred(cred, PRIV_VFS_READ))
5222 priv_granted |= VREAD;
5224 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5225 !priv_check_cred(cred, PRIV_VFS_WRITE))
5226 priv_granted |= (VWRITE | VAPPEND);
5228 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5229 !priv_check_cred(cred, PRIV_VFS_ADMIN))
5230 priv_granted |= VADMIN;
5232 if ((accmode & (priv_granted | dac_granted)) == accmode) {
5233 /* XXX audit: privilege used */
5234 if (privused != NULL)
5239 return ((accmode & VADMIN) ? EPERM : EACCES);
5243 * Credential check based on process requesting service, and per-attribute
5247 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5248 struct thread *td, accmode_t accmode)
5252 * Kernel-invoked always succeeds.
5258 * Do not allow privileged processes in jail to directly manipulate
5259 * system attributes.
5261 switch (attrnamespace) {
5262 case EXTATTR_NAMESPACE_SYSTEM:
5263 /* Potentially should be: return (EPERM); */
5264 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5265 case EXTATTR_NAMESPACE_USER:
5266 return (VOP_ACCESS(vp, accmode, cred, td));
5272 #ifdef DEBUG_VFS_LOCKS
5274 * This only exists to suppress warnings from unlocked specfs accesses. It is
5275 * no longer ok to have an unlocked VFS.
5277 #define IGNORE_LOCK(vp) (KERNEL_PANICKED() || (vp) == NULL || \
5278 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
5280 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
5281 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5282 "Drop into debugger on lock violation");
5284 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
5285 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5286 0, "Check for interlock across VOPs");
5288 int vfs_badlock_print = 1; /* Print lock violations. */
5289 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5290 0, "Print lock violations");
5292 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
5293 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5294 0, "Print vnode details on lock violations");
5297 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
5298 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5299 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5303 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5307 if (vfs_badlock_backtrace)
5310 if (vfs_badlock_vnode)
5311 vn_printf(vp, "vnode ");
5312 if (vfs_badlock_print)
5313 printf("%s: %p %s\n", str, (void *)vp, msg);
5314 if (vfs_badlock_ddb)
5315 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5319 assert_vi_locked(struct vnode *vp, const char *str)
5322 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5323 vfs_badlock("interlock is not locked but should be", str, vp);
5327 assert_vi_unlocked(struct vnode *vp, const char *str)
5330 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5331 vfs_badlock("interlock is locked but should not be", str, vp);
5335 assert_vop_locked(struct vnode *vp, const char *str)
5339 if (!IGNORE_LOCK(vp)) {
5340 locked = VOP_ISLOCKED(vp);
5341 if (locked == 0 || locked == LK_EXCLOTHER)
5342 vfs_badlock("is not locked but should be", str, vp);
5347 assert_vop_unlocked(struct vnode *vp, const char *str)
5350 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5351 vfs_badlock("is locked but should not be", str, vp);
5355 assert_vop_elocked(struct vnode *vp, const char *str)
5358 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5359 vfs_badlock("is not exclusive locked but should be", str, vp);
5361 #endif /* DEBUG_VFS_LOCKS */
5364 vop_rename_fail(struct vop_rename_args *ap)
5367 if (ap->a_tvp != NULL)
5369 if (ap->a_tdvp == ap->a_tvp)
5378 vop_rename_pre(void *ap)
5380 struct vop_rename_args *a = ap;
5382 #ifdef DEBUG_VFS_LOCKS
5384 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5385 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5386 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5387 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5389 /* Check the source (from). */
5390 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5391 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5392 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5393 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5394 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5396 /* Check the target. */
5398 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5399 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5401 if (a->a_tdvp != a->a_fdvp)
5403 if (a->a_tvp != a->a_fvp)
5410 #ifdef DEBUG_VFS_LOCKS
5412 vop_strategy_pre(void *ap)
5414 struct vop_strategy_args *a;
5421 * Cluster ops lock their component buffers but not the IO container.
5423 if ((bp->b_flags & B_CLUSTER) != 0)
5426 if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5427 if (vfs_badlock_print)
5429 "VOP_STRATEGY: bp is not locked but should be\n");
5430 if (vfs_badlock_ddb)
5431 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5436 vop_lock_pre(void *ap)
5438 struct vop_lock1_args *a = ap;
5440 if ((a->a_flags & LK_INTERLOCK) == 0)
5441 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5443 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5447 vop_lock_post(void *ap, int rc)
5449 struct vop_lock1_args *a = ap;
5451 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5452 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5453 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5457 vop_unlock_pre(void *ap)
5459 struct vop_unlock_args *a = ap;
5461 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5465 vop_need_inactive_pre(void *ap)
5467 struct vop_need_inactive_args *a = ap;
5469 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5473 vop_need_inactive_post(void *ap, int rc)
5475 struct vop_need_inactive_args *a = ap;
5477 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5482 vop_create_post(void *ap, int rc)
5484 struct vop_create_args *a = ap;
5487 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5491 vop_deleteextattr_post(void *ap, int rc)
5493 struct vop_deleteextattr_args *a = ap;
5496 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5500 vop_link_post(void *ap, int rc)
5502 struct vop_link_args *a = ap;
5505 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
5506 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
5511 vop_mkdir_post(void *ap, int rc)
5513 struct vop_mkdir_args *a = ap;
5516 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5520 vop_mknod_post(void *ap, int rc)
5522 struct vop_mknod_args *a = ap;
5525 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5529 vop_reclaim_post(void *ap, int rc)
5531 struct vop_reclaim_args *a = ap;
5534 VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
5538 vop_remove_post(void *ap, int rc)
5540 struct vop_remove_args *a = ap;
5543 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5544 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5549 vop_rename_post(void *ap, int rc)
5551 struct vop_rename_args *a = ap;
5556 if (a->a_fdvp == a->a_tdvp) {
5557 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5559 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5560 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5562 hint |= NOTE_EXTEND;
5563 if (a->a_fvp->v_type == VDIR)
5565 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5567 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5568 a->a_tvp->v_type == VDIR)
5570 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5573 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5575 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5577 if (a->a_tdvp != a->a_fdvp)
5579 if (a->a_tvp != a->a_fvp)
5587 vop_rmdir_post(void *ap, int rc)
5589 struct vop_rmdir_args *a = ap;
5592 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5593 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5598 vop_setattr_post(void *ap, int rc)
5600 struct vop_setattr_args *a = ap;
5603 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5607 vop_setextattr_post(void *ap, int rc)
5609 struct vop_setextattr_args *a = ap;
5612 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5616 vop_symlink_post(void *ap, int rc)
5618 struct vop_symlink_args *a = ap;
5621 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5625 vop_open_post(void *ap, int rc)
5627 struct vop_open_args *a = ap;
5630 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
5634 vop_close_post(void *ap, int rc)
5636 struct vop_close_args *a = ap;
5638 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
5639 !VN_IS_DOOMED(a->a_vp))) {
5640 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
5641 NOTE_CLOSE_WRITE : NOTE_CLOSE);
5646 vop_read_post(void *ap, int rc)
5648 struct vop_read_args *a = ap;
5651 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5655 vop_readdir_post(void *ap, int rc)
5657 struct vop_readdir_args *a = ap;
5660 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5663 static struct knlist fs_knlist;
5666 vfs_event_init(void *arg)
5668 knlist_init_mtx(&fs_knlist, NULL);
5670 /* XXX - correct order? */
5671 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
5674 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
5677 KNOTE_UNLOCKED(&fs_knlist, event);
5680 static int filt_fsattach(struct knote *kn);
5681 static void filt_fsdetach(struct knote *kn);
5682 static int filt_fsevent(struct knote *kn, long hint);
5684 struct filterops fs_filtops = {
5686 .f_attach = filt_fsattach,
5687 .f_detach = filt_fsdetach,
5688 .f_event = filt_fsevent
5692 filt_fsattach(struct knote *kn)
5695 kn->kn_flags |= EV_CLEAR;
5696 knlist_add(&fs_knlist, kn, 0);
5701 filt_fsdetach(struct knote *kn)
5704 knlist_remove(&fs_knlist, kn, 0);
5708 filt_fsevent(struct knote *kn, long hint)
5711 kn->kn_fflags |= hint;
5712 return (kn->kn_fflags != 0);
5716 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
5722 error = SYSCTL_IN(req, &vc, sizeof(vc));
5725 if (vc.vc_vers != VFS_CTL_VERS1)
5727 mp = vfs_getvfs(&vc.vc_fsid);
5730 /* ensure that a specific sysctl goes to the right filesystem. */
5731 if (strcmp(vc.vc_fstypename, "*") != 0 &&
5732 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
5736 VCTLTOREQ(&vc, req);
5737 error = VFS_SYSCTL(mp, vc.vc_op, req);
5742 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
5743 NULL, 0, sysctl_vfs_ctl, "",
5747 * Function to initialize a va_filerev field sensibly.
5748 * XXX: Wouldn't a random number make a lot more sense ??
5751 init_va_filerev(void)
5756 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
5759 static int filt_vfsread(struct knote *kn, long hint);
5760 static int filt_vfswrite(struct knote *kn, long hint);
5761 static int filt_vfsvnode(struct knote *kn, long hint);
5762 static void filt_vfsdetach(struct knote *kn);
5763 static struct filterops vfsread_filtops = {
5765 .f_detach = filt_vfsdetach,
5766 .f_event = filt_vfsread
5768 static struct filterops vfswrite_filtops = {
5770 .f_detach = filt_vfsdetach,
5771 .f_event = filt_vfswrite
5773 static struct filterops vfsvnode_filtops = {
5775 .f_detach = filt_vfsdetach,
5776 .f_event = filt_vfsvnode
5780 vfs_knllock(void *arg)
5782 struct vnode *vp = arg;
5784 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5788 vfs_knlunlock(void *arg)
5790 struct vnode *vp = arg;
5796 vfs_knl_assert_locked(void *arg)
5798 #ifdef DEBUG_VFS_LOCKS
5799 struct vnode *vp = arg;
5801 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
5806 vfs_knl_assert_unlocked(void *arg)
5808 #ifdef DEBUG_VFS_LOCKS
5809 struct vnode *vp = arg;
5811 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
5816 vfs_kqfilter(struct vop_kqfilter_args *ap)
5818 struct vnode *vp = ap->a_vp;
5819 struct knote *kn = ap->a_kn;
5822 switch (kn->kn_filter) {
5824 kn->kn_fop = &vfsread_filtops;
5827 kn->kn_fop = &vfswrite_filtops;
5830 kn->kn_fop = &vfsvnode_filtops;
5836 kn->kn_hook = (caddr_t)vp;
5839 if (vp->v_pollinfo == NULL)
5841 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5843 knlist_add(knl, kn, 0);
5849 * Detach knote from vnode
5852 filt_vfsdetach(struct knote *kn)
5854 struct vnode *vp = (struct vnode *)kn->kn_hook;
5856 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
5857 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
5863 filt_vfsread(struct knote *kn, long hint)
5865 struct vnode *vp = (struct vnode *)kn->kn_hook;
5870 * filesystem is gone, so set the EOF flag and schedule
5871 * the knote for deletion.
5873 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5875 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5880 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
5884 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
5885 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
5892 filt_vfswrite(struct knote *kn, long hint)
5894 struct vnode *vp = (struct vnode *)kn->kn_hook;
5899 * filesystem is gone, so set the EOF flag and schedule
5900 * the knote for deletion.
5902 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
5903 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5911 filt_vfsvnode(struct knote *kn, long hint)
5913 struct vnode *vp = (struct vnode *)kn->kn_hook;
5917 if (kn->kn_sfflags & hint)
5918 kn->kn_fflags |= hint;
5919 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5920 kn->kn_flags |= EV_EOF;
5924 res = (kn->kn_fflags != 0);
5930 * Returns whether the directory is empty or not.
5931 * If it is empty, the return value is 0; otherwise
5932 * the return value is an error value (which may
5936 vfs_emptydir(struct vnode *vp)
5940 struct dirent *dirent, *dp, *endp;
5946 ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
5948 dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
5949 iov.iov_base = dirent;
5950 iov.iov_len = sizeof(struct dirent);
5955 uio.uio_resid = sizeof(struct dirent);
5956 uio.uio_segflg = UIO_SYSSPACE;
5957 uio.uio_rw = UIO_READ;
5958 uio.uio_td = curthread;
5960 while (eof == 0 && error == 0) {
5961 error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
5965 endp = (void *)((uint8_t *)dirent +
5966 sizeof(struct dirent) - uio.uio_resid);
5967 for (dp = dirent; dp < endp;
5968 dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
5969 if (dp->d_type == DT_WHT)
5971 if (dp->d_namlen == 0)
5973 if (dp->d_type != DT_DIR &&
5974 dp->d_type != DT_UNKNOWN) {
5978 if (dp->d_namlen > 2) {
5982 if (dp->d_namlen == 1 &&
5983 dp->d_name[0] != '.') {
5987 if (dp->d_namlen == 2 &&
5988 dp->d_name[1] != '.') {
5992 uio.uio_resid = sizeof(struct dirent);
5995 free(dirent, M_TEMP);
6000 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6004 if (dp->d_reclen > ap->a_uio->uio_resid)
6005 return (ENAMETOOLONG);
6006 error = uiomove(dp, dp->d_reclen, ap->a_uio);
6008 if (ap->a_ncookies != NULL) {
6009 if (ap->a_cookies != NULL)
6010 free(ap->a_cookies, M_TEMP);
6011 ap->a_cookies = NULL;
6012 *ap->a_ncookies = 0;
6016 if (ap->a_ncookies == NULL)
6019 KASSERT(ap->a_cookies,
6020 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6022 *ap->a_cookies = realloc(*ap->a_cookies,
6023 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
6024 (*ap->a_cookies)[*ap->a_ncookies] = off;
6025 *ap->a_ncookies += 1;
6030 * The purpose of this routine is to remove granularity from accmode_t,
6031 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6032 * VADMIN and VAPPEND.
6034 * If it returns 0, the caller is supposed to continue with the usual
6035 * access checks using 'accmode' as modified by this routine. If it
6036 * returns nonzero value, the caller is supposed to return that value
6039 * Note that after this routine runs, accmode may be zero.
6042 vfs_unixify_accmode(accmode_t *accmode)
6045 * There is no way to specify explicit "deny" rule using
6046 * file mode or POSIX.1e ACLs.
6048 if (*accmode & VEXPLICIT_DENY) {
6054 * None of these can be translated into usual access bits.
6055 * Also, the common case for NFSv4 ACLs is to not contain
6056 * either of these bits. Caller should check for VWRITE
6057 * on the containing directory instead.
6059 if (*accmode & (VDELETE_CHILD | VDELETE))
6062 if (*accmode & VADMIN_PERMS) {
6063 *accmode &= ~VADMIN_PERMS;
6068 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6069 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6071 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6077 * Clear out a doomed vnode (if any) and replace it with a new one as long
6078 * as the fs is not being unmounted. Return the root vnode to the caller.
6080 static int __noinline
6081 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6087 if (mp->mnt_rootvnode != NULL) {
6089 vp = mp->mnt_rootvnode;
6091 if (!VN_IS_DOOMED(vp)) {
6094 error = vn_lock(vp, flags);
6103 * Clear the old one.
6105 mp->mnt_rootvnode = NULL;
6109 vfs_op_barrier_wait(mp);
6113 error = VFS_CACHEDROOT(mp, flags, vpp);
6116 if (mp->mnt_vfs_ops == 0) {
6118 if (mp->mnt_vfs_ops != 0) {
6122 if (mp->mnt_rootvnode == NULL) {
6124 mp->mnt_rootvnode = *vpp;
6126 if (mp->mnt_rootvnode != *vpp) {
6127 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6128 panic("%s: mismatch between vnode returned "
6129 " by VFS_CACHEDROOT and the one cached "
6131 __func__, *vpp, mp->mnt_rootvnode);
6141 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6146 if (!vfs_op_thread_enter(mp))
6147 return (vfs_cache_root_fallback(mp, flags, vpp));
6148 vp = atomic_load_ptr(&mp->mnt_rootvnode);
6149 if (vp == NULL || VN_IS_DOOMED(vp)) {
6150 vfs_op_thread_exit(mp);
6151 return (vfs_cache_root_fallback(mp, flags, vpp));
6154 vfs_op_thread_exit(mp);
6155 error = vn_lock(vp, flags);
6158 return (vfs_cache_root_fallback(mp, flags, vpp));
6165 vfs_cache_root_clear(struct mount *mp)
6170 * ops > 0 guarantees there is nobody who can see this vnode
6172 MPASS(mp->mnt_vfs_ops > 0);
6173 vp = mp->mnt_rootvnode;
6174 mp->mnt_rootvnode = NULL;
6179 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6182 MPASS(mp->mnt_vfs_ops > 0);
6184 mp->mnt_rootvnode = vp;
6188 * These are helper functions for filesystems to traverse all
6189 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6191 * This interface replaces MNT_VNODE_FOREACH.
6195 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6200 kern_yield(PRI_USER);
6202 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6203 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6204 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6205 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6206 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6209 if (VN_IS_DOOMED(vp)) {
6216 __mnt_vnode_markerfree_all(mvp, mp);
6217 /* MNT_IUNLOCK(mp); -- done in above function */
6218 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6221 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6222 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6228 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6232 *mvp = vn_alloc_marker(mp);
6236 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6237 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6238 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6241 if (VN_IS_DOOMED(vp)) {
6250 vn_free_marker(*mvp);
6254 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6260 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6268 mtx_assert(MNT_MTX(mp), MA_OWNED);
6270 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6271 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6274 vn_free_marker(*mvp);
6279 * These are helper functions for filesystems to traverse their
6280 * lazy vnodes. See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6283 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6286 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6291 vn_free_marker(*mvp);
6296 * Relock the mp mount vnode list lock with the vp vnode interlock in the
6297 * conventional lock order during mnt_vnode_next_lazy iteration.
6299 * On entry, the mount vnode list lock is held and the vnode interlock is not.
6300 * The list lock is dropped and reacquired. On success, both locks are held.
6301 * On failure, the mount vnode list lock is held but the vnode interlock is
6302 * not, and the procedure may have yielded.
6305 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6309 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6310 TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6311 ("%s: bad marker", __func__));
6312 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6313 ("%s: inappropriate vnode", __func__));
6314 ASSERT_VI_UNLOCKED(vp, __func__);
6315 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6317 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6318 TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6321 * Note we may be racing against vdrop which transitioned the hold
6322 * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
6323 * if we are the only user after we get the interlock we will just
6327 mtx_unlock(&mp->mnt_listmtx);
6329 if (VN_IS_DOOMED(vp)) {
6330 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
6333 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
6335 * There is nothing to do if we are the last user.
6337 if (!refcount_release_if_not_last(&vp->v_holdcnt))
6339 mtx_lock(&mp->mnt_listmtx);
6344 mtx_lock(&mp->mnt_listmtx);
6348 static struct vnode *
6349 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6354 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6355 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6357 vp = TAILQ_NEXT(*mvp, v_lazylist);
6358 while (vp != NULL) {
6359 if (vp->v_type == VMARKER) {
6360 vp = TAILQ_NEXT(vp, v_lazylist);
6364 * See if we want to process the vnode. Note we may encounter a
6365 * long string of vnodes we don't care about and hog the list
6366 * as a result. Check for it and requeue the marker.
6368 VNPASS(!VN_IS_DOOMED(vp), vp);
6369 if (!cb(vp, cbarg)) {
6370 if (!should_yield()) {
6371 vp = TAILQ_NEXT(vp, v_lazylist);
6374 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6376 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6378 mtx_unlock(&mp->mnt_listmtx);
6379 kern_yield(PRI_USER);
6380 mtx_lock(&mp->mnt_listmtx);
6384 * Try-lock because this is the wrong lock order.
6386 if (!VI_TRYLOCK(vp) &&
6387 !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6389 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6390 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6391 ("alien vnode on the lazy list %p %p", vp, mp));
6392 VNPASS(vp->v_mount == mp, vp);
6393 VNPASS(!VN_IS_DOOMED(vp), vp);
6396 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6398 /* Check if we are done */
6400 mtx_unlock(&mp->mnt_listmtx);
6401 mnt_vnode_markerfree_lazy(mvp, mp);
6404 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6405 mtx_unlock(&mp->mnt_listmtx);
6406 ASSERT_VI_LOCKED(vp, "lazy iter");
6411 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6416 kern_yield(PRI_USER);
6417 mtx_lock(&mp->mnt_listmtx);
6418 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6422 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6427 if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
6430 *mvp = vn_alloc_marker(mp);
6435 mtx_lock(&mp->mnt_listmtx);
6436 vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6438 mtx_unlock(&mp->mnt_listmtx);
6439 mnt_vnode_markerfree_lazy(mvp, mp);
6442 TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6443 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6447 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6453 mtx_lock(&mp->mnt_listmtx);
6454 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6455 mtx_unlock(&mp->mnt_listmtx);
6456 mnt_vnode_markerfree_lazy(mvp, mp);
6460 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
6463 if ((cnp->cn_flags & NOEXECCHECK) != 0) {
6464 cnp->cn_flags &= ~NOEXECCHECK;
6468 return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, cnp->cn_thread));