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 * Number of vnodes in existence. Increased whenever getnewvnode()
126 * allocates a new vnode, decreased in vdropl() for VIRF_DOOMED vnode.
128 static u_long __exclusive_cache_line numvnodes;
130 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
131 "Number of vnodes in existence");
133 static counter_u64_t vnodes_created;
134 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
135 "Number of vnodes created by getnewvnode");
138 * Conversion tables for conversion from vnode types to inode formats
141 enum vtype iftovt_tab[16] = {
142 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
143 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
145 int vttoif_tab[10] = {
146 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
147 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
151 * List of allocates vnodes in the system.
153 static TAILQ_HEAD(freelst, vnode) vnode_list;
154 static struct vnode *vnode_list_free_marker;
155 static struct vnode *vnode_list_reclaim_marker;
158 * "Free" vnode target. Free vnodes are rarely completely free, but are
159 * just ones that are cheap to recycle. Usually they are for files which
160 * have been stat'd but not read; these usually have inode and namecache
161 * data attached to them. This target is the preferred minimum size of a
162 * sub-cache consisting mostly of such files. The system balances the size
163 * of this sub-cache with its complement to try to prevent either from
164 * thrashing while the other is relatively inactive. The targets express
165 * a preference for the best balance.
167 * "Above" this target there are 2 further targets (watermarks) related
168 * to recyling of free vnodes. In the best-operating case, the cache is
169 * exactly full, the free list has size between vlowat and vhiwat above the
170 * free target, and recycling from it and normal use maintains this state.
171 * Sometimes the free list is below vlowat or even empty, but this state
172 * is even better for immediate use provided the cache is not full.
173 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
174 * ones) to reach one of these states. The watermarks are currently hard-
175 * coded as 4% and 9% of the available space higher. These and the default
176 * of 25% for wantfreevnodes are too large if the memory size is large.
177 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
178 * whenever vnlru_proc() becomes active.
180 static long wantfreevnodes;
181 static long __exclusive_cache_line freevnodes;
182 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
183 &freevnodes, 0, "Number of \"free\" vnodes");
184 static long freevnodes_old;
186 static counter_u64_t recycles_count;
187 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
188 "Number of vnodes recycled to meet vnode cache targets");
190 static counter_u64_t recycles_free_count;
191 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD, &recycles_free_count,
192 "Number of free vnodes recycled to meet vnode cache targets");
194 static counter_u64_t deferred_inact;
195 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, deferred_inact, CTLFLAG_RD, &deferred_inact,
196 "Number of times inactive processing was deferred");
198 /* To keep more than one thread at a time from running vfs_getnewfsid */
199 static struct mtx mntid_mtx;
202 * Lock for any access to the following:
207 static struct mtx __exclusive_cache_line vnode_list_mtx;
209 /* Publicly exported FS */
210 struct nfs_public nfs_pub;
212 static uma_zone_t buf_trie_zone;
213 static smr_t buf_trie_smr;
215 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
216 static uma_zone_t vnode_zone;
217 MALLOC_DEFINE(M_VNODEPOLL, "VN POLL", "vnode poll");
219 __read_frequently smr_t vfs_smr;
222 * The workitem queue.
224 * It is useful to delay writes of file data and filesystem metadata
225 * for tens of seconds so that quickly created and deleted files need
226 * not waste disk bandwidth being created and removed. To realize this,
227 * we append vnodes to a "workitem" queue. When running with a soft
228 * updates implementation, most pending metadata dependencies should
229 * not wait for more than a few seconds. Thus, mounted on block devices
230 * are delayed only about a half the time that file data is delayed.
231 * Similarly, directory updates are more critical, so are only delayed
232 * about a third the time that file data is delayed. Thus, there are
233 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
234 * one each second (driven off the filesystem syncer process). The
235 * syncer_delayno variable indicates the next queue that is to be processed.
236 * Items that need to be processed soon are placed in this queue:
238 * syncer_workitem_pending[syncer_delayno]
240 * A delay of fifteen seconds is done by placing the request fifteen
241 * entries later in the queue:
243 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
246 static int syncer_delayno;
247 static long syncer_mask;
248 LIST_HEAD(synclist, bufobj);
249 static struct synclist *syncer_workitem_pending;
251 * The sync_mtx protects:
256 * syncer_workitem_pending
257 * syncer_worklist_len
260 static struct mtx sync_mtx;
261 static struct cv sync_wakeup;
263 #define SYNCER_MAXDELAY 32
264 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
265 static int syncdelay = 30; /* max time to delay syncing data */
266 static int filedelay = 30; /* time to delay syncing files */
267 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
268 "Time to delay syncing files (in seconds)");
269 static int dirdelay = 29; /* time to delay syncing directories */
270 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
271 "Time to delay syncing directories (in seconds)");
272 static int metadelay = 28; /* time to delay syncing metadata */
273 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
274 "Time to delay syncing metadata (in seconds)");
275 static int rushjob; /* number of slots to run ASAP */
276 static int stat_rush_requests; /* number of times I/O speeded up */
277 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
278 "Number of times I/O speeded up (rush requests)");
280 #define VDBATCH_SIZE 8
285 struct vnode *tab[VDBATCH_SIZE];
287 DPCPU_DEFINE_STATIC(struct vdbatch, vd);
289 static void vdbatch_dequeue(struct vnode *vp);
292 * When shutting down the syncer, run it at four times normal speed.
294 #define SYNCER_SHUTDOWN_SPEEDUP 4
295 static int sync_vnode_count;
296 static int syncer_worklist_len;
297 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
300 /* Target for maximum number of vnodes. */
301 u_long desiredvnodes;
302 static u_long gapvnodes; /* gap between wanted and desired */
303 static u_long vhiwat; /* enough extras after expansion */
304 static u_long vlowat; /* minimal extras before expansion */
305 static u_long vstir; /* nonzero to stir non-free vnodes */
306 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
308 static u_long vnlru_read_freevnodes(void);
311 * Note that no attempt is made to sanitize these parameters.
314 sysctl_maxvnodes(SYSCTL_HANDLER_ARGS)
320 error = sysctl_handle_long(oidp, &val, 0, req);
321 if (error != 0 || req->newptr == NULL)
324 if (val == desiredvnodes)
326 mtx_lock(&vnode_list_mtx);
328 wantfreevnodes = desiredvnodes / 4;
330 mtx_unlock(&vnode_list_mtx);
332 * XXX There is no protection against multiple threads changing
333 * desiredvnodes at the same time. Locking above only helps vnlru and
336 vfs_hash_changesize(desiredvnodes);
337 cache_changesize(desiredvnodes);
341 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
342 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
343 "LU", "Target for maximum number of vnodes");
346 sysctl_wantfreevnodes(SYSCTL_HANDLER_ARGS)
351 val = wantfreevnodes;
352 error = sysctl_handle_long(oidp, &val, 0, req);
353 if (error != 0 || req->newptr == NULL)
356 if (val == wantfreevnodes)
358 mtx_lock(&vnode_list_mtx);
359 wantfreevnodes = val;
361 mtx_unlock(&vnode_list_mtx);
365 SYSCTL_PROC(_vfs, OID_AUTO, wantfreevnodes,
366 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
367 "LU", "Target for minimum number of \"free\" vnodes");
369 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
370 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
371 static int vnlru_nowhere;
372 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
373 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
376 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
381 unsigned long ndflags;
384 if (req->newptr == NULL)
386 if (req->newlen >= PATH_MAX)
389 buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
390 error = SYSCTL_IN(req, buf, req->newlen);
394 buf[req->newlen] = '\0';
396 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | SAVENAME;
397 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
398 if ((error = namei(&nd)) != 0)
402 if (VN_IS_DOOMED(vp)) {
404 * This vnode is being recycled. Return != 0 to let the caller
405 * know that the sysctl had no effect. Return EAGAIN because a
406 * subsequent call will likely succeed (since namei will create
407 * a new vnode if necessary)
413 counter_u64_add(recycles_count, 1);
423 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
425 struct thread *td = curthread;
431 if (req->newptr == NULL)
434 error = sysctl_handle_int(oidp, &fd, 0, req);
437 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
442 error = vn_lock(vp, LK_EXCLUSIVE);
446 counter_u64_add(recycles_count, 1);
454 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
455 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
456 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
457 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
458 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
459 sysctl_ftry_reclaim_vnode, "I",
460 "Try to reclaim a vnode by its file descriptor");
462 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
466 * Support for the bufobj clean & dirty pctrie.
469 buf_trie_alloc(struct pctrie *ptree)
471 return (uma_zalloc_smr(buf_trie_zone, M_NOWAIT));
475 buf_trie_free(struct pctrie *ptree, void *node)
477 uma_zfree_smr(buf_trie_zone, node);
479 PCTRIE_DEFINE_SMR(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free,
483 * Initialize the vnode management data structures.
485 * Reevaluate the following cap on the number of vnodes after the physical
486 * memory size exceeds 512GB. In the limit, as the physical memory size
487 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
489 #ifndef MAXVNODES_MAX
490 #define MAXVNODES_MAX (512UL * 1024 * 1024 / 64) /* 8M */
493 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
495 static struct vnode *
496 vn_alloc_marker(struct mount *mp)
500 vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
501 vp->v_type = VMARKER;
508 vn_free_marker(struct vnode *vp)
511 MPASS(vp->v_type == VMARKER);
512 free(vp, M_VNODE_MARKER);
517 vnode_ctor(void *mem, int size, void *arg __unused, int flags __unused)
519 kasan_mark(mem, size, roundup2(size, UMA_ALIGN_PTR + 1), 0);
524 vnode_dtor(void *mem, int size, void *arg __unused)
526 size_t end1, end2, off1, off2;
528 _Static_assert(offsetof(struct vnode, v_vnodelist) <
529 offsetof(struct vnode, v_dbatchcpu),
530 "KASAN marks require updating");
532 off1 = offsetof(struct vnode, v_vnodelist);
533 off2 = offsetof(struct vnode, v_dbatchcpu);
534 end1 = off1 + sizeof(((struct vnode *)NULL)->v_vnodelist);
535 end2 = off2 + sizeof(((struct vnode *)NULL)->v_dbatchcpu);
538 * Access to the v_vnodelist and v_dbatchcpu fields are permitted even
539 * after the vnode has been freed. Try to get some KASAN coverage by
540 * marking everything except those two fields as invalid. Because
541 * KASAN's tracking is not byte-granular, any preceding fields sharing
542 * the same 8-byte aligned word must also be marked valid.
545 /* Handle the area from the start until v_vnodelist... */
546 off1 = rounddown2(off1, KASAN_SHADOW_SCALE);
547 kasan_mark(mem, off1, off1, KASAN_UMA_FREED);
549 /* ... then the area between v_vnodelist and v_dbatchcpu ... */
550 off1 = roundup2(end1, KASAN_SHADOW_SCALE);
551 off2 = rounddown2(off2, KASAN_SHADOW_SCALE);
553 kasan_mark((void *)((char *)mem + off1), off2 - off1,
554 off2 - off1, KASAN_UMA_FREED);
556 /* ... and finally the area from v_dbatchcpu to the end. */
557 off2 = roundup2(end2, KASAN_SHADOW_SCALE);
558 kasan_mark((void *)((char *)mem + off2), size - off2, size - off2,
564 * Initialize a vnode as it first enters the zone.
567 vnode_init(void *mem, int size, int flags)
576 vp->v_vnlock = &vp->v_lock;
577 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
579 * By default, don't allow shared locks unless filesystems opt-in.
581 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
582 LK_NOSHARE | LK_IS_VNODE);
586 bufobj_init(&vp->v_bufobj, vp);
588 * Initialize namecache.
590 cache_vnode_init(vp);
592 * Initialize rangelocks.
594 rangelock_init(&vp->v_rl);
596 vp->v_dbatchcpu = NOCPU;
599 * Check vhold_recycle_free for an explanation.
601 vp->v_holdcnt = VHOLD_NO_SMR;
603 mtx_lock(&vnode_list_mtx);
604 TAILQ_INSERT_BEFORE(vnode_list_free_marker, vp, v_vnodelist);
605 mtx_unlock(&vnode_list_mtx);
610 * Free a vnode when it is cleared from the zone.
613 vnode_fini(void *mem, int size)
620 mtx_lock(&vnode_list_mtx);
621 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
622 mtx_unlock(&vnode_list_mtx);
623 rangelock_destroy(&vp->v_rl);
624 lockdestroy(vp->v_vnlock);
625 mtx_destroy(&vp->v_interlock);
627 rw_destroy(BO_LOCKPTR(bo));
629 kasan_mark(mem, size, size, 0);
633 * Provide the size of NFS nclnode and NFS fh for calculation of the
634 * vnode memory consumption. The size is specified directly to
635 * eliminate dependency on NFS-private header.
637 * Other filesystems may use bigger or smaller (like UFS and ZFS)
638 * private inode data, but the NFS-based estimation is ample enough.
639 * Still, we care about differences in the size between 64- and 32-bit
642 * Namecache structure size is heuristically
643 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
646 #define NFS_NCLNODE_SZ (528 + 64)
649 #define NFS_NCLNODE_SZ (360 + 32)
654 vntblinit(void *dummy __unused)
659 int cpu, physvnodes, virtvnodes;
663 * Desiredvnodes is a function of the physical memory size and the
664 * kernel's heap size. Generally speaking, it scales with the
665 * physical memory size. The ratio of desiredvnodes to the physical
666 * memory size is 1:16 until desiredvnodes exceeds 98,304.
668 * marginal ratio of desiredvnodes to the physical memory size is
669 * 1:64. However, desiredvnodes is limited by the kernel's heap
670 * size. The memory required by desiredvnodes vnodes and vm objects
671 * must not exceed 1/10th of the kernel's heap size.
673 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
674 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
675 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
676 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
677 desiredvnodes = min(physvnodes, virtvnodes);
678 if (desiredvnodes > MAXVNODES_MAX) {
680 printf("Reducing kern.maxvnodes %lu -> %lu\n",
681 desiredvnodes, MAXVNODES_MAX);
682 desiredvnodes = MAXVNODES_MAX;
684 wantfreevnodes = desiredvnodes / 4;
685 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
686 TAILQ_INIT(&vnode_list);
687 mtx_init(&vnode_list_mtx, "vnode_list", NULL, MTX_DEF);
689 * The lock is taken to appease WITNESS.
691 mtx_lock(&vnode_list_mtx);
693 mtx_unlock(&vnode_list_mtx);
694 vnode_list_free_marker = vn_alloc_marker(NULL);
695 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_free_marker, v_vnodelist);
696 vnode_list_reclaim_marker = vn_alloc_marker(NULL);
697 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_reclaim_marker, v_vnodelist);
706 vnode_zone = uma_zcreate("VNODE", sizeof(struct vnode), ctor, dtor,
707 vnode_init, vnode_fini, UMA_ALIGN_PTR, UMA_ZONE_NOKASAN);
708 uma_zone_set_smr(vnode_zone, vfs_smr);
711 * Preallocate enough nodes to support one-per buf so that
712 * we can not fail an insert. reassignbuf() callers can not
713 * tolerate the insertion failure.
715 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
716 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
717 UMA_ZONE_NOFREE | UMA_ZONE_SMR);
718 buf_trie_smr = uma_zone_get_smr(buf_trie_zone);
719 uma_prealloc(buf_trie_zone, nbuf);
721 vnodes_created = counter_u64_alloc(M_WAITOK);
722 recycles_count = counter_u64_alloc(M_WAITOK);
723 recycles_free_count = counter_u64_alloc(M_WAITOK);
724 deferred_inact = counter_u64_alloc(M_WAITOK);
727 * Initialize the filesystem syncer.
729 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
731 syncer_maxdelay = syncer_mask + 1;
732 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
733 cv_init(&sync_wakeup, "syncer");
734 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
739 vd = DPCPU_ID_PTR((cpu), vd);
740 bzero(vd, sizeof(*vd));
741 mtx_init(&vd->lock, "vdbatch", NULL, MTX_DEF);
744 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
747 * Mark a mount point as busy. Used to synchronize access and to delay
748 * unmounting. Eventually, mountlist_mtx is not released on failure.
750 * vfs_busy() is a custom lock, it can block the caller.
751 * vfs_busy() only sleeps if the unmount is active on the mount point.
752 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
753 * vnode belonging to mp.
755 * Lookup uses vfs_busy() to traverse mount points.
757 * / vnode lock A / vnode lock (/var) D
758 * /var vnode lock B /log vnode lock(/var/log) E
759 * vfs_busy lock C vfs_busy lock F
761 * Within each file system, the lock order is C->A->B and F->D->E.
763 * When traversing across mounts, the system follows that lock order:
769 * The lookup() process for namei("/var") illustrates the process:
770 * VOP_LOOKUP() obtains B while A is held
771 * vfs_busy() obtains a shared lock on F while A and B are held
772 * vput() releases lock on B
773 * vput() releases lock on A
774 * VFS_ROOT() obtains lock on D while shared lock on F is held
775 * vfs_unbusy() releases shared lock on F
776 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
777 * Attempt to lock A (instead of vp_crossmp) while D is held would
778 * violate the global order, causing deadlocks.
780 * dounmount() locks B while F is drained.
783 vfs_busy(struct mount *mp, int flags)
785 struct mount_pcpu *mpcpu;
787 MPASS((flags & ~MBF_MASK) == 0);
788 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
790 if (vfs_op_thread_enter(mp, mpcpu)) {
791 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
792 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
793 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
794 vfs_mp_count_add_pcpu(mpcpu, ref, 1);
795 vfs_mp_count_add_pcpu(mpcpu, lockref, 1);
796 vfs_op_thread_exit(mp, mpcpu);
797 if (flags & MBF_MNTLSTLOCK)
798 mtx_unlock(&mountlist_mtx);
803 vfs_assert_mount_counters(mp);
806 * If mount point is currently being unmounted, sleep until the
807 * mount point fate is decided. If thread doing the unmounting fails,
808 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
809 * that this mount point has survived the unmount attempt and vfs_busy
810 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
811 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
812 * about to be really destroyed. vfs_busy needs to release its
813 * reference on the mount point in this case and return with ENOENT,
814 * telling the caller that mount mount it tried to busy is no longer
817 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
818 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
821 CTR1(KTR_VFS, "%s: failed busying before sleeping",
825 if (flags & MBF_MNTLSTLOCK)
826 mtx_unlock(&mountlist_mtx);
827 mp->mnt_kern_flag |= MNTK_MWAIT;
828 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
829 if (flags & MBF_MNTLSTLOCK)
830 mtx_lock(&mountlist_mtx);
833 if (flags & MBF_MNTLSTLOCK)
834 mtx_unlock(&mountlist_mtx);
841 * Free a busy filesystem.
844 vfs_unbusy(struct mount *mp)
846 struct mount_pcpu *mpcpu;
849 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
851 if (vfs_op_thread_enter(mp, mpcpu)) {
852 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
853 vfs_mp_count_sub_pcpu(mpcpu, lockref, 1);
854 vfs_mp_count_sub_pcpu(mpcpu, ref, 1);
855 vfs_op_thread_exit(mp, mpcpu);
860 vfs_assert_mount_counters(mp);
862 c = --mp->mnt_lockref;
863 if (mp->mnt_vfs_ops == 0) {
864 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
869 vfs_dump_mount_counters(mp);
870 if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
871 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
872 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
873 mp->mnt_kern_flag &= ~MNTK_DRAINING;
874 wakeup(&mp->mnt_lockref);
880 * Lookup a mount point by filesystem identifier.
883 vfs_getvfs(fsid_t *fsid)
887 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
888 mtx_lock(&mountlist_mtx);
889 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
890 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
892 mtx_unlock(&mountlist_mtx);
896 mtx_unlock(&mountlist_mtx);
897 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
898 return ((struct mount *) 0);
902 * Lookup a mount point by filesystem identifier, busying it before
905 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
906 * cache for popular filesystem identifiers. The cache is lockess, using
907 * the fact that struct mount's are never freed. In worst case we may
908 * get pointer to unmounted or even different filesystem, so we have to
909 * check what we got, and go slow way if so.
912 vfs_busyfs(fsid_t *fsid)
914 #define FSID_CACHE_SIZE 256
915 typedef struct mount * volatile vmp_t;
916 static vmp_t cache[FSID_CACHE_SIZE];
921 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
922 hash = fsid->val[0] ^ fsid->val[1];
923 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
925 if (mp == NULL || fsidcmp(&mp->mnt_stat.f_fsid, fsid) != 0)
927 if (vfs_busy(mp, 0) != 0) {
931 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0)
937 mtx_lock(&mountlist_mtx);
938 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
939 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
940 error = vfs_busy(mp, MBF_MNTLSTLOCK);
943 mtx_unlock(&mountlist_mtx);
950 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
951 mtx_unlock(&mountlist_mtx);
952 return ((struct mount *) 0);
956 * Check if a user can access privileged mount options.
959 vfs_suser(struct mount *mp, struct thread *td)
963 if (jailed(td->td_ucred)) {
965 * If the jail of the calling thread lacks permission for
966 * this type of file system, deny immediately.
968 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
972 * If the file system was mounted outside the jail of the
973 * calling thread, deny immediately.
975 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
980 * If file system supports delegated administration, we don't check
981 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
982 * by the file system itself.
983 * If this is not the user that did original mount, we check for
984 * the PRIV_VFS_MOUNT_OWNER privilege.
986 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
987 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
988 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
995 * Get a new unique fsid. Try to make its val[0] unique, since this value
996 * will be used to create fake device numbers for stat(). Also try (but
997 * not so hard) make its val[0] unique mod 2^16, since some emulators only
998 * support 16-bit device numbers. We end up with unique val[0]'s for the
999 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
1001 * Keep in mind that several mounts may be running in parallel. Starting
1002 * the search one past where the previous search terminated is both a
1003 * micro-optimization and a defense against returning the same fsid to
1007 vfs_getnewfsid(struct mount *mp)
1009 static uint16_t mntid_base;
1014 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
1015 mtx_lock(&mntid_mtx);
1016 mtype = mp->mnt_vfc->vfc_typenum;
1017 tfsid.val[1] = mtype;
1018 mtype = (mtype & 0xFF) << 24;
1020 tfsid.val[0] = makedev(255,
1021 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
1023 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
1027 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
1028 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
1029 mtx_unlock(&mntid_mtx);
1033 * Knob to control the precision of file timestamps:
1035 * 0 = seconds only; nanoseconds zeroed.
1036 * 1 = seconds and nanoseconds, accurate within 1/HZ.
1037 * 2 = seconds and nanoseconds, truncated to microseconds.
1038 * >=3 = seconds and nanoseconds, maximum precision.
1040 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
1042 static int timestamp_precision = TSP_USEC;
1043 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
1044 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
1045 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
1046 "3+: sec + ns (max. precision))");
1049 * Get a current timestamp.
1052 vfs_timestamp(struct timespec *tsp)
1056 switch (timestamp_precision) {
1058 tsp->tv_sec = time_second;
1066 TIMEVAL_TO_TIMESPEC(&tv, tsp);
1076 * Set vnode attributes to VNOVAL
1079 vattr_null(struct vattr *vap)
1082 vap->va_type = VNON;
1083 vap->va_size = VNOVAL;
1084 vap->va_bytes = VNOVAL;
1085 vap->va_mode = VNOVAL;
1086 vap->va_nlink = VNOVAL;
1087 vap->va_uid = VNOVAL;
1088 vap->va_gid = VNOVAL;
1089 vap->va_fsid = VNOVAL;
1090 vap->va_fileid = VNOVAL;
1091 vap->va_blocksize = VNOVAL;
1092 vap->va_rdev = VNOVAL;
1093 vap->va_atime.tv_sec = VNOVAL;
1094 vap->va_atime.tv_nsec = VNOVAL;
1095 vap->va_mtime.tv_sec = VNOVAL;
1096 vap->va_mtime.tv_nsec = VNOVAL;
1097 vap->va_ctime.tv_sec = VNOVAL;
1098 vap->va_ctime.tv_nsec = VNOVAL;
1099 vap->va_birthtime.tv_sec = VNOVAL;
1100 vap->va_birthtime.tv_nsec = VNOVAL;
1101 vap->va_flags = VNOVAL;
1102 vap->va_gen = VNOVAL;
1103 vap->va_vaflags = 0;
1107 * Try to reduce the total number of vnodes.
1109 * This routine (and its user) are buggy in at least the following ways:
1110 * - all parameters were picked years ago when RAM sizes were significantly
1112 * - it can pick vnodes based on pages used by the vm object, but filesystems
1113 * like ZFS don't use it making the pick broken
1114 * - since ZFS has its own aging policy it gets partially combated by this one
1115 * - a dedicated method should be provided for filesystems to let them decide
1116 * whether the vnode should be recycled
1118 * This routine is called when we have too many vnodes. It attempts
1119 * to free <count> vnodes and will potentially free vnodes that still
1120 * have VM backing store (VM backing store is typically the cause
1121 * of a vnode blowout so we want to do this). Therefore, this operation
1122 * is not considered cheap.
1124 * A number of conditions may prevent a vnode from being reclaimed.
1125 * the buffer cache may have references on the vnode, a directory
1126 * vnode may still have references due to the namei cache representing
1127 * underlying files, or the vnode may be in active use. It is not
1128 * desirable to reuse such vnodes. These conditions may cause the
1129 * number of vnodes to reach some minimum value regardless of what
1130 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
1132 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1133 * entries if this argument is strue
1134 * @param trigger Only reclaim vnodes with fewer than this many resident
1136 * @param target How many vnodes to reclaim.
1137 * @return The number of vnodes that were reclaimed.
1140 vlrureclaim(bool reclaim_nc_src, int trigger, u_long target)
1142 struct vnode *vp, *mvp;
1144 struct vm_object *object;
1148 mtx_assert(&vnode_list_mtx, MA_OWNED);
1153 mvp = vnode_list_reclaim_marker;
1156 while (done < target) {
1157 vp = TAILQ_NEXT(vp, v_vnodelist);
1158 if (__predict_false(vp == NULL))
1161 if (__predict_false(vp->v_type == VMARKER))
1165 * If it's been deconstructed already, it's still
1166 * referenced, or it exceeds the trigger, skip it.
1167 * Also skip free vnodes. We are trying to make space
1168 * to expand the free list, not reduce it.
1170 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1171 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)))
1174 if (vp->v_type == VBAD || vp->v_type == VNON)
1177 object = atomic_load_ptr(&vp->v_object);
1178 if (object == NULL || object->resident_page_count > trigger) {
1183 * Handle races against vnode allocation. Filesystems lock the
1184 * vnode some time after it gets returned from getnewvnode,
1185 * despite type and hold count being manipulated earlier.
1186 * Resorting to checking v_mount restores guarantees present
1187 * before the global list was reworked to contain all vnodes.
1189 if (!VI_TRYLOCK(vp))
1191 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1195 if (vp->v_mount == NULL) {
1201 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1202 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1203 mtx_unlock(&vnode_list_mtx);
1205 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1207 goto next_iter_unlocked;
1209 if (VOP_LOCK(vp, LK_EXCLUSIVE|LK_NOWAIT) != 0) {
1211 vn_finished_write(mp);
1212 goto next_iter_unlocked;
1216 if (vp->v_usecount > 0 ||
1217 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1218 (vp->v_object != NULL && vp->v_object->handle == vp &&
1219 vp->v_object->resident_page_count > trigger)) {
1222 vn_finished_write(mp);
1223 goto next_iter_unlocked;
1225 counter_u64_add(recycles_count, 1);
1229 vn_finished_write(mp);
1233 kern_yield(PRI_USER);
1234 mtx_lock(&vnode_list_mtx);
1237 MPASS(vp->v_type != VMARKER);
1238 if (!should_yield())
1240 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1241 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1242 mtx_unlock(&vnode_list_mtx);
1243 kern_yield(PRI_USER);
1244 mtx_lock(&vnode_list_mtx);
1247 if (done == 0 && !retried) {
1248 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1249 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1256 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1257 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1259 "limit on vnode free requests per call to the vnlru_free routine");
1262 * Attempt to reduce the free list by the requested amount.
1265 vnlru_free_impl(int count, struct vfsops *mnt_op, struct vnode *mvp)
1271 mtx_assert(&vnode_list_mtx, MA_OWNED);
1272 if (count > max_vnlru_free)
1273 count = max_vnlru_free;
1280 vp = TAILQ_NEXT(vp, v_vnodelist);
1281 if (__predict_false(vp == NULL)) {
1282 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1283 TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1286 if (__predict_false(vp->v_type == VMARKER))
1288 if (vp->v_holdcnt > 0)
1291 * Don't recycle if our vnode is from different type
1292 * of mount point. Note that mp is type-safe, the
1293 * check does not reach unmapped address even if
1294 * vnode is reclaimed.
1296 if (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1297 mp->mnt_op != mnt_op) {
1300 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1303 if (!vhold_recycle_free(vp))
1305 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1306 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1307 mtx_unlock(&vnode_list_mtx);
1308 if (vtryrecycle(vp) == 0)
1310 mtx_lock(&vnode_list_mtx);
1313 return (ocount - count);
1317 vnlru_free_locked(int count)
1320 mtx_assert(&vnode_list_mtx, MA_OWNED);
1321 return (vnlru_free_impl(count, NULL, vnode_list_free_marker));
1325 vnlru_free_vfsops(int count, struct vfsops *mnt_op, struct vnode *mvp)
1328 MPASS(mnt_op != NULL);
1330 VNPASS(mvp->v_type == VMARKER, mvp);
1331 mtx_lock(&vnode_list_mtx);
1332 vnlru_free_impl(count, mnt_op, mvp);
1333 mtx_unlock(&vnode_list_mtx);
1337 * Temporary binary compat, don't use. Call vnlru_free_vfsops instead.
1340 vnlru_free(int count, struct vfsops *mnt_op)
1346 mtx_lock(&vnode_list_mtx);
1347 mvp = vnode_list_free_marker;
1348 if (vnlru_free_impl(count, mnt_op, mvp) == 0) {
1350 * It is possible the marker was moved over eligible vnodes by
1351 * callers which filtered by different ops. If so, start from
1354 if (vnlru_read_freevnodes() > 0) {
1355 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1356 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1358 vnlru_free_impl(count, mnt_op, mvp);
1360 mtx_unlock(&vnode_list_mtx);
1364 vnlru_alloc_marker(void)
1368 mvp = vn_alloc_marker(NULL);
1369 mtx_lock(&vnode_list_mtx);
1370 TAILQ_INSERT_BEFORE(vnode_list_free_marker, mvp, v_vnodelist);
1371 mtx_unlock(&vnode_list_mtx);
1376 vnlru_free_marker(struct vnode *mvp)
1378 mtx_lock(&vnode_list_mtx);
1379 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1380 mtx_unlock(&vnode_list_mtx);
1381 vn_free_marker(mvp);
1388 mtx_assert(&vnode_list_mtx, MA_OWNED);
1389 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1390 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1391 vlowat = vhiwat / 2;
1395 * Attempt to recycle vnodes in a context that is always safe to block.
1396 * Calling vlrurecycle() from the bowels of filesystem code has some
1397 * interesting deadlock problems.
1399 static struct proc *vnlruproc;
1400 static int vnlruproc_sig;
1403 * The main freevnodes counter is only updated when threads requeue their vnode
1404 * batches. CPUs are conditionally walked to compute a more accurate total.
1406 * Limit how much of a slop are we willing to tolerate. Note: the actual value
1407 * at any given moment can still exceed slop, but it should not be by significant
1408 * margin in practice.
1410 #define VNLRU_FREEVNODES_SLOP 128
1412 static __inline void
1413 vfs_freevnodes_inc(void)
1423 static __inline void
1424 vfs_freevnodes_dec(void)
1435 vnlru_read_freevnodes(void)
1441 mtx_assert(&vnode_list_mtx, MA_OWNED);
1442 if (freevnodes > freevnodes_old)
1443 slop = freevnodes - freevnodes_old;
1445 slop = freevnodes_old - freevnodes;
1446 if (slop < VNLRU_FREEVNODES_SLOP)
1447 return (freevnodes >= 0 ? freevnodes : 0);
1448 freevnodes_old = freevnodes;
1450 vd = DPCPU_ID_PTR((cpu), vd);
1451 freevnodes_old += vd->freevnodes;
1453 return (freevnodes_old >= 0 ? freevnodes_old : 0);
1457 vnlru_under(u_long rnumvnodes, u_long limit)
1459 u_long rfreevnodes, space;
1461 if (__predict_false(rnumvnodes > desiredvnodes))
1464 space = desiredvnodes - rnumvnodes;
1465 if (space < limit) {
1466 rfreevnodes = vnlru_read_freevnodes();
1467 if (rfreevnodes > wantfreevnodes)
1468 space += rfreevnodes - wantfreevnodes;
1470 return (space < limit);
1474 vnlru_under_unlocked(u_long rnumvnodes, u_long limit)
1476 long rfreevnodes, space;
1478 if (__predict_false(rnumvnodes > desiredvnodes))
1481 space = desiredvnodes - rnumvnodes;
1482 if (space < limit) {
1483 rfreevnodes = atomic_load_long(&freevnodes);
1484 if (rfreevnodes > wantfreevnodes)
1485 space += rfreevnodes - wantfreevnodes;
1487 return (space < limit);
1494 mtx_assert(&vnode_list_mtx, MA_OWNED);
1495 if (vnlruproc_sig == 0) {
1504 u_long rnumvnodes, rfreevnodes, target;
1505 unsigned long onumvnodes;
1506 int done, force, trigger, usevnodes;
1507 bool reclaim_nc_src, want_reread;
1509 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1510 SHUTDOWN_PRI_FIRST);
1513 want_reread = false;
1515 kproc_suspend_check(vnlruproc);
1516 mtx_lock(&vnode_list_mtx);
1517 rnumvnodes = atomic_load_long(&numvnodes);
1520 force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1521 want_reread = false;
1525 * If numvnodes is too large (due to desiredvnodes being
1526 * adjusted using its sysctl, or emergency growth), first
1527 * try to reduce it by discarding from the free list.
1529 if (rnumvnodes > desiredvnodes) {
1530 vnlru_free_locked(rnumvnodes - desiredvnodes);
1531 rnumvnodes = atomic_load_long(&numvnodes);
1534 * Sleep if the vnode cache is in a good state. This is
1535 * when it is not over-full and has space for about a 4%
1536 * or 9% expansion (by growing its size or inexcessively
1537 * reducing its free list). Otherwise, try to reclaim
1538 * space for a 10% expansion.
1540 if (vstir && force == 0) {
1544 if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1546 wakeup(&vnlruproc_sig);
1547 msleep(vnlruproc, &vnode_list_mtx,
1548 PVFS|PDROP, "vlruwt", hz);
1551 rfreevnodes = vnlru_read_freevnodes();
1553 onumvnodes = rnumvnodes;
1555 * Calculate parameters for recycling. These are the same
1556 * throughout the loop to give some semblance of fairness.
1557 * The trigger point is to avoid recycling vnodes with lots
1558 * of resident pages. We aren't trying to free memory; we
1559 * are trying to recycle or at least free vnodes.
1561 if (rnumvnodes <= desiredvnodes)
1562 usevnodes = rnumvnodes - rfreevnodes;
1564 usevnodes = rnumvnodes;
1568 * The trigger value is is chosen to give a conservatively
1569 * large value to ensure that it alone doesn't prevent
1570 * making progress. The value can easily be so large that
1571 * it is effectively infinite in some congested and
1572 * misconfigured cases, and this is necessary. Normally
1573 * it is about 8 to 100 (pages), which is quite large.
1575 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1577 trigger = vsmalltrigger;
1578 reclaim_nc_src = force >= 3;
1579 target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1580 target = target / 10 + 1;
1581 done = vlrureclaim(reclaim_nc_src, trigger, target);
1582 mtx_unlock(&vnode_list_mtx);
1583 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1584 uma_reclaim(UMA_RECLAIM_DRAIN);
1586 if (force == 0 || force == 1) {
1597 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1600 kern_yield(PRI_USER);
1605 static struct kproc_desc vnlru_kp = {
1610 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1614 * Routines having to do with the management of the vnode table.
1618 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1619 * before we actually vgone(). This function must be called with the vnode
1620 * held to prevent the vnode from being returned to the free list midway
1624 vtryrecycle(struct vnode *vp)
1628 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1629 VNASSERT(vp->v_holdcnt, vp,
1630 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1632 * This vnode may found and locked via some other list, if so we
1633 * can't recycle it yet.
1635 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1637 "%s: impossible to recycle, vp %p lock is already held",
1640 return (EWOULDBLOCK);
1643 * Don't recycle if its filesystem is being suspended.
1645 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1648 "%s: impossible to recycle, cannot start the write for %p",
1654 * If we got this far, we need to acquire the interlock and see if
1655 * anyone picked up this vnode from another list. If not, we will
1656 * mark it with DOOMED via vgonel() so that anyone who does find it
1657 * will skip over it.
1660 if (vp->v_usecount) {
1663 vn_finished_write(vnmp);
1665 "%s: impossible to recycle, %p is already referenced",
1669 if (!VN_IS_DOOMED(vp)) {
1670 counter_u64_add(recycles_free_count, 1);
1675 vn_finished_write(vnmp);
1680 * Allocate a new vnode.
1682 * The operation never returns an error. Returning an error was disabled
1683 * in r145385 (dated 2005) with the following comment:
1685 * XXX Not all VFS_VGET/ffs_vget callers check returns.
1687 * Given the age of this commit (almost 15 years at the time of writing this
1688 * comment) restoring the ability to fail requires a significant audit of
1691 * The routine can try to free a vnode or stall for up to 1 second waiting for
1692 * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1694 static u_long vn_alloc_cyclecount;
1696 static struct vnode * __noinline
1697 vn_alloc_hard(struct mount *mp)
1699 u_long rnumvnodes, rfreevnodes;
1701 mtx_lock(&vnode_list_mtx);
1702 rnumvnodes = atomic_load_long(&numvnodes);
1703 if (rnumvnodes + 1 < desiredvnodes) {
1704 vn_alloc_cyclecount = 0;
1707 rfreevnodes = vnlru_read_freevnodes();
1708 if (vn_alloc_cyclecount++ >= rfreevnodes) {
1709 vn_alloc_cyclecount = 0;
1713 * Grow the vnode cache if it will not be above its target max
1714 * after growing. Otherwise, if the free list is nonempty, try
1715 * to reclaim 1 item from it before growing the cache (possibly
1716 * above its target max if the reclamation failed or is delayed).
1717 * Otherwise, wait for some space. In all cases, schedule
1718 * vnlru_proc() if we are getting short of space. The watermarks
1719 * should be chosen so that we never wait or even reclaim from
1720 * the free list to below its target minimum.
1722 if (vnlru_free_locked(1) > 0)
1724 if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1726 * Wait for space for a new vnode.
1729 msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1730 if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1731 vnlru_read_freevnodes() > 1)
1732 vnlru_free_locked(1);
1735 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1736 if (vnlru_under(rnumvnodes, vlowat))
1738 mtx_unlock(&vnode_list_mtx);
1739 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1742 static struct vnode *
1743 vn_alloc(struct mount *mp)
1747 if (__predict_false(vn_alloc_cyclecount != 0))
1748 return (vn_alloc_hard(mp));
1749 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1750 if (__predict_false(vnlru_under_unlocked(rnumvnodes, vlowat))) {
1751 atomic_subtract_long(&numvnodes, 1);
1752 return (vn_alloc_hard(mp));
1755 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1759 vn_free(struct vnode *vp)
1762 atomic_subtract_long(&numvnodes, 1);
1763 uma_zfree_smr(vnode_zone, vp);
1767 * Return the next vnode from the free list.
1770 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1775 struct lock_object *lo;
1777 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1779 KASSERT(vops->registered,
1780 ("%s: not registered vector op %p\n", __func__, vops));
1783 if (td->td_vp_reserved != NULL) {
1784 vp = td->td_vp_reserved;
1785 td->td_vp_reserved = NULL;
1789 counter_u64_add(vnodes_created, 1);
1791 * Locks are given the generic name "vnode" when created.
1792 * Follow the historic practice of using the filesystem
1793 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1795 * Locks live in a witness group keyed on their name. Thus,
1796 * when a lock is renamed, it must also move from the witness
1797 * group of its old name to the witness group of its new name.
1799 * The change only needs to be made when the vnode moves
1800 * from one filesystem type to another. We ensure that each
1801 * filesystem use a single static name pointer for its tag so
1802 * that we can compare pointers rather than doing a strcmp().
1804 lo = &vp->v_vnlock->lock_object;
1806 if (lo->lo_name != tag) {
1810 WITNESS_DESTROY(lo);
1811 WITNESS_INIT(lo, tag);
1815 * By default, don't allow shared locks unless filesystems opt-in.
1817 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1819 * Finalize various vnode identity bits.
1821 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1822 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1823 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1827 v_init_counters(vp);
1829 vp->v_bufobj.bo_ops = &buf_ops_bio;
1831 if (mp == NULL && vops != &dead_vnodeops)
1832 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1836 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1837 mac_vnode_associate_singlelabel(mp, vp);
1840 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1841 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1842 vp->v_vflag |= VV_NOKNOTE;
1846 * For the filesystems which do not use vfs_hash_insert(),
1847 * still initialize v_hash to have vfs_hash_index() useful.
1848 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1851 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1858 getnewvnode_reserve(void)
1863 MPASS(td->td_vp_reserved == NULL);
1864 td->td_vp_reserved = vn_alloc(NULL);
1868 getnewvnode_drop_reserve(void)
1873 if (td->td_vp_reserved != NULL) {
1874 vn_free(td->td_vp_reserved);
1875 td->td_vp_reserved = NULL;
1879 static void __noinline
1880 freevnode(struct vnode *vp)
1885 * The vnode has been marked for destruction, so free it.
1887 * The vnode will be returned to the zone where it will
1888 * normally remain until it is needed for another vnode. We
1889 * need to cleanup (or verify that the cleanup has already
1890 * been done) any residual data left from its current use
1891 * so as not to contaminate the freshly allocated vnode.
1893 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1895 * Paired with vgone.
1897 vn_seqc_write_end_free(vp);
1900 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1901 VNPASS(vp->v_holdcnt == VHOLD_NO_SMR, vp);
1902 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1903 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1904 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1905 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1906 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1907 ("clean blk trie not empty"));
1908 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1909 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1910 ("dirty blk trie not empty"));
1911 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1912 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1913 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1914 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1915 ("Dangling rangelock waiters"));
1916 VNASSERT((vp->v_iflag & (VI_DOINGINACT | VI_OWEINACT)) == 0, vp,
1917 ("Leaked inactivation"));
1920 mac_vnode_destroy(vp);
1922 if (vp->v_pollinfo != NULL) {
1923 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1924 destroy_vpollinfo(vp->v_pollinfo);
1926 vp->v_pollinfo = NULL;
1928 vp->v_mountedhere = NULL;
1931 vp->v_fifoinfo = NULL;
1932 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
1940 * Delete from old mount point vnode list, if on one.
1943 delmntque(struct vnode *vp)
1947 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
1956 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1957 ("bad mount point vnode list size"));
1958 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1959 mp->mnt_nvnodelistsize--;
1965 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1969 vp->v_op = &dead_vnodeops;
1975 * Insert into list of vnodes for the new mount point, if available.
1978 insmntque1(struct vnode *vp, struct mount *mp,
1979 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1982 KASSERT(vp->v_mount == NULL,
1983 ("insmntque: vnode already on per mount vnode list"));
1984 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1985 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1988 * We acquire the vnode interlock early to ensure that the
1989 * vnode cannot be recycled by another process releasing a
1990 * holdcnt on it before we get it on both the vnode list
1991 * and the active vnode list. The mount mutex protects only
1992 * manipulation of the vnode list and the vnode freelist
1993 * mutex protects only manipulation of the active vnode list.
1994 * Hence the need to hold the vnode interlock throughout.
1998 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1999 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
2000 mp->mnt_nvnodelistsize == 0)) &&
2001 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
2010 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
2011 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
2012 ("neg mount point vnode list size"));
2013 mp->mnt_nvnodelistsize++;
2020 insmntque(struct vnode *vp, struct mount *mp)
2023 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
2027 * Flush out and invalidate all buffers associated with a bufobj
2028 * Called with the underlying object locked.
2031 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
2036 if (flags & V_SAVE) {
2037 error = bufobj_wwait(bo, slpflag, slptimeo);
2042 if (bo->bo_dirty.bv_cnt > 0) {
2045 error = BO_SYNC(bo, MNT_WAIT);
2046 } while (error == ERELOOKUP);
2050 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0) {
2057 * If you alter this loop please notice that interlock is dropped and
2058 * reacquired in flushbuflist. Special care is needed to ensure that
2059 * no race conditions occur from this.
2062 error = flushbuflist(&bo->bo_clean,
2063 flags, bo, slpflag, slptimeo);
2064 if (error == 0 && !(flags & V_CLEANONLY))
2065 error = flushbuflist(&bo->bo_dirty,
2066 flags, bo, slpflag, slptimeo);
2067 if (error != 0 && error != EAGAIN) {
2071 } while (error != 0);
2074 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
2075 * have write I/O in-progress but if there is a VM object then the
2076 * VM object can also have read-I/O in-progress.
2079 bufobj_wwait(bo, 0, 0);
2080 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
2082 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
2085 } while (bo->bo_numoutput > 0);
2089 * Destroy the copy in the VM cache, too.
2091 if (bo->bo_object != NULL &&
2092 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
2093 VM_OBJECT_WLOCK(bo->bo_object);
2094 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
2095 OBJPR_CLEANONLY : 0);
2096 VM_OBJECT_WUNLOCK(bo->bo_object);
2101 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
2102 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
2103 bo->bo_clean.bv_cnt > 0))
2104 panic("vinvalbuf: flush failed");
2105 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
2106 bo->bo_dirty.bv_cnt > 0)
2107 panic("vinvalbuf: flush dirty failed");
2114 * Flush out and invalidate all buffers associated with a vnode.
2115 * Called with the underlying object locked.
2118 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
2121 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2122 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
2123 if (vp->v_object != NULL && vp->v_object->handle != vp)
2125 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
2129 * Flush out buffers on the specified list.
2133 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
2136 struct buf *bp, *nbp;
2141 ASSERT_BO_WLOCKED(bo);
2144 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2146 * If we are flushing both V_NORMAL and V_ALT buffers then
2147 * do not skip any buffers. If we are flushing only V_NORMAL
2148 * buffers then skip buffers marked as BX_ALTDATA. If we are
2149 * flushing only V_ALT buffers then skip buffers not marked
2152 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2153 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2154 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2158 lblkno = nbp->b_lblkno;
2159 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2162 error = BUF_TIMELOCK(bp,
2163 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2164 "flushbuf", slpflag, slptimeo);
2167 return (error != ENOLCK ? error : EAGAIN);
2169 KASSERT(bp->b_bufobj == bo,
2170 ("bp %p wrong b_bufobj %p should be %p",
2171 bp, bp->b_bufobj, bo));
2173 * XXX Since there are no node locks for NFS, I
2174 * believe there is a slight chance that a delayed
2175 * write will occur while sleeping just above, so
2178 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2181 bp->b_flags |= B_ASYNC;
2184 return (EAGAIN); /* XXX: why not loop ? */
2187 bp->b_flags |= (B_INVAL | B_RELBUF);
2188 bp->b_flags &= ~B_ASYNC;
2193 nbp = gbincore(bo, lblkno);
2194 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2196 break; /* nbp invalid */
2202 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2208 ASSERT_BO_LOCKED(bo);
2210 for (lblkno = startn;;) {
2212 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2213 if (bp == NULL || bp->b_lblkno >= endn ||
2214 bp->b_lblkno < startn)
2216 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2217 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2220 if (error == ENOLCK)
2224 KASSERT(bp->b_bufobj == bo,
2225 ("bp %p wrong b_bufobj %p should be %p",
2226 bp, bp->b_bufobj, bo));
2227 lblkno = bp->b_lblkno + 1;
2228 if ((bp->b_flags & B_MANAGED) == 0)
2230 bp->b_flags |= B_RELBUF;
2232 * In the VMIO case, use the B_NOREUSE flag to hint that the
2233 * pages backing each buffer in the range are unlikely to be
2234 * reused. Dirty buffers will have the hint applied once
2235 * they've been written.
2237 if ((bp->b_flags & B_VMIO) != 0)
2238 bp->b_flags |= B_NOREUSE;
2246 * Truncate a file's buffer and pages to a specified length. This
2247 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2251 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2253 struct buf *bp, *nbp;
2257 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2258 vp, blksize, (uintmax_t)length);
2261 * Round up to the *next* lbn.
2263 startlbn = howmany(length, blksize);
2265 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2271 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2276 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2277 if (bp->b_lblkno > 0)
2280 * Since we hold the vnode lock this should only
2281 * fail if we're racing with the buf daemon.
2284 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2285 BO_LOCKPTR(bo)) == ENOLCK)
2286 goto restart_unlocked;
2288 VNASSERT((bp->b_flags & B_DELWRI), vp,
2289 ("buf(%p) on dirty queue without DELWRI", bp));
2298 bufobj_wwait(bo, 0, 0);
2300 vnode_pager_setsize(vp, length);
2306 * Invalidate the cached pages of a file's buffer within the range of block
2307 * numbers [startlbn, endlbn).
2310 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2316 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2318 start = blksize * startlbn;
2319 end = blksize * endlbn;
2323 MPASS(blksize == bo->bo_bsize);
2325 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2329 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2333 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2334 daddr_t startlbn, daddr_t endlbn)
2336 struct buf *bp, *nbp;
2339 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2340 ASSERT_BO_LOCKED(bo);
2344 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2345 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2348 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2349 BO_LOCKPTR(bo)) == ENOLCK) {
2355 bp->b_flags |= B_INVAL | B_RELBUF;
2356 bp->b_flags &= ~B_ASYNC;
2362 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2364 (nbp->b_flags & B_DELWRI) != 0))
2368 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2369 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2372 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2373 BO_LOCKPTR(bo)) == ENOLCK) {
2378 bp->b_flags |= B_INVAL | B_RELBUF;
2379 bp->b_flags &= ~B_ASYNC;
2385 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2386 (nbp->b_vp != vp) ||
2387 (nbp->b_flags & B_DELWRI) == 0))
2395 buf_vlist_remove(struct buf *bp)
2400 flags = bp->b_xflags;
2402 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2403 ASSERT_BO_WLOCKED(bp->b_bufobj);
2404 KASSERT((flags & (BX_VNDIRTY | BX_VNCLEAN)) != 0 &&
2405 (flags & (BX_VNDIRTY | BX_VNCLEAN)) != (BX_VNDIRTY | BX_VNCLEAN),
2406 ("%s: buffer %p has invalid queue state", __func__, bp));
2408 if ((flags & BX_VNDIRTY) != 0)
2409 bv = &bp->b_bufobj->bo_dirty;
2411 bv = &bp->b_bufobj->bo_clean;
2412 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2413 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2415 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2419 * Add the buffer to the sorted clean or dirty block list.
2421 * NOTE: xflags is passed as a constant, optimizing this inline function!
2424 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2430 ASSERT_BO_WLOCKED(bo);
2431 KASSERT((bo->bo_flag & BO_NOBUFS) == 0,
2432 ("buf_vlist_add: bo %p does not allow bufs", bo));
2433 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2434 ("dead bo %p", bo));
2435 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2436 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2437 bp->b_xflags |= xflags;
2438 if (xflags & BX_VNDIRTY)
2444 * Keep the list ordered. Optimize empty list insertion. Assume
2445 * we tend to grow at the tail so lookup_le should usually be cheaper
2448 if (bv->bv_cnt == 0 ||
2449 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2450 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2451 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2452 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2454 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2455 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2457 panic("buf_vlist_add: Preallocated nodes insufficient.");
2462 * Look up a buffer using the buffer tries.
2465 gbincore(struct bufobj *bo, daddr_t lblkno)
2469 ASSERT_BO_LOCKED(bo);
2470 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2473 return (BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno));
2477 * Look up a buf using the buffer tries, without the bufobj lock. This relies
2478 * on SMR for safe lookup, and bufs being in a no-free zone to provide type
2479 * stability of the result. Like other lockless lookups, the found buf may
2480 * already be invalid by the time this function returns.
2483 gbincore_unlocked(struct bufobj *bo, daddr_t lblkno)
2487 ASSERT_BO_UNLOCKED(bo);
2488 bp = BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_clean.bv_root, lblkno);
2491 return (BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_dirty.bv_root, lblkno));
2495 * Associate a buffer with a vnode.
2498 bgetvp(struct vnode *vp, struct buf *bp)
2503 ASSERT_BO_WLOCKED(bo);
2504 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2506 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2507 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2508 ("bgetvp: bp already attached! %p", bp));
2514 * Insert onto list for new vnode.
2516 buf_vlist_add(bp, bo, BX_VNCLEAN);
2520 * Disassociate a buffer from a vnode.
2523 brelvp(struct buf *bp)
2528 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2529 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2532 * Delete from old vnode list, if on one.
2534 vp = bp->b_vp; /* XXX */
2537 buf_vlist_remove(bp);
2538 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2539 bo->bo_flag &= ~BO_ONWORKLST;
2540 mtx_lock(&sync_mtx);
2541 LIST_REMOVE(bo, bo_synclist);
2542 syncer_worklist_len--;
2543 mtx_unlock(&sync_mtx);
2546 bp->b_bufobj = NULL;
2552 * Add an item to the syncer work queue.
2555 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2559 ASSERT_BO_WLOCKED(bo);
2561 mtx_lock(&sync_mtx);
2562 if (bo->bo_flag & BO_ONWORKLST)
2563 LIST_REMOVE(bo, bo_synclist);
2565 bo->bo_flag |= BO_ONWORKLST;
2566 syncer_worklist_len++;
2569 if (delay > syncer_maxdelay - 2)
2570 delay = syncer_maxdelay - 2;
2571 slot = (syncer_delayno + delay) & syncer_mask;
2573 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2574 mtx_unlock(&sync_mtx);
2578 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2582 mtx_lock(&sync_mtx);
2583 len = syncer_worklist_len - sync_vnode_count;
2584 mtx_unlock(&sync_mtx);
2585 error = SYSCTL_OUT(req, &len, sizeof(len));
2589 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2590 CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2591 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2593 static struct proc *updateproc;
2594 static void sched_sync(void);
2595 static struct kproc_desc up_kp = {
2600 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2603 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2608 *bo = LIST_FIRST(slp);
2612 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2615 * We use vhold in case the vnode does not
2616 * successfully sync. vhold prevents the vnode from
2617 * going away when we unlock the sync_mtx so that
2618 * we can acquire the vnode interlock.
2621 mtx_unlock(&sync_mtx);
2623 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2625 mtx_lock(&sync_mtx);
2626 return (*bo == LIST_FIRST(slp));
2628 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2629 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2631 vn_finished_write(mp);
2633 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2635 * Put us back on the worklist. The worklist
2636 * routine will remove us from our current
2637 * position and then add us back in at a later
2640 vn_syncer_add_to_worklist(*bo, syncdelay);
2644 mtx_lock(&sync_mtx);
2648 static int first_printf = 1;
2651 * System filesystem synchronizer daemon.
2656 struct synclist *next, *slp;
2659 struct thread *td = curthread;
2661 int net_worklist_len;
2662 int syncer_final_iter;
2666 syncer_final_iter = 0;
2667 syncer_state = SYNCER_RUNNING;
2668 starttime = time_uptime;
2669 td->td_pflags |= TDP_NORUNNINGBUF;
2671 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2674 mtx_lock(&sync_mtx);
2676 if (syncer_state == SYNCER_FINAL_DELAY &&
2677 syncer_final_iter == 0) {
2678 mtx_unlock(&sync_mtx);
2679 kproc_suspend_check(td->td_proc);
2680 mtx_lock(&sync_mtx);
2682 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2683 if (syncer_state != SYNCER_RUNNING &&
2684 starttime != time_uptime) {
2686 printf("\nSyncing disks, vnodes remaining... ");
2689 printf("%d ", net_worklist_len);
2691 starttime = time_uptime;
2694 * Push files whose dirty time has expired. Be careful
2695 * of interrupt race on slp queue.
2697 * Skip over empty worklist slots when shutting down.
2700 slp = &syncer_workitem_pending[syncer_delayno];
2701 syncer_delayno += 1;
2702 if (syncer_delayno == syncer_maxdelay)
2704 next = &syncer_workitem_pending[syncer_delayno];
2706 * If the worklist has wrapped since the
2707 * it was emptied of all but syncer vnodes,
2708 * switch to the FINAL_DELAY state and run
2709 * for one more second.
2711 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2712 net_worklist_len == 0 &&
2713 last_work_seen == syncer_delayno) {
2714 syncer_state = SYNCER_FINAL_DELAY;
2715 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2717 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2718 syncer_worklist_len > 0);
2721 * Keep track of the last time there was anything
2722 * on the worklist other than syncer vnodes.
2723 * Return to the SHUTTING_DOWN state if any
2726 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2727 last_work_seen = syncer_delayno;
2728 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2729 syncer_state = SYNCER_SHUTTING_DOWN;
2730 while (!LIST_EMPTY(slp)) {
2731 error = sync_vnode(slp, &bo, td);
2733 LIST_REMOVE(bo, bo_synclist);
2734 LIST_INSERT_HEAD(next, bo, bo_synclist);
2738 if (first_printf == 0) {
2740 * Drop the sync mutex, because some watchdog
2741 * drivers need to sleep while patting
2743 mtx_unlock(&sync_mtx);
2744 wdog_kern_pat(WD_LASTVAL);
2745 mtx_lock(&sync_mtx);
2748 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2749 syncer_final_iter--;
2751 * The variable rushjob allows the kernel to speed up the
2752 * processing of the filesystem syncer process. A rushjob
2753 * value of N tells the filesystem syncer to process the next
2754 * N seconds worth of work on its queue ASAP. Currently rushjob
2755 * is used by the soft update code to speed up the filesystem
2756 * syncer process when the incore state is getting so far
2757 * ahead of the disk that the kernel memory pool is being
2758 * threatened with exhaustion.
2765 * Just sleep for a short period of time between
2766 * iterations when shutting down to allow some I/O
2769 * If it has taken us less than a second to process the
2770 * current work, then wait. Otherwise start right over
2771 * again. We can still lose time if any single round
2772 * takes more than two seconds, but it does not really
2773 * matter as we are just trying to generally pace the
2774 * filesystem activity.
2776 if (syncer_state != SYNCER_RUNNING ||
2777 time_uptime == starttime) {
2779 sched_prio(td, PPAUSE);
2782 if (syncer_state != SYNCER_RUNNING)
2783 cv_timedwait(&sync_wakeup, &sync_mtx,
2784 hz / SYNCER_SHUTDOWN_SPEEDUP);
2785 else if (time_uptime == starttime)
2786 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2791 * Request the syncer daemon to speed up its work.
2792 * We never push it to speed up more than half of its
2793 * normal turn time, otherwise it could take over the cpu.
2796 speedup_syncer(void)
2800 mtx_lock(&sync_mtx);
2801 if (rushjob < syncdelay / 2) {
2803 stat_rush_requests += 1;
2806 mtx_unlock(&sync_mtx);
2807 cv_broadcast(&sync_wakeup);
2812 * Tell the syncer to speed up its work and run though its work
2813 * list several times, then tell it to shut down.
2816 syncer_shutdown(void *arg, int howto)
2819 if (howto & RB_NOSYNC)
2821 mtx_lock(&sync_mtx);
2822 syncer_state = SYNCER_SHUTTING_DOWN;
2824 mtx_unlock(&sync_mtx);
2825 cv_broadcast(&sync_wakeup);
2826 kproc_shutdown(arg, howto);
2830 syncer_suspend(void)
2833 syncer_shutdown(updateproc, 0);
2840 mtx_lock(&sync_mtx);
2842 syncer_state = SYNCER_RUNNING;
2843 mtx_unlock(&sync_mtx);
2844 cv_broadcast(&sync_wakeup);
2845 kproc_resume(updateproc);
2849 * Move the buffer between the clean and dirty lists of its vnode.
2852 reassignbuf(struct buf *bp)
2864 KASSERT((bp->b_flags & B_PAGING) == 0,
2865 ("%s: cannot reassign paging buffer %p", __func__, bp));
2867 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2868 bp, bp->b_vp, bp->b_flags);
2871 buf_vlist_remove(bp);
2874 * If dirty, put on list of dirty buffers; otherwise insert onto list
2877 if (bp->b_flags & B_DELWRI) {
2878 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2879 switch (vp->v_type) {
2889 vn_syncer_add_to_worklist(bo, delay);
2891 buf_vlist_add(bp, bo, BX_VNDIRTY);
2893 buf_vlist_add(bp, bo, BX_VNCLEAN);
2895 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2896 mtx_lock(&sync_mtx);
2897 LIST_REMOVE(bo, bo_synclist);
2898 syncer_worklist_len--;
2899 mtx_unlock(&sync_mtx);
2900 bo->bo_flag &= ~BO_ONWORKLST;
2905 bp = TAILQ_FIRST(&bv->bv_hd);
2906 KASSERT(bp == NULL || bp->b_bufobj == bo,
2907 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2908 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2909 KASSERT(bp == NULL || bp->b_bufobj == bo,
2910 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2912 bp = TAILQ_FIRST(&bv->bv_hd);
2913 KASSERT(bp == NULL || bp->b_bufobj == bo,
2914 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2915 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2916 KASSERT(bp == NULL || bp->b_bufobj == bo,
2917 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2923 v_init_counters(struct vnode *vp)
2926 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2927 vp, ("%s called for an initialized vnode", __FUNCTION__));
2928 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2930 refcount_init(&vp->v_holdcnt, 1);
2931 refcount_init(&vp->v_usecount, 1);
2935 * Grab a particular vnode from the free list, increment its
2936 * reference count and lock it. VIRF_DOOMED is set if the vnode
2937 * is being destroyed. Only callers who specify LK_RETRY will
2938 * see doomed vnodes. If inactive processing was delayed in
2939 * vput try to do it here.
2941 * usecount is manipulated using atomics without holding any locks.
2943 * holdcnt can be manipulated using atomics without holding any locks,
2944 * except when transitioning 1<->0, in which case the interlock is held.
2946 * Consumers which don't guarantee liveness of the vnode can use SMR to
2947 * try to get a reference. Note this operation can fail since the vnode
2948 * may be awaiting getting freed by the time they get to it.
2951 vget_prep_smr(struct vnode *vp)
2955 VFS_SMR_ASSERT_ENTERED();
2957 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2969 vget_prep(struct vnode *vp)
2973 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2983 vget_abort(struct vnode *vp, enum vgetstate vs)
2994 __assert_unreachable();
2999 vget(struct vnode *vp, int flags)
3004 return (vget_finish(vp, flags, vs));
3008 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
3012 if ((flags & LK_INTERLOCK) != 0)
3013 ASSERT_VI_LOCKED(vp, __func__);
3015 ASSERT_VI_UNLOCKED(vp, __func__);
3016 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3017 VNPASS(vp->v_holdcnt > 0, vp);
3018 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3020 error = vn_lock(vp, flags);
3021 if (__predict_false(error != 0)) {
3023 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
3028 vget_finish_ref(vp, vs);
3033 vget_finish_ref(struct vnode *vp, enum vgetstate vs)
3037 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3038 VNPASS(vp->v_holdcnt > 0, vp);
3039 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3041 if (vs == VGET_USECOUNT)
3045 * We hold the vnode. If the usecount is 0 it will be utilized to keep
3046 * the vnode around. Otherwise someone else lended their hold count and
3047 * we have to drop ours.
3049 old = atomic_fetchadd_int(&vp->v_usecount, 1);
3050 VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
3053 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
3054 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
3056 refcount_release(&vp->v_holdcnt);
3062 vref(struct vnode *vp)
3066 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3068 vget_finish_ref(vp, vs);
3072 vrefact(struct vnode *vp)
3075 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3077 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
3078 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3080 refcount_acquire(&vp->v_usecount);
3085 vlazy(struct vnode *vp)
3089 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
3091 if ((vp->v_mflag & VMP_LAZYLIST) != 0)
3094 * We may get here for inactive routines after the vnode got doomed.
3096 if (VN_IS_DOOMED(vp))
3099 mtx_lock(&mp->mnt_listmtx);
3100 if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
3101 vp->v_mflag |= VMP_LAZYLIST;
3102 TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3103 mp->mnt_lazyvnodelistsize++;
3105 mtx_unlock(&mp->mnt_listmtx);
3109 vunlazy(struct vnode *vp)
3113 ASSERT_VI_LOCKED(vp, __func__);
3114 VNPASS(!VN_IS_DOOMED(vp), vp);
3117 mtx_lock(&mp->mnt_listmtx);
3118 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3120 * Don't remove the vnode from the lazy list if another thread
3121 * has increased the hold count. It may have re-enqueued the
3122 * vnode to the lazy list and is now responsible for its
3125 if (vp->v_holdcnt == 0) {
3126 vp->v_mflag &= ~VMP_LAZYLIST;
3127 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3128 mp->mnt_lazyvnodelistsize--;
3130 mtx_unlock(&mp->mnt_listmtx);
3134 * This routine is only meant to be called from vgonel prior to dooming
3138 vunlazy_gone(struct vnode *vp)
3142 ASSERT_VOP_ELOCKED(vp, __func__);
3143 ASSERT_VI_LOCKED(vp, __func__);
3144 VNPASS(!VN_IS_DOOMED(vp), vp);
3146 if (vp->v_mflag & VMP_LAZYLIST) {
3148 mtx_lock(&mp->mnt_listmtx);
3149 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3150 vp->v_mflag &= ~VMP_LAZYLIST;
3151 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3152 mp->mnt_lazyvnodelistsize--;
3153 mtx_unlock(&mp->mnt_listmtx);
3158 vdefer_inactive(struct vnode *vp)
3161 ASSERT_VI_LOCKED(vp, __func__);
3162 VNASSERT(vp->v_holdcnt > 0, vp,
3163 ("%s: vnode without hold count", __func__));
3164 if (VN_IS_DOOMED(vp)) {
3168 if (vp->v_iflag & VI_DEFINACT) {
3169 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3173 if (vp->v_usecount > 0) {
3174 vp->v_iflag &= ~VI_OWEINACT;
3179 vp->v_iflag |= VI_DEFINACT;
3181 counter_u64_add(deferred_inact, 1);
3185 vdefer_inactive_unlocked(struct vnode *vp)
3189 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3193 vdefer_inactive(vp);
3196 enum vput_op { VRELE, VPUT, VUNREF };
3199 * Handle ->v_usecount transitioning to 0.
3201 * By releasing the last usecount we take ownership of the hold count which
3202 * provides liveness of the vnode, meaning we have to vdrop.
3204 * For all vnodes we may need to perform inactive processing. It requires an
3205 * exclusive lock on the vnode, while it is legal to call here with only a
3206 * shared lock (or no locks). If locking the vnode in an expected manner fails,
3207 * inactive processing gets deferred to the syncer.
3209 * XXX Some filesystems pass in an exclusively locked vnode and strongly depend
3210 * on the lock being held all the way until VOP_INACTIVE. This in particular
3211 * happens with UFS which adds half-constructed vnodes to the hash, where they
3212 * can be found by other code.
3215 vput_final(struct vnode *vp, enum vput_op func)
3220 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3221 VNPASS(vp->v_holdcnt > 0, vp);
3226 * By the time we got here someone else might have transitioned
3227 * the count back to > 0.
3229 if (vp->v_usecount > 0)
3233 * If the vnode is doomed vgone already performed inactive processing
3236 if (VN_IS_DOOMED(vp))
3239 if (__predict_true(VOP_NEED_INACTIVE(vp) == 0))
3242 if (vp->v_iflag & VI_DOINGINACT)
3246 * Locking operations here will drop the interlock and possibly the
3247 * vnode lock, opening a window where the vnode can get doomed all the
3248 * while ->v_usecount is 0. Set VI_OWEINACT to let vgone know to
3251 vp->v_iflag |= VI_OWEINACT;
3252 want_unlock = false;
3256 switch (VOP_ISLOCKED(vp)) {
3262 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3267 * The lock has at least one sharer, but we have no way
3268 * to conclude whether this is us. Play it safe and
3277 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3278 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3284 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3285 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3291 if (func == VUNREF) {
3292 VNASSERT((vp->v_vflag & VV_UNREF) == 0, vp,
3293 ("recursive vunref"));
3294 vp->v_vflag |= VV_UNREF;
3297 error = vinactive(vp);
3300 if (error != ERELOOKUP || !want_unlock)
3302 VOP_LOCK(vp, LK_EXCLUSIVE);
3305 vp->v_vflag &= ~VV_UNREF;
3308 vdefer_inactive(vp);
3318 * Decrement ->v_usecount for a vnode.
3320 * Releasing the last use count requires additional processing, see vput_final
3321 * above for details.
3323 * Comment above each variant denotes lock state on entry and exit.
3328 * out: same as passed in
3331 vrele(struct vnode *vp)
3334 ASSERT_VI_UNLOCKED(vp, __func__);
3335 if (!refcount_release(&vp->v_usecount))
3337 vput_final(vp, VRELE);
3345 vput(struct vnode *vp)
3348 ASSERT_VOP_LOCKED(vp, __func__);
3349 ASSERT_VI_UNLOCKED(vp, __func__);
3350 if (!refcount_release(&vp->v_usecount)) {
3354 vput_final(vp, VPUT);
3362 vunref(struct vnode *vp)
3365 ASSERT_VOP_LOCKED(vp, __func__);
3366 ASSERT_VI_UNLOCKED(vp, __func__);
3367 if (!refcount_release(&vp->v_usecount))
3369 vput_final(vp, VUNREF);
3373 vhold(struct vnode *vp)
3377 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3378 old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3379 VNASSERT(old >= 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3380 ("%s: wrong hold count %d", __func__, old));
3382 vfs_freevnodes_dec();
3386 vholdnz(struct vnode *vp)
3389 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3391 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3392 VNASSERT(old > 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3393 ("%s: wrong hold count %d", __func__, old));
3395 atomic_add_int(&vp->v_holdcnt, 1);
3400 * Grab a hold count unless the vnode is freed.
3402 * Only use this routine if vfs smr is the only protection you have against
3403 * freeing the vnode.
3405 * The code loops trying to add a hold count as long as the VHOLD_NO_SMR flag
3406 * is not set. After the flag is set the vnode becomes immutable to anyone but
3407 * the thread which managed to set the flag.
3409 * It may be tempting to replace the loop with:
3410 * count = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3411 * if (count & VHOLD_NO_SMR) {
3412 * backpedal and error out;
3415 * However, while this is more performant, it hinders debugging by eliminating
3416 * the previously mentioned invariant.
3419 vhold_smr(struct vnode *vp)
3423 VFS_SMR_ASSERT_ENTERED();
3425 count = atomic_load_int(&vp->v_holdcnt);
3427 if (count & VHOLD_NO_SMR) {
3428 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3429 ("non-zero hold count with flags %d\n", count));
3432 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3433 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3435 vfs_freevnodes_dec();
3442 * Hold a free vnode for recycling.
3444 * Note: vnode_init references this comment.
3446 * Attempts to recycle only need the global vnode list lock and have no use for
3449 * However, vnodes get inserted into the global list before they get fully
3450 * initialized and stay there until UMA decides to free the memory. This in
3451 * particular means the target can be found before it becomes usable and after
3452 * it becomes recycled. Picking up such vnodes is guarded with v_holdcnt set to
3455 * Note: the vnode may gain more references after we transition the count 0->1.
3458 vhold_recycle_free(struct vnode *vp)
3462 mtx_assert(&vnode_list_mtx, MA_OWNED);
3464 count = atomic_load_int(&vp->v_holdcnt);
3466 if (count & VHOLD_NO_SMR) {
3467 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3468 ("non-zero hold count with flags %d\n", count));
3471 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3475 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3476 vfs_freevnodes_dec();
3482 static void __noinline
3483 vdbatch_process(struct vdbatch *vd)
3488 mtx_assert(&vd->lock, MA_OWNED);
3489 MPASS(curthread->td_pinned > 0);
3490 MPASS(vd->index == VDBATCH_SIZE);
3492 mtx_lock(&vnode_list_mtx);
3494 freevnodes += vd->freevnodes;
3495 for (i = 0; i < VDBATCH_SIZE; i++) {
3497 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3498 TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3499 MPASS(vp->v_dbatchcpu != NOCPU);
3500 vp->v_dbatchcpu = NOCPU;
3502 mtx_unlock(&vnode_list_mtx);
3504 bzero(vd->tab, sizeof(vd->tab));
3510 vdbatch_enqueue(struct vnode *vp)
3514 ASSERT_VI_LOCKED(vp, __func__);
3515 VNASSERT(!VN_IS_DOOMED(vp), vp,
3516 ("%s: deferring requeue of a doomed vnode", __func__));
3518 if (vp->v_dbatchcpu != NOCPU) {
3525 mtx_lock(&vd->lock);
3526 MPASS(vd->index < VDBATCH_SIZE);
3527 MPASS(vd->tab[vd->index] == NULL);
3529 * A hack: we depend on being pinned so that we know what to put in
3532 vp->v_dbatchcpu = curcpu;
3533 vd->tab[vd->index] = vp;
3536 if (vd->index == VDBATCH_SIZE)
3537 vdbatch_process(vd);
3538 mtx_unlock(&vd->lock);
3543 * This routine must only be called for vnodes which are about to be
3544 * deallocated. Supporting dequeue for arbitrary vndoes would require
3545 * validating that the locked batch matches.
3548 vdbatch_dequeue(struct vnode *vp)
3554 VNASSERT(vp->v_type == VBAD || vp->v_type == VNON, vp,
3555 ("%s: called for a used vnode\n", __func__));
3557 cpu = vp->v_dbatchcpu;
3561 vd = DPCPU_ID_PTR(cpu, vd);
3562 mtx_lock(&vd->lock);
3563 for (i = 0; i < vd->index; i++) {
3564 if (vd->tab[i] != vp)
3566 vp->v_dbatchcpu = NOCPU;
3568 vd->tab[i] = vd->tab[vd->index];
3569 vd->tab[vd->index] = NULL;
3572 mtx_unlock(&vd->lock);
3574 * Either we dequeued the vnode above or the target CPU beat us to it.
3576 MPASS(vp->v_dbatchcpu == NOCPU);
3580 * Drop the hold count of the vnode. If this is the last reference to
3581 * the vnode we place it on the free list unless it has been vgone'd
3582 * (marked VIRF_DOOMED) in which case we will free it.
3584 * Because the vnode vm object keeps a hold reference on the vnode if
3585 * there is at least one resident non-cached page, the vnode cannot
3586 * leave the active list without the page cleanup done.
3588 static void __noinline
3589 vdropl_final(struct vnode *vp)
3592 ASSERT_VI_LOCKED(vp, __func__);
3593 VNPASS(VN_IS_DOOMED(vp), vp);
3595 * Set the VHOLD_NO_SMR flag.
3597 * We may be racing against vhold_smr. If they win we can just pretend
3598 * we never got this far, they will vdrop later.
3600 if (__predict_false(!atomic_cmpset_int(&vp->v_holdcnt, 0, VHOLD_NO_SMR))) {
3601 vfs_freevnodes_inc();
3604 * We lost the aforementioned race. Any subsequent access is
3605 * invalid as they might have managed to vdropl on their own.
3610 * Don't bump freevnodes as this one is going away.
3616 vdrop(struct vnode *vp)
3619 ASSERT_VI_UNLOCKED(vp, __func__);
3620 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3621 if (refcount_release_if_not_last(&vp->v_holdcnt))
3628 vdropl(struct vnode *vp)
3631 ASSERT_VI_LOCKED(vp, __func__);
3632 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3633 if (!refcount_release(&vp->v_holdcnt)) {
3637 VNPASS((vp->v_iflag & VI_OWEINACT) == 0, vp);
3638 VNPASS((vp->v_iflag & VI_DEFINACT) == 0, vp);
3639 if (VN_IS_DOOMED(vp)) {
3644 vfs_freevnodes_inc();
3645 if (vp->v_mflag & VMP_LAZYLIST) {
3649 * Also unlocks the interlock. We can't assert on it as we
3650 * released our hold and by now the vnode might have been
3653 vdbatch_enqueue(vp);
3657 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3658 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3661 vinactivef(struct vnode *vp)
3663 struct vm_object *obj;
3666 ASSERT_VOP_ELOCKED(vp, "vinactive");
3667 ASSERT_VI_LOCKED(vp, "vinactive");
3668 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3669 ("vinactive: recursed on VI_DOINGINACT"));
3670 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3671 vp->v_iflag |= VI_DOINGINACT;
3672 vp->v_iflag &= ~VI_OWEINACT;
3675 * Before moving off the active list, we must be sure that any
3676 * modified pages are converted into the vnode's dirty
3677 * buffers, since these will no longer be checked once the
3678 * vnode is on the inactive list.
3680 * The write-out of the dirty pages is asynchronous. At the
3681 * point that VOP_INACTIVE() is called, there could still be
3682 * pending I/O and dirty pages in the object.
3684 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3685 vm_object_mightbedirty(obj)) {
3686 VM_OBJECT_WLOCK(obj);
3687 vm_object_page_clean(obj, 0, 0, 0);
3688 VM_OBJECT_WUNLOCK(obj);
3690 error = VOP_INACTIVE(vp);
3692 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3693 ("vinactive: lost VI_DOINGINACT"));
3694 vp->v_iflag &= ~VI_DOINGINACT;
3699 vinactive(struct vnode *vp)
3702 ASSERT_VOP_ELOCKED(vp, "vinactive");
3703 ASSERT_VI_LOCKED(vp, "vinactive");
3704 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3706 if ((vp->v_iflag & VI_OWEINACT) == 0)
3708 if (vp->v_iflag & VI_DOINGINACT)
3710 if (vp->v_usecount > 0) {
3711 vp->v_iflag &= ~VI_OWEINACT;
3714 return (vinactivef(vp));
3718 * Remove any vnodes in the vnode table belonging to mount point mp.
3720 * If FORCECLOSE is not specified, there should not be any active ones,
3721 * return error if any are found (nb: this is a user error, not a
3722 * system error). If FORCECLOSE is specified, detach any active vnodes
3725 * If WRITECLOSE is set, only flush out regular file vnodes open for
3728 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3730 * `rootrefs' specifies the base reference count for the root vnode
3731 * of this filesystem. The root vnode is considered busy if its
3732 * v_usecount exceeds this value. On a successful return, vflush(, td)
3733 * will call vrele() on the root vnode exactly rootrefs times.
3734 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3738 static int busyprt = 0; /* print out busy vnodes */
3739 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3743 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3745 struct vnode *vp, *mvp, *rootvp = NULL;
3747 int busy = 0, error;
3749 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3752 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3753 ("vflush: bad args"));
3755 * Get the filesystem root vnode. We can vput() it
3756 * immediately, since with rootrefs > 0, it won't go away.
3758 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3759 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3766 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3768 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3771 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3775 * Skip over a vnodes marked VV_SYSTEM.
3777 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3783 * If WRITECLOSE is set, flush out unlinked but still open
3784 * files (even if open only for reading) and regular file
3785 * vnodes open for writing.
3787 if (flags & WRITECLOSE) {
3788 if (vp->v_object != NULL) {
3789 VM_OBJECT_WLOCK(vp->v_object);
3790 vm_object_page_clean(vp->v_object, 0, 0, 0);
3791 VM_OBJECT_WUNLOCK(vp->v_object);
3794 error = VOP_FSYNC(vp, MNT_WAIT, td);
3795 } while (error == ERELOOKUP);
3799 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3802 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3805 if ((vp->v_type == VNON ||
3806 (error == 0 && vattr.va_nlink > 0)) &&
3807 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3815 * With v_usecount == 0, all we need to do is clear out the
3816 * vnode data structures and we are done.
3818 * If FORCECLOSE is set, forcibly close the vnode.
3820 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3826 vn_printf(vp, "vflush: busy vnode ");
3832 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3834 * If just the root vnode is busy, and if its refcount
3835 * is equal to `rootrefs', then go ahead and kill it.
3838 KASSERT(busy > 0, ("vflush: not busy"));
3839 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3840 ("vflush: usecount %d < rootrefs %d",
3841 rootvp->v_usecount, rootrefs));
3842 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3843 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3851 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3855 for (; rootrefs > 0; rootrefs--)
3861 * Recycle an unused vnode to the front of the free list.
3864 vrecycle(struct vnode *vp)
3869 recycled = vrecyclel(vp);
3875 * vrecycle, with the vp interlock held.
3878 vrecyclel(struct vnode *vp)
3882 ASSERT_VOP_ELOCKED(vp, __func__);
3883 ASSERT_VI_LOCKED(vp, __func__);
3884 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3886 if (vp->v_usecount == 0) {
3894 * Eliminate all activity associated with a vnode
3895 * in preparation for reuse.
3898 vgone(struct vnode *vp)
3906 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3907 struct vnode *lowervp __unused)
3912 * Notify upper mounts about reclaimed or unlinked vnode.
3915 vfs_notify_upper(struct vnode *vp, int event)
3917 static struct vfsops vgonel_vfsops = {
3918 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3919 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3921 struct mount *mp, *ump, *mmp;
3926 if (TAILQ_EMPTY(&mp->mnt_uppers))
3929 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3930 mmp->mnt_op = &vgonel_vfsops;
3931 mmp->mnt_kern_flag |= MNTK_MARKER;
3933 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3934 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3935 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3936 ump = TAILQ_NEXT(ump, mnt_upper_link);
3939 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3942 case VFS_NOTIFY_UPPER_RECLAIM:
3943 VFS_RECLAIM_LOWERVP(ump, vp);
3945 case VFS_NOTIFY_UPPER_UNLINK:
3946 VFS_UNLINK_LOWERVP(ump, vp);
3949 KASSERT(0, ("invalid event %d", event));
3953 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3954 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3957 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3958 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3959 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3960 wakeup(&mp->mnt_uppers);
3966 * vgone, with the vp interlock held.
3969 vgonel(struct vnode *vp)
3974 bool active, doinginact, oweinact;
3976 ASSERT_VOP_ELOCKED(vp, "vgonel");
3977 ASSERT_VI_LOCKED(vp, "vgonel");
3978 VNASSERT(vp->v_holdcnt, vp,
3979 ("vgonel: vp %p has no reference.", vp));
3980 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3984 * Don't vgonel if we're already doomed.
3986 if (VN_IS_DOOMED(vp))
3989 * Paired with freevnode.
3991 vn_seqc_write_begin_locked(vp);
3993 vn_irflag_set_locked(vp, VIRF_DOOMED);
3996 * Check to see if the vnode is in use. If so, we have to
3997 * call VOP_CLOSE() and VOP_INACTIVE().
3999 * It could be that VOP_INACTIVE() requested reclamation, in
4000 * which case we should avoid recursion, so check
4001 * VI_DOINGINACT. This is not precise but good enough.
4003 active = vp->v_usecount > 0;
4004 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4005 doinginact = (vp->v_iflag & VI_DOINGINACT) != 0;
4008 * If we need to do inactive VI_OWEINACT will be set.
4010 if (vp->v_iflag & VI_DEFINACT) {
4011 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
4012 vp->v_iflag &= ~VI_DEFINACT;
4015 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
4018 cache_purge_vgone(vp);
4019 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
4022 * If purging an active vnode, it must be closed and
4023 * deactivated before being reclaimed.
4026 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
4029 if (oweinact || active) {
4032 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4037 if (vp->v_type == VSOCK)
4038 vfs_unp_reclaim(vp);
4041 * Clean out any buffers associated with the vnode.
4042 * If the flush fails, just toss the buffers.
4045 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
4046 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
4047 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
4048 while (vinvalbuf(vp, 0, 0, 0) != 0)
4052 BO_LOCK(&vp->v_bufobj);
4053 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
4054 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
4055 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
4056 vp->v_bufobj.bo_clean.bv_cnt == 0,
4057 ("vp %p bufobj not invalidated", vp));
4060 * For VMIO bufobj, BO_DEAD is set later, or in
4061 * vm_object_terminate() after the object's page queue is
4064 object = vp->v_bufobj.bo_object;
4066 vp->v_bufobj.bo_flag |= BO_DEAD;
4067 BO_UNLOCK(&vp->v_bufobj);
4070 * Handle the VM part. Tmpfs handles v_object on its own (the
4071 * OBJT_VNODE check). Nullfs or other bypassing filesystems
4072 * should not touch the object borrowed from the lower vnode
4073 * (the handle check).
4075 if (object != NULL && object->type == OBJT_VNODE &&
4076 object->handle == vp)
4077 vnode_destroy_vobject(vp);
4080 * Reclaim the vnode.
4082 if (VOP_RECLAIM(vp))
4083 panic("vgone: cannot reclaim");
4085 vn_finished_secondary_write(mp);
4086 VNASSERT(vp->v_object == NULL, vp,
4087 ("vop_reclaim left v_object vp=%p", vp));
4089 * Clear the advisory locks and wake up waiting threads.
4091 (void)VOP_ADVLOCKPURGE(vp);
4094 * Delete from old mount point vnode list.
4098 * Done with purge, reset to the standard lock and invalidate
4102 vp->v_vnlock = &vp->v_lock;
4103 vp->v_op = &dead_vnodeops;
4108 * Print out a description of a vnode.
4110 static const char * const typename[] =
4111 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
4114 _Static_assert((VHOLD_ALL_FLAGS & ~VHOLD_NO_SMR) == 0,
4115 "new hold count flag not added to vn_printf");
4118 vn_printf(struct vnode *vp, const char *fmt, ...)
4121 char buf[256], buf2[16];
4129 printf("%p: ", (void *)vp);
4130 printf("type %s\n", typename[vp->v_type]);
4131 holdcnt = atomic_load_int(&vp->v_holdcnt);
4132 printf(" usecount %d, writecount %d, refcount %d seqc users %d",
4133 vp->v_usecount, vp->v_writecount, holdcnt & ~VHOLD_ALL_FLAGS,
4135 switch (vp->v_type) {
4137 printf(" mountedhere %p\n", vp->v_mountedhere);
4140 printf(" rdev %p\n", vp->v_rdev);
4143 printf(" socket %p\n", vp->v_unpcb);
4146 printf(" fifoinfo %p\n", vp->v_fifoinfo);
4154 if (holdcnt & VHOLD_NO_SMR)
4155 strlcat(buf, "|VHOLD_NO_SMR", sizeof(buf));
4156 printf(" hold count flags (%s)\n", buf + 1);
4160 irflag = vn_irflag_read(vp);
4161 if (irflag & VIRF_DOOMED)
4162 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
4163 if (irflag & VIRF_PGREAD)
4164 strlcat(buf, "|VIRF_PGREAD", sizeof(buf));
4165 if (irflag & VIRF_MOUNTPOINT)
4166 strlcat(buf, "|VIRF_MOUNTPOINT", sizeof(buf));
4167 flags = irflag & ~(VIRF_DOOMED | VIRF_PGREAD | VIRF_MOUNTPOINT);
4169 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
4170 strlcat(buf, buf2, sizeof(buf));
4172 if (vp->v_vflag & VV_ROOT)
4173 strlcat(buf, "|VV_ROOT", sizeof(buf));
4174 if (vp->v_vflag & VV_ISTTY)
4175 strlcat(buf, "|VV_ISTTY", sizeof(buf));
4176 if (vp->v_vflag & VV_NOSYNC)
4177 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
4178 if (vp->v_vflag & VV_ETERNALDEV)
4179 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
4180 if (vp->v_vflag & VV_CACHEDLABEL)
4181 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
4182 if (vp->v_vflag & VV_VMSIZEVNLOCK)
4183 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
4184 if (vp->v_vflag & VV_COPYONWRITE)
4185 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
4186 if (vp->v_vflag & VV_SYSTEM)
4187 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
4188 if (vp->v_vflag & VV_PROCDEP)
4189 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
4190 if (vp->v_vflag & VV_NOKNOTE)
4191 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
4192 if (vp->v_vflag & VV_DELETED)
4193 strlcat(buf, "|VV_DELETED", sizeof(buf));
4194 if (vp->v_vflag & VV_MD)
4195 strlcat(buf, "|VV_MD", sizeof(buf));
4196 if (vp->v_vflag & VV_FORCEINSMQ)
4197 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
4198 if (vp->v_vflag & VV_READLINK)
4199 strlcat(buf, "|VV_READLINK", sizeof(buf));
4200 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4201 VV_CACHEDLABEL | VV_VMSIZEVNLOCK | VV_COPYONWRITE | VV_SYSTEM |
4202 VV_PROCDEP | VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ |
4205 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4206 strlcat(buf, buf2, sizeof(buf));
4208 if (vp->v_iflag & VI_TEXT_REF)
4209 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
4210 if (vp->v_iflag & VI_MOUNT)
4211 strlcat(buf, "|VI_MOUNT", sizeof(buf));
4212 if (vp->v_iflag & VI_DOINGINACT)
4213 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4214 if (vp->v_iflag & VI_OWEINACT)
4215 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4216 if (vp->v_iflag & VI_DEFINACT)
4217 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4218 if (vp->v_iflag & VI_FOPENING)
4219 strlcat(buf, "|VI_FOPENING", sizeof(buf));
4220 flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOINGINACT |
4221 VI_OWEINACT | VI_DEFINACT | VI_FOPENING);
4223 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4224 strlcat(buf, buf2, sizeof(buf));
4226 if (vp->v_mflag & VMP_LAZYLIST)
4227 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4228 flags = vp->v_mflag & ~(VMP_LAZYLIST);
4230 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4231 strlcat(buf, buf2, sizeof(buf));
4233 printf(" flags (%s)", buf + 1);
4234 if (mtx_owned(VI_MTX(vp)))
4235 printf(" VI_LOCKed");
4237 if (vp->v_object != NULL)
4238 printf(" v_object %p ref %d pages %d "
4239 "cleanbuf %d dirtybuf %d\n",
4240 vp->v_object, vp->v_object->ref_count,
4241 vp->v_object->resident_page_count,
4242 vp->v_bufobj.bo_clean.bv_cnt,
4243 vp->v_bufobj.bo_dirty.bv_cnt);
4245 lockmgr_printinfo(vp->v_vnlock);
4246 if (vp->v_data != NULL)
4252 * List all of the locked vnodes in the system.
4253 * Called when debugging the kernel.
4255 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
4261 * Note: because this is DDB, we can't obey the locking semantics
4262 * for these structures, which means we could catch an inconsistent
4263 * state and dereference a nasty pointer. Not much to be done
4266 db_printf("Locked vnodes\n");
4267 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4268 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4269 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4270 vn_printf(vp, "vnode ");
4276 * Show details about the given vnode.
4278 DB_SHOW_COMMAND(vnode, db_show_vnode)
4284 vp = (struct vnode *)addr;
4285 vn_printf(vp, "vnode ");
4289 * Show details about the given mount point.
4291 DB_SHOW_COMMAND(mount, db_show_mount)
4302 /* No address given, print short info about all mount points. */
4303 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4304 db_printf("%p %s on %s (%s)\n", mp,
4305 mp->mnt_stat.f_mntfromname,
4306 mp->mnt_stat.f_mntonname,
4307 mp->mnt_stat.f_fstypename);
4311 db_printf("\nMore info: show mount <addr>\n");
4315 mp = (struct mount *)addr;
4316 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4317 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4320 mflags = mp->mnt_flag;
4321 #define MNT_FLAG(flag) do { \
4322 if (mflags & (flag)) { \
4323 if (buf[0] != '\0') \
4324 strlcat(buf, ", ", sizeof(buf)); \
4325 strlcat(buf, (#flag) + 4, sizeof(buf)); \
4326 mflags &= ~(flag); \
4329 MNT_FLAG(MNT_RDONLY);
4330 MNT_FLAG(MNT_SYNCHRONOUS);
4331 MNT_FLAG(MNT_NOEXEC);
4332 MNT_FLAG(MNT_NOSUID);
4333 MNT_FLAG(MNT_NFS4ACLS);
4334 MNT_FLAG(MNT_UNION);
4335 MNT_FLAG(MNT_ASYNC);
4336 MNT_FLAG(MNT_SUIDDIR);
4337 MNT_FLAG(MNT_SOFTDEP);
4338 MNT_FLAG(MNT_NOSYMFOLLOW);
4339 MNT_FLAG(MNT_GJOURNAL);
4340 MNT_FLAG(MNT_MULTILABEL);
4342 MNT_FLAG(MNT_NOATIME);
4343 MNT_FLAG(MNT_NOCLUSTERR);
4344 MNT_FLAG(MNT_NOCLUSTERW);
4346 MNT_FLAG(MNT_EXRDONLY);
4347 MNT_FLAG(MNT_EXPORTED);
4348 MNT_FLAG(MNT_DEFEXPORTED);
4349 MNT_FLAG(MNT_EXPORTANON);
4350 MNT_FLAG(MNT_EXKERB);
4351 MNT_FLAG(MNT_EXPUBLIC);
4352 MNT_FLAG(MNT_LOCAL);
4353 MNT_FLAG(MNT_QUOTA);
4354 MNT_FLAG(MNT_ROOTFS);
4356 MNT_FLAG(MNT_IGNORE);
4357 MNT_FLAG(MNT_UPDATE);
4358 MNT_FLAG(MNT_DELEXPORT);
4359 MNT_FLAG(MNT_RELOAD);
4360 MNT_FLAG(MNT_FORCE);
4361 MNT_FLAG(MNT_SNAPSHOT);
4362 MNT_FLAG(MNT_BYFSID);
4366 strlcat(buf, ", ", sizeof(buf));
4367 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4368 "0x%016jx", mflags);
4370 db_printf(" mnt_flag = %s\n", buf);
4373 flags = mp->mnt_kern_flag;
4374 #define MNT_KERN_FLAG(flag) do { \
4375 if (flags & (flag)) { \
4376 if (buf[0] != '\0') \
4377 strlcat(buf, ", ", sizeof(buf)); \
4378 strlcat(buf, (#flag) + 5, sizeof(buf)); \
4382 MNT_KERN_FLAG(MNTK_UNMOUNTF);
4383 MNT_KERN_FLAG(MNTK_ASYNC);
4384 MNT_KERN_FLAG(MNTK_SOFTDEP);
4385 MNT_KERN_FLAG(MNTK_DRAINING);
4386 MNT_KERN_FLAG(MNTK_REFEXPIRE);
4387 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4388 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4389 MNT_KERN_FLAG(MNTK_NO_IOPF);
4390 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4391 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4392 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4393 MNT_KERN_FLAG(MNTK_MARKER);
4394 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4395 MNT_KERN_FLAG(MNTK_FPLOOKUP);
4396 MNT_KERN_FLAG(MNTK_NOASYNC);
4397 MNT_KERN_FLAG(MNTK_UNMOUNT);
4398 MNT_KERN_FLAG(MNTK_MWAIT);
4399 MNT_KERN_FLAG(MNTK_SUSPEND);
4400 MNT_KERN_FLAG(MNTK_SUSPEND2);
4401 MNT_KERN_FLAG(MNTK_SUSPENDED);
4402 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4403 MNT_KERN_FLAG(MNTK_NOKNOTE);
4404 #undef MNT_KERN_FLAG
4407 strlcat(buf, ", ", sizeof(buf));
4408 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4411 db_printf(" mnt_kern_flag = %s\n", buf);
4413 db_printf(" mnt_opt = ");
4414 opt = TAILQ_FIRST(mp->mnt_opt);
4416 db_printf("%s", opt->name);
4417 opt = TAILQ_NEXT(opt, link);
4418 while (opt != NULL) {
4419 db_printf(", %s", opt->name);
4420 opt = TAILQ_NEXT(opt, link);
4426 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4427 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4428 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4429 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4430 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4431 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4432 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4433 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4434 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4435 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4436 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4437 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4439 db_printf(" mnt_cred = { uid=%u ruid=%u",
4440 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4441 if (jailed(mp->mnt_cred))
4442 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4444 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4445 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4446 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4447 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4448 db_printf(" mnt_lazyvnodelistsize = %d\n",
4449 mp->mnt_lazyvnodelistsize);
4450 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4451 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4452 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4453 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4454 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4455 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4456 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4457 db_printf(" mnt_secondary_accwrites = %d\n",
4458 mp->mnt_secondary_accwrites);
4459 db_printf(" mnt_gjprovider = %s\n",
4460 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4461 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4463 db_printf("\n\nList of active vnodes\n");
4464 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4465 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4466 vn_printf(vp, "vnode ");
4471 db_printf("\n\nList of inactive vnodes\n");
4472 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4473 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4474 vn_printf(vp, "vnode ");
4483 * Fill in a struct xvfsconf based on a struct vfsconf.
4486 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4488 struct xvfsconf xvfsp;
4490 bzero(&xvfsp, sizeof(xvfsp));
4491 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4492 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4493 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4494 xvfsp.vfc_flags = vfsp->vfc_flags;
4496 * These are unused in userland, we keep them
4497 * to not break binary compatibility.
4499 xvfsp.vfc_vfsops = NULL;
4500 xvfsp.vfc_next = NULL;
4501 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4504 #ifdef COMPAT_FREEBSD32
4506 uint32_t vfc_vfsops;
4507 char vfc_name[MFSNAMELEN];
4508 int32_t vfc_typenum;
4509 int32_t vfc_refcount;
4515 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4517 struct xvfsconf32 xvfsp;
4519 bzero(&xvfsp, sizeof(xvfsp));
4520 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4521 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4522 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4523 xvfsp.vfc_flags = vfsp->vfc_flags;
4524 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4529 * Top level filesystem related information gathering.
4532 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4534 struct vfsconf *vfsp;
4539 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4540 #ifdef COMPAT_FREEBSD32
4541 if (req->flags & SCTL_MASK32)
4542 error = vfsconf2x32(req, vfsp);
4545 error = vfsconf2x(req, vfsp);
4553 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4554 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4555 "S,xvfsconf", "List of all configured filesystems");
4557 #ifndef BURN_BRIDGES
4558 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4561 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4563 int *name = (int *)arg1 - 1; /* XXX */
4564 u_int namelen = arg2 + 1; /* XXX */
4565 struct vfsconf *vfsp;
4567 log(LOG_WARNING, "userland calling deprecated sysctl, "
4568 "please rebuild world\n");
4570 #if 1 || defined(COMPAT_PRELITE2)
4571 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4573 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4577 case VFS_MAXTYPENUM:
4580 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4583 return (ENOTDIR); /* overloaded */
4585 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4586 if (vfsp->vfc_typenum == name[2])
4591 return (EOPNOTSUPP);
4592 #ifdef COMPAT_FREEBSD32
4593 if (req->flags & SCTL_MASK32)
4594 return (vfsconf2x32(req, vfsp));
4597 return (vfsconf2x(req, vfsp));
4599 return (EOPNOTSUPP);
4602 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4603 CTLFLAG_MPSAFE, vfs_sysctl,
4604 "Generic filesystem");
4606 #if 1 || defined(COMPAT_PRELITE2)
4609 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4612 struct vfsconf *vfsp;
4613 struct ovfsconf ovfs;
4616 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4617 bzero(&ovfs, sizeof(ovfs));
4618 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4619 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4620 ovfs.vfc_index = vfsp->vfc_typenum;
4621 ovfs.vfc_refcount = vfsp->vfc_refcount;
4622 ovfs.vfc_flags = vfsp->vfc_flags;
4623 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4633 #endif /* 1 || COMPAT_PRELITE2 */
4634 #endif /* !BURN_BRIDGES */
4636 #define KINFO_VNODESLOP 10
4639 * Dump vnode list (via sysctl).
4643 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4651 * Stale numvnodes access is not fatal here.
4654 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4656 /* Make an estimate */
4657 return (SYSCTL_OUT(req, 0, len));
4659 error = sysctl_wire_old_buffer(req, 0);
4662 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4664 mtx_lock(&mountlist_mtx);
4665 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4666 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4669 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4673 xvn[n].xv_size = sizeof *xvn;
4674 xvn[n].xv_vnode = vp;
4675 xvn[n].xv_id = 0; /* XXX compat */
4676 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4678 XV_COPY(writecount);
4684 xvn[n].xv_flag = vp->v_vflag;
4686 switch (vp->v_type) {
4693 if (vp->v_rdev == NULL) {
4697 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4700 xvn[n].xv_socket = vp->v_socket;
4703 xvn[n].xv_fifo = vp->v_fifoinfo;
4708 /* shouldn't happen? */
4716 mtx_lock(&mountlist_mtx);
4721 mtx_unlock(&mountlist_mtx);
4723 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4728 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4729 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4734 unmount_or_warn(struct mount *mp)
4738 error = dounmount(mp, MNT_FORCE, curthread);
4740 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4744 printf("%d)\n", error);
4749 * Unmount all filesystems. The list is traversed in reverse order
4750 * of mounting to avoid dependencies.
4753 vfs_unmountall(void)
4755 struct mount *mp, *tmp;
4757 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4760 * Since this only runs when rebooting, it is not interlocked.
4762 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4766 * Forcibly unmounting "/dev" before "/" would prevent clean
4767 * unmount of the latter.
4769 if (mp == rootdevmp)
4772 unmount_or_warn(mp);
4775 if (rootdevmp != NULL)
4776 unmount_or_warn(rootdevmp);
4780 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4783 ASSERT_VI_LOCKED(vp, __func__);
4784 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4785 if ((vp->v_iflag & VI_OWEINACT) == 0) {
4789 if (vn_lock(vp, lkflags) == 0) {
4796 vdefer_inactive_unlocked(vp);
4800 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4803 return (vp->v_iflag & VI_DEFINACT);
4806 static void __noinline
4807 vfs_periodic_inactive(struct mount *mp, int flags)
4809 struct vnode *vp, *mvp;
4812 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4813 if (flags != MNT_WAIT)
4814 lkflags |= LK_NOWAIT;
4816 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4817 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4821 vp->v_iflag &= ~VI_DEFINACT;
4822 vfs_deferred_inactive(vp, lkflags);
4827 vfs_want_msync(struct vnode *vp)
4829 struct vm_object *obj;
4832 * This test may be performed without any locks held.
4833 * We rely on vm_object's type stability.
4835 if (vp->v_vflag & VV_NOSYNC)
4838 return (obj != NULL && vm_object_mightbedirty(obj));
4842 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4845 if (vp->v_vflag & VV_NOSYNC)
4847 if (vp->v_iflag & VI_DEFINACT)
4849 return (vfs_want_msync(vp));
4852 static void __noinline
4853 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4855 struct vnode *vp, *mvp;
4856 struct vm_object *obj;
4857 int lkflags, objflags;
4860 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4861 if (flags != MNT_WAIT) {
4862 lkflags |= LK_NOWAIT;
4863 objflags = OBJPC_NOSYNC;
4865 objflags = OBJPC_SYNC;
4868 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4870 if (vp->v_iflag & VI_DEFINACT) {
4871 vp->v_iflag &= ~VI_DEFINACT;
4874 if (!vfs_want_msync(vp)) {
4876 vfs_deferred_inactive(vp, lkflags);
4881 if (vget(vp, lkflags) == 0) {
4883 if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4884 VM_OBJECT_WLOCK(obj);
4885 vm_object_page_clean(obj, 0, 0, objflags);
4886 VM_OBJECT_WUNLOCK(obj);
4893 vdefer_inactive_unlocked(vp);
4899 vfs_periodic(struct mount *mp, int flags)
4902 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4904 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4905 vfs_periodic_inactive(mp, flags);
4907 vfs_periodic_msync_inactive(mp, flags);
4911 destroy_vpollinfo_free(struct vpollinfo *vi)
4914 knlist_destroy(&vi->vpi_selinfo.si_note);
4915 mtx_destroy(&vi->vpi_lock);
4916 free(vi, M_VNODEPOLL);
4920 destroy_vpollinfo(struct vpollinfo *vi)
4923 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4924 seldrain(&vi->vpi_selinfo);
4925 destroy_vpollinfo_free(vi);
4929 * Initialize per-vnode helper structure to hold poll-related state.
4932 v_addpollinfo(struct vnode *vp)
4934 struct vpollinfo *vi;
4936 if (vp->v_pollinfo != NULL)
4938 vi = malloc(sizeof(*vi), M_VNODEPOLL, M_WAITOK | M_ZERO);
4939 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4940 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4941 vfs_knlunlock, vfs_knl_assert_lock);
4943 if (vp->v_pollinfo != NULL) {
4945 destroy_vpollinfo_free(vi);
4948 vp->v_pollinfo = vi;
4953 * Record a process's interest in events which might happen to
4954 * a vnode. Because poll uses the historic select-style interface
4955 * internally, this routine serves as both the ``check for any
4956 * pending events'' and the ``record my interest in future events''
4957 * functions. (These are done together, while the lock is held,
4958 * to avoid race conditions.)
4961 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4965 mtx_lock(&vp->v_pollinfo->vpi_lock);
4966 if (vp->v_pollinfo->vpi_revents & events) {
4968 * This leaves events we are not interested
4969 * in available for the other process which
4970 * which presumably had requested them
4971 * (otherwise they would never have been
4974 events &= vp->v_pollinfo->vpi_revents;
4975 vp->v_pollinfo->vpi_revents &= ~events;
4977 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4980 vp->v_pollinfo->vpi_events |= events;
4981 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4982 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4987 * Routine to create and manage a filesystem syncer vnode.
4989 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4990 static int sync_fsync(struct vop_fsync_args *);
4991 static int sync_inactive(struct vop_inactive_args *);
4992 static int sync_reclaim(struct vop_reclaim_args *);
4994 static struct vop_vector sync_vnodeops = {
4995 .vop_bypass = VOP_EOPNOTSUPP,
4996 .vop_close = sync_close, /* close */
4997 .vop_fsync = sync_fsync, /* fsync */
4998 .vop_inactive = sync_inactive, /* inactive */
4999 .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
5000 .vop_reclaim = sync_reclaim, /* reclaim */
5001 .vop_lock1 = vop_stdlock, /* lock */
5002 .vop_unlock = vop_stdunlock, /* unlock */
5003 .vop_islocked = vop_stdislocked, /* islocked */
5005 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
5008 * Create a new filesystem syncer vnode for the specified mount point.
5011 vfs_allocate_syncvnode(struct mount *mp)
5015 static long start, incr, next;
5018 /* Allocate a new vnode */
5019 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
5021 panic("vfs_allocate_syncvnode: getnewvnode() failed");
5023 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5024 vp->v_vflag |= VV_FORCEINSMQ;
5025 error = insmntque(vp, mp);
5027 panic("vfs_allocate_syncvnode: insmntque() failed");
5028 vp->v_vflag &= ~VV_FORCEINSMQ;
5031 * Place the vnode onto the syncer worklist. We attempt to
5032 * scatter them about on the list so that they will go off
5033 * at evenly distributed times even if all the filesystems
5034 * are mounted at once.
5037 if (next == 0 || next > syncer_maxdelay) {
5041 start = syncer_maxdelay / 2;
5042 incr = syncer_maxdelay;
5048 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
5049 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
5050 mtx_lock(&sync_mtx);
5052 if (mp->mnt_syncer == NULL) {
5053 mp->mnt_syncer = vp;
5056 mtx_unlock(&sync_mtx);
5059 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5066 vfs_deallocate_syncvnode(struct mount *mp)
5070 mtx_lock(&sync_mtx);
5071 vp = mp->mnt_syncer;
5073 mp->mnt_syncer = NULL;
5074 mtx_unlock(&sync_mtx);
5080 * Do a lazy sync of the filesystem.
5083 sync_fsync(struct vop_fsync_args *ap)
5085 struct vnode *syncvp = ap->a_vp;
5086 struct mount *mp = syncvp->v_mount;
5091 * We only need to do something if this is a lazy evaluation.
5093 if (ap->a_waitfor != MNT_LAZY)
5097 * Move ourselves to the back of the sync list.
5099 bo = &syncvp->v_bufobj;
5101 vn_syncer_add_to_worklist(bo, syncdelay);
5105 * Walk the list of vnodes pushing all that are dirty and
5106 * not already on the sync list.
5108 if (vfs_busy(mp, MBF_NOWAIT) != 0)
5110 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
5114 save = curthread_pflags_set(TDP_SYNCIO);
5116 * The filesystem at hand may be idle with free vnodes stored in the
5117 * batch. Return them instead of letting them stay there indefinitely.
5119 vfs_periodic(mp, MNT_NOWAIT);
5120 error = VFS_SYNC(mp, MNT_LAZY);
5121 curthread_pflags_restore(save);
5122 vn_finished_write(mp);
5128 * The syncer vnode is no referenced.
5131 sync_inactive(struct vop_inactive_args *ap)
5139 * The syncer vnode is no longer needed and is being decommissioned.
5141 * Modifications to the worklist must be protected by sync_mtx.
5144 sync_reclaim(struct vop_reclaim_args *ap)
5146 struct vnode *vp = ap->a_vp;
5151 mtx_lock(&sync_mtx);
5152 if (vp->v_mount->mnt_syncer == vp)
5153 vp->v_mount->mnt_syncer = NULL;
5154 if (bo->bo_flag & BO_ONWORKLST) {
5155 LIST_REMOVE(bo, bo_synclist);
5156 syncer_worklist_len--;
5158 bo->bo_flag &= ~BO_ONWORKLST;
5160 mtx_unlock(&sync_mtx);
5167 vn_need_pageq_flush(struct vnode *vp)
5169 struct vm_object *obj;
5172 return (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
5173 vm_object_mightbedirty(obj));
5177 * Check if vnode represents a disk device
5180 vn_isdisk_error(struct vnode *vp, int *errp)
5184 if (vp->v_type != VCHR) {
5190 if (vp->v_rdev == NULL)
5192 else if (vp->v_rdev->si_devsw == NULL)
5194 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5199 return (error == 0);
5203 vn_isdisk(struct vnode *vp)
5207 return (vn_isdisk_error(vp, &error));
5211 * VOP_FPLOOKUP_VEXEC routines are subject to special circumstances, see
5212 * the comment above cache_fplookup for details.
5215 vaccess_vexec_smr(mode_t file_mode, uid_t file_uid, gid_t file_gid, struct ucred *cred)
5219 VFS_SMR_ASSERT_ENTERED();
5221 /* Check the owner. */
5222 if (cred->cr_uid == file_uid) {
5223 if (file_mode & S_IXUSR)
5228 /* Otherwise, check the groups (first match) */
5229 if (groupmember(file_gid, cred)) {
5230 if (file_mode & S_IXGRP)
5235 /* Otherwise, check everyone else. */
5236 if (file_mode & S_IXOTH)
5240 * Permission check failed, but it is possible denial will get overwritten
5241 * (e.g., when root is traversing through a 700 directory owned by someone
5244 * vaccess() calls priv_check_cred which in turn can descent into MAC
5245 * modules overriding this result. It's quite unclear what semantics
5246 * are allowed for them to operate, thus for safety we don't call them
5247 * from within the SMR section. This also means if any such modules
5248 * are present, we have to let the regular lookup decide.
5250 error = priv_check_cred_vfs_lookup_nomac(cred);
5256 * MAC modules present.
5267 * Common filesystem object access control check routine. Accepts a
5268 * vnode's type, "mode", uid and gid, requested access mode, and credentials.
5269 * Returns 0 on success, or an errno on failure.
5272 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5273 accmode_t accmode, struct ucred *cred)
5275 accmode_t dac_granted;
5276 accmode_t priv_granted;
5278 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5279 ("invalid bit in accmode"));
5280 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5281 ("VAPPEND without VWRITE"));
5284 * Look for a normal, non-privileged way to access the file/directory
5285 * as requested. If it exists, go with that.
5290 /* Check the owner. */
5291 if (cred->cr_uid == file_uid) {
5292 dac_granted |= VADMIN;
5293 if (file_mode & S_IXUSR)
5294 dac_granted |= VEXEC;
5295 if (file_mode & S_IRUSR)
5296 dac_granted |= VREAD;
5297 if (file_mode & S_IWUSR)
5298 dac_granted |= (VWRITE | VAPPEND);
5300 if ((accmode & dac_granted) == accmode)
5306 /* Otherwise, check the groups (first match) */
5307 if (groupmember(file_gid, cred)) {
5308 if (file_mode & S_IXGRP)
5309 dac_granted |= VEXEC;
5310 if (file_mode & S_IRGRP)
5311 dac_granted |= VREAD;
5312 if (file_mode & S_IWGRP)
5313 dac_granted |= (VWRITE | VAPPEND);
5315 if ((accmode & dac_granted) == accmode)
5321 /* Otherwise, check everyone else. */
5322 if (file_mode & S_IXOTH)
5323 dac_granted |= VEXEC;
5324 if (file_mode & S_IROTH)
5325 dac_granted |= VREAD;
5326 if (file_mode & S_IWOTH)
5327 dac_granted |= (VWRITE | VAPPEND);
5328 if ((accmode & dac_granted) == accmode)
5333 * Build a privilege mask to determine if the set of privileges
5334 * satisfies the requirements when combined with the granted mask
5335 * from above. For each privilege, if the privilege is required,
5336 * bitwise or the request type onto the priv_granted mask.
5342 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5343 * requests, instead of PRIV_VFS_EXEC.
5345 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5346 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5347 priv_granted |= VEXEC;
5350 * Ensure that at least one execute bit is on. Otherwise,
5351 * a privileged user will always succeed, and we don't want
5352 * this to happen unless the file really is executable.
5354 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5355 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5356 !priv_check_cred(cred, PRIV_VFS_EXEC))
5357 priv_granted |= VEXEC;
5360 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5361 !priv_check_cred(cred, PRIV_VFS_READ))
5362 priv_granted |= VREAD;
5364 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5365 !priv_check_cred(cred, PRIV_VFS_WRITE))
5366 priv_granted |= (VWRITE | VAPPEND);
5368 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5369 !priv_check_cred(cred, PRIV_VFS_ADMIN))
5370 priv_granted |= VADMIN;
5372 if ((accmode & (priv_granted | dac_granted)) == accmode) {
5376 return ((accmode & VADMIN) ? EPERM : EACCES);
5380 * Credential check based on process requesting service, and per-attribute
5384 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5385 struct thread *td, accmode_t accmode)
5389 * Kernel-invoked always succeeds.
5395 * Do not allow privileged processes in jail to directly manipulate
5396 * system attributes.
5398 switch (attrnamespace) {
5399 case EXTATTR_NAMESPACE_SYSTEM:
5400 /* Potentially should be: return (EPERM); */
5401 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5402 case EXTATTR_NAMESPACE_USER:
5403 return (VOP_ACCESS(vp, accmode, cred, td));
5409 #ifdef DEBUG_VFS_LOCKS
5410 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
5411 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5412 "Drop into debugger on lock violation");
5414 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
5415 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5416 0, "Check for interlock across VOPs");
5418 int vfs_badlock_print = 1; /* Print lock violations. */
5419 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5420 0, "Print lock violations");
5422 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
5423 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5424 0, "Print vnode details on lock violations");
5427 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
5428 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5429 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5433 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5437 if (vfs_badlock_backtrace)
5440 if (vfs_badlock_vnode)
5441 vn_printf(vp, "vnode ");
5442 if (vfs_badlock_print)
5443 printf("%s: %p %s\n", str, (void *)vp, msg);
5444 if (vfs_badlock_ddb)
5445 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5449 assert_vi_locked(struct vnode *vp, const char *str)
5452 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5453 vfs_badlock("interlock is not locked but should be", str, vp);
5457 assert_vi_unlocked(struct vnode *vp, const char *str)
5460 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5461 vfs_badlock("interlock is locked but should not be", str, vp);
5465 assert_vop_locked(struct vnode *vp, const char *str)
5469 if (KERNEL_PANICKED() || vp == NULL)
5472 locked = VOP_ISLOCKED(vp);
5473 if (locked == 0 || locked == LK_EXCLOTHER)
5474 vfs_badlock("is not locked but should be", str, vp);
5478 assert_vop_unlocked(struct vnode *vp, const char *str)
5480 if (KERNEL_PANICKED() || vp == NULL)
5483 if (VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5484 vfs_badlock("is locked but should not be", str, vp);
5488 assert_vop_elocked(struct vnode *vp, const char *str)
5490 if (KERNEL_PANICKED() || vp == NULL)
5493 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5494 vfs_badlock("is not exclusive locked but should be", str, vp);
5496 #endif /* DEBUG_VFS_LOCKS */
5499 vop_rename_fail(struct vop_rename_args *ap)
5502 if (ap->a_tvp != NULL)
5504 if (ap->a_tdvp == ap->a_tvp)
5513 vop_rename_pre(void *ap)
5515 struct vop_rename_args *a = ap;
5517 #ifdef DEBUG_VFS_LOCKS
5519 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5520 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5521 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5522 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5524 /* Check the source (from). */
5525 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5526 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5527 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5528 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5529 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5531 /* Check the target. */
5533 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5534 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5537 * It may be tempting to add vn_seqc_write_begin/end calls here and
5538 * in vop_rename_post but that's not going to work out since some
5539 * filesystems relookup vnodes mid-rename. This is probably a bug.
5541 * For now filesystems are expected to do the relevant calls after they
5542 * decide what vnodes to operate on.
5544 if (a->a_tdvp != a->a_fdvp)
5546 if (a->a_tvp != a->a_fvp)
5553 #ifdef DEBUG_VFS_LOCKS
5555 vop_fplookup_vexec_debugpre(void *ap __unused)
5558 VFS_SMR_ASSERT_ENTERED();
5562 vop_fplookup_vexec_debugpost(void *ap __unused, int rc __unused)
5565 VFS_SMR_ASSERT_ENTERED();
5569 vop_fplookup_symlink_debugpre(void *ap __unused)
5572 VFS_SMR_ASSERT_ENTERED();
5576 vop_fplookup_symlink_debugpost(void *ap __unused, int rc __unused)
5579 VFS_SMR_ASSERT_ENTERED();
5583 vop_fsync_debugprepost(struct vnode *vp, const char *name)
5585 if (vp->v_type == VCHR)
5587 else if (MNT_EXTENDED_SHARED(vp->v_mount))
5588 ASSERT_VOP_LOCKED(vp, name);
5590 ASSERT_VOP_ELOCKED(vp, name);
5594 vop_fsync_debugpre(void *a)
5596 struct vop_fsync_args *ap;
5599 vop_fsync_debugprepost(ap->a_vp, "fsync");
5603 vop_fsync_debugpost(void *a, int rc __unused)
5605 struct vop_fsync_args *ap;
5608 vop_fsync_debugprepost(ap->a_vp, "fsync");
5612 vop_fdatasync_debugpre(void *a)
5614 struct vop_fdatasync_args *ap;
5617 vop_fsync_debugprepost(ap->a_vp, "fsync");
5621 vop_fdatasync_debugpost(void *a, int rc __unused)
5623 struct vop_fdatasync_args *ap;
5626 vop_fsync_debugprepost(ap->a_vp, "fsync");
5630 vop_strategy_debugpre(void *ap)
5632 struct vop_strategy_args *a;
5639 * Cluster ops lock their component buffers but not the IO container.
5641 if ((bp->b_flags & B_CLUSTER) != 0)
5644 if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5645 if (vfs_badlock_print)
5647 "VOP_STRATEGY: bp is not locked but should be\n");
5648 if (vfs_badlock_ddb)
5649 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5654 vop_lock_debugpre(void *ap)
5656 struct vop_lock1_args *a = ap;
5658 if ((a->a_flags & LK_INTERLOCK) == 0)
5659 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5661 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5665 vop_lock_debugpost(void *ap, int rc)
5667 struct vop_lock1_args *a = ap;
5669 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5670 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5671 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5675 vop_unlock_debugpre(void *ap)
5677 struct vop_unlock_args *a = ap;
5679 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5683 vop_need_inactive_debugpre(void *ap)
5685 struct vop_need_inactive_args *a = ap;
5687 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5691 vop_need_inactive_debugpost(void *ap, int rc)
5693 struct vop_need_inactive_args *a = ap;
5695 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5700 vop_create_pre(void *ap)
5702 struct vop_create_args *a;
5707 vn_seqc_write_begin(dvp);
5711 vop_create_post(void *ap, int rc)
5713 struct vop_create_args *a;
5718 vn_seqc_write_end(dvp);
5720 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5724 vop_whiteout_pre(void *ap)
5726 struct vop_whiteout_args *a;
5731 vn_seqc_write_begin(dvp);
5735 vop_whiteout_post(void *ap, int rc)
5737 struct vop_whiteout_args *a;
5742 vn_seqc_write_end(dvp);
5746 vop_deleteextattr_pre(void *ap)
5748 struct vop_deleteextattr_args *a;
5753 vn_seqc_write_begin(vp);
5757 vop_deleteextattr_post(void *ap, int rc)
5759 struct vop_deleteextattr_args *a;
5764 vn_seqc_write_end(vp);
5766 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5770 vop_link_pre(void *ap)
5772 struct vop_link_args *a;
5773 struct vnode *vp, *tdvp;
5778 vn_seqc_write_begin(vp);
5779 vn_seqc_write_begin(tdvp);
5783 vop_link_post(void *ap, int rc)
5785 struct vop_link_args *a;
5786 struct vnode *vp, *tdvp;
5791 vn_seqc_write_end(vp);
5792 vn_seqc_write_end(tdvp);
5794 VFS_KNOTE_LOCKED(vp, NOTE_LINK);
5795 VFS_KNOTE_LOCKED(tdvp, NOTE_WRITE);
5800 vop_mkdir_pre(void *ap)
5802 struct vop_mkdir_args *a;
5807 vn_seqc_write_begin(dvp);
5811 vop_mkdir_post(void *ap, int rc)
5813 struct vop_mkdir_args *a;
5818 vn_seqc_write_end(dvp);
5820 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5823 #ifdef DEBUG_VFS_LOCKS
5825 vop_mkdir_debugpost(void *ap, int rc)
5827 struct vop_mkdir_args *a;
5831 cache_validate(a->a_dvp, *a->a_vpp, a->a_cnp);
5836 vop_mknod_pre(void *ap)
5838 struct vop_mknod_args *a;
5843 vn_seqc_write_begin(dvp);
5847 vop_mknod_post(void *ap, int rc)
5849 struct vop_mknod_args *a;
5854 vn_seqc_write_end(dvp);
5856 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5860 vop_reclaim_post(void *ap, int rc)
5862 struct vop_reclaim_args *a;
5867 ASSERT_VOP_IN_SEQC(vp);
5869 VFS_KNOTE_LOCKED(vp, NOTE_REVOKE);
5873 vop_remove_pre(void *ap)
5875 struct vop_remove_args *a;
5876 struct vnode *dvp, *vp;
5881 vn_seqc_write_begin(dvp);
5882 vn_seqc_write_begin(vp);
5886 vop_remove_post(void *ap, int rc)
5888 struct vop_remove_args *a;
5889 struct vnode *dvp, *vp;
5894 vn_seqc_write_end(dvp);
5895 vn_seqc_write_end(vp);
5897 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5898 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5903 vop_rename_post(void *ap, int rc)
5905 struct vop_rename_args *a = ap;
5910 if (a->a_fdvp == a->a_tdvp) {
5911 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5913 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5914 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5916 hint |= NOTE_EXTEND;
5917 if (a->a_fvp->v_type == VDIR)
5919 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5921 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5922 a->a_tvp->v_type == VDIR)
5924 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5927 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5929 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5931 if (a->a_tdvp != a->a_fdvp)
5933 if (a->a_tvp != a->a_fvp)
5941 vop_rmdir_pre(void *ap)
5943 struct vop_rmdir_args *a;
5944 struct vnode *dvp, *vp;
5949 vn_seqc_write_begin(dvp);
5950 vn_seqc_write_begin(vp);
5954 vop_rmdir_post(void *ap, int rc)
5956 struct vop_rmdir_args *a;
5957 struct vnode *dvp, *vp;
5962 vn_seqc_write_end(dvp);
5963 vn_seqc_write_end(vp);
5965 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5966 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5971 vop_setattr_pre(void *ap)
5973 struct vop_setattr_args *a;
5978 vn_seqc_write_begin(vp);
5982 vop_setattr_post(void *ap, int rc)
5984 struct vop_setattr_args *a;
5989 vn_seqc_write_end(vp);
5991 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
5995 vop_setacl_pre(void *ap)
5997 struct vop_setacl_args *a;
6002 vn_seqc_write_begin(vp);
6006 vop_setacl_post(void *ap, int rc __unused)
6008 struct vop_setacl_args *a;
6013 vn_seqc_write_end(vp);
6017 vop_setextattr_pre(void *ap)
6019 struct vop_setextattr_args *a;
6024 vn_seqc_write_begin(vp);
6028 vop_setextattr_post(void *ap, int rc)
6030 struct vop_setextattr_args *a;
6035 vn_seqc_write_end(vp);
6037 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6041 vop_symlink_pre(void *ap)
6043 struct vop_symlink_args *a;
6048 vn_seqc_write_begin(dvp);
6052 vop_symlink_post(void *ap, int rc)
6054 struct vop_symlink_args *a;
6059 vn_seqc_write_end(dvp);
6061 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6065 vop_open_post(void *ap, int rc)
6067 struct vop_open_args *a = ap;
6070 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
6074 vop_close_post(void *ap, int rc)
6076 struct vop_close_args *a = ap;
6078 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
6079 !VN_IS_DOOMED(a->a_vp))) {
6080 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
6081 NOTE_CLOSE_WRITE : NOTE_CLOSE);
6086 vop_read_post(void *ap, int rc)
6088 struct vop_read_args *a = ap;
6091 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6095 vop_read_pgcache_post(void *ap, int rc)
6097 struct vop_read_pgcache_args *a = ap;
6100 VFS_KNOTE_UNLOCKED(a->a_vp, NOTE_READ);
6104 vop_readdir_post(void *ap, int rc)
6106 struct vop_readdir_args *a = ap;
6109 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6112 static struct knlist fs_knlist;
6115 vfs_event_init(void *arg)
6117 knlist_init_mtx(&fs_knlist, NULL);
6119 /* XXX - correct order? */
6120 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
6123 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
6126 KNOTE_UNLOCKED(&fs_knlist, event);
6129 static int filt_fsattach(struct knote *kn);
6130 static void filt_fsdetach(struct knote *kn);
6131 static int filt_fsevent(struct knote *kn, long hint);
6133 struct filterops fs_filtops = {
6135 .f_attach = filt_fsattach,
6136 .f_detach = filt_fsdetach,
6137 .f_event = filt_fsevent
6141 filt_fsattach(struct knote *kn)
6144 kn->kn_flags |= EV_CLEAR;
6145 knlist_add(&fs_knlist, kn, 0);
6150 filt_fsdetach(struct knote *kn)
6153 knlist_remove(&fs_knlist, kn, 0);
6157 filt_fsevent(struct knote *kn, long hint)
6160 kn->kn_fflags |= hint;
6161 return (kn->kn_fflags != 0);
6165 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
6171 error = SYSCTL_IN(req, &vc, sizeof(vc));
6174 if (vc.vc_vers != VFS_CTL_VERS1)
6176 mp = vfs_getvfs(&vc.vc_fsid);
6179 /* ensure that a specific sysctl goes to the right filesystem. */
6180 if (strcmp(vc.vc_fstypename, "*") != 0 &&
6181 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
6185 VCTLTOREQ(&vc, req);
6186 error = VFS_SYSCTL(mp, vc.vc_op, req);
6191 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
6192 NULL, 0, sysctl_vfs_ctl, "",
6196 * Function to initialize a va_filerev field sensibly.
6197 * XXX: Wouldn't a random number make a lot more sense ??
6200 init_va_filerev(void)
6205 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
6208 static int filt_vfsread(struct knote *kn, long hint);
6209 static int filt_vfswrite(struct knote *kn, long hint);
6210 static int filt_vfsvnode(struct knote *kn, long hint);
6211 static void filt_vfsdetach(struct knote *kn);
6212 static struct filterops vfsread_filtops = {
6214 .f_detach = filt_vfsdetach,
6215 .f_event = filt_vfsread
6217 static struct filterops vfswrite_filtops = {
6219 .f_detach = filt_vfsdetach,
6220 .f_event = filt_vfswrite
6222 static struct filterops vfsvnode_filtops = {
6224 .f_detach = filt_vfsdetach,
6225 .f_event = filt_vfsvnode
6229 vfs_knllock(void *arg)
6231 struct vnode *vp = arg;
6233 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
6237 vfs_knlunlock(void *arg)
6239 struct vnode *vp = arg;
6245 vfs_knl_assert_lock(void *arg, int what)
6247 #ifdef DEBUG_VFS_LOCKS
6248 struct vnode *vp = arg;
6250 if (what == LA_LOCKED)
6251 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
6253 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
6258 vfs_kqfilter(struct vop_kqfilter_args *ap)
6260 struct vnode *vp = ap->a_vp;
6261 struct knote *kn = ap->a_kn;
6264 switch (kn->kn_filter) {
6266 kn->kn_fop = &vfsread_filtops;
6269 kn->kn_fop = &vfswrite_filtops;
6272 kn->kn_fop = &vfsvnode_filtops;
6278 kn->kn_hook = (caddr_t)vp;
6281 if (vp->v_pollinfo == NULL)
6283 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
6285 knlist_add(knl, kn, 0);
6291 * Detach knote from vnode
6294 filt_vfsdetach(struct knote *kn)
6296 struct vnode *vp = (struct vnode *)kn->kn_hook;
6298 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
6299 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
6305 filt_vfsread(struct knote *kn, long hint)
6307 struct vnode *vp = (struct vnode *)kn->kn_hook;
6312 * filesystem is gone, so set the EOF flag and schedule
6313 * the knote for deletion.
6315 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6317 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6322 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
6326 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
6327 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
6334 filt_vfswrite(struct knote *kn, long hint)
6336 struct vnode *vp = (struct vnode *)kn->kn_hook;
6341 * filesystem is gone, so set the EOF flag and schedule
6342 * the knote for deletion.
6344 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
6345 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6353 filt_vfsvnode(struct knote *kn, long hint)
6355 struct vnode *vp = (struct vnode *)kn->kn_hook;
6359 if (kn->kn_sfflags & hint)
6360 kn->kn_fflags |= hint;
6361 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6362 kn->kn_flags |= EV_EOF;
6366 res = (kn->kn_fflags != 0);
6372 * Returns whether the directory is empty or not.
6373 * If it is empty, the return value is 0; otherwise
6374 * the return value is an error value (which may
6378 vfs_emptydir(struct vnode *vp)
6382 struct dirent *dirent, *dp, *endp;
6388 ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
6389 VNASSERT(vp->v_type == VDIR, vp, ("vp is not a directory"));
6391 dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
6392 iov.iov_base = dirent;
6393 iov.iov_len = sizeof(struct dirent);
6398 uio.uio_resid = sizeof(struct dirent);
6399 uio.uio_segflg = UIO_SYSSPACE;
6400 uio.uio_rw = UIO_READ;
6401 uio.uio_td = curthread;
6403 while (eof == 0 && error == 0) {
6404 error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
6408 endp = (void *)((uint8_t *)dirent +
6409 sizeof(struct dirent) - uio.uio_resid);
6410 for (dp = dirent; dp < endp;
6411 dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
6412 if (dp->d_type == DT_WHT)
6414 if (dp->d_namlen == 0)
6416 if (dp->d_type != DT_DIR &&
6417 dp->d_type != DT_UNKNOWN) {
6421 if (dp->d_namlen > 2) {
6425 if (dp->d_namlen == 1 &&
6426 dp->d_name[0] != '.') {
6430 if (dp->d_namlen == 2 &&
6431 dp->d_name[1] != '.') {
6435 uio.uio_resid = sizeof(struct dirent);
6438 free(dirent, M_TEMP);
6443 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6447 if (dp->d_reclen > ap->a_uio->uio_resid)
6448 return (ENAMETOOLONG);
6449 error = uiomove(dp, dp->d_reclen, ap->a_uio);
6451 if (ap->a_ncookies != NULL) {
6452 if (ap->a_cookies != NULL)
6453 free(ap->a_cookies, M_TEMP);
6454 ap->a_cookies = NULL;
6455 *ap->a_ncookies = 0;
6459 if (ap->a_ncookies == NULL)
6462 KASSERT(ap->a_cookies,
6463 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6465 *ap->a_cookies = realloc(*ap->a_cookies,
6466 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
6467 (*ap->a_cookies)[*ap->a_ncookies] = off;
6468 *ap->a_ncookies += 1;
6473 * The purpose of this routine is to remove granularity from accmode_t,
6474 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6475 * VADMIN and VAPPEND.
6477 * If it returns 0, the caller is supposed to continue with the usual
6478 * access checks using 'accmode' as modified by this routine. If it
6479 * returns nonzero value, the caller is supposed to return that value
6482 * Note that after this routine runs, accmode may be zero.
6485 vfs_unixify_accmode(accmode_t *accmode)
6488 * There is no way to specify explicit "deny" rule using
6489 * file mode or POSIX.1e ACLs.
6491 if (*accmode & VEXPLICIT_DENY) {
6497 * None of these can be translated into usual access bits.
6498 * Also, the common case for NFSv4 ACLs is to not contain
6499 * either of these bits. Caller should check for VWRITE
6500 * on the containing directory instead.
6502 if (*accmode & (VDELETE_CHILD | VDELETE))
6505 if (*accmode & VADMIN_PERMS) {
6506 *accmode &= ~VADMIN_PERMS;
6511 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6512 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6514 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6520 * Clear out a doomed vnode (if any) and replace it with a new one as long
6521 * as the fs is not being unmounted. Return the root vnode to the caller.
6523 static int __noinline
6524 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6530 if (mp->mnt_rootvnode != NULL) {
6532 vp = mp->mnt_rootvnode;
6534 if (!VN_IS_DOOMED(vp)) {
6537 error = vn_lock(vp, flags);
6546 * Clear the old one.
6548 mp->mnt_rootvnode = NULL;
6552 vfs_op_barrier_wait(mp);
6556 error = VFS_CACHEDROOT(mp, flags, vpp);
6559 if (mp->mnt_vfs_ops == 0) {
6561 if (mp->mnt_vfs_ops != 0) {
6565 if (mp->mnt_rootvnode == NULL) {
6567 mp->mnt_rootvnode = *vpp;
6569 if (mp->mnt_rootvnode != *vpp) {
6570 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6571 panic("%s: mismatch between vnode returned "
6572 " by VFS_CACHEDROOT and the one cached "
6574 __func__, *vpp, mp->mnt_rootvnode);
6584 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6586 struct mount_pcpu *mpcpu;
6590 if (!vfs_op_thread_enter(mp, mpcpu))
6591 return (vfs_cache_root_fallback(mp, flags, vpp));
6592 vp = atomic_load_ptr(&mp->mnt_rootvnode);
6593 if (vp == NULL || VN_IS_DOOMED(vp)) {
6594 vfs_op_thread_exit(mp, mpcpu);
6595 return (vfs_cache_root_fallback(mp, flags, vpp));
6598 vfs_op_thread_exit(mp, mpcpu);
6599 error = vn_lock(vp, flags);
6602 return (vfs_cache_root_fallback(mp, flags, vpp));
6609 vfs_cache_root_clear(struct mount *mp)
6614 * ops > 0 guarantees there is nobody who can see this vnode
6616 MPASS(mp->mnt_vfs_ops > 0);
6617 vp = mp->mnt_rootvnode;
6619 vn_seqc_write_begin(vp);
6620 mp->mnt_rootvnode = NULL;
6625 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6628 MPASS(mp->mnt_vfs_ops > 0);
6630 mp->mnt_rootvnode = vp;
6634 * These are helper functions for filesystems to traverse all
6635 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6637 * This interface replaces MNT_VNODE_FOREACH.
6641 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6646 kern_yield(PRI_USER);
6648 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6649 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6650 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6651 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6652 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6655 if (VN_IS_DOOMED(vp)) {
6662 __mnt_vnode_markerfree_all(mvp, mp);
6663 /* MNT_IUNLOCK(mp); -- done in above function */
6664 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6667 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6668 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6674 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6678 *mvp = vn_alloc_marker(mp);
6682 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6683 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6684 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6687 if (VN_IS_DOOMED(vp)) {
6696 vn_free_marker(*mvp);
6700 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6706 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6714 mtx_assert(MNT_MTX(mp), MA_OWNED);
6716 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6717 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6720 vn_free_marker(*mvp);
6725 * These are helper functions for filesystems to traverse their
6726 * lazy vnodes. See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6729 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6732 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6737 vn_free_marker(*mvp);
6742 * Relock the mp mount vnode list lock with the vp vnode interlock in the
6743 * conventional lock order during mnt_vnode_next_lazy iteration.
6745 * On entry, the mount vnode list lock is held and the vnode interlock is not.
6746 * The list lock is dropped and reacquired. On success, both locks are held.
6747 * On failure, the mount vnode list lock is held but the vnode interlock is
6748 * not, and the procedure may have yielded.
6751 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6755 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6756 TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6757 ("%s: bad marker", __func__));
6758 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6759 ("%s: inappropriate vnode", __func__));
6760 ASSERT_VI_UNLOCKED(vp, __func__);
6761 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6763 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6764 TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6767 * Note we may be racing against vdrop which transitioned the hold
6768 * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
6769 * if we are the only user after we get the interlock we will just
6773 mtx_unlock(&mp->mnt_listmtx);
6775 if (VN_IS_DOOMED(vp)) {
6776 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
6779 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
6781 * There is nothing to do if we are the last user.
6783 if (!refcount_release_if_not_last(&vp->v_holdcnt))
6785 mtx_lock(&mp->mnt_listmtx);
6790 mtx_lock(&mp->mnt_listmtx);
6794 static struct vnode *
6795 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6800 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6801 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6803 vp = TAILQ_NEXT(*mvp, v_lazylist);
6804 while (vp != NULL) {
6805 if (vp->v_type == VMARKER) {
6806 vp = TAILQ_NEXT(vp, v_lazylist);
6810 * See if we want to process the vnode. Note we may encounter a
6811 * long string of vnodes we don't care about and hog the list
6812 * as a result. Check for it and requeue the marker.
6814 VNPASS(!VN_IS_DOOMED(vp), vp);
6815 if (!cb(vp, cbarg)) {
6816 if (!should_yield()) {
6817 vp = TAILQ_NEXT(vp, v_lazylist);
6820 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6822 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6824 mtx_unlock(&mp->mnt_listmtx);
6825 kern_yield(PRI_USER);
6826 mtx_lock(&mp->mnt_listmtx);
6830 * Try-lock because this is the wrong lock order.
6832 if (!VI_TRYLOCK(vp) &&
6833 !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6835 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6836 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6837 ("alien vnode on the lazy list %p %p", vp, mp));
6838 VNPASS(vp->v_mount == mp, vp);
6839 VNPASS(!VN_IS_DOOMED(vp), vp);
6842 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6844 /* Check if we are done */
6846 mtx_unlock(&mp->mnt_listmtx);
6847 mnt_vnode_markerfree_lazy(mvp, mp);
6850 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6851 mtx_unlock(&mp->mnt_listmtx);
6852 ASSERT_VI_LOCKED(vp, "lazy iter");
6857 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6862 kern_yield(PRI_USER);
6863 mtx_lock(&mp->mnt_listmtx);
6864 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6868 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6873 if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
6876 *mvp = vn_alloc_marker(mp);
6881 mtx_lock(&mp->mnt_listmtx);
6882 vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6884 mtx_unlock(&mp->mnt_listmtx);
6885 mnt_vnode_markerfree_lazy(mvp, mp);
6888 TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6889 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6893 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6899 mtx_lock(&mp->mnt_listmtx);
6900 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6901 mtx_unlock(&mp->mnt_listmtx);
6902 mnt_vnode_markerfree_lazy(mvp, mp);
6906 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
6909 if ((cnp->cn_flags & NOEXECCHECK) != 0) {
6910 cnp->cn_flags &= ~NOEXECCHECK;
6914 return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, cnp->cn_thread));
6918 * Do not use this variant unless you have means other than the hold count
6919 * to prevent the vnode from getting freed.
6922 vn_seqc_write_begin_locked(struct vnode *vp)
6925 ASSERT_VI_LOCKED(vp, __func__);
6926 VNPASS(vp->v_holdcnt > 0, vp);
6927 VNPASS(vp->v_seqc_users >= 0, vp);
6929 if (vp->v_seqc_users == 1)
6930 seqc_sleepable_write_begin(&vp->v_seqc);
6934 vn_seqc_write_begin(struct vnode *vp)
6938 vn_seqc_write_begin_locked(vp);
6943 vn_seqc_write_end_locked(struct vnode *vp)
6946 ASSERT_VI_LOCKED(vp, __func__);
6947 VNPASS(vp->v_seqc_users > 0, vp);
6949 if (vp->v_seqc_users == 0)
6950 seqc_sleepable_write_end(&vp->v_seqc);
6954 vn_seqc_write_end(struct vnode *vp)
6958 vn_seqc_write_end_locked(vp);
6963 * Special case handling for allocating and freeing vnodes.
6965 * The counter remains unchanged on free so that a doomed vnode will
6966 * keep testing as in modify as long as it is accessible with SMR.
6969 vn_seqc_init(struct vnode *vp)
6973 vp->v_seqc_users = 0;
6977 vn_seqc_write_end_free(struct vnode *vp)
6980 VNPASS(seqc_in_modify(vp->v_seqc), vp);
6981 VNPASS(vp->v_seqc_users == 1, vp);
6985 vn_irflag_set_locked(struct vnode *vp, short toset)
6989 ASSERT_VI_LOCKED(vp, __func__);
6990 flags = vn_irflag_read(vp);
6991 VNASSERT((flags & toset) == 0, vp,
6992 ("%s: some of the passed flags already set (have %d, passed %d)\n",
6993 __func__, flags, toset));
6994 atomic_store_short(&vp->v_irflag, flags | toset);
6998 vn_irflag_set(struct vnode *vp, short toset)
7002 vn_irflag_set_locked(vp, toset);
7007 vn_irflag_set_cond_locked(struct vnode *vp, short toset)
7011 ASSERT_VI_LOCKED(vp, __func__);
7012 flags = vn_irflag_read(vp);
7013 atomic_store_short(&vp->v_irflag, flags | toset);
7017 vn_irflag_set_cond(struct vnode *vp, short toset)
7021 vn_irflag_set_cond_locked(vp, toset);
7026 vn_irflag_unset_locked(struct vnode *vp, short tounset)
7030 ASSERT_VI_LOCKED(vp, __func__);
7031 flags = vn_irflag_read(vp);
7032 VNASSERT((flags & tounset) == tounset, vp,
7033 ("%s: some of the passed flags not set (have %d, passed %d)\n",
7034 __func__, flags, tounset));
7035 atomic_store_short(&vp->v_irflag, flags & ~tounset);
7039 vn_irflag_unset(struct vnode *vp, short tounset)
7043 vn_irflag_unset_locked(vp, tounset);