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;
1106 mtx_assert(&vnode_list_mtx, MA_OWNED);
1111 mvp = vnode_list_reclaim_marker;
1114 while (done < target) {
1115 vp = TAILQ_NEXT(vp, v_vnodelist);
1116 if (__predict_false(vp == NULL))
1119 if (__predict_false(vp->v_type == VMARKER))
1123 * If it's been deconstructed already, it's still
1124 * referenced, or it exceeds the trigger, skip it.
1125 * Also skip free vnodes. We are trying to make space
1126 * to expand the free list, not reduce it.
1128 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1129 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)))
1132 if (vp->v_type == VBAD || vp->v_type == VNON)
1135 if (!VI_TRYLOCK(vp))
1138 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1139 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1140 vp->v_type == VBAD || vp->v_type == VNON ||
1141 (vp->v_object != NULL &&
1142 vp->v_object->resident_page_count > trigger)) {
1148 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1149 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1150 mtx_unlock(&vnode_list_mtx);
1152 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1154 goto next_iter_unlocked;
1156 if (VOP_LOCK(vp, LK_EXCLUSIVE|LK_NOWAIT) != 0) {
1158 vn_finished_write(mp);
1159 goto next_iter_unlocked;
1163 if (vp->v_usecount > 0 ||
1164 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1165 (vp->v_object != NULL &&
1166 vp->v_object->resident_page_count > trigger)) {
1169 vn_finished_write(mp);
1170 goto next_iter_unlocked;
1172 counter_u64_add(recycles_count, 1);
1176 vn_finished_write(mp);
1180 kern_yield(PRI_USER);
1181 mtx_lock(&vnode_list_mtx);
1184 MPASS(vp->v_type != VMARKER);
1185 if (!should_yield())
1187 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1188 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1189 mtx_unlock(&vnode_list_mtx);
1190 kern_yield(PRI_USER);
1191 mtx_lock(&vnode_list_mtx);
1194 if (done == 0 && !retried) {
1195 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1196 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1203 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1204 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1206 "limit on vnode free requests per call to the vnlru_free routine");
1209 * Attempt to reduce the free list by the requested amount.
1212 vnlru_free_locked(int count, struct vfsops *mnt_op)
1214 struct vnode *vp, *mvp;
1218 mtx_assert(&vnode_list_mtx, MA_OWNED);
1219 if (count > max_vnlru_free)
1220 count = max_vnlru_free;
1222 mvp = vnode_list_free_marker;
1226 vp = TAILQ_NEXT(vp, v_vnodelist);
1227 if (__predict_false(vp == NULL)) {
1228 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1229 TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1232 if (__predict_false(vp->v_type == VMARKER))
1236 * Don't recycle if our vnode is from different type
1237 * of mount point. Note that mp is type-safe, the
1238 * check does not reach unmapped address even if
1239 * vnode is reclaimed.
1240 * Don't recycle if we can't get the interlock without
1243 if (vp->v_holdcnt > 0 || (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1244 mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
1247 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1248 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1249 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1255 mtx_unlock(&vnode_list_mtx);
1259 mtx_lock(&vnode_list_mtx);
1262 return (ocount - count);
1266 vnlru_free(int count, struct vfsops *mnt_op)
1269 mtx_lock(&vnode_list_mtx);
1270 vnlru_free_locked(count, mnt_op);
1271 mtx_unlock(&vnode_list_mtx);
1278 mtx_assert(&vnode_list_mtx, MA_OWNED);
1279 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1280 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1281 vlowat = vhiwat / 2;
1285 * Attempt to recycle vnodes in a context that is always safe to block.
1286 * Calling vlrurecycle() from the bowels of filesystem code has some
1287 * interesting deadlock problems.
1289 static struct proc *vnlruproc;
1290 static int vnlruproc_sig;
1293 * The main freevnodes counter is only updated when threads requeue their vnode
1294 * batches. CPUs are conditionally walked to compute a more accurate total.
1296 * Limit how much of a slop are we willing to tolerate. Note: the actual value
1297 * at any given moment can still exceed slop, but it should not be by significant
1298 * margin in practice.
1300 #define VNLRU_FREEVNODES_SLOP 128
1303 vnlru_read_freevnodes(void)
1309 mtx_assert(&vnode_list_mtx, MA_OWNED);
1310 if (freevnodes > freevnodes_old)
1311 slop = freevnodes - freevnodes_old;
1313 slop = freevnodes_old - freevnodes;
1314 if (slop < VNLRU_FREEVNODES_SLOP)
1315 return (freevnodes >= 0 ? freevnodes : 0);
1316 freevnodes_old = freevnodes;
1318 vd = DPCPU_ID_PTR((cpu), vd);
1319 freevnodes_old += vd->freevnodes;
1321 return (freevnodes_old >= 0 ? freevnodes_old : 0);
1325 vnlru_under(u_long rnumvnodes, u_long limit)
1327 u_long rfreevnodes, space;
1329 if (__predict_false(rnumvnodes > desiredvnodes))
1332 space = desiredvnodes - rnumvnodes;
1333 if (space < limit) {
1334 rfreevnodes = vnlru_read_freevnodes();
1335 if (rfreevnodes > wantfreevnodes)
1336 space += rfreevnodes - wantfreevnodes;
1338 return (space < limit);
1342 vnlru_under_unlocked(u_long rnumvnodes, u_long limit)
1344 long rfreevnodes, space;
1346 if (__predict_false(rnumvnodes > desiredvnodes))
1349 space = desiredvnodes - rnumvnodes;
1350 if (space < limit) {
1351 rfreevnodes = atomic_load_long(&freevnodes);
1352 if (rfreevnodes > wantfreevnodes)
1353 space += rfreevnodes - wantfreevnodes;
1355 return (space < limit);
1362 mtx_assert(&vnode_list_mtx, MA_OWNED);
1363 if (vnlruproc_sig == 0) {
1372 u_long rnumvnodes, rfreevnodes, target;
1373 unsigned long onumvnodes;
1374 int done, force, trigger, usevnodes;
1375 bool reclaim_nc_src, want_reread;
1377 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1378 SHUTDOWN_PRI_FIRST);
1381 want_reread = false;
1383 kproc_suspend_check(vnlruproc);
1384 mtx_lock(&vnode_list_mtx);
1385 rnumvnodes = atomic_load_long(&numvnodes);
1388 force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1389 want_reread = false;
1393 * If numvnodes is too large (due to desiredvnodes being
1394 * adjusted using its sysctl, or emergency growth), first
1395 * try to reduce it by discarding from the free list.
1397 if (rnumvnodes > desiredvnodes) {
1398 vnlru_free_locked(rnumvnodes - desiredvnodes, NULL);
1399 rnumvnodes = atomic_load_long(&numvnodes);
1402 * Sleep if the vnode cache is in a good state. This is
1403 * when it is not over-full and has space for about a 4%
1404 * or 9% expansion (by growing its size or inexcessively
1405 * reducing its free list). Otherwise, try to reclaim
1406 * space for a 10% expansion.
1408 if (vstir && force == 0) {
1412 if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1414 wakeup(&vnlruproc_sig);
1415 msleep(vnlruproc, &vnode_list_mtx,
1416 PVFS|PDROP, "vlruwt", hz);
1419 rfreevnodes = vnlru_read_freevnodes();
1421 onumvnodes = rnumvnodes;
1423 * Calculate parameters for recycling. These are the same
1424 * throughout the loop to give some semblance of fairness.
1425 * The trigger point is to avoid recycling vnodes with lots
1426 * of resident pages. We aren't trying to free memory; we
1427 * are trying to recycle or at least free vnodes.
1429 if (rnumvnodes <= desiredvnodes)
1430 usevnodes = rnumvnodes - rfreevnodes;
1432 usevnodes = rnumvnodes;
1436 * The trigger value is is chosen to give a conservatively
1437 * large value to ensure that it alone doesn't prevent
1438 * making progress. The value can easily be so large that
1439 * it is effectively infinite in some congested and
1440 * misconfigured cases, and this is necessary. Normally
1441 * it is about 8 to 100 (pages), which is quite large.
1443 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1445 trigger = vsmalltrigger;
1446 reclaim_nc_src = force >= 3;
1447 target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1448 target = target / 10 + 1;
1449 done = vlrureclaim(reclaim_nc_src, trigger, target);
1450 mtx_unlock(&vnode_list_mtx);
1451 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1452 uma_reclaim(UMA_RECLAIM_DRAIN);
1454 if (force == 0 || force == 1) {
1465 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1468 kern_yield(PRI_USER);
1473 static struct kproc_desc vnlru_kp = {
1478 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1482 * Routines having to do with the management of the vnode table.
1486 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1487 * before we actually vgone(). This function must be called with the vnode
1488 * held to prevent the vnode from being returned to the free list midway
1492 vtryrecycle(struct vnode *vp)
1496 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1497 VNASSERT(vp->v_holdcnt, vp,
1498 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1500 * This vnode may found and locked via some other list, if so we
1501 * can't recycle it yet.
1503 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1505 "%s: impossible to recycle, vp %p lock is already held",
1507 return (EWOULDBLOCK);
1510 * Don't recycle if its filesystem is being suspended.
1512 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1515 "%s: impossible to recycle, cannot start the write for %p",
1520 * If we got this far, we need to acquire the interlock and see if
1521 * anyone picked up this vnode from another list. If not, we will
1522 * mark it with DOOMED via vgonel() so that anyone who does find it
1523 * will skip over it.
1526 if (vp->v_usecount) {
1529 vn_finished_write(vnmp);
1531 "%s: impossible to recycle, %p is already referenced",
1535 if (!VN_IS_DOOMED(vp)) {
1536 counter_u64_add(recycles_free_count, 1);
1541 vn_finished_write(vnmp);
1546 * Allocate a new vnode.
1548 * The operation never returns an error. Returning an error was disabled
1549 * in r145385 (dated 2005) with the following comment:
1551 * XXX Not all VFS_VGET/ffs_vget callers check returns.
1553 * Given the age of this commit (almost 15 years at the time of writing this
1554 * comment) restoring the ability to fail requires a significant audit of
1557 * The routine can try to free a vnode or stall for up to 1 second waiting for
1558 * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1560 static u_long vn_alloc_cyclecount;
1562 static struct vnode * __noinline
1563 vn_alloc_hard(struct mount *mp)
1565 u_long rnumvnodes, rfreevnodes;
1567 mtx_lock(&vnode_list_mtx);
1568 rnumvnodes = atomic_load_long(&numvnodes);
1569 if (rnumvnodes + 1 < desiredvnodes) {
1570 vn_alloc_cyclecount = 0;
1573 rfreevnodes = vnlru_read_freevnodes();
1574 if (vn_alloc_cyclecount++ >= rfreevnodes) {
1575 vn_alloc_cyclecount = 0;
1579 * Grow the vnode cache if it will not be above its target max
1580 * after growing. Otherwise, if the free list is nonempty, try
1581 * to reclaim 1 item from it before growing the cache (possibly
1582 * above its target max if the reclamation failed or is delayed).
1583 * Otherwise, wait for some space. In all cases, schedule
1584 * vnlru_proc() if we are getting short of space. The watermarks
1585 * should be chosen so that we never wait or even reclaim from
1586 * the free list to below its target minimum.
1588 if (vnlru_free_locked(1, NULL) > 0)
1590 if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1592 * Wait for space for a new vnode.
1595 msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1596 if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1597 vnlru_read_freevnodes() > 1)
1598 vnlru_free_locked(1, NULL);
1601 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1602 if (vnlru_under(rnumvnodes, vlowat))
1604 mtx_unlock(&vnode_list_mtx);
1605 return (uma_zalloc(vnode_zone, M_WAITOK));
1608 static struct vnode *
1609 vn_alloc(struct mount *mp)
1613 if (__predict_false(vn_alloc_cyclecount != 0))
1614 return (vn_alloc_hard(mp));
1615 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1616 if (__predict_false(vnlru_under_unlocked(rnumvnodes, vlowat))) {
1617 atomic_subtract_long(&numvnodes, 1);
1618 return (vn_alloc_hard(mp));
1621 return (uma_zalloc(vnode_zone, M_WAITOK));
1625 vn_free(struct vnode *vp)
1628 atomic_subtract_long(&numvnodes, 1);
1629 uma_zfree(vnode_zone, vp);
1633 * Return the next vnode from the free list.
1636 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1641 struct lock_object *lo;
1643 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1645 KASSERT(vops->registered,
1646 ("%s: not registered vector op %p\n", __func__, vops));
1649 if (td->td_vp_reserved != NULL) {
1650 vp = td->td_vp_reserved;
1651 td->td_vp_reserved = NULL;
1655 counter_u64_add(vnodes_created, 1);
1657 * Locks are given the generic name "vnode" when created.
1658 * Follow the historic practice of using the filesystem
1659 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1661 * Locks live in a witness group keyed on their name. Thus,
1662 * when a lock is renamed, it must also move from the witness
1663 * group of its old name to the witness group of its new name.
1665 * The change only needs to be made when the vnode moves
1666 * from one filesystem type to another. We ensure that each
1667 * filesystem use a single static name pointer for its tag so
1668 * that we can compare pointers rather than doing a strcmp().
1670 lo = &vp->v_vnlock->lock_object;
1672 if (lo->lo_name != tag) {
1676 WITNESS_DESTROY(lo);
1677 WITNESS_INIT(lo, tag);
1681 * By default, don't allow shared locks unless filesystems opt-in.
1683 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1685 * Finalize various vnode identity bits.
1687 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1688 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1689 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1692 v_init_counters(vp);
1693 vp->v_bufobj.bo_ops = &buf_ops_bio;
1695 if (mp == NULL && vops != &dead_vnodeops)
1696 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1700 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1701 mac_vnode_associate_singlelabel(mp, vp);
1704 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1705 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1706 vp->v_vflag |= VV_NOKNOTE;
1710 * For the filesystems which do not use vfs_hash_insert(),
1711 * still initialize v_hash to have vfs_hash_index() useful.
1712 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1715 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1722 getnewvnode_reserve(void)
1727 MPASS(td->td_vp_reserved == NULL);
1728 td->td_vp_reserved = vn_alloc(NULL);
1732 getnewvnode_drop_reserve(void)
1737 if (td->td_vp_reserved != NULL) {
1738 vn_free(td->td_vp_reserved);
1739 td->td_vp_reserved = NULL;
1744 freevnode(struct vnode *vp)
1749 * The vnode has been marked for destruction, so free it.
1751 * The vnode will be returned to the zone where it will
1752 * normally remain until it is needed for another vnode. We
1753 * need to cleanup (or verify that the cleanup has already
1754 * been done) any residual data left from its current use
1755 * so as not to contaminate the freshly allocated vnode.
1757 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1759 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1760 VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
1761 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1762 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1763 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1764 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1765 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1766 ("clean blk trie not empty"));
1767 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1768 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1769 ("dirty blk trie not empty"));
1770 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1771 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1772 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1773 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1774 ("Dangling rangelock waiters"));
1777 mac_vnode_destroy(vp);
1779 if (vp->v_pollinfo != NULL) {
1780 destroy_vpollinfo(vp->v_pollinfo);
1781 vp->v_pollinfo = NULL;
1784 /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
1787 vp->v_mountedhere = NULL;
1790 vp->v_fifoinfo = NULL;
1791 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
1800 * Delete from old mount point vnode list, if on one.
1803 delmntque(struct vnode *vp)
1807 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
1816 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1817 ("bad mount point vnode list size"));
1818 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1819 mp->mnt_nvnodelistsize--;
1825 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1829 vp->v_op = &dead_vnodeops;
1835 * Insert into list of vnodes for the new mount point, if available.
1838 insmntque1(struct vnode *vp, struct mount *mp,
1839 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1842 KASSERT(vp->v_mount == NULL,
1843 ("insmntque: vnode already on per mount vnode list"));
1844 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1845 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1848 * We acquire the vnode interlock early to ensure that the
1849 * vnode cannot be recycled by another process releasing a
1850 * holdcnt on it before we get it on both the vnode list
1851 * and the active vnode list. The mount mutex protects only
1852 * manipulation of the vnode list and the vnode freelist
1853 * mutex protects only manipulation of the active vnode list.
1854 * Hence the need to hold the vnode interlock throughout.
1858 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1859 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1860 mp->mnt_nvnodelistsize == 0)) &&
1861 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1870 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1871 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1872 ("neg mount point vnode list size"));
1873 mp->mnt_nvnodelistsize++;
1880 insmntque(struct vnode *vp, struct mount *mp)
1883 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1887 * Flush out and invalidate all buffers associated with a bufobj
1888 * Called with the underlying object locked.
1891 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1896 if (flags & V_SAVE) {
1897 error = bufobj_wwait(bo, slpflag, slptimeo);
1902 if (bo->bo_dirty.bv_cnt > 0) {
1904 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1907 * XXX We could save a lock/unlock if this was only
1908 * enabled under INVARIANTS
1911 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1912 panic("vinvalbuf: dirty bufs");
1916 * If you alter this loop please notice that interlock is dropped and
1917 * reacquired in flushbuflist. Special care is needed to ensure that
1918 * no race conditions occur from this.
1921 error = flushbuflist(&bo->bo_clean,
1922 flags, bo, slpflag, slptimeo);
1923 if (error == 0 && !(flags & V_CLEANONLY))
1924 error = flushbuflist(&bo->bo_dirty,
1925 flags, bo, slpflag, slptimeo);
1926 if (error != 0 && error != EAGAIN) {
1930 } while (error != 0);
1933 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1934 * have write I/O in-progress but if there is a VM object then the
1935 * VM object can also have read-I/O in-progress.
1938 bufobj_wwait(bo, 0, 0);
1939 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
1941 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
1944 } while (bo->bo_numoutput > 0);
1948 * Destroy the copy in the VM cache, too.
1950 if (bo->bo_object != NULL &&
1951 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1952 VM_OBJECT_WLOCK(bo->bo_object);
1953 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1954 OBJPR_CLEANONLY : 0);
1955 VM_OBJECT_WUNLOCK(bo->bo_object);
1960 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1961 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1962 bo->bo_clean.bv_cnt > 0))
1963 panic("vinvalbuf: flush failed");
1964 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1965 bo->bo_dirty.bv_cnt > 0)
1966 panic("vinvalbuf: flush dirty failed");
1973 * Flush out and invalidate all buffers associated with a vnode.
1974 * Called with the underlying object locked.
1977 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1980 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1981 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1982 if (vp->v_object != NULL && vp->v_object->handle != vp)
1984 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1988 * Flush out buffers on the specified list.
1992 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1995 struct buf *bp, *nbp;
2000 ASSERT_BO_WLOCKED(bo);
2003 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2005 * If we are flushing both V_NORMAL and V_ALT buffers then
2006 * do not skip any buffers. If we are flushing only V_NORMAL
2007 * buffers then skip buffers marked as BX_ALTDATA. If we are
2008 * flushing only V_ALT buffers then skip buffers not marked
2011 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2012 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2013 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2017 lblkno = nbp->b_lblkno;
2018 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2021 error = BUF_TIMELOCK(bp,
2022 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2023 "flushbuf", slpflag, slptimeo);
2026 return (error != ENOLCK ? error : EAGAIN);
2028 KASSERT(bp->b_bufobj == bo,
2029 ("bp %p wrong b_bufobj %p should be %p",
2030 bp, bp->b_bufobj, bo));
2032 * XXX Since there are no node locks for NFS, I
2033 * believe there is a slight chance that a delayed
2034 * write will occur while sleeping just above, so
2037 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2040 bp->b_flags |= B_ASYNC;
2043 return (EAGAIN); /* XXX: why not loop ? */
2046 bp->b_flags |= (B_INVAL | B_RELBUF);
2047 bp->b_flags &= ~B_ASYNC;
2052 nbp = gbincore(bo, lblkno);
2053 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2055 break; /* nbp invalid */
2061 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2067 ASSERT_BO_LOCKED(bo);
2069 for (lblkno = startn;;) {
2071 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2072 if (bp == NULL || bp->b_lblkno >= endn ||
2073 bp->b_lblkno < startn)
2075 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2076 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2079 if (error == ENOLCK)
2083 KASSERT(bp->b_bufobj == bo,
2084 ("bp %p wrong b_bufobj %p should be %p",
2085 bp, bp->b_bufobj, bo));
2086 lblkno = bp->b_lblkno + 1;
2087 if ((bp->b_flags & B_MANAGED) == 0)
2089 bp->b_flags |= B_RELBUF;
2091 * In the VMIO case, use the B_NOREUSE flag to hint that the
2092 * pages backing each buffer in the range are unlikely to be
2093 * reused. Dirty buffers will have the hint applied once
2094 * they've been written.
2096 if ((bp->b_flags & B_VMIO) != 0)
2097 bp->b_flags |= B_NOREUSE;
2105 * Truncate a file's buffer and pages to a specified length. This
2106 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2110 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2112 struct buf *bp, *nbp;
2116 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2117 vp, blksize, (uintmax_t)length);
2120 * Round up to the *next* lbn.
2122 startlbn = howmany(length, blksize);
2124 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2130 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2135 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2136 if (bp->b_lblkno > 0)
2139 * Since we hold the vnode lock this should only
2140 * fail if we're racing with the buf daemon.
2143 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2144 BO_LOCKPTR(bo)) == ENOLCK)
2145 goto restart_unlocked;
2147 VNASSERT((bp->b_flags & B_DELWRI), vp,
2148 ("buf(%p) on dirty queue without DELWRI", bp));
2157 bufobj_wwait(bo, 0, 0);
2159 vnode_pager_setsize(vp, length);
2165 * Invalidate the cached pages of a file's buffer within the range of block
2166 * numbers [startlbn, endlbn).
2169 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2175 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2177 start = blksize * startlbn;
2178 end = blksize * endlbn;
2182 MPASS(blksize == bo->bo_bsize);
2184 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2188 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2192 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2193 daddr_t startlbn, daddr_t endlbn)
2195 struct buf *bp, *nbp;
2198 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2199 ASSERT_BO_LOCKED(bo);
2203 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2204 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2207 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2208 BO_LOCKPTR(bo)) == ENOLCK) {
2214 bp->b_flags |= B_INVAL | B_RELBUF;
2215 bp->b_flags &= ~B_ASYNC;
2221 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2223 (nbp->b_flags & B_DELWRI) != 0))
2227 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2228 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2231 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2232 BO_LOCKPTR(bo)) == ENOLCK) {
2237 bp->b_flags |= B_INVAL | B_RELBUF;
2238 bp->b_flags &= ~B_ASYNC;
2244 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2245 (nbp->b_vp != vp) ||
2246 (nbp->b_flags & B_DELWRI) == 0))
2254 buf_vlist_remove(struct buf *bp)
2258 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2259 ASSERT_BO_WLOCKED(bp->b_bufobj);
2260 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
2261 (BX_VNDIRTY|BX_VNCLEAN),
2262 ("buf_vlist_remove: Buf %p is on two lists", bp));
2263 if (bp->b_xflags & BX_VNDIRTY)
2264 bv = &bp->b_bufobj->bo_dirty;
2266 bv = &bp->b_bufobj->bo_clean;
2267 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2268 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2270 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2274 * Add the buffer to the sorted clean or dirty block list.
2276 * NOTE: xflags is passed as a constant, optimizing this inline function!
2279 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2285 ASSERT_BO_WLOCKED(bo);
2286 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2287 ("dead bo %p", bo));
2288 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2289 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2290 bp->b_xflags |= xflags;
2291 if (xflags & BX_VNDIRTY)
2297 * Keep the list ordered. Optimize empty list insertion. Assume
2298 * we tend to grow at the tail so lookup_le should usually be cheaper
2301 if (bv->bv_cnt == 0 ||
2302 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2303 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2304 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2305 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2307 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2308 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2310 panic("buf_vlist_add: Preallocated nodes insufficient.");
2315 * Look up a buffer using the buffer tries.
2318 gbincore(struct bufobj *bo, daddr_t lblkno)
2322 ASSERT_BO_LOCKED(bo);
2323 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2326 return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
2330 * Associate a buffer with a vnode.
2333 bgetvp(struct vnode *vp, struct buf *bp)
2338 ASSERT_BO_WLOCKED(bo);
2339 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2341 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2342 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2343 ("bgetvp: bp already attached! %p", bp));
2349 * Insert onto list for new vnode.
2351 buf_vlist_add(bp, bo, BX_VNCLEAN);
2355 * Disassociate a buffer from a vnode.
2358 brelvp(struct buf *bp)
2363 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2364 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2367 * Delete from old vnode list, if on one.
2369 vp = bp->b_vp; /* XXX */
2372 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2373 buf_vlist_remove(bp);
2375 panic("brelvp: Buffer %p not on queue.", bp);
2376 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2377 bo->bo_flag &= ~BO_ONWORKLST;
2378 mtx_lock(&sync_mtx);
2379 LIST_REMOVE(bo, bo_synclist);
2380 syncer_worklist_len--;
2381 mtx_unlock(&sync_mtx);
2384 bp->b_bufobj = NULL;
2390 * Add an item to the syncer work queue.
2393 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2397 ASSERT_BO_WLOCKED(bo);
2399 mtx_lock(&sync_mtx);
2400 if (bo->bo_flag & BO_ONWORKLST)
2401 LIST_REMOVE(bo, bo_synclist);
2403 bo->bo_flag |= BO_ONWORKLST;
2404 syncer_worklist_len++;
2407 if (delay > syncer_maxdelay - 2)
2408 delay = syncer_maxdelay - 2;
2409 slot = (syncer_delayno + delay) & syncer_mask;
2411 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2412 mtx_unlock(&sync_mtx);
2416 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2420 mtx_lock(&sync_mtx);
2421 len = syncer_worklist_len - sync_vnode_count;
2422 mtx_unlock(&sync_mtx);
2423 error = SYSCTL_OUT(req, &len, sizeof(len));
2427 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2428 CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2429 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2431 static struct proc *updateproc;
2432 static void sched_sync(void);
2433 static struct kproc_desc up_kp = {
2438 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2441 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2446 *bo = LIST_FIRST(slp);
2450 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2453 * We use vhold in case the vnode does not
2454 * successfully sync. vhold prevents the vnode from
2455 * going away when we unlock the sync_mtx so that
2456 * we can acquire the vnode interlock.
2459 mtx_unlock(&sync_mtx);
2461 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2463 mtx_lock(&sync_mtx);
2464 return (*bo == LIST_FIRST(slp));
2466 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2467 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2469 vn_finished_write(mp);
2471 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2473 * Put us back on the worklist. The worklist
2474 * routine will remove us from our current
2475 * position and then add us back in at a later
2478 vn_syncer_add_to_worklist(*bo, syncdelay);
2482 mtx_lock(&sync_mtx);
2486 static int first_printf = 1;
2489 * System filesystem synchronizer daemon.
2494 struct synclist *next, *slp;
2497 struct thread *td = curthread;
2499 int net_worklist_len;
2500 int syncer_final_iter;
2504 syncer_final_iter = 0;
2505 syncer_state = SYNCER_RUNNING;
2506 starttime = time_uptime;
2507 td->td_pflags |= TDP_NORUNNINGBUF;
2509 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2512 mtx_lock(&sync_mtx);
2514 if (syncer_state == SYNCER_FINAL_DELAY &&
2515 syncer_final_iter == 0) {
2516 mtx_unlock(&sync_mtx);
2517 kproc_suspend_check(td->td_proc);
2518 mtx_lock(&sync_mtx);
2520 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2521 if (syncer_state != SYNCER_RUNNING &&
2522 starttime != time_uptime) {
2524 printf("\nSyncing disks, vnodes remaining... ");
2527 printf("%d ", net_worklist_len);
2529 starttime = time_uptime;
2532 * Push files whose dirty time has expired. Be careful
2533 * of interrupt race on slp queue.
2535 * Skip over empty worklist slots when shutting down.
2538 slp = &syncer_workitem_pending[syncer_delayno];
2539 syncer_delayno += 1;
2540 if (syncer_delayno == syncer_maxdelay)
2542 next = &syncer_workitem_pending[syncer_delayno];
2544 * If the worklist has wrapped since the
2545 * it was emptied of all but syncer vnodes,
2546 * switch to the FINAL_DELAY state and run
2547 * for one more second.
2549 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2550 net_worklist_len == 0 &&
2551 last_work_seen == syncer_delayno) {
2552 syncer_state = SYNCER_FINAL_DELAY;
2553 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2555 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2556 syncer_worklist_len > 0);
2559 * Keep track of the last time there was anything
2560 * on the worklist other than syncer vnodes.
2561 * Return to the SHUTTING_DOWN state if any
2564 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2565 last_work_seen = syncer_delayno;
2566 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2567 syncer_state = SYNCER_SHUTTING_DOWN;
2568 while (!LIST_EMPTY(slp)) {
2569 error = sync_vnode(slp, &bo, td);
2571 LIST_REMOVE(bo, bo_synclist);
2572 LIST_INSERT_HEAD(next, bo, bo_synclist);
2576 if (first_printf == 0) {
2578 * Drop the sync mutex, because some watchdog
2579 * drivers need to sleep while patting
2581 mtx_unlock(&sync_mtx);
2582 wdog_kern_pat(WD_LASTVAL);
2583 mtx_lock(&sync_mtx);
2587 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2588 syncer_final_iter--;
2590 * The variable rushjob allows the kernel to speed up the
2591 * processing of the filesystem syncer process. A rushjob
2592 * value of N tells the filesystem syncer to process the next
2593 * N seconds worth of work on its queue ASAP. Currently rushjob
2594 * is used by the soft update code to speed up the filesystem
2595 * syncer process when the incore state is getting so far
2596 * ahead of the disk that the kernel memory pool is being
2597 * threatened with exhaustion.
2604 * Just sleep for a short period of time between
2605 * iterations when shutting down to allow some I/O
2608 * If it has taken us less than a second to process the
2609 * current work, then wait. Otherwise start right over
2610 * again. We can still lose time if any single round
2611 * takes more than two seconds, but it does not really
2612 * matter as we are just trying to generally pace the
2613 * filesystem activity.
2615 if (syncer_state != SYNCER_RUNNING ||
2616 time_uptime == starttime) {
2618 sched_prio(td, PPAUSE);
2621 if (syncer_state != SYNCER_RUNNING)
2622 cv_timedwait(&sync_wakeup, &sync_mtx,
2623 hz / SYNCER_SHUTDOWN_SPEEDUP);
2624 else if (time_uptime == starttime)
2625 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2630 * Request the syncer daemon to speed up its work.
2631 * We never push it to speed up more than half of its
2632 * normal turn time, otherwise it could take over the cpu.
2635 speedup_syncer(void)
2639 mtx_lock(&sync_mtx);
2640 if (rushjob < syncdelay / 2) {
2642 stat_rush_requests += 1;
2645 mtx_unlock(&sync_mtx);
2646 cv_broadcast(&sync_wakeup);
2651 * Tell the syncer to speed up its work and run though its work
2652 * list several times, then tell it to shut down.
2655 syncer_shutdown(void *arg, int howto)
2658 if (howto & RB_NOSYNC)
2660 mtx_lock(&sync_mtx);
2661 syncer_state = SYNCER_SHUTTING_DOWN;
2663 mtx_unlock(&sync_mtx);
2664 cv_broadcast(&sync_wakeup);
2665 kproc_shutdown(arg, howto);
2669 syncer_suspend(void)
2672 syncer_shutdown(updateproc, 0);
2679 mtx_lock(&sync_mtx);
2681 syncer_state = SYNCER_RUNNING;
2682 mtx_unlock(&sync_mtx);
2683 cv_broadcast(&sync_wakeup);
2684 kproc_resume(updateproc);
2688 * Reassign a buffer from one vnode to another.
2689 * Used to assign file specific control information
2690 * (indirect blocks) to the vnode to which they belong.
2693 reassignbuf(struct buf *bp)
2706 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2707 bp, bp->b_vp, bp->b_flags);
2709 * B_PAGING flagged buffers cannot be reassigned because their vp
2710 * is not fully linked in.
2712 if (bp->b_flags & B_PAGING)
2713 panic("cannot reassign paging buffer");
2716 * Delete from old vnode list, if on one.
2719 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2720 buf_vlist_remove(bp);
2722 panic("reassignbuf: Buffer %p not on queue.", bp);
2724 * If dirty, put on list of dirty buffers; otherwise insert onto list
2727 if (bp->b_flags & B_DELWRI) {
2728 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2729 switch (vp->v_type) {
2739 vn_syncer_add_to_worklist(bo, delay);
2741 buf_vlist_add(bp, bo, BX_VNDIRTY);
2743 buf_vlist_add(bp, bo, BX_VNCLEAN);
2745 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2746 mtx_lock(&sync_mtx);
2747 LIST_REMOVE(bo, bo_synclist);
2748 syncer_worklist_len--;
2749 mtx_unlock(&sync_mtx);
2750 bo->bo_flag &= ~BO_ONWORKLST;
2755 bp = TAILQ_FIRST(&bv->bv_hd);
2756 KASSERT(bp == NULL || bp->b_bufobj == bo,
2757 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2758 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2759 KASSERT(bp == NULL || bp->b_bufobj == bo,
2760 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2762 bp = TAILQ_FIRST(&bv->bv_hd);
2763 KASSERT(bp == NULL || bp->b_bufobj == bo,
2764 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2765 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2766 KASSERT(bp == NULL || bp->b_bufobj == bo,
2767 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2773 v_init_counters(struct vnode *vp)
2776 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2777 vp, ("%s called for an initialized vnode", __FUNCTION__));
2778 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2780 refcount_init(&vp->v_holdcnt, 1);
2781 refcount_init(&vp->v_usecount, 1);
2785 * Increment si_usecount of the associated device, if any.
2788 v_incr_devcount(struct vnode *vp)
2791 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2792 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2794 vp->v_rdev->si_usecount++;
2800 * Decrement si_usecount of the associated device, if any.
2803 v_decr_devcount(struct vnode *vp)
2806 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2807 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2809 vp->v_rdev->si_usecount--;
2815 * Grab a particular vnode from the free list, increment its
2816 * reference count and lock it. VIRF_DOOMED is set if the vnode
2817 * is being destroyed. Only callers who specify LK_RETRY will
2818 * see doomed vnodes. If inactive processing was delayed in
2819 * vput try to do it here.
2821 * usecount is manipulated using atomics without holding any locks.
2823 * holdcnt can be manipulated using atomics without holding any locks,
2824 * except when transitioning 1<->0, in which case the interlock is held.
2827 vget_prep(struct vnode *vp)
2831 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2841 vget(struct vnode *vp, int flags, struct thread *td)
2845 MPASS(td == curthread);
2848 return (vget_finish(vp, flags, vs));
2851 static int __noinline
2852 vget_finish_vchr(struct vnode *vp)
2855 VNASSERT(vp->v_type == VCHR, vp, ("type != VCHR)"));
2858 * See the comment in vget_finish before usecount bump.
2860 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2862 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2863 VNASSERT(old > 0, vp, ("%s: wrong hold count %d", __func__, old));
2865 refcount_release(&vp->v_holdcnt);
2871 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2873 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2874 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2876 refcount_release(&vp->v_holdcnt);
2881 v_incr_devcount(vp);
2882 refcount_acquire(&vp->v_usecount);
2888 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
2892 VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2893 ("%s: invalid lock operation", __func__));
2895 if ((flags & LK_INTERLOCK) != 0)
2896 ASSERT_VI_LOCKED(vp, __func__);
2898 ASSERT_VI_UNLOCKED(vp, __func__);
2899 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
2900 if (vs == VGET_USECOUNT) {
2901 VNASSERT(vp->v_usecount > 0, vp,
2902 ("%s: vnode without usecount when VGET_USECOUNT was passed",
2906 error = vn_lock(vp, flags);
2907 if (__predict_false(error != 0)) {
2908 if (vs == VGET_USECOUNT)
2912 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2917 if (vs == VGET_USECOUNT) {
2921 if (__predict_false(vp->v_type == VCHR))
2922 return (vget_finish_vchr(vp));
2925 * We hold the vnode. If the usecount is 0 it will be utilized to keep
2926 * the vnode around. Otherwise someone else lended their hold count and
2927 * we have to drop ours.
2929 old = atomic_fetchadd_int(&vp->v_usecount, 1);
2930 VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
2933 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2934 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2936 refcount_release(&vp->v_holdcnt);
2943 * Increase the reference (use) and hold count of a vnode.
2944 * This will also remove the vnode from the free list if it is presently free.
2946 static void __noinline
2947 vref_vchr(struct vnode *vp, bool interlock)
2951 * See the comment in vget_finish before usecount bump.
2954 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2955 VNODE_REFCOUNT_FENCE_ACQ();
2956 VNASSERT(vp->v_holdcnt > 0, vp,
2957 ("%s: active vnode not held", __func__));
2962 * By the time we get here the vnode might have been doomed, at
2963 * which point the 0->1 use count transition is no longer
2964 * protected by the interlock. Since it can't bounce back to
2965 * VCHR and requires vref semantics, punt it back
2967 if (__predict_false(vp->v_type == VBAD)) {
2973 VNASSERT(vp->v_type == VCHR, vp, ("type != VCHR)"));
2974 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2975 VNODE_REFCOUNT_FENCE_ACQ();
2976 VNASSERT(vp->v_holdcnt > 0, vp,
2977 ("%s: active vnode not held", __func__));
2983 v_incr_devcount(vp);
2984 refcount_acquire(&vp->v_usecount);
2991 vref(struct vnode *vp)
2995 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2996 if (__predict_false(vp->v_type == VCHR)) {
2997 vref_vchr(vp, false);
3001 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3002 VNODE_REFCOUNT_FENCE_ACQ();
3003 VNASSERT(vp->v_holdcnt > 0, vp,
3004 ("%s: active vnode not held", __func__));
3009 * See the comment in vget_finish.
3011 old = atomic_fetchadd_int(&vp->v_usecount, 1);
3012 VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
3015 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
3016 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
3018 refcount_release(&vp->v_holdcnt);
3024 vrefl(struct vnode *vp)
3027 ASSERT_VI_LOCKED(vp, __func__);
3028 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3029 if (__predict_false(vp->v_type == VCHR)) {
3030 vref_vchr(vp, true);
3037 vrefact(struct vnode *vp)
3040 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3042 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
3043 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3045 refcount_acquire(&vp->v_usecount);
3050 * Return reference count of a vnode.
3052 * The results of this call are only guaranteed when some mechanism is used to
3053 * stop other processes from gaining references to the vnode. This may be the
3054 * case if the caller holds the only reference. This is also useful when stale
3055 * data is acceptable as race conditions may be accounted for by some other
3059 vrefcnt(struct vnode *vp)
3062 return (vp->v_usecount);
3066 vlazy(struct vnode *vp)
3070 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
3072 if ((vp->v_mflag & VMP_LAZYLIST) != 0)
3075 * We may get here for inactive routines after the vnode got doomed.
3077 if (VN_IS_DOOMED(vp))
3080 mtx_lock(&mp->mnt_listmtx);
3081 if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
3082 vp->v_mflag |= VMP_LAZYLIST;
3083 TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3084 mp->mnt_lazyvnodelistsize++;
3086 mtx_unlock(&mp->mnt_listmtx);
3090 * This routine is only meant to be called from vgonel prior to dooming
3094 vunlazy_gone(struct vnode *vp)
3098 ASSERT_VOP_ELOCKED(vp, __func__);
3099 ASSERT_VI_LOCKED(vp, __func__);
3100 VNPASS(!VN_IS_DOOMED(vp), vp);
3102 if (vp->v_mflag & VMP_LAZYLIST) {
3104 mtx_lock(&mp->mnt_listmtx);
3105 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3106 vp->v_mflag &= ~VMP_LAZYLIST;
3107 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3108 mp->mnt_lazyvnodelistsize--;
3109 mtx_unlock(&mp->mnt_listmtx);
3114 vdefer_inactive(struct vnode *vp)
3117 ASSERT_VI_LOCKED(vp, __func__);
3118 VNASSERT(vp->v_holdcnt > 0, vp,
3119 ("%s: vnode without hold count", __func__));
3120 if (VN_IS_DOOMED(vp)) {
3124 if (vp->v_iflag & VI_DEFINACT) {
3125 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3129 if (vp->v_usecount > 0) {
3130 vp->v_iflag &= ~VI_OWEINACT;
3135 vp->v_iflag |= VI_DEFINACT;
3137 counter_u64_add(deferred_inact, 1);
3141 vdefer_inactive_unlocked(struct vnode *vp)
3145 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3149 vdefer_inactive(vp);
3152 enum vputx_op { VPUTX_VRELE, VPUTX_VPUT, VPUTX_VUNREF };
3155 * Decrement the use and hold counts for a vnode.
3157 * See an explanation near vget() as to why atomic operation is safe.
3159 * XXX Some filesystems pass in an exclusively locked vnode and strongly depend
3160 * on the lock being held all the way until VOP_INACTIVE. This in particular
3161 * happens with UFS which adds half-constructed vnodes to the hash, where they
3162 * can be found by other code.
3165 vputx(struct vnode *vp, enum vputx_op func)
3169 KASSERT(vp != NULL, ("vputx: null vp"));
3170 if (func == VPUTX_VUNREF)
3171 ASSERT_VOP_LOCKED(vp, "vunref");
3172 else if (func == VPUTX_VPUT)
3173 ASSERT_VOP_LOCKED(vp, "vput");
3174 ASSERT_VI_UNLOCKED(vp, __func__);
3175 VNASSERT(vp->v_holdcnt > 0 && vp->v_usecount > 0, vp,
3176 ("%s: wrong ref counts", __func__));
3178 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3181 * We want to hold the vnode until the inactive finishes to
3182 * prevent vgone() races. We drop the use count here and the
3183 * hold count below when we're done.
3185 * If we release the last usecount we take ownership of the hold
3186 * count which provides liveness of the vnode, in which case we
3189 if (!refcount_release(&vp->v_usecount)) {
3190 if (func == VPUTX_VPUT)
3195 v_decr_devcount(vp);
3197 * By the time we got here someone else might have transitioned
3198 * the count back to > 0.
3200 if (vp->v_usecount > 0 || vp->v_iflag & VI_DOINGINACT)
3204 * Check if the fs wants to perform inactive processing. Note we
3205 * may be only holding the interlock, in which case it is possible
3206 * someone else called vgone on the vnode and ->v_data is now NULL.
3207 * Since vgone performs inactive on its own there is nothing to do
3208 * here but to drop our hold count.
3210 if (__predict_false(VN_IS_DOOMED(vp)) ||
3211 VOP_NEED_INACTIVE(vp) == 0)
3215 * We must call VOP_INACTIVE with the node locked. Mark
3216 * as VI_DOINGINACT to avoid recursion.
3218 vp->v_iflag |= VI_OWEINACT;
3221 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3226 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3227 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3234 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3235 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3242 if (func != VPUTX_VUNREF)
3246 vdefer_inactive(vp);
3250 if (func == VPUTX_VPUT)
3256 * Vnode put/release.
3257 * If count drops to zero, call inactive routine and return to freelist.
3260 vrele(struct vnode *vp)
3263 vputx(vp, VPUTX_VRELE);
3267 * Release an already locked vnode. This give the same effects as
3268 * unlock+vrele(), but takes less time and avoids releasing and
3269 * re-aquiring the lock (as vrele() acquires the lock internally.)
3272 vput(struct vnode *vp)
3275 vputx(vp, VPUTX_VPUT);
3279 * Release an exclusively locked vnode. Do not unlock the vnode lock.
3282 vunref(struct vnode *vp)
3285 vputx(vp, VPUTX_VUNREF);
3289 vhold(struct vnode *vp)
3294 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3295 old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3296 VNASSERT(old >= 0, vp, ("%s: wrong hold count %d", __func__, old));
3306 vholdl(struct vnode *vp)
3309 ASSERT_VI_LOCKED(vp, __func__);
3310 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3315 vholdnz(struct vnode *vp)
3318 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3320 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3321 VNASSERT(old > 0, vp, ("%s: wrong hold count %d", __func__, old));
3323 atomic_add_int(&vp->v_holdcnt, 1);
3327 static void __noinline
3328 vdbatch_process(struct vdbatch *vd)
3333 mtx_assert(&vd->lock, MA_OWNED);
3334 MPASS(curthread->td_pinned > 0);
3335 MPASS(vd->index == VDBATCH_SIZE);
3337 mtx_lock(&vnode_list_mtx);
3339 freevnodes += vd->freevnodes;
3340 for (i = 0; i < VDBATCH_SIZE; i++) {
3342 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3343 TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3344 MPASS(vp->v_dbatchcpu != NOCPU);
3345 vp->v_dbatchcpu = NOCPU;
3347 mtx_unlock(&vnode_list_mtx);
3349 bzero(vd->tab, sizeof(vd->tab));
3355 vdbatch_enqueue(struct vnode *vp)
3359 ASSERT_VI_LOCKED(vp, __func__);
3360 VNASSERT(!VN_IS_DOOMED(vp), vp,
3361 ("%s: deferring requeue of a doomed vnode", __func__));
3366 if (vp->v_dbatchcpu != NOCPU) {
3374 mtx_lock(&vd->lock);
3375 MPASS(vd->index < VDBATCH_SIZE);
3376 MPASS(vd->tab[vd->index] == NULL);
3378 * A hack: we depend on being pinned so that we know what to put in
3381 vp->v_dbatchcpu = curcpu;
3382 vd->tab[vd->index] = vp;
3385 if (vd->index == VDBATCH_SIZE)
3386 vdbatch_process(vd);
3387 mtx_unlock(&vd->lock);
3392 * This routine must only be called for vnodes which are about to be
3393 * deallocated. Supporting dequeue for arbitrary vndoes would require
3394 * validating that the locked batch matches.
3397 vdbatch_dequeue(struct vnode *vp)
3403 VNASSERT(vp->v_type == VBAD || vp->v_type == VNON, vp,
3404 ("%s: called for a used vnode\n", __func__));
3406 cpu = vp->v_dbatchcpu;
3410 vd = DPCPU_ID_PTR(cpu, vd);
3411 mtx_lock(&vd->lock);
3412 for (i = 0; i < vd->index; i++) {
3413 if (vd->tab[i] != vp)
3415 vp->v_dbatchcpu = NOCPU;
3417 vd->tab[i] = vd->tab[vd->index];
3418 vd->tab[vd->index] = NULL;
3421 mtx_unlock(&vd->lock);
3423 * Either we dequeued the vnode above or the target CPU beat us to it.
3425 MPASS(vp->v_dbatchcpu == NOCPU);
3429 * Drop the hold count of the vnode. If this is the last reference to
3430 * the vnode we place it on the free list unless it has been vgone'd
3431 * (marked VIRF_DOOMED) in which case we will free it.
3433 * Because the vnode vm object keeps a hold reference on the vnode if
3434 * there is at least one resident non-cached page, the vnode cannot
3435 * leave the active list without the page cleanup done.
3438 vdrop_deactivate(struct vnode *vp)
3442 ASSERT_VI_LOCKED(vp, __func__);
3444 * Mark a vnode as free: remove it from its active list
3445 * and put it up for recycling on the freelist.
3447 VNASSERT(!VN_IS_DOOMED(vp), vp,
3448 ("vdrop: returning doomed vnode"));
3449 VNASSERT(vp->v_op != NULL, vp,
3450 ("vdrop: vnode already reclaimed."));
3451 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
3452 ("vnode with VI_OWEINACT set"));
3453 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp,
3454 ("vnode with VI_DEFINACT set"));
3455 if (vp->v_mflag & VMP_LAZYLIST) {
3457 mtx_lock(&mp->mnt_listmtx);
3458 VNASSERT(vp->v_mflag & VMP_LAZYLIST, vp, ("lost VMP_LAZYLIST"));
3460 * Don't remove the vnode from the lazy list if another thread
3461 * has increased the hold count. It may have re-enqueued the
3462 * vnode to the lazy list and is now responsible for its
3465 if (vp->v_holdcnt == 0) {
3466 vp->v_mflag &= ~VMP_LAZYLIST;
3467 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3468 mp->mnt_lazyvnodelistsize--;
3470 mtx_unlock(&mp->mnt_listmtx);
3472 vdbatch_enqueue(vp);
3476 vdrop(struct vnode *vp)
3479 ASSERT_VI_UNLOCKED(vp, __func__);
3480 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3481 if (refcount_release_if_not_last(&vp->v_holdcnt))
3488 vdropl(struct vnode *vp)
3491 ASSERT_VI_LOCKED(vp, __func__);
3492 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3493 if (!refcount_release(&vp->v_holdcnt)) {
3497 if (VN_IS_DOOMED(vp)) {
3501 vdrop_deactivate(vp);
3505 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3506 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3509 vinactivef(struct vnode *vp)
3511 struct vm_object *obj;
3513 ASSERT_VOP_ELOCKED(vp, "vinactive");
3514 ASSERT_VI_LOCKED(vp, "vinactive");
3515 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3516 ("vinactive: recursed on VI_DOINGINACT"));
3517 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3518 vp->v_iflag |= VI_DOINGINACT;
3519 vp->v_iflag &= ~VI_OWEINACT;
3522 * Before moving off the active list, we must be sure that any
3523 * modified pages are converted into the vnode's dirty
3524 * buffers, since these will no longer be checked once the
3525 * vnode is on the inactive list.
3527 * The write-out of the dirty pages is asynchronous. At the
3528 * point that VOP_INACTIVE() is called, there could still be
3529 * pending I/O and dirty pages in the object.
3531 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3532 vm_object_mightbedirty(obj)) {
3533 VM_OBJECT_WLOCK(obj);
3534 vm_object_page_clean(obj, 0, 0, 0);
3535 VM_OBJECT_WUNLOCK(obj);
3537 VOP_INACTIVE(vp, curthread);
3539 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3540 ("vinactive: lost VI_DOINGINACT"));
3541 vp->v_iflag &= ~VI_DOINGINACT;
3545 vinactive(struct vnode *vp)
3548 ASSERT_VOP_ELOCKED(vp, "vinactive");
3549 ASSERT_VI_LOCKED(vp, "vinactive");
3550 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3552 if ((vp->v_iflag & VI_OWEINACT) == 0)
3554 if (vp->v_iflag & VI_DOINGINACT)
3556 if (vp->v_usecount > 0) {
3557 vp->v_iflag &= ~VI_OWEINACT;
3564 * Remove any vnodes in the vnode table belonging to mount point mp.
3566 * If FORCECLOSE is not specified, there should not be any active ones,
3567 * return error if any are found (nb: this is a user error, not a
3568 * system error). If FORCECLOSE is specified, detach any active vnodes
3571 * If WRITECLOSE is set, only flush out regular file vnodes open for
3574 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3576 * `rootrefs' specifies the base reference count for the root vnode
3577 * of this filesystem. The root vnode is considered busy if its
3578 * v_usecount exceeds this value. On a successful return, vflush(, td)
3579 * will call vrele() on the root vnode exactly rootrefs times.
3580 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3584 static int busyprt = 0; /* print out busy vnodes */
3585 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3589 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3591 struct vnode *vp, *mvp, *rootvp = NULL;
3593 int busy = 0, error;
3595 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3598 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3599 ("vflush: bad args"));
3601 * Get the filesystem root vnode. We can vput() it
3602 * immediately, since with rootrefs > 0, it won't go away.
3604 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3605 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3612 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3614 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3617 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3621 * Skip over a vnodes marked VV_SYSTEM.
3623 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3629 * If WRITECLOSE is set, flush out unlinked but still open
3630 * files (even if open only for reading) and regular file
3631 * vnodes open for writing.
3633 if (flags & WRITECLOSE) {
3634 if (vp->v_object != NULL) {
3635 VM_OBJECT_WLOCK(vp->v_object);
3636 vm_object_page_clean(vp->v_object, 0, 0, 0);
3637 VM_OBJECT_WUNLOCK(vp->v_object);
3639 error = VOP_FSYNC(vp, MNT_WAIT, td);
3643 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3646 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3649 if ((vp->v_type == VNON ||
3650 (error == 0 && vattr.va_nlink > 0)) &&
3651 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3659 * With v_usecount == 0, all we need to do is clear out the
3660 * vnode data structures and we are done.
3662 * If FORCECLOSE is set, forcibly close the vnode.
3664 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3670 vn_printf(vp, "vflush: busy vnode ");
3676 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3678 * If just the root vnode is busy, and if its refcount
3679 * is equal to `rootrefs', then go ahead and kill it.
3682 KASSERT(busy > 0, ("vflush: not busy"));
3683 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3684 ("vflush: usecount %d < rootrefs %d",
3685 rootvp->v_usecount, rootrefs));
3686 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3687 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3695 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3699 for (; rootrefs > 0; rootrefs--)
3705 * Recycle an unused vnode to the front of the free list.
3708 vrecycle(struct vnode *vp)
3713 recycled = vrecyclel(vp);
3719 * vrecycle, with the vp interlock held.
3722 vrecyclel(struct vnode *vp)
3726 ASSERT_VOP_ELOCKED(vp, __func__);
3727 ASSERT_VI_LOCKED(vp, __func__);
3728 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3730 if (vp->v_usecount == 0) {
3738 * Eliminate all activity associated with a vnode
3739 * in preparation for reuse.
3742 vgone(struct vnode *vp)
3750 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3751 struct vnode *lowervp __unused)
3756 * Notify upper mounts about reclaimed or unlinked vnode.
3759 vfs_notify_upper(struct vnode *vp, int event)
3761 static struct vfsops vgonel_vfsops = {
3762 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3763 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3765 struct mount *mp, *ump, *mmp;
3770 if (TAILQ_EMPTY(&mp->mnt_uppers))
3773 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3774 mmp->mnt_op = &vgonel_vfsops;
3775 mmp->mnt_kern_flag |= MNTK_MARKER;
3777 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3778 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3779 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3780 ump = TAILQ_NEXT(ump, mnt_upper_link);
3783 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3786 case VFS_NOTIFY_UPPER_RECLAIM:
3787 VFS_RECLAIM_LOWERVP(ump, vp);
3789 case VFS_NOTIFY_UPPER_UNLINK:
3790 VFS_UNLINK_LOWERVP(ump, vp);
3793 KASSERT(0, ("invalid event %d", event));
3797 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3798 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3801 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3802 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3803 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3804 wakeup(&mp->mnt_uppers);
3810 * vgone, with the vp interlock held.
3813 vgonel(struct vnode *vp)
3818 bool active, oweinact;
3820 ASSERT_VOP_ELOCKED(vp, "vgonel");
3821 ASSERT_VI_LOCKED(vp, "vgonel");
3822 VNASSERT(vp->v_holdcnt, vp,
3823 ("vgonel: vp %p has no reference.", vp));
3824 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3828 * Don't vgonel if we're already doomed.
3830 if (vp->v_irflag & VIRF_DOOMED)
3833 vp->v_irflag |= VIRF_DOOMED;
3836 * Check to see if the vnode is in use. If so, we have to call
3837 * VOP_CLOSE() and VOP_INACTIVE().
3839 active = vp->v_usecount > 0;
3840 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
3842 * If we need to do inactive VI_OWEINACT will be set.
3844 if (vp->v_iflag & VI_DEFINACT) {
3845 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3846 vp->v_iflag &= ~VI_DEFINACT;
3849 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
3852 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
3855 * If purging an active vnode, it must be closed and
3856 * deactivated before being reclaimed.
3859 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
3860 if (oweinact || active) {
3865 if (vp->v_type == VSOCK)
3866 vfs_unp_reclaim(vp);
3869 * Clean out any buffers associated with the vnode.
3870 * If the flush fails, just toss the buffers.
3873 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
3874 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
3875 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
3876 while (vinvalbuf(vp, 0, 0, 0) != 0)
3880 BO_LOCK(&vp->v_bufobj);
3881 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
3882 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
3883 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
3884 vp->v_bufobj.bo_clean.bv_cnt == 0,
3885 ("vp %p bufobj not invalidated", vp));
3888 * For VMIO bufobj, BO_DEAD is set later, or in
3889 * vm_object_terminate() after the object's page queue is
3892 object = vp->v_bufobj.bo_object;
3894 vp->v_bufobj.bo_flag |= BO_DEAD;
3895 BO_UNLOCK(&vp->v_bufobj);
3898 * Handle the VM part. Tmpfs handles v_object on its own (the
3899 * OBJT_VNODE check). Nullfs or other bypassing filesystems
3900 * should not touch the object borrowed from the lower vnode
3901 * (the handle check).
3903 if (object != NULL && object->type == OBJT_VNODE &&
3904 object->handle == vp)
3905 vnode_destroy_vobject(vp);
3908 * Reclaim the vnode.
3910 if (VOP_RECLAIM(vp, td))
3911 panic("vgone: cannot reclaim");
3913 vn_finished_secondary_write(mp);
3914 VNASSERT(vp->v_object == NULL, vp,
3915 ("vop_reclaim left v_object vp=%p", vp));
3917 * Clear the advisory locks and wake up waiting threads.
3919 (void)VOP_ADVLOCKPURGE(vp);
3922 * Delete from old mount point vnode list.
3927 * Done with purge, reset to the standard lock and invalidate
3931 vp->v_vnlock = &vp->v_lock;
3932 vp->v_op = &dead_vnodeops;
3937 * Calculate the total number of references to a special device.
3940 vcount(struct vnode *vp)
3945 count = vp->v_rdev->si_usecount;
3951 * Print out a description of a vnode.
3953 static char *typename[] =
3954 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
3958 vn_printf(struct vnode *vp, const char *fmt, ...)
3961 char buf[256], buf2[16];
3967 printf("%p: ", (void *)vp);
3968 printf("type %s\n", typename[vp->v_type]);
3969 printf(" usecount %d, writecount %d, refcount %d",
3970 vp->v_usecount, vp->v_writecount, vp->v_holdcnt);
3971 switch (vp->v_type) {
3973 printf(" mountedhere %p\n", vp->v_mountedhere);
3976 printf(" rdev %p\n", vp->v_rdev);
3979 printf(" socket %p\n", vp->v_unpcb);
3982 printf(" fifoinfo %p\n", vp->v_fifoinfo);
3990 if (vp->v_irflag & VIRF_DOOMED)
3991 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
3992 flags = vp->v_irflag & ~(VIRF_DOOMED);
3994 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
3995 strlcat(buf, buf2, sizeof(buf));
3997 if (vp->v_vflag & VV_ROOT)
3998 strlcat(buf, "|VV_ROOT", sizeof(buf));
3999 if (vp->v_vflag & VV_ISTTY)
4000 strlcat(buf, "|VV_ISTTY", sizeof(buf));
4001 if (vp->v_vflag & VV_NOSYNC)
4002 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
4003 if (vp->v_vflag & VV_ETERNALDEV)
4004 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
4005 if (vp->v_vflag & VV_CACHEDLABEL)
4006 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
4007 if (vp->v_vflag & VV_VMSIZEVNLOCK)
4008 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
4009 if (vp->v_vflag & VV_COPYONWRITE)
4010 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
4011 if (vp->v_vflag & VV_SYSTEM)
4012 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
4013 if (vp->v_vflag & VV_PROCDEP)
4014 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
4015 if (vp->v_vflag & VV_NOKNOTE)
4016 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
4017 if (vp->v_vflag & VV_DELETED)
4018 strlcat(buf, "|VV_DELETED", sizeof(buf));
4019 if (vp->v_vflag & VV_MD)
4020 strlcat(buf, "|VV_MD", sizeof(buf));
4021 if (vp->v_vflag & VV_FORCEINSMQ)
4022 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
4023 if (vp->v_vflag & VV_READLINK)
4024 strlcat(buf, "|VV_READLINK", sizeof(buf));
4025 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4026 VV_CACHEDLABEL | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
4027 VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
4029 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4030 strlcat(buf, buf2, sizeof(buf));
4032 if (vp->v_iflag & VI_TEXT_REF)
4033 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
4034 if (vp->v_iflag & VI_MOUNT)
4035 strlcat(buf, "|VI_MOUNT", sizeof(buf));
4036 if (vp->v_iflag & VI_DOINGINACT)
4037 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4038 if (vp->v_iflag & VI_OWEINACT)
4039 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4040 if (vp->v_iflag & VI_DEFINACT)
4041 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4042 flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOINGINACT |
4043 VI_OWEINACT | VI_DEFINACT);
4045 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4046 strlcat(buf, buf2, sizeof(buf));
4048 if (vp->v_mflag & VMP_LAZYLIST)
4049 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4050 flags = vp->v_mflag & ~(VMP_LAZYLIST);
4052 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4053 strlcat(buf, buf2, sizeof(buf));
4055 printf(" flags (%s)\n", buf + 1);
4056 if (mtx_owned(VI_MTX(vp)))
4057 printf(" VI_LOCKed");
4058 if (vp->v_object != NULL)
4059 printf(" v_object %p ref %d pages %d "
4060 "cleanbuf %d dirtybuf %d\n",
4061 vp->v_object, vp->v_object->ref_count,
4062 vp->v_object->resident_page_count,
4063 vp->v_bufobj.bo_clean.bv_cnt,
4064 vp->v_bufobj.bo_dirty.bv_cnt);
4066 lockmgr_printinfo(vp->v_vnlock);
4067 if (vp->v_data != NULL)
4073 * List all of the locked vnodes in the system.
4074 * Called when debugging the kernel.
4076 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
4082 * Note: because this is DDB, we can't obey the locking semantics
4083 * for these structures, which means we could catch an inconsistent
4084 * state and dereference a nasty pointer. Not much to be done
4087 db_printf("Locked vnodes\n");
4088 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4089 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4090 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4091 vn_printf(vp, "vnode ");
4097 * Show details about the given vnode.
4099 DB_SHOW_COMMAND(vnode, db_show_vnode)
4105 vp = (struct vnode *)addr;
4106 vn_printf(vp, "vnode ");
4110 * Show details about the given mount point.
4112 DB_SHOW_COMMAND(mount, db_show_mount)
4123 /* No address given, print short info about all mount points. */
4124 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4125 db_printf("%p %s on %s (%s)\n", mp,
4126 mp->mnt_stat.f_mntfromname,
4127 mp->mnt_stat.f_mntonname,
4128 mp->mnt_stat.f_fstypename);
4132 db_printf("\nMore info: show mount <addr>\n");
4136 mp = (struct mount *)addr;
4137 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4138 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4141 mflags = mp->mnt_flag;
4142 #define MNT_FLAG(flag) do { \
4143 if (mflags & (flag)) { \
4144 if (buf[0] != '\0') \
4145 strlcat(buf, ", ", sizeof(buf)); \
4146 strlcat(buf, (#flag) + 4, sizeof(buf)); \
4147 mflags &= ~(flag); \
4150 MNT_FLAG(MNT_RDONLY);
4151 MNT_FLAG(MNT_SYNCHRONOUS);
4152 MNT_FLAG(MNT_NOEXEC);
4153 MNT_FLAG(MNT_NOSUID);
4154 MNT_FLAG(MNT_NFS4ACLS);
4155 MNT_FLAG(MNT_UNION);
4156 MNT_FLAG(MNT_ASYNC);
4157 MNT_FLAG(MNT_SUIDDIR);
4158 MNT_FLAG(MNT_SOFTDEP);
4159 MNT_FLAG(MNT_NOSYMFOLLOW);
4160 MNT_FLAG(MNT_GJOURNAL);
4161 MNT_FLAG(MNT_MULTILABEL);
4163 MNT_FLAG(MNT_NOATIME);
4164 MNT_FLAG(MNT_NOCLUSTERR);
4165 MNT_FLAG(MNT_NOCLUSTERW);
4167 MNT_FLAG(MNT_EXRDONLY);
4168 MNT_FLAG(MNT_EXPORTED);
4169 MNT_FLAG(MNT_DEFEXPORTED);
4170 MNT_FLAG(MNT_EXPORTANON);
4171 MNT_FLAG(MNT_EXKERB);
4172 MNT_FLAG(MNT_EXPUBLIC);
4173 MNT_FLAG(MNT_LOCAL);
4174 MNT_FLAG(MNT_QUOTA);
4175 MNT_FLAG(MNT_ROOTFS);
4177 MNT_FLAG(MNT_IGNORE);
4178 MNT_FLAG(MNT_UPDATE);
4179 MNT_FLAG(MNT_DELEXPORT);
4180 MNT_FLAG(MNT_RELOAD);
4181 MNT_FLAG(MNT_FORCE);
4182 MNT_FLAG(MNT_SNAPSHOT);
4183 MNT_FLAG(MNT_BYFSID);
4187 strlcat(buf, ", ", sizeof(buf));
4188 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4189 "0x%016jx", mflags);
4191 db_printf(" mnt_flag = %s\n", buf);
4194 flags = mp->mnt_kern_flag;
4195 #define MNT_KERN_FLAG(flag) do { \
4196 if (flags & (flag)) { \
4197 if (buf[0] != '\0') \
4198 strlcat(buf, ", ", sizeof(buf)); \
4199 strlcat(buf, (#flag) + 5, sizeof(buf)); \
4203 MNT_KERN_FLAG(MNTK_UNMOUNTF);
4204 MNT_KERN_FLAG(MNTK_ASYNC);
4205 MNT_KERN_FLAG(MNTK_SOFTDEP);
4206 MNT_KERN_FLAG(MNTK_DRAINING);
4207 MNT_KERN_FLAG(MNTK_REFEXPIRE);
4208 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4209 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4210 MNT_KERN_FLAG(MNTK_NO_IOPF);
4211 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4212 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4213 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4214 MNT_KERN_FLAG(MNTK_MARKER);
4215 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4216 MNT_KERN_FLAG(MNTK_NOASYNC);
4217 MNT_KERN_FLAG(MNTK_UNMOUNT);
4218 MNT_KERN_FLAG(MNTK_MWAIT);
4219 MNT_KERN_FLAG(MNTK_SUSPEND);
4220 MNT_KERN_FLAG(MNTK_SUSPEND2);
4221 MNT_KERN_FLAG(MNTK_SUSPENDED);
4222 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4223 MNT_KERN_FLAG(MNTK_NOKNOTE);
4224 #undef MNT_KERN_FLAG
4227 strlcat(buf, ", ", sizeof(buf));
4228 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4231 db_printf(" mnt_kern_flag = %s\n", buf);
4233 db_printf(" mnt_opt = ");
4234 opt = TAILQ_FIRST(mp->mnt_opt);
4236 db_printf("%s", opt->name);
4237 opt = TAILQ_NEXT(opt, link);
4238 while (opt != NULL) {
4239 db_printf(", %s", opt->name);
4240 opt = TAILQ_NEXT(opt, link);
4246 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4247 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4248 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4249 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4250 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4251 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4252 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4253 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4254 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4255 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4256 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4257 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4259 db_printf(" mnt_cred = { uid=%u ruid=%u",
4260 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4261 if (jailed(mp->mnt_cred))
4262 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4264 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4265 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4266 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4267 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4268 db_printf(" mnt_lazyvnodelistsize = %d\n",
4269 mp->mnt_lazyvnodelistsize);
4270 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4271 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4272 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
4273 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4274 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4275 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4276 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4277 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4278 db_printf(" mnt_secondary_accwrites = %d\n",
4279 mp->mnt_secondary_accwrites);
4280 db_printf(" mnt_gjprovider = %s\n",
4281 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4282 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4284 db_printf("\n\nList of active vnodes\n");
4285 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4286 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4287 vn_printf(vp, "vnode ");
4292 db_printf("\n\nList of inactive vnodes\n");
4293 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4294 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4295 vn_printf(vp, "vnode ");
4304 * Fill in a struct xvfsconf based on a struct vfsconf.
4307 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4309 struct xvfsconf xvfsp;
4311 bzero(&xvfsp, sizeof(xvfsp));
4312 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4313 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4314 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4315 xvfsp.vfc_flags = vfsp->vfc_flags;
4317 * These are unused in userland, we keep them
4318 * to not break binary compatibility.
4320 xvfsp.vfc_vfsops = NULL;
4321 xvfsp.vfc_next = NULL;
4322 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4325 #ifdef COMPAT_FREEBSD32
4327 uint32_t vfc_vfsops;
4328 char vfc_name[MFSNAMELEN];
4329 int32_t vfc_typenum;
4330 int32_t vfc_refcount;
4336 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4338 struct xvfsconf32 xvfsp;
4340 bzero(&xvfsp, sizeof(xvfsp));
4341 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4342 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4343 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4344 xvfsp.vfc_flags = vfsp->vfc_flags;
4345 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4350 * Top level filesystem related information gathering.
4353 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4355 struct vfsconf *vfsp;
4360 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4361 #ifdef COMPAT_FREEBSD32
4362 if (req->flags & SCTL_MASK32)
4363 error = vfsconf2x32(req, vfsp);
4366 error = vfsconf2x(req, vfsp);
4374 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4375 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4376 "S,xvfsconf", "List of all configured filesystems");
4378 #ifndef BURN_BRIDGES
4379 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4382 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4384 int *name = (int *)arg1 - 1; /* XXX */
4385 u_int namelen = arg2 + 1; /* XXX */
4386 struct vfsconf *vfsp;
4388 log(LOG_WARNING, "userland calling deprecated sysctl, "
4389 "please rebuild world\n");
4391 #if 1 || defined(COMPAT_PRELITE2)
4392 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4394 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4398 case VFS_MAXTYPENUM:
4401 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4404 return (ENOTDIR); /* overloaded */
4406 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4407 if (vfsp->vfc_typenum == name[2])
4412 return (EOPNOTSUPP);
4413 #ifdef COMPAT_FREEBSD32
4414 if (req->flags & SCTL_MASK32)
4415 return (vfsconf2x32(req, vfsp));
4418 return (vfsconf2x(req, vfsp));
4420 return (EOPNOTSUPP);
4423 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4424 CTLFLAG_MPSAFE, vfs_sysctl,
4425 "Generic filesystem");
4427 #if 1 || defined(COMPAT_PRELITE2)
4430 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4433 struct vfsconf *vfsp;
4434 struct ovfsconf ovfs;
4437 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4438 bzero(&ovfs, sizeof(ovfs));
4439 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4440 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4441 ovfs.vfc_index = vfsp->vfc_typenum;
4442 ovfs.vfc_refcount = vfsp->vfc_refcount;
4443 ovfs.vfc_flags = vfsp->vfc_flags;
4444 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4454 #endif /* 1 || COMPAT_PRELITE2 */
4455 #endif /* !BURN_BRIDGES */
4457 #define KINFO_VNODESLOP 10
4460 * Dump vnode list (via sysctl).
4464 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4472 * Stale numvnodes access is not fatal here.
4475 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4477 /* Make an estimate */
4478 return (SYSCTL_OUT(req, 0, len));
4480 error = sysctl_wire_old_buffer(req, 0);
4483 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4485 mtx_lock(&mountlist_mtx);
4486 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4487 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4490 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4494 xvn[n].xv_size = sizeof *xvn;
4495 xvn[n].xv_vnode = vp;
4496 xvn[n].xv_id = 0; /* XXX compat */
4497 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4499 XV_COPY(writecount);
4505 xvn[n].xv_flag = vp->v_vflag;
4507 switch (vp->v_type) {
4514 if (vp->v_rdev == NULL) {
4518 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4521 xvn[n].xv_socket = vp->v_socket;
4524 xvn[n].xv_fifo = vp->v_fifoinfo;
4529 /* shouldn't happen? */
4537 mtx_lock(&mountlist_mtx);
4542 mtx_unlock(&mountlist_mtx);
4544 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4549 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4550 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4555 unmount_or_warn(struct mount *mp)
4559 error = dounmount(mp, MNT_FORCE, curthread);
4561 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4565 printf("%d)\n", error);
4570 * Unmount all filesystems. The list is traversed in reverse order
4571 * of mounting to avoid dependencies.
4574 vfs_unmountall(void)
4576 struct mount *mp, *tmp;
4578 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4581 * Since this only runs when rebooting, it is not interlocked.
4583 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4587 * Forcibly unmounting "/dev" before "/" would prevent clean
4588 * unmount of the latter.
4590 if (mp == rootdevmp)
4593 unmount_or_warn(mp);
4596 if (rootdevmp != NULL)
4597 unmount_or_warn(rootdevmp);
4601 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4604 ASSERT_VI_LOCKED(vp, __func__);
4605 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4606 if ((vp->v_iflag & VI_OWEINACT) == 0) {
4610 if (vn_lock(vp, lkflags) == 0) {
4617 vdefer_inactive_unlocked(vp);
4621 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4624 return (vp->v_iflag & VI_DEFINACT);
4627 static void __noinline
4628 vfs_periodic_inactive(struct mount *mp, int flags)
4630 struct vnode *vp, *mvp;
4633 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4634 if (flags != MNT_WAIT)
4635 lkflags |= LK_NOWAIT;
4637 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4638 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4642 vp->v_iflag &= ~VI_DEFINACT;
4643 vfs_deferred_inactive(vp, lkflags);
4648 vfs_want_msync(struct vnode *vp)
4650 struct vm_object *obj;
4653 * This test may be performed without any locks held.
4654 * We rely on vm_object's type stability.
4656 if (vp->v_vflag & VV_NOSYNC)
4659 return (obj != NULL && vm_object_mightbedirty(obj));
4663 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4666 if (vp->v_vflag & VV_NOSYNC)
4668 if (vp->v_iflag & VI_DEFINACT)
4670 return (vfs_want_msync(vp));
4673 static void __noinline
4674 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4676 struct vnode *vp, *mvp;
4677 struct vm_object *obj;
4679 int lkflags, objflags;
4684 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4685 if (flags != MNT_WAIT) {
4686 lkflags |= LK_NOWAIT;
4687 objflags = OBJPC_NOSYNC;
4689 objflags = OBJPC_SYNC;
4692 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4694 if (vp->v_iflag & VI_DEFINACT) {
4695 vp->v_iflag &= ~VI_DEFINACT;
4698 if (!vfs_want_msync(vp)) {
4700 vfs_deferred_inactive(vp, lkflags);
4705 if (vget(vp, lkflags, td) == 0) {
4707 if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4708 VM_OBJECT_WLOCK(obj);
4709 vm_object_page_clean(obj, 0, 0, objflags);
4710 VM_OBJECT_WUNLOCK(obj);
4717 vdefer_inactive_unlocked(vp);
4723 vfs_periodic(struct mount *mp, int flags)
4726 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4728 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4729 vfs_periodic_inactive(mp, flags);
4731 vfs_periodic_msync_inactive(mp, flags);
4735 destroy_vpollinfo_free(struct vpollinfo *vi)
4738 knlist_destroy(&vi->vpi_selinfo.si_note);
4739 mtx_destroy(&vi->vpi_lock);
4740 uma_zfree(vnodepoll_zone, vi);
4744 destroy_vpollinfo(struct vpollinfo *vi)
4747 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4748 seldrain(&vi->vpi_selinfo);
4749 destroy_vpollinfo_free(vi);
4753 * Initialize per-vnode helper structure to hold poll-related state.
4756 v_addpollinfo(struct vnode *vp)
4758 struct vpollinfo *vi;
4760 if (vp->v_pollinfo != NULL)
4762 vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4763 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4764 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4765 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4767 if (vp->v_pollinfo != NULL) {
4769 destroy_vpollinfo_free(vi);
4772 vp->v_pollinfo = vi;
4777 * Record a process's interest in events which might happen to
4778 * a vnode. Because poll uses the historic select-style interface
4779 * internally, this routine serves as both the ``check for any
4780 * pending events'' and the ``record my interest in future events''
4781 * functions. (These are done together, while the lock is held,
4782 * to avoid race conditions.)
4785 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4789 mtx_lock(&vp->v_pollinfo->vpi_lock);
4790 if (vp->v_pollinfo->vpi_revents & events) {
4792 * This leaves events we are not interested
4793 * in available for the other process which
4794 * which presumably had requested them
4795 * (otherwise they would never have been
4798 events &= vp->v_pollinfo->vpi_revents;
4799 vp->v_pollinfo->vpi_revents &= ~events;
4801 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4804 vp->v_pollinfo->vpi_events |= events;
4805 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4806 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4811 * Routine to create and manage a filesystem syncer vnode.
4813 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4814 static int sync_fsync(struct vop_fsync_args *);
4815 static int sync_inactive(struct vop_inactive_args *);
4816 static int sync_reclaim(struct vop_reclaim_args *);
4818 static struct vop_vector sync_vnodeops = {
4819 .vop_bypass = VOP_EOPNOTSUPP,
4820 .vop_close = sync_close, /* close */
4821 .vop_fsync = sync_fsync, /* fsync */
4822 .vop_inactive = sync_inactive, /* inactive */
4823 .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
4824 .vop_reclaim = sync_reclaim, /* reclaim */
4825 .vop_lock1 = vop_stdlock, /* lock */
4826 .vop_unlock = vop_stdunlock, /* unlock */
4827 .vop_islocked = vop_stdislocked, /* islocked */
4829 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
4832 * Create a new filesystem syncer vnode for the specified mount point.
4835 vfs_allocate_syncvnode(struct mount *mp)
4839 static long start, incr, next;
4842 /* Allocate a new vnode */
4843 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
4845 panic("vfs_allocate_syncvnode: getnewvnode() failed");
4847 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4848 vp->v_vflag |= VV_FORCEINSMQ;
4849 error = insmntque(vp, mp);
4851 panic("vfs_allocate_syncvnode: insmntque() failed");
4852 vp->v_vflag &= ~VV_FORCEINSMQ;
4855 * Place the vnode onto the syncer worklist. We attempt to
4856 * scatter them about on the list so that they will go off
4857 * at evenly distributed times even if all the filesystems
4858 * are mounted at once.
4861 if (next == 0 || next > syncer_maxdelay) {
4865 start = syncer_maxdelay / 2;
4866 incr = syncer_maxdelay;
4872 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
4873 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
4874 mtx_lock(&sync_mtx);
4876 if (mp->mnt_syncer == NULL) {
4877 mp->mnt_syncer = vp;
4880 mtx_unlock(&sync_mtx);
4883 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4890 vfs_deallocate_syncvnode(struct mount *mp)
4894 mtx_lock(&sync_mtx);
4895 vp = mp->mnt_syncer;
4897 mp->mnt_syncer = NULL;
4898 mtx_unlock(&sync_mtx);
4904 * Do a lazy sync of the filesystem.
4907 sync_fsync(struct vop_fsync_args *ap)
4909 struct vnode *syncvp = ap->a_vp;
4910 struct mount *mp = syncvp->v_mount;
4915 * We only need to do something if this is a lazy evaluation.
4917 if (ap->a_waitfor != MNT_LAZY)
4921 * Move ourselves to the back of the sync list.
4923 bo = &syncvp->v_bufobj;
4925 vn_syncer_add_to_worklist(bo, syncdelay);
4929 * Walk the list of vnodes pushing all that are dirty and
4930 * not already on the sync list.
4932 if (vfs_busy(mp, MBF_NOWAIT) != 0)
4934 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
4938 save = curthread_pflags_set(TDP_SYNCIO);
4940 * The filesystem at hand may be idle with free vnodes stored in the
4941 * batch. Return them instead of letting them stay there indefinitely.
4943 vfs_periodic(mp, MNT_NOWAIT);
4944 error = VFS_SYNC(mp, MNT_LAZY);
4945 curthread_pflags_restore(save);
4946 vn_finished_write(mp);
4952 * The syncer vnode is no referenced.
4955 sync_inactive(struct vop_inactive_args *ap)
4963 * The syncer vnode is no longer needed and is being decommissioned.
4965 * Modifications to the worklist must be protected by sync_mtx.
4968 sync_reclaim(struct vop_reclaim_args *ap)
4970 struct vnode *vp = ap->a_vp;
4975 mtx_lock(&sync_mtx);
4976 if (vp->v_mount->mnt_syncer == vp)
4977 vp->v_mount->mnt_syncer = NULL;
4978 if (bo->bo_flag & BO_ONWORKLST) {
4979 LIST_REMOVE(bo, bo_synclist);
4980 syncer_worklist_len--;
4982 bo->bo_flag &= ~BO_ONWORKLST;
4984 mtx_unlock(&sync_mtx);
4991 vn_need_pageq_flush(struct vnode *vp)
4993 struct vm_object *obj;
4996 MPASS(mtx_owned(VI_MTX(vp)));
4998 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
4999 vm_object_mightbedirty(obj))
5005 * Check if vnode represents a disk device
5008 vn_isdisk(struct vnode *vp, int *errp)
5012 if (vp->v_type != VCHR) {
5018 if (vp->v_rdev == NULL)
5020 else if (vp->v_rdev->si_devsw == NULL)
5022 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5028 return (error == 0);
5032 * Common filesystem object access control check routine. Accepts a
5033 * vnode's type, "mode", uid and gid, requested access mode, credentials,
5034 * and optional call-by-reference privused argument allowing vaccess()
5035 * to indicate to the caller whether privilege was used to satisfy the
5036 * request (obsoleted). Returns 0 on success, or an errno on failure.
5039 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5040 accmode_t accmode, struct ucred *cred, int *privused)
5042 accmode_t dac_granted;
5043 accmode_t priv_granted;
5045 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5046 ("invalid bit in accmode"));
5047 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5048 ("VAPPEND without VWRITE"));
5051 * Look for a normal, non-privileged way to access the file/directory
5052 * as requested. If it exists, go with that.
5055 if (privused != NULL)
5060 /* Check the owner. */
5061 if (cred->cr_uid == file_uid) {
5062 dac_granted |= VADMIN;
5063 if (file_mode & S_IXUSR)
5064 dac_granted |= VEXEC;
5065 if (file_mode & S_IRUSR)
5066 dac_granted |= VREAD;
5067 if (file_mode & S_IWUSR)
5068 dac_granted |= (VWRITE | VAPPEND);
5070 if ((accmode & dac_granted) == accmode)
5076 /* Otherwise, check the groups (first match) */
5077 if (groupmember(file_gid, cred)) {
5078 if (file_mode & S_IXGRP)
5079 dac_granted |= VEXEC;
5080 if (file_mode & S_IRGRP)
5081 dac_granted |= VREAD;
5082 if (file_mode & S_IWGRP)
5083 dac_granted |= (VWRITE | VAPPEND);
5085 if ((accmode & dac_granted) == accmode)
5091 /* Otherwise, check everyone else. */
5092 if (file_mode & S_IXOTH)
5093 dac_granted |= VEXEC;
5094 if (file_mode & S_IROTH)
5095 dac_granted |= VREAD;
5096 if (file_mode & S_IWOTH)
5097 dac_granted |= (VWRITE | VAPPEND);
5098 if ((accmode & dac_granted) == accmode)
5103 * Build a privilege mask to determine if the set of privileges
5104 * satisfies the requirements when combined with the granted mask
5105 * from above. For each privilege, if the privilege is required,
5106 * bitwise or the request type onto the priv_granted mask.
5112 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5113 * requests, instead of PRIV_VFS_EXEC.
5115 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5116 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5117 priv_granted |= VEXEC;
5120 * Ensure that at least one execute bit is on. Otherwise,
5121 * a privileged user will always succeed, and we don't want
5122 * this to happen unless the file really is executable.
5124 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5125 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5126 !priv_check_cred(cred, PRIV_VFS_EXEC))
5127 priv_granted |= VEXEC;
5130 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5131 !priv_check_cred(cred, PRIV_VFS_READ))
5132 priv_granted |= VREAD;
5134 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5135 !priv_check_cred(cred, PRIV_VFS_WRITE))
5136 priv_granted |= (VWRITE | VAPPEND);
5138 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5139 !priv_check_cred(cred, PRIV_VFS_ADMIN))
5140 priv_granted |= VADMIN;
5142 if ((accmode & (priv_granted | dac_granted)) == accmode) {
5143 /* XXX audit: privilege used */
5144 if (privused != NULL)
5149 return ((accmode & VADMIN) ? EPERM : EACCES);
5153 * Credential check based on process requesting service, and per-attribute
5157 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5158 struct thread *td, accmode_t accmode)
5162 * Kernel-invoked always succeeds.
5168 * Do not allow privileged processes in jail to directly manipulate
5169 * system attributes.
5171 switch (attrnamespace) {
5172 case EXTATTR_NAMESPACE_SYSTEM:
5173 /* Potentially should be: return (EPERM); */
5174 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5175 case EXTATTR_NAMESPACE_USER:
5176 return (VOP_ACCESS(vp, accmode, cred, td));
5182 #ifdef DEBUG_VFS_LOCKS
5184 * This only exists to suppress warnings from unlocked specfs accesses. It is
5185 * no longer ok to have an unlocked VFS.
5187 #define IGNORE_LOCK(vp) (KERNEL_PANICKED() || (vp) == NULL || \
5188 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
5190 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
5191 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5192 "Drop into debugger on lock violation");
5194 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
5195 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5196 0, "Check for interlock across VOPs");
5198 int vfs_badlock_print = 1; /* Print lock violations. */
5199 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5200 0, "Print lock violations");
5202 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
5203 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5204 0, "Print vnode details on lock violations");
5207 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
5208 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5209 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5213 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5217 if (vfs_badlock_backtrace)
5220 if (vfs_badlock_vnode)
5221 vn_printf(vp, "vnode ");
5222 if (vfs_badlock_print)
5223 printf("%s: %p %s\n", str, (void *)vp, msg);
5224 if (vfs_badlock_ddb)
5225 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5229 assert_vi_locked(struct vnode *vp, const char *str)
5232 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5233 vfs_badlock("interlock is not locked but should be", str, vp);
5237 assert_vi_unlocked(struct vnode *vp, const char *str)
5240 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5241 vfs_badlock("interlock is locked but should not be", str, vp);
5245 assert_vop_locked(struct vnode *vp, const char *str)
5249 if (!IGNORE_LOCK(vp)) {
5250 locked = VOP_ISLOCKED(vp);
5251 if (locked == 0 || locked == LK_EXCLOTHER)
5252 vfs_badlock("is not locked but should be", str, vp);
5257 assert_vop_unlocked(struct vnode *vp, const char *str)
5260 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5261 vfs_badlock("is locked but should not be", str, vp);
5265 assert_vop_elocked(struct vnode *vp, const char *str)
5268 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5269 vfs_badlock("is not exclusive locked but should be", str, vp);
5271 #endif /* DEBUG_VFS_LOCKS */
5274 vop_rename_fail(struct vop_rename_args *ap)
5277 if (ap->a_tvp != NULL)
5279 if (ap->a_tdvp == ap->a_tvp)
5288 vop_rename_pre(void *ap)
5290 struct vop_rename_args *a = ap;
5292 #ifdef DEBUG_VFS_LOCKS
5294 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5295 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5296 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5297 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5299 /* Check the source (from). */
5300 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5301 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5302 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5303 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5304 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5306 /* Check the target. */
5308 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5309 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5311 if (a->a_tdvp != a->a_fdvp)
5313 if (a->a_tvp != a->a_fvp)
5320 #ifdef DEBUG_VFS_LOCKS
5322 vop_strategy_pre(void *ap)
5324 struct vop_strategy_args *a;
5331 * Cluster ops lock their component buffers but not the IO container.
5333 if ((bp->b_flags & B_CLUSTER) != 0)
5336 if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5337 if (vfs_badlock_print)
5339 "VOP_STRATEGY: bp is not locked but should be\n");
5340 if (vfs_badlock_ddb)
5341 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5346 vop_lock_pre(void *ap)
5348 struct vop_lock1_args *a = ap;
5350 if ((a->a_flags & LK_INTERLOCK) == 0)
5351 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5353 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5357 vop_lock_post(void *ap, int rc)
5359 struct vop_lock1_args *a = ap;
5361 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5362 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5363 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5367 vop_unlock_pre(void *ap)
5369 struct vop_unlock_args *a = ap;
5371 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5375 vop_unlock_post(void *ap, int rc)
5381 vop_need_inactive_pre(void *ap)
5383 struct vop_need_inactive_args *a = ap;
5385 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5389 vop_need_inactive_post(void *ap, int rc)
5391 struct vop_need_inactive_args *a = ap;
5393 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5398 vop_create_post(void *ap, int rc)
5400 struct vop_create_args *a = ap;
5403 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5407 vop_deleteextattr_post(void *ap, int rc)
5409 struct vop_deleteextattr_args *a = ap;
5412 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5416 vop_link_post(void *ap, int rc)
5418 struct vop_link_args *a = ap;
5421 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
5422 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
5427 vop_mkdir_post(void *ap, int rc)
5429 struct vop_mkdir_args *a = ap;
5432 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5436 vop_mknod_post(void *ap, int rc)
5438 struct vop_mknod_args *a = ap;
5441 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5445 vop_reclaim_post(void *ap, int rc)
5447 struct vop_reclaim_args *a = ap;
5450 VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
5454 vop_remove_post(void *ap, int rc)
5456 struct vop_remove_args *a = ap;
5459 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5460 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5465 vop_rename_post(void *ap, int rc)
5467 struct vop_rename_args *a = ap;
5472 if (a->a_fdvp == a->a_tdvp) {
5473 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5475 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5476 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5478 hint |= NOTE_EXTEND;
5479 if (a->a_fvp->v_type == VDIR)
5481 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5483 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5484 a->a_tvp->v_type == VDIR)
5486 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5489 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5491 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5493 if (a->a_tdvp != a->a_fdvp)
5495 if (a->a_tvp != a->a_fvp)
5503 vop_rmdir_post(void *ap, int rc)
5505 struct vop_rmdir_args *a = ap;
5508 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5509 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5514 vop_setattr_post(void *ap, int rc)
5516 struct vop_setattr_args *a = ap;
5519 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5523 vop_setextattr_post(void *ap, int rc)
5525 struct vop_setextattr_args *a = ap;
5528 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5532 vop_symlink_post(void *ap, int rc)
5534 struct vop_symlink_args *a = ap;
5537 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5541 vop_open_post(void *ap, int rc)
5543 struct vop_open_args *a = ap;
5546 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
5550 vop_close_post(void *ap, int rc)
5552 struct vop_close_args *a = ap;
5554 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
5555 !VN_IS_DOOMED(a->a_vp))) {
5556 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
5557 NOTE_CLOSE_WRITE : NOTE_CLOSE);
5562 vop_read_post(void *ap, int rc)
5564 struct vop_read_args *a = ap;
5567 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5571 vop_readdir_post(void *ap, int rc)
5573 struct vop_readdir_args *a = ap;
5576 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5579 static struct knlist fs_knlist;
5582 vfs_event_init(void *arg)
5584 knlist_init_mtx(&fs_knlist, NULL);
5586 /* XXX - correct order? */
5587 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
5590 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
5593 KNOTE_UNLOCKED(&fs_knlist, event);
5596 static int filt_fsattach(struct knote *kn);
5597 static void filt_fsdetach(struct knote *kn);
5598 static int filt_fsevent(struct knote *kn, long hint);
5600 struct filterops fs_filtops = {
5602 .f_attach = filt_fsattach,
5603 .f_detach = filt_fsdetach,
5604 .f_event = filt_fsevent
5608 filt_fsattach(struct knote *kn)
5611 kn->kn_flags |= EV_CLEAR;
5612 knlist_add(&fs_knlist, kn, 0);
5617 filt_fsdetach(struct knote *kn)
5620 knlist_remove(&fs_knlist, kn, 0);
5624 filt_fsevent(struct knote *kn, long hint)
5627 kn->kn_fflags |= hint;
5628 return (kn->kn_fflags != 0);
5632 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
5638 error = SYSCTL_IN(req, &vc, sizeof(vc));
5641 if (vc.vc_vers != VFS_CTL_VERS1)
5643 mp = vfs_getvfs(&vc.vc_fsid);
5646 /* ensure that a specific sysctl goes to the right filesystem. */
5647 if (strcmp(vc.vc_fstypename, "*") != 0 &&
5648 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
5652 VCTLTOREQ(&vc, req);
5653 error = VFS_SYSCTL(mp, vc.vc_op, req);
5658 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
5659 NULL, 0, sysctl_vfs_ctl, "",
5663 * Function to initialize a va_filerev field sensibly.
5664 * XXX: Wouldn't a random number make a lot more sense ??
5667 init_va_filerev(void)
5672 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
5675 static int filt_vfsread(struct knote *kn, long hint);
5676 static int filt_vfswrite(struct knote *kn, long hint);
5677 static int filt_vfsvnode(struct knote *kn, long hint);
5678 static void filt_vfsdetach(struct knote *kn);
5679 static struct filterops vfsread_filtops = {
5681 .f_detach = filt_vfsdetach,
5682 .f_event = filt_vfsread
5684 static struct filterops vfswrite_filtops = {
5686 .f_detach = filt_vfsdetach,
5687 .f_event = filt_vfswrite
5689 static struct filterops vfsvnode_filtops = {
5691 .f_detach = filt_vfsdetach,
5692 .f_event = filt_vfsvnode
5696 vfs_knllock(void *arg)
5698 struct vnode *vp = arg;
5700 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5704 vfs_knlunlock(void *arg)
5706 struct vnode *vp = arg;
5712 vfs_knl_assert_locked(void *arg)
5714 #ifdef DEBUG_VFS_LOCKS
5715 struct vnode *vp = arg;
5717 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
5722 vfs_knl_assert_unlocked(void *arg)
5724 #ifdef DEBUG_VFS_LOCKS
5725 struct vnode *vp = arg;
5727 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
5732 vfs_kqfilter(struct vop_kqfilter_args *ap)
5734 struct vnode *vp = ap->a_vp;
5735 struct knote *kn = ap->a_kn;
5738 switch (kn->kn_filter) {
5740 kn->kn_fop = &vfsread_filtops;
5743 kn->kn_fop = &vfswrite_filtops;
5746 kn->kn_fop = &vfsvnode_filtops;
5752 kn->kn_hook = (caddr_t)vp;
5755 if (vp->v_pollinfo == NULL)
5757 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5759 knlist_add(knl, kn, 0);
5765 * Detach knote from vnode
5768 filt_vfsdetach(struct knote *kn)
5770 struct vnode *vp = (struct vnode *)kn->kn_hook;
5772 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
5773 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
5779 filt_vfsread(struct knote *kn, long hint)
5781 struct vnode *vp = (struct vnode *)kn->kn_hook;
5786 * filesystem is gone, so set the EOF flag and schedule
5787 * the knote for deletion.
5789 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5791 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5796 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
5800 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
5801 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
5808 filt_vfswrite(struct knote *kn, long hint)
5810 struct vnode *vp = (struct vnode *)kn->kn_hook;
5815 * filesystem is gone, so set the EOF flag and schedule
5816 * the knote for deletion.
5818 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
5819 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5827 filt_vfsvnode(struct knote *kn, long hint)
5829 struct vnode *vp = (struct vnode *)kn->kn_hook;
5833 if (kn->kn_sfflags & hint)
5834 kn->kn_fflags |= hint;
5835 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5836 kn->kn_flags |= EV_EOF;
5840 res = (kn->kn_fflags != 0);
5846 * Returns whether the directory is empty or not.
5847 * If it is empty, the return value is 0; otherwise
5848 * the return value is an error value (which may
5852 vfs_emptydir(struct vnode *vp)
5856 struct dirent *dirent, *dp, *endp;
5862 ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
5864 dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
5865 iov.iov_base = dirent;
5866 iov.iov_len = sizeof(struct dirent);
5871 uio.uio_resid = sizeof(struct dirent);
5872 uio.uio_segflg = UIO_SYSSPACE;
5873 uio.uio_rw = UIO_READ;
5874 uio.uio_td = curthread;
5876 while (eof == 0 && error == 0) {
5877 error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
5881 endp = (void *)((uint8_t *)dirent +
5882 sizeof(struct dirent) - uio.uio_resid);
5883 for (dp = dirent; dp < endp;
5884 dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
5885 if (dp->d_type == DT_WHT)
5887 if (dp->d_namlen == 0)
5889 if (dp->d_type != DT_DIR &&
5890 dp->d_type != DT_UNKNOWN) {
5894 if (dp->d_namlen > 2) {
5898 if (dp->d_namlen == 1 &&
5899 dp->d_name[0] != '.') {
5903 if (dp->d_namlen == 2 &&
5904 dp->d_name[1] != '.') {
5908 uio.uio_resid = sizeof(struct dirent);
5911 free(dirent, M_TEMP);
5916 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
5920 if (dp->d_reclen > ap->a_uio->uio_resid)
5921 return (ENAMETOOLONG);
5922 error = uiomove(dp, dp->d_reclen, ap->a_uio);
5924 if (ap->a_ncookies != NULL) {
5925 if (ap->a_cookies != NULL)
5926 free(ap->a_cookies, M_TEMP);
5927 ap->a_cookies = NULL;
5928 *ap->a_ncookies = 0;
5932 if (ap->a_ncookies == NULL)
5935 KASSERT(ap->a_cookies,
5936 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
5938 *ap->a_cookies = realloc(*ap->a_cookies,
5939 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
5940 (*ap->a_cookies)[*ap->a_ncookies] = off;
5941 *ap->a_ncookies += 1;
5946 * Mark for update the access time of the file if the filesystem
5947 * supports VOP_MARKATIME. This functionality is used by execve and
5948 * mmap, so we want to avoid the I/O implied by directly setting
5949 * va_atime for the sake of efficiency.
5952 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
5957 ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
5958 if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
5959 (void)VOP_MARKATIME(vp);
5963 * The purpose of this routine is to remove granularity from accmode_t,
5964 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
5965 * VADMIN and VAPPEND.
5967 * If it returns 0, the caller is supposed to continue with the usual
5968 * access checks using 'accmode' as modified by this routine. If it
5969 * returns nonzero value, the caller is supposed to return that value
5972 * Note that after this routine runs, accmode may be zero.
5975 vfs_unixify_accmode(accmode_t *accmode)
5978 * There is no way to specify explicit "deny" rule using
5979 * file mode or POSIX.1e ACLs.
5981 if (*accmode & VEXPLICIT_DENY) {
5987 * None of these can be translated into usual access bits.
5988 * Also, the common case for NFSv4 ACLs is to not contain
5989 * either of these bits. Caller should check for VWRITE
5990 * on the containing directory instead.
5992 if (*accmode & (VDELETE_CHILD | VDELETE))
5995 if (*accmode & VADMIN_PERMS) {
5996 *accmode &= ~VADMIN_PERMS;
6001 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6002 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6004 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6010 * Clear out a doomed vnode (if any) and replace it with a new one as long
6011 * as the fs is not being unmounted. Return the root vnode to the caller.
6013 static int __noinline
6014 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6020 if (mp->mnt_rootvnode != NULL) {
6022 vp = mp->mnt_rootvnode;
6024 if (!VN_IS_DOOMED(vp)) {
6027 error = vn_lock(vp, flags);
6036 * Clear the old one.
6038 mp->mnt_rootvnode = NULL;
6043 * Paired with a fence in vfs_op_thread_exit().
6045 atomic_thread_fence_acq();
6046 vfs_op_barrier_wait(mp);
6050 error = VFS_CACHEDROOT(mp, flags, vpp);
6053 if (mp->mnt_vfs_ops == 0) {
6055 if (mp->mnt_vfs_ops != 0) {
6059 if (mp->mnt_rootvnode == NULL) {
6061 mp->mnt_rootvnode = *vpp;
6063 if (mp->mnt_rootvnode != *vpp) {
6064 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6065 panic("%s: mismatch between vnode returned "
6066 " by VFS_CACHEDROOT and the one cached "
6068 __func__, *vpp, mp->mnt_rootvnode);
6078 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6083 if (!vfs_op_thread_enter(mp))
6084 return (vfs_cache_root_fallback(mp, flags, vpp));
6085 vp = (struct vnode *)atomic_load_ptr(&mp->mnt_rootvnode);
6086 if (vp == NULL || VN_IS_DOOMED(vp)) {
6087 vfs_op_thread_exit(mp);
6088 return (vfs_cache_root_fallback(mp, flags, vpp));
6091 vfs_op_thread_exit(mp);
6092 error = vn_lock(vp, flags);
6095 return (vfs_cache_root_fallback(mp, flags, vpp));
6102 vfs_cache_root_clear(struct mount *mp)
6107 * ops > 0 guarantees there is nobody who can see this vnode
6109 MPASS(mp->mnt_vfs_ops > 0);
6110 vp = mp->mnt_rootvnode;
6111 mp->mnt_rootvnode = NULL;
6116 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6119 MPASS(mp->mnt_vfs_ops > 0);
6121 mp->mnt_rootvnode = vp;
6125 * These are helper functions for filesystems to traverse all
6126 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6128 * This interface replaces MNT_VNODE_FOREACH.
6132 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6137 kern_yield(PRI_USER);
6139 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6140 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6141 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6142 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6143 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6146 if (VN_IS_DOOMED(vp)) {
6153 __mnt_vnode_markerfree_all(mvp, mp);
6154 /* MNT_IUNLOCK(mp); -- done in above function */
6155 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6158 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6159 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6165 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6169 *mvp = vn_alloc_marker(mp);
6173 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6174 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6175 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6178 if (VN_IS_DOOMED(vp)) {
6187 vn_free_marker(*mvp);
6191 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6197 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6205 mtx_assert(MNT_MTX(mp), MA_OWNED);
6207 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6208 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6211 vn_free_marker(*mvp);
6216 * These are helper functions for filesystems to traverse their
6217 * lazy vnodes. See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6220 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6223 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6228 vn_free_marker(*mvp);
6233 * Relock the mp mount vnode list lock with the vp vnode interlock in the
6234 * conventional lock order during mnt_vnode_next_lazy iteration.
6236 * On entry, the mount vnode list lock is held and the vnode interlock is not.
6237 * The list lock is dropped and reacquired. On success, both locks are held.
6238 * On failure, the mount vnode list lock is held but the vnode interlock is
6239 * not, and the procedure may have yielded.
6242 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6246 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6247 TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6248 ("%s: bad marker", __func__));
6249 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6250 ("%s: inappropriate vnode", __func__));
6251 ASSERT_VI_UNLOCKED(vp, __func__);
6252 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6254 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6255 TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6258 mtx_unlock(&mp->mnt_listmtx);
6260 if (VN_IS_DOOMED(vp)) {
6261 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
6264 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
6266 * Since we had a period with no locks held we may be the last
6267 * remaining user, in which case there is nothing to do.
6269 if (!refcount_release_if_not_last(&vp->v_holdcnt))
6271 mtx_lock(&mp->mnt_listmtx);
6276 mtx_lock(&mp->mnt_listmtx);
6280 static struct vnode *
6281 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6286 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6287 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6289 vp = TAILQ_NEXT(*mvp, v_lazylist);
6290 while (vp != NULL) {
6291 if (vp->v_type == VMARKER) {
6292 vp = TAILQ_NEXT(vp, v_lazylist);
6296 * See if we want to process the vnode. Note we may encounter a
6297 * long string of vnodes we don't care about and hog the list
6298 * as a result. Check for it and requeue the marker.
6300 VNPASS(!VN_IS_DOOMED(vp), vp);
6301 if (!cb(vp, cbarg)) {
6302 if (!should_yield()) {
6303 vp = TAILQ_NEXT(vp, v_lazylist);
6306 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6308 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6310 mtx_unlock(&mp->mnt_listmtx);
6311 kern_yield(PRI_USER);
6312 mtx_lock(&mp->mnt_listmtx);
6316 * Try-lock because this is the wrong lock order.
6318 if (!VI_TRYLOCK(vp) &&
6319 !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6321 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6322 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6323 ("alien vnode on the lazy list %p %p", vp, mp));
6324 VNPASS(vp->v_mount == mp, vp);
6325 VNPASS(!VN_IS_DOOMED(vp), vp);
6328 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6330 /* Check if we are done */
6332 mtx_unlock(&mp->mnt_listmtx);
6333 mnt_vnode_markerfree_lazy(mvp, mp);
6336 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6337 mtx_unlock(&mp->mnt_listmtx);
6338 ASSERT_VI_LOCKED(vp, "lazy iter");
6343 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6348 kern_yield(PRI_USER);
6349 mtx_lock(&mp->mnt_listmtx);
6350 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6354 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6359 if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
6362 *mvp = vn_alloc_marker(mp);
6367 mtx_lock(&mp->mnt_listmtx);
6368 vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6370 mtx_unlock(&mp->mnt_listmtx);
6371 mnt_vnode_markerfree_lazy(mvp, mp);
6374 TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6375 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6379 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6385 mtx_lock(&mp->mnt_listmtx);
6386 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6387 mtx_unlock(&mp->mnt_listmtx);
6388 mnt_vnode_markerfree_lazy(mvp, mp);