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>
54 #include <sys/capsicum.h>
55 #include <sys/condvar.h>
57 #include <sys/counter.h>
58 #include <sys/dirent.h>
59 #include <sys/event.h>
60 #include <sys/eventhandler.h>
61 #include <sys/extattr.h>
63 #include <sys/fcntl.h>
66 #include <sys/kernel.h>
67 #include <sys/kthread.h>
69 #include <sys/lockf.h>
70 #include <sys/malloc.h>
71 #include <sys/mount.h>
72 #include <sys/namei.h>
73 #include <sys/pctrie.h>
75 #include <sys/reboot.h>
76 #include <sys/refcount.h>
77 #include <sys/rwlock.h>
78 #include <sys/sched.h>
79 #include <sys/sleepqueue.h>
83 #include <sys/sysctl.h>
84 #include <sys/syslog.h>
85 #include <sys/vmmeter.h>
86 #include <sys/vnode.h>
87 #include <sys/watchdog.h>
89 #include <machine/stdarg.h>
91 #include <security/mac/mac_framework.h>
94 #include <vm/vm_object.h>
95 #include <vm/vm_extern.h>
97 #include <vm/vm_map.h>
98 #include <vm/vm_page.h>
99 #include <vm/vm_kern.h>
106 static void delmntque(struct vnode *vp);
107 static int flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
108 int slpflag, int slptimeo);
109 static void syncer_shutdown(void *arg, int howto);
110 static int vtryrecycle(struct vnode *vp);
111 static void v_init_counters(struct vnode *);
112 static void vn_seqc_init(struct vnode *);
113 static void vn_seqc_write_end_free(struct vnode *vp);
114 static void vgonel(struct vnode *);
115 static bool vhold_recycle_free(struct vnode *);
116 static void vfs_knllock(void *arg);
117 static void vfs_knlunlock(void *arg);
118 static void vfs_knl_assert_lock(void *arg, int what);
119 static void destroy_vpollinfo(struct vpollinfo *vi);
120 static int v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
121 daddr_t startlbn, daddr_t endlbn);
122 static void vnlru_recalc(void);
125 * These fences are intended for cases where some synchronization is
126 * needed between access of v_iflags and lockless vnode refcount (v_holdcnt
127 * and v_usecount) updates. Access to v_iflags is generally synchronized
128 * by the interlock, but we have some internal assertions that check vnode
129 * flags without acquiring the lock. Thus, these fences are INVARIANTS-only
133 #define VNODE_REFCOUNT_FENCE_ACQ() atomic_thread_fence_acq()
134 #define VNODE_REFCOUNT_FENCE_REL() atomic_thread_fence_rel()
136 #define VNODE_REFCOUNT_FENCE_ACQ()
137 #define VNODE_REFCOUNT_FENCE_REL()
141 * Number of vnodes in existence. Increased whenever getnewvnode()
142 * allocates a new vnode, decreased in vdropl() for VIRF_DOOMED vnode.
144 static u_long __exclusive_cache_line numvnodes;
146 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
147 "Number of vnodes in existence");
149 static counter_u64_t vnodes_created;
150 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
151 "Number of vnodes created by getnewvnode");
154 * Conversion tables for conversion from vnode types to inode formats
157 enum vtype iftovt_tab[16] = {
158 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
159 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
161 int vttoif_tab[10] = {
162 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
163 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
167 * List of allocates vnodes in the system.
169 static TAILQ_HEAD(freelst, vnode) vnode_list;
170 static struct vnode *vnode_list_free_marker;
171 static struct vnode *vnode_list_reclaim_marker;
174 * "Free" vnode target. Free vnodes are rarely completely free, but are
175 * just ones that are cheap to recycle. Usually they are for files which
176 * have been stat'd but not read; these usually have inode and namecache
177 * data attached to them. This target is the preferred minimum size of a
178 * sub-cache consisting mostly of such files. The system balances the size
179 * of this sub-cache with its complement to try to prevent either from
180 * thrashing while the other is relatively inactive. The targets express
181 * a preference for the best balance.
183 * "Above" this target there are 2 further targets (watermarks) related
184 * to recyling of free vnodes. In the best-operating case, the cache is
185 * exactly full, the free list has size between vlowat and vhiwat above the
186 * free target, and recycling from it and normal use maintains this state.
187 * Sometimes the free list is below vlowat or even empty, but this state
188 * is even better for immediate use provided the cache is not full.
189 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
190 * ones) to reach one of these states. The watermarks are currently hard-
191 * coded as 4% and 9% of the available space higher. These and the default
192 * of 25% for wantfreevnodes are too large if the memory size is large.
193 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
194 * whenever vnlru_proc() becomes active.
196 static long wantfreevnodes;
197 static long __exclusive_cache_line freevnodes;
198 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
199 &freevnodes, 0, "Number of \"free\" vnodes");
200 static long freevnodes_old;
202 static counter_u64_t recycles_count;
203 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
204 "Number of vnodes recycled to meet vnode cache targets");
206 static counter_u64_t recycles_free_count;
207 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD, &recycles_free_count,
208 "Number of free vnodes recycled to meet vnode cache targets");
210 static counter_u64_t deferred_inact;
211 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, deferred_inact, CTLFLAG_RD, &deferred_inact,
212 "Number of times inactive processing was deferred");
214 /* To keep more than one thread at a time from running vfs_getnewfsid */
215 static struct mtx mntid_mtx;
218 * Lock for any access to the following:
223 static struct mtx __exclusive_cache_line vnode_list_mtx;
225 /* Publicly exported FS */
226 struct nfs_public nfs_pub;
228 static uma_zone_t buf_trie_zone;
229 static smr_t buf_trie_smr;
231 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
232 static uma_zone_t vnode_zone;
233 MALLOC_DEFINE(M_VNODEPOLL, "VN POLL", "vnode poll");
235 __read_frequently smr_t vfs_smr;
238 * The workitem queue.
240 * It is useful to delay writes of file data and filesystem metadata
241 * for tens of seconds so that quickly created and deleted files need
242 * not waste disk bandwidth being created and removed. To realize this,
243 * we append vnodes to a "workitem" queue. When running with a soft
244 * updates implementation, most pending metadata dependencies should
245 * not wait for more than a few seconds. Thus, mounted on block devices
246 * are delayed only about a half the time that file data is delayed.
247 * Similarly, directory updates are more critical, so are only delayed
248 * about a third the time that file data is delayed. Thus, there are
249 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
250 * one each second (driven off the filesystem syncer process). The
251 * syncer_delayno variable indicates the next queue that is to be processed.
252 * Items that need to be processed soon are placed in this queue:
254 * syncer_workitem_pending[syncer_delayno]
256 * A delay of fifteen seconds is done by placing the request fifteen
257 * entries later in the queue:
259 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
262 static int syncer_delayno;
263 static long syncer_mask;
264 LIST_HEAD(synclist, bufobj);
265 static struct synclist *syncer_workitem_pending;
267 * The sync_mtx protects:
272 * syncer_workitem_pending
273 * syncer_worklist_len
276 static struct mtx sync_mtx;
277 static struct cv sync_wakeup;
279 #define SYNCER_MAXDELAY 32
280 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
281 static int syncdelay = 30; /* max time to delay syncing data */
282 static int filedelay = 30; /* time to delay syncing files */
283 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
284 "Time to delay syncing files (in seconds)");
285 static int dirdelay = 29; /* time to delay syncing directories */
286 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
287 "Time to delay syncing directories (in seconds)");
288 static int metadelay = 28; /* time to delay syncing metadata */
289 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
290 "Time to delay syncing metadata (in seconds)");
291 static int rushjob; /* number of slots to run ASAP */
292 static int stat_rush_requests; /* number of times I/O speeded up */
293 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
294 "Number of times I/O speeded up (rush requests)");
296 #define VDBATCH_SIZE 8
301 struct vnode *tab[VDBATCH_SIZE];
303 DPCPU_DEFINE_STATIC(struct vdbatch, vd);
305 static void vdbatch_dequeue(struct vnode *vp);
308 * When shutting down the syncer, run it at four times normal speed.
310 #define SYNCER_SHUTDOWN_SPEEDUP 4
311 static int sync_vnode_count;
312 static int syncer_worklist_len;
313 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
316 /* Target for maximum number of vnodes. */
317 u_long desiredvnodes;
318 static u_long gapvnodes; /* gap between wanted and desired */
319 static u_long vhiwat; /* enough extras after expansion */
320 static u_long vlowat; /* minimal extras before expansion */
321 static u_long vstir; /* nonzero to stir non-free vnodes */
322 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
324 static u_long vnlru_read_freevnodes(void);
327 * Note that no attempt is made to sanitize these parameters.
330 sysctl_maxvnodes(SYSCTL_HANDLER_ARGS)
336 error = sysctl_handle_long(oidp, &val, 0, req);
337 if (error != 0 || req->newptr == NULL)
340 if (val == desiredvnodes)
342 mtx_lock(&vnode_list_mtx);
344 wantfreevnodes = desiredvnodes / 4;
346 mtx_unlock(&vnode_list_mtx);
348 * XXX There is no protection against multiple threads changing
349 * desiredvnodes at the same time. Locking above only helps vnlru and
352 vfs_hash_changesize(desiredvnodes);
353 cache_changesize(desiredvnodes);
357 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
358 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
359 "LU", "Target for maximum number of vnodes");
362 sysctl_wantfreevnodes(SYSCTL_HANDLER_ARGS)
367 val = wantfreevnodes;
368 error = sysctl_handle_long(oidp, &val, 0, req);
369 if (error != 0 || req->newptr == NULL)
372 if (val == wantfreevnodes)
374 mtx_lock(&vnode_list_mtx);
375 wantfreevnodes = val;
377 mtx_unlock(&vnode_list_mtx);
381 SYSCTL_PROC(_vfs, OID_AUTO, wantfreevnodes,
382 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
383 "LU", "Target for minimum number of \"free\" vnodes");
385 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
386 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
387 static int vnlru_nowhere;
388 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
389 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
392 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
397 unsigned long ndflags;
400 if (req->newptr == NULL)
402 if (req->newlen >= PATH_MAX)
405 buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
406 error = SYSCTL_IN(req, buf, req->newlen);
410 buf[req->newlen] = '\0';
412 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | SAVENAME;
413 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
414 if ((error = namei(&nd)) != 0)
418 if (VN_IS_DOOMED(vp)) {
420 * This vnode is being recycled. Return != 0 to let the caller
421 * know that the sysctl had no effect. Return EAGAIN because a
422 * subsequent call will likely succeed (since namei will create
423 * a new vnode if necessary)
429 counter_u64_add(recycles_count, 1);
439 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
441 struct thread *td = curthread;
447 if (req->newptr == NULL)
450 error = sysctl_handle_int(oidp, &fd, 0, req);
453 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
458 error = vn_lock(vp, LK_EXCLUSIVE);
462 counter_u64_add(recycles_count, 1);
470 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
471 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
472 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
473 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
474 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
475 sysctl_ftry_reclaim_vnode, "I",
476 "Try to reclaim a vnode by its file descriptor");
478 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
482 * Support for the bufobj clean & dirty pctrie.
485 buf_trie_alloc(struct pctrie *ptree)
487 return (uma_zalloc_smr(buf_trie_zone, M_NOWAIT));
491 buf_trie_free(struct pctrie *ptree, void *node)
493 uma_zfree_smr(buf_trie_zone, node);
495 PCTRIE_DEFINE_SMR(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free,
499 * Initialize the vnode management data structures.
501 * Reevaluate the following cap on the number of vnodes after the physical
502 * memory size exceeds 512GB. In the limit, as the physical memory size
503 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
505 #ifndef MAXVNODES_MAX
506 #define MAXVNODES_MAX (512UL * 1024 * 1024 / 64) /* 8M */
509 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
511 static struct vnode *
512 vn_alloc_marker(struct mount *mp)
516 vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
517 vp->v_type = VMARKER;
524 vn_free_marker(struct vnode *vp)
527 MPASS(vp->v_type == VMARKER);
528 free(vp, M_VNODE_MARKER);
533 vnode_ctor(void *mem, int size, void *arg __unused, int flags __unused)
535 kasan_mark(mem, size, roundup2(size, UMA_ALIGN_PTR + 1), 0);
540 vnode_dtor(void *mem, int size, void *arg __unused)
542 size_t end1, end2, off1, off2;
544 _Static_assert(offsetof(struct vnode, v_vnodelist) <
545 offsetof(struct vnode, v_dbatchcpu),
546 "KASAN marks require updating");
548 off1 = offsetof(struct vnode, v_vnodelist);
549 off2 = offsetof(struct vnode, v_dbatchcpu);
550 end1 = off1 + sizeof(((struct vnode *)NULL)->v_vnodelist);
551 end2 = off2 + sizeof(((struct vnode *)NULL)->v_dbatchcpu);
554 * Access to the v_vnodelist and v_dbatchcpu fields are permitted even
555 * after the vnode has been freed. Try to get some KASAN coverage by
556 * marking everything except those two fields as invalid. Because
557 * KASAN's tracking is not byte-granular, any preceding fields sharing
558 * the same 8-byte aligned word must also be marked valid.
561 /* Handle the area from the start until v_vnodelist... */
562 off1 = rounddown2(off1, KASAN_SHADOW_SCALE);
563 kasan_mark(mem, off1, off1, KASAN_UMA_FREED);
565 /* ... then the area between v_vnodelist and v_dbatchcpu ... */
566 off1 = roundup2(end1, KASAN_SHADOW_SCALE);
567 off2 = rounddown2(off2, KASAN_SHADOW_SCALE);
569 kasan_mark((void *)((char *)mem + off1), off2 - off1,
570 off2 - off1, KASAN_UMA_FREED);
572 /* ... and finally the area from v_dbatchcpu to the end. */
573 off2 = roundup2(end2, KASAN_SHADOW_SCALE);
574 kasan_mark((void *)((char *)mem + off2), size - off2, size - off2,
580 * Initialize a vnode as it first enters the zone.
583 vnode_init(void *mem, int size, int flags)
592 vp->v_vnlock = &vp->v_lock;
593 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
595 * By default, don't allow shared locks unless filesystems opt-in.
597 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
598 LK_NOSHARE | LK_IS_VNODE);
602 bufobj_init(&vp->v_bufobj, vp);
604 * Initialize namecache.
606 cache_vnode_init(vp);
608 * Initialize rangelocks.
610 rangelock_init(&vp->v_rl);
612 vp->v_dbatchcpu = NOCPU;
615 * Check vhold_recycle_free for an explanation.
617 vp->v_holdcnt = VHOLD_NO_SMR;
619 mtx_lock(&vnode_list_mtx);
620 TAILQ_INSERT_BEFORE(vnode_list_free_marker, vp, v_vnodelist);
621 mtx_unlock(&vnode_list_mtx);
626 * Free a vnode when it is cleared from the zone.
629 vnode_fini(void *mem, int size)
636 mtx_lock(&vnode_list_mtx);
637 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
638 mtx_unlock(&vnode_list_mtx);
639 rangelock_destroy(&vp->v_rl);
640 lockdestroy(vp->v_vnlock);
641 mtx_destroy(&vp->v_interlock);
643 rw_destroy(BO_LOCKPTR(bo));
645 kasan_mark(mem, size, size, 0);
649 * Provide the size of NFS nclnode and NFS fh for calculation of the
650 * vnode memory consumption. The size is specified directly to
651 * eliminate dependency on NFS-private header.
653 * Other filesystems may use bigger or smaller (like UFS and ZFS)
654 * private inode data, but the NFS-based estimation is ample enough.
655 * Still, we care about differences in the size between 64- and 32-bit
658 * Namecache structure size is heuristically
659 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
662 #define NFS_NCLNODE_SZ (528 + 64)
665 #define NFS_NCLNODE_SZ (360 + 32)
670 vntblinit(void *dummy __unused)
675 int cpu, physvnodes, virtvnodes;
679 * Desiredvnodes is a function of the physical memory size and the
680 * kernel's heap size. Generally speaking, it scales with the
681 * physical memory size. The ratio of desiredvnodes to the physical
682 * memory size is 1:16 until desiredvnodes exceeds 98,304.
684 * marginal ratio of desiredvnodes to the physical memory size is
685 * 1:64. However, desiredvnodes is limited by the kernel's heap
686 * size. The memory required by desiredvnodes vnodes and vm objects
687 * must not exceed 1/10th of the kernel's heap size.
689 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
690 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
691 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
692 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
693 desiredvnodes = min(physvnodes, virtvnodes);
694 if (desiredvnodes > MAXVNODES_MAX) {
696 printf("Reducing kern.maxvnodes %lu -> %lu\n",
697 desiredvnodes, MAXVNODES_MAX);
698 desiredvnodes = MAXVNODES_MAX;
700 wantfreevnodes = desiredvnodes / 4;
701 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
702 TAILQ_INIT(&vnode_list);
703 mtx_init(&vnode_list_mtx, "vnode_list", NULL, MTX_DEF);
705 * The lock is taken to appease WITNESS.
707 mtx_lock(&vnode_list_mtx);
709 mtx_unlock(&vnode_list_mtx);
710 vnode_list_free_marker = vn_alloc_marker(NULL);
711 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_free_marker, v_vnodelist);
712 vnode_list_reclaim_marker = vn_alloc_marker(NULL);
713 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_reclaim_marker, v_vnodelist);
722 vnode_zone = uma_zcreate("VNODE", sizeof(struct vnode), ctor, dtor,
723 vnode_init, vnode_fini, UMA_ALIGN_PTR, UMA_ZONE_NOKASAN);
724 uma_zone_set_smr(vnode_zone, vfs_smr);
727 * Preallocate enough nodes to support one-per buf so that
728 * we can not fail an insert. reassignbuf() callers can not
729 * tolerate the insertion failure.
731 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
732 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
733 UMA_ZONE_NOFREE | UMA_ZONE_SMR);
734 buf_trie_smr = uma_zone_get_smr(buf_trie_zone);
735 uma_prealloc(buf_trie_zone, nbuf);
737 vnodes_created = counter_u64_alloc(M_WAITOK);
738 recycles_count = counter_u64_alloc(M_WAITOK);
739 recycles_free_count = counter_u64_alloc(M_WAITOK);
740 deferred_inact = counter_u64_alloc(M_WAITOK);
743 * Initialize the filesystem syncer.
745 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
747 syncer_maxdelay = syncer_mask + 1;
748 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
749 cv_init(&sync_wakeup, "syncer");
750 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
755 vd = DPCPU_ID_PTR((cpu), vd);
756 bzero(vd, sizeof(*vd));
757 mtx_init(&vd->lock, "vdbatch", NULL, MTX_DEF);
760 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
763 * Mark a mount point as busy. Used to synchronize access and to delay
764 * unmounting. Eventually, mountlist_mtx is not released on failure.
766 * vfs_busy() is a custom lock, it can block the caller.
767 * vfs_busy() only sleeps if the unmount is active on the mount point.
768 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
769 * vnode belonging to mp.
771 * Lookup uses vfs_busy() to traverse mount points.
773 * / vnode lock A / vnode lock (/var) D
774 * /var vnode lock B /log vnode lock(/var/log) E
775 * vfs_busy lock C vfs_busy lock F
777 * Within each file system, the lock order is C->A->B and F->D->E.
779 * When traversing across mounts, the system follows that lock order:
785 * The lookup() process for namei("/var") illustrates the process:
786 * VOP_LOOKUP() obtains B while A is held
787 * vfs_busy() obtains a shared lock on F while A and B are held
788 * vput() releases lock on B
789 * vput() releases lock on A
790 * VFS_ROOT() obtains lock on D while shared lock on F is held
791 * vfs_unbusy() releases shared lock on F
792 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
793 * Attempt to lock A (instead of vp_crossmp) while D is held would
794 * violate the global order, causing deadlocks.
796 * dounmount() locks B while F is drained.
799 vfs_busy(struct mount *mp, int flags)
801 struct mount_pcpu *mpcpu;
803 MPASS((flags & ~MBF_MASK) == 0);
804 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
806 if (vfs_op_thread_enter(mp, mpcpu)) {
807 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
808 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
809 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
810 vfs_mp_count_add_pcpu(mpcpu, ref, 1);
811 vfs_mp_count_add_pcpu(mpcpu, lockref, 1);
812 vfs_op_thread_exit(mp, mpcpu);
813 if (flags & MBF_MNTLSTLOCK)
814 mtx_unlock(&mountlist_mtx);
819 vfs_assert_mount_counters(mp);
822 * If mount point is currently being unmounted, sleep until the
823 * mount point fate is decided. If thread doing the unmounting fails,
824 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
825 * that this mount point has survived the unmount attempt and vfs_busy
826 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
827 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
828 * about to be really destroyed. vfs_busy needs to release its
829 * reference on the mount point in this case and return with ENOENT,
830 * telling the caller that mount mount it tried to busy is no longer
833 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
834 KASSERT(mp->mnt_pinned_count == 0,
835 ("%s: non-zero pinned count %d with pending unmount",
836 __func__, mp->mnt_pinned_count));
837 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
840 CTR1(KTR_VFS, "%s: failed busying before sleeping",
844 if (flags & MBF_MNTLSTLOCK)
845 mtx_unlock(&mountlist_mtx);
846 mp->mnt_kern_flag |= MNTK_MWAIT;
847 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
848 if (flags & MBF_MNTLSTLOCK)
849 mtx_lock(&mountlist_mtx);
852 if (flags & MBF_MNTLSTLOCK)
853 mtx_unlock(&mountlist_mtx);
860 * Free a busy filesystem.
863 vfs_unbusy(struct mount *mp)
865 struct mount_pcpu *mpcpu;
868 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
870 if (vfs_op_thread_enter(mp, mpcpu)) {
871 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
872 vfs_mp_count_sub_pcpu(mpcpu, lockref, 1);
873 vfs_mp_count_sub_pcpu(mpcpu, ref, 1);
874 vfs_op_thread_exit(mp, mpcpu);
879 vfs_assert_mount_counters(mp);
881 c = --mp->mnt_lockref;
882 if (mp->mnt_vfs_ops == 0) {
883 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
888 vfs_dump_mount_counters(mp);
889 if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
890 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
891 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
892 mp->mnt_kern_flag &= ~MNTK_DRAINING;
893 wakeup(&mp->mnt_lockref);
899 * Lookup a mount point by filesystem identifier.
902 vfs_getvfs(fsid_t *fsid)
906 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
907 mtx_lock(&mountlist_mtx);
908 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
909 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
911 mtx_unlock(&mountlist_mtx);
915 mtx_unlock(&mountlist_mtx);
916 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
917 return ((struct mount *) 0);
921 * Lookup a mount point by filesystem identifier, busying it before
924 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
925 * cache for popular filesystem identifiers. The cache is lockess, using
926 * the fact that struct mount's are never freed. In worst case we may
927 * get pointer to unmounted or even different filesystem, so we have to
928 * check what we got, and go slow way if so.
931 vfs_busyfs(fsid_t *fsid)
933 #define FSID_CACHE_SIZE 256
934 typedef struct mount * volatile vmp_t;
935 static vmp_t cache[FSID_CACHE_SIZE];
940 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
941 hash = fsid->val[0] ^ fsid->val[1];
942 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
944 if (mp == NULL || fsidcmp(&mp->mnt_stat.f_fsid, fsid) != 0)
946 if (vfs_busy(mp, 0) != 0) {
950 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0)
956 mtx_lock(&mountlist_mtx);
957 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
958 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
959 error = vfs_busy(mp, MBF_MNTLSTLOCK);
962 mtx_unlock(&mountlist_mtx);
969 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
970 mtx_unlock(&mountlist_mtx);
971 return ((struct mount *) 0);
975 * Check if a user can access privileged mount options.
978 vfs_suser(struct mount *mp, struct thread *td)
982 if (jailed(td->td_ucred)) {
984 * If the jail of the calling thread lacks permission for
985 * this type of file system, deny immediately.
987 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
991 * If the file system was mounted outside the jail of the
992 * calling thread, deny immediately.
994 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
999 * If file system supports delegated administration, we don't check
1000 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
1001 * by the file system itself.
1002 * If this is not the user that did original mount, we check for
1003 * the PRIV_VFS_MOUNT_OWNER privilege.
1005 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
1006 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
1007 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
1014 * Get a new unique fsid. Try to make its val[0] unique, since this value
1015 * will be used to create fake device numbers for stat(). Also try (but
1016 * not so hard) make its val[0] unique mod 2^16, since some emulators only
1017 * support 16-bit device numbers. We end up with unique val[0]'s for the
1018 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
1020 * Keep in mind that several mounts may be running in parallel. Starting
1021 * the search one past where the previous search terminated is both a
1022 * micro-optimization and a defense against returning the same fsid to
1026 vfs_getnewfsid(struct mount *mp)
1028 static uint16_t mntid_base;
1033 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
1034 mtx_lock(&mntid_mtx);
1035 mtype = mp->mnt_vfc->vfc_typenum;
1036 tfsid.val[1] = mtype;
1037 mtype = (mtype & 0xFF) << 24;
1039 tfsid.val[0] = makedev(255,
1040 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
1042 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
1046 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
1047 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
1048 mtx_unlock(&mntid_mtx);
1052 * Knob to control the precision of file timestamps:
1054 * 0 = seconds only; nanoseconds zeroed.
1055 * 1 = seconds and nanoseconds, accurate within 1/HZ.
1056 * 2 = seconds and nanoseconds, truncated to microseconds.
1057 * >=3 = seconds and nanoseconds, maximum precision.
1059 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
1061 static int timestamp_precision = TSP_USEC;
1062 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
1063 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
1064 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
1065 "3+: sec + ns (max. precision))");
1068 * Get a current timestamp.
1071 vfs_timestamp(struct timespec *tsp)
1075 switch (timestamp_precision) {
1077 tsp->tv_sec = time_second;
1085 TIMEVAL_TO_TIMESPEC(&tv, tsp);
1095 * Set vnode attributes to VNOVAL
1098 vattr_null(struct vattr *vap)
1101 vap->va_type = VNON;
1102 vap->va_size = VNOVAL;
1103 vap->va_bytes = VNOVAL;
1104 vap->va_mode = VNOVAL;
1105 vap->va_nlink = VNOVAL;
1106 vap->va_uid = VNOVAL;
1107 vap->va_gid = VNOVAL;
1108 vap->va_fsid = VNOVAL;
1109 vap->va_fileid = VNOVAL;
1110 vap->va_blocksize = VNOVAL;
1111 vap->va_rdev = VNOVAL;
1112 vap->va_atime.tv_sec = VNOVAL;
1113 vap->va_atime.tv_nsec = VNOVAL;
1114 vap->va_mtime.tv_sec = VNOVAL;
1115 vap->va_mtime.tv_nsec = VNOVAL;
1116 vap->va_ctime.tv_sec = VNOVAL;
1117 vap->va_ctime.tv_nsec = VNOVAL;
1118 vap->va_birthtime.tv_sec = VNOVAL;
1119 vap->va_birthtime.tv_nsec = VNOVAL;
1120 vap->va_flags = VNOVAL;
1121 vap->va_gen = VNOVAL;
1122 vap->va_vaflags = 0;
1126 * Try to reduce the total number of vnodes.
1128 * This routine (and its user) are buggy in at least the following ways:
1129 * - all parameters were picked years ago when RAM sizes were significantly
1131 * - it can pick vnodes based on pages used by the vm object, but filesystems
1132 * like ZFS don't use it making the pick broken
1133 * - since ZFS has its own aging policy it gets partially combated by this one
1134 * - a dedicated method should be provided for filesystems to let them decide
1135 * whether the vnode should be recycled
1137 * This routine is called when we have too many vnodes. It attempts
1138 * to free <count> vnodes and will potentially free vnodes that still
1139 * have VM backing store (VM backing store is typically the cause
1140 * of a vnode blowout so we want to do this). Therefore, this operation
1141 * is not considered cheap.
1143 * A number of conditions may prevent a vnode from being reclaimed.
1144 * the buffer cache may have references on the vnode, a directory
1145 * vnode may still have references due to the namei cache representing
1146 * underlying files, or the vnode may be in active use. It is not
1147 * desirable to reuse such vnodes. These conditions may cause the
1148 * number of vnodes to reach some minimum value regardless of what
1149 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
1151 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1152 * entries if this argument is strue
1153 * @param trigger Only reclaim vnodes with fewer than this many resident
1155 * @param target How many vnodes to reclaim.
1156 * @return The number of vnodes that were reclaimed.
1159 vlrureclaim(bool reclaim_nc_src, int trigger, u_long target)
1161 struct vnode *vp, *mvp;
1163 struct vm_object *object;
1167 mtx_assert(&vnode_list_mtx, MA_OWNED);
1172 mvp = vnode_list_reclaim_marker;
1175 while (done < target) {
1176 vp = TAILQ_NEXT(vp, v_vnodelist);
1177 if (__predict_false(vp == NULL))
1180 if (__predict_false(vp->v_type == VMARKER))
1184 * If it's been deconstructed already, it's still
1185 * referenced, or it exceeds the trigger, skip it.
1186 * Also skip free vnodes. We are trying to make space
1187 * to expand the free list, not reduce it.
1189 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1190 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)))
1193 if (vp->v_type == VBAD || vp->v_type == VNON)
1196 object = atomic_load_ptr(&vp->v_object);
1197 if (object == NULL || object->resident_page_count > trigger) {
1202 * Handle races against vnode allocation. Filesystems lock the
1203 * vnode some time after it gets returned from getnewvnode,
1204 * despite type and hold count being manipulated earlier.
1205 * Resorting to checking v_mount restores guarantees present
1206 * before the global list was reworked to contain all vnodes.
1208 if (!VI_TRYLOCK(vp))
1210 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1214 if (vp->v_mount == NULL) {
1220 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1221 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1222 mtx_unlock(&vnode_list_mtx);
1224 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1226 goto next_iter_unlocked;
1228 if (VOP_LOCK(vp, LK_EXCLUSIVE|LK_NOWAIT) != 0) {
1230 vn_finished_write(mp);
1231 goto next_iter_unlocked;
1235 if (vp->v_usecount > 0 ||
1236 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1237 (vp->v_object != NULL && vp->v_object->handle == vp &&
1238 vp->v_object->resident_page_count > trigger)) {
1241 vn_finished_write(mp);
1242 goto next_iter_unlocked;
1244 counter_u64_add(recycles_count, 1);
1248 vn_finished_write(mp);
1252 kern_yield(PRI_USER);
1253 mtx_lock(&vnode_list_mtx);
1256 MPASS(vp->v_type != VMARKER);
1257 if (!should_yield())
1259 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1260 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1261 mtx_unlock(&vnode_list_mtx);
1262 kern_yield(PRI_USER);
1263 mtx_lock(&vnode_list_mtx);
1266 if (done == 0 && !retried) {
1267 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1268 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1275 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1276 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1278 "limit on vnode free requests per call to the vnlru_free routine");
1281 * Attempt to reduce the free list by the requested amount.
1284 vnlru_free_impl(int count, struct vfsops *mnt_op, struct vnode *mvp)
1290 mtx_assert(&vnode_list_mtx, MA_OWNED);
1291 if (count > max_vnlru_free)
1292 count = max_vnlru_free;
1299 vp = TAILQ_NEXT(vp, v_vnodelist);
1300 if (__predict_false(vp == NULL)) {
1301 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1302 TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1305 if (__predict_false(vp->v_type == VMARKER))
1307 if (vp->v_holdcnt > 0)
1310 * Don't recycle if our vnode is from different type
1311 * of mount point. Note that mp is type-safe, the
1312 * check does not reach unmapped address even if
1313 * vnode is reclaimed.
1315 if (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1316 mp->mnt_op != mnt_op) {
1319 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1322 if (!vhold_recycle_free(vp))
1324 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1325 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1326 mtx_unlock(&vnode_list_mtx);
1327 if (vtryrecycle(vp) == 0)
1329 mtx_lock(&vnode_list_mtx);
1332 return (ocount - count);
1336 vnlru_free_locked(int count)
1339 mtx_assert(&vnode_list_mtx, MA_OWNED);
1340 return (vnlru_free_impl(count, NULL, vnode_list_free_marker));
1344 vnlru_free_vfsops(int count, struct vfsops *mnt_op, struct vnode *mvp)
1347 MPASS(mnt_op != NULL);
1349 VNPASS(mvp->v_type == VMARKER, mvp);
1350 mtx_lock(&vnode_list_mtx);
1351 vnlru_free_impl(count, mnt_op, mvp);
1352 mtx_unlock(&vnode_list_mtx);
1356 vnlru_alloc_marker(void)
1360 mvp = vn_alloc_marker(NULL);
1361 mtx_lock(&vnode_list_mtx);
1362 TAILQ_INSERT_BEFORE(vnode_list_free_marker, mvp, v_vnodelist);
1363 mtx_unlock(&vnode_list_mtx);
1368 vnlru_free_marker(struct vnode *mvp)
1370 mtx_lock(&vnode_list_mtx);
1371 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1372 mtx_unlock(&vnode_list_mtx);
1373 vn_free_marker(mvp);
1380 mtx_assert(&vnode_list_mtx, MA_OWNED);
1381 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1382 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1383 vlowat = vhiwat / 2;
1387 * Attempt to recycle vnodes in a context that is always safe to block.
1388 * Calling vlrurecycle() from the bowels of filesystem code has some
1389 * interesting deadlock problems.
1391 static struct proc *vnlruproc;
1392 static int vnlruproc_sig;
1395 * The main freevnodes counter is only updated when threads requeue their vnode
1396 * batches. CPUs are conditionally walked to compute a more accurate total.
1398 * Limit how much of a slop are we willing to tolerate. Note: the actual value
1399 * at any given moment can still exceed slop, but it should not be by significant
1400 * margin in practice.
1402 #define VNLRU_FREEVNODES_SLOP 128
1404 static __inline void
1405 vfs_freevnodes_inc(void)
1415 static __inline void
1416 vfs_freevnodes_dec(void)
1427 vnlru_read_freevnodes(void)
1433 mtx_assert(&vnode_list_mtx, MA_OWNED);
1434 if (freevnodes > freevnodes_old)
1435 slop = freevnodes - freevnodes_old;
1437 slop = freevnodes_old - freevnodes;
1438 if (slop < VNLRU_FREEVNODES_SLOP)
1439 return (freevnodes >= 0 ? freevnodes : 0);
1440 freevnodes_old = freevnodes;
1442 vd = DPCPU_ID_PTR((cpu), vd);
1443 freevnodes_old += vd->freevnodes;
1445 return (freevnodes_old >= 0 ? freevnodes_old : 0);
1449 vnlru_under(u_long rnumvnodes, u_long limit)
1451 u_long rfreevnodes, space;
1453 if (__predict_false(rnumvnodes > desiredvnodes))
1456 space = desiredvnodes - rnumvnodes;
1457 if (space < limit) {
1458 rfreevnodes = vnlru_read_freevnodes();
1459 if (rfreevnodes > wantfreevnodes)
1460 space += rfreevnodes - wantfreevnodes;
1462 return (space < limit);
1466 vnlru_under_unlocked(u_long rnumvnodes, u_long limit)
1468 long rfreevnodes, space;
1470 if (__predict_false(rnumvnodes > desiredvnodes))
1473 space = desiredvnodes - rnumvnodes;
1474 if (space < limit) {
1475 rfreevnodes = atomic_load_long(&freevnodes);
1476 if (rfreevnodes > wantfreevnodes)
1477 space += rfreevnodes - wantfreevnodes;
1479 return (space < limit);
1486 mtx_assert(&vnode_list_mtx, MA_OWNED);
1487 if (vnlruproc_sig == 0) {
1496 u_long rnumvnodes, rfreevnodes, target;
1497 unsigned long onumvnodes;
1498 int done, force, trigger, usevnodes;
1499 bool reclaim_nc_src, want_reread;
1501 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1502 SHUTDOWN_PRI_FIRST);
1505 want_reread = false;
1507 kproc_suspend_check(vnlruproc);
1508 mtx_lock(&vnode_list_mtx);
1509 rnumvnodes = atomic_load_long(&numvnodes);
1512 force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1513 want_reread = false;
1517 * If numvnodes is too large (due to desiredvnodes being
1518 * adjusted using its sysctl, or emergency growth), first
1519 * try to reduce it by discarding from the free list.
1521 if (rnumvnodes > desiredvnodes) {
1522 vnlru_free_locked(rnumvnodes - desiredvnodes);
1523 rnumvnodes = atomic_load_long(&numvnodes);
1526 * Sleep if the vnode cache is in a good state. This is
1527 * when it is not over-full and has space for about a 4%
1528 * or 9% expansion (by growing its size or inexcessively
1529 * reducing its free list). Otherwise, try to reclaim
1530 * space for a 10% expansion.
1532 if (vstir && force == 0) {
1536 if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1538 wakeup(&vnlruproc_sig);
1539 msleep(vnlruproc, &vnode_list_mtx,
1540 PVFS|PDROP, "vlruwt", hz);
1543 rfreevnodes = vnlru_read_freevnodes();
1545 onumvnodes = rnumvnodes;
1547 * Calculate parameters for recycling. These are the same
1548 * throughout the loop to give some semblance of fairness.
1549 * The trigger point is to avoid recycling vnodes with lots
1550 * of resident pages. We aren't trying to free memory; we
1551 * are trying to recycle or at least free vnodes.
1553 if (rnumvnodes <= desiredvnodes)
1554 usevnodes = rnumvnodes - rfreevnodes;
1556 usevnodes = rnumvnodes;
1560 * The trigger value is is chosen to give a conservatively
1561 * large value to ensure that it alone doesn't prevent
1562 * making progress. The value can easily be so large that
1563 * it is effectively infinite in some congested and
1564 * misconfigured cases, and this is necessary. Normally
1565 * it is about 8 to 100 (pages), which is quite large.
1567 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1569 trigger = vsmalltrigger;
1570 reclaim_nc_src = force >= 3;
1571 target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1572 target = target / 10 + 1;
1573 done = vlrureclaim(reclaim_nc_src, trigger, target);
1574 mtx_unlock(&vnode_list_mtx);
1575 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1576 uma_reclaim(UMA_RECLAIM_DRAIN);
1578 if (force == 0 || force == 1) {
1589 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1592 kern_yield(PRI_USER);
1597 static struct kproc_desc vnlru_kp = {
1602 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1606 * Routines having to do with the management of the vnode table.
1610 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1611 * before we actually vgone(). This function must be called with the vnode
1612 * held to prevent the vnode from being returned to the free list midway
1616 vtryrecycle(struct vnode *vp)
1620 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1621 VNASSERT(vp->v_holdcnt, vp,
1622 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1624 * This vnode may found and locked via some other list, if so we
1625 * can't recycle it yet.
1627 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1629 "%s: impossible to recycle, vp %p lock is already held",
1632 return (EWOULDBLOCK);
1635 * Don't recycle if its filesystem is being suspended.
1637 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1640 "%s: impossible to recycle, cannot start the write for %p",
1646 * If we got this far, we need to acquire the interlock and see if
1647 * anyone picked up this vnode from another list. If not, we will
1648 * mark it with DOOMED via vgonel() so that anyone who does find it
1649 * will skip over it.
1652 if (vp->v_usecount) {
1655 vn_finished_write(vnmp);
1657 "%s: impossible to recycle, %p is already referenced",
1661 if (!VN_IS_DOOMED(vp)) {
1662 counter_u64_add(recycles_free_count, 1);
1667 vn_finished_write(vnmp);
1672 * Allocate a new vnode.
1674 * The operation never returns an error. Returning an error was disabled
1675 * in r145385 (dated 2005) with the following comment:
1677 * XXX Not all VFS_VGET/ffs_vget callers check returns.
1679 * Given the age of this commit (almost 15 years at the time of writing this
1680 * comment) restoring the ability to fail requires a significant audit of
1683 * The routine can try to free a vnode or stall for up to 1 second waiting for
1684 * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1686 static u_long vn_alloc_cyclecount;
1688 static struct vnode * __noinline
1689 vn_alloc_hard(struct mount *mp)
1691 u_long rnumvnodes, rfreevnodes;
1693 mtx_lock(&vnode_list_mtx);
1694 rnumvnodes = atomic_load_long(&numvnodes);
1695 if (rnumvnodes + 1 < desiredvnodes) {
1696 vn_alloc_cyclecount = 0;
1699 rfreevnodes = vnlru_read_freevnodes();
1700 if (vn_alloc_cyclecount++ >= rfreevnodes) {
1701 vn_alloc_cyclecount = 0;
1705 * Grow the vnode cache if it will not be above its target max
1706 * after growing. Otherwise, if the free list is nonempty, try
1707 * to reclaim 1 item from it before growing the cache (possibly
1708 * above its target max if the reclamation failed or is delayed).
1709 * Otherwise, wait for some space. In all cases, schedule
1710 * vnlru_proc() if we are getting short of space. The watermarks
1711 * should be chosen so that we never wait or even reclaim from
1712 * the free list to below its target minimum.
1714 if (vnlru_free_locked(1) > 0)
1716 if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1718 * Wait for space for a new vnode.
1721 msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1722 if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1723 vnlru_read_freevnodes() > 1)
1724 vnlru_free_locked(1);
1727 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1728 if (vnlru_under(rnumvnodes, vlowat))
1730 mtx_unlock(&vnode_list_mtx);
1731 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1734 static struct vnode *
1735 vn_alloc(struct mount *mp)
1739 if (__predict_false(vn_alloc_cyclecount != 0))
1740 return (vn_alloc_hard(mp));
1741 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1742 if (__predict_false(vnlru_under_unlocked(rnumvnodes, vlowat))) {
1743 atomic_subtract_long(&numvnodes, 1);
1744 return (vn_alloc_hard(mp));
1747 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1751 vn_free(struct vnode *vp)
1754 atomic_subtract_long(&numvnodes, 1);
1755 uma_zfree_smr(vnode_zone, vp);
1759 * Return the next vnode from the free list.
1762 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1767 struct lock_object *lo;
1769 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1771 KASSERT(vops->registered,
1772 ("%s: not registered vector op %p\n", __func__, vops));
1775 if (td->td_vp_reserved != NULL) {
1776 vp = td->td_vp_reserved;
1777 td->td_vp_reserved = NULL;
1781 counter_u64_add(vnodes_created, 1);
1783 * Locks are given the generic name "vnode" when created.
1784 * Follow the historic practice of using the filesystem
1785 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1787 * Locks live in a witness group keyed on their name. Thus,
1788 * when a lock is renamed, it must also move from the witness
1789 * group of its old name to the witness group of its new name.
1791 * The change only needs to be made when the vnode moves
1792 * from one filesystem type to another. We ensure that each
1793 * filesystem use a single static name pointer for its tag so
1794 * that we can compare pointers rather than doing a strcmp().
1796 lo = &vp->v_vnlock->lock_object;
1798 if (lo->lo_name != tag) {
1802 WITNESS_DESTROY(lo);
1803 WITNESS_INIT(lo, tag);
1807 * By default, don't allow shared locks unless filesystems opt-in.
1809 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1811 * Finalize various vnode identity bits.
1813 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1814 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1815 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1819 v_init_counters(vp);
1821 vp->v_bufobj.bo_ops = &buf_ops_bio;
1823 if (mp == NULL && vops != &dead_vnodeops)
1824 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1828 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1829 mac_vnode_associate_singlelabel(mp, vp);
1832 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1833 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1834 vp->v_vflag |= VV_NOKNOTE;
1838 * For the filesystems which do not use vfs_hash_insert(),
1839 * still initialize v_hash to have vfs_hash_index() useful.
1840 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1843 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1850 getnewvnode_reserve(void)
1855 MPASS(td->td_vp_reserved == NULL);
1856 td->td_vp_reserved = vn_alloc(NULL);
1860 getnewvnode_drop_reserve(void)
1865 if (td->td_vp_reserved != NULL) {
1866 vn_free(td->td_vp_reserved);
1867 td->td_vp_reserved = NULL;
1871 static void __noinline
1872 freevnode(struct vnode *vp)
1877 * The vnode has been marked for destruction, so free it.
1879 * The vnode will be returned to the zone where it will
1880 * normally remain until it is needed for another vnode. We
1881 * need to cleanup (or verify that the cleanup has already
1882 * been done) any residual data left from its current use
1883 * so as not to contaminate the freshly allocated vnode.
1885 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1887 * Paired with vgone.
1889 vn_seqc_write_end_free(vp);
1892 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1893 VNPASS(vp->v_holdcnt == VHOLD_NO_SMR, vp);
1894 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1895 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1896 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1897 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1898 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1899 ("clean blk trie not empty"));
1900 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1901 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1902 ("dirty blk trie not empty"));
1903 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1904 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1905 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1906 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1907 ("Dangling rangelock waiters"));
1908 VNASSERT((vp->v_iflag & (VI_DOINGINACT | VI_OWEINACT)) == 0, vp,
1909 ("Leaked inactivation"));
1912 mac_vnode_destroy(vp);
1914 if (vp->v_pollinfo != NULL) {
1915 destroy_vpollinfo(vp->v_pollinfo);
1916 vp->v_pollinfo = NULL;
1918 vp->v_mountedhere = NULL;
1921 vp->v_fifoinfo = NULL;
1929 * Delete from old mount point vnode list, if on one.
1932 delmntque(struct vnode *vp)
1936 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
1945 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1946 ("bad mount point vnode list size"));
1947 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1948 mp->mnt_nvnodelistsize--;
1954 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1958 vp->v_op = &dead_vnodeops;
1964 * Insert into list of vnodes for the new mount point, if available.
1967 insmntque1(struct vnode *vp, struct mount *mp,
1968 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1971 KASSERT(vp->v_mount == NULL,
1972 ("insmntque: vnode already on per mount vnode list"));
1973 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1974 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1977 * We acquire the vnode interlock early to ensure that the
1978 * vnode cannot be recycled by another process releasing a
1979 * holdcnt on it before we get it on both the vnode list
1980 * and the active vnode list. The mount mutex protects only
1981 * manipulation of the vnode list and the vnode freelist
1982 * mutex protects only manipulation of the active vnode list.
1983 * Hence the need to hold the vnode interlock throughout.
1987 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1988 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1989 mp->mnt_nvnodelistsize == 0)) &&
1990 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1999 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
2000 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
2001 ("neg mount point vnode list size"));
2002 mp->mnt_nvnodelistsize++;
2009 insmntque(struct vnode *vp, struct mount *mp)
2012 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
2016 * Flush out and invalidate all buffers associated with a bufobj
2017 * Called with the underlying object locked.
2020 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
2025 if (flags & V_SAVE) {
2026 error = bufobj_wwait(bo, slpflag, slptimeo);
2031 if (bo->bo_dirty.bv_cnt > 0) {
2034 error = BO_SYNC(bo, MNT_WAIT);
2035 } while (error == ERELOOKUP);
2039 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0) {
2046 * If you alter this loop please notice that interlock is dropped and
2047 * reacquired in flushbuflist. Special care is needed to ensure that
2048 * no race conditions occur from this.
2051 error = flushbuflist(&bo->bo_clean,
2052 flags, bo, slpflag, slptimeo);
2053 if (error == 0 && !(flags & V_CLEANONLY))
2054 error = flushbuflist(&bo->bo_dirty,
2055 flags, bo, slpflag, slptimeo);
2056 if (error != 0 && error != EAGAIN) {
2060 } while (error != 0);
2063 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
2064 * have write I/O in-progress but if there is a VM object then the
2065 * VM object can also have read-I/O in-progress.
2068 bufobj_wwait(bo, 0, 0);
2069 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
2071 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
2074 } while (bo->bo_numoutput > 0);
2078 * Destroy the copy in the VM cache, too.
2080 if (bo->bo_object != NULL &&
2081 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
2082 VM_OBJECT_WLOCK(bo->bo_object);
2083 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
2084 OBJPR_CLEANONLY : 0);
2085 VM_OBJECT_WUNLOCK(bo->bo_object);
2090 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
2091 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
2092 bo->bo_clean.bv_cnt > 0))
2093 panic("vinvalbuf: flush failed");
2094 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
2095 bo->bo_dirty.bv_cnt > 0)
2096 panic("vinvalbuf: flush dirty failed");
2103 * Flush out and invalidate all buffers associated with a vnode.
2104 * Called with the underlying object locked.
2107 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
2110 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2111 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
2112 if (vp->v_object != NULL && vp->v_object->handle != vp)
2114 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
2118 * Flush out buffers on the specified list.
2122 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
2125 struct buf *bp, *nbp;
2130 ASSERT_BO_WLOCKED(bo);
2133 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2135 * If we are flushing both V_NORMAL and V_ALT buffers then
2136 * do not skip any buffers. If we are flushing only V_NORMAL
2137 * buffers then skip buffers marked as BX_ALTDATA. If we are
2138 * flushing only V_ALT buffers then skip buffers not marked
2141 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2142 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2143 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2147 lblkno = nbp->b_lblkno;
2148 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2151 error = BUF_TIMELOCK(bp,
2152 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2153 "flushbuf", slpflag, slptimeo);
2156 return (error != ENOLCK ? error : EAGAIN);
2158 KASSERT(bp->b_bufobj == bo,
2159 ("bp %p wrong b_bufobj %p should be %p",
2160 bp, bp->b_bufobj, bo));
2162 * XXX Since there are no node locks for NFS, I
2163 * believe there is a slight chance that a delayed
2164 * write will occur while sleeping just above, so
2167 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2170 bp->b_flags |= B_ASYNC;
2173 return (EAGAIN); /* XXX: why not loop ? */
2176 bp->b_flags |= (B_INVAL | B_RELBUF);
2177 bp->b_flags &= ~B_ASYNC;
2182 nbp = gbincore(bo, lblkno);
2183 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2185 break; /* nbp invalid */
2191 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2197 ASSERT_BO_LOCKED(bo);
2199 for (lblkno = startn;;) {
2201 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2202 if (bp == NULL || bp->b_lblkno >= endn ||
2203 bp->b_lblkno < startn)
2205 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2206 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2209 if (error == ENOLCK)
2213 KASSERT(bp->b_bufobj == bo,
2214 ("bp %p wrong b_bufobj %p should be %p",
2215 bp, bp->b_bufobj, bo));
2216 lblkno = bp->b_lblkno + 1;
2217 if ((bp->b_flags & B_MANAGED) == 0)
2219 bp->b_flags |= B_RELBUF;
2221 * In the VMIO case, use the B_NOREUSE flag to hint that the
2222 * pages backing each buffer in the range are unlikely to be
2223 * reused. Dirty buffers will have the hint applied once
2224 * they've been written.
2226 if ((bp->b_flags & B_VMIO) != 0)
2227 bp->b_flags |= B_NOREUSE;
2235 * Truncate a file's buffer and pages to a specified length. This
2236 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2240 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2242 struct buf *bp, *nbp;
2246 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2247 vp, blksize, (uintmax_t)length);
2250 * Round up to the *next* lbn.
2252 startlbn = howmany(length, blksize);
2254 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2260 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2265 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2266 if (bp->b_lblkno > 0)
2269 * Since we hold the vnode lock this should only
2270 * fail if we're racing with the buf daemon.
2273 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2274 BO_LOCKPTR(bo)) == ENOLCK)
2275 goto restart_unlocked;
2277 VNASSERT((bp->b_flags & B_DELWRI), vp,
2278 ("buf(%p) on dirty queue without DELWRI", bp));
2287 bufobj_wwait(bo, 0, 0);
2289 vnode_pager_setsize(vp, length);
2295 * Invalidate the cached pages of a file's buffer within the range of block
2296 * numbers [startlbn, endlbn).
2299 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2305 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2307 start = blksize * startlbn;
2308 end = blksize * endlbn;
2312 MPASS(blksize == bo->bo_bsize);
2314 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2318 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2322 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2323 daddr_t startlbn, daddr_t endlbn)
2325 struct buf *bp, *nbp;
2328 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2329 ASSERT_BO_LOCKED(bo);
2333 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2334 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2337 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2338 BO_LOCKPTR(bo)) == ENOLCK) {
2344 bp->b_flags |= B_INVAL | B_RELBUF;
2345 bp->b_flags &= ~B_ASYNC;
2351 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2353 (nbp->b_flags & B_DELWRI) != 0))
2357 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2358 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2361 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2362 BO_LOCKPTR(bo)) == ENOLCK) {
2367 bp->b_flags |= B_INVAL | B_RELBUF;
2368 bp->b_flags &= ~B_ASYNC;
2374 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2375 (nbp->b_vp != vp) ||
2376 (nbp->b_flags & B_DELWRI) == 0))
2384 buf_vlist_remove(struct buf *bp)
2389 flags = bp->b_xflags;
2391 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2392 ASSERT_BO_WLOCKED(bp->b_bufobj);
2393 KASSERT((flags & (BX_VNDIRTY | BX_VNCLEAN)) != 0 &&
2394 (flags & (BX_VNDIRTY | BX_VNCLEAN)) != (BX_VNDIRTY | BX_VNCLEAN),
2395 ("%s: buffer %p has invalid queue state", __func__, bp));
2397 if ((flags & BX_VNDIRTY) != 0)
2398 bv = &bp->b_bufobj->bo_dirty;
2400 bv = &bp->b_bufobj->bo_clean;
2401 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2402 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2404 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2408 * Add the buffer to the sorted clean or dirty block list.
2410 * NOTE: xflags is passed as a constant, optimizing this inline function!
2413 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2419 ASSERT_BO_WLOCKED(bo);
2420 KASSERT((bo->bo_flag & BO_NOBUFS) == 0,
2421 ("buf_vlist_add: bo %p does not allow bufs", bo));
2422 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2423 ("dead bo %p", bo));
2424 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2425 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2426 bp->b_xflags |= xflags;
2427 if (xflags & BX_VNDIRTY)
2433 * Keep the list ordered. Optimize empty list insertion. Assume
2434 * we tend to grow at the tail so lookup_le should usually be cheaper
2437 if (bv->bv_cnt == 0 ||
2438 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2439 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2440 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2441 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2443 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2444 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2446 panic("buf_vlist_add: Preallocated nodes insufficient.");
2451 * Look up a buffer using the buffer tries.
2454 gbincore(struct bufobj *bo, daddr_t lblkno)
2458 ASSERT_BO_LOCKED(bo);
2459 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2462 return (BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno));
2466 * Look up a buf using the buffer tries, without the bufobj lock. This relies
2467 * on SMR for safe lookup, and bufs being in a no-free zone to provide type
2468 * stability of the result. Like other lockless lookups, the found buf may
2469 * already be invalid by the time this function returns.
2472 gbincore_unlocked(struct bufobj *bo, daddr_t lblkno)
2476 ASSERT_BO_UNLOCKED(bo);
2477 bp = BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_clean.bv_root, lblkno);
2480 return (BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_dirty.bv_root, lblkno));
2484 * Associate a buffer with a vnode.
2487 bgetvp(struct vnode *vp, struct buf *bp)
2492 ASSERT_BO_WLOCKED(bo);
2493 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2495 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2496 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2497 ("bgetvp: bp already attached! %p", bp));
2503 * Insert onto list for new vnode.
2505 buf_vlist_add(bp, bo, BX_VNCLEAN);
2509 * Disassociate a buffer from a vnode.
2512 brelvp(struct buf *bp)
2517 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2518 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2521 * Delete from old vnode list, if on one.
2523 vp = bp->b_vp; /* XXX */
2526 buf_vlist_remove(bp);
2527 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2528 bo->bo_flag &= ~BO_ONWORKLST;
2529 mtx_lock(&sync_mtx);
2530 LIST_REMOVE(bo, bo_synclist);
2531 syncer_worklist_len--;
2532 mtx_unlock(&sync_mtx);
2535 bp->b_bufobj = NULL;
2541 * Add an item to the syncer work queue.
2544 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2548 ASSERT_BO_WLOCKED(bo);
2550 mtx_lock(&sync_mtx);
2551 if (bo->bo_flag & BO_ONWORKLST)
2552 LIST_REMOVE(bo, bo_synclist);
2554 bo->bo_flag |= BO_ONWORKLST;
2555 syncer_worklist_len++;
2558 if (delay > syncer_maxdelay - 2)
2559 delay = syncer_maxdelay - 2;
2560 slot = (syncer_delayno + delay) & syncer_mask;
2562 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2563 mtx_unlock(&sync_mtx);
2567 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2571 mtx_lock(&sync_mtx);
2572 len = syncer_worklist_len - sync_vnode_count;
2573 mtx_unlock(&sync_mtx);
2574 error = SYSCTL_OUT(req, &len, sizeof(len));
2578 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2579 CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2580 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2582 static struct proc *updateproc;
2583 static void sched_sync(void);
2584 static struct kproc_desc up_kp = {
2589 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2592 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2597 *bo = LIST_FIRST(slp);
2601 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2604 * We use vhold in case the vnode does not
2605 * successfully sync. vhold prevents the vnode from
2606 * going away when we unlock the sync_mtx so that
2607 * we can acquire the vnode interlock.
2610 mtx_unlock(&sync_mtx);
2612 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2614 mtx_lock(&sync_mtx);
2615 return (*bo == LIST_FIRST(slp));
2617 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2618 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2620 vn_finished_write(mp);
2622 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2624 * Put us back on the worklist. The worklist
2625 * routine will remove us from our current
2626 * position and then add us back in at a later
2629 vn_syncer_add_to_worklist(*bo, syncdelay);
2633 mtx_lock(&sync_mtx);
2637 static int first_printf = 1;
2640 * System filesystem synchronizer daemon.
2645 struct synclist *next, *slp;
2648 struct thread *td = curthread;
2650 int net_worklist_len;
2651 int syncer_final_iter;
2655 syncer_final_iter = 0;
2656 syncer_state = SYNCER_RUNNING;
2657 starttime = time_uptime;
2658 td->td_pflags |= TDP_NORUNNINGBUF;
2660 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2663 mtx_lock(&sync_mtx);
2665 if (syncer_state == SYNCER_FINAL_DELAY &&
2666 syncer_final_iter == 0) {
2667 mtx_unlock(&sync_mtx);
2668 kproc_suspend_check(td->td_proc);
2669 mtx_lock(&sync_mtx);
2671 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2672 if (syncer_state != SYNCER_RUNNING &&
2673 starttime != time_uptime) {
2675 printf("\nSyncing disks, vnodes remaining... ");
2678 printf("%d ", net_worklist_len);
2680 starttime = time_uptime;
2683 * Push files whose dirty time has expired. Be careful
2684 * of interrupt race on slp queue.
2686 * Skip over empty worklist slots when shutting down.
2689 slp = &syncer_workitem_pending[syncer_delayno];
2690 syncer_delayno += 1;
2691 if (syncer_delayno == syncer_maxdelay)
2693 next = &syncer_workitem_pending[syncer_delayno];
2695 * If the worklist has wrapped since the
2696 * it was emptied of all but syncer vnodes,
2697 * switch to the FINAL_DELAY state and run
2698 * for one more second.
2700 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2701 net_worklist_len == 0 &&
2702 last_work_seen == syncer_delayno) {
2703 syncer_state = SYNCER_FINAL_DELAY;
2704 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2706 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2707 syncer_worklist_len > 0);
2710 * Keep track of the last time there was anything
2711 * on the worklist other than syncer vnodes.
2712 * Return to the SHUTTING_DOWN state if any
2715 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2716 last_work_seen = syncer_delayno;
2717 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2718 syncer_state = SYNCER_SHUTTING_DOWN;
2719 while (!LIST_EMPTY(slp)) {
2720 error = sync_vnode(slp, &bo, td);
2722 LIST_REMOVE(bo, bo_synclist);
2723 LIST_INSERT_HEAD(next, bo, bo_synclist);
2727 if (first_printf == 0) {
2729 * Drop the sync mutex, because some watchdog
2730 * drivers need to sleep while patting
2732 mtx_unlock(&sync_mtx);
2733 wdog_kern_pat(WD_LASTVAL);
2734 mtx_lock(&sync_mtx);
2737 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2738 syncer_final_iter--;
2740 * The variable rushjob allows the kernel to speed up the
2741 * processing of the filesystem syncer process. A rushjob
2742 * value of N tells the filesystem syncer to process the next
2743 * N seconds worth of work on its queue ASAP. Currently rushjob
2744 * is used by the soft update code to speed up the filesystem
2745 * syncer process when the incore state is getting so far
2746 * ahead of the disk that the kernel memory pool is being
2747 * threatened with exhaustion.
2754 * Just sleep for a short period of time between
2755 * iterations when shutting down to allow some I/O
2758 * If it has taken us less than a second to process the
2759 * current work, then wait. Otherwise start right over
2760 * again. We can still lose time if any single round
2761 * takes more than two seconds, but it does not really
2762 * matter as we are just trying to generally pace the
2763 * filesystem activity.
2765 if (syncer_state != SYNCER_RUNNING ||
2766 time_uptime == starttime) {
2768 sched_prio(td, PPAUSE);
2771 if (syncer_state != SYNCER_RUNNING)
2772 cv_timedwait(&sync_wakeup, &sync_mtx,
2773 hz / SYNCER_SHUTDOWN_SPEEDUP);
2774 else if (time_uptime == starttime)
2775 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2780 * Request the syncer daemon to speed up its work.
2781 * We never push it to speed up more than half of its
2782 * normal turn time, otherwise it could take over the cpu.
2785 speedup_syncer(void)
2789 mtx_lock(&sync_mtx);
2790 if (rushjob < syncdelay / 2) {
2792 stat_rush_requests += 1;
2795 mtx_unlock(&sync_mtx);
2796 cv_broadcast(&sync_wakeup);
2801 * Tell the syncer to speed up its work and run though its work
2802 * list several times, then tell it to shut down.
2805 syncer_shutdown(void *arg, int howto)
2808 if (howto & RB_NOSYNC)
2810 mtx_lock(&sync_mtx);
2811 syncer_state = SYNCER_SHUTTING_DOWN;
2813 mtx_unlock(&sync_mtx);
2814 cv_broadcast(&sync_wakeup);
2815 kproc_shutdown(arg, howto);
2819 syncer_suspend(void)
2822 syncer_shutdown(updateproc, 0);
2829 mtx_lock(&sync_mtx);
2831 syncer_state = SYNCER_RUNNING;
2832 mtx_unlock(&sync_mtx);
2833 cv_broadcast(&sync_wakeup);
2834 kproc_resume(updateproc);
2838 * Move the buffer between the clean and dirty lists of its vnode.
2841 reassignbuf(struct buf *bp)
2853 KASSERT((bp->b_flags & B_PAGING) == 0,
2854 ("%s: cannot reassign paging buffer %p", __func__, bp));
2856 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2857 bp, bp->b_vp, bp->b_flags);
2860 buf_vlist_remove(bp);
2863 * If dirty, put on list of dirty buffers; otherwise insert onto list
2866 if (bp->b_flags & B_DELWRI) {
2867 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2868 switch (vp->v_type) {
2878 vn_syncer_add_to_worklist(bo, delay);
2880 buf_vlist_add(bp, bo, BX_VNDIRTY);
2882 buf_vlist_add(bp, bo, BX_VNCLEAN);
2884 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2885 mtx_lock(&sync_mtx);
2886 LIST_REMOVE(bo, bo_synclist);
2887 syncer_worklist_len--;
2888 mtx_unlock(&sync_mtx);
2889 bo->bo_flag &= ~BO_ONWORKLST;
2894 bp = TAILQ_FIRST(&bv->bv_hd);
2895 KASSERT(bp == NULL || bp->b_bufobj == bo,
2896 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2897 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2898 KASSERT(bp == NULL || bp->b_bufobj == bo,
2899 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2901 bp = TAILQ_FIRST(&bv->bv_hd);
2902 KASSERT(bp == NULL || bp->b_bufobj == bo,
2903 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2904 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2905 KASSERT(bp == NULL || bp->b_bufobj == bo,
2906 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2912 v_init_counters(struct vnode *vp)
2915 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2916 vp, ("%s called for an initialized vnode", __FUNCTION__));
2917 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2919 refcount_init(&vp->v_holdcnt, 1);
2920 refcount_init(&vp->v_usecount, 1);
2924 * Grab a particular vnode from the free list, increment its
2925 * reference count and lock it. VIRF_DOOMED is set if the vnode
2926 * is being destroyed. Only callers who specify LK_RETRY will
2927 * see doomed vnodes. If inactive processing was delayed in
2928 * vput try to do it here.
2930 * usecount is manipulated using atomics without holding any locks.
2932 * holdcnt can be manipulated using atomics without holding any locks,
2933 * except when transitioning 1<->0, in which case the interlock is held.
2935 * Consumers which don't guarantee liveness of the vnode can use SMR to
2936 * try to get a reference. Note this operation can fail since the vnode
2937 * may be awaiting getting freed by the time they get to it.
2940 vget_prep_smr(struct vnode *vp)
2944 VFS_SMR_ASSERT_ENTERED();
2946 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2958 vget_prep(struct vnode *vp)
2962 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2972 vget_abort(struct vnode *vp, enum vgetstate vs)
2983 __assert_unreachable();
2988 vget(struct vnode *vp, int flags)
2993 return (vget_finish(vp, flags, vs));
2997 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
3001 if ((flags & LK_INTERLOCK) != 0)
3002 ASSERT_VI_LOCKED(vp, __func__);
3004 ASSERT_VI_UNLOCKED(vp, __func__);
3005 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3006 VNPASS(vp->v_holdcnt > 0, vp);
3007 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3009 error = vn_lock(vp, flags);
3010 if (__predict_false(error != 0)) {
3012 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
3017 vget_finish_ref(vp, vs);
3022 vget_finish_ref(struct vnode *vp, enum vgetstate vs)
3026 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3027 VNPASS(vp->v_holdcnt > 0, vp);
3028 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3030 if (vs == VGET_USECOUNT)
3034 * We hold the vnode. If the usecount is 0 it will be utilized to keep
3035 * the vnode around. Otherwise someone else lended their hold count and
3036 * we have to drop ours.
3038 old = atomic_fetchadd_int(&vp->v_usecount, 1);
3039 VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
3042 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
3043 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
3045 refcount_release(&vp->v_holdcnt);
3051 vref(struct vnode *vp)
3055 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3057 vget_finish_ref(vp, vs);
3061 vrefact(struct vnode *vp)
3064 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3066 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
3067 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3069 refcount_acquire(&vp->v_usecount);
3074 vlazy(struct vnode *vp)
3078 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
3080 if ((vp->v_mflag & VMP_LAZYLIST) != 0)
3083 * We may get here for inactive routines after the vnode got doomed.
3085 if (VN_IS_DOOMED(vp))
3088 mtx_lock(&mp->mnt_listmtx);
3089 if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
3090 vp->v_mflag |= VMP_LAZYLIST;
3091 TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3092 mp->mnt_lazyvnodelistsize++;
3094 mtx_unlock(&mp->mnt_listmtx);
3098 vunlazy(struct vnode *vp)
3102 ASSERT_VI_LOCKED(vp, __func__);
3103 VNPASS(!VN_IS_DOOMED(vp), vp);
3106 mtx_lock(&mp->mnt_listmtx);
3107 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3109 * Don't remove the vnode from the lazy list if another thread
3110 * has increased the hold count. It may have re-enqueued the
3111 * vnode to the lazy list and is now responsible for its
3114 if (vp->v_holdcnt == 0) {
3115 vp->v_mflag &= ~VMP_LAZYLIST;
3116 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3117 mp->mnt_lazyvnodelistsize--;
3119 mtx_unlock(&mp->mnt_listmtx);
3123 * This routine is only meant to be called from vgonel prior to dooming
3127 vunlazy_gone(struct vnode *vp)
3131 ASSERT_VOP_ELOCKED(vp, __func__);
3132 ASSERT_VI_LOCKED(vp, __func__);
3133 VNPASS(!VN_IS_DOOMED(vp), vp);
3135 if (vp->v_mflag & VMP_LAZYLIST) {
3137 mtx_lock(&mp->mnt_listmtx);
3138 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3139 vp->v_mflag &= ~VMP_LAZYLIST;
3140 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3141 mp->mnt_lazyvnodelistsize--;
3142 mtx_unlock(&mp->mnt_listmtx);
3147 vdefer_inactive(struct vnode *vp)
3150 ASSERT_VI_LOCKED(vp, __func__);
3151 VNASSERT(vp->v_holdcnt > 0, vp,
3152 ("%s: vnode without hold count", __func__));
3153 if (VN_IS_DOOMED(vp)) {
3157 if (vp->v_iflag & VI_DEFINACT) {
3158 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3162 if (vp->v_usecount > 0) {
3163 vp->v_iflag &= ~VI_OWEINACT;
3168 vp->v_iflag |= VI_DEFINACT;
3170 counter_u64_add(deferred_inact, 1);
3174 vdefer_inactive_unlocked(struct vnode *vp)
3178 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3182 vdefer_inactive(vp);
3185 enum vput_op { VRELE, VPUT, VUNREF };
3188 * Handle ->v_usecount transitioning to 0.
3190 * By releasing the last usecount we take ownership of the hold count which
3191 * provides liveness of the vnode, meaning we have to vdrop.
3193 * For all vnodes we may need to perform inactive processing. It requires an
3194 * exclusive lock on the vnode, while it is legal to call here with only a
3195 * shared lock (or no locks). If locking the vnode in an expected manner fails,
3196 * inactive processing gets deferred to the syncer.
3198 * XXX Some filesystems pass in an exclusively locked vnode and strongly depend
3199 * on the lock being held all the way until VOP_INACTIVE. This in particular
3200 * happens with UFS which adds half-constructed vnodes to the hash, where they
3201 * can be found by other code.
3204 vput_final(struct vnode *vp, enum vput_op func)
3209 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3210 VNPASS(vp->v_holdcnt > 0, vp);
3215 * By the time we got here someone else might have transitioned
3216 * the count back to > 0.
3218 if (vp->v_usecount > 0)
3222 * If the vnode is doomed vgone already performed inactive processing
3225 if (VN_IS_DOOMED(vp))
3228 if (__predict_true(VOP_NEED_INACTIVE(vp) == 0))
3231 if (vp->v_iflag & VI_DOINGINACT)
3235 * Locking operations here will drop the interlock and possibly the
3236 * vnode lock, opening a window where the vnode can get doomed all the
3237 * while ->v_usecount is 0. Set VI_OWEINACT to let vgone know to
3240 vp->v_iflag |= VI_OWEINACT;
3241 want_unlock = false;
3245 switch (VOP_ISLOCKED(vp)) {
3251 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3256 * The lock has at least one sharer, but we have no way
3257 * to conclude whether this is us. Play it safe and
3266 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3267 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3273 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3274 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3280 if (func == VUNREF) {
3281 VNASSERT((vp->v_vflag & VV_UNREF) == 0, vp,
3282 ("recursive vunref"));
3283 vp->v_vflag |= VV_UNREF;
3286 error = vinactive(vp);
3289 if (error != ERELOOKUP || !want_unlock)
3291 VOP_LOCK(vp, LK_EXCLUSIVE);
3294 vp->v_vflag &= ~VV_UNREF;
3297 vdefer_inactive(vp);
3307 * Decrement ->v_usecount for a vnode.
3309 * Releasing the last use count requires additional processing, see vput_final
3310 * above for details.
3312 * Comment above each variant denotes lock state on entry and exit.
3317 * out: same as passed in
3320 vrele(struct vnode *vp)
3323 ASSERT_VI_UNLOCKED(vp, __func__);
3324 if (!refcount_release(&vp->v_usecount))
3326 vput_final(vp, VRELE);
3334 vput(struct vnode *vp)
3337 ASSERT_VOP_LOCKED(vp, __func__);
3338 ASSERT_VI_UNLOCKED(vp, __func__);
3339 if (!refcount_release(&vp->v_usecount)) {
3343 vput_final(vp, VPUT);
3351 vunref(struct vnode *vp)
3354 ASSERT_VOP_LOCKED(vp, __func__);
3355 ASSERT_VI_UNLOCKED(vp, __func__);
3356 if (!refcount_release(&vp->v_usecount))
3358 vput_final(vp, VUNREF);
3362 vhold(struct vnode *vp)
3366 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3367 old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3368 VNASSERT(old >= 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3369 ("%s: wrong hold count %d", __func__, old));
3371 vfs_freevnodes_dec();
3375 vholdnz(struct vnode *vp)
3378 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3380 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3381 VNASSERT(old > 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3382 ("%s: wrong hold count %d", __func__, old));
3384 atomic_add_int(&vp->v_holdcnt, 1);
3389 * Grab a hold count unless the vnode is freed.
3391 * Only use this routine if vfs smr is the only protection you have against
3392 * freeing the vnode.
3394 * The code loops trying to add a hold count as long as the VHOLD_NO_SMR flag
3395 * is not set. After the flag is set the vnode becomes immutable to anyone but
3396 * the thread which managed to set the flag.
3398 * It may be tempting to replace the loop with:
3399 * count = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3400 * if (count & VHOLD_NO_SMR) {
3401 * backpedal and error out;
3404 * However, while this is more performant, it hinders debugging by eliminating
3405 * the previously mentioned invariant.
3408 vhold_smr(struct vnode *vp)
3412 VFS_SMR_ASSERT_ENTERED();
3414 count = atomic_load_int(&vp->v_holdcnt);
3416 if (count & VHOLD_NO_SMR) {
3417 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3418 ("non-zero hold count with flags %d\n", count));
3421 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3422 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3424 vfs_freevnodes_dec();
3431 * Hold a free vnode for recycling.
3433 * Note: vnode_init references this comment.
3435 * Attempts to recycle only need the global vnode list lock and have no use for
3438 * However, vnodes get inserted into the global list before they get fully
3439 * initialized and stay there until UMA decides to free the memory. This in
3440 * particular means the target can be found before it becomes usable and after
3441 * it becomes recycled. Picking up such vnodes is guarded with v_holdcnt set to
3444 * Note: the vnode may gain more references after we transition the count 0->1.
3447 vhold_recycle_free(struct vnode *vp)
3451 mtx_assert(&vnode_list_mtx, MA_OWNED);
3453 count = atomic_load_int(&vp->v_holdcnt);
3455 if (count & VHOLD_NO_SMR) {
3456 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3457 ("non-zero hold count with flags %d\n", count));
3460 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3464 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3465 vfs_freevnodes_dec();
3471 static void __noinline
3472 vdbatch_process(struct vdbatch *vd)
3477 mtx_assert(&vd->lock, MA_OWNED);
3478 MPASS(curthread->td_pinned > 0);
3479 MPASS(vd->index == VDBATCH_SIZE);
3481 mtx_lock(&vnode_list_mtx);
3483 freevnodes += vd->freevnodes;
3484 for (i = 0; i < VDBATCH_SIZE; i++) {
3486 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3487 TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3488 MPASS(vp->v_dbatchcpu != NOCPU);
3489 vp->v_dbatchcpu = NOCPU;
3491 mtx_unlock(&vnode_list_mtx);
3493 bzero(vd->tab, sizeof(vd->tab));
3499 vdbatch_enqueue(struct vnode *vp)
3503 ASSERT_VI_LOCKED(vp, __func__);
3504 VNASSERT(!VN_IS_DOOMED(vp), vp,
3505 ("%s: deferring requeue of a doomed vnode", __func__));
3507 if (vp->v_dbatchcpu != NOCPU) {
3514 mtx_lock(&vd->lock);
3515 MPASS(vd->index < VDBATCH_SIZE);
3516 MPASS(vd->tab[vd->index] == NULL);
3518 * A hack: we depend on being pinned so that we know what to put in
3521 vp->v_dbatchcpu = curcpu;
3522 vd->tab[vd->index] = vp;
3525 if (vd->index == VDBATCH_SIZE)
3526 vdbatch_process(vd);
3527 mtx_unlock(&vd->lock);
3532 * This routine must only be called for vnodes which are about to be
3533 * deallocated. Supporting dequeue for arbitrary vndoes would require
3534 * validating that the locked batch matches.
3537 vdbatch_dequeue(struct vnode *vp)
3543 VNASSERT(vp->v_type == VBAD || vp->v_type == VNON, vp,
3544 ("%s: called for a used vnode\n", __func__));
3546 cpu = vp->v_dbatchcpu;
3550 vd = DPCPU_ID_PTR(cpu, vd);
3551 mtx_lock(&vd->lock);
3552 for (i = 0; i < vd->index; i++) {
3553 if (vd->tab[i] != vp)
3555 vp->v_dbatchcpu = NOCPU;
3557 vd->tab[i] = vd->tab[vd->index];
3558 vd->tab[vd->index] = NULL;
3561 mtx_unlock(&vd->lock);
3563 * Either we dequeued the vnode above or the target CPU beat us to it.
3565 MPASS(vp->v_dbatchcpu == NOCPU);
3569 * Drop the hold count of the vnode. If this is the last reference to
3570 * the vnode we place it on the free list unless it has been vgone'd
3571 * (marked VIRF_DOOMED) in which case we will free it.
3573 * Because the vnode vm object keeps a hold reference on the vnode if
3574 * there is at least one resident non-cached page, the vnode cannot
3575 * leave the active list without the page cleanup done.
3577 static void __noinline
3578 vdropl_final(struct vnode *vp)
3581 ASSERT_VI_LOCKED(vp, __func__);
3582 VNPASS(VN_IS_DOOMED(vp), vp);
3584 * Set the VHOLD_NO_SMR flag.
3586 * We may be racing against vhold_smr. If they win we can just pretend
3587 * we never got this far, they will vdrop later.
3589 if (__predict_false(!atomic_cmpset_int(&vp->v_holdcnt, 0, VHOLD_NO_SMR))) {
3590 vfs_freevnodes_inc();
3593 * We lost the aforementioned race. Any subsequent access is
3594 * invalid as they might have managed to vdropl on their own.
3599 * Don't bump freevnodes as this one is going away.
3605 vdrop(struct vnode *vp)
3608 ASSERT_VI_UNLOCKED(vp, __func__);
3609 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3610 if (refcount_release_if_not_last(&vp->v_holdcnt))
3617 vdropl(struct vnode *vp)
3620 ASSERT_VI_LOCKED(vp, __func__);
3621 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3622 if (!refcount_release(&vp->v_holdcnt)) {
3626 VNPASS((vp->v_iflag & VI_OWEINACT) == 0, vp);
3627 VNPASS((vp->v_iflag & VI_DEFINACT) == 0, vp);
3628 if (VN_IS_DOOMED(vp)) {
3633 vfs_freevnodes_inc();
3634 if (vp->v_mflag & VMP_LAZYLIST) {
3638 * Also unlocks the interlock. We can't assert on it as we
3639 * released our hold and by now the vnode might have been
3642 vdbatch_enqueue(vp);
3646 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3647 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3650 vinactivef(struct vnode *vp)
3652 struct vm_object *obj;
3655 ASSERT_VOP_ELOCKED(vp, "vinactive");
3656 ASSERT_VI_LOCKED(vp, "vinactive");
3657 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3658 ("vinactive: recursed on VI_DOINGINACT"));
3659 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3660 vp->v_iflag |= VI_DOINGINACT;
3661 vp->v_iflag &= ~VI_OWEINACT;
3664 * Before moving off the active list, we must be sure that any
3665 * modified pages are converted into the vnode's dirty
3666 * buffers, since these will no longer be checked once the
3667 * vnode is on the inactive list.
3669 * The write-out of the dirty pages is asynchronous. At the
3670 * point that VOP_INACTIVE() is called, there could still be
3671 * pending I/O and dirty pages in the object.
3673 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3674 vm_object_mightbedirty(obj)) {
3675 VM_OBJECT_WLOCK(obj);
3676 vm_object_page_clean(obj, 0, 0, 0);
3677 VM_OBJECT_WUNLOCK(obj);
3679 error = VOP_INACTIVE(vp);
3681 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3682 ("vinactive: lost VI_DOINGINACT"));
3683 vp->v_iflag &= ~VI_DOINGINACT;
3688 vinactive(struct vnode *vp)
3691 ASSERT_VOP_ELOCKED(vp, "vinactive");
3692 ASSERT_VI_LOCKED(vp, "vinactive");
3693 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3695 if ((vp->v_iflag & VI_OWEINACT) == 0)
3697 if (vp->v_iflag & VI_DOINGINACT)
3699 if (vp->v_usecount > 0) {
3700 vp->v_iflag &= ~VI_OWEINACT;
3703 return (vinactivef(vp));
3707 * Remove any vnodes in the vnode table belonging to mount point mp.
3709 * If FORCECLOSE is not specified, there should not be any active ones,
3710 * return error if any are found (nb: this is a user error, not a
3711 * system error). If FORCECLOSE is specified, detach any active vnodes
3714 * If WRITECLOSE is set, only flush out regular file vnodes open for
3717 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3719 * `rootrefs' specifies the base reference count for the root vnode
3720 * of this filesystem. The root vnode is considered busy if its
3721 * v_usecount exceeds this value. On a successful return, vflush(, td)
3722 * will call vrele() on the root vnode exactly rootrefs times.
3723 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3727 static int busyprt = 0; /* print out busy vnodes */
3728 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3732 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3734 struct vnode *vp, *mvp, *rootvp = NULL;
3736 int busy = 0, error;
3738 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3741 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3742 ("vflush: bad args"));
3744 * Get the filesystem root vnode. We can vput() it
3745 * immediately, since with rootrefs > 0, it won't go away.
3747 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3748 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3755 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3757 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3760 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3764 * Skip over a vnodes marked VV_SYSTEM.
3766 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3772 * If WRITECLOSE is set, flush out unlinked but still open
3773 * files (even if open only for reading) and regular file
3774 * vnodes open for writing.
3776 if (flags & WRITECLOSE) {
3777 if (vp->v_object != NULL) {
3778 VM_OBJECT_WLOCK(vp->v_object);
3779 vm_object_page_clean(vp->v_object, 0, 0, 0);
3780 VM_OBJECT_WUNLOCK(vp->v_object);
3783 error = VOP_FSYNC(vp, MNT_WAIT, td);
3784 } while (error == ERELOOKUP);
3788 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3791 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3794 if ((vp->v_type == VNON ||
3795 (error == 0 && vattr.va_nlink > 0)) &&
3796 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3804 * With v_usecount == 0, all we need to do is clear out the
3805 * vnode data structures and we are done.
3807 * If FORCECLOSE is set, forcibly close the vnode.
3809 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3815 vn_printf(vp, "vflush: busy vnode ");
3821 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3823 * If just the root vnode is busy, and if its refcount
3824 * is equal to `rootrefs', then go ahead and kill it.
3827 KASSERT(busy > 0, ("vflush: not busy"));
3828 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3829 ("vflush: usecount %d < rootrefs %d",
3830 rootvp->v_usecount, rootrefs));
3831 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3832 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3840 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3844 for (; rootrefs > 0; rootrefs--)
3850 * Recycle an unused vnode to the front of the free list.
3853 vrecycle(struct vnode *vp)
3858 recycled = vrecyclel(vp);
3864 * vrecycle, with the vp interlock held.
3867 vrecyclel(struct vnode *vp)
3871 ASSERT_VOP_ELOCKED(vp, __func__);
3872 ASSERT_VI_LOCKED(vp, __func__);
3873 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3875 if (vp->v_usecount == 0) {
3883 * Eliminate all activity associated with a vnode
3884 * in preparation for reuse.
3887 vgone(struct vnode *vp)
3895 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3896 struct vnode *lowervp __unused)
3901 * Notify upper mounts about reclaimed or unlinked vnode.
3904 vfs_notify_upper(struct vnode *vp, int event)
3906 static struct vfsops vgonel_vfsops = {
3907 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3908 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3910 struct mount *mp, *ump, *mmp;
3915 if (TAILQ_EMPTY(&mp->mnt_uppers))
3918 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3919 mmp->mnt_op = &vgonel_vfsops;
3920 mmp->mnt_kern_flag |= MNTK_MARKER;
3922 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3923 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3924 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3925 ump = TAILQ_NEXT(ump, mnt_upper_link);
3928 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3931 case VFS_NOTIFY_UPPER_RECLAIM:
3932 VFS_RECLAIM_LOWERVP(ump, vp);
3934 case VFS_NOTIFY_UPPER_UNLINK:
3935 VFS_UNLINK_LOWERVP(ump, vp);
3938 KASSERT(0, ("invalid event %d", event));
3942 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3943 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3946 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3947 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3948 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3949 wakeup(&mp->mnt_uppers);
3955 * vgone, with the vp interlock held.
3958 vgonel(struct vnode *vp)
3963 bool active, doinginact, oweinact;
3965 ASSERT_VOP_ELOCKED(vp, "vgonel");
3966 ASSERT_VI_LOCKED(vp, "vgonel");
3967 VNASSERT(vp->v_holdcnt, vp,
3968 ("vgonel: vp %p has no reference.", vp));
3969 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3973 * Don't vgonel if we're already doomed.
3975 if (VN_IS_DOOMED(vp))
3978 * Paired with freevnode.
3980 vn_seqc_write_begin_locked(vp);
3982 vn_irflag_set_locked(vp, VIRF_DOOMED);
3985 * Check to see if the vnode is in use. If so, we have to
3986 * call VOP_CLOSE() and VOP_INACTIVE().
3988 * It could be that VOP_INACTIVE() requested reclamation, in
3989 * which case we should avoid recursion, so check
3990 * VI_DOINGINACT. This is not precise but good enough.
3992 active = vp->v_usecount > 0;
3993 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
3994 doinginact = (vp->v_iflag & VI_DOINGINACT) != 0;
3997 * If we need to do inactive VI_OWEINACT will be set.
3999 if (vp->v_iflag & VI_DEFINACT) {
4000 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
4001 vp->v_iflag &= ~VI_DEFINACT;
4004 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
4007 cache_purge_vgone(vp);
4008 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
4011 * If purging an active vnode, it must be closed and
4012 * deactivated before being reclaimed.
4015 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
4018 if (oweinact || active) {
4021 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4026 if (vp->v_type == VSOCK)
4027 vfs_unp_reclaim(vp);
4030 * Clean out any buffers associated with the vnode.
4031 * If the flush fails, just toss the buffers.
4034 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
4035 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
4036 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
4037 while (vinvalbuf(vp, 0, 0, 0) != 0)
4041 BO_LOCK(&vp->v_bufobj);
4042 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
4043 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
4044 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
4045 vp->v_bufobj.bo_clean.bv_cnt == 0,
4046 ("vp %p bufobj not invalidated", vp));
4049 * For VMIO bufobj, BO_DEAD is set later, or in
4050 * vm_object_terminate() after the object's page queue is
4053 object = vp->v_bufobj.bo_object;
4055 vp->v_bufobj.bo_flag |= BO_DEAD;
4056 BO_UNLOCK(&vp->v_bufobj);
4059 * Handle the VM part. Tmpfs handles v_object on its own (the
4060 * OBJT_VNODE check). Nullfs or other bypassing filesystems
4061 * should not touch the object borrowed from the lower vnode
4062 * (the handle check).
4064 if (object != NULL && object->type == OBJT_VNODE &&
4065 object->handle == vp)
4066 vnode_destroy_vobject(vp);
4069 * Reclaim the vnode.
4071 if (VOP_RECLAIM(vp))
4072 panic("vgone: cannot reclaim");
4074 vn_finished_secondary_write(mp);
4075 VNASSERT(vp->v_object == NULL, vp,
4076 ("vop_reclaim left v_object vp=%p", vp));
4078 * Clear the advisory locks and wake up waiting threads.
4080 (void)VOP_ADVLOCKPURGE(vp);
4083 * Delete from old mount point vnode list.
4087 * Done with purge, reset to the standard lock and invalidate
4091 vp->v_vnlock = &vp->v_lock;
4092 vp->v_op = &dead_vnodeops;
4097 * Print out a description of a vnode.
4099 static const char * const typename[] =
4100 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
4103 _Static_assert((VHOLD_ALL_FLAGS & ~VHOLD_NO_SMR) == 0,
4104 "new hold count flag not added to vn_printf");
4107 vn_printf(struct vnode *vp, const char *fmt, ...)
4110 char buf[256], buf2[16];
4118 printf("%p: ", (void *)vp);
4119 printf("type %s\n", typename[vp->v_type]);
4120 holdcnt = atomic_load_int(&vp->v_holdcnt);
4121 printf(" usecount %d, writecount %d, refcount %d seqc users %d",
4122 vp->v_usecount, vp->v_writecount, holdcnt & ~VHOLD_ALL_FLAGS,
4124 switch (vp->v_type) {
4126 printf(" mountedhere %p\n", vp->v_mountedhere);
4129 printf(" rdev %p\n", vp->v_rdev);
4132 printf(" socket %p\n", vp->v_unpcb);
4135 printf(" fifoinfo %p\n", vp->v_fifoinfo);
4143 if (holdcnt & VHOLD_NO_SMR)
4144 strlcat(buf, "|VHOLD_NO_SMR", sizeof(buf));
4145 printf(" hold count flags (%s)\n", buf + 1);
4149 irflag = vn_irflag_read(vp);
4150 if (irflag & VIRF_DOOMED)
4151 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
4152 if (irflag & VIRF_PGREAD)
4153 strlcat(buf, "|VIRF_PGREAD", sizeof(buf));
4154 if (irflag & VIRF_MOUNTPOINT)
4155 strlcat(buf, "|VIRF_MOUNTPOINT", sizeof(buf));
4156 flags = irflag & ~(VIRF_DOOMED | VIRF_PGREAD | VIRF_MOUNTPOINT);
4158 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
4159 strlcat(buf, buf2, sizeof(buf));
4161 if (vp->v_vflag & VV_ROOT)
4162 strlcat(buf, "|VV_ROOT", sizeof(buf));
4163 if (vp->v_vflag & VV_ISTTY)
4164 strlcat(buf, "|VV_ISTTY", sizeof(buf));
4165 if (vp->v_vflag & VV_NOSYNC)
4166 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
4167 if (vp->v_vflag & VV_ETERNALDEV)
4168 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
4169 if (vp->v_vflag & VV_CACHEDLABEL)
4170 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
4171 if (vp->v_vflag & VV_VMSIZEVNLOCK)
4172 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
4173 if (vp->v_vflag & VV_COPYONWRITE)
4174 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
4175 if (vp->v_vflag & VV_SYSTEM)
4176 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
4177 if (vp->v_vflag & VV_PROCDEP)
4178 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
4179 if (vp->v_vflag & VV_NOKNOTE)
4180 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
4181 if (vp->v_vflag & VV_DELETED)
4182 strlcat(buf, "|VV_DELETED", sizeof(buf));
4183 if (vp->v_vflag & VV_MD)
4184 strlcat(buf, "|VV_MD", sizeof(buf));
4185 if (vp->v_vflag & VV_FORCEINSMQ)
4186 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
4187 if (vp->v_vflag & VV_READLINK)
4188 strlcat(buf, "|VV_READLINK", sizeof(buf));
4189 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4190 VV_CACHEDLABEL | VV_VMSIZEVNLOCK | VV_COPYONWRITE | VV_SYSTEM |
4191 VV_PROCDEP | VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ |
4194 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4195 strlcat(buf, buf2, sizeof(buf));
4197 if (vp->v_iflag & VI_TEXT_REF)
4198 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
4199 if (vp->v_iflag & VI_MOUNT)
4200 strlcat(buf, "|VI_MOUNT", sizeof(buf));
4201 if (vp->v_iflag & VI_DOINGINACT)
4202 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4203 if (vp->v_iflag & VI_OWEINACT)
4204 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4205 if (vp->v_iflag & VI_DEFINACT)
4206 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4207 if (vp->v_iflag & VI_FOPENING)
4208 strlcat(buf, "|VI_FOPENING", sizeof(buf));
4209 flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOINGINACT |
4210 VI_OWEINACT | VI_DEFINACT | VI_FOPENING);
4212 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4213 strlcat(buf, buf2, sizeof(buf));
4215 if (vp->v_mflag & VMP_LAZYLIST)
4216 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4217 flags = vp->v_mflag & ~(VMP_LAZYLIST);
4219 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4220 strlcat(buf, buf2, sizeof(buf));
4222 printf(" flags (%s)", buf + 1);
4223 if (mtx_owned(VI_MTX(vp)))
4224 printf(" VI_LOCKed");
4226 if (vp->v_object != NULL)
4227 printf(" v_object %p ref %d pages %d "
4228 "cleanbuf %d dirtybuf %d\n",
4229 vp->v_object, vp->v_object->ref_count,
4230 vp->v_object->resident_page_count,
4231 vp->v_bufobj.bo_clean.bv_cnt,
4232 vp->v_bufobj.bo_dirty.bv_cnt);
4234 lockmgr_printinfo(vp->v_vnlock);
4235 if (vp->v_data != NULL)
4241 * List all of the locked vnodes in the system.
4242 * Called when debugging the kernel.
4244 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
4250 * Note: because this is DDB, we can't obey the locking semantics
4251 * for these structures, which means we could catch an inconsistent
4252 * state and dereference a nasty pointer. Not much to be done
4255 db_printf("Locked vnodes\n");
4256 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4257 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4258 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4259 vn_printf(vp, "vnode ");
4265 * Show details about the given vnode.
4267 DB_SHOW_COMMAND(vnode, db_show_vnode)
4273 vp = (struct vnode *)addr;
4274 vn_printf(vp, "vnode ");
4278 * Show details about the given mount point.
4280 DB_SHOW_COMMAND(mount, db_show_mount)
4291 /* No address given, print short info about all mount points. */
4292 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4293 db_printf("%p %s on %s (%s)\n", mp,
4294 mp->mnt_stat.f_mntfromname,
4295 mp->mnt_stat.f_mntonname,
4296 mp->mnt_stat.f_fstypename);
4300 db_printf("\nMore info: show mount <addr>\n");
4304 mp = (struct mount *)addr;
4305 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4306 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4309 mflags = mp->mnt_flag;
4310 #define MNT_FLAG(flag) do { \
4311 if (mflags & (flag)) { \
4312 if (buf[0] != '\0') \
4313 strlcat(buf, ", ", sizeof(buf)); \
4314 strlcat(buf, (#flag) + 4, sizeof(buf)); \
4315 mflags &= ~(flag); \
4318 MNT_FLAG(MNT_RDONLY);
4319 MNT_FLAG(MNT_SYNCHRONOUS);
4320 MNT_FLAG(MNT_NOEXEC);
4321 MNT_FLAG(MNT_NOSUID);
4322 MNT_FLAG(MNT_NFS4ACLS);
4323 MNT_FLAG(MNT_UNION);
4324 MNT_FLAG(MNT_ASYNC);
4325 MNT_FLAG(MNT_SUIDDIR);
4326 MNT_FLAG(MNT_SOFTDEP);
4327 MNT_FLAG(MNT_NOSYMFOLLOW);
4328 MNT_FLAG(MNT_GJOURNAL);
4329 MNT_FLAG(MNT_MULTILABEL);
4331 MNT_FLAG(MNT_NOATIME);
4332 MNT_FLAG(MNT_NOCLUSTERR);
4333 MNT_FLAG(MNT_NOCLUSTERW);
4335 MNT_FLAG(MNT_EXRDONLY);
4336 MNT_FLAG(MNT_EXPORTED);
4337 MNT_FLAG(MNT_DEFEXPORTED);
4338 MNT_FLAG(MNT_EXPORTANON);
4339 MNT_FLAG(MNT_EXKERB);
4340 MNT_FLAG(MNT_EXPUBLIC);
4341 MNT_FLAG(MNT_LOCAL);
4342 MNT_FLAG(MNT_QUOTA);
4343 MNT_FLAG(MNT_ROOTFS);
4345 MNT_FLAG(MNT_IGNORE);
4346 MNT_FLAG(MNT_UPDATE);
4347 MNT_FLAG(MNT_DELEXPORT);
4348 MNT_FLAG(MNT_RELOAD);
4349 MNT_FLAG(MNT_FORCE);
4350 MNT_FLAG(MNT_SNAPSHOT);
4351 MNT_FLAG(MNT_BYFSID);
4355 strlcat(buf, ", ", sizeof(buf));
4356 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4357 "0x%016jx", mflags);
4359 db_printf(" mnt_flag = %s\n", buf);
4362 flags = mp->mnt_kern_flag;
4363 #define MNT_KERN_FLAG(flag) do { \
4364 if (flags & (flag)) { \
4365 if (buf[0] != '\0') \
4366 strlcat(buf, ", ", sizeof(buf)); \
4367 strlcat(buf, (#flag) + 5, sizeof(buf)); \
4371 MNT_KERN_FLAG(MNTK_UNMOUNTF);
4372 MNT_KERN_FLAG(MNTK_ASYNC);
4373 MNT_KERN_FLAG(MNTK_SOFTDEP);
4374 MNT_KERN_FLAG(MNTK_DRAINING);
4375 MNT_KERN_FLAG(MNTK_REFEXPIRE);
4376 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4377 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4378 MNT_KERN_FLAG(MNTK_NO_IOPF);
4379 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4380 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4381 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4382 MNT_KERN_FLAG(MNTK_MARKER);
4383 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4384 MNT_KERN_FLAG(MNTK_FPLOOKUP);
4385 MNT_KERN_FLAG(MNTK_NOASYNC);
4386 MNT_KERN_FLAG(MNTK_UNMOUNT);
4387 MNT_KERN_FLAG(MNTK_MWAIT);
4388 MNT_KERN_FLAG(MNTK_SUSPEND);
4389 MNT_KERN_FLAG(MNTK_SUSPEND2);
4390 MNT_KERN_FLAG(MNTK_SUSPENDED);
4391 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4392 MNT_KERN_FLAG(MNTK_NOKNOTE);
4393 #undef MNT_KERN_FLAG
4396 strlcat(buf, ", ", sizeof(buf));
4397 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4400 db_printf(" mnt_kern_flag = %s\n", buf);
4402 db_printf(" mnt_opt = ");
4403 opt = TAILQ_FIRST(mp->mnt_opt);
4405 db_printf("%s", opt->name);
4406 opt = TAILQ_NEXT(opt, link);
4407 while (opt != NULL) {
4408 db_printf(", %s", opt->name);
4409 opt = TAILQ_NEXT(opt, link);
4415 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4416 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4417 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4418 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4419 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4420 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4421 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4422 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4423 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4424 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4425 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4426 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4428 db_printf(" mnt_cred = { uid=%u ruid=%u",
4429 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4430 if (jailed(mp->mnt_cred))
4431 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4433 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4434 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4435 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4436 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4437 db_printf(" mnt_lazyvnodelistsize = %d\n",
4438 mp->mnt_lazyvnodelistsize);
4439 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4440 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4441 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4442 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4443 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4444 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4445 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4446 db_printf(" mnt_secondary_accwrites = %d\n",
4447 mp->mnt_secondary_accwrites);
4448 db_printf(" mnt_gjprovider = %s\n",
4449 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4450 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4452 db_printf("\n\nList of active vnodes\n");
4453 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4454 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4455 vn_printf(vp, "vnode ");
4460 db_printf("\n\nList of inactive vnodes\n");
4461 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4462 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4463 vn_printf(vp, "vnode ");
4472 * Fill in a struct xvfsconf based on a struct vfsconf.
4475 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4477 struct xvfsconf xvfsp;
4479 bzero(&xvfsp, sizeof(xvfsp));
4480 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4481 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4482 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4483 xvfsp.vfc_flags = vfsp->vfc_flags;
4485 * These are unused in userland, we keep them
4486 * to not break binary compatibility.
4488 xvfsp.vfc_vfsops = NULL;
4489 xvfsp.vfc_next = NULL;
4490 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4493 #ifdef COMPAT_FREEBSD32
4495 uint32_t vfc_vfsops;
4496 char vfc_name[MFSNAMELEN];
4497 int32_t vfc_typenum;
4498 int32_t vfc_refcount;
4504 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4506 struct xvfsconf32 xvfsp;
4508 bzero(&xvfsp, sizeof(xvfsp));
4509 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4510 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4511 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4512 xvfsp.vfc_flags = vfsp->vfc_flags;
4513 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4518 * Top level filesystem related information gathering.
4521 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4523 struct vfsconf *vfsp;
4528 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4529 #ifdef COMPAT_FREEBSD32
4530 if (req->flags & SCTL_MASK32)
4531 error = vfsconf2x32(req, vfsp);
4534 error = vfsconf2x(req, vfsp);
4542 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4543 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4544 "S,xvfsconf", "List of all configured filesystems");
4546 #ifndef BURN_BRIDGES
4547 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4550 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4552 int *name = (int *)arg1 - 1; /* XXX */
4553 u_int namelen = arg2 + 1; /* XXX */
4554 struct vfsconf *vfsp;
4556 log(LOG_WARNING, "userland calling deprecated sysctl, "
4557 "please rebuild world\n");
4559 #if 1 || defined(COMPAT_PRELITE2)
4560 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4562 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4566 case VFS_MAXTYPENUM:
4569 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4572 return (ENOTDIR); /* overloaded */
4574 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4575 if (vfsp->vfc_typenum == name[2])
4580 return (EOPNOTSUPP);
4581 #ifdef COMPAT_FREEBSD32
4582 if (req->flags & SCTL_MASK32)
4583 return (vfsconf2x32(req, vfsp));
4586 return (vfsconf2x(req, vfsp));
4588 return (EOPNOTSUPP);
4591 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4592 CTLFLAG_MPSAFE, vfs_sysctl,
4593 "Generic filesystem");
4595 #if 1 || defined(COMPAT_PRELITE2)
4598 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4601 struct vfsconf *vfsp;
4602 struct ovfsconf ovfs;
4605 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4606 bzero(&ovfs, sizeof(ovfs));
4607 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4608 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4609 ovfs.vfc_index = vfsp->vfc_typenum;
4610 ovfs.vfc_refcount = vfsp->vfc_refcount;
4611 ovfs.vfc_flags = vfsp->vfc_flags;
4612 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4622 #endif /* 1 || COMPAT_PRELITE2 */
4623 #endif /* !BURN_BRIDGES */
4625 #define KINFO_VNODESLOP 10
4628 * Dump vnode list (via sysctl).
4632 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4640 * Stale numvnodes access is not fatal here.
4643 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4645 /* Make an estimate */
4646 return (SYSCTL_OUT(req, 0, len));
4648 error = sysctl_wire_old_buffer(req, 0);
4651 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4653 mtx_lock(&mountlist_mtx);
4654 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4655 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4658 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4662 xvn[n].xv_size = sizeof *xvn;
4663 xvn[n].xv_vnode = vp;
4664 xvn[n].xv_id = 0; /* XXX compat */
4665 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4667 XV_COPY(writecount);
4673 xvn[n].xv_flag = vp->v_vflag;
4675 switch (vp->v_type) {
4682 if (vp->v_rdev == NULL) {
4686 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4689 xvn[n].xv_socket = vp->v_socket;
4692 xvn[n].xv_fifo = vp->v_fifoinfo;
4697 /* shouldn't happen? */
4705 mtx_lock(&mountlist_mtx);
4710 mtx_unlock(&mountlist_mtx);
4712 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4717 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4718 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4723 unmount_or_warn(struct mount *mp)
4727 error = dounmount(mp, MNT_FORCE, curthread);
4729 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4733 printf("%d)\n", error);
4738 * Unmount all filesystems. The list is traversed in reverse order
4739 * of mounting to avoid dependencies.
4742 vfs_unmountall(void)
4744 struct mount *mp, *tmp;
4746 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4749 * Since this only runs when rebooting, it is not interlocked.
4751 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4755 * Forcibly unmounting "/dev" before "/" would prevent clean
4756 * unmount of the latter.
4758 if (mp == rootdevmp)
4761 unmount_or_warn(mp);
4764 if (rootdevmp != NULL)
4765 unmount_or_warn(rootdevmp);
4769 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4772 ASSERT_VI_LOCKED(vp, __func__);
4773 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4774 if ((vp->v_iflag & VI_OWEINACT) == 0) {
4778 if (vn_lock(vp, lkflags) == 0) {
4785 vdefer_inactive_unlocked(vp);
4789 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4792 return (vp->v_iflag & VI_DEFINACT);
4795 static void __noinline
4796 vfs_periodic_inactive(struct mount *mp, int flags)
4798 struct vnode *vp, *mvp;
4801 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4802 if (flags != MNT_WAIT)
4803 lkflags |= LK_NOWAIT;
4805 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4806 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4810 vp->v_iflag &= ~VI_DEFINACT;
4811 vfs_deferred_inactive(vp, lkflags);
4816 vfs_want_msync(struct vnode *vp)
4818 struct vm_object *obj;
4821 * This test may be performed without any locks held.
4822 * We rely on vm_object's type stability.
4824 if (vp->v_vflag & VV_NOSYNC)
4827 return (obj != NULL && vm_object_mightbedirty(obj));
4831 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4834 if (vp->v_vflag & VV_NOSYNC)
4836 if (vp->v_iflag & VI_DEFINACT)
4838 return (vfs_want_msync(vp));
4841 static void __noinline
4842 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4844 struct vnode *vp, *mvp;
4845 struct vm_object *obj;
4846 int lkflags, objflags;
4849 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4850 if (flags != MNT_WAIT) {
4851 lkflags |= LK_NOWAIT;
4852 objflags = OBJPC_NOSYNC;
4854 objflags = OBJPC_SYNC;
4857 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4859 if (vp->v_iflag & VI_DEFINACT) {
4860 vp->v_iflag &= ~VI_DEFINACT;
4863 if (!vfs_want_msync(vp)) {
4865 vfs_deferred_inactive(vp, lkflags);
4870 if (vget(vp, lkflags) == 0) {
4872 if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4873 VM_OBJECT_WLOCK(obj);
4874 vm_object_page_clean(obj, 0, 0, objflags);
4875 VM_OBJECT_WUNLOCK(obj);
4882 vdefer_inactive_unlocked(vp);
4888 vfs_periodic(struct mount *mp, int flags)
4891 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4893 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4894 vfs_periodic_inactive(mp, flags);
4896 vfs_periodic_msync_inactive(mp, flags);
4900 destroy_vpollinfo_free(struct vpollinfo *vi)
4903 knlist_destroy(&vi->vpi_selinfo.si_note);
4904 mtx_destroy(&vi->vpi_lock);
4905 free(vi, M_VNODEPOLL);
4909 destroy_vpollinfo(struct vpollinfo *vi)
4912 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4913 seldrain(&vi->vpi_selinfo);
4914 destroy_vpollinfo_free(vi);
4918 * Initialize per-vnode helper structure to hold poll-related state.
4921 v_addpollinfo(struct vnode *vp)
4923 struct vpollinfo *vi;
4925 if (vp->v_pollinfo != NULL)
4927 vi = malloc(sizeof(*vi), M_VNODEPOLL, M_WAITOK | M_ZERO);
4928 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4929 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4930 vfs_knlunlock, vfs_knl_assert_lock);
4932 if (vp->v_pollinfo != NULL) {
4934 destroy_vpollinfo_free(vi);
4937 vp->v_pollinfo = vi;
4942 * Record a process's interest in events which might happen to
4943 * a vnode. Because poll uses the historic select-style interface
4944 * internally, this routine serves as both the ``check for any
4945 * pending events'' and the ``record my interest in future events''
4946 * functions. (These are done together, while the lock is held,
4947 * to avoid race conditions.)
4950 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4954 mtx_lock(&vp->v_pollinfo->vpi_lock);
4955 if (vp->v_pollinfo->vpi_revents & events) {
4957 * This leaves events we are not interested
4958 * in available for the other process which
4959 * which presumably had requested them
4960 * (otherwise they would never have been
4963 events &= vp->v_pollinfo->vpi_revents;
4964 vp->v_pollinfo->vpi_revents &= ~events;
4966 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4969 vp->v_pollinfo->vpi_events |= events;
4970 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4971 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4976 * Routine to create and manage a filesystem syncer vnode.
4978 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4979 static int sync_fsync(struct vop_fsync_args *);
4980 static int sync_inactive(struct vop_inactive_args *);
4981 static int sync_reclaim(struct vop_reclaim_args *);
4983 static struct vop_vector sync_vnodeops = {
4984 .vop_bypass = VOP_EOPNOTSUPP,
4985 .vop_close = sync_close, /* close */
4986 .vop_fsync = sync_fsync, /* fsync */
4987 .vop_inactive = sync_inactive, /* inactive */
4988 .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
4989 .vop_reclaim = sync_reclaim, /* reclaim */
4990 .vop_lock1 = vop_stdlock, /* lock */
4991 .vop_unlock = vop_stdunlock, /* unlock */
4992 .vop_islocked = vop_stdislocked, /* islocked */
4994 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
4997 * Create a new filesystem syncer vnode for the specified mount point.
5000 vfs_allocate_syncvnode(struct mount *mp)
5004 static long start, incr, next;
5007 /* Allocate a new vnode */
5008 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
5010 panic("vfs_allocate_syncvnode: getnewvnode() failed");
5012 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5013 vp->v_vflag |= VV_FORCEINSMQ;
5014 error = insmntque(vp, mp);
5016 panic("vfs_allocate_syncvnode: insmntque() failed");
5017 vp->v_vflag &= ~VV_FORCEINSMQ;
5020 * Place the vnode onto the syncer worklist. We attempt to
5021 * scatter them about on the list so that they will go off
5022 * at evenly distributed times even if all the filesystems
5023 * are mounted at once.
5026 if (next == 0 || next > syncer_maxdelay) {
5030 start = syncer_maxdelay / 2;
5031 incr = syncer_maxdelay;
5037 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
5038 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
5039 mtx_lock(&sync_mtx);
5041 if (mp->mnt_syncer == NULL) {
5042 mp->mnt_syncer = vp;
5045 mtx_unlock(&sync_mtx);
5048 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5055 vfs_deallocate_syncvnode(struct mount *mp)
5059 mtx_lock(&sync_mtx);
5060 vp = mp->mnt_syncer;
5062 mp->mnt_syncer = NULL;
5063 mtx_unlock(&sync_mtx);
5069 * Do a lazy sync of the filesystem.
5072 sync_fsync(struct vop_fsync_args *ap)
5074 struct vnode *syncvp = ap->a_vp;
5075 struct mount *mp = syncvp->v_mount;
5080 * We only need to do something if this is a lazy evaluation.
5082 if (ap->a_waitfor != MNT_LAZY)
5086 * Move ourselves to the back of the sync list.
5088 bo = &syncvp->v_bufobj;
5090 vn_syncer_add_to_worklist(bo, syncdelay);
5094 * Walk the list of vnodes pushing all that are dirty and
5095 * not already on the sync list.
5097 if (vfs_busy(mp, MBF_NOWAIT) != 0)
5099 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
5103 save = curthread_pflags_set(TDP_SYNCIO);
5105 * The filesystem at hand may be idle with free vnodes stored in the
5106 * batch. Return them instead of letting them stay there indefinitely.
5108 vfs_periodic(mp, MNT_NOWAIT);
5109 error = VFS_SYNC(mp, MNT_LAZY);
5110 curthread_pflags_restore(save);
5111 vn_finished_write(mp);
5117 * The syncer vnode is no referenced.
5120 sync_inactive(struct vop_inactive_args *ap)
5128 * The syncer vnode is no longer needed and is being decommissioned.
5130 * Modifications to the worklist must be protected by sync_mtx.
5133 sync_reclaim(struct vop_reclaim_args *ap)
5135 struct vnode *vp = ap->a_vp;
5140 mtx_lock(&sync_mtx);
5141 if (vp->v_mount->mnt_syncer == vp)
5142 vp->v_mount->mnt_syncer = NULL;
5143 if (bo->bo_flag & BO_ONWORKLST) {
5144 LIST_REMOVE(bo, bo_synclist);
5145 syncer_worklist_len--;
5147 bo->bo_flag &= ~BO_ONWORKLST;
5149 mtx_unlock(&sync_mtx);
5156 vn_need_pageq_flush(struct vnode *vp)
5158 struct vm_object *obj;
5161 return (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
5162 vm_object_mightbedirty(obj));
5166 * Check if vnode represents a disk device
5169 vn_isdisk_error(struct vnode *vp, int *errp)
5173 if (vp->v_type != VCHR) {
5179 if (vp->v_rdev == NULL)
5181 else if (vp->v_rdev->si_devsw == NULL)
5183 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5188 return (error == 0);
5192 vn_isdisk(struct vnode *vp)
5196 return (vn_isdisk_error(vp, &error));
5200 * VOP_FPLOOKUP_VEXEC routines are subject to special circumstances, see
5201 * the comment above cache_fplookup for details.
5204 vaccess_vexec_smr(mode_t file_mode, uid_t file_uid, gid_t file_gid, struct ucred *cred)
5208 VFS_SMR_ASSERT_ENTERED();
5210 /* Check the owner. */
5211 if (cred->cr_uid == file_uid) {
5212 if (file_mode & S_IXUSR)
5217 /* Otherwise, check the groups (first match) */
5218 if (groupmember(file_gid, cred)) {
5219 if (file_mode & S_IXGRP)
5224 /* Otherwise, check everyone else. */
5225 if (file_mode & S_IXOTH)
5229 * Permission check failed, but it is possible denial will get overwritten
5230 * (e.g., when root is traversing through a 700 directory owned by someone
5233 * vaccess() calls priv_check_cred which in turn can descent into MAC
5234 * modules overriding this result. It's quite unclear what semantics
5235 * are allowed for them to operate, thus for safety we don't call them
5236 * from within the SMR section. This also means if any such modules
5237 * are present, we have to let the regular lookup decide.
5239 error = priv_check_cred_vfs_lookup_nomac(cred);
5245 * MAC modules present.
5256 * Common filesystem object access control check routine. Accepts a
5257 * vnode's type, "mode", uid and gid, requested access mode, and credentials.
5258 * Returns 0 on success, or an errno on failure.
5261 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5262 accmode_t accmode, struct ucred *cred)
5264 accmode_t dac_granted;
5265 accmode_t priv_granted;
5267 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5268 ("invalid bit in accmode"));
5269 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5270 ("VAPPEND without VWRITE"));
5273 * Look for a normal, non-privileged way to access the file/directory
5274 * as requested. If it exists, go with that.
5279 /* Check the owner. */
5280 if (cred->cr_uid == file_uid) {
5281 dac_granted |= VADMIN;
5282 if (file_mode & S_IXUSR)
5283 dac_granted |= VEXEC;
5284 if (file_mode & S_IRUSR)
5285 dac_granted |= VREAD;
5286 if (file_mode & S_IWUSR)
5287 dac_granted |= (VWRITE | VAPPEND);
5289 if ((accmode & dac_granted) == accmode)
5295 /* Otherwise, check the groups (first match) */
5296 if (groupmember(file_gid, cred)) {
5297 if (file_mode & S_IXGRP)
5298 dac_granted |= VEXEC;
5299 if (file_mode & S_IRGRP)
5300 dac_granted |= VREAD;
5301 if (file_mode & S_IWGRP)
5302 dac_granted |= (VWRITE | VAPPEND);
5304 if ((accmode & dac_granted) == accmode)
5310 /* Otherwise, check everyone else. */
5311 if (file_mode & S_IXOTH)
5312 dac_granted |= VEXEC;
5313 if (file_mode & S_IROTH)
5314 dac_granted |= VREAD;
5315 if (file_mode & S_IWOTH)
5316 dac_granted |= (VWRITE | VAPPEND);
5317 if ((accmode & dac_granted) == accmode)
5322 * Build a privilege mask to determine if the set of privileges
5323 * satisfies the requirements when combined with the granted mask
5324 * from above. For each privilege, if the privilege is required,
5325 * bitwise or the request type onto the priv_granted mask.
5331 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5332 * requests, instead of PRIV_VFS_EXEC.
5334 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5335 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5336 priv_granted |= VEXEC;
5339 * Ensure that at least one execute bit is on. Otherwise,
5340 * a privileged user will always succeed, and we don't want
5341 * this to happen unless the file really is executable.
5343 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5344 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5345 !priv_check_cred(cred, PRIV_VFS_EXEC))
5346 priv_granted |= VEXEC;
5349 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5350 !priv_check_cred(cred, PRIV_VFS_READ))
5351 priv_granted |= VREAD;
5353 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5354 !priv_check_cred(cred, PRIV_VFS_WRITE))
5355 priv_granted |= (VWRITE | VAPPEND);
5357 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5358 !priv_check_cred(cred, PRIV_VFS_ADMIN))
5359 priv_granted |= VADMIN;
5361 if ((accmode & (priv_granted | dac_granted)) == accmode) {
5365 return ((accmode & VADMIN) ? EPERM : EACCES);
5369 * Credential check based on process requesting service, and per-attribute
5373 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5374 struct thread *td, accmode_t accmode)
5378 * Kernel-invoked always succeeds.
5384 * Do not allow privileged processes in jail to directly manipulate
5385 * system attributes.
5387 switch (attrnamespace) {
5388 case EXTATTR_NAMESPACE_SYSTEM:
5389 /* Potentially should be: return (EPERM); */
5390 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5391 case EXTATTR_NAMESPACE_USER:
5392 return (VOP_ACCESS(vp, accmode, cred, td));
5398 #ifdef DEBUG_VFS_LOCKS
5400 * This only exists to suppress warnings from unlocked specfs accesses. It is
5401 * no longer ok to have an unlocked VFS.
5403 #define IGNORE_LOCK(vp) (KERNEL_PANICKED() || (vp) == NULL || \
5404 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
5406 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
5407 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5408 "Drop into debugger on lock violation");
5410 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
5411 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5412 0, "Check for interlock across VOPs");
5414 int vfs_badlock_print = 1; /* Print lock violations. */
5415 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5416 0, "Print lock violations");
5418 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
5419 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5420 0, "Print vnode details on lock violations");
5423 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
5424 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5425 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5429 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5433 if (vfs_badlock_backtrace)
5436 if (vfs_badlock_vnode)
5437 vn_printf(vp, "vnode ");
5438 if (vfs_badlock_print)
5439 printf("%s: %p %s\n", str, (void *)vp, msg);
5440 if (vfs_badlock_ddb)
5441 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5445 assert_vi_locked(struct vnode *vp, const char *str)
5448 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5449 vfs_badlock("interlock is not locked but should be", str, vp);
5453 assert_vi_unlocked(struct vnode *vp, const char *str)
5456 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5457 vfs_badlock("interlock is locked but should not be", str, vp);
5461 assert_vop_locked(struct vnode *vp, const char *str)
5465 if (!IGNORE_LOCK(vp)) {
5466 locked = VOP_ISLOCKED(vp);
5467 if (locked == 0 || locked == LK_EXCLOTHER)
5468 vfs_badlock("is not locked but should be", str, vp);
5473 assert_vop_unlocked(struct vnode *vp, const char *str)
5476 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5477 vfs_badlock("is locked but should not be", str, vp);
5481 assert_vop_elocked(struct vnode *vp, const char *str)
5484 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5485 vfs_badlock("is not exclusive locked but should be", str, vp);
5487 #endif /* DEBUG_VFS_LOCKS */
5490 vop_rename_fail(struct vop_rename_args *ap)
5493 if (ap->a_tvp != NULL)
5495 if (ap->a_tdvp == ap->a_tvp)
5504 vop_rename_pre(void *ap)
5506 struct vop_rename_args *a = ap;
5508 #ifdef DEBUG_VFS_LOCKS
5510 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5511 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5512 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5513 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5515 /* Check the source (from). */
5516 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5517 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5518 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5519 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5520 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5522 /* Check the target. */
5524 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5525 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5528 * It may be tempting to add vn_seqc_write_begin/end calls here and
5529 * in vop_rename_post but that's not going to work out since some
5530 * filesystems relookup vnodes mid-rename. This is probably a bug.
5532 * For now filesystems are expected to do the relevant calls after they
5533 * decide what vnodes to operate on.
5535 if (a->a_tdvp != a->a_fdvp)
5537 if (a->a_tvp != a->a_fvp)
5544 #ifdef DEBUG_VFS_LOCKS
5546 vop_fplookup_vexec_debugpre(void *ap __unused)
5549 VFS_SMR_ASSERT_ENTERED();
5553 vop_fplookup_vexec_debugpost(void *ap __unused, int rc __unused)
5556 VFS_SMR_ASSERT_ENTERED();
5560 vop_fplookup_symlink_debugpre(void *ap __unused)
5563 VFS_SMR_ASSERT_ENTERED();
5567 vop_fplookup_symlink_debugpost(void *ap __unused, int rc __unused)
5570 VFS_SMR_ASSERT_ENTERED();
5573 vop_strategy_debugpre(void *ap)
5575 struct vop_strategy_args *a;
5582 * Cluster ops lock their component buffers but not the IO container.
5584 if ((bp->b_flags & B_CLUSTER) != 0)
5587 if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5588 if (vfs_badlock_print)
5590 "VOP_STRATEGY: bp is not locked but should be\n");
5591 if (vfs_badlock_ddb)
5592 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5597 vop_lock_debugpre(void *ap)
5599 struct vop_lock1_args *a = ap;
5601 if ((a->a_flags & LK_INTERLOCK) == 0)
5602 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5604 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5608 vop_lock_debugpost(void *ap, int rc)
5610 struct vop_lock1_args *a = ap;
5612 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5613 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5614 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5618 vop_unlock_debugpre(void *ap)
5620 struct vop_unlock_args *a = ap;
5622 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5626 vop_need_inactive_debugpre(void *ap)
5628 struct vop_need_inactive_args *a = ap;
5630 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5634 vop_need_inactive_debugpost(void *ap, int rc)
5636 struct vop_need_inactive_args *a = ap;
5638 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5643 vop_create_pre(void *ap)
5645 struct vop_create_args *a;
5650 vn_seqc_write_begin(dvp);
5654 vop_create_post(void *ap, int rc)
5656 struct vop_create_args *a;
5661 vn_seqc_write_end(dvp);
5663 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5667 vop_whiteout_pre(void *ap)
5669 struct vop_whiteout_args *a;
5674 vn_seqc_write_begin(dvp);
5678 vop_whiteout_post(void *ap, int rc)
5680 struct vop_whiteout_args *a;
5685 vn_seqc_write_end(dvp);
5689 vop_deleteextattr_pre(void *ap)
5691 struct vop_deleteextattr_args *a;
5696 vn_seqc_write_begin(vp);
5700 vop_deleteextattr_post(void *ap, int rc)
5702 struct vop_deleteextattr_args *a;
5707 vn_seqc_write_end(vp);
5709 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5713 vop_link_pre(void *ap)
5715 struct vop_link_args *a;
5716 struct vnode *vp, *tdvp;
5721 vn_seqc_write_begin(vp);
5722 vn_seqc_write_begin(tdvp);
5726 vop_link_post(void *ap, int rc)
5728 struct vop_link_args *a;
5729 struct vnode *vp, *tdvp;
5734 vn_seqc_write_end(vp);
5735 vn_seqc_write_end(tdvp);
5737 VFS_KNOTE_LOCKED(vp, NOTE_LINK);
5738 VFS_KNOTE_LOCKED(tdvp, NOTE_WRITE);
5743 vop_mkdir_pre(void *ap)
5745 struct vop_mkdir_args *a;
5750 vn_seqc_write_begin(dvp);
5754 vop_mkdir_post(void *ap, int rc)
5756 struct vop_mkdir_args *a;
5761 vn_seqc_write_end(dvp);
5763 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5766 #ifdef DEBUG_VFS_LOCKS
5768 vop_mkdir_debugpost(void *ap, int rc)
5770 struct vop_mkdir_args *a;
5774 cache_validate(a->a_dvp, *a->a_vpp, a->a_cnp);
5779 vop_mknod_pre(void *ap)
5781 struct vop_mknod_args *a;
5786 vn_seqc_write_begin(dvp);
5790 vop_mknod_post(void *ap, int rc)
5792 struct vop_mknod_args *a;
5797 vn_seqc_write_end(dvp);
5799 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5803 vop_reclaim_post(void *ap, int rc)
5805 struct vop_reclaim_args *a;
5810 ASSERT_VOP_IN_SEQC(vp);
5812 VFS_KNOTE_LOCKED(vp, NOTE_REVOKE);
5816 vop_remove_pre(void *ap)
5818 struct vop_remove_args *a;
5819 struct vnode *dvp, *vp;
5824 vn_seqc_write_begin(dvp);
5825 vn_seqc_write_begin(vp);
5829 vop_remove_post(void *ap, int rc)
5831 struct vop_remove_args *a;
5832 struct vnode *dvp, *vp;
5837 vn_seqc_write_end(dvp);
5838 vn_seqc_write_end(vp);
5840 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5841 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5846 vop_rename_post(void *ap, int rc)
5848 struct vop_rename_args *a = ap;
5853 if (a->a_fdvp == a->a_tdvp) {
5854 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5856 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5857 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5859 hint |= NOTE_EXTEND;
5860 if (a->a_fvp->v_type == VDIR)
5862 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5864 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5865 a->a_tvp->v_type == VDIR)
5867 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5870 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5872 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5874 if (a->a_tdvp != a->a_fdvp)
5876 if (a->a_tvp != a->a_fvp)
5884 vop_rmdir_pre(void *ap)
5886 struct vop_rmdir_args *a;
5887 struct vnode *dvp, *vp;
5892 vn_seqc_write_begin(dvp);
5893 vn_seqc_write_begin(vp);
5897 vop_rmdir_post(void *ap, int rc)
5899 struct vop_rmdir_args *a;
5900 struct vnode *dvp, *vp;
5905 vn_seqc_write_end(dvp);
5906 vn_seqc_write_end(vp);
5908 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5909 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5914 vop_setattr_pre(void *ap)
5916 struct vop_setattr_args *a;
5921 vn_seqc_write_begin(vp);
5925 vop_setattr_post(void *ap, int rc)
5927 struct vop_setattr_args *a;
5932 vn_seqc_write_end(vp);
5934 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
5938 vop_setacl_pre(void *ap)
5940 struct vop_setacl_args *a;
5945 vn_seqc_write_begin(vp);
5949 vop_setacl_post(void *ap, int rc __unused)
5951 struct vop_setacl_args *a;
5956 vn_seqc_write_end(vp);
5960 vop_setextattr_pre(void *ap)
5962 struct vop_setextattr_args *a;
5967 vn_seqc_write_begin(vp);
5971 vop_setextattr_post(void *ap, int rc)
5973 struct vop_setextattr_args *a;
5978 vn_seqc_write_end(vp);
5980 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
5984 vop_symlink_pre(void *ap)
5986 struct vop_symlink_args *a;
5991 vn_seqc_write_begin(dvp);
5995 vop_symlink_post(void *ap, int rc)
5997 struct vop_symlink_args *a;
6002 vn_seqc_write_end(dvp);
6004 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6008 vop_open_post(void *ap, int rc)
6010 struct vop_open_args *a = ap;
6013 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
6017 vop_close_post(void *ap, int rc)
6019 struct vop_close_args *a = ap;
6021 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
6022 !VN_IS_DOOMED(a->a_vp))) {
6023 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
6024 NOTE_CLOSE_WRITE : NOTE_CLOSE);
6029 vop_read_post(void *ap, int rc)
6031 struct vop_read_args *a = ap;
6034 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6038 vop_read_pgcache_post(void *ap, int rc)
6040 struct vop_read_pgcache_args *a = ap;
6043 VFS_KNOTE_UNLOCKED(a->a_vp, NOTE_READ);
6047 vop_readdir_post(void *ap, int rc)
6049 struct vop_readdir_args *a = ap;
6052 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6055 static struct knlist fs_knlist;
6058 vfs_event_init(void *arg)
6060 knlist_init_mtx(&fs_knlist, NULL);
6062 /* XXX - correct order? */
6063 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
6066 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
6069 KNOTE_UNLOCKED(&fs_knlist, event);
6072 static int filt_fsattach(struct knote *kn);
6073 static void filt_fsdetach(struct knote *kn);
6074 static int filt_fsevent(struct knote *kn, long hint);
6076 struct filterops fs_filtops = {
6078 .f_attach = filt_fsattach,
6079 .f_detach = filt_fsdetach,
6080 .f_event = filt_fsevent
6084 filt_fsattach(struct knote *kn)
6087 kn->kn_flags |= EV_CLEAR;
6088 knlist_add(&fs_knlist, kn, 0);
6093 filt_fsdetach(struct knote *kn)
6096 knlist_remove(&fs_knlist, kn, 0);
6100 filt_fsevent(struct knote *kn, long hint)
6103 kn->kn_fflags |= kn->kn_sfflags & hint;
6105 return (kn->kn_fflags != 0);
6109 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
6115 error = SYSCTL_IN(req, &vc, sizeof(vc));
6118 if (vc.vc_vers != VFS_CTL_VERS1)
6120 mp = vfs_getvfs(&vc.vc_fsid);
6123 /* ensure that a specific sysctl goes to the right filesystem. */
6124 if (strcmp(vc.vc_fstypename, "*") != 0 &&
6125 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
6129 VCTLTOREQ(&vc, req);
6130 error = VFS_SYSCTL(mp, vc.vc_op, req);
6135 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
6136 NULL, 0, sysctl_vfs_ctl, "",
6140 * Function to initialize a va_filerev field sensibly.
6141 * XXX: Wouldn't a random number make a lot more sense ??
6144 init_va_filerev(void)
6149 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
6152 static int filt_vfsread(struct knote *kn, long hint);
6153 static int filt_vfswrite(struct knote *kn, long hint);
6154 static int filt_vfsvnode(struct knote *kn, long hint);
6155 static void filt_vfsdetach(struct knote *kn);
6156 static struct filterops vfsread_filtops = {
6158 .f_detach = filt_vfsdetach,
6159 .f_event = filt_vfsread
6161 static struct filterops vfswrite_filtops = {
6163 .f_detach = filt_vfsdetach,
6164 .f_event = filt_vfswrite
6166 static struct filterops vfsvnode_filtops = {
6168 .f_detach = filt_vfsdetach,
6169 .f_event = filt_vfsvnode
6173 vfs_knllock(void *arg)
6175 struct vnode *vp = arg;
6177 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
6181 vfs_knlunlock(void *arg)
6183 struct vnode *vp = arg;
6189 vfs_knl_assert_lock(void *arg, int what)
6191 #ifdef DEBUG_VFS_LOCKS
6192 struct vnode *vp = arg;
6194 if (what == LA_LOCKED)
6195 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
6197 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
6202 vfs_kqfilter(struct vop_kqfilter_args *ap)
6204 struct vnode *vp = ap->a_vp;
6205 struct knote *kn = ap->a_kn;
6208 switch (kn->kn_filter) {
6210 kn->kn_fop = &vfsread_filtops;
6213 kn->kn_fop = &vfswrite_filtops;
6216 kn->kn_fop = &vfsvnode_filtops;
6222 kn->kn_hook = (caddr_t)vp;
6225 if (vp->v_pollinfo == NULL)
6227 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
6229 knlist_add(knl, kn, 0);
6235 * Detach knote from vnode
6238 filt_vfsdetach(struct knote *kn)
6240 struct vnode *vp = (struct vnode *)kn->kn_hook;
6242 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
6243 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
6249 filt_vfsread(struct knote *kn, long hint)
6251 struct vnode *vp = (struct vnode *)kn->kn_hook;
6256 * filesystem is gone, so set the EOF flag and schedule
6257 * the knote for deletion.
6259 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6261 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6266 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
6270 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
6271 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
6278 filt_vfswrite(struct knote *kn, long hint)
6280 struct vnode *vp = (struct vnode *)kn->kn_hook;
6285 * filesystem is gone, so set the EOF flag and schedule
6286 * the knote for deletion.
6288 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
6289 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6297 filt_vfsvnode(struct knote *kn, long hint)
6299 struct vnode *vp = (struct vnode *)kn->kn_hook;
6303 if (kn->kn_sfflags & hint)
6304 kn->kn_fflags |= hint;
6305 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6306 kn->kn_flags |= EV_EOF;
6310 res = (kn->kn_fflags != 0);
6316 * Returns whether the directory is empty or not.
6317 * If it is empty, the return value is 0; otherwise
6318 * the return value is an error value (which may
6322 vfs_emptydir(struct vnode *vp)
6326 struct dirent *dirent, *dp, *endp;
6332 ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
6334 dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
6335 iov.iov_base = dirent;
6336 iov.iov_len = sizeof(struct dirent);
6341 uio.uio_resid = sizeof(struct dirent);
6342 uio.uio_segflg = UIO_SYSSPACE;
6343 uio.uio_rw = UIO_READ;
6344 uio.uio_td = curthread;
6346 while (eof == 0 && error == 0) {
6347 error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
6351 endp = (void *)((uint8_t *)dirent +
6352 sizeof(struct dirent) - uio.uio_resid);
6353 for (dp = dirent; dp < endp;
6354 dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
6355 if (dp->d_type == DT_WHT)
6357 if (dp->d_namlen == 0)
6359 if (dp->d_type != DT_DIR &&
6360 dp->d_type != DT_UNKNOWN) {
6364 if (dp->d_namlen > 2) {
6368 if (dp->d_namlen == 1 &&
6369 dp->d_name[0] != '.') {
6373 if (dp->d_namlen == 2 &&
6374 dp->d_name[1] != '.') {
6378 uio.uio_resid = sizeof(struct dirent);
6381 free(dirent, M_TEMP);
6386 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6390 if (dp->d_reclen > ap->a_uio->uio_resid)
6391 return (ENAMETOOLONG);
6392 error = uiomove(dp, dp->d_reclen, ap->a_uio);
6394 if (ap->a_ncookies != NULL) {
6395 if (ap->a_cookies != NULL)
6396 free(ap->a_cookies, M_TEMP);
6397 ap->a_cookies = NULL;
6398 *ap->a_ncookies = 0;
6402 if (ap->a_ncookies == NULL)
6405 KASSERT(ap->a_cookies,
6406 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6408 *ap->a_cookies = realloc(*ap->a_cookies,
6409 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
6410 (*ap->a_cookies)[*ap->a_ncookies] = off;
6411 *ap->a_ncookies += 1;
6416 * The purpose of this routine is to remove granularity from accmode_t,
6417 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6418 * VADMIN and VAPPEND.
6420 * If it returns 0, the caller is supposed to continue with the usual
6421 * access checks using 'accmode' as modified by this routine. If it
6422 * returns nonzero value, the caller is supposed to return that value
6425 * Note that after this routine runs, accmode may be zero.
6428 vfs_unixify_accmode(accmode_t *accmode)
6431 * There is no way to specify explicit "deny" rule using
6432 * file mode or POSIX.1e ACLs.
6434 if (*accmode & VEXPLICIT_DENY) {
6440 * None of these can be translated into usual access bits.
6441 * Also, the common case for NFSv4 ACLs is to not contain
6442 * either of these bits. Caller should check for VWRITE
6443 * on the containing directory instead.
6445 if (*accmode & (VDELETE_CHILD | VDELETE))
6448 if (*accmode & VADMIN_PERMS) {
6449 *accmode &= ~VADMIN_PERMS;
6454 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6455 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6457 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6463 * Clear out a doomed vnode (if any) and replace it with a new one as long
6464 * as the fs is not being unmounted. Return the root vnode to the caller.
6466 static int __noinline
6467 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6473 if (mp->mnt_rootvnode != NULL) {
6475 vp = mp->mnt_rootvnode;
6477 if (!VN_IS_DOOMED(vp)) {
6480 error = vn_lock(vp, flags);
6489 * Clear the old one.
6491 mp->mnt_rootvnode = NULL;
6495 vfs_op_barrier_wait(mp);
6499 error = VFS_CACHEDROOT(mp, flags, vpp);
6502 if (mp->mnt_vfs_ops == 0) {
6504 if (mp->mnt_vfs_ops != 0) {
6508 if (mp->mnt_rootvnode == NULL) {
6510 mp->mnt_rootvnode = *vpp;
6512 if (mp->mnt_rootvnode != *vpp) {
6513 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6514 panic("%s: mismatch between vnode returned "
6515 " by VFS_CACHEDROOT and the one cached "
6517 __func__, *vpp, mp->mnt_rootvnode);
6527 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6529 struct mount_pcpu *mpcpu;
6533 if (!vfs_op_thread_enter(mp, mpcpu))
6534 return (vfs_cache_root_fallback(mp, flags, vpp));
6535 vp = atomic_load_ptr(&mp->mnt_rootvnode);
6536 if (vp == NULL || VN_IS_DOOMED(vp)) {
6537 vfs_op_thread_exit(mp, mpcpu);
6538 return (vfs_cache_root_fallback(mp, flags, vpp));
6541 vfs_op_thread_exit(mp, mpcpu);
6542 error = vn_lock(vp, flags);
6545 return (vfs_cache_root_fallback(mp, flags, vpp));
6552 vfs_cache_root_clear(struct mount *mp)
6557 * ops > 0 guarantees there is nobody who can see this vnode
6559 MPASS(mp->mnt_vfs_ops > 0);
6560 vp = mp->mnt_rootvnode;
6562 vn_seqc_write_begin(vp);
6563 mp->mnt_rootvnode = NULL;
6568 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6571 MPASS(mp->mnt_vfs_ops > 0);
6573 mp->mnt_rootvnode = vp;
6577 * These are helper functions for filesystems to traverse all
6578 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6580 * This interface replaces MNT_VNODE_FOREACH.
6584 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6589 kern_yield(PRI_USER);
6591 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6592 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6593 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6594 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6595 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6598 if (VN_IS_DOOMED(vp)) {
6605 __mnt_vnode_markerfree_all(mvp, mp);
6606 /* MNT_IUNLOCK(mp); -- done in above function */
6607 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6610 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6611 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6617 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6621 *mvp = vn_alloc_marker(mp);
6625 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6626 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6627 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6630 if (VN_IS_DOOMED(vp)) {
6639 vn_free_marker(*mvp);
6643 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6649 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6657 mtx_assert(MNT_MTX(mp), MA_OWNED);
6659 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6660 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6663 vn_free_marker(*mvp);
6668 * These are helper functions for filesystems to traverse their
6669 * lazy vnodes. See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6672 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6675 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6680 vn_free_marker(*mvp);
6685 * Relock the mp mount vnode list lock with the vp vnode interlock in the
6686 * conventional lock order during mnt_vnode_next_lazy iteration.
6688 * On entry, the mount vnode list lock is held and the vnode interlock is not.
6689 * The list lock is dropped and reacquired. On success, both locks are held.
6690 * On failure, the mount vnode list lock is held but the vnode interlock is
6691 * not, and the procedure may have yielded.
6694 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6698 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6699 TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6700 ("%s: bad marker", __func__));
6701 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6702 ("%s: inappropriate vnode", __func__));
6703 ASSERT_VI_UNLOCKED(vp, __func__);
6704 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6706 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6707 TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6710 * Note we may be racing against vdrop which transitioned the hold
6711 * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
6712 * if we are the only user after we get the interlock we will just
6716 mtx_unlock(&mp->mnt_listmtx);
6718 if (VN_IS_DOOMED(vp)) {
6719 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
6722 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
6724 * There is nothing to do if we are the last user.
6726 if (!refcount_release_if_not_last(&vp->v_holdcnt))
6728 mtx_lock(&mp->mnt_listmtx);
6733 mtx_lock(&mp->mnt_listmtx);
6737 static struct vnode *
6738 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6743 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6744 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6746 vp = TAILQ_NEXT(*mvp, v_lazylist);
6747 while (vp != NULL) {
6748 if (vp->v_type == VMARKER) {
6749 vp = TAILQ_NEXT(vp, v_lazylist);
6753 * See if we want to process the vnode. Note we may encounter a
6754 * long string of vnodes we don't care about and hog the list
6755 * as a result. Check for it and requeue the marker.
6757 VNPASS(!VN_IS_DOOMED(vp), vp);
6758 if (!cb(vp, cbarg)) {
6759 if (!should_yield()) {
6760 vp = TAILQ_NEXT(vp, v_lazylist);
6763 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6765 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6767 mtx_unlock(&mp->mnt_listmtx);
6768 kern_yield(PRI_USER);
6769 mtx_lock(&mp->mnt_listmtx);
6773 * Try-lock because this is the wrong lock order.
6775 if (!VI_TRYLOCK(vp) &&
6776 !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6778 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6779 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6780 ("alien vnode on the lazy list %p %p", vp, mp));
6781 VNPASS(vp->v_mount == mp, vp);
6782 VNPASS(!VN_IS_DOOMED(vp), vp);
6785 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6787 /* Check if we are done */
6789 mtx_unlock(&mp->mnt_listmtx);
6790 mnt_vnode_markerfree_lazy(mvp, mp);
6793 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6794 mtx_unlock(&mp->mnt_listmtx);
6795 ASSERT_VI_LOCKED(vp, "lazy iter");
6800 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6805 kern_yield(PRI_USER);
6806 mtx_lock(&mp->mnt_listmtx);
6807 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6811 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6816 if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
6819 *mvp = vn_alloc_marker(mp);
6824 mtx_lock(&mp->mnt_listmtx);
6825 vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6827 mtx_unlock(&mp->mnt_listmtx);
6828 mnt_vnode_markerfree_lazy(mvp, mp);
6831 TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6832 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6836 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6842 mtx_lock(&mp->mnt_listmtx);
6843 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6844 mtx_unlock(&mp->mnt_listmtx);
6845 mnt_vnode_markerfree_lazy(mvp, mp);
6849 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
6852 if ((cnp->cn_flags & NOEXECCHECK) != 0) {
6853 cnp->cn_flags &= ~NOEXECCHECK;
6857 return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, cnp->cn_thread));
6861 * Do not use this variant unless you have means other than the hold count
6862 * to prevent the vnode from getting freed.
6865 vn_seqc_write_begin_locked(struct vnode *vp)
6868 ASSERT_VI_LOCKED(vp, __func__);
6869 VNPASS(vp->v_holdcnt > 0, vp);
6870 VNPASS(vp->v_seqc_users >= 0, vp);
6872 if (vp->v_seqc_users == 1)
6873 seqc_sleepable_write_begin(&vp->v_seqc);
6877 vn_seqc_write_begin(struct vnode *vp)
6881 vn_seqc_write_begin_locked(vp);
6886 vn_seqc_write_end_locked(struct vnode *vp)
6889 ASSERT_VI_LOCKED(vp, __func__);
6890 VNPASS(vp->v_seqc_users > 0, vp);
6892 if (vp->v_seqc_users == 0)
6893 seqc_sleepable_write_end(&vp->v_seqc);
6897 vn_seqc_write_end(struct vnode *vp)
6901 vn_seqc_write_end_locked(vp);
6906 * Special case handling for allocating and freeing vnodes.
6908 * The counter remains unchanged on free so that a doomed vnode will
6909 * keep testing as in modify as long as it is accessible with SMR.
6912 vn_seqc_init(struct vnode *vp)
6916 vp->v_seqc_users = 0;
6920 vn_seqc_write_end_free(struct vnode *vp)
6923 VNPASS(seqc_in_modify(vp->v_seqc), vp);
6924 VNPASS(vp->v_seqc_users == 1, vp);
6928 vn_irflag_set_locked(struct vnode *vp, short toset)
6932 ASSERT_VI_LOCKED(vp, __func__);
6933 flags = vn_irflag_read(vp);
6934 VNASSERT((flags & toset) == 0, vp,
6935 ("%s: some of the passed flags already set (have %d, passed %d)\n",
6936 __func__, flags, toset));
6937 atomic_store_short(&vp->v_irflag, flags | toset);
6941 vn_irflag_set(struct vnode *vp, short toset)
6945 vn_irflag_set_locked(vp, toset);
6950 vn_irflag_set_cond_locked(struct vnode *vp, short toset)
6954 ASSERT_VI_LOCKED(vp, __func__);
6955 flags = vn_irflag_read(vp);
6956 atomic_store_short(&vp->v_irflag, flags | toset);
6960 vn_irflag_set_cond(struct vnode *vp, short toset)
6964 vn_irflag_set_cond_locked(vp, toset);
6969 vn_irflag_unset_locked(struct vnode *vp, short tounset)
6973 ASSERT_VI_LOCKED(vp, __func__);
6974 flags = vn_irflag_read(vp);
6975 VNASSERT((flags & tounset) == tounset, vp,
6976 ("%s: some of the passed flags not set (have %d, passed %d)\n",
6977 __func__, flags, tounset));
6978 atomic_store_short(&vp->v_irflag, flags & ~tounset);
6982 vn_irflag_unset(struct vnode *vp, short tounset)
6986 vn_irflag_unset_locked(vp, tounset);