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>
102 #if defined(DEBUG_VFS_LOCKS) && (!defined(INVARIANTS) || !defined(WITNESS))
103 #error DEBUG_VFS_LOCKS requires INVARIANTS and WITNESS
110 static void delmntque(struct vnode *vp);
111 static int flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
112 int slpflag, int slptimeo);
113 static void syncer_shutdown(void *arg, int howto);
114 static int vtryrecycle(struct vnode *vp);
115 static void v_init_counters(struct vnode *);
116 static void vn_seqc_init(struct vnode *);
117 static void vn_seqc_write_end_free(struct vnode *vp);
118 static void vgonel(struct vnode *);
119 static bool vhold_recycle_free(struct vnode *);
120 static void vdropl_recycle(struct vnode *vp);
121 static void vdrop_recycle(struct vnode *vp);
122 static void vfs_knllock(void *arg);
123 static void vfs_knlunlock(void *arg);
124 static void vfs_knl_assert_lock(void *arg, int what);
125 static void destroy_vpollinfo(struct vpollinfo *vi);
126 static int v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
127 daddr_t startlbn, daddr_t endlbn);
128 static void vnlru_recalc(void);
131 * Number of vnodes in existence. Increased whenever getnewvnode()
132 * allocates a new vnode, decreased in vdropl() for VIRF_DOOMED vnode.
134 static u_long __exclusive_cache_line numvnodes;
136 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
137 "Number of vnodes in existence");
139 static counter_u64_t vnodes_created;
140 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
141 "Number of vnodes created by getnewvnode");
144 * Conversion tables for conversion from vnode types to inode formats
147 enum vtype iftovt_tab[16] = {
148 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
149 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
151 int vttoif_tab[10] = {
152 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
153 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
157 * List of allocates vnodes in the system.
159 static TAILQ_HEAD(freelst, vnode) vnode_list;
160 static struct vnode *vnode_list_free_marker;
161 static struct vnode *vnode_list_reclaim_marker;
164 * "Free" vnode target. Free vnodes are rarely completely free, but are
165 * just ones that are cheap to recycle. Usually they are for files which
166 * have been stat'd but not read; these usually have inode and namecache
167 * data attached to them. This target is the preferred minimum size of a
168 * sub-cache consisting mostly of such files. The system balances the size
169 * of this sub-cache with its complement to try to prevent either from
170 * thrashing while the other is relatively inactive. The targets express
171 * a preference for the best balance.
173 * "Above" this target there are 2 further targets (watermarks) related
174 * to recyling of free vnodes. In the best-operating case, the cache is
175 * exactly full, the free list has size between vlowat and vhiwat above the
176 * free target, and recycling from it and normal use maintains this state.
177 * Sometimes the free list is below vlowat or even empty, but this state
178 * is even better for immediate use provided the cache is not full.
179 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
180 * ones) to reach one of these states. The watermarks are currently hard-
181 * coded as 4% and 9% of the available space higher. These and the default
182 * of 25% for wantfreevnodes are too large if the memory size is large.
183 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
184 * whenever vnlru_proc() becomes active.
186 static long wantfreevnodes;
187 static long __exclusive_cache_line freevnodes;
188 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
189 &freevnodes, 0, "Number of \"free\" vnodes");
190 static long freevnodes_old;
192 static counter_u64_t recycles_count;
193 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
194 "Number of vnodes recycled to meet vnode cache targets");
196 static counter_u64_t recycles_free_count;
197 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD, &recycles_free_count,
198 "Number of free vnodes recycled to meet vnode cache targets");
200 static counter_u64_t deferred_inact;
201 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, deferred_inact, CTLFLAG_RD, &deferred_inact,
202 "Number of times inactive processing was deferred");
204 /* To keep more than one thread at a time from running vfs_getnewfsid */
205 static struct mtx mntid_mtx;
208 * Lock for any access to the following:
213 static struct mtx __exclusive_cache_line vnode_list_mtx;
215 /* Publicly exported FS */
216 struct nfs_public nfs_pub;
218 static uma_zone_t buf_trie_zone;
219 static smr_t buf_trie_smr;
221 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
222 static uma_zone_t vnode_zone;
223 MALLOC_DEFINE(M_VNODEPOLL, "VN POLL", "vnode poll");
225 __read_frequently smr_t vfs_smr;
228 * The workitem queue.
230 * It is useful to delay writes of file data and filesystem metadata
231 * for tens of seconds so that quickly created and deleted files need
232 * not waste disk bandwidth being created and removed. To realize this,
233 * we append vnodes to a "workitem" queue. When running with a soft
234 * updates implementation, most pending metadata dependencies should
235 * not wait for more than a few seconds. Thus, mounted on block devices
236 * are delayed only about a half the time that file data is delayed.
237 * Similarly, directory updates are more critical, so are only delayed
238 * about a third the time that file data is delayed. Thus, there are
239 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
240 * one each second (driven off the filesystem syncer process). The
241 * syncer_delayno variable indicates the next queue that is to be processed.
242 * Items that need to be processed soon are placed in this queue:
244 * syncer_workitem_pending[syncer_delayno]
246 * A delay of fifteen seconds is done by placing the request fifteen
247 * entries later in the queue:
249 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
252 static int syncer_delayno;
253 static long syncer_mask;
254 LIST_HEAD(synclist, bufobj);
255 static struct synclist *syncer_workitem_pending;
257 * The sync_mtx protects:
262 * syncer_workitem_pending
263 * syncer_worklist_len
266 static struct mtx sync_mtx;
267 static struct cv sync_wakeup;
269 #define SYNCER_MAXDELAY 32
270 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
271 static int syncdelay = 30; /* max time to delay syncing data */
272 static int filedelay = 30; /* time to delay syncing files */
273 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
274 "Time to delay syncing files (in seconds)");
275 static int dirdelay = 29; /* time to delay syncing directories */
276 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
277 "Time to delay syncing directories (in seconds)");
278 static int metadelay = 28; /* time to delay syncing metadata */
279 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
280 "Time to delay syncing metadata (in seconds)");
281 static int rushjob; /* number of slots to run ASAP */
282 static int stat_rush_requests; /* number of times I/O speeded up */
283 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
284 "Number of times I/O speeded up (rush requests)");
286 #define VDBATCH_SIZE 8
291 struct vnode *tab[VDBATCH_SIZE];
293 DPCPU_DEFINE_STATIC(struct vdbatch, vd);
295 static void vdbatch_dequeue(struct vnode *vp);
298 * When shutting down the syncer, run it at four times normal speed.
300 #define SYNCER_SHUTDOWN_SPEEDUP 4
301 static int sync_vnode_count;
302 static int syncer_worklist_len;
303 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
306 /* Target for maximum number of vnodes. */
307 u_long desiredvnodes;
308 static u_long gapvnodes; /* gap between wanted and desired */
309 static u_long vhiwat; /* enough extras after expansion */
310 static u_long vlowat; /* minimal extras before expansion */
311 static u_long vstir; /* nonzero to stir non-free vnodes */
312 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
314 static u_long vnlru_read_freevnodes(void);
317 * Note that no attempt is made to sanitize these parameters.
320 sysctl_maxvnodes(SYSCTL_HANDLER_ARGS)
326 error = sysctl_handle_long(oidp, &val, 0, req);
327 if (error != 0 || req->newptr == NULL)
330 if (val == desiredvnodes)
332 mtx_lock(&vnode_list_mtx);
334 wantfreevnodes = desiredvnodes / 4;
336 mtx_unlock(&vnode_list_mtx);
338 * XXX There is no protection against multiple threads changing
339 * desiredvnodes at the same time. Locking above only helps vnlru and
342 vfs_hash_changesize(desiredvnodes);
343 cache_changesize(desiredvnodes);
347 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
348 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
349 "LU", "Target for maximum number of vnodes");
352 sysctl_wantfreevnodes(SYSCTL_HANDLER_ARGS)
357 val = wantfreevnodes;
358 error = sysctl_handle_long(oidp, &val, 0, req);
359 if (error != 0 || req->newptr == NULL)
362 if (val == wantfreevnodes)
364 mtx_lock(&vnode_list_mtx);
365 wantfreevnodes = val;
367 mtx_unlock(&vnode_list_mtx);
371 SYSCTL_PROC(_vfs, OID_AUTO, wantfreevnodes,
372 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
373 "LU", "Target for minimum number of \"free\" vnodes");
375 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
376 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
377 static int vnlru_nowhere;
378 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
379 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
382 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
387 unsigned long ndflags;
390 if (req->newptr == NULL)
392 if (req->newlen >= PATH_MAX)
395 buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
396 error = SYSCTL_IN(req, buf, req->newlen);
400 buf[req->newlen] = '\0';
402 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | SAVENAME;
403 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
404 if ((error = namei(&nd)) != 0)
408 if (VN_IS_DOOMED(vp)) {
410 * This vnode is being recycled. Return != 0 to let the caller
411 * know that the sysctl had no effect. Return EAGAIN because a
412 * subsequent call will likely succeed (since namei will create
413 * a new vnode if necessary)
419 counter_u64_add(recycles_count, 1);
429 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
431 struct thread *td = curthread;
437 if (req->newptr == NULL)
440 error = sysctl_handle_int(oidp, &fd, 0, req);
443 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
448 error = vn_lock(vp, LK_EXCLUSIVE);
452 counter_u64_add(recycles_count, 1);
460 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
461 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
462 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
463 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
464 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
465 sysctl_ftry_reclaim_vnode, "I",
466 "Try to reclaim a vnode by its file descriptor");
468 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
472 * Support for the bufobj clean & dirty pctrie.
475 buf_trie_alloc(struct pctrie *ptree)
477 return (uma_zalloc_smr(buf_trie_zone, M_NOWAIT));
481 buf_trie_free(struct pctrie *ptree, void *node)
483 uma_zfree_smr(buf_trie_zone, node);
485 PCTRIE_DEFINE_SMR(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free,
489 * Initialize the vnode management data structures.
491 * Reevaluate the following cap on the number of vnodes after the physical
492 * memory size exceeds 512GB. In the limit, as the physical memory size
493 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
495 #ifndef MAXVNODES_MAX
496 #define MAXVNODES_MAX (512UL * 1024 * 1024 / 64) /* 8M */
499 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
501 static struct vnode *
502 vn_alloc_marker(struct mount *mp)
506 vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
507 vp->v_type = VMARKER;
514 vn_free_marker(struct vnode *vp)
517 MPASS(vp->v_type == VMARKER);
518 free(vp, M_VNODE_MARKER);
523 vnode_ctor(void *mem, int size, void *arg __unused, int flags __unused)
525 kasan_mark(mem, size, roundup2(size, UMA_ALIGN_PTR + 1), 0);
530 vnode_dtor(void *mem, int size, void *arg __unused)
532 size_t end1, end2, off1, off2;
534 _Static_assert(offsetof(struct vnode, v_vnodelist) <
535 offsetof(struct vnode, v_dbatchcpu),
536 "KASAN marks require updating");
538 off1 = offsetof(struct vnode, v_vnodelist);
539 off2 = offsetof(struct vnode, v_dbatchcpu);
540 end1 = off1 + sizeof(((struct vnode *)NULL)->v_vnodelist);
541 end2 = off2 + sizeof(((struct vnode *)NULL)->v_dbatchcpu);
544 * Access to the v_vnodelist and v_dbatchcpu fields are permitted even
545 * after the vnode has been freed. Try to get some KASAN coverage by
546 * marking everything except those two fields as invalid. Because
547 * KASAN's tracking is not byte-granular, any preceding fields sharing
548 * the same 8-byte aligned word must also be marked valid.
551 /* Handle the area from the start until v_vnodelist... */
552 off1 = rounddown2(off1, KASAN_SHADOW_SCALE);
553 kasan_mark(mem, off1, off1, KASAN_UMA_FREED);
555 /* ... then the area between v_vnodelist and v_dbatchcpu ... */
556 off1 = roundup2(end1, KASAN_SHADOW_SCALE);
557 off2 = rounddown2(off2, KASAN_SHADOW_SCALE);
559 kasan_mark((void *)((char *)mem + off1), off2 - off1,
560 off2 - off1, KASAN_UMA_FREED);
562 /* ... and finally the area from v_dbatchcpu to the end. */
563 off2 = roundup2(end2, KASAN_SHADOW_SCALE);
564 kasan_mark((void *)((char *)mem + off2), size - off2, size - off2,
570 * Initialize a vnode as it first enters the zone.
573 vnode_init(void *mem, int size, int flags)
582 vp->v_vnlock = &vp->v_lock;
583 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
585 * By default, don't allow shared locks unless filesystems opt-in.
587 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
588 LK_NOSHARE | LK_IS_VNODE);
592 bufobj_init(&vp->v_bufobj, vp);
594 * Initialize namecache.
596 cache_vnode_init(vp);
598 * Initialize rangelocks.
600 rangelock_init(&vp->v_rl);
602 vp->v_dbatchcpu = NOCPU;
605 * Check vhold_recycle_free for an explanation.
607 vp->v_holdcnt = VHOLD_NO_SMR;
609 mtx_lock(&vnode_list_mtx);
610 TAILQ_INSERT_BEFORE(vnode_list_free_marker, vp, v_vnodelist);
611 mtx_unlock(&vnode_list_mtx);
616 * Free a vnode when it is cleared from the zone.
619 vnode_fini(void *mem, int size)
626 mtx_lock(&vnode_list_mtx);
627 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
628 mtx_unlock(&vnode_list_mtx);
629 rangelock_destroy(&vp->v_rl);
630 lockdestroy(vp->v_vnlock);
631 mtx_destroy(&vp->v_interlock);
633 rw_destroy(BO_LOCKPTR(bo));
635 kasan_mark(mem, size, size, 0);
639 * Provide the size of NFS nclnode and NFS fh for calculation of the
640 * vnode memory consumption. The size is specified directly to
641 * eliminate dependency on NFS-private header.
643 * Other filesystems may use bigger or smaller (like UFS and ZFS)
644 * private inode data, but the NFS-based estimation is ample enough.
645 * Still, we care about differences in the size between 64- and 32-bit
648 * Namecache structure size is heuristically
649 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
652 #define NFS_NCLNODE_SZ (528 + 64)
655 #define NFS_NCLNODE_SZ (360 + 32)
660 vntblinit(void *dummy __unused)
665 int cpu, physvnodes, virtvnodes;
669 * Desiredvnodes is a function of the physical memory size and the
670 * kernel's heap size. Generally speaking, it scales with the
671 * physical memory size. The ratio of desiredvnodes to the physical
672 * memory size is 1:16 until desiredvnodes exceeds 98,304.
674 * marginal ratio of desiredvnodes to the physical memory size is
675 * 1:64. However, desiredvnodes is limited by the kernel's heap
676 * size. The memory required by desiredvnodes vnodes and vm objects
677 * must not exceed 1/10th of the kernel's heap size.
679 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
680 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
681 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
682 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
683 desiredvnodes = min(physvnodes, virtvnodes);
684 if (desiredvnodes > MAXVNODES_MAX) {
686 printf("Reducing kern.maxvnodes %lu -> %lu\n",
687 desiredvnodes, MAXVNODES_MAX);
688 desiredvnodes = MAXVNODES_MAX;
690 wantfreevnodes = desiredvnodes / 4;
691 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
692 TAILQ_INIT(&vnode_list);
693 mtx_init(&vnode_list_mtx, "vnode_list", NULL, MTX_DEF);
695 * The lock is taken to appease WITNESS.
697 mtx_lock(&vnode_list_mtx);
699 mtx_unlock(&vnode_list_mtx);
700 vnode_list_free_marker = vn_alloc_marker(NULL);
701 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_free_marker, v_vnodelist);
702 vnode_list_reclaim_marker = vn_alloc_marker(NULL);
703 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_reclaim_marker, v_vnodelist);
712 vnode_zone = uma_zcreate("VNODE", sizeof(struct vnode), ctor, dtor,
713 vnode_init, vnode_fini, UMA_ALIGN_PTR, UMA_ZONE_NOKASAN);
714 uma_zone_set_smr(vnode_zone, vfs_smr);
717 * Preallocate enough nodes to support one-per buf so that
718 * we can not fail an insert. reassignbuf() callers can not
719 * tolerate the insertion failure.
721 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
722 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
723 UMA_ZONE_NOFREE | UMA_ZONE_SMR);
724 buf_trie_smr = uma_zone_get_smr(buf_trie_zone);
725 uma_prealloc(buf_trie_zone, nbuf);
727 vnodes_created = counter_u64_alloc(M_WAITOK);
728 recycles_count = counter_u64_alloc(M_WAITOK);
729 recycles_free_count = counter_u64_alloc(M_WAITOK);
730 deferred_inact = counter_u64_alloc(M_WAITOK);
733 * Initialize the filesystem syncer.
735 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
737 syncer_maxdelay = syncer_mask + 1;
738 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
739 cv_init(&sync_wakeup, "syncer");
740 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
745 vd = DPCPU_ID_PTR((cpu), vd);
746 bzero(vd, sizeof(*vd));
747 mtx_init(&vd->lock, "vdbatch", NULL, MTX_DEF);
750 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
753 * Mark a mount point as busy. Used to synchronize access and to delay
754 * unmounting. Eventually, mountlist_mtx is not released on failure.
756 * vfs_busy() is a custom lock, it can block the caller.
757 * vfs_busy() only sleeps if the unmount is active on the mount point.
758 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
759 * vnode belonging to mp.
761 * Lookup uses vfs_busy() to traverse mount points.
763 * / vnode lock A / vnode lock (/var) D
764 * /var vnode lock B /log vnode lock(/var/log) E
765 * vfs_busy lock C vfs_busy lock F
767 * Within each file system, the lock order is C->A->B and F->D->E.
769 * When traversing across mounts, the system follows that lock order:
775 * The lookup() process for namei("/var") illustrates the process:
776 * VOP_LOOKUP() obtains B while A is held
777 * vfs_busy() obtains a shared lock on F while A and B are held
778 * vput() releases lock on B
779 * vput() releases lock on A
780 * VFS_ROOT() obtains lock on D while shared lock on F is held
781 * vfs_unbusy() releases shared lock on F
782 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
783 * Attempt to lock A (instead of vp_crossmp) while D is held would
784 * violate the global order, causing deadlocks.
786 * dounmount() locks B while F is drained.
789 vfs_busy(struct mount *mp, int flags)
791 struct mount_pcpu *mpcpu;
793 MPASS((flags & ~MBF_MASK) == 0);
794 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
796 if (vfs_op_thread_enter(mp, mpcpu)) {
797 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
798 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
799 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
800 vfs_mp_count_add_pcpu(mpcpu, ref, 1);
801 vfs_mp_count_add_pcpu(mpcpu, lockref, 1);
802 vfs_op_thread_exit(mp, mpcpu);
803 if (flags & MBF_MNTLSTLOCK)
804 mtx_unlock(&mountlist_mtx);
809 vfs_assert_mount_counters(mp);
812 * If mount point is currently being unmounted, sleep until the
813 * mount point fate is decided. If thread doing the unmounting fails,
814 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
815 * that this mount point has survived the unmount attempt and vfs_busy
816 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
817 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
818 * about to be really destroyed. vfs_busy needs to release its
819 * reference on the mount point in this case and return with ENOENT,
820 * telling the caller that mount mount it tried to busy is no longer
823 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
824 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
827 CTR1(KTR_VFS, "%s: failed busying before sleeping",
831 if (flags & MBF_MNTLSTLOCK)
832 mtx_unlock(&mountlist_mtx);
833 mp->mnt_kern_flag |= MNTK_MWAIT;
834 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
835 if (flags & MBF_MNTLSTLOCK)
836 mtx_lock(&mountlist_mtx);
839 if (flags & MBF_MNTLSTLOCK)
840 mtx_unlock(&mountlist_mtx);
847 * Free a busy filesystem.
850 vfs_unbusy(struct mount *mp)
852 struct mount_pcpu *mpcpu;
855 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
857 if (vfs_op_thread_enter(mp, mpcpu)) {
858 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
859 vfs_mp_count_sub_pcpu(mpcpu, lockref, 1);
860 vfs_mp_count_sub_pcpu(mpcpu, ref, 1);
861 vfs_op_thread_exit(mp, mpcpu);
866 vfs_assert_mount_counters(mp);
868 c = --mp->mnt_lockref;
869 if (mp->mnt_vfs_ops == 0) {
870 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
875 vfs_dump_mount_counters(mp);
876 if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
877 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
878 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
879 mp->mnt_kern_flag &= ~MNTK_DRAINING;
880 wakeup(&mp->mnt_lockref);
886 * Lookup a mount point by filesystem identifier.
889 vfs_getvfs(fsid_t *fsid)
893 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
894 mtx_lock(&mountlist_mtx);
895 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
896 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
898 mtx_unlock(&mountlist_mtx);
902 mtx_unlock(&mountlist_mtx);
903 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
904 return ((struct mount *) 0);
908 * Lookup a mount point by filesystem identifier, busying it before
911 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
912 * cache for popular filesystem identifiers. The cache is lockess, using
913 * the fact that struct mount's are never freed. In worst case we may
914 * get pointer to unmounted or even different filesystem, so we have to
915 * check what we got, and go slow way if so.
918 vfs_busyfs(fsid_t *fsid)
920 #define FSID_CACHE_SIZE 256
921 typedef struct mount * volatile vmp_t;
922 static vmp_t cache[FSID_CACHE_SIZE];
927 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
928 hash = fsid->val[0] ^ fsid->val[1];
929 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
931 if (mp == NULL || fsidcmp(&mp->mnt_stat.f_fsid, fsid) != 0)
933 if (vfs_busy(mp, 0) != 0) {
937 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0)
943 mtx_lock(&mountlist_mtx);
944 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
945 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
946 error = vfs_busy(mp, MBF_MNTLSTLOCK);
949 mtx_unlock(&mountlist_mtx);
956 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
957 mtx_unlock(&mountlist_mtx);
958 return ((struct mount *) 0);
962 * Check if a user can access privileged mount options.
965 vfs_suser(struct mount *mp, struct thread *td)
969 if (jailed(td->td_ucred)) {
971 * If the jail of the calling thread lacks permission for
972 * this type of file system, deny immediately.
974 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
978 * If the file system was mounted outside the jail of the
979 * calling thread, deny immediately.
981 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
986 * If file system supports delegated administration, we don't check
987 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
988 * by the file system itself.
989 * If this is not the user that did original mount, we check for
990 * the PRIV_VFS_MOUNT_OWNER privilege.
992 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
993 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
994 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
1001 * Get a new unique fsid. Try to make its val[0] unique, since this value
1002 * will be used to create fake device numbers for stat(). Also try (but
1003 * not so hard) make its val[0] unique mod 2^16, since some emulators only
1004 * support 16-bit device numbers. We end up with unique val[0]'s for the
1005 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
1007 * Keep in mind that several mounts may be running in parallel. Starting
1008 * the search one past where the previous search terminated is both a
1009 * micro-optimization and a defense against returning the same fsid to
1013 vfs_getnewfsid(struct mount *mp)
1015 static uint16_t mntid_base;
1020 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
1021 mtx_lock(&mntid_mtx);
1022 mtype = mp->mnt_vfc->vfc_typenum;
1023 tfsid.val[1] = mtype;
1024 mtype = (mtype & 0xFF) << 24;
1026 tfsid.val[0] = makedev(255,
1027 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
1029 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
1033 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
1034 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
1035 mtx_unlock(&mntid_mtx);
1039 * Knob to control the precision of file timestamps:
1041 * 0 = seconds only; nanoseconds zeroed.
1042 * 1 = seconds and nanoseconds, accurate within 1/HZ.
1043 * 2 = seconds and nanoseconds, truncated to microseconds.
1044 * >=3 = seconds and nanoseconds, maximum precision.
1046 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
1048 static int timestamp_precision = TSP_USEC;
1049 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
1050 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
1051 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
1052 "3+: sec + ns (max. precision))");
1055 * Get a current timestamp.
1058 vfs_timestamp(struct timespec *tsp)
1062 switch (timestamp_precision) {
1064 tsp->tv_sec = time_second;
1072 TIMEVAL_TO_TIMESPEC(&tv, tsp);
1082 * Set vnode attributes to VNOVAL
1085 vattr_null(struct vattr *vap)
1088 vap->va_type = VNON;
1089 vap->va_size = VNOVAL;
1090 vap->va_bytes = VNOVAL;
1091 vap->va_mode = VNOVAL;
1092 vap->va_nlink = VNOVAL;
1093 vap->va_uid = VNOVAL;
1094 vap->va_gid = VNOVAL;
1095 vap->va_fsid = VNOVAL;
1096 vap->va_fileid = VNOVAL;
1097 vap->va_blocksize = VNOVAL;
1098 vap->va_rdev = VNOVAL;
1099 vap->va_atime.tv_sec = VNOVAL;
1100 vap->va_atime.tv_nsec = VNOVAL;
1101 vap->va_mtime.tv_sec = VNOVAL;
1102 vap->va_mtime.tv_nsec = VNOVAL;
1103 vap->va_ctime.tv_sec = VNOVAL;
1104 vap->va_ctime.tv_nsec = VNOVAL;
1105 vap->va_birthtime.tv_sec = VNOVAL;
1106 vap->va_birthtime.tv_nsec = VNOVAL;
1107 vap->va_flags = VNOVAL;
1108 vap->va_gen = VNOVAL;
1109 vap->va_vaflags = 0;
1113 * Try to reduce the total number of vnodes.
1115 * This routine (and its user) are buggy in at least the following ways:
1116 * - all parameters were picked years ago when RAM sizes were significantly
1118 * - it can pick vnodes based on pages used by the vm object, but filesystems
1119 * like ZFS don't use it making the pick broken
1120 * - since ZFS has its own aging policy it gets partially combated by this one
1121 * - a dedicated method should be provided for filesystems to let them decide
1122 * whether the vnode should be recycled
1124 * This routine is called when we have too many vnodes. It attempts
1125 * to free <count> vnodes and will potentially free vnodes that still
1126 * have VM backing store (VM backing store is typically the cause
1127 * of a vnode blowout so we want to do this). Therefore, this operation
1128 * is not considered cheap.
1130 * A number of conditions may prevent a vnode from being reclaimed.
1131 * the buffer cache may have references on the vnode, a directory
1132 * vnode may still have references due to the namei cache representing
1133 * underlying files, or the vnode may be in active use. It is not
1134 * desirable to reuse such vnodes. These conditions may cause the
1135 * number of vnodes to reach some minimum value regardless of what
1136 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
1138 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1139 * entries if this argument is strue
1140 * @param trigger Only reclaim vnodes with fewer than this many resident
1142 * @param target How many vnodes to reclaim.
1143 * @return The number of vnodes that were reclaimed.
1146 vlrureclaim(bool reclaim_nc_src, int trigger, u_long target)
1148 struct vnode *vp, *mvp;
1150 struct vm_object *object;
1154 mtx_assert(&vnode_list_mtx, MA_OWNED);
1159 mvp = vnode_list_reclaim_marker;
1162 while (done < target) {
1163 vp = TAILQ_NEXT(vp, v_vnodelist);
1164 if (__predict_false(vp == NULL))
1167 if (__predict_false(vp->v_type == VMARKER))
1171 * If it's been deconstructed already, it's still
1172 * referenced, or it exceeds the trigger, skip it.
1173 * Also skip free vnodes. We are trying to make space
1174 * to expand the free list, not reduce it.
1176 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1177 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)))
1180 if (vp->v_type == VBAD || vp->v_type == VNON)
1183 object = atomic_load_ptr(&vp->v_object);
1184 if (object == NULL || object->resident_page_count > trigger) {
1189 * Handle races against vnode allocation. Filesystems lock the
1190 * vnode some time after it gets returned from getnewvnode,
1191 * despite type and hold count being manipulated earlier.
1192 * Resorting to checking v_mount restores guarantees present
1193 * before the global list was reworked to contain all vnodes.
1195 if (!VI_TRYLOCK(vp))
1197 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1201 if (vp->v_mount == NULL) {
1207 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1208 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1209 mtx_unlock(&vnode_list_mtx);
1211 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1213 goto next_iter_unlocked;
1215 if (VOP_LOCK(vp, LK_EXCLUSIVE|LK_NOWAIT) != 0) {
1217 vn_finished_write(mp);
1218 goto next_iter_unlocked;
1222 if (vp->v_usecount > 0 ||
1223 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1224 (vp->v_object != NULL && vp->v_object->handle == vp &&
1225 vp->v_object->resident_page_count > trigger)) {
1228 vn_finished_write(mp);
1229 goto next_iter_unlocked;
1231 counter_u64_add(recycles_count, 1);
1235 vn_finished_write(mp);
1239 mtx_lock(&vnode_list_mtx);
1242 MPASS(vp->v_type != VMARKER);
1243 if (!should_yield())
1245 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1246 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1247 mtx_unlock(&vnode_list_mtx);
1248 kern_yield(PRI_USER);
1249 mtx_lock(&vnode_list_mtx);
1252 if (done == 0 && !retried) {
1253 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1254 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1261 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1262 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1264 "limit on vnode free requests per call to the vnlru_free routine");
1267 * Attempt to reduce the free list by the requested amount.
1270 vnlru_free_impl(int count, struct vfsops *mnt_op, struct vnode *mvp)
1276 mtx_assert(&vnode_list_mtx, MA_OWNED);
1277 if (count > max_vnlru_free)
1278 count = max_vnlru_free;
1285 vp = TAILQ_NEXT(vp, v_vnodelist);
1286 if (__predict_false(vp == NULL)) {
1287 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1288 TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1291 if (__predict_false(vp->v_type == VMARKER))
1293 if (vp->v_holdcnt > 0)
1296 * Don't recycle if our vnode is from different type
1297 * of mount point. Note that mp is type-safe, the
1298 * check does not reach unmapped address even if
1299 * vnode is reclaimed.
1301 if (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1302 mp->mnt_op != mnt_op) {
1305 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1308 if (!vhold_recycle_free(vp))
1310 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1311 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1312 mtx_unlock(&vnode_list_mtx);
1314 * FIXME: ignores the return value, meaning it may be nothing
1315 * got recycled but it claims otherwise to the caller.
1317 * Originally the value started being ignored in 2005 with
1318 * 114a1006a8204aa156e1f9ad6476cdff89cada7f .
1320 * Respecting the value can run into significant stalls if most
1321 * vnodes belong to one file system and it has writes
1322 * suspended. In presence of many threads and millions of
1323 * vnodes they keep contending on the vnode_list_mtx lock only
1324 * to find vnodes they can't recycle.
1326 * The solution would be to pre-check if the vnode is likely to
1327 * be recycle-able, but it needs to happen with the
1328 * vnode_list_mtx lock held. This runs into a problem where
1329 * VOP_GETWRITEMOUNT (currently needed to find out about if
1330 * writes are frozen) can take locks which LOR against it.
1332 * Check nullfs for one example (null_getwritemount).
1336 mtx_lock(&vnode_list_mtx);
1339 return (ocount - count);
1343 vnlru_free_locked(int count)
1346 mtx_assert(&vnode_list_mtx, MA_OWNED);
1347 return (vnlru_free_impl(count, NULL, vnode_list_free_marker));
1351 vnlru_free_vfsops(int count, struct vfsops *mnt_op, struct vnode *mvp)
1354 MPASS(mnt_op != NULL);
1356 VNPASS(mvp->v_type == VMARKER, mvp);
1357 mtx_lock(&vnode_list_mtx);
1358 vnlru_free_impl(count, mnt_op, mvp);
1359 mtx_unlock(&vnode_list_mtx);
1363 * Temporary binary compat, don't use. Call vnlru_free_vfsops instead.
1366 vnlru_free(int count, struct vfsops *mnt_op)
1372 mtx_lock(&vnode_list_mtx);
1373 mvp = vnode_list_free_marker;
1374 if (vnlru_free_impl(count, mnt_op, mvp) == 0) {
1376 * It is possible the marker was moved over eligible vnodes by
1377 * callers which filtered by different ops. If so, start from
1380 if (vnlru_read_freevnodes() > 0) {
1381 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1382 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1384 vnlru_free_impl(count, mnt_op, mvp);
1386 mtx_unlock(&vnode_list_mtx);
1390 vnlru_alloc_marker(void)
1394 mvp = vn_alloc_marker(NULL);
1395 mtx_lock(&vnode_list_mtx);
1396 TAILQ_INSERT_BEFORE(vnode_list_free_marker, mvp, v_vnodelist);
1397 mtx_unlock(&vnode_list_mtx);
1402 vnlru_free_marker(struct vnode *mvp)
1404 mtx_lock(&vnode_list_mtx);
1405 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1406 mtx_unlock(&vnode_list_mtx);
1407 vn_free_marker(mvp);
1414 mtx_assert(&vnode_list_mtx, MA_OWNED);
1415 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1416 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1417 vlowat = vhiwat / 2;
1421 * Attempt to recycle vnodes in a context that is always safe to block.
1422 * Calling vlrurecycle() from the bowels of filesystem code has some
1423 * interesting deadlock problems.
1425 static struct proc *vnlruproc;
1426 static int vnlruproc_sig;
1429 * The main freevnodes counter is only updated when threads requeue their vnode
1430 * batches. CPUs are conditionally walked to compute a more accurate total.
1432 * Limit how much of a slop are we willing to tolerate. Note: the actual value
1433 * at any given moment can still exceed slop, but it should not be by significant
1434 * margin in practice.
1436 #define VNLRU_FREEVNODES_SLOP 128
1438 static __inline void
1439 vfs_freevnodes_inc(void)
1449 static __inline void
1450 vfs_freevnodes_dec(void)
1461 vnlru_read_freevnodes(void)
1467 mtx_assert(&vnode_list_mtx, MA_OWNED);
1468 if (freevnodes > freevnodes_old)
1469 slop = freevnodes - freevnodes_old;
1471 slop = freevnodes_old - freevnodes;
1472 if (slop < VNLRU_FREEVNODES_SLOP)
1473 return (freevnodes >= 0 ? freevnodes : 0);
1474 freevnodes_old = freevnodes;
1476 vd = DPCPU_ID_PTR((cpu), vd);
1477 freevnodes_old += vd->freevnodes;
1479 return (freevnodes_old >= 0 ? freevnodes_old : 0);
1483 vnlru_under(u_long rnumvnodes, u_long limit)
1485 u_long rfreevnodes, space;
1487 if (__predict_false(rnumvnodes > desiredvnodes))
1490 space = desiredvnodes - rnumvnodes;
1491 if (space < limit) {
1492 rfreevnodes = vnlru_read_freevnodes();
1493 if (rfreevnodes > wantfreevnodes)
1494 space += rfreevnodes - wantfreevnodes;
1496 return (space < limit);
1500 vnlru_under_unlocked(u_long rnumvnodes, u_long limit)
1502 long rfreevnodes, space;
1504 if (__predict_false(rnumvnodes > desiredvnodes))
1507 space = desiredvnodes - rnumvnodes;
1508 if (space < limit) {
1509 rfreevnodes = atomic_load_long(&freevnodes);
1510 if (rfreevnodes > wantfreevnodes)
1511 space += rfreevnodes - wantfreevnodes;
1513 return (space < limit);
1520 mtx_assert(&vnode_list_mtx, MA_OWNED);
1521 if (vnlruproc_sig == 0) {
1530 u_long rnumvnodes, rfreevnodes, target;
1531 unsigned long onumvnodes;
1532 int done, force, trigger, usevnodes;
1533 bool reclaim_nc_src, want_reread;
1535 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1536 SHUTDOWN_PRI_FIRST);
1539 want_reread = false;
1541 kproc_suspend_check(vnlruproc);
1542 mtx_lock(&vnode_list_mtx);
1543 rnumvnodes = atomic_load_long(&numvnodes);
1546 force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1547 want_reread = false;
1551 * If numvnodes is too large (due to desiredvnodes being
1552 * adjusted using its sysctl, or emergency growth), first
1553 * try to reduce it by discarding from the free list.
1555 if (rnumvnodes > desiredvnodes) {
1556 vnlru_free_locked(rnumvnodes - desiredvnodes);
1557 rnumvnodes = atomic_load_long(&numvnodes);
1560 * Sleep if the vnode cache is in a good state. This is
1561 * when it is not over-full and has space for about a 4%
1562 * or 9% expansion (by growing its size or inexcessively
1563 * reducing its free list). Otherwise, try to reclaim
1564 * space for a 10% expansion.
1566 if (vstir && force == 0) {
1570 if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1572 wakeup(&vnlruproc_sig);
1573 msleep(vnlruproc, &vnode_list_mtx,
1574 PVFS|PDROP, "vlruwt", hz);
1577 rfreevnodes = vnlru_read_freevnodes();
1579 onumvnodes = rnumvnodes;
1581 * Calculate parameters for recycling. These are the same
1582 * throughout the loop to give some semblance of fairness.
1583 * The trigger point is to avoid recycling vnodes with lots
1584 * of resident pages. We aren't trying to free memory; we
1585 * are trying to recycle or at least free vnodes.
1587 if (rnumvnodes <= desiredvnodes)
1588 usevnodes = rnumvnodes - rfreevnodes;
1590 usevnodes = rnumvnodes;
1594 * The trigger value is chosen to give a conservatively
1595 * large value to ensure that it alone doesn't prevent
1596 * making progress. The value can easily be so large that
1597 * it is effectively infinite in some congested and
1598 * misconfigured cases, and this is necessary. Normally
1599 * it is about 8 to 100 (pages), which is quite large.
1601 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1603 trigger = vsmalltrigger;
1604 reclaim_nc_src = force >= 3;
1605 target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1606 target = target / 10 + 1;
1607 done = vlrureclaim(reclaim_nc_src, trigger, target);
1608 mtx_unlock(&vnode_list_mtx);
1609 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1610 uma_reclaim(UMA_RECLAIM_DRAIN);
1612 if (force == 0 || force == 1) {
1623 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1626 kern_yield(PRI_USER);
1631 static struct kproc_desc vnlru_kp = {
1636 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1640 * Routines having to do with the management of the vnode table.
1644 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1645 * before we actually vgone(). This function must be called with the vnode
1646 * held to prevent the vnode from being returned to the free list midway
1650 vtryrecycle(struct vnode *vp)
1654 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1655 VNASSERT(vp->v_holdcnt, vp,
1656 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1658 * This vnode may found and locked via some other list, if so we
1659 * can't recycle it yet.
1661 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1663 "%s: impossible to recycle, vp %p lock is already held",
1666 return (EWOULDBLOCK);
1669 * Don't recycle if its filesystem is being suspended.
1671 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1674 "%s: impossible to recycle, cannot start the write for %p",
1680 * If we got this far, we need to acquire the interlock and see if
1681 * anyone picked up this vnode from another list. If not, we will
1682 * mark it with DOOMED via vgonel() so that anyone who does find it
1683 * will skip over it.
1686 if (vp->v_usecount) {
1689 vn_finished_write(vnmp);
1691 "%s: impossible to recycle, %p is already referenced",
1695 if (!VN_IS_DOOMED(vp)) {
1696 counter_u64_add(recycles_free_count, 1);
1701 vn_finished_write(vnmp);
1706 * Allocate a new vnode.
1708 * The operation never returns an error. Returning an error was disabled
1709 * in r145385 (dated 2005) with the following comment:
1711 * XXX Not all VFS_VGET/ffs_vget callers check returns.
1713 * Given the age of this commit (almost 15 years at the time of writing this
1714 * comment) restoring the ability to fail requires a significant audit of
1717 * The routine can try to free a vnode or stall for up to 1 second waiting for
1718 * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1720 static u_long vn_alloc_cyclecount;
1722 static struct vnode * __noinline
1723 vn_alloc_hard(struct mount *mp)
1725 u_long rnumvnodes, rfreevnodes;
1727 mtx_lock(&vnode_list_mtx);
1728 rnumvnodes = atomic_load_long(&numvnodes);
1729 if (rnumvnodes + 1 < desiredvnodes) {
1730 vn_alloc_cyclecount = 0;
1733 rfreevnodes = vnlru_read_freevnodes();
1734 if (vn_alloc_cyclecount++ >= rfreevnodes) {
1735 vn_alloc_cyclecount = 0;
1739 * Grow the vnode cache if it will not be above its target max
1740 * after growing. Otherwise, if the free list is nonempty, try
1741 * to reclaim 1 item from it before growing the cache (possibly
1742 * above its target max if the reclamation failed or is delayed).
1743 * Otherwise, wait for some space. In all cases, schedule
1744 * vnlru_proc() if we are getting short of space. The watermarks
1745 * should be chosen so that we never wait or even reclaim from
1746 * the free list to below its target minimum.
1748 if (vnlru_free_locked(1) > 0)
1750 if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1752 * Wait for space for a new vnode.
1755 msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1756 if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1757 vnlru_read_freevnodes() > 1)
1758 vnlru_free_locked(1);
1761 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1762 if (vnlru_under(rnumvnodes, vlowat))
1764 mtx_unlock(&vnode_list_mtx);
1765 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1768 static struct vnode *
1769 vn_alloc(struct mount *mp)
1773 if (__predict_false(vn_alloc_cyclecount != 0))
1774 return (vn_alloc_hard(mp));
1775 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1776 if (__predict_false(vnlru_under_unlocked(rnumvnodes, vlowat))) {
1777 atomic_subtract_long(&numvnodes, 1);
1778 return (vn_alloc_hard(mp));
1781 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1785 vn_free(struct vnode *vp)
1788 atomic_subtract_long(&numvnodes, 1);
1789 uma_zfree_smr(vnode_zone, vp);
1793 * Return the next vnode from the free list.
1796 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1801 struct lock_object *lo;
1803 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1805 KASSERT(vops->registered,
1806 ("%s: not registered vector op %p\n", __func__, vops));
1809 if (td->td_vp_reserved != NULL) {
1810 vp = td->td_vp_reserved;
1811 td->td_vp_reserved = NULL;
1815 counter_u64_add(vnodes_created, 1);
1817 * Locks are given the generic name "vnode" when created.
1818 * Follow the historic practice of using the filesystem
1819 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1821 * Locks live in a witness group keyed on their name. Thus,
1822 * when a lock is renamed, it must also move from the witness
1823 * group of its old name to the witness group of its new name.
1825 * The change only needs to be made when the vnode moves
1826 * from one filesystem type to another. We ensure that each
1827 * filesystem use a single static name pointer for its tag so
1828 * that we can compare pointers rather than doing a strcmp().
1830 lo = &vp->v_vnlock->lock_object;
1832 if (lo->lo_name != tag) {
1836 WITNESS_DESTROY(lo);
1837 WITNESS_INIT(lo, tag);
1841 * By default, don't allow shared locks unless filesystems opt-in.
1843 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1845 * Finalize various vnode identity bits.
1847 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1848 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1849 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1853 v_init_counters(vp);
1855 vp->v_bufobj.bo_ops = &buf_ops_bio;
1857 if (mp == NULL && vops != &dead_vnodeops)
1858 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1862 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1863 mac_vnode_associate_singlelabel(mp, vp);
1866 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1867 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1868 vp->v_vflag |= VV_NOKNOTE;
1872 * For the filesystems which do not use vfs_hash_insert(),
1873 * still initialize v_hash to have vfs_hash_index() useful.
1874 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1877 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1884 getnewvnode_reserve(void)
1889 MPASS(td->td_vp_reserved == NULL);
1890 td->td_vp_reserved = vn_alloc(NULL);
1894 getnewvnode_drop_reserve(void)
1899 if (td->td_vp_reserved != NULL) {
1900 vn_free(td->td_vp_reserved);
1901 td->td_vp_reserved = NULL;
1905 static void __noinline
1906 freevnode(struct vnode *vp)
1911 * The vnode has been marked for destruction, so free it.
1913 * The vnode will be returned to the zone where it will
1914 * normally remain until it is needed for another vnode. We
1915 * need to cleanup (or verify that the cleanup has already
1916 * been done) any residual data left from its current use
1917 * so as not to contaminate the freshly allocated vnode.
1919 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1921 * Paired with vgone.
1923 vn_seqc_write_end_free(vp);
1926 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1927 VNPASS(vp->v_holdcnt == VHOLD_NO_SMR, vp);
1928 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1929 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1930 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1931 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1932 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1933 ("clean blk trie not empty"));
1934 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1935 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1936 ("dirty blk trie not empty"));
1937 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1938 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1939 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1940 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1941 ("Dangling rangelock waiters"));
1942 VNASSERT((vp->v_iflag & (VI_DOINGINACT | VI_OWEINACT)) == 0, vp,
1943 ("Leaked inactivation"));
1946 mac_vnode_destroy(vp);
1948 if (vp->v_pollinfo != NULL) {
1949 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1950 destroy_vpollinfo(vp->v_pollinfo);
1952 vp->v_pollinfo = NULL;
1954 vp->v_mountedhere = NULL;
1957 vp->v_fifoinfo = NULL;
1958 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
1966 * Delete from old mount point vnode list, if on one.
1969 delmntque(struct vnode *vp)
1973 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
1982 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1983 ("bad mount point vnode list size"));
1984 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1985 mp->mnt_nvnodelistsize--;
1991 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1995 vp->v_op = &dead_vnodeops;
2001 * Insert into list of vnodes for the new mount point, if available.
2004 insmntque1(struct vnode *vp, struct mount *mp,
2005 void (*dtr)(struct vnode *, void *), void *dtr_arg)
2008 KASSERT(vp->v_mount == NULL,
2009 ("insmntque: vnode already on per mount vnode list"));
2010 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
2011 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
2014 * We acquire the vnode interlock early to ensure that the
2015 * vnode cannot be recycled by another process releasing a
2016 * holdcnt on it before we get it on both the vnode list
2017 * and the active vnode list. The mount mutex protects only
2018 * manipulation of the vnode list and the vnode freelist
2019 * mutex protects only manipulation of the active vnode list.
2020 * Hence the need to hold the vnode interlock throughout.
2024 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
2025 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
2026 mp->mnt_nvnodelistsize == 0)) &&
2027 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
2036 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
2037 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
2038 ("neg mount point vnode list size"));
2039 mp->mnt_nvnodelistsize++;
2046 insmntque(struct vnode *vp, struct mount *mp)
2049 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
2053 * Flush out and invalidate all buffers associated with a bufobj
2054 * Called with the underlying object locked.
2057 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
2062 if (flags & V_SAVE) {
2063 error = bufobj_wwait(bo, slpflag, slptimeo);
2068 if (bo->bo_dirty.bv_cnt > 0) {
2071 error = BO_SYNC(bo, MNT_WAIT);
2072 } while (error == ERELOOKUP);
2076 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0) {
2083 * If you alter this loop please notice that interlock is dropped and
2084 * reacquired in flushbuflist. Special care is needed to ensure that
2085 * no race conditions occur from this.
2088 error = flushbuflist(&bo->bo_clean,
2089 flags, bo, slpflag, slptimeo);
2090 if (error == 0 && !(flags & V_CLEANONLY))
2091 error = flushbuflist(&bo->bo_dirty,
2092 flags, bo, slpflag, slptimeo);
2093 if (error != 0 && error != EAGAIN) {
2097 } while (error != 0);
2100 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
2101 * have write I/O in-progress but if there is a VM object then the
2102 * VM object can also have read-I/O in-progress.
2105 bufobj_wwait(bo, 0, 0);
2106 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
2108 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
2111 } while (bo->bo_numoutput > 0);
2115 * Destroy the copy in the VM cache, too.
2117 if (bo->bo_object != NULL &&
2118 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
2119 VM_OBJECT_WLOCK(bo->bo_object);
2120 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
2121 OBJPR_CLEANONLY : 0);
2122 VM_OBJECT_WUNLOCK(bo->bo_object);
2127 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
2128 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
2129 bo->bo_clean.bv_cnt > 0))
2130 panic("vinvalbuf: flush failed");
2131 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
2132 bo->bo_dirty.bv_cnt > 0)
2133 panic("vinvalbuf: flush dirty failed");
2140 * Flush out and invalidate all buffers associated with a vnode.
2141 * Called with the underlying object locked.
2144 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
2147 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2148 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
2149 if (vp->v_object != NULL && vp->v_object->handle != vp)
2151 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
2155 * Flush out buffers on the specified list.
2159 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
2162 struct buf *bp, *nbp;
2167 ASSERT_BO_WLOCKED(bo);
2170 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2172 * If we are flushing both V_NORMAL and V_ALT buffers then
2173 * do not skip any buffers. If we are flushing only V_NORMAL
2174 * buffers then skip buffers marked as BX_ALTDATA. If we are
2175 * flushing only V_ALT buffers then skip buffers not marked
2178 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2179 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2180 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2184 lblkno = nbp->b_lblkno;
2185 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2188 error = BUF_TIMELOCK(bp,
2189 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2190 "flushbuf", slpflag, slptimeo);
2193 return (error != ENOLCK ? error : EAGAIN);
2195 KASSERT(bp->b_bufobj == bo,
2196 ("bp %p wrong b_bufobj %p should be %p",
2197 bp, bp->b_bufobj, bo));
2199 * XXX Since there are no node locks for NFS, I
2200 * believe there is a slight chance that a delayed
2201 * write will occur while sleeping just above, so
2204 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2207 bp->b_flags |= B_ASYNC;
2210 return (EAGAIN); /* XXX: why not loop ? */
2213 bp->b_flags |= (B_INVAL | B_RELBUF);
2214 bp->b_flags &= ~B_ASYNC;
2219 nbp = gbincore(bo, lblkno);
2220 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2222 break; /* nbp invalid */
2228 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2234 ASSERT_BO_LOCKED(bo);
2236 for (lblkno = startn;;) {
2238 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2239 if (bp == NULL || bp->b_lblkno >= endn ||
2240 bp->b_lblkno < startn)
2242 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2243 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2246 if (error == ENOLCK)
2250 KASSERT(bp->b_bufobj == bo,
2251 ("bp %p wrong b_bufobj %p should be %p",
2252 bp, bp->b_bufobj, bo));
2253 lblkno = bp->b_lblkno + 1;
2254 if ((bp->b_flags & B_MANAGED) == 0)
2256 bp->b_flags |= B_RELBUF;
2258 * In the VMIO case, use the B_NOREUSE flag to hint that the
2259 * pages backing each buffer in the range are unlikely to be
2260 * reused. Dirty buffers will have the hint applied once
2261 * they've been written.
2263 if ((bp->b_flags & B_VMIO) != 0)
2264 bp->b_flags |= B_NOREUSE;
2272 * Truncate a file's buffer and pages to a specified length. This
2273 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2277 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2279 struct buf *bp, *nbp;
2283 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2284 vp, blksize, (uintmax_t)length);
2287 * Round up to the *next* lbn.
2289 startlbn = howmany(length, blksize);
2291 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2297 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2302 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2303 if (bp->b_lblkno > 0)
2306 * Since we hold the vnode lock this should only
2307 * fail if we're racing with the buf daemon.
2310 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2311 BO_LOCKPTR(bo)) == ENOLCK)
2312 goto restart_unlocked;
2314 VNASSERT((bp->b_flags & B_DELWRI), vp,
2315 ("buf(%p) on dirty queue without DELWRI", bp));
2324 bufobj_wwait(bo, 0, 0);
2326 vnode_pager_setsize(vp, length);
2332 * Invalidate the cached pages of a file's buffer within the range of block
2333 * numbers [startlbn, endlbn).
2336 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2342 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2344 start = blksize * startlbn;
2345 end = blksize * endlbn;
2349 MPASS(blksize == bo->bo_bsize);
2351 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2355 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2359 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2360 daddr_t startlbn, daddr_t endlbn)
2362 struct buf *bp, *nbp;
2365 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2366 ASSERT_BO_LOCKED(bo);
2370 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2371 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2374 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2375 BO_LOCKPTR(bo)) == ENOLCK) {
2381 bp->b_flags |= B_INVAL | B_RELBUF;
2382 bp->b_flags &= ~B_ASYNC;
2388 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2390 (nbp->b_flags & B_DELWRI) != 0))
2394 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2395 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2398 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2399 BO_LOCKPTR(bo)) == ENOLCK) {
2404 bp->b_flags |= B_INVAL | B_RELBUF;
2405 bp->b_flags &= ~B_ASYNC;
2411 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2412 (nbp->b_vp != vp) ||
2413 (nbp->b_flags & B_DELWRI) == 0))
2421 buf_vlist_remove(struct buf *bp)
2426 flags = bp->b_xflags;
2428 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2429 ASSERT_BO_WLOCKED(bp->b_bufobj);
2430 KASSERT((flags & (BX_VNDIRTY | BX_VNCLEAN)) != 0 &&
2431 (flags & (BX_VNDIRTY | BX_VNCLEAN)) != (BX_VNDIRTY | BX_VNCLEAN),
2432 ("%s: buffer %p has invalid queue state", __func__, bp));
2434 if ((flags & BX_VNDIRTY) != 0)
2435 bv = &bp->b_bufobj->bo_dirty;
2437 bv = &bp->b_bufobj->bo_clean;
2438 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2439 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2441 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2445 * Add the buffer to the sorted clean or dirty block list.
2447 * NOTE: xflags is passed as a constant, optimizing this inline function!
2450 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2456 ASSERT_BO_WLOCKED(bo);
2457 KASSERT((bo->bo_flag & BO_NOBUFS) == 0,
2458 ("buf_vlist_add: bo %p does not allow bufs", bo));
2459 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2460 ("dead bo %p", bo));
2461 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2462 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2463 bp->b_xflags |= xflags;
2464 if (xflags & BX_VNDIRTY)
2470 * Keep the list ordered. Optimize empty list insertion. Assume
2471 * we tend to grow at the tail so lookup_le should usually be cheaper
2474 if (bv->bv_cnt == 0 ||
2475 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2476 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2477 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2478 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2480 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2481 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2483 panic("buf_vlist_add: Preallocated nodes insufficient.");
2488 * Look up a buffer using the buffer tries.
2491 gbincore(struct bufobj *bo, daddr_t lblkno)
2495 ASSERT_BO_LOCKED(bo);
2496 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2499 return (BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno));
2503 * Look up a buf using the buffer tries, without the bufobj lock. This relies
2504 * on SMR for safe lookup, and bufs being in a no-free zone to provide type
2505 * stability of the result. Like other lockless lookups, the found buf may
2506 * already be invalid by the time this function returns.
2509 gbincore_unlocked(struct bufobj *bo, daddr_t lblkno)
2513 ASSERT_BO_UNLOCKED(bo);
2514 bp = BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_clean.bv_root, lblkno);
2517 return (BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_dirty.bv_root, lblkno));
2521 * Associate a buffer with a vnode.
2524 bgetvp(struct vnode *vp, struct buf *bp)
2529 ASSERT_BO_WLOCKED(bo);
2530 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2532 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2533 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2534 ("bgetvp: bp already attached! %p", bp));
2540 * Insert onto list for new vnode.
2542 buf_vlist_add(bp, bo, BX_VNCLEAN);
2546 * Disassociate a buffer from a vnode.
2549 brelvp(struct buf *bp)
2554 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2555 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2558 * Delete from old vnode list, if on one.
2560 vp = bp->b_vp; /* XXX */
2563 buf_vlist_remove(bp);
2564 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2565 bo->bo_flag &= ~BO_ONWORKLST;
2566 mtx_lock(&sync_mtx);
2567 LIST_REMOVE(bo, bo_synclist);
2568 syncer_worklist_len--;
2569 mtx_unlock(&sync_mtx);
2572 bp->b_bufobj = NULL;
2578 * Add an item to the syncer work queue.
2581 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2585 ASSERT_BO_WLOCKED(bo);
2587 mtx_lock(&sync_mtx);
2588 if (bo->bo_flag & BO_ONWORKLST)
2589 LIST_REMOVE(bo, bo_synclist);
2591 bo->bo_flag |= BO_ONWORKLST;
2592 syncer_worklist_len++;
2595 if (delay > syncer_maxdelay - 2)
2596 delay = syncer_maxdelay - 2;
2597 slot = (syncer_delayno + delay) & syncer_mask;
2599 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2600 mtx_unlock(&sync_mtx);
2604 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2608 mtx_lock(&sync_mtx);
2609 len = syncer_worklist_len - sync_vnode_count;
2610 mtx_unlock(&sync_mtx);
2611 error = SYSCTL_OUT(req, &len, sizeof(len));
2615 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2616 CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2617 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2619 static struct proc *updateproc;
2620 static void sched_sync(void);
2621 static struct kproc_desc up_kp = {
2626 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2629 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2634 *bo = LIST_FIRST(slp);
2638 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2641 * We use vhold in case the vnode does not
2642 * successfully sync. vhold prevents the vnode from
2643 * going away when we unlock the sync_mtx so that
2644 * we can acquire the vnode interlock.
2647 mtx_unlock(&sync_mtx);
2649 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2651 mtx_lock(&sync_mtx);
2652 return (*bo == LIST_FIRST(slp));
2654 MPASSERT(mp == NULL || (curthread->td_pflags & TDP_IGNSUSP) != 0 ||
2655 (mp->mnt_kern_flag & MNTK_SUSPENDED) == 0, mp,
2656 ("suspended mp syncing vp %p", vp));
2657 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2658 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2660 vn_finished_write(mp);
2662 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2664 * Put us back on the worklist. The worklist
2665 * routine will remove us from our current
2666 * position and then add us back in at a later
2669 vn_syncer_add_to_worklist(*bo, syncdelay);
2673 mtx_lock(&sync_mtx);
2677 static int first_printf = 1;
2680 * System filesystem synchronizer daemon.
2685 struct synclist *next, *slp;
2688 struct thread *td = curthread;
2690 int net_worklist_len;
2691 int syncer_final_iter;
2695 syncer_final_iter = 0;
2696 syncer_state = SYNCER_RUNNING;
2697 starttime = time_uptime;
2698 td->td_pflags |= TDP_NORUNNINGBUF;
2700 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2703 mtx_lock(&sync_mtx);
2705 if (syncer_state == SYNCER_FINAL_DELAY &&
2706 syncer_final_iter == 0) {
2707 mtx_unlock(&sync_mtx);
2708 kproc_suspend_check(td->td_proc);
2709 mtx_lock(&sync_mtx);
2711 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2712 if (syncer_state != SYNCER_RUNNING &&
2713 starttime != time_uptime) {
2715 printf("\nSyncing disks, vnodes remaining... ");
2718 printf("%d ", net_worklist_len);
2720 starttime = time_uptime;
2723 * Push files whose dirty time has expired. Be careful
2724 * of interrupt race on slp queue.
2726 * Skip over empty worklist slots when shutting down.
2729 slp = &syncer_workitem_pending[syncer_delayno];
2730 syncer_delayno += 1;
2731 if (syncer_delayno == syncer_maxdelay)
2733 next = &syncer_workitem_pending[syncer_delayno];
2735 * If the worklist has wrapped since the
2736 * it was emptied of all but syncer vnodes,
2737 * switch to the FINAL_DELAY state and run
2738 * for one more second.
2740 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2741 net_worklist_len == 0 &&
2742 last_work_seen == syncer_delayno) {
2743 syncer_state = SYNCER_FINAL_DELAY;
2744 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2746 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2747 syncer_worklist_len > 0);
2750 * Keep track of the last time there was anything
2751 * on the worklist other than syncer vnodes.
2752 * Return to the SHUTTING_DOWN state if any
2755 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2756 last_work_seen = syncer_delayno;
2757 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2758 syncer_state = SYNCER_SHUTTING_DOWN;
2759 while (!LIST_EMPTY(slp)) {
2760 error = sync_vnode(slp, &bo, td);
2762 LIST_REMOVE(bo, bo_synclist);
2763 LIST_INSERT_HEAD(next, bo, bo_synclist);
2767 if (first_printf == 0) {
2769 * Drop the sync mutex, because some watchdog
2770 * drivers need to sleep while patting
2772 mtx_unlock(&sync_mtx);
2773 wdog_kern_pat(WD_LASTVAL);
2774 mtx_lock(&sync_mtx);
2777 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2778 syncer_final_iter--;
2780 * The variable rushjob allows the kernel to speed up the
2781 * processing of the filesystem syncer process. A rushjob
2782 * value of N tells the filesystem syncer to process the next
2783 * N seconds worth of work on its queue ASAP. Currently rushjob
2784 * is used by the soft update code to speed up the filesystem
2785 * syncer process when the incore state is getting so far
2786 * ahead of the disk that the kernel memory pool is being
2787 * threatened with exhaustion.
2794 * Just sleep for a short period of time between
2795 * iterations when shutting down to allow some I/O
2798 * If it has taken us less than a second to process the
2799 * current work, then wait. Otherwise start right over
2800 * again. We can still lose time if any single round
2801 * takes more than two seconds, but it does not really
2802 * matter as we are just trying to generally pace the
2803 * filesystem activity.
2805 if (syncer_state != SYNCER_RUNNING ||
2806 time_uptime == starttime) {
2808 sched_prio(td, PPAUSE);
2811 if (syncer_state != SYNCER_RUNNING)
2812 cv_timedwait(&sync_wakeup, &sync_mtx,
2813 hz / SYNCER_SHUTDOWN_SPEEDUP);
2814 else if (time_uptime == starttime)
2815 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2820 * Request the syncer daemon to speed up its work.
2821 * We never push it to speed up more than half of its
2822 * normal turn time, otherwise it could take over the cpu.
2825 speedup_syncer(void)
2829 mtx_lock(&sync_mtx);
2830 if (rushjob < syncdelay / 2) {
2832 stat_rush_requests += 1;
2835 mtx_unlock(&sync_mtx);
2836 cv_broadcast(&sync_wakeup);
2841 * Tell the syncer to speed up its work and run though its work
2842 * list several times, then tell it to shut down.
2845 syncer_shutdown(void *arg, int howto)
2848 if (howto & RB_NOSYNC)
2850 mtx_lock(&sync_mtx);
2851 syncer_state = SYNCER_SHUTTING_DOWN;
2853 mtx_unlock(&sync_mtx);
2854 cv_broadcast(&sync_wakeup);
2855 kproc_shutdown(arg, howto);
2859 syncer_suspend(void)
2862 syncer_shutdown(updateproc, 0);
2869 mtx_lock(&sync_mtx);
2871 syncer_state = SYNCER_RUNNING;
2872 mtx_unlock(&sync_mtx);
2873 cv_broadcast(&sync_wakeup);
2874 kproc_resume(updateproc);
2878 * Move the buffer between the clean and dirty lists of its vnode.
2881 reassignbuf(struct buf *bp)
2893 KASSERT((bp->b_flags & B_PAGING) == 0,
2894 ("%s: cannot reassign paging buffer %p", __func__, bp));
2896 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2897 bp, bp->b_vp, bp->b_flags);
2900 buf_vlist_remove(bp);
2903 * If dirty, put on list of dirty buffers; otherwise insert onto list
2906 if (bp->b_flags & B_DELWRI) {
2907 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2908 switch (vp->v_type) {
2918 vn_syncer_add_to_worklist(bo, delay);
2920 buf_vlist_add(bp, bo, BX_VNDIRTY);
2922 buf_vlist_add(bp, bo, BX_VNCLEAN);
2924 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2925 mtx_lock(&sync_mtx);
2926 LIST_REMOVE(bo, bo_synclist);
2927 syncer_worklist_len--;
2928 mtx_unlock(&sync_mtx);
2929 bo->bo_flag &= ~BO_ONWORKLST;
2934 bp = TAILQ_FIRST(&bv->bv_hd);
2935 KASSERT(bp == NULL || bp->b_bufobj == bo,
2936 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2937 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2938 KASSERT(bp == NULL || bp->b_bufobj == bo,
2939 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2941 bp = TAILQ_FIRST(&bv->bv_hd);
2942 KASSERT(bp == NULL || bp->b_bufobj == bo,
2943 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2944 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2945 KASSERT(bp == NULL || bp->b_bufobj == bo,
2946 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2952 v_init_counters(struct vnode *vp)
2955 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2956 vp, ("%s called for an initialized vnode", __FUNCTION__));
2957 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2959 refcount_init(&vp->v_holdcnt, 1);
2960 refcount_init(&vp->v_usecount, 1);
2964 * Grab a particular vnode from the free list, increment its
2965 * reference count and lock it. VIRF_DOOMED is set if the vnode
2966 * is being destroyed. Only callers who specify LK_RETRY will
2967 * see doomed vnodes. If inactive processing was delayed in
2968 * vput try to do it here.
2970 * usecount is manipulated using atomics without holding any locks.
2972 * holdcnt can be manipulated using atomics without holding any locks,
2973 * except when transitioning 1<->0, in which case the interlock is held.
2975 * Consumers which don't guarantee liveness of the vnode can use SMR to
2976 * try to get a reference. Note this operation can fail since the vnode
2977 * may be awaiting getting freed by the time they get to it.
2980 vget_prep_smr(struct vnode *vp)
2984 VFS_SMR_ASSERT_ENTERED();
2986 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2998 vget_prep(struct vnode *vp)
3002 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3012 vget_abort(struct vnode *vp, enum vgetstate vs)
3023 __assert_unreachable();
3028 vget(struct vnode *vp, int flags)
3033 return (vget_finish(vp, flags, vs));
3037 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
3041 if ((flags & LK_INTERLOCK) != 0)
3042 ASSERT_VI_LOCKED(vp, __func__);
3044 ASSERT_VI_UNLOCKED(vp, __func__);
3045 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3046 VNPASS(vp->v_holdcnt > 0, vp);
3047 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3049 error = vn_lock(vp, flags);
3050 if (__predict_false(error != 0)) {
3052 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
3057 vget_finish_ref(vp, vs);
3062 vget_finish_ref(struct vnode *vp, enum vgetstate vs)
3066 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3067 VNPASS(vp->v_holdcnt > 0, vp);
3068 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3070 if (vs == VGET_USECOUNT)
3074 * We hold the vnode. If the usecount is 0 it will be utilized to keep
3075 * the vnode around. Otherwise someone else lended their hold count and
3076 * we have to drop ours.
3078 old = atomic_fetchadd_int(&vp->v_usecount, 1);
3079 VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
3082 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
3083 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
3085 refcount_release(&vp->v_holdcnt);
3091 vref(struct vnode *vp)
3095 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3097 vget_finish_ref(vp, vs);
3101 vrefact(struct vnode *vp)
3104 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3106 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
3107 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3109 refcount_acquire(&vp->v_usecount);
3114 vlazy(struct vnode *vp)
3118 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
3120 if ((vp->v_mflag & VMP_LAZYLIST) != 0)
3123 * We may get here for inactive routines after the vnode got doomed.
3125 if (VN_IS_DOOMED(vp))
3128 mtx_lock(&mp->mnt_listmtx);
3129 if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
3130 vp->v_mflag |= VMP_LAZYLIST;
3131 TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3132 mp->mnt_lazyvnodelistsize++;
3134 mtx_unlock(&mp->mnt_listmtx);
3138 vunlazy(struct vnode *vp)
3142 ASSERT_VI_LOCKED(vp, __func__);
3143 VNPASS(!VN_IS_DOOMED(vp), vp);
3146 mtx_lock(&mp->mnt_listmtx);
3147 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3149 * Don't remove the vnode from the lazy list if another thread
3150 * has increased the hold count. It may have re-enqueued the
3151 * vnode to the lazy list and is now responsible for its
3154 if (vp->v_holdcnt == 0) {
3155 vp->v_mflag &= ~VMP_LAZYLIST;
3156 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3157 mp->mnt_lazyvnodelistsize--;
3159 mtx_unlock(&mp->mnt_listmtx);
3163 * This routine is only meant to be called from vgonel prior to dooming
3167 vunlazy_gone(struct vnode *vp)
3171 ASSERT_VOP_ELOCKED(vp, __func__);
3172 ASSERT_VI_LOCKED(vp, __func__);
3173 VNPASS(!VN_IS_DOOMED(vp), vp);
3175 if (vp->v_mflag & VMP_LAZYLIST) {
3177 mtx_lock(&mp->mnt_listmtx);
3178 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3179 vp->v_mflag &= ~VMP_LAZYLIST;
3180 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3181 mp->mnt_lazyvnodelistsize--;
3182 mtx_unlock(&mp->mnt_listmtx);
3187 vdefer_inactive(struct vnode *vp)
3190 ASSERT_VI_LOCKED(vp, __func__);
3191 VNASSERT(vp->v_holdcnt > 0, vp,
3192 ("%s: vnode without hold count", __func__));
3193 if (VN_IS_DOOMED(vp)) {
3197 if (vp->v_iflag & VI_DEFINACT) {
3198 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3202 if (vp->v_usecount > 0) {
3203 vp->v_iflag &= ~VI_OWEINACT;
3208 vp->v_iflag |= VI_DEFINACT;
3210 counter_u64_add(deferred_inact, 1);
3214 vdefer_inactive_unlocked(struct vnode *vp)
3218 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3222 vdefer_inactive(vp);
3225 enum vput_op { VRELE, VPUT, VUNREF };
3228 * Handle ->v_usecount transitioning to 0.
3230 * By releasing the last usecount we take ownership of the hold count which
3231 * provides liveness of the vnode, meaning we have to vdrop.
3233 * For all vnodes we may need to perform inactive processing. It requires an
3234 * exclusive lock on the vnode, while it is legal to call here with only a
3235 * shared lock (or no locks). If locking the vnode in an expected manner fails,
3236 * inactive processing gets deferred to the syncer.
3238 * XXX Some filesystems pass in an exclusively locked vnode and strongly depend
3239 * on the lock being held all the way until VOP_INACTIVE. This in particular
3240 * happens with UFS which adds half-constructed vnodes to the hash, where they
3241 * can be found by other code.
3244 vput_final(struct vnode *vp, enum vput_op func)
3249 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3250 VNPASS(vp->v_holdcnt > 0, vp);
3255 * By the time we got here someone else might have transitioned
3256 * the count back to > 0.
3258 if (vp->v_usecount > 0)
3262 * If the vnode is doomed vgone already performed inactive processing
3265 if (VN_IS_DOOMED(vp))
3268 if (__predict_true(VOP_NEED_INACTIVE(vp) == 0))
3271 if (vp->v_iflag & VI_DOINGINACT)
3275 * Locking operations here will drop the interlock and possibly the
3276 * vnode lock, opening a window where the vnode can get doomed all the
3277 * while ->v_usecount is 0. Set VI_OWEINACT to let vgone know to
3280 vp->v_iflag |= VI_OWEINACT;
3281 want_unlock = false;
3285 switch (VOP_ISLOCKED(vp)) {
3291 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3296 * The lock has at least one sharer, but we have no way
3297 * to conclude whether this is us. Play it safe and
3306 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3307 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3313 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3314 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3320 if (func == VUNREF) {
3321 VNASSERT((vp->v_vflag & VV_UNREF) == 0, vp,
3322 ("recursive vunref"));
3323 vp->v_vflag |= VV_UNREF;
3326 error = vinactive(vp);
3329 if (error != ERELOOKUP || !want_unlock)
3331 VOP_LOCK(vp, LK_EXCLUSIVE);
3334 vp->v_vflag &= ~VV_UNREF;
3337 vdefer_inactive(vp);
3347 * Decrement ->v_usecount for a vnode.
3349 * Releasing the last use count requires additional processing, see vput_final
3350 * above for details.
3352 * Comment above each variant denotes lock state on entry and exit.
3357 * out: same as passed in
3360 vrele(struct vnode *vp)
3363 ASSERT_VI_UNLOCKED(vp, __func__);
3364 if (!refcount_release(&vp->v_usecount))
3366 vput_final(vp, VRELE);
3374 vput(struct vnode *vp)
3377 ASSERT_VOP_LOCKED(vp, __func__);
3378 ASSERT_VI_UNLOCKED(vp, __func__);
3379 if (!refcount_release(&vp->v_usecount)) {
3383 vput_final(vp, VPUT);
3391 vunref(struct vnode *vp)
3394 ASSERT_VOP_LOCKED(vp, __func__);
3395 ASSERT_VI_UNLOCKED(vp, __func__);
3396 if (!refcount_release(&vp->v_usecount))
3398 vput_final(vp, VUNREF);
3402 vhold(struct vnode *vp)
3406 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3407 old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3408 VNASSERT(old >= 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3409 ("%s: wrong hold count %d", __func__, old));
3411 vfs_freevnodes_dec();
3415 vholdnz(struct vnode *vp)
3418 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3420 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3421 VNASSERT(old > 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3422 ("%s: wrong hold count %d", __func__, old));
3424 atomic_add_int(&vp->v_holdcnt, 1);
3429 * Grab a hold count unless the vnode is freed.
3431 * Only use this routine if vfs smr is the only protection you have against
3432 * freeing the vnode.
3434 * The code loops trying to add a hold count as long as the VHOLD_NO_SMR flag
3435 * is not set. After the flag is set the vnode becomes immutable to anyone but
3436 * the thread which managed to set the flag.
3438 * It may be tempting to replace the loop with:
3439 * count = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3440 * if (count & VHOLD_NO_SMR) {
3441 * backpedal and error out;
3444 * However, while this is more performant, it hinders debugging by eliminating
3445 * the previously mentioned invariant.
3448 vhold_smr(struct vnode *vp)
3452 VFS_SMR_ASSERT_ENTERED();
3454 count = atomic_load_int(&vp->v_holdcnt);
3456 if (count & VHOLD_NO_SMR) {
3457 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3458 ("non-zero hold count with flags %d\n", count));
3461 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3462 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3464 vfs_freevnodes_dec();
3471 * Hold a free vnode for recycling.
3473 * Note: vnode_init references this comment.
3475 * Attempts to recycle only need the global vnode list lock and have no use for
3478 * However, vnodes get inserted into the global list before they get fully
3479 * initialized and stay there until UMA decides to free the memory. This in
3480 * particular means the target can be found before it becomes usable and after
3481 * it becomes recycled. Picking up such vnodes is guarded with v_holdcnt set to
3484 * Note: the vnode may gain more references after we transition the count 0->1.
3487 vhold_recycle_free(struct vnode *vp)
3491 mtx_assert(&vnode_list_mtx, MA_OWNED);
3493 count = atomic_load_int(&vp->v_holdcnt);
3495 if (count & VHOLD_NO_SMR) {
3496 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3497 ("non-zero hold count with flags %d\n", count));
3500 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3504 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3505 vfs_freevnodes_dec();
3511 static void __noinline
3512 vdbatch_process(struct vdbatch *vd)
3517 mtx_assert(&vd->lock, MA_OWNED);
3518 MPASS(curthread->td_pinned > 0);
3519 MPASS(vd->index == VDBATCH_SIZE);
3521 mtx_lock(&vnode_list_mtx);
3523 freevnodes += vd->freevnodes;
3524 for (i = 0; i < VDBATCH_SIZE; i++) {
3526 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3527 TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3528 MPASS(vp->v_dbatchcpu != NOCPU);
3529 vp->v_dbatchcpu = NOCPU;
3531 mtx_unlock(&vnode_list_mtx);
3533 bzero(vd->tab, sizeof(vd->tab));
3539 vdbatch_enqueue(struct vnode *vp)
3543 ASSERT_VI_LOCKED(vp, __func__);
3544 VNASSERT(!VN_IS_DOOMED(vp), vp,
3545 ("%s: deferring requeue of a doomed vnode", __func__));
3547 if (vp->v_dbatchcpu != NOCPU) {
3554 mtx_lock(&vd->lock);
3555 MPASS(vd->index < VDBATCH_SIZE);
3556 MPASS(vd->tab[vd->index] == NULL);
3558 * A hack: we depend on being pinned so that we know what to put in
3561 vp->v_dbatchcpu = curcpu;
3562 vd->tab[vd->index] = vp;
3565 if (vd->index == VDBATCH_SIZE)
3566 vdbatch_process(vd);
3567 mtx_unlock(&vd->lock);
3572 * This routine must only be called for vnodes which are about to be
3573 * deallocated. Supporting dequeue for arbitrary vndoes would require
3574 * validating that the locked batch matches.
3577 vdbatch_dequeue(struct vnode *vp)
3583 VNASSERT(vp->v_type == VBAD || vp->v_type == VNON, vp,
3584 ("%s: called for a used vnode\n", __func__));
3586 cpu = vp->v_dbatchcpu;
3590 vd = DPCPU_ID_PTR(cpu, vd);
3591 mtx_lock(&vd->lock);
3592 for (i = 0; i < vd->index; i++) {
3593 if (vd->tab[i] != vp)
3595 vp->v_dbatchcpu = NOCPU;
3597 vd->tab[i] = vd->tab[vd->index];
3598 vd->tab[vd->index] = NULL;
3601 mtx_unlock(&vd->lock);
3603 * Either we dequeued the vnode above or the target CPU beat us to it.
3605 MPASS(vp->v_dbatchcpu == NOCPU);
3609 * Drop the hold count of the vnode. If this is the last reference to
3610 * the vnode we place it on the free list unless it has been vgone'd
3611 * (marked VIRF_DOOMED) in which case we will free it.
3613 * Because the vnode vm object keeps a hold reference on the vnode if
3614 * there is at least one resident non-cached page, the vnode cannot
3615 * leave the active list without the page cleanup done.
3617 static void __noinline
3618 vdropl_final(struct vnode *vp)
3621 ASSERT_VI_LOCKED(vp, __func__);
3622 VNPASS(VN_IS_DOOMED(vp), vp);
3624 * Set the VHOLD_NO_SMR flag.
3626 * We may be racing against vhold_smr. If they win we can just pretend
3627 * we never got this far, they will vdrop later.
3629 if (__predict_false(!atomic_cmpset_int(&vp->v_holdcnt, 0, VHOLD_NO_SMR))) {
3630 vfs_freevnodes_inc();
3633 * We lost the aforementioned race. Any subsequent access is
3634 * invalid as they might have managed to vdropl on their own.
3639 * Don't bump freevnodes as this one is going away.
3645 vdrop(struct vnode *vp)
3648 ASSERT_VI_UNLOCKED(vp, __func__);
3649 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3650 if (refcount_release_if_not_last(&vp->v_holdcnt))
3656 static void __always_inline
3657 vdropl_impl(struct vnode *vp, bool enqueue)
3660 ASSERT_VI_LOCKED(vp, __func__);
3661 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3662 if (!refcount_release(&vp->v_holdcnt)) {
3666 VNPASS((vp->v_iflag & VI_OWEINACT) == 0, vp);
3667 VNPASS((vp->v_iflag & VI_DEFINACT) == 0, vp);
3668 if (VN_IS_DOOMED(vp)) {
3673 vfs_freevnodes_inc();
3674 if (vp->v_mflag & VMP_LAZYLIST) {
3684 * Also unlocks the interlock. We can't assert on it as we
3685 * released our hold and by now the vnode might have been
3688 vdbatch_enqueue(vp);
3692 vdropl(struct vnode *vp)
3695 vdropl_impl(vp, true);
3699 * vdrop a vnode when recycling
3701 * This is a special case routine only to be used when recycling, differs from
3702 * regular vdrop by not requeieing the vnode on LRU.
3704 * Consider a case where vtryrecycle continuously fails with all vnodes (due to
3705 * e.g., frozen writes on the filesystem), filling the batch and causing it to
3706 * be requeued. Then vnlru will end up revisiting the same vnodes. This is a
3707 * loop which can last for as long as writes are frozen.
3710 vdropl_recycle(struct vnode *vp)
3713 vdropl_impl(vp, false);
3717 vdrop_recycle(struct vnode *vp)
3725 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3726 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3729 vinactivef(struct vnode *vp)
3731 struct vm_object *obj;
3734 ASSERT_VOP_ELOCKED(vp, "vinactive");
3735 ASSERT_VI_LOCKED(vp, "vinactive");
3736 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3737 ("vinactive: recursed on VI_DOINGINACT"));
3738 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3739 vp->v_iflag |= VI_DOINGINACT;
3740 vp->v_iflag &= ~VI_OWEINACT;
3743 * Before moving off the active list, we must be sure that any
3744 * modified pages are converted into the vnode's dirty
3745 * buffers, since these will no longer be checked once the
3746 * vnode is on the inactive list.
3748 * The write-out of the dirty pages is asynchronous. At the
3749 * point that VOP_INACTIVE() is called, there could still be
3750 * pending I/O and dirty pages in the object.
3752 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3753 vm_object_mightbedirty(obj)) {
3754 VM_OBJECT_WLOCK(obj);
3755 vm_object_page_clean(obj, 0, 0, 0);
3756 VM_OBJECT_WUNLOCK(obj);
3758 error = VOP_INACTIVE(vp);
3760 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3761 ("vinactive: lost VI_DOINGINACT"));
3762 vp->v_iflag &= ~VI_DOINGINACT;
3767 vinactive(struct vnode *vp)
3770 ASSERT_VOP_ELOCKED(vp, "vinactive");
3771 ASSERT_VI_LOCKED(vp, "vinactive");
3772 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3774 if ((vp->v_iflag & VI_OWEINACT) == 0)
3776 if (vp->v_iflag & VI_DOINGINACT)
3778 if (vp->v_usecount > 0) {
3779 vp->v_iflag &= ~VI_OWEINACT;
3782 return (vinactivef(vp));
3786 * Remove any vnodes in the vnode table belonging to mount point mp.
3788 * If FORCECLOSE is not specified, there should not be any active ones,
3789 * return error if any are found (nb: this is a user error, not a
3790 * system error). If FORCECLOSE is specified, detach any active vnodes
3793 * If WRITECLOSE is set, only flush out regular file vnodes open for
3796 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3798 * `rootrefs' specifies the base reference count for the root vnode
3799 * of this filesystem. The root vnode is considered busy if its
3800 * v_usecount exceeds this value. On a successful return, vflush(, td)
3801 * will call vrele() on the root vnode exactly rootrefs times.
3802 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3806 static int busyprt = 0; /* print out busy vnodes */
3807 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3811 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3813 struct vnode *vp, *mvp, *rootvp = NULL;
3815 int busy = 0, error;
3817 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3820 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3821 ("vflush: bad args"));
3823 * Get the filesystem root vnode. We can vput() it
3824 * immediately, since with rootrefs > 0, it won't go away.
3826 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3827 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3834 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3836 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3839 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3843 * Skip over a vnodes marked VV_SYSTEM.
3845 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3851 * If WRITECLOSE is set, flush out unlinked but still open
3852 * files (even if open only for reading) and regular file
3853 * vnodes open for writing.
3855 if (flags & WRITECLOSE) {
3856 if (vp->v_object != NULL) {
3857 VM_OBJECT_WLOCK(vp->v_object);
3858 vm_object_page_clean(vp->v_object, 0, 0, 0);
3859 VM_OBJECT_WUNLOCK(vp->v_object);
3862 error = VOP_FSYNC(vp, MNT_WAIT, td);
3863 } while (error == ERELOOKUP);
3867 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3870 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3873 if ((vp->v_type == VNON ||
3874 (error == 0 && vattr.va_nlink > 0)) &&
3875 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3883 * With v_usecount == 0, all we need to do is clear out the
3884 * vnode data structures and we are done.
3886 * If FORCECLOSE is set, forcibly close the vnode.
3888 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3894 vn_printf(vp, "vflush: busy vnode ");
3900 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3902 * If just the root vnode is busy, and if its refcount
3903 * is equal to `rootrefs', then go ahead and kill it.
3906 KASSERT(busy > 0, ("vflush: not busy"));
3907 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3908 ("vflush: usecount %d < rootrefs %d",
3909 rootvp->v_usecount, rootrefs));
3910 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3911 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3919 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3923 for (; rootrefs > 0; rootrefs--)
3929 * Recycle an unused vnode to the front of the free list.
3932 vrecycle(struct vnode *vp)
3937 recycled = vrecyclel(vp);
3943 * vrecycle, with the vp interlock held.
3946 vrecyclel(struct vnode *vp)
3950 ASSERT_VOP_ELOCKED(vp, __func__);
3951 ASSERT_VI_LOCKED(vp, __func__);
3952 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3954 if (vp->v_usecount == 0) {
3962 * Eliminate all activity associated with a vnode
3963 * in preparation for reuse.
3966 vgone(struct vnode *vp)
3974 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3975 struct vnode *lowervp __unused)
3980 * Notify upper mounts about reclaimed or unlinked vnode.
3983 vfs_notify_upper(struct vnode *vp, int event)
3985 static struct vfsops vgonel_vfsops = {
3986 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3987 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3989 struct mount *mp, *ump, *mmp;
3994 if (TAILQ_EMPTY(&mp->mnt_uppers))
3997 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3998 mmp->mnt_op = &vgonel_vfsops;
3999 mmp->mnt_kern_flag |= MNTK_MARKER;
4001 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
4002 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
4003 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
4004 ump = TAILQ_NEXT(ump, mnt_upper_link);
4007 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
4010 case VFS_NOTIFY_UPPER_RECLAIM:
4011 VFS_RECLAIM_LOWERVP(ump, vp);
4013 case VFS_NOTIFY_UPPER_UNLINK:
4014 VFS_UNLINK_LOWERVP(ump, vp);
4017 KASSERT(0, ("invalid event %d", event));
4021 ump = TAILQ_NEXT(mmp, mnt_upper_link);
4022 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
4025 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
4026 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
4027 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
4028 wakeup(&mp->mnt_uppers);
4034 * vgone, with the vp interlock held.
4037 vgonel(struct vnode *vp)
4042 bool active, doinginact, oweinact;
4044 ASSERT_VOP_ELOCKED(vp, "vgonel");
4045 ASSERT_VI_LOCKED(vp, "vgonel");
4046 VNASSERT(vp->v_holdcnt, vp,
4047 ("vgonel: vp %p has no reference.", vp));
4048 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
4052 * Don't vgonel if we're already doomed.
4054 if (VN_IS_DOOMED(vp))
4057 * Paired with freevnode.
4059 vn_seqc_write_begin_locked(vp);
4061 vn_irflag_set_locked(vp, VIRF_DOOMED);
4064 * Check to see if the vnode is in use. If so, we have to
4065 * call VOP_CLOSE() and VOP_INACTIVE().
4067 * It could be that VOP_INACTIVE() requested reclamation, in
4068 * which case we should avoid recursion, so check
4069 * VI_DOINGINACT. This is not precise but good enough.
4071 active = vp->v_usecount > 0;
4072 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4073 doinginact = (vp->v_iflag & VI_DOINGINACT) != 0;
4076 * If we need to do inactive VI_OWEINACT will be set.
4078 if (vp->v_iflag & VI_DEFINACT) {
4079 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
4080 vp->v_iflag &= ~VI_DEFINACT;
4083 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
4086 cache_purge_vgone(vp);
4087 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
4090 * If purging an active vnode, it must be closed and
4091 * deactivated before being reclaimed.
4094 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
4097 if (oweinact || active) {
4100 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4105 if (vp->v_type == VSOCK)
4106 vfs_unp_reclaim(vp);
4109 * Clean out any buffers associated with the vnode.
4110 * If the flush fails, just toss the buffers.
4113 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
4114 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
4115 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
4116 while (vinvalbuf(vp, 0, 0, 0) != 0)
4120 BO_LOCK(&vp->v_bufobj);
4121 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
4122 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
4123 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
4124 vp->v_bufobj.bo_clean.bv_cnt == 0,
4125 ("vp %p bufobj not invalidated", vp));
4128 * For VMIO bufobj, BO_DEAD is set later, or in
4129 * vm_object_terminate() after the object's page queue is
4132 object = vp->v_bufobj.bo_object;
4134 vp->v_bufobj.bo_flag |= BO_DEAD;
4135 BO_UNLOCK(&vp->v_bufobj);
4138 * Handle the VM part. Tmpfs handles v_object on its own (the
4139 * OBJT_VNODE check). Nullfs or other bypassing filesystems
4140 * should not touch the object borrowed from the lower vnode
4141 * (the handle check).
4143 if (object != NULL && object->type == OBJT_VNODE &&
4144 object->handle == vp)
4145 vnode_destroy_vobject(vp);
4148 * Reclaim the vnode.
4150 if (VOP_RECLAIM(vp))
4151 panic("vgone: cannot reclaim");
4153 vn_finished_secondary_write(mp);
4154 VNASSERT(vp->v_object == NULL, vp,
4155 ("vop_reclaim left v_object vp=%p", vp));
4157 * Clear the advisory locks and wake up waiting threads.
4159 (void)VOP_ADVLOCKPURGE(vp);
4162 * Delete from old mount point vnode list.
4166 * Done with purge, reset to the standard lock and invalidate
4170 vp->v_vnlock = &vp->v_lock;
4171 vp->v_op = &dead_vnodeops;
4176 * Print out a description of a vnode.
4178 static const char * const typename[] =
4179 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
4182 _Static_assert((VHOLD_ALL_FLAGS & ~VHOLD_NO_SMR) == 0,
4183 "new hold count flag not added to vn_printf");
4186 vn_printf(struct vnode *vp, const char *fmt, ...)
4189 char buf[256], buf2[16];
4197 printf("%p: ", (void *)vp);
4198 printf("type %s\n", typename[vp->v_type]);
4199 holdcnt = atomic_load_int(&vp->v_holdcnt);
4200 printf(" usecount %d, writecount %d, refcount %d seqc users %d",
4201 vp->v_usecount, vp->v_writecount, holdcnt & ~VHOLD_ALL_FLAGS,
4203 switch (vp->v_type) {
4205 printf(" mountedhere %p\n", vp->v_mountedhere);
4208 printf(" rdev %p\n", vp->v_rdev);
4211 printf(" socket %p\n", vp->v_unpcb);
4214 printf(" fifoinfo %p\n", vp->v_fifoinfo);
4222 if (holdcnt & VHOLD_NO_SMR)
4223 strlcat(buf, "|VHOLD_NO_SMR", sizeof(buf));
4224 printf(" hold count flags (%s)\n", buf + 1);
4228 irflag = vn_irflag_read(vp);
4229 if (irflag & VIRF_DOOMED)
4230 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
4231 if (irflag & VIRF_PGREAD)
4232 strlcat(buf, "|VIRF_PGREAD", sizeof(buf));
4233 if (irflag & VIRF_MOUNTPOINT)
4234 strlcat(buf, "|VIRF_MOUNTPOINT", sizeof(buf));
4235 flags = irflag & ~(VIRF_DOOMED | VIRF_PGREAD | VIRF_MOUNTPOINT);
4237 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
4238 strlcat(buf, buf2, sizeof(buf));
4240 if (vp->v_vflag & VV_ROOT)
4241 strlcat(buf, "|VV_ROOT", sizeof(buf));
4242 if (vp->v_vflag & VV_ISTTY)
4243 strlcat(buf, "|VV_ISTTY", sizeof(buf));
4244 if (vp->v_vflag & VV_NOSYNC)
4245 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
4246 if (vp->v_vflag & VV_ETERNALDEV)
4247 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
4248 if (vp->v_vflag & VV_CACHEDLABEL)
4249 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
4250 if (vp->v_vflag & VV_VMSIZEVNLOCK)
4251 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
4252 if (vp->v_vflag & VV_COPYONWRITE)
4253 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
4254 if (vp->v_vflag & VV_SYSTEM)
4255 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
4256 if (vp->v_vflag & VV_PROCDEP)
4257 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
4258 if (vp->v_vflag & VV_NOKNOTE)
4259 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
4260 if (vp->v_vflag & VV_DELETED)
4261 strlcat(buf, "|VV_DELETED", sizeof(buf));
4262 if (vp->v_vflag & VV_MD)
4263 strlcat(buf, "|VV_MD", sizeof(buf));
4264 if (vp->v_vflag & VV_FORCEINSMQ)
4265 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
4266 if (vp->v_vflag & VV_READLINK)
4267 strlcat(buf, "|VV_READLINK", sizeof(buf));
4268 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4269 VV_CACHEDLABEL | VV_VMSIZEVNLOCK | VV_COPYONWRITE | VV_SYSTEM |
4270 VV_PROCDEP | VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ |
4273 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4274 strlcat(buf, buf2, sizeof(buf));
4276 if (vp->v_iflag & VI_TEXT_REF)
4277 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
4278 if (vp->v_iflag & VI_MOUNT)
4279 strlcat(buf, "|VI_MOUNT", sizeof(buf));
4280 if (vp->v_iflag & VI_DOINGINACT)
4281 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4282 if (vp->v_iflag & VI_OWEINACT)
4283 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4284 if (vp->v_iflag & VI_DEFINACT)
4285 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4286 if (vp->v_iflag & VI_FOPENING)
4287 strlcat(buf, "|VI_FOPENING", sizeof(buf));
4288 flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOINGINACT |
4289 VI_OWEINACT | VI_DEFINACT | VI_FOPENING);
4291 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4292 strlcat(buf, buf2, sizeof(buf));
4294 if (vp->v_mflag & VMP_LAZYLIST)
4295 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4296 flags = vp->v_mflag & ~(VMP_LAZYLIST);
4298 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4299 strlcat(buf, buf2, sizeof(buf));
4301 printf(" flags (%s)", buf + 1);
4302 if (mtx_owned(VI_MTX(vp)))
4303 printf(" VI_LOCKed");
4305 if (vp->v_object != NULL)
4306 printf(" v_object %p ref %d pages %d "
4307 "cleanbuf %d dirtybuf %d\n",
4308 vp->v_object, vp->v_object->ref_count,
4309 vp->v_object->resident_page_count,
4310 vp->v_bufobj.bo_clean.bv_cnt,
4311 vp->v_bufobj.bo_dirty.bv_cnt);
4313 lockmgr_printinfo(vp->v_vnlock);
4314 if (vp->v_data != NULL)
4320 * List all of the locked vnodes in the system.
4321 * Called when debugging the kernel.
4323 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
4329 * Note: because this is DDB, we can't obey the locking semantics
4330 * for these structures, which means we could catch an inconsistent
4331 * state and dereference a nasty pointer. Not much to be done
4334 db_printf("Locked vnodes\n");
4335 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4336 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4337 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4338 vn_printf(vp, "vnode ");
4344 * Show details about the given vnode.
4346 DB_SHOW_COMMAND(vnode, db_show_vnode)
4352 vp = (struct vnode *)addr;
4353 vn_printf(vp, "vnode ");
4357 * Show details about the given mount point.
4359 DB_SHOW_COMMAND(mount, db_show_mount)
4370 /* No address given, print short info about all mount points. */
4371 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4372 db_printf("%p %s on %s (%s)\n", mp,
4373 mp->mnt_stat.f_mntfromname,
4374 mp->mnt_stat.f_mntonname,
4375 mp->mnt_stat.f_fstypename);
4379 db_printf("\nMore info: show mount <addr>\n");
4383 mp = (struct mount *)addr;
4384 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4385 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4388 mflags = mp->mnt_flag;
4389 #define MNT_FLAG(flag) do { \
4390 if (mflags & (flag)) { \
4391 if (buf[0] != '\0') \
4392 strlcat(buf, ", ", sizeof(buf)); \
4393 strlcat(buf, (#flag) + 4, sizeof(buf)); \
4394 mflags &= ~(flag); \
4397 MNT_FLAG(MNT_RDONLY);
4398 MNT_FLAG(MNT_SYNCHRONOUS);
4399 MNT_FLAG(MNT_NOEXEC);
4400 MNT_FLAG(MNT_NOSUID);
4401 MNT_FLAG(MNT_NFS4ACLS);
4402 MNT_FLAG(MNT_UNION);
4403 MNT_FLAG(MNT_ASYNC);
4404 MNT_FLAG(MNT_SUIDDIR);
4405 MNT_FLAG(MNT_SOFTDEP);
4406 MNT_FLAG(MNT_NOSYMFOLLOW);
4407 MNT_FLAG(MNT_GJOURNAL);
4408 MNT_FLAG(MNT_MULTILABEL);
4410 MNT_FLAG(MNT_NOATIME);
4411 MNT_FLAG(MNT_NOCLUSTERR);
4412 MNT_FLAG(MNT_NOCLUSTERW);
4414 MNT_FLAG(MNT_EXRDONLY);
4415 MNT_FLAG(MNT_EXPORTED);
4416 MNT_FLAG(MNT_DEFEXPORTED);
4417 MNT_FLAG(MNT_EXPORTANON);
4418 MNT_FLAG(MNT_EXKERB);
4419 MNT_FLAG(MNT_EXPUBLIC);
4420 MNT_FLAG(MNT_LOCAL);
4421 MNT_FLAG(MNT_QUOTA);
4422 MNT_FLAG(MNT_ROOTFS);
4424 MNT_FLAG(MNT_IGNORE);
4425 MNT_FLAG(MNT_UPDATE);
4426 MNT_FLAG(MNT_DELEXPORT);
4427 MNT_FLAG(MNT_RELOAD);
4428 MNT_FLAG(MNT_FORCE);
4429 MNT_FLAG(MNT_SNAPSHOT);
4430 MNT_FLAG(MNT_BYFSID);
4434 strlcat(buf, ", ", sizeof(buf));
4435 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4436 "0x%016jx", mflags);
4438 db_printf(" mnt_flag = %s\n", buf);
4441 flags = mp->mnt_kern_flag;
4442 #define MNT_KERN_FLAG(flag) do { \
4443 if (flags & (flag)) { \
4444 if (buf[0] != '\0') \
4445 strlcat(buf, ", ", sizeof(buf)); \
4446 strlcat(buf, (#flag) + 5, sizeof(buf)); \
4450 MNT_KERN_FLAG(MNTK_UNMOUNTF);
4451 MNT_KERN_FLAG(MNTK_ASYNC);
4452 MNT_KERN_FLAG(MNTK_SOFTDEP);
4453 MNT_KERN_FLAG(MNTK_DRAINING);
4454 MNT_KERN_FLAG(MNTK_REFEXPIRE);
4455 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4456 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4457 MNT_KERN_FLAG(MNTK_NO_IOPF);
4458 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4459 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4460 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4461 MNT_KERN_FLAG(MNTK_MARKER);
4462 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4463 MNT_KERN_FLAG(MNTK_FPLOOKUP);
4464 MNT_KERN_FLAG(MNTK_NOASYNC);
4465 MNT_KERN_FLAG(MNTK_UNMOUNT);
4466 MNT_KERN_FLAG(MNTK_MWAIT);
4467 MNT_KERN_FLAG(MNTK_SUSPEND);
4468 MNT_KERN_FLAG(MNTK_SUSPEND2);
4469 MNT_KERN_FLAG(MNTK_SUSPENDED);
4470 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4471 MNT_KERN_FLAG(MNTK_NOKNOTE);
4472 #undef MNT_KERN_FLAG
4475 strlcat(buf, ", ", sizeof(buf));
4476 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4479 db_printf(" mnt_kern_flag = %s\n", buf);
4481 db_printf(" mnt_opt = ");
4482 opt = TAILQ_FIRST(mp->mnt_opt);
4484 db_printf("%s", opt->name);
4485 opt = TAILQ_NEXT(opt, link);
4486 while (opt != NULL) {
4487 db_printf(", %s", opt->name);
4488 opt = TAILQ_NEXT(opt, link);
4494 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4495 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4496 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4497 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4498 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4499 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4500 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4501 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4502 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4503 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4504 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4505 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4507 db_printf(" mnt_cred = { uid=%u ruid=%u",
4508 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4509 if (jailed(mp->mnt_cred))
4510 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4512 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4513 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4514 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4515 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4516 db_printf(" mnt_lazyvnodelistsize = %d\n",
4517 mp->mnt_lazyvnodelistsize);
4518 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4519 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4520 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4521 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4522 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4523 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4524 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4525 db_printf(" mnt_secondary_accwrites = %d\n",
4526 mp->mnt_secondary_accwrites);
4527 db_printf(" mnt_gjprovider = %s\n",
4528 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4529 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4531 db_printf("\n\nList of active vnodes\n");
4532 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4533 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4534 vn_printf(vp, "vnode ");
4539 db_printf("\n\nList of inactive vnodes\n");
4540 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4541 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4542 vn_printf(vp, "vnode ");
4551 * Fill in a struct xvfsconf based on a struct vfsconf.
4554 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4556 struct xvfsconf xvfsp;
4558 bzero(&xvfsp, sizeof(xvfsp));
4559 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4560 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4561 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4562 xvfsp.vfc_flags = vfsp->vfc_flags;
4564 * These are unused in userland, we keep them
4565 * to not break binary compatibility.
4567 xvfsp.vfc_vfsops = NULL;
4568 xvfsp.vfc_next = NULL;
4569 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4572 #ifdef COMPAT_FREEBSD32
4574 uint32_t vfc_vfsops;
4575 char vfc_name[MFSNAMELEN];
4576 int32_t vfc_typenum;
4577 int32_t vfc_refcount;
4583 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4585 struct xvfsconf32 xvfsp;
4587 bzero(&xvfsp, sizeof(xvfsp));
4588 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4589 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4590 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4591 xvfsp.vfc_flags = vfsp->vfc_flags;
4592 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4597 * Top level filesystem related information gathering.
4600 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4602 struct vfsconf *vfsp;
4607 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4608 #ifdef COMPAT_FREEBSD32
4609 if (req->flags & SCTL_MASK32)
4610 error = vfsconf2x32(req, vfsp);
4613 error = vfsconf2x(req, vfsp);
4621 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4622 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4623 "S,xvfsconf", "List of all configured filesystems");
4625 #ifndef BURN_BRIDGES
4626 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4629 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4631 int *name = (int *)arg1 - 1; /* XXX */
4632 u_int namelen = arg2 + 1; /* XXX */
4633 struct vfsconf *vfsp;
4635 log(LOG_WARNING, "userland calling deprecated sysctl, "
4636 "please rebuild world\n");
4638 #if 1 || defined(COMPAT_PRELITE2)
4639 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4641 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4645 case VFS_MAXTYPENUM:
4648 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4651 return (ENOTDIR); /* overloaded */
4653 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4654 if (vfsp->vfc_typenum == name[2])
4659 return (EOPNOTSUPP);
4660 #ifdef COMPAT_FREEBSD32
4661 if (req->flags & SCTL_MASK32)
4662 return (vfsconf2x32(req, vfsp));
4665 return (vfsconf2x(req, vfsp));
4667 return (EOPNOTSUPP);
4670 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4671 CTLFLAG_MPSAFE, vfs_sysctl,
4672 "Generic filesystem");
4674 #if 1 || defined(COMPAT_PRELITE2)
4677 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4680 struct vfsconf *vfsp;
4681 struct ovfsconf ovfs;
4684 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4685 bzero(&ovfs, sizeof(ovfs));
4686 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4687 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4688 ovfs.vfc_index = vfsp->vfc_typenum;
4689 ovfs.vfc_refcount = vfsp->vfc_refcount;
4690 ovfs.vfc_flags = vfsp->vfc_flags;
4691 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4701 #endif /* 1 || COMPAT_PRELITE2 */
4702 #endif /* !BURN_BRIDGES */
4704 #define KINFO_VNODESLOP 10
4707 * Dump vnode list (via sysctl).
4711 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4719 * Stale numvnodes access is not fatal here.
4722 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4724 /* Make an estimate */
4725 return (SYSCTL_OUT(req, 0, len));
4727 error = sysctl_wire_old_buffer(req, 0);
4730 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4732 mtx_lock(&mountlist_mtx);
4733 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4734 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4737 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4741 xvn[n].xv_size = sizeof *xvn;
4742 xvn[n].xv_vnode = vp;
4743 xvn[n].xv_id = 0; /* XXX compat */
4744 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4746 XV_COPY(writecount);
4752 xvn[n].xv_flag = vp->v_vflag;
4754 switch (vp->v_type) {
4761 if (vp->v_rdev == NULL) {
4765 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4768 xvn[n].xv_socket = vp->v_socket;
4771 xvn[n].xv_fifo = vp->v_fifoinfo;
4776 /* shouldn't happen? */
4784 mtx_lock(&mountlist_mtx);
4789 mtx_unlock(&mountlist_mtx);
4791 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4796 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4797 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4802 unmount_or_warn(struct mount *mp)
4806 error = dounmount(mp, MNT_FORCE, curthread);
4808 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4812 printf("%d)\n", error);
4817 * Unmount all filesystems. The list is traversed in reverse order
4818 * of mounting to avoid dependencies.
4821 vfs_unmountall(void)
4823 struct mount *mp, *tmp;
4825 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4828 * Since this only runs when rebooting, it is not interlocked.
4830 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4834 * Forcibly unmounting "/dev" before "/" would prevent clean
4835 * unmount of the latter.
4837 if (mp == rootdevmp)
4840 unmount_or_warn(mp);
4843 if (rootdevmp != NULL)
4844 unmount_or_warn(rootdevmp);
4848 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4851 ASSERT_VI_LOCKED(vp, __func__);
4852 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4853 if ((vp->v_iflag & VI_OWEINACT) == 0) {
4857 if (vn_lock(vp, lkflags) == 0) {
4864 vdefer_inactive_unlocked(vp);
4868 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4871 return (vp->v_iflag & VI_DEFINACT);
4874 static void __noinline
4875 vfs_periodic_inactive(struct mount *mp, int flags)
4877 struct vnode *vp, *mvp;
4880 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4881 if (flags != MNT_WAIT)
4882 lkflags |= LK_NOWAIT;
4884 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4885 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4889 vp->v_iflag &= ~VI_DEFINACT;
4890 vfs_deferred_inactive(vp, lkflags);
4895 vfs_want_msync(struct vnode *vp)
4897 struct vm_object *obj;
4900 * This test may be performed without any locks held.
4901 * We rely on vm_object's type stability.
4903 if (vp->v_vflag & VV_NOSYNC)
4906 return (obj != NULL && vm_object_mightbedirty(obj));
4910 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4913 if (vp->v_vflag & VV_NOSYNC)
4915 if (vp->v_iflag & VI_DEFINACT)
4917 return (vfs_want_msync(vp));
4920 static void __noinline
4921 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4923 struct vnode *vp, *mvp;
4924 struct vm_object *obj;
4925 int lkflags, objflags;
4928 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4929 if (flags != MNT_WAIT) {
4930 lkflags |= LK_NOWAIT;
4931 objflags = OBJPC_NOSYNC;
4933 objflags = OBJPC_SYNC;
4936 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4938 if (vp->v_iflag & VI_DEFINACT) {
4939 vp->v_iflag &= ~VI_DEFINACT;
4942 if (!vfs_want_msync(vp)) {
4944 vfs_deferred_inactive(vp, lkflags);
4949 if (vget(vp, lkflags) == 0) {
4951 if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4952 VM_OBJECT_WLOCK(obj);
4953 vm_object_page_clean(obj, 0, 0, objflags);
4954 VM_OBJECT_WUNLOCK(obj);
4961 vdefer_inactive_unlocked(vp);
4967 vfs_periodic(struct mount *mp, int flags)
4970 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4972 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4973 vfs_periodic_inactive(mp, flags);
4975 vfs_periodic_msync_inactive(mp, flags);
4979 destroy_vpollinfo_free(struct vpollinfo *vi)
4982 knlist_destroy(&vi->vpi_selinfo.si_note);
4983 mtx_destroy(&vi->vpi_lock);
4984 free(vi, M_VNODEPOLL);
4988 destroy_vpollinfo(struct vpollinfo *vi)
4991 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4992 seldrain(&vi->vpi_selinfo);
4993 destroy_vpollinfo_free(vi);
4997 * Initialize per-vnode helper structure to hold poll-related state.
5000 v_addpollinfo(struct vnode *vp)
5002 struct vpollinfo *vi;
5004 if (vp->v_pollinfo != NULL)
5006 vi = malloc(sizeof(*vi), M_VNODEPOLL, M_WAITOK | M_ZERO);
5007 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
5008 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
5009 vfs_knlunlock, vfs_knl_assert_lock);
5011 if (vp->v_pollinfo != NULL) {
5013 destroy_vpollinfo_free(vi);
5016 vp->v_pollinfo = vi;
5021 * Record a process's interest in events which might happen to
5022 * a vnode. Because poll uses the historic select-style interface
5023 * internally, this routine serves as both the ``check for any
5024 * pending events'' and the ``record my interest in future events''
5025 * functions. (These are done together, while the lock is held,
5026 * to avoid race conditions.)
5029 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
5033 mtx_lock(&vp->v_pollinfo->vpi_lock);
5034 if (vp->v_pollinfo->vpi_revents & events) {
5036 * This leaves events we are not interested
5037 * in available for the other process which
5038 * which presumably had requested them
5039 * (otherwise they would never have been
5042 events &= vp->v_pollinfo->vpi_revents;
5043 vp->v_pollinfo->vpi_revents &= ~events;
5045 mtx_unlock(&vp->v_pollinfo->vpi_lock);
5048 vp->v_pollinfo->vpi_events |= events;
5049 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
5050 mtx_unlock(&vp->v_pollinfo->vpi_lock);
5055 * Routine to create and manage a filesystem syncer vnode.
5057 #define sync_close ((int (*)(struct vop_close_args *))nullop)
5058 static int sync_fsync(struct vop_fsync_args *);
5059 static int sync_inactive(struct vop_inactive_args *);
5060 static int sync_reclaim(struct vop_reclaim_args *);
5062 static struct vop_vector sync_vnodeops = {
5063 .vop_bypass = VOP_EOPNOTSUPP,
5064 .vop_close = sync_close, /* close */
5065 .vop_fsync = sync_fsync, /* fsync */
5066 .vop_getwritemount = vop_stdgetwritemount,
5067 .vop_inactive = sync_inactive, /* inactive */
5068 .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
5069 .vop_reclaim = sync_reclaim, /* reclaim */
5070 .vop_lock1 = vop_stdlock, /* lock */
5071 .vop_unlock = vop_stdunlock, /* unlock */
5072 .vop_islocked = vop_stdislocked, /* islocked */
5074 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
5077 * Create a new filesystem syncer vnode for the specified mount point.
5080 vfs_allocate_syncvnode(struct mount *mp)
5084 static long start, incr, next;
5087 /* Allocate a new vnode */
5088 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
5090 panic("vfs_allocate_syncvnode: getnewvnode() failed");
5092 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5093 vp->v_vflag |= VV_FORCEINSMQ;
5094 error = insmntque(vp, mp);
5096 panic("vfs_allocate_syncvnode: insmntque() failed");
5097 vp->v_vflag &= ~VV_FORCEINSMQ;
5100 * Place the vnode onto the syncer worklist. We attempt to
5101 * scatter them about on the list so that they will go off
5102 * at evenly distributed times even if all the filesystems
5103 * are mounted at once.
5106 if (next == 0 || next > syncer_maxdelay) {
5110 start = syncer_maxdelay / 2;
5111 incr = syncer_maxdelay;
5117 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
5118 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
5119 mtx_lock(&sync_mtx);
5121 if (mp->mnt_syncer == NULL) {
5122 mp->mnt_syncer = vp;
5125 mtx_unlock(&sync_mtx);
5128 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5135 vfs_deallocate_syncvnode(struct mount *mp)
5139 mtx_lock(&sync_mtx);
5140 vp = mp->mnt_syncer;
5142 mp->mnt_syncer = NULL;
5143 mtx_unlock(&sync_mtx);
5149 * Do a lazy sync of the filesystem.
5152 sync_fsync(struct vop_fsync_args *ap)
5154 struct vnode *syncvp = ap->a_vp;
5155 struct mount *mp = syncvp->v_mount;
5160 * We only need to do something if this is a lazy evaluation.
5162 if (ap->a_waitfor != MNT_LAZY)
5166 * Move ourselves to the back of the sync list.
5168 bo = &syncvp->v_bufobj;
5170 vn_syncer_add_to_worklist(bo, syncdelay);
5174 * Walk the list of vnodes pushing all that are dirty and
5175 * not already on the sync list.
5177 if (vfs_busy(mp, MBF_NOWAIT) != 0)
5180 save = curthread_pflags_set(TDP_SYNCIO);
5182 * The filesystem at hand may be idle with free vnodes stored in the
5183 * batch. Return them instead of letting them stay there indefinitely.
5185 vfs_periodic(mp, MNT_NOWAIT);
5186 error = VFS_SYNC(mp, MNT_LAZY);
5187 curthread_pflags_restore(save);
5188 vn_lock(syncvp, LK_EXCLUSIVE | LK_RETRY);
5194 * The syncer vnode is no referenced.
5197 sync_inactive(struct vop_inactive_args *ap)
5205 * The syncer vnode is no longer needed and is being decommissioned.
5207 * Modifications to the worklist must be protected by sync_mtx.
5210 sync_reclaim(struct vop_reclaim_args *ap)
5212 struct vnode *vp = ap->a_vp;
5217 mtx_lock(&sync_mtx);
5218 if (vp->v_mount->mnt_syncer == vp)
5219 vp->v_mount->mnt_syncer = NULL;
5220 if (bo->bo_flag & BO_ONWORKLST) {
5221 LIST_REMOVE(bo, bo_synclist);
5222 syncer_worklist_len--;
5224 bo->bo_flag &= ~BO_ONWORKLST;
5226 mtx_unlock(&sync_mtx);
5233 vn_need_pageq_flush(struct vnode *vp)
5235 struct vm_object *obj;
5238 return (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
5239 vm_object_mightbedirty(obj));
5243 * Check if vnode represents a disk device
5246 vn_isdisk_error(struct vnode *vp, int *errp)
5250 if (vp->v_type != VCHR) {
5256 if (vp->v_rdev == NULL)
5258 else if (vp->v_rdev->si_devsw == NULL)
5260 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5265 return (error == 0);
5269 vn_isdisk(struct vnode *vp)
5273 return (vn_isdisk_error(vp, &error));
5277 * VOP_FPLOOKUP_VEXEC routines are subject to special circumstances, see
5278 * the comment above cache_fplookup for details.
5281 vaccess_vexec_smr(mode_t file_mode, uid_t file_uid, gid_t file_gid, struct ucred *cred)
5285 VFS_SMR_ASSERT_ENTERED();
5287 /* Check the owner. */
5288 if (cred->cr_uid == file_uid) {
5289 if (file_mode & S_IXUSR)
5294 /* Otherwise, check the groups (first match) */
5295 if (groupmember(file_gid, cred)) {
5296 if (file_mode & S_IXGRP)
5301 /* Otherwise, check everyone else. */
5302 if (file_mode & S_IXOTH)
5306 * Permission check failed, but it is possible denial will get overwritten
5307 * (e.g., when root is traversing through a 700 directory owned by someone
5310 * vaccess() calls priv_check_cred which in turn can descent into MAC
5311 * modules overriding this result. It's quite unclear what semantics
5312 * are allowed for them to operate, thus for safety we don't call them
5313 * from within the SMR section. This also means if any such modules
5314 * are present, we have to let the regular lookup decide.
5316 error = priv_check_cred_vfs_lookup_nomac(cred);
5322 * MAC modules present.
5333 * Common filesystem object access control check routine. Accepts a
5334 * vnode's type, "mode", uid and gid, requested access mode, and credentials.
5335 * Returns 0 on success, or an errno on failure.
5338 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5339 accmode_t accmode, struct ucred *cred)
5341 accmode_t dac_granted;
5342 accmode_t priv_granted;
5344 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5345 ("invalid bit in accmode"));
5346 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5347 ("VAPPEND without VWRITE"));
5350 * Look for a normal, non-privileged way to access the file/directory
5351 * as requested. If it exists, go with that.
5356 /* Check the owner. */
5357 if (cred->cr_uid == file_uid) {
5358 dac_granted |= VADMIN;
5359 if (file_mode & S_IXUSR)
5360 dac_granted |= VEXEC;
5361 if (file_mode & S_IRUSR)
5362 dac_granted |= VREAD;
5363 if (file_mode & S_IWUSR)
5364 dac_granted |= (VWRITE | VAPPEND);
5366 if ((accmode & dac_granted) == accmode)
5372 /* Otherwise, check the groups (first match) */
5373 if (groupmember(file_gid, cred)) {
5374 if (file_mode & S_IXGRP)
5375 dac_granted |= VEXEC;
5376 if (file_mode & S_IRGRP)
5377 dac_granted |= VREAD;
5378 if (file_mode & S_IWGRP)
5379 dac_granted |= (VWRITE | VAPPEND);
5381 if ((accmode & dac_granted) == accmode)
5387 /* Otherwise, check everyone else. */
5388 if (file_mode & S_IXOTH)
5389 dac_granted |= VEXEC;
5390 if (file_mode & S_IROTH)
5391 dac_granted |= VREAD;
5392 if (file_mode & S_IWOTH)
5393 dac_granted |= (VWRITE | VAPPEND);
5394 if ((accmode & dac_granted) == accmode)
5399 * Build a privilege mask to determine if the set of privileges
5400 * satisfies the requirements when combined with the granted mask
5401 * from above. For each privilege, if the privilege is required,
5402 * bitwise or the request type onto the priv_granted mask.
5408 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5409 * requests, instead of PRIV_VFS_EXEC.
5411 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5412 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5413 priv_granted |= VEXEC;
5416 * Ensure that at least one execute bit is on. Otherwise,
5417 * a privileged user will always succeed, and we don't want
5418 * this to happen unless the file really is executable.
5420 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5421 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5422 !priv_check_cred(cred, PRIV_VFS_EXEC))
5423 priv_granted |= VEXEC;
5426 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5427 !priv_check_cred(cred, PRIV_VFS_READ))
5428 priv_granted |= VREAD;
5430 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5431 !priv_check_cred(cred, PRIV_VFS_WRITE))
5432 priv_granted |= (VWRITE | VAPPEND);
5434 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5435 !priv_check_cred(cred, PRIV_VFS_ADMIN))
5436 priv_granted |= VADMIN;
5438 if ((accmode & (priv_granted | dac_granted)) == accmode) {
5442 return ((accmode & VADMIN) ? EPERM : EACCES);
5446 * Credential check based on process requesting service, and per-attribute
5450 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5451 struct thread *td, accmode_t accmode)
5455 * Kernel-invoked always succeeds.
5461 * Do not allow privileged processes in jail to directly manipulate
5462 * system attributes.
5464 switch (attrnamespace) {
5465 case EXTATTR_NAMESPACE_SYSTEM:
5466 /* Potentially should be: return (EPERM); */
5467 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5468 case EXTATTR_NAMESPACE_USER:
5469 return (VOP_ACCESS(vp, accmode, cred, td));
5475 #ifdef DEBUG_VFS_LOCKS
5476 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
5477 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5478 "Drop into debugger on lock violation");
5480 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
5481 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5482 0, "Check for interlock across VOPs");
5484 int vfs_badlock_print = 1; /* Print lock violations. */
5485 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5486 0, "Print lock violations");
5488 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
5489 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5490 0, "Print vnode details on lock violations");
5493 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
5494 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5495 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5499 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5503 if (vfs_badlock_backtrace)
5506 if (vfs_badlock_vnode)
5507 vn_printf(vp, "vnode ");
5508 if (vfs_badlock_print)
5509 printf("%s: %p %s\n", str, (void *)vp, msg);
5510 if (vfs_badlock_ddb)
5511 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5515 assert_vi_locked(struct vnode *vp, const char *str)
5518 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5519 vfs_badlock("interlock is not locked but should be", str, vp);
5523 assert_vi_unlocked(struct vnode *vp, const char *str)
5526 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5527 vfs_badlock("interlock is locked but should not be", str, vp);
5531 assert_vop_locked(struct vnode *vp, const char *str)
5533 if (KERNEL_PANICKED() || vp == NULL)
5537 if ((vp->v_irflag & VIRF_CROSSMP) == 0 &&
5538 witness_is_owned(&vp->v_vnlock->lock_object) == -1)
5540 int locked = VOP_ISLOCKED(vp);
5541 if (locked == 0 || locked == LK_EXCLOTHER)
5543 vfs_badlock("is not locked but should be", str, vp);
5547 assert_vop_unlocked(struct vnode *vp, const char *str)
5549 if (KERNEL_PANICKED() || vp == NULL)
5553 if ((vp->v_irflag & VIRF_CROSSMP) == 0 &&
5554 witness_is_owned(&vp->v_vnlock->lock_object) == 1)
5556 if (VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5558 vfs_badlock("is locked but should not be", str, vp);
5562 assert_vop_elocked(struct vnode *vp, const char *str)
5564 if (KERNEL_PANICKED() || vp == NULL)
5567 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5568 vfs_badlock("is not exclusive locked but should be", str, vp);
5570 #endif /* DEBUG_VFS_LOCKS */
5573 vop_rename_fail(struct vop_rename_args *ap)
5576 if (ap->a_tvp != NULL)
5578 if (ap->a_tdvp == ap->a_tvp)
5587 vop_rename_pre(void *ap)
5589 struct vop_rename_args *a = ap;
5591 #ifdef DEBUG_VFS_LOCKS
5593 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5594 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5595 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5596 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5598 /* Check the source (from). */
5599 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5600 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5601 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5602 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5603 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5605 /* Check the target. */
5607 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5608 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5611 * It may be tempting to add vn_seqc_write_begin/end calls here and
5612 * in vop_rename_post but that's not going to work out since some
5613 * filesystems relookup vnodes mid-rename. This is probably a bug.
5615 * For now filesystems are expected to do the relevant calls after they
5616 * decide what vnodes to operate on.
5618 if (a->a_tdvp != a->a_fdvp)
5620 if (a->a_tvp != a->a_fvp)
5627 #ifdef DEBUG_VFS_LOCKS
5629 vop_fplookup_vexec_debugpre(void *ap __unused)
5632 VFS_SMR_ASSERT_ENTERED();
5636 vop_fplookup_vexec_debugpost(void *ap __unused, int rc __unused)
5639 VFS_SMR_ASSERT_ENTERED();
5643 vop_fplookup_symlink_debugpre(void *ap __unused)
5646 VFS_SMR_ASSERT_ENTERED();
5650 vop_fplookup_symlink_debugpost(void *ap __unused, int rc __unused)
5653 VFS_SMR_ASSERT_ENTERED();
5657 vop_fsync_debugprepost(struct vnode *vp, const char *name)
5659 if (vp->v_type == VCHR)
5661 else if (MNT_EXTENDED_SHARED(vp->v_mount))
5662 ASSERT_VOP_LOCKED(vp, name);
5664 ASSERT_VOP_ELOCKED(vp, name);
5668 vop_fsync_debugpre(void *a)
5670 struct vop_fsync_args *ap;
5673 vop_fsync_debugprepost(ap->a_vp, "fsync");
5677 vop_fsync_debugpost(void *a, int rc __unused)
5679 struct vop_fsync_args *ap;
5682 vop_fsync_debugprepost(ap->a_vp, "fsync");
5686 vop_fdatasync_debugpre(void *a)
5688 struct vop_fdatasync_args *ap;
5691 vop_fsync_debugprepost(ap->a_vp, "fsync");
5695 vop_fdatasync_debugpost(void *a, int rc __unused)
5697 struct vop_fdatasync_args *ap;
5700 vop_fsync_debugprepost(ap->a_vp, "fsync");
5704 vop_strategy_debugpre(void *ap)
5706 struct vop_strategy_args *a;
5713 * Cluster ops lock their component buffers but not the IO container.
5715 if ((bp->b_flags & B_CLUSTER) != 0)
5718 if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5719 if (vfs_badlock_print)
5721 "VOP_STRATEGY: bp is not locked but should be\n");
5722 if (vfs_badlock_ddb)
5723 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5728 vop_lock_debugpre(void *ap)
5730 struct vop_lock1_args *a = ap;
5732 if ((a->a_flags & LK_INTERLOCK) == 0)
5733 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5735 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5739 vop_lock_debugpost(void *ap, int rc)
5741 struct vop_lock1_args *a = ap;
5743 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5744 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5745 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5749 vop_unlock_debugpre(void *ap)
5751 struct vop_unlock_args *a = ap;
5753 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5757 vop_need_inactive_debugpre(void *ap)
5759 struct vop_need_inactive_args *a = ap;
5761 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5765 vop_need_inactive_debugpost(void *ap, int rc)
5767 struct vop_need_inactive_args *a = ap;
5769 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5774 vop_create_pre(void *ap)
5776 struct vop_create_args *a;
5781 vn_seqc_write_begin(dvp);
5785 vop_create_post(void *ap, int rc)
5787 struct vop_create_args *a;
5792 vn_seqc_write_end(dvp);
5794 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5798 vop_whiteout_pre(void *ap)
5800 struct vop_whiteout_args *a;
5805 vn_seqc_write_begin(dvp);
5809 vop_whiteout_post(void *ap, int rc)
5811 struct vop_whiteout_args *a;
5816 vn_seqc_write_end(dvp);
5820 vop_deleteextattr_pre(void *ap)
5822 struct vop_deleteextattr_args *a;
5827 vn_seqc_write_begin(vp);
5831 vop_deleteextattr_post(void *ap, int rc)
5833 struct vop_deleteextattr_args *a;
5838 vn_seqc_write_end(vp);
5840 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5844 vop_link_pre(void *ap)
5846 struct vop_link_args *a;
5847 struct vnode *vp, *tdvp;
5852 vn_seqc_write_begin(vp);
5853 vn_seqc_write_begin(tdvp);
5857 vop_link_post(void *ap, int rc)
5859 struct vop_link_args *a;
5860 struct vnode *vp, *tdvp;
5865 vn_seqc_write_end(vp);
5866 vn_seqc_write_end(tdvp);
5868 VFS_KNOTE_LOCKED(vp, NOTE_LINK);
5869 VFS_KNOTE_LOCKED(tdvp, NOTE_WRITE);
5874 vop_mkdir_pre(void *ap)
5876 struct vop_mkdir_args *a;
5881 vn_seqc_write_begin(dvp);
5885 vop_mkdir_post(void *ap, int rc)
5887 struct vop_mkdir_args *a;
5892 vn_seqc_write_end(dvp);
5894 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5897 #ifdef DEBUG_VFS_LOCKS
5899 vop_mkdir_debugpost(void *ap, int rc)
5901 struct vop_mkdir_args *a;
5905 cache_validate(a->a_dvp, *a->a_vpp, a->a_cnp);
5910 vop_mknod_pre(void *ap)
5912 struct vop_mknod_args *a;
5917 vn_seqc_write_begin(dvp);
5921 vop_mknod_post(void *ap, int rc)
5923 struct vop_mknod_args *a;
5928 vn_seqc_write_end(dvp);
5930 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5934 vop_reclaim_post(void *ap, int rc)
5936 struct vop_reclaim_args *a;
5941 ASSERT_VOP_IN_SEQC(vp);
5943 VFS_KNOTE_LOCKED(vp, NOTE_REVOKE);
5947 vop_remove_pre(void *ap)
5949 struct vop_remove_args *a;
5950 struct vnode *dvp, *vp;
5955 vn_seqc_write_begin(dvp);
5956 vn_seqc_write_begin(vp);
5960 vop_remove_post(void *ap, int rc)
5962 struct vop_remove_args *a;
5963 struct vnode *dvp, *vp;
5968 vn_seqc_write_end(dvp);
5969 vn_seqc_write_end(vp);
5971 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5972 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5977 vop_rename_post(void *ap, int rc)
5979 struct vop_rename_args *a = ap;
5984 if (a->a_fdvp == a->a_tdvp) {
5985 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5987 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5988 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5990 hint |= NOTE_EXTEND;
5991 if (a->a_fvp->v_type == VDIR)
5993 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5995 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5996 a->a_tvp->v_type == VDIR)
5998 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
6001 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
6003 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
6005 if (a->a_tdvp != a->a_fdvp)
6007 if (a->a_tvp != a->a_fvp)
6015 vop_rmdir_pre(void *ap)
6017 struct vop_rmdir_args *a;
6018 struct vnode *dvp, *vp;
6023 vn_seqc_write_begin(dvp);
6024 vn_seqc_write_begin(vp);
6028 vop_rmdir_post(void *ap, int rc)
6030 struct vop_rmdir_args *a;
6031 struct vnode *dvp, *vp;
6036 vn_seqc_write_end(dvp);
6037 vn_seqc_write_end(vp);
6039 vp->v_vflag |= VV_UNLINKED;
6040 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
6041 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
6046 vop_setattr_pre(void *ap)
6048 struct vop_setattr_args *a;
6053 vn_seqc_write_begin(vp);
6057 vop_setattr_post(void *ap, int rc)
6059 struct vop_setattr_args *a;
6064 vn_seqc_write_end(vp);
6066 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6070 vop_setacl_pre(void *ap)
6072 struct vop_setacl_args *a;
6077 vn_seqc_write_begin(vp);
6081 vop_setacl_post(void *ap, int rc __unused)
6083 struct vop_setacl_args *a;
6088 vn_seqc_write_end(vp);
6092 vop_setextattr_pre(void *ap)
6094 struct vop_setextattr_args *a;
6099 vn_seqc_write_begin(vp);
6103 vop_setextattr_post(void *ap, int rc)
6105 struct vop_setextattr_args *a;
6110 vn_seqc_write_end(vp);
6112 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6116 vop_symlink_pre(void *ap)
6118 struct vop_symlink_args *a;
6123 vn_seqc_write_begin(dvp);
6127 vop_symlink_post(void *ap, int rc)
6129 struct vop_symlink_args *a;
6134 vn_seqc_write_end(dvp);
6136 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6140 vop_open_post(void *ap, int rc)
6142 struct vop_open_args *a = ap;
6145 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
6149 vop_close_post(void *ap, int rc)
6151 struct vop_close_args *a = ap;
6153 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
6154 !VN_IS_DOOMED(a->a_vp))) {
6155 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
6156 NOTE_CLOSE_WRITE : NOTE_CLOSE);
6161 vop_read_post(void *ap, int rc)
6163 struct vop_read_args *a = ap;
6166 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6170 vop_read_pgcache_post(void *ap, int rc)
6172 struct vop_read_pgcache_args *a = ap;
6175 VFS_KNOTE_UNLOCKED(a->a_vp, NOTE_READ);
6179 vop_readdir_post(void *ap, int rc)
6181 struct vop_readdir_args *a = ap;
6184 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6187 static struct knlist fs_knlist;
6190 vfs_event_init(void *arg)
6192 knlist_init_mtx(&fs_knlist, NULL);
6194 /* XXX - correct order? */
6195 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
6198 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
6201 KNOTE_UNLOCKED(&fs_knlist, event);
6204 static int filt_fsattach(struct knote *kn);
6205 static void filt_fsdetach(struct knote *kn);
6206 static int filt_fsevent(struct knote *kn, long hint);
6208 struct filterops fs_filtops = {
6210 .f_attach = filt_fsattach,
6211 .f_detach = filt_fsdetach,
6212 .f_event = filt_fsevent
6216 filt_fsattach(struct knote *kn)
6219 kn->kn_flags |= EV_CLEAR;
6220 knlist_add(&fs_knlist, kn, 0);
6225 filt_fsdetach(struct knote *kn)
6228 knlist_remove(&fs_knlist, kn, 0);
6232 filt_fsevent(struct knote *kn, long hint)
6235 kn->kn_fflags |= hint;
6236 return (kn->kn_fflags != 0);
6240 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
6246 error = SYSCTL_IN(req, &vc, sizeof(vc));
6249 if (vc.vc_vers != VFS_CTL_VERS1)
6251 mp = vfs_getvfs(&vc.vc_fsid);
6254 /* ensure that a specific sysctl goes to the right filesystem. */
6255 if (strcmp(vc.vc_fstypename, "*") != 0 &&
6256 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
6260 VCTLTOREQ(&vc, req);
6261 error = VFS_SYSCTL(mp, vc.vc_op, req);
6266 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
6267 NULL, 0, sysctl_vfs_ctl, "",
6271 * Function to initialize a va_filerev field sensibly.
6272 * XXX: Wouldn't a random number make a lot more sense ??
6275 init_va_filerev(void)
6280 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
6283 static int filt_vfsread(struct knote *kn, long hint);
6284 static int filt_vfswrite(struct knote *kn, long hint);
6285 static int filt_vfsvnode(struct knote *kn, long hint);
6286 static void filt_vfsdetach(struct knote *kn);
6287 static struct filterops vfsread_filtops = {
6289 .f_detach = filt_vfsdetach,
6290 .f_event = filt_vfsread
6292 static struct filterops vfswrite_filtops = {
6294 .f_detach = filt_vfsdetach,
6295 .f_event = filt_vfswrite
6297 static struct filterops vfsvnode_filtops = {
6299 .f_detach = filt_vfsdetach,
6300 .f_event = filt_vfsvnode
6304 vfs_knllock(void *arg)
6306 struct vnode *vp = arg;
6308 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
6312 vfs_knlunlock(void *arg)
6314 struct vnode *vp = arg;
6320 vfs_knl_assert_lock(void *arg, int what)
6322 #ifdef DEBUG_VFS_LOCKS
6323 struct vnode *vp = arg;
6325 if (what == LA_LOCKED)
6326 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
6328 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
6333 vfs_kqfilter(struct vop_kqfilter_args *ap)
6335 struct vnode *vp = ap->a_vp;
6336 struct knote *kn = ap->a_kn;
6339 switch (kn->kn_filter) {
6341 kn->kn_fop = &vfsread_filtops;
6344 kn->kn_fop = &vfswrite_filtops;
6347 kn->kn_fop = &vfsvnode_filtops;
6353 kn->kn_hook = (caddr_t)vp;
6356 if (vp->v_pollinfo == NULL)
6358 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
6360 knlist_add(knl, kn, 0);
6366 * Detach knote from vnode
6369 filt_vfsdetach(struct knote *kn)
6371 struct vnode *vp = (struct vnode *)kn->kn_hook;
6373 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
6374 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
6380 filt_vfsread(struct knote *kn, long hint)
6382 struct vnode *vp = (struct vnode *)kn->kn_hook;
6387 * filesystem is gone, so set the EOF flag and schedule
6388 * the knote for deletion.
6390 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6392 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6397 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
6401 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
6402 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
6409 filt_vfswrite(struct knote *kn, long hint)
6411 struct vnode *vp = (struct vnode *)kn->kn_hook;
6416 * filesystem is gone, so set the EOF flag and schedule
6417 * the knote for deletion.
6419 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
6420 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6428 filt_vfsvnode(struct knote *kn, long hint)
6430 struct vnode *vp = (struct vnode *)kn->kn_hook;
6434 if (kn->kn_sfflags & hint)
6435 kn->kn_fflags |= hint;
6436 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6437 kn->kn_flags |= EV_EOF;
6441 res = (kn->kn_fflags != 0);
6447 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6451 if (dp->d_reclen > ap->a_uio->uio_resid)
6452 return (ENAMETOOLONG);
6453 error = uiomove(dp, dp->d_reclen, ap->a_uio);
6455 if (ap->a_ncookies != NULL) {
6456 if (ap->a_cookies != NULL)
6457 free(ap->a_cookies, M_TEMP);
6458 ap->a_cookies = NULL;
6459 *ap->a_ncookies = 0;
6463 if (ap->a_ncookies == NULL)
6466 KASSERT(ap->a_cookies,
6467 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6469 *ap->a_cookies = realloc(*ap->a_cookies,
6470 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
6471 (*ap->a_cookies)[*ap->a_ncookies] = off;
6472 *ap->a_ncookies += 1;
6477 * The purpose of this routine is to remove granularity from accmode_t,
6478 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6479 * VADMIN and VAPPEND.
6481 * If it returns 0, the caller is supposed to continue with the usual
6482 * access checks using 'accmode' as modified by this routine. If it
6483 * returns nonzero value, the caller is supposed to return that value
6486 * Note that after this routine runs, accmode may be zero.
6489 vfs_unixify_accmode(accmode_t *accmode)
6492 * There is no way to specify explicit "deny" rule using
6493 * file mode or POSIX.1e ACLs.
6495 if (*accmode & VEXPLICIT_DENY) {
6501 * None of these can be translated into usual access bits.
6502 * Also, the common case for NFSv4 ACLs is to not contain
6503 * either of these bits. Caller should check for VWRITE
6504 * on the containing directory instead.
6506 if (*accmode & (VDELETE_CHILD | VDELETE))
6509 if (*accmode & VADMIN_PERMS) {
6510 *accmode &= ~VADMIN_PERMS;
6515 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6516 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6518 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6524 * Clear out a doomed vnode (if any) and replace it with a new one as long
6525 * as the fs is not being unmounted. Return the root vnode to the caller.
6527 static int __noinline
6528 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6534 if (mp->mnt_rootvnode != NULL) {
6536 vp = mp->mnt_rootvnode;
6538 if (!VN_IS_DOOMED(vp)) {
6541 error = vn_lock(vp, flags);
6550 * Clear the old one.
6552 mp->mnt_rootvnode = NULL;
6556 vfs_op_barrier_wait(mp);
6560 error = VFS_CACHEDROOT(mp, flags, vpp);
6563 if (mp->mnt_vfs_ops == 0) {
6565 if (mp->mnt_vfs_ops != 0) {
6569 if (mp->mnt_rootvnode == NULL) {
6571 mp->mnt_rootvnode = *vpp;
6573 if (mp->mnt_rootvnode != *vpp) {
6574 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6575 panic("%s: mismatch between vnode returned "
6576 " by VFS_CACHEDROOT and the one cached "
6578 __func__, *vpp, mp->mnt_rootvnode);
6588 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6590 struct mount_pcpu *mpcpu;
6594 if (!vfs_op_thread_enter(mp, mpcpu))
6595 return (vfs_cache_root_fallback(mp, flags, vpp));
6596 vp = atomic_load_ptr(&mp->mnt_rootvnode);
6597 if (vp == NULL || VN_IS_DOOMED(vp)) {
6598 vfs_op_thread_exit(mp, mpcpu);
6599 return (vfs_cache_root_fallback(mp, flags, vpp));
6602 vfs_op_thread_exit(mp, mpcpu);
6603 error = vn_lock(vp, flags);
6606 return (vfs_cache_root_fallback(mp, flags, vpp));
6613 vfs_cache_root_clear(struct mount *mp)
6618 * ops > 0 guarantees there is nobody who can see this vnode
6620 MPASS(mp->mnt_vfs_ops > 0);
6621 vp = mp->mnt_rootvnode;
6623 vn_seqc_write_begin(vp);
6624 mp->mnt_rootvnode = NULL;
6629 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6632 MPASS(mp->mnt_vfs_ops > 0);
6634 mp->mnt_rootvnode = vp;
6638 * These are helper functions for filesystems to traverse all
6639 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6641 * This interface replaces MNT_VNODE_FOREACH.
6645 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6651 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6652 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6653 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6654 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6655 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6658 if (VN_IS_DOOMED(vp)) {
6665 __mnt_vnode_markerfree_all(mvp, mp);
6666 /* MNT_IUNLOCK(mp); -- done in above function */
6667 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6670 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6671 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6677 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6681 *mvp = vn_alloc_marker(mp);
6685 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6686 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6687 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6690 if (VN_IS_DOOMED(vp)) {
6699 vn_free_marker(*mvp);
6703 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6709 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6717 mtx_assert(MNT_MTX(mp), MA_OWNED);
6719 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6720 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6723 vn_free_marker(*mvp);
6728 * These are helper functions for filesystems to traverse their
6729 * lazy vnodes. See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6732 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6735 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6740 vn_free_marker(*mvp);
6745 * Relock the mp mount vnode list lock with the vp vnode interlock in the
6746 * conventional lock order during mnt_vnode_next_lazy iteration.
6748 * On entry, the mount vnode list lock is held and the vnode interlock is not.
6749 * The list lock is dropped and reacquired. On success, both locks are held.
6750 * On failure, the mount vnode list lock is held but the vnode interlock is
6751 * not, and the procedure may have yielded.
6754 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6758 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6759 TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6760 ("%s: bad marker", __func__));
6761 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6762 ("%s: inappropriate vnode", __func__));
6763 ASSERT_VI_UNLOCKED(vp, __func__);
6764 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6766 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6767 TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6770 * Note we may be racing against vdrop which transitioned the hold
6771 * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
6772 * if we are the only user after we get the interlock we will just
6776 mtx_unlock(&mp->mnt_listmtx);
6778 if (VN_IS_DOOMED(vp)) {
6779 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
6782 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
6784 * There is nothing to do if we are the last user.
6786 if (!refcount_release_if_not_last(&vp->v_holdcnt))
6788 mtx_lock(&mp->mnt_listmtx);
6793 mtx_lock(&mp->mnt_listmtx);
6797 static struct vnode *
6798 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6803 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6804 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6806 vp = TAILQ_NEXT(*mvp, v_lazylist);
6807 while (vp != NULL) {
6808 if (vp->v_type == VMARKER) {
6809 vp = TAILQ_NEXT(vp, v_lazylist);
6813 * See if we want to process the vnode. Note we may encounter a
6814 * long string of vnodes we don't care about and hog the list
6815 * as a result. Check for it and requeue the marker.
6817 VNPASS(!VN_IS_DOOMED(vp), vp);
6818 if (!cb(vp, cbarg)) {
6819 if (!should_yield()) {
6820 vp = TAILQ_NEXT(vp, v_lazylist);
6823 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6825 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6827 mtx_unlock(&mp->mnt_listmtx);
6828 kern_yield(PRI_USER);
6829 mtx_lock(&mp->mnt_listmtx);
6833 * Try-lock because this is the wrong lock order.
6835 if (!VI_TRYLOCK(vp) &&
6836 !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6838 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6839 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6840 ("alien vnode on the lazy list %p %p", vp, mp));
6841 VNPASS(vp->v_mount == mp, vp);
6842 VNPASS(!VN_IS_DOOMED(vp), vp);
6845 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6847 /* Check if we are done */
6849 mtx_unlock(&mp->mnt_listmtx);
6850 mnt_vnode_markerfree_lazy(mvp, mp);
6853 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6854 mtx_unlock(&mp->mnt_listmtx);
6855 ASSERT_VI_LOCKED(vp, "lazy iter");
6860 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6865 mtx_lock(&mp->mnt_listmtx);
6866 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6870 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6875 if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
6878 *mvp = vn_alloc_marker(mp);
6883 mtx_lock(&mp->mnt_listmtx);
6884 vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6886 mtx_unlock(&mp->mnt_listmtx);
6887 mnt_vnode_markerfree_lazy(mvp, mp);
6890 TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6891 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6895 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6901 mtx_lock(&mp->mnt_listmtx);
6902 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6903 mtx_unlock(&mp->mnt_listmtx);
6904 mnt_vnode_markerfree_lazy(mvp, mp);
6908 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
6911 if ((cnp->cn_flags & NOEXECCHECK) != 0) {
6912 cnp->cn_flags &= ~NOEXECCHECK;
6916 return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, cnp->cn_thread));
6920 * Do not use this variant unless you have means other than the hold count
6921 * to prevent the vnode from getting freed.
6924 vn_seqc_write_begin_locked(struct vnode *vp)
6927 ASSERT_VI_LOCKED(vp, __func__);
6928 VNPASS(vp->v_holdcnt > 0, vp);
6929 VNPASS(vp->v_seqc_users >= 0, vp);
6931 if (vp->v_seqc_users == 1)
6932 seqc_sleepable_write_begin(&vp->v_seqc);
6936 vn_seqc_write_begin(struct vnode *vp)
6940 vn_seqc_write_begin_locked(vp);
6945 vn_seqc_write_end_locked(struct vnode *vp)
6948 ASSERT_VI_LOCKED(vp, __func__);
6949 VNPASS(vp->v_seqc_users > 0, vp);
6951 if (vp->v_seqc_users == 0)
6952 seqc_sleepable_write_end(&vp->v_seqc);
6956 vn_seqc_write_end(struct vnode *vp)
6960 vn_seqc_write_end_locked(vp);
6965 * Special case handling for allocating and freeing vnodes.
6967 * The counter remains unchanged on free so that a doomed vnode will
6968 * keep testing as in modify as long as it is accessible with SMR.
6971 vn_seqc_init(struct vnode *vp)
6975 vp->v_seqc_users = 0;
6979 vn_seqc_write_end_free(struct vnode *vp)
6982 VNPASS(seqc_in_modify(vp->v_seqc), vp);
6983 VNPASS(vp->v_seqc_users == 1, vp);
6987 vn_irflag_set_locked(struct vnode *vp, short toset)
6991 ASSERT_VI_LOCKED(vp, __func__);
6992 flags = vn_irflag_read(vp);
6993 VNASSERT((flags & toset) == 0, vp,
6994 ("%s: some of the passed flags already set (have %d, passed %d)\n",
6995 __func__, flags, toset));
6996 atomic_store_short(&vp->v_irflag, flags | toset);
7000 vn_irflag_set(struct vnode *vp, short toset)
7004 vn_irflag_set_locked(vp, toset);
7009 vn_irflag_set_cond_locked(struct vnode *vp, short toset)
7013 ASSERT_VI_LOCKED(vp, __func__);
7014 flags = vn_irflag_read(vp);
7015 atomic_store_short(&vp->v_irflag, flags | toset);
7019 vn_irflag_set_cond(struct vnode *vp, short toset)
7023 vn_irflag_set_cond_locked(vp, toset);
7028 vn_irflag_unset_locked(struct vnode *vp, short tounset)
7032 ASSERT_VI_LOCKED(vp, __func__);
7033 flags = vn_irflag_read(vp);
7034 VNASSERT((flags & tounset) == tounset, vp,
7035 ("%s: some of the passed flags not set (have %d, passed %d)\n",
7036 __func__, flags, tounset));
7037 atomic_store_short(&vp->v_irflag, flags & ~tounset);
7041 vn_irflag_unset(struct vnode *vp, short tounset)
7045 vn_irflag_unset_locked(vp, tounset);