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>
45 #include "opt_watchdog.h"
47 #include <sys/param.h>
48 #include <sys/systm.h>
52 #include <sys/capsicum.h>
53 #include <sys/condvar.h>
55 #include <sys/counter.h>
56 #include <sys/dirent.h>
57 #include <sys/event.h>
58 #include <sys/eventhandler.h>
59 #include <sys/extattr.h>
61 #include <sys/fcntl.h>
64 #include <sys/kernel.h>
65 #include <sys/kthread.h>
67 #include <sys/lockf.h>
68 #include <sys/malloc.h>
69 #include <sys/mount.h>
70 #include <sys/namei.h>
71 #include <sys/pctrie.h>
73 #include <sys/reboot.h>
74 #include <sys/refcount.h>
75 #include <sys/rwlock.h>
76 #include <sys/sched.h>
77 #include <sys/sleepqueue.h>
81 #include <sys/sysctl.h>
82 #include <sys/syslog.h>
83 #include <sys/vmmeter.h>
84 #include <sys/vnode.h>
85 #include <sys/watchdog.h>
87 #include <machine/stdarg.h>
89 #include <security/mac/mac_framework.h>
92 #include <vm/vm_object.h>
93 #include <vm/vm_extern.h>
95 #include <vm/vm_map.h>
96 #include <vm/vm_page.h>
97 #include <vm/vm_kern.h>
100 #if defined(DEBUG_VFS_LOCKS) && (!defined(INVARIANTS) || !defined(WITNESS))
101 #error DEBUG_VFS_LOCKS requires INVARIANTS and WITNESS
108 static void delmntque(struct vnode *vp);
109 static int flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
110 int slpflag, int slptimeo);
111 static void syncer_shutdown(void *arg, int howto);
112 static int vtryrecycle(struct vnode *vp);
113 static void v_init_counters(struct vnode *);
114 static void vn_seqc_init(struct vnode *);
115 static void vn_seqc_write_end_free(struct vnode *vp);
116 static void vgonel(struct vnode *);
117 static bool vhold_recycle_free(struct vnode *);
118 static void vdropl_recycle(struct vnode *vp);
119 static void vdrop_recycle(struct vnode *vp);
120 static void vfs_knllock(void *arg);
121 static void vfs_knlunlock(void *arg);
122 static void vfs_knl_assert_lock(void *arg, int what);
123 static void destroy_vpollinfo(struct vpollinfo *vi);
124 static int v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
125 daddr_t startlbn, daddr_t endlbn);
126 static void vnlru_recalc(void);
129 * Number of vnodes in existence. Increased whenever getnewvnode()
130 * allocates a new vnode, decreased in vdropl() for VIRF_DOOMED vnode.
132 static u_long __exclusive_cache_line numvnodes;
134 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
135 "Number of vnodes in existence");
137 static counter_u64_t vnodes_created;
138 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
139 "Number of vnodes created by getnewvnode");
142 * Conversion tables for conversion from vnode types to inode formats
145 enum vtype iftovt_tab[16] = {
146 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
147 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
149 int vttoif_tab[10] = {
150 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
151 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
155 * List of allocates vnodes in the system.
157 static TAILQ_HEAD(freelst, vnode) vnode_list;
158 static struct vnode *vnode_list_free_marker;
159 static struct vnode *vnode_list_reclaim_marker;
162 * "Free" vnode target. Free vnodes are rarely completely free, but are
163 * just ones that are cheap to recycle. Usually they are for files which
164 * have been stat'd but not read; these usually have inode and namecache
165 * data attached to them. This target is the preferred minimum size of a
166 * sub-cache consisting mostly of such files. The system balances the size
167 * of this sub-cache with its complement to try to prevent either from
168 * thrashing while the other is relatively inactive. The targets express
169 * a preference for the best balance.
171 * "Above" this target there are 2 further targets (watermarks) related
172 * to recyling of free vnodes. In the best-operating case, the cache is
173 * exactly full, the free list has size between vlowat and vhiwat above the
174 * free target, and recycling from it and normal use maintains this state.
175 * Sometimes the free list is below vlowat or even empty, but this state
176 * is even better for immediate use provided the cache is not full.
177 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
178 * ones) to reach one of these states. The watermarks are currently hard-
179 * coded as 4% and 9% of the available space higher. These and the default
180 * of 25% for wantfreevnodes are too large if the memory size is large.
181 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
182 * whenever vnlru_proc() becomes active.
184 static long wantfreevnodes;
185 static long __exclusive_cache_line freevnodes;
186 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
187 &freevnodes, 0, "Number of \"free\" vnodes");
188 static long freevnodes_old;
190 static counter_u64_t recycles_count;
191 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
192 "Number of vnodes recycled to meet vnode cache targets");
194 static counter_u64_t recycles_free_count;
195 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD, &recycles_free_count,
196 "Number of free vnodes recycled to meet vnode cache targets");
198 static counter_u64_t deferred_inact;
199 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, deferred_inact, CTLFLAG_RD, &deferred_inact,
200 "Number of times inactive processing was deferred");
202 /* To keep more than one thread at a time from running vfs_getnewfsid */
203 static struct mtx mntid_mtx;
206 * Lock for any access to the following:
211 static struct mtx __exclusive_cache_line vnode_list_mtx;
213 /* Publicly exported FS */
214 struct nfs_public nfs_pub;
216 static uma_zone_t buf_trie_zone;
217 static smr_t buf_trie_smr;
219 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
220 static uma_zone_t vnode_zone;
221 MALLOC_DEFINE(M_VNODEPOLL, "VN POLL", "vnode poll");
223 __read_frequently smr_t vfs_smr;
226 * The workitem queue.
228 * It is useful to delay writes of file data and filesystem metadata
229 * for tens of seconds so that quickly created and deleted files need
230 * not waste disk bandwidth being created and removed. To realize this,
231 * we append vnodes to a "workitem" queue. When running with a soft
232 * updates implementation, most pending metadata dependencies should
233 * not wait for more than a few seconds. Thus, mounted on block devices
234 * are delayed only about a half the time that file data is delayed.
235 * Similarly, directory updates are more critical, so are only delayed
236 * about a third the time that file data is delayed. Thus, there are
237 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
238 * one each second (driven off the filesystem syncer process). The
239 * syncer_delayno variable indicates the next queue that is to be processed.
240 * Items that need to be processed soon are placed in this queue:
242 * syncer_workitem_pending[syncer_delayno]
244 * A delay of fifteen seconds is done by placing the request fifteen
245 * entries later in the queue:
247 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
250 static int syncer_delayno;
251 static long syncer_mask;
252 LIST_HEAD(synclist, bufobj);
253 static struct synclist *syncer_workitem_pending;
255 * The sync_mtx protects:
260 * syncer_workitem_pending
261 * syncer_worklist_len
264 static struct mtx sync_mtx;
265 static struct cv sync_wakeup;
267 #define SYNCER_MAXDELAY 32
268 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
269 static int syncdelay = 30; /* max time to delay syncing data */
270 static int filedelay = 30; /* time to delay syncing files */
271 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
272 "Time to delay syncing files (in seconds)");
273 static int dirdelay = 29; /* time to delay syncing directories */
274 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
275 "Time to delay syncing directories (in seconds)");
276 static int metadelay = 28; /* time to delay syncing metadata */
277 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
278 "Time to delay syncing metadata (in seconds)");
279 static int rushjob; /* number of slots to run ASAP */
280 static int stat_rush_requests; /* number of times I/O speeded up */
281 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
282 "Number of times I/O speeded up (rush requests)");
284 #define VDBATCH_SIZE 8
289 struct vnode *tab[VDBATCH_SIZE];
291 DPCPU_DEFINE_STATIC(struct vdbatch, vd);
293 static void vdbatch_dequeue(struct vnode *vp);
296 * When shutting down the syncer, run it at four times normal speed.
298 #define SYNCER_SHUTDOWN_SPEEDUP 4
299 static int sync_vnode_count;
300 static int syncer_worklist_len;
301 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
304 /* Target for maximum number of vnodes. */
305 u_long desiredvnodes;
306 static u_long gapvnodes; /* gap between wanted and desired */
307 static u_long vhiwat; /* enough extras after expansion */
308 static u_long vlowat; /* minimal extras before expansion */
309 static u_long vstir; /* nonzero to stir non-free vnodes */
310 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
312 static u_long vnlru_read_freevnodes(void);
315 * Note that no attempt is made to sanitize these parameters.
318 sysctl_maxvnodes(SYSCTL_HANDLER_ARGS)
324 error = sysctl_handle_long(oidp, &val, 0, req);
325 if (error != 0 || req->newptr == NULL)
328 if (val == desiredvnodes)
330 mtx_lock(&vnode_list_mtx);
332 wantfreevnodes = desiredvnodes / 4;
334 mtx_unlock(&vnode_list_mtx);
336 * XXX There is no protection against multiple threads changing
337 * desiredvnodes at the same time. Locking above only helps vnlru and
340 vfs_hash_changesize(desiredvnodes);
341 cache_changesize(desiredvnodes);
345 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
346 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
347 "LU", "Target for maximum number of vnodes");
350 sysctl_wantfreevnodes(SYSCTL_HANDLER_ARGS)
355 val = wantfreevnodes;
356 error = sysctl_handle_long(oidp, &val, 0, req);
357 if (error != 0 || req->newptr == NULL)
360 if (val == wantfreevnodes)
362 mtx_lock(&vnode_list_mtx);
363 wantfreevnodes = val;
365 mtx_unlock(&vnode_list_mtx);
369 SYSCTL_PROC(_vfs, OID_AUTO, wantfreevnodes,
370 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
371 "LU", "Target for minimum number of \"free\" vnodes");
373 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
374 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
375 static int vnlru_nowhere;
376 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
377 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
380 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
385 unsigned long ndflags;
388 if (req->newptr == NULL)
390 if (req->newlen >= PATH_MAX)
393 buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
394 error = SYSCTL_IN(req, buf, req->newlen);
398 buf[req->newlen] = '\0';
400 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | SAVENAME;
401 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
402 if ((error = namei(&nd)) != 0)
406 if (VN_IS_DOOMED(vp)) {
408 * This vnode is being recycled. Return != 0 to let the caller
409 * know that the sysctl had no effect. Return EAGAIN because a
410 * subsequent call will likely succeed (since namei will create
411 * a new vnode if necessary)
417 counter_u64_add(recycles_count, 1);
427 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
429 struct thread *td = curthread;
435 if (req->newptr == NULL)
438 error = sysctl_handle_int(oidp, &fd, 0, req);
441 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
446 error = vn_lock(vp, LK_EXCLUSIVE);
450 counter_u64_add(recycles_count, 1);
458 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
459 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
460 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
461 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
462 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
463 sysctl_ftry_reclaim_vnode, "I",
464 "Try to reclaim a vnode by its file descriptor");
466 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
470 * Support for the bufobj clean & dirty pctrie.
473 buf_trie_alloc(struct pctrie *ptree)
475 return (uma_zalloc_smr(buf_trie_zone, M_NOWAIT));
479 buf_trie_free(struct pctrie *ptree, void *node)
481 uma_zfree_smr(buf_trie_zone, node);
483 PCTRIE_DEFINE_SMR(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free,
487 * Initialize the vnode management data structures.
489 * Reevaluate the following cap on the number of vnodes after the physical
490 * memory size exceeds 512GB. In the limit, as the physical memory size
491 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
493 #ifndef MAXVNODES_MAX
494 #define MAXVNODES_MAX (512UL * 1024 * 1024 / 64) /* 8M */
497 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
499 static struct vnode *
500 vn_alloc_marker(struct mount *mp)
504 vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
505 vp->v_type = VMARKER;
512 vn_free_marker(struct vnode *vp)
515 MPASS(vp->v_type == VMARKER);
516 free(vp, M_VNODE_MARKER);
521 vnode_ctor(void *mem, int size, void *arg __unused, int flags __unused)
523 kasan_mark(mem, size, roundup2(size, UMA_ALIGN_PTR + 1), 0);
528 vnode_dtor(void *mem, int size, void *arg __unused)
530 size_t end1, end2, off1, off2;
532 _Static_assert(offsetof(struct vnode, v_vnodelist) <
533 offsetof(struct vnode, v_dbatchcpu),
534 "KASAN marks require updating");
536 off1 = offsetof(struct vnode, v_vnodelist);
537 off2 = offsetof(struct vnode, v_dbatchcpu);
538 end1 = off1 + sizeof(((struct vnode *)NULL)->v_vnodelist);
539 end2 = off2 + sizeof(((struct vnode *)NULL)->v_dbatchcpu);
542 * Access to the v_vnodelist and v_dbatchcpu fields are permitted even
543 * after the vnode has been freed. Try to get some KASAN coverage by
544 * marking everything except those two fields as invalid. Because
545 * KASAN's tracking is not byte-granular, any preceding fields sharing
546 * the same 8-byte aligned word must also be marked valid.
549 /* Handle the area from the start until v_vnodelist... */
550 off1 = rounddown2(off1, KASAN_SHADOW_SCALE);
551 kasan_mark(mem, off1, off1, KASAN_UMA_FREED);
553 /* ... then the area between v_vnodelist and v_dbatchcpu ... */
554 off1 = roundup2(end1, KASAN_SHADOW_SCALE);
555 off2 = rounddown2(off2, KASAN_SHADOW_SCALE);
557 kasan_mark((void *)((char *)mem + off1), off2 - off1,
558 off2 - off1, KASAN_UMA_FREED);
560 /* ... and finally the area from v_dbatchcpu to the end. */
561 off2 = roundup2(end2, KASAN_SHADOW_SCALE);
562 kasan_mark((void *)((char *)mem + off2), size - off2, size - off2,
568 * Initialize a vnode as it first enters the zone.
571 vnode_init(void *mem, int size, int flags)
580 vp->v_vnlock = &vp->v_lock;
581 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
583 * By default, don't allow shared locks unless filesystems opt-in.
585 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
586 LK_NOSHARE | LK_IS_VNODE);
590 bufobj_init(&vp->v_bufobj, vp);
592 * Initialize namecache.
594 cache_vnode_init(vp);
596 * Initialize rangelocks.
598 rangelock_init(&vp->v_rl);
600 vp->v_dbatchcpu = NOCPU;
603 * Check vhold_recycle_free for an explanation.
605 vp->v_holdcnt = VHOLD_NO_SMR;
607 mtx_lock(&vnode_list_mtx);
608 TAILQ_INSERT_BEFORE(vnode_list_free_marker, vp, v_vnodelist);
609 mtx_unlock(&vnode_list_mtx);
614 * Free a vnode when it is cleared from the zone.
617 vnode_fini(void *mem, int size)
624 mtx_lock(&vnode_list_mtx);
625 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
626 mtx_unlock(&vnode_list_mtx);
627 rangelock_destroy(&vp->v_rl);
628 lockdestroy(vp->v_vnlock);
629 mtx_destroy(&vp->v_interlock);
631 rw_destroy(BO_LOCKPTR(bo));
633 kasan_mark(mem, size, size, 0);
637 * Provide the size of NFS nclnode and NFS fh for calculation of the
638 * vnode memory consumption. The size is specified directly to
639 * eliminate dependency on NFS-private header.
641 * Other filesystems may use bigger or smaller (like UFS and ZFS)
642 * private inode data, but the NFS-based estimation is ample enough.
643 * Still, we care about differences in the size between 64- and 32-bit
646 * Namecache structure size is heuristically
647 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
650 #define NFS_NCLNODE_SZ (528 + 64)
653 #define NFS_NCLNODE_SZ (360 + 32)
658 vntblinit(void *dummy __unused)
663 int cpu, physvnodes, virtvnodes;
667 * Desiredvnodes is a function of the physical memory size and the
668 * kernel's heap size. Generally speaking, it scales with the
669 * physical memory size. The ratio of desiredvnodes to the physical
670 * memory size is 1:16 until desiredvnodes exceeds 98,304.
672 * marginal ratio of desiredvnodes to the physical memory size is
673 * 1:64. However, desiredvnodes is limited by the kernel's heap
674 * size. The memory required by desiredvnodes vnodes and vm objects
675 * must not exceed 1/10th of the kernel's heap size.
677 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
678 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
679 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
680 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
681 desiredvnodes = min(physvnodes, virtvnodes);
682 if (desiredvnodes > MAXVNODES_MAX) {
684 printf("Reducing kern.maxvnodes %lu -> %lu\n",
685 desiredvnodes, MAXVNODES_MAX);
686 desiredvnodes = MAXVNODES_MAX;
688 wantfreevnodes = desiredvnodes / 4;
689 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
690 TAILQ_INIT(&vnode_list);
691 mtx_init(&vnode_list_mtx, "vnode_list", NULL, MTX_DEF);
693 * The lock is taken to appease WITNESS.
695 mtx_lock(&vnode_list_mtx);
697 mtx_unlock(&vnode_list_mtx);
698 vnode_list_free_marker = vn_alloc_marker(NULL);
699 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_free_marker, v_vnodelist);
700 vnode_list_reclaim_marker = vn_alloc_marker(NULL);
701 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_reclaim_marker, v_vnodelist);
710 vnode_zone = uma_zcreate("VNODE", sizeof(struct vnode), ctor, dtor,
711 vnode_init, vnode_fini, UMA_ALIGN_PTR, UMA_ZONE_NOKASAN);
712 uma_zone_set_smr(vnode_zone, vfs_smr);
715 * Preallocate enough nodes to support one-per buf so that
716 * we can not fail an insert. reassignbuf() callers can not
717 * tolerate the insertion failure.
719 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
720 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
721 UMA_ZONE_NOFREE | UMA_ZONE_SMR);
722 buf_trie_smr = uma_zone_get_smr(buf_trie_zone);
723 uma_prealloc(buf_trie_zone, nbuf);
725 vnodes_created = counter_u64_alloc(M_WAITOK);
726 recycles_count = counter_u64_alloc(M_WAITOK);
727 recycles_free_count = counter_u64_alloc(M_WAITOK);
728 deferred_inact = counter_u64_alloc(M_WAITOK);
731 * Initialize the filesystem syncer.
733 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
735 syncer_maxdelay = syncer_mask + 1;
736 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
737 cv_init(&sync_wakeup, "syncer");
738 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
743 vd = DPCPU_ID_PTR((cpu), vd);
744 bzero(vd, sizeof(*vd));
745 mtx_init(&vd->lock, "vdbatch", NULL, MTX_DEF);
748 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
751 * Mark a mount point as busy. Used to synchronize access and to delay
752 * unmounting. Eventually, mountlist_mtx is not released on failure.
754 * vfs_busy() is a custom lock, it can block the caller.
755 * vfs_busy() only sleeps if the unmount is active on the mount point.
756 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
757 * vnode belonging to mp.
759 * Lookup uses vfs_busy() to traverse mount points.
761 * / vnode lock A / vnode lock (/var) D
762 * /var vnode lock B /log vnode lock(/var/log) E
763 * vfs_busy lock C vfs_busy lock F
765 * Within each file system, the lock order is C->A->B and F->D->E.
767 * When traversing across mounts, the system follows that lock order:
773 * The lookup() process for namei("/var") illustrates the process:
774 * VOP_LOOKUP() obtains B while A is held
775 * vfs_busy() obtains a shared lock on F while A and B are held
776 * vput() releases lock on B
777 * vput() releases lock on A
778 * VFS_ROOT() obtains lock on D while shared lock on F is held
779 * vfs_unbusy() releases shared lock on F
780 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
781 * Attempt to lock A (instead of vp_crossmp) while D is held would
782 * violate the global order, causing deadlocks.
784 * dounmount() locks B while F is drained.
787 vfs_busy(struct mount *mp, int flags)
789 struct mount_pcpu *mpcpu;
791 MPASS((flags & ~MBF_MASK) == 0);
792 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
794 if (vfs_op_thread_enter(mp, mpcpu)) {
795 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
796 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
797 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
798 vfs_mp_count_add_pcpu(mpcpu, ref, 1);
799 vfs_mp_count_add_pcpu(mpcpu, lockref, 1);
800 vfs_op_thread_exit(mp, mpcpu);
801 if (flags & MBF_MNTLSTLOCK)
802 mtx_unlock(&mountlist_mtx);
807 vfs_assert_mount_counters(mp);
810 * If mount point is currently being unmounted, sleep until the
811 * mount point fate is decided. If thread doing the unmounting fails,
812 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
813 * that this mount point has survived the unmount attempt and vfs_busy
814 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
815 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
816 * about to be really destroyed. vfs_busy needs to release its
817 * reference on the mount point in this case and return with ENOENT,
818 * telling the caller that mount mount it tried to busy is no longer
821 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
822 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
825 CTR1(KTR_VFS, "%s: failed busying before sleeping",
829 if (flags & MBF_MNTLSTLOCK)
830 mtx_unlock(&mountlist_mtx);
831 mp->mnt_kern_flag |= MNTK_MWAIT;
832 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
833 if (flags & MBF_MNTLSTLOCK)
834 mtx_lock(&mountlist_mtx);
837 if (flags & MBF_MNTLSTLOCK)
838 mtx_unlock(&mountlist_mtx);
845 * Free a busy filesystem.
848 vfs_unbusy(struct mount *mp)
850 struct mount_pcpu *mpcpu;
853 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
855 if (vfs_op_thread_enter(mp, mpcpu)) {
856 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
857 vfs_mp_count_sub_pcpu(mpcpu, lockref, 1);
858 vfs_mp_count_sub_pcpu(mpcpu, ref, 1);
859 vfs_op_thread_exit(mp, mpcpu);
864 vfs_assert_mount_counters(mp);
866 c = --mp->mnt_lockref;
867 if (mp->mnt_vfs_ops == 0) {
868 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
873 vfs_dump_mount_counters(mp);
874 if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
875 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
876 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
877 mp->mnt_kern_flag &= ~MNTK_DRAINING;
878 wakeup(&mp->mnt_lockref);
884 * Lookup a mount point by filesystem identifier.
887 vfs_getvfs(fsid_t *fsid)
891 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
892 mtx_lock(&mountlist_mtx);
893 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
894 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
896 mtx_unlock(&mountlist_mtx);
900 mtx_unlock(&mountlist_mtx);
901 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
902 return ((struct mount *) 0);
906 * Lookup a mount point by filesystem identifier, busying it before
909 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
910 * cache for popular filesystem identifiers. The cache is lockess, using
911 * the fact that struct mount's are never freed. In worst case we may
912 * get pointer to unmounted or even different filesystem, so we have to
913 * check what we got, and go slow way if so.
916 vfs_busyfs(fsid_t *fsid)
918 #define FSID_CACHE_SIZE 256
919 typedef struct mount * volatile vmp_t;
920 static vmp_t cache[FSID_CACHE_SIZE];
925 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
926 hash = fsid->val[0] ^ fsid->val[1];
927 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
929 if (mp == NULL || fsidcmp(&mp->mnt_stat.f_fsid, fsid) != 0)
931 if (vfs_busy(mp, 0) != 0) {
935 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0)
941 mtx_lock(&mountlist_mtx);
942 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
943 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
944 error = vfs_busy(mp, MBF_MNTLSTLOCK);
947 mtx_unlock(&mountlist_mtx);
954 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
955 mtx_unlock(&mountlist_mtx);
956 return ((struct mount *) 0);
960 * Check if a user can access privileged mount options.
963 vfs_suser(struct mount *mp, struct thread *td)
967 if (jailed(td->td_ucred)) {
969 * If the jail of the calling thread lacks permission for
970 * this type of file system, deny immediately.
972 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
976 * If the file system was mounted outside the jail of the
977 * calling thread, deny immediately.
979 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
984 * If file system supports delegated administration, we don't check
985 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
986 * by the file system itself.
987 * If this is not the user that did original mount, we check for
988 * the PRIV_VFS_MOUNT_OWNER privilege.
990 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
991 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
992 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
999 * Get a new unique fsid. Try to make its val[0] unique, since this value
1000 * will be used to create fake device numbers for stat(). Also try (but
1001 * not so hard) make its val[0] unique mod 2^16, since some emulators only
1002 * support 16-bit device numbers. We end up with unique val[0]'s for the
1003 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
1005 * Keep in mind that several mounts may be running in parallel. Starting
1006 * the search one past where the previous search terminated is both a
1007 * micro-optimization and a defense against returning the same fsid to
1011 vfs_getnewfsid(struct mount *mp)
1013 static uint16_t mntid_base;
1018 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
1019 mtx_lock(&mntid_mtx);
1020 mtype = mp->mnt_vfc->vfc_typenum;
1021 tfsid.val[1] = mtype;
1022 mtype = (mtype & 0xFF) << 24;
1024 tfsid.val[0] = makedev(255,
1025 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
1027 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
1031 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
1032 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
1033 mtx_unlock(&mntid_mtx);
1037 * Knob to control the precision of file timestamps:
1039 * 0 = seconds only; nanoseconds zeroed.
1040 * 1 = seconds and nanoseconds, accurate within 1/HZ.
1041 * 2 = seconds and nanoseconds, truncated to microseconds.
1042 * >=3 = seconds and nanoseconds, maximum precision.
1044 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
1046 static int timestamp_precision = TSP_USEC;
1047 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
1048 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
1049 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
1050 "3+: sec + ns (max. precision))");
1053 * Get a current timestamp.
1056 vfs_timestamp(struct timespec *tsp)
1060 switch (timestamp_precision) {
1062 tsp->tv_sec = time_second;
1070 TIMEVAL_TO_TIMESPEC(&tv, tsp);
1080 * Set vnode attributes to VNOVAL
1083 vattr_null(struct vattr *vap)
1086 vap->va_type = VNON;
1087 vap->va_size = VNOVAL;
1088 vap->va_bytes = VNOVAL;
1089 vap->va_mode = VNOVAL;
1090 vap->va_nlink = VNOVAL;
1091 vap->va_uid = VNOVAL;
1092 vap->va_gid = VNOVAL;
1093 vap->va_fsid = VNOVAL;
1094 vap->va_fileid = VNOVAL;
1095 vap->va_blocksize = VNOVAL;
1096 vap->va_rdev = VNOVAL;
1097 vap->va_atime.tv_sec = VNOVAL;
1098 vap->va_atime.tv_nsec = VNOVAL;
1099 vap->va_mtime.tv_sec = VNOVAL;
1100 vap->va_mtime.tv_nsec = VNOVAL;
1101 vap->va_ctime.tv_sec = VNOVAL;
1102 vap->va_ctime.tv_nsec = VNOVAL;
1103 vap->va_birthtime.tv_sec = VNOVAL;
1104 vap->va_birthtime.tv_nsec = VNOVAL;
1105 vap->va_flags = VNOVAL;
1106 vap->va_gen = VNOVAL;
1107 vap->va_vaflags = 0;
1111 * Try to reduce the total number of vnodes.
1113 * This routine (and its user) are buggy in at least the following ways:
1114 * - all parameters were picked years ago when RAM sizes were significantly
1116 * - it can pick vnodes based on pages used by the vm object, but filesystems
1117 * like ZFS don't use it making the pick broken
1118 * - since ZFS has its own aging policy it gets partially combated by this one
1119 * - a dedicated method should be provided for filesystems to let them decide
1120 * whether the vnode should be recycled
1122 * This routine is called when we have too many vnodes. It attempts
1123 * to free <count> vnodes and will potentially free vnodes that still
1124 * have VM backing store (VM backing store is typically the cause
1125 * of a vnode blowout so we want to do this). Therefore, this operation
1126 * is not considered cheap.
1128 * A number of conditions may prevent a vnode from being reclaimed.
1129 * the buffer cache may have references on the vnode, a directory
1130 * vnode may still have references due to the namei cache representing
1131 * underlying files, or the vnode may be in active use. It is not
1132 * desirable to reuse such vnodes. These conditions may cause the
1133 * number of vnodes to reach some minimum value regardless of what
1134 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
1136 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1137 * entries if this argument is strue
1138 * @param trigger Only reclaim vnodes with fewer than this many resident
1140 * @param target How many vnodes to reclaim.
1141 * @return The number of vnodes that were reclaimed.
1144 vlrureclaim(bool reclaim_nc_src, int trigger, u_long target)
1146 struct vnode *vp, *mvp;
1148 struct vm_object *object;
1152 mtx_assert(&vnode_list_mtx, MA_OWNED);
1157 mvp = vnode_list_reclaim_marker;
1160 while (done < target) {
1161 vp = TAILQ_NEXT(vp, v_vnodelist);
1162 if (__predict_false(vp == NULL))
1165 if (__predict_false(vp->v_type == VMARKER))
1169 * If it's been deconstructed already, it's still
1170 * referenced, or it exceeds the trigger, skip it.
1171 * Also skip free vnodes. We are trying to make space
1172 * to expand the free list, not reduce it.
1174 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1175 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)))
1178 if (vp->v_type == VBAD || vp->v_type == VNON)
1181 object = atomic_load_ptr(&vp->v_object);
1182 if (object == NULL || object->resident_page_count > trigger) {
1187 * Handle races against vnode allocation. Filesystems lock the
1188 * vnode some time after it gets returned from getnewvnode,
1189 * despite type and hold count being manipulated earlier.
1190 * Resorting to checking v_mount restores guarantees present
1191 * before the global list was reworked to contain all vnodes.
1193 if (!VI_TRYLOCK(vp))
1195 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1199 if (vp->v_mount == NULL) {
1205 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1206 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1207 mtx_unlock(&vnode_list_mtx);
1209 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1211 goto next_iter_unlocked;
1213 if (VOP_LOCK(vp, LK_EXCLUSIVE|LK_NOWAIT) != 0) {
1215 vn_finished_write(mp);
1216 goto next_iter_unlocked;
1220 if (vp->v_usecount > 0 ||
1221 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1222 (vp->v_object != NULL && vp->v_object->handle == vp &&
1223 vp->v_object->resident_page_count > trigger)) {
1226 vn_finished_write(mp);
1227 goto next_iter_unlocked;
1229 counter_u64_add(recycles_count, 1);
1233 vn_finished_write(mp);
1237 mtx_lock(&vnode_list_mtx);
1240 MPASS(vp->v_type != VMARKER);
1241 if (!should_yield())
1243 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1244 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1245 mtx_unlock(&vnode_list_mtx);
1246 kern_yield(PRI_USER);
1247 mtx_lock(&vnode_list_mtx);
1250 if (done == 0 && !retried) {
1251 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1252 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1259 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1260 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1262 "limit on vnode free requests per call to the vnlru_free routine");
1265 * Attempt to reduce the free list by the requested amount.
1268 vnlru_free_impl(int count, struct vfsops *mnt_op, struct vnode *mvp)
1274 mtx_assert(&vnode_list_mtx, MA_OWNED);
1275 if (count > max_vnlru_free)
1276 count = max_vnlru_free;
1283 vp = TAILQ_NEXT(vp, v_vnodelist);
1284 if (__predict_false(vp == NULL)) {
1285 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1286 TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1289 if (__predict_false(vp->v_type == VMARKER))
1291 if (vp->v_holdcnt > 0)
1294 * Don't recycle if our vnode is from different type
1295 * of mount point. Note that mp is type-safe, the
1296 * check does not reach unmapped address even if
1297 * vnode is reclaimed.
1299 if (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1300 mp->mnt_op != mnt_op) {
1303 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1306 if (!vhold_recycle_free(vp))
1308 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1309 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1310 mtx_unlock(&vnode_list_mtx);
1312 * FIXME: ignores the return value, meaning it may be nothing
1313 * got recycled but it claims otherwise to the caller.
1315 * Originally the value started being ignored in 2005 with
1316 * 114a1006a8204aa156e1f9ad6476cdff89cada7f .
1318 * Respecting the value can run into significant stalls if most
1319 * vnodes belong to one file system and it has writes
1320 * suspended. In presence of many threads and millions of
1321 * vnodes they keep contending on the vnode_list_mtx lock only
1322 * to find vnodes they can't recycle.
1324 * The solution would be to pre-check if the vnode is likely to
1325 * be recycle-able, but it needs to happen with the
1326 * vnode_list_mtx lock held. This runs into a problem where
1327 * VOP_GETWRITEMOUNT (currently needed to find out about if
1328 * writes are frozen) can take locks which LOR against it.
1330 * Check nullfs for one example (null_getwritemount).
1334 mtx_lock(&vnode_list_mtx);
1337 return (ocount - count);
1341 vnlru_free_locked(int count)
1344 mtx_assert(&vnode_list_mtx, MA_OWNED);
1345 return (vnlru_free_impl(count, NULL, vnode_list_free_marker));
1349 vnlru_free_vfsops(int count, struct vfsops *mnt_op, struct vnode *mvp)
1352 MPASS(mnt_op != NULL);
1354 VNPASS(mvp->v_type == VMARKER, mvp);
1355 mtx_lock(&vnode_list_mtx);
1356 vnlru_free_impl(count, mnt_op, mvp);
1357 mtx_unlock(&vnode_list_mtx);
1361 * Temporary binary compat, don't use. Call vnlru_free_vfsops instead.
1364 vnlru_free(int count, struct vfsops *mnt_op)
1370 mtx_lock(&vnode_list_mtx);
1371 mvp = vnode_list_free_marker;
1372 if (vnlru_free_impl(count, mnt_op, mvp) == 0) {
1374 * It is possible the marker was moved over eligible vnodes by
1375 * callers which filtered by different ops. If so, start from
1378 if (vnlru_read_freevnodes() > 0) {
1379 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1380 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1382 vnlru_free_impl(count, mnt_op, mvp);
1384 mtx_unlock(&vnode_list_mtx);
1388 vnlru_alloc_marker(void)
1392 mvp = vn_alloc_marker(NULL);
1393 mtx_lock(&vnode_list_mtx);
1394 TAILQ_INSERT_BEFORE(vnode_list_free_marker, mvp, v_vnodelist);
1395 mtx_unlock(&vnode_list_mtx);
1400 vnlru_free_marker(struct vnode *mvp)
1402 mtx_lock(&vnode_list_mtx);
1403 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1404 mtx_unlock(&vnode_list_mtx);
1405 vn_free_marker(mvp);
1412 mtx_assert(&vnode_list_mtx, MA_OWNED);
1413 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1414 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1415 vlowat = vhiwat / 2;
1419 * Attempt to recycle vnodes in a context that is always safe to block.
1420 * Calling vlrurecycle() from the bowels of filesystem code has some
1421 * interesting deadlock problems.
1423 static struct proc *vnlruproc;
1424 static int vnlruproc_sig;
1427 * The main freevnodes counter is only updated when threads requeue their vnode
1428 * batches. CPUs are conditionally walked to compute a more accurate total.
1430 * Limit how much of a slop are we willing to tolerate. Note: the actual value
1431 * at any given moment can still exceed slop, but it should not be by significant
1432 * margin in practice.
1434 #define VNLRU_FREEVNODES_SLOP 128
1436 static __inline void
1437 vfs_freevnodes_inc(void)
1447 static __inline void
1448 vfs_freevnodes_dec(void)
1459 vnlru_read_freevnodes(void)
1465 mtx_assert(&vnode_list_mtx, MA_OWNED);
1466 if (freevnodes > freevnodes_old)
1467 slop = freevnodes - freevnodes_old;
1469 slop = freevnodes_old - freevnodes;
1470 if (slop < VNLRU_FREEVNODES_SLOP)
1471 return (freevnodes >= 0 ? freevnodes : 0);
1472 freevnodes_old = freevnodes;
1474 vd = DPCPU_ID_PTR((cpu), vd);
1475 freevnodes_old += vd->freevnodes;
1477 return (freevnodes_old >= 0 ? freevnodes_old : 0);
1481 vnlru_under(u_long rnumvnodes, u_long limit)
1483 u_long rfreevnodes, space;
1485 if (__predict_false(rnumvnodes > desiredvnodes))
1488 space = desiredvnodes - rnumvnodes;
1489 if (space < limit) {
1490 rfreevnodes = vnlru_read_freevnodes();
1491 if (rfreevnodes > wantfreevnodes)
1492 space += rfreevnodes - wantfreevnodes;
1494 return (space < limit);
1498 vnlru_under_unlocked(u_long rnumvnodes, u_long limit)
1500 long rfreevnodes, space;
1502 if (__predict_false(rnumvnodes > desiredvnodes))
1505 space = desiredvnodes - rnumvnodes;
1506 if (space < limit) {
1507 rfreevnodes = atomic_load_long(&freevnodes);
1508 if (rfreevnodes > wantfreevnodes)
1509 space += rfreevnodes - wantfreevnodes;
1511 return (space < limit);
1518 mtx_assert(&vnode_list_mtx, MA_OWNED);
1519 if (vnlruproc_sig == 0) {
1528 u_long rnumvnodes, rfreevnodes, target;
1529 unsigned long onumvnodes;
1530 int done, force, trigger, usevnodes;
1531 bool reclaim_nc_src, want_reread;
1533 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1534 SHUTDOWN_PRI_FIRST);
1537 want_reread = false;
1539 kproc_suspend_check(vnlruproc);
1540 mtx_lock(&vnode_list_mtx);
1541 rnumvnodes = atomic_load_long(&numvnodes);
1544 force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1545 want_reread = false;
1549 * If numvnodes is too large (due to desiredvnodes being
1550 * adjusted using its sysctl, or emergency growth), first
1551 * try to reduce it by discarding from the free list.
1553 if (rnumvnodes > desiredvnodes) {
1554 vnlru_free_locked(rnumvnodes - desiredvnodes);
1555 rnumvnodes = atomic_load_long(&numvnodes);
1558 * Sleep if the vnode cache is in a good state. This is
1559 * when it is not over-full and has space for about a 4%
1560 * or 9% expansion (by growing its size or inexcessively
1561 * reducing its free list). Otherwise, try to reclaim
1562 * space for a 10% expansion.
1564 if (vstir && force == 0) {
1568 if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1570 wakeup(&vnlruproc_sig);
1571 msleep(vnlruproc, &vnode_list_mtx,
1572 PVFS|PDROP, "vlruwt", hz);
1575 rfreevnodes = vnlru_read_freevnodes();
1577 onumvnodes = rnumvnodes;
1579 * Calculate parameters for recycling. These are the same
1580 * throughout the loop to give some semblance of fairness.
1581 * The trigger point is to avoid recycling vnodes with lots
1582 * of resident pages. We aren't trying to free memory; we
1583 * are trying to recycle or at least free vnodes.
1585 if (rnumvnodes <= desiredvnodes)
1586 usevnodes = rnumvnodes - rfreevnodes;
1588 usevnodes = rnumvnodes;
1592 * The trigger value is chosen to give a conservatively
1593 * large value to ensure that it alone doesn't prevent
1594 * making progress. The value can easily be so large that
1595 * it is effectively infinite in some congested and
1596 * misconfigured cases, and this is necessary. Normally
1597 * it is about 8 to 100 (pages), which is quite large.
1599 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1601 trigger = vsmalltrigger;
1602 reclaim_nc_src = force >= 3;
1603 target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1604 target = target / 10 + 1;
1605 done = vlrureclaim(reclaim_nc_src, trigger, target);
1606 mtx_unlock(&vnode_list_mtx);
1607 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1608 uma_reclaim(UMA_RECLAIM_DRAIN);
1610 if (force == 0 || force == 1) {
1621 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1624 kern_yield(PRI_USER);
1629 static struct kproc_desc vnlru_kp = {
1634 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1638 * Routines having to do with the management of the vnode table.
1642 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1643 * before we actually vgone(). This function must be called with the vnode
1644 * held to prevent the vnode from being returned to the free list midway
1648 vtryrecycle(struct vnode *vp)
1652 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1653 VNASSERT(vp->v_holdcnt, vp,
1654 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1656 * This vnode may found and locked via some other list, if so we
1657 * can't recycle it yet.
1659 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1661 "%s: impossible to recycle, vp %p lock is already held",
1664 return (EWOULDBLOCK);
1667 * Don't recycle if its filesystem is being suspended.
1669 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1672 "%s: impossible to recycle, cannot start the write for %p",
1678 * If we got this far, we need to acquire the interlock and see if
1679 * anyone picked up this vnode from another list. If not, we will
1680 * mark it with DOOMED via vgonel() so that anyone who does find it
1681 * will skip over it.
1684 if (vp->v_usecount) {
1687 vn_finished_write(vnmp);
1689 "%s: impossible to recycle, %p is already referenced",
1693 if (!VN_IS_DOOMED(vp)) {
1694 counter_u64_add(recycles_free_count, 1);
1699 vn_finished_write(vnmp);
1704 * Allocate a new vnode.
1706 * The operation never returns an error. Returning an error was disabled
1707 * in r145385 (dated 2005) with the following comment:
1709 * XXX Not all VFS_VGET/ffs_vget callers check returns.
1711 * Given the age of this commit (almost 15 years at the time of writing this
1712 * comment) restoring the ability to fail requires a significant audit of
1715 * The routine can try to free a vnode or stall for up to 1 second waiting for
1716 * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1718 static u_long vn_alloc_cyclecount;
1720 static struct vnode * __noinline
1721 vn_alloc_hard(struct mount *mp)
1723 u_long rnumvnodes, rfreevnodes;
1725 mtx_lock(&vnode_list_mtx);
1726 rnumvnodes = atomic_load_long(&numvnodes);
1727 if (rnumvnodes + 1 < desiredvnodes) {
1728 vn_alloc_cyclecount = 0;
1731 rfreevnodes = vnlru_read_freevnodes();
1732 if (vn_alloc_cyclecount++ >= rfreevnodes) {
1733 vn_alloc_cyclecount = 0;
1737 * Grow the vnode cache if it will not be above its target max
1738 * after growing. Otherwise, if the free list is nonempty, try
1739 * to reclaim 1 item from it before growing the cache (possibly
1740 * above its target max if the reclamation failed or is delayed).
1741 * Otherwise, wait for some space. In all cases, schedule
1742 * vnlru_proc() if we are getting short of space. The watermarks
1743 * should be chosen so that we never wait or even reclaim from
1744 * the free list to below its target minimum.
1746 if (vnlru_free_locked(1) > 0)
1748 if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1750 * Wait for space for a new vnode.
1753 msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1754 if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1755 vnlru_read_freevnodes() > 1)
1756 vnlru_free_locked(1);
1759 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1760 if (vnlru_under(rnumvnodes, vlowat))
1762 mtx_unlock(&vnode_list_mtx);
1763 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1766 static struct vnode *
1767 vn_alloc(struct mount *mp)
1771 if (__predict_false(vn_alloc_cyclecount != 0))
1772 return (vn_alloc_hard(mp));
1773 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1774 if (__predict_false(vnlru_under_unlocked(rnumvnodes, vlowat))) {
1775 atomic_subtract_long(&numvnodes, 1);
1776 return (vn_alloc_hard(mp));
1779 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1783 vn_free(struct vnode *vp)
1786 atomic_subtract_long(&numvnodes, 1);
1787 uma_zfree_smr(vnode_zone, vp);
1791 * Return the next vnode from the free list.
1794 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1799 struct lock_object *lo;
1801 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1803 KASSERT(vops->registered,
1804 ("%s: not registered vector op %p\n", __func__, vops));
1807 if (td->td_vp_reserved != NULL) {
1808 vp = td->td_vp_reserved;
1809 td->td_vp_reserved = NULL;
1813 counter_u64_add(vnodes_created, 1);
1815 * Locks are given the generic name "vnode" when created.
1816 * Follow the historic practice of using the filesystem
1817 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1819 * Locks live in a witness group keyed on their name. Thus,
1820 * when a lock is renamed, it must also move from the witness
1821 * group of its old name to the witness group of its new name.
1823 * The change only needs to be made when the vnode moves
1824 * from one filesystem type to another. We ensure that each
1825 * filesystem use a single static name pointer for its tag so
1826 * that we can compare pointers rather than doing a strcmp().
1828 lo = &vp->v_vnlock->lock_object;
1830 if (lo->lo_name != tag) {
1834 WITNESS_DESTROY(lo);
1835 WITNESS_INIT(lo, tag);
1839 * By default, don't allow shared locks unless filesystems opt-in.
1841 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1843 * Finalize various vnode identity bits.
1845 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1846 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1847 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1851 v_init_counters(vp);
1853 vp->v_bufobj.bo_ops = &buf_ops_bio;
1855 if (mp == NULL && vops != &dead_vnodeops)
1856 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1860 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1861 mac_vnode_associate_singlelabel(mp, vp);
1864 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1865 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1866 vp->v_vflag |= VV_NOKNOTE;
1870 * For the filesystems which do not use vfs_hash_insert(),
1871 * still initialize v_hash to have vfs_hash_index() useful.
1872 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1875 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1882 getnewvnode_reserve(void)
1887 MPASS(td->td_vp_reserved == NULL);
1888 td->td_vp_reserved = vn_alloc(NULL);
1892 getnewvnode_drop_reserve(void)
1897 if (td->td_vp_reserved != NULL) {
1898 vn_free(td->td_vp_reserved);
1899 td->td_vp_reserved = NULL;
1903 static void __noinline
1904 freevnode(struct vnode *vp)
1909 * The vnode has been marked for destruction, so free it.
1911 * The vnode will be returned to the zone where it will
1912 * normally remain until it is needed for another vnode. We
1913 * need to cleanup (or verify that the cleanup has already
1914 * been done) any residual data left from its current use
1915 * so as not to contaminate the freshly allocated vnode.
1917 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1919 * Paired with vgone.
1921 vn_seqc_write_end_free(vp);
1924 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1925 VNPASS(vp->v_holdcnt == VHOLD_NO_SMR, vp);
1926 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1927 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1928 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1929 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1930 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1931 ("clean blk trie not empty"));
1932 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1933 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1934 ("dirty blk trie not empty"));
1935 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1936 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1937 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1938 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1939 ("Dangling rangelock waiters"));
1940 VNASSERT((vp->v_iflag & (VI_DOINGINACT | VI_OWEINACT)) == 0, vp,
1941 ("Leaked inactivation"));
1944 mac_vnode_destroy(vp);
1946 if (vp->v_pollinfo != NULL) {
1947 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1948 destroy_vpollinfo(vp->v_pollinfo);
1950 vp->v_pollinfo = NULL;
1952 vp->v_mountedhere = NULL;
1955 vp->v_fifoinfo = NULL;
1956 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
1964 * Delete from old mount point vnode list, if on one.
1967 delmntque(struct vnode *vp)
1971 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
1980 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1981 ("bad mount point vnode list size"));
1982 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1983 mp->mnt_nvnodelistsize--;
1989 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1993 vp->v_op = &dead_vnodeops;
1999 * Insert into list of vnodes for the new mount point, if available.
2002 insmntque1(struct vnode *vp, struct mount *mp,
2003 void (*dtr)(struct vnode *, void *), void *dtr_arg)
2006 KASSERT(vp->v_mount == NULL,
2007 ("insmntque: vnode already on per mount vnode list"));
2008 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
2009 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
2012 * We acquire the vnode interlock early to ensure that the
2013 * vnode cannot be recycled by another process releasing a
2014 * holdcnt on it before we get it on both the vnode list
2015 * and the active vnode list. The mount mutex protects only
2016 * manipulation of the vnode list and the vnode freelist
2017 * mutex protects only manipulation of the active vnode list.
2018 * Hence the need to hold the vnode interlock throughout.
2022 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
2023 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
2024 mp->mnt_nvnodelistsize == 0)) &&
2025 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
2034 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
2035 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
2036 ("neg mount point vnode list size"));
2037 mp->mnt_nvnodelistsize++;
2044 insmntque(struct vnode *vp, struct mount *mp)
2047 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
2051 * Flush out and invalidate all buffers associated with a bufobj
2052 * Called with the underlying object locked.
2055 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
2060 if (flags & V_SAVE) {
2061 error = bufobj_wwait(bo, slpflag, slptimeo);
2066 if (bo->bo_dirty.bv_cnt > 0) {
2069 error = BO_SYNC(bo, MNT_WAIT);
2070 } while (error == ERELOOKUP);
2074 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0) {
2081 * If you alter this loop please notice that interlock is dropped and
2082 * reacquired in flushbuflist. Special care is needed to ensure that
2083 * no race conditions occur from this.
2086 error = flushbuflist(&bo->bo_clean,
2087 flags, bo, slpflag, slptimeo);
2088 if (error == 0 && !(flags & V_CLEANONLY))
2089 error = flushbuflist(&bo->bo_dirty,
2090 flags, bo, slpflag, slptimeo);
2091 if (error != 0 && error != EAGAIN) {
2095 } while (error != 0);
2098 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
2099 * have write I/O in-progress but if there is a VM object then the
2100 * VM object can also have read-I/O in-progress.
2103 bufobj_wwait(bo, 0, 0);
2104 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
2106 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
2109 } while (bo->bo_numoutput > 0);
2113 * Destroy the copy in the VM cache, too.
2115 if (bo->bo_object != NULL &&
2116 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
2117 VM_OBJECT_WLOCK(bo->bo_object);
2118 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
2119 OBJPR_CLEANONLY : 0);
2120 VM_OBJECT_WUNLOCK(bo->bo_object);
2125 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
2126 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
2127 bo->bo_clean.bv_cnt > 0))
2128 panic("vinvalbuf: flush failed");
2129 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
2130 bo->bo_dirty.bv_cnt > 0)
2131 panic("vinvalbuf: flush dirty failed");
2138 * Flush out and invalidate all buffers associated with a vnode.
2139 * Called with the underlying object locked.
2142 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
2145 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2146 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
2147 if (vp->v_object != NULL && vp->v_object->handle != vp)
2149 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
2153 * Flush out buffers on the specified list.
2157 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
2160 struct buf *bp, *nbp;
2165 ASSERT_BO_WLOCKED(bo);
2168 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2170 * If we are flushing both V_NORMAL and V_ALT buffers then
2171 * do not skip any buffers. If we are flushing only V_NORMAL
2172 * buffers then skip buffers marked as BX_ALTDATA. If we are
2173 * flushing only V_ALT buffers then skip buffers not marked
2176 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2177 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2178 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2182 lblkno = nbp->b_lblkno;
2183 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2186 error = BUF_TIMELOCK(bp,
2187 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2188 "flushbuf", slpflag, slptimeo);
2191 return (error != ENOLCK ? error : EAGAIN);
2193 KASSERT(bp->b_bufobj == bo,
2194 ("bp %p wrong b_bufobj %p should be %p",
2195 bp, bp->b_bufobj, bo));
2197 * XXX Since there are no node locks for NFS, I
2198 * believe there is a slight chance that a delayed
2199 * write will occur while sleeping just above, so
2202 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2205 bp->b_flags |= B_ASYNC;
2208 return (EAGAIN); /* XXX: why not loop ? */
2211 bp->b_flags |= (B_INVAL | B_RELBUF);
2212 bp->b_flags &= ~B_ASYNC;
2217 nbp = gbincore(bo, lblkno);
2218 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2220 break; /* nbp invalid */
2226 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2232 ASSERT_BO_LOCKED(bo);
2234 for (lblkno = startn;;) {
2236 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2237 if (bp == NULL || bp->b_lblkno >= endn ||
2238 bp->b_lblkno < startn)
2240 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2241 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2244 if (error == ENOLCK)
2248 KASSERT(bp->b_bufobj == bo,
2249 ("bp %p wrong b_bufobj %p should be %p",
2250 bp, bp->b_bufobj, bo));
2251 lblkno = bp->b_lblkno + 1;
2252 if ((bp->b_flags & B_MANAGED) == 0)
2254 bp->b_flags |= B_RELBUF;
2256 * In the VMIO case, use the B_NOREUSE flag to hint that the
2257 * pages backing each buffer in the range are unlikely to be
2258 * reused. Dirty buffers will have the hint applied once
2259 * they've been written.
2261 if ((bp->b_flags & B_VMIO) != 0)
2262 bp->b_flags |= B_NOREUSE;
2270 * Truncate a file's buffer and pages to a specified length. This
2271 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2275 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2277 struct buf *bp, *nbp;
2281 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2282 vp, blksize, (uintmax_t)length);
2285 * Round up to the *next* lbn.
2287 startlbn = howmany(length, blksize);
2289 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2295 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2300 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2301 if (bp->b_lblkno > 0)
2304 * Since we hold the vnode lock this should only
2305 * fail if we're racing with the buf daemon.
2308 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2309 BO_LOCKPTR(bo)) == ENOLCK)
2310 goto restart_unlocked;
2312 VNASSERT((bp->b_flags & B_DELWRI), vp,
2313 ("buf(%p) on dirty queue without DELWRI", bp));
2322 bufobj_wwait(bo, 0, 0);
2324 vnode_pager_setsize(vp, length);
2330 * Invalidate the cached pages of a file's buffer within the range of block
2331 * numbers [startlbn, endlbn).
2334 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2340 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2342 start = blksize * startlbn;
2343 end = blksize * endlbn;
2347 MPASS(blksize == bo->bo_bsize);
2349 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2353 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2357 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2358 daddr_t startlbn, daddr_t endlbn)
2360 struct buf *bp, *nbp;
2363 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2364 ASSERT_BO_LOCKED(bo);
2368 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2369 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2372 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2373 BO_LOCKPTR(bo)) == ENOLCK) {
2379 bp->b_flags |= B_INVAL | B_RELBUF;
2380 bp->b_flags &= ~B_ASYNC;
2386 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2388 (nbp->b_flags & B_DELWRI) != 0))
2392 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2393 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2396 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2397 BO_LOCKPTR(bo)) == ENOLCK) {
2402 bp->b_flags |= B_INVAL | B_RELBUF;
2403 bp->b_flags &= ~B_ASYNC;
2409 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2410 (nbp->b_vp != vp) ||
2411 (nbp->b_flags & B_DELWRI) == 0))
2419 buf_vlist_remove(struct buf *bp)
2424 flags = bp->b_xflags;
2426 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2427 ASSERT_BO_WLOCKED(bp->b_bufobj);
2428 KASSERT((flags & (BX_VNDIRTY | BX_VNCLEAN)) != 0 &&
2429 (flags & (BX_VNDIRTY | BX_VNCLEAN)) != (BX_VNDIRTY | BX_VNCLEAN),
2430 ("%s: buffer %p has invalid queue state", __func__, bp));
2432 if ((flags & BX_VNDIRTY) != 0)
2433 bv = &bp->b_bufobj->bo_dirty;
2435 bv = &bp->b_bufobj->bo_clean;
2436 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2437 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2439 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2443 * Add the buffer to the sorted clean or dirty block list.
2445 * NOTE: xflags is passed as a constant, optimizing this inline function!
2448 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2454 ASSERT_BO_WLOCKED(bo);
2455 KASSERT((bo->bo_flag & BO_NOBUFS) == 0,
2456 ("buf_vlist_add: bo %p does not allow bufs", bo));
2457 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2458 ("dead bo %p", bo));
2459 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2460 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2461 bp->b_xflags |= xflags;
2462 if (xflags & BX_VNDIRTY)
2468 * Keep the list ordered. Optimize empty list insertion. Assume
2469 * we tend to grow at the tail so lookup_le should usually be cheaper
2472 if (bv->bv_cnt == 0 ||
2473 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2474 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2475 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2476 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2478 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2479 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2481 panic("buf_vlist_add: Preallocated nodes insufficient.");
2486 * Look up a buffer using the buffer tries.
2489 gbincore(struct bufobj *bo, daddr_t lblkno)
2493 ASSERT_BO_LOCKED(bo);
2494 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2497 return (BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno));
2501 * Look up a buf using the buffer tries, without the bufobj lock. This relies
2502 * on SMR for safe lookup, and bufs being in a no-free zone to provide type
2503 * stability of the result. Like other lockless lookups, the found buf may
2504 * already be invalid by the time this function returns.
2507 gbincore_unlocked(struct bufobj *bo, daddr_t lblkno)
2511 ASSERT_BO_UNLOCKED(bo);
2512 bp = BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_clean.bv_root, lblkno);
2515 return (BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_dirty.bv_root, lblkno));
2519 * Associate a buffer with a vnode.
2522 bgetvp(struct vnode *vp, struct buf *bp)
2527 ASSERT_BO_WLOCKED(bo);
2528 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2530 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2531 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2532 ("bgetvp: bp already attached! %p", bp));
2538 * Insert onto list for new vnode.
2540 buf_vlist_add(bp, bo, BX_VNCLEAN);
2544 * Disassociate a buffer from a vnode.
2547 brelvp(struct buf *bp)
2552 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2553 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2556 * Delete from old vnode list, if on one.
2558 vp = bp->b_vp; /* XXX */
2561 buf_vlist_remove(bp);
2562 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2563 bo->bo_flag &= ~BO_ONWORKLST;
2564 mtx_lock(&sync_mtx);
2565 LIST_REMOVE(bo, bo_synclist);
2566 syncer_worklist_len--;
2567 mtx_unlock(&sync_mtx);
2570 bp->b_bufobj = NULL;
2576 * Add an item to the syncer work queue.
2579 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2583 ASSERT_BO_WLOCKED(bo);
2585 mtx_lock(&sync_mtx);
2586 if (bo->bo_flag & BO_ONWORKLST)
2587 LIST_REMOVE(bo, bo_synclist);
2589 bo->bo_flag |= BO_ONWORKLST;
2590 syncer_worklist_len++;
2593 if (delay > syncer_maxdelay - 2)
2594 delay = syncer_maxdelay - 2;
2595 slot = (syncer_delayno + delay) & syncer_mask;
2597 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2598 mtx_unlock(&sync_mtx);
2602 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2606 mtx_lock(&sync_mtx);
2607 len = syncer_worklist_len - sync_vnode_count;
2608 mtx_unlock(&sync_mtx);
2609 error = SYSCTL_OUT(req, &len, sizeof(len));
2613 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2614 CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2615 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2617 static struct proc *updateproc;
2618 static void sched_sync(void);
2619 static struct kproc_desc up_kp = {
2624 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2627 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2632 *bo = LIST_FIRST(slp);
2636 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2639 * We use vhold in case the vnode does not
2640 * successfully sync. vhold prevents the vnode from
2641 * going away when we unlock the sync_mtx so that
2642 * we can acquire the vnode interlock.
2645 mtx_unlock(&sync_mtx);
2647 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2649 mtx_lock(&sync_mtx);
2650 return (*bo == LIST_FIRST(slp));
2652 MPASSERT(mp == NULL || (curthread->td_pflags & TDP_IGNSUSP) != 0 ||
2653 (mp->mnt_kern_flag & MNTK_SUSPENDED) == 0, mp,
2654 ("suspended mp syncing vp %p", vp));
2655 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2656 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2658 vn_finished_write(mp);
2660 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2662 * Put us back on the worklist. The worklist
2663 * routine will remove us from our current
2664 * position and then add us back in at a later
2667 vn_syncer_add_to_worklist(*bo, syncdelay);
2671 mtx_lock(&sync_mtx);
2675 static int first_printf = 1;
2678 * System filesystem synchronizer daemon.
2683 struct synclist *next, *slp;
2686 struct thread *td = curthread;
2688 int net_worklist_len;
2689 int syncer_final_iter;
2693 syncer_final_iter = 0;
2694 syncer_state = SYNCER_RUNNING;
2695 starttime = time_uptime;
2696 td->td_pflags |= TDP_NORUNNINGBUF;
2698 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2701 mtx_lock(&sync_mtx);
2703 if (syncer_state == SYNCER_FINAL_DELAY &&
2704 syncer_final_iter == 0) {
2705 mtx_unlock(&sync_mtx);
2706 kproc_suspend_check(td->td_proc);
2707 mtx_lock(&sync_mtx);
2709 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2710 if (syncer_state != SYNCER_RUNNING &&
2711 starttime != time_uptime) {
2713 printf("\nSyncing disks, vnodes remaining... ");
2716 printf("%d ", net_worklist_len);
2718 starttime = time_uptime;
2721 * Push files whose dirty time has expired. Be careful
2722 * of interrupt race on slp queue.
2724 * Skip over empty worklist slots when shutting down.
2727 slp = &syncer_workitem_pending[syncer_delayno];
2728 syncer_delayno += 1;
2729 if (syncer_delayno == syncer_maxdelay)
2731 next = &syncer_workitem_pending[syncer_delayno];
2733 * If the worklist has wrapped since the
2734 * it was emptied of all but syncer vnodes,
2735 * switch to the FINAL_DELAY state and run
2736 * for one more second.
2738 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2739 net_worklist_len == 0 &&
2740 last_work_seen == syncer_delayno) {
2741 syncer_state = SYNCER_FINAL_DELAY;
2742 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2744 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2745 syncer_worklist_len > 0);
2748 * Keep track of the last time there was anything
2749 * on the worklist other than syncer vnodes.
2750 * Return to the SHUTTING_DOWN state if any
2753 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2754 last_work_seen = syncer_delayno;
2755 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2756 syncer_state = SYNCER_SHUTTING_DOWN;
2757 while (!LIST_EMPTY(slp)) {
2758 error = sync_vnode(slp, &bo, td);
2760 LIST_REMOVE(bo, bo_synclist);
2761 LIST_INSERT_HEAD(next, bo, bo_synclist);
2765 if (first_printf == 0) {
2767 * Drop the sync mutex, because some watchdog
2768 * drivers need to sleep while patting
2770 mtx_unlock(&sync_mtx);
2771 wdog_kern_pat(WD_LASTVAL);
2772 mtx_lock(&sync_mtx);
2775 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2776 syncer_final_iter--;
2778 * The variable rushjob allows the kernel to speed up the
2779 * processing of the filesystem syncer process. A rushjob
2780 * value of N tells the filesystem syncer to process the next
2781 * N seconds worth of work on its queue ASAP. Currently rushjob
2782 * is used by the soft update code to speed up the filesystem
2783 * syncer process when the incore state is getting so far
2784 * ahead of the disk that the kernel memory pool is being
2785 * threatened with exhaustion.
2792 * Just sleep for a short period of time between
2793 * iterations when shutting down to allow some I/O
2796 * If it has taken us less than a second to process the
2797 * current work, then wait. Otherwise start right over
2798 * again. We can still lose time if any single round
2799 * takes more than two seconds, but it does not really
2800 * matter as we are just trying to generally pace the
2801 * filesystem activity.
2803 if (syncer_state != SYNCER_RUNNING ||
2804 time_uptime == starttime) {
2806 sched_prio(td, PPAUSE);
2809 if (syncer_state != SYNCER_RUNNING)
2810 cv_timedwait(&sync_wakeup, &sync_mtx,
2811 hz / SYNCER_SHUTDOWN_SPEEDUP);
2812 else if (time_uptime == starttime)
2813 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2818 * Request the syncer daemon to speed up its work.
2819 * We never push it to speed up more than half of its
2820 * normal turn time, otherwise it could take over the cpu.
2823 speedup_syncer(void)
2827 mtx_lock(&sync_mtx);
2828 if (rushjob < syncdelay / 2) {
2830 stat_rush_requests += 1;
2833 mtx_unlock(&sync_mtx);
2834 cv_broadcast(&sync_wakeup);
2839 * Tell the syncer to speed up its work and run though its work
2840 * list several times, then tell it to shut down.
2843 syncer_shutdown(void *arg, int howto)
2846 if (howto & RB_NOSYNC)
2848 mtx_lock(&sync_mtx);
2849 syncer_state = SYNCER_SHUTTING_DOWN;
2851 mtx_unlock(&sync_mtx);
2852 cv_broadcast(&sync_wakeup);
2853 kproc_shutdown(arg, howto);
2857 syncer_suspend(void)
2860 syncer_shutdown(updateproc, 0);
2867 mtx_lock(&sync_mtx);
2869 syncer_state = SYNCER_RUNNING;
2870 mtx_unlock(&sync_mtx);
2871 cv_broadcast(&sync_wakeup);
2872 kproc_resume(updateproc);
2876 * Move the buffer between the clean and dirty lists of its vnode.
2879 reassignbuf(struct buf *bp)
2891 KASSERT((bp->b_flags & B_PAGING) == 0,
2892 ("%s: cannot reassign paging buffer %p", __func__, bp));
2894 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2895 bp, bp->b_vp, bp->b_flags);
2898 buf_vlist_remove(bp);
2901 * If dirty, put on list of dirty buffers; otherwise insert onto list
2904 if (bp->b_flags & B_DELWRI) {
2905 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2906 switch (vp->v_type) {
2916 vn_syncer_add_to_worklist(bo, delay);
2918 buf_vlist_add(bp, bo, BX_VNDIRTY);
2920 buf_vlist_add(bp, bo, BX_VNCLEAN);
2922 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2923 mtx_lock(&sync_mtx);
2924 LIST_REMOVE(bo, bo_synclist);
2925 syncer_worklist_len--;
2926 mtx_unlock(&sync_mtx);
2927 bo->bo_flag &= ~BO_ONWORKLST;
2932 bp = TAILQ_FIRST(&bv->bv_hd);
2933 KASSERT(bp == NULL || bp->b_bufobj == bo,
2934 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2935 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2936 KASSERT(bp == NULL || bp->b_bufobj == bo,
2937 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2939 bp = TAILQ_FIRST(&bv->bv_hd);
2940 KASSERT(bp == NULL || bp->b_bufobj == bo,
2941 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2942 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2943 KASSERT(bp == NULL || bp->b_bufobj == bo,
2944 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2950 v_init_counters(struct vnode *vp)
2953 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2954 vp, ("%s called for an initialized vnode", __FUNCTION__));
2955 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2957 refcount_init(&vp->v_holdcnt, 1);
2958 refcount_init(&vp->v_usecount, 1);
2962 * Grab a particular vnode from the free list, increment its
2963 * reference count and lock it. VIRF_DOOMED is set if the vnode
2964 * is being destroyed. Only callers who specify LK_RETRY will
2965 * see doomed vnodes. If inactive processing was delayed in
2966 * vput try to do it here.
2968 * usecount is manipulated using atomics without holding any locks.
2970 * holdcnt can be manipulated using atomics without holding any locks,
2971 * except when transitioning 1<->0, in which case the interlock is held.
2973 * Consumers which don't guarantee liveness of the vnode can use SMR to
2974 * try to get a reference. Note this operation can fail since the vnode
2975 * may be awaiting getting freed by the time they get to it.
2978 vget_prep_smr(struct vnode *vp)
2982 VFS_SMR_ASSERT_ENTERED();
2984 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2996 vget_prep(struct vnode *vp)
3000 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3010 vget_abort(struct vnode *vp, enum vgetstate vs)
3021 __assert_unreachable();
3026 vget(struct vnode *vp, int flags)
3031 return (vget_finish(vp, flags, vs));
3035 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
3039 if ((flags & LK_INTERLOCK) != 0)
3040 ASSERT_VI_LOCKED(vp, __func__);
3042 ASSERT_VI_UNLOCKED(vp, __func__);
3043 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3044 VNPASS(vp->v_holdcnt > 0, vp);
3045 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3047 error = vn_lock(vp, flags);
3048 if (__predict_false(error != 0)) {
3050 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
3055 vget_finish_ref(vp, vs);
3060 vget_finish_ref(struct vnode *vp, enum vgetstate vs)
3064 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3065 VNPASS(vp->v_holdcnt > 0, vp);
3066 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3068 if (vs == VGET_USECOUNT)
3072 * We hold the vnode. If the usecount is 0 it will be utilized to keep
3073 * the vnode around. Otherwise someone else lended their hold count and
3074 * we have to drop ours.
3076 old = atomic_fetchadd_int(&vp->v_usecount, 1);
3077 VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
3080 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
3081 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
3083 refcount_release(&vp->v_holdcnt);
3089 vref(struct vnode *vp)
3093 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3095 vget_finish_ref(vp, vs);
3099 vrefact(struct vnode *vp)
3102 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3104 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
3105 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3107 refcount_acquire(&vp->v_usecount);
3112 vlazy(struct vnode *vp)
3116 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
3118 if ((vp->v_mflag & VMP_LAZYLIST) != 0)
3121 * We may get here for inactive routines after the vnode got doomed.
3123 if (VN_IS_DOOMED(vp))
3126 mtx_lock(&mp->mnt_listmtx);
3127 if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
3128 vp->v_mflag |= VMP_LAZYLIST;
3129 TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3130 mp->mnt_lazyvnodelistsize++;
3132 mtx_unlock(&mp->mnt_listmtx);
3136 vunlazy(struct vnode *vp)
3140 ASSERT_VI_LOCKED(vp, __func__);
3141 VNPASS(!VN_IS_DOOMED(vp), vp);
3144 mtx_lock(&mp->mnt_listmtx);
3145 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3147 * Don't remove the vnode from the lazy list if another thread
3148 * has increased the hold count. It may have re-enqueued the
3149 * vnode to the lazy list and is now responsible for its
3152 if (vp->v_holdcnt == 0) {
3153 vp->v_mflag &= ~VMP_LAZYLIST;
3154 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3155 mp->mnt_lazyvnodelistsize--;
3157 mtx_unlock(&mp->mnt_listmtx);
3161 * This routine is only meant to be called from vgonel prior to dooming
3165 vunlazy_gone(struct vnode *vp)
3169 ASSERT_VOP_ELOCKED(vp, __func__);
3170 ASSERT_VI_LOCKED(vp, __func__);
3171 VNPASS(!VN_IS_DOOMED(vp), vp);
3173 if (vp->v_mflag & VMP_LAZYLIST) {
3175 mtx_lock(&mp->mnt_listmtx);
3176 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3177 vp->v_mflag &= ~VMP_LAZYLIST;
3178 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3179 mp->mnt_lazyvnodelistsize--;
3180 mtx_unlock(&mp->mnt_listmtx);
3185 vdefer_inactive(struct vnode *vp)
3188 ASSERT_VI_LOCKED(vp, __func__);
3189 VNASSERT(vp->v_holdcnt > 0, vp,
3190 ("%s: vnode without hold count", __func__));
3191 if (VN_IS_DOOMED(vp)) {
3195 if (vp->v_iflag & VI_DEFINACT) {
3196 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3200 if (vp->v_usecount > 0) {
3201 vp->v_iflag &= ~VI_OWEINACT;
3206 vp->v_iflag |= VI_DEFINACT;
3208 counter_u64_add(deferred_inact, 1);
3212 vdefer_inactive_unlocked(struct vnode *vp)
3216 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3220 vdefer_inactive(vp);
3223 enum vput_op { VRELE, VPUT, VUNREF };
3226 * Handle ->v_usecount transitioning to 0.
3228 * By releasing the last usecount we take ownership of the hold count which
3229 * provides liveness of the vnode, meaning we have to vdrop.
3231 * For all vnodes we may need to perform inactive processing. It requires an
3232 * exclusive lock on the vnode, while it is legal to call here with only a
3233 * shared lock (or no locks). If locking the vnode in an expected manner fails,
3234 * inactive processing gets deferred to the syncer.
3236 * XXX Some filesystems pass in an exclusively locked vnode and strongly depend
3237 * on the lock being held all the way until VOP_INACTIVE. This in particular
3238 * happens with UFS which adds half-constructed vnodes to the hash, where they
3239 * can be found by other code.
3242 vput_final(struct vnode *vp, enum vput_op func)
3247 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3248 VNPASS(vp->v_holdcnt > 0, vp);
3253 * By the time we got here someone else might have transitioned
3254 * the count back to > 0.
3256 if (vp->v_usecount > 0)
3260 * If the vnode is doomed vgone already performed inactive processing
3263 if (VN_IS_DOOMED(vp))
3266 if (__predict_true(VOP_NEED_INACTIVE(vp) == 0))
3269 if (vp->v_iflag & VI_DOINGINACT)
3273 * Locking operations here will drop the interlock and possibly the
3274 * vnode lock, opening a window where the vnode can get doomed all the
3275 * while ->v_usecount is 0. Set VI_OWEINACT to let vgone know to
3278 vp->v_iflag |= VI_OWEINACT;
3279 want_unlock = false;
3283 switch (VOP_ISLOCKED(vp)) {
3289 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3294 * The lock has at least one sharer, but we have no way
3295 * to conclude whether this is us. Play it safe and
3304 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3305 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3311 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3312 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3318 if (func == VUNREF) {
3319 VNASSERT((vp->v_vflag & VV_UNREF) == 0, vp,
3320 ("recursive vunref"));
3321 vp->v_vflag |= VV_UNREF;
3324 error = vinactive(vp);
3327 if (error != ERELOOKUP || !want_unlock)
3329 VOP_LOCK(vp, LK_EXCLUSIVE);
3332 vp->v_vflag &= ~VV_UNREF;
3335 vdefer_inactive(vp);
3345 * Decrement ->v_usecount for a vnode.
3347 * Releasing the last use count requires additional processing, see vput_final
3348 * above for details.
3350 * Comment above each variant denotes lock state on entry and exit.
3355 * out: same as passed in
3358 vrele(struct vnode *vp)
3361 ASSERT_VI_UNLOCKED(vp, __func__);
3362 if (!refcount_release(&vp->v_usecount))
3364 vput_final(vp, VRELE);
3372 vput(struct vnode *vp)
3375 ASSERT_VOP_LOCKED(vp, __func__);
3376 ASSERT_VI_UNLOCKED(vp, __func__);
3377 if (!refcount_release(&vp->v_usecount)) {
3381 vput_final(vp, VPUT);
3389 vunref(struct vnode *vp)
3392 ASSERT_VOP_LOCKED(vp, __func__);
3393 ASSERT_VI_UNLOCKED(vp, __func__);
3394 if (!refcount_release(&vp->v_usecount))
3396 vput_final(vp, VUNREF);
3400 vhold(struct vnode *vp)
3404 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3405 old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3406 VNASSERT(old >= 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3407 ("%s: wrong hold count %d", __func__, old));
3409 vfs_freevnodes_dec();
3413 vholdnz(struct vnode *vp)
3416 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3418 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3419 VNASSERT(old > 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3420 ("%s: wrong hold count %d", __func__, old));
3422 atomic_add_int(&vp->v_holdcnt, 1);
3427 * Grab a hold count unless the vnode is freed.
3429 * Only use this routine if vfs smr is the only protection you have against
3430 * freeing the vnode.
3432 * The code loops trying to add a hold count as long as the VHOLD_NO_SMR flag
3433 * is not set. After the flag is set the vnode becomes immutable to anyone but
3434 * the thread which managed to set the flag.
3436 * It may be tempting to replace the loop with:
3437 * count = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3438 * if (count & VHOLD_NO_SMR) {
3439 * backpedal and error out;
3442 * However, while this is more performant, it hinders debugging by eliminating
3443 * the previously mentioned invariant.
3446 vhold_smr(struct vnode *vp)
3450 VFS_SMR_ASSERT_ENTERED();
3452 count = atomic_load_int(&vp->v_holdcnt);
3454 if (count & VHOLD_NO_SMR) {
3455 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3456 ("non-zero hold count with flags %d\n", count));
3459 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3460 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3462 vfs_freevnodes_dec();
3469 * Hold a free vnode for recycling.
3471 * Note: vnode_init references this comment.
3473 * Attempts to recycle only need the global vnode list lock and have no use for
3476 * However, vnodes get inserted into the global list before they get fully
3477 * initialized and stay there until UMA decides to free the memory. This in
3478 * particular means the target can be found before it becomes usable and after
3479 * it becomes recycled. Picking up such vnodes is guarded with v_holdcnt set to
3482 * Note: the vnode may gain more references after we transition the count 0->1.
3485 vhold_recycle_free(struct vnode *vp)
3489 mtx_assert(&vnode_list_mtx, MA_OWNED);
3491 count = atomic_load_int(&vp->v_holdcnt);
3493 if (count & VHOLD_NO_SMR) {
3494 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3495 ("non-zero hold count with flags %d\n", count));
3498 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3502 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3503 vfs_freevnodes_dec();
3509 static void __noinline
3510 vdbatch_process(struct vdbatch *vd)
3515 mtx_assert(&vd->lock, MA_OWNED);
3516 MPASS(curthread->td_pinned > 0);
3517 MPASS(vd->index == VDBATCH_SIZE);
3519 mtx_lock(&vnode_list_mtx);
3521 freevnodes += vd->freevnodes;
3522 for (i = 0; i < VDBATCH_SIZE; i++) {
3524 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3525 TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3526 MPASS(vp->v_dbatchcpu != NOCPU);
3527 vp->v_dbatchcpu = NOCPU;
3529 mtx_unlock(&vnode_list_mtx);
3531 bzero(vd->tab, sizeof(vd->tab));
3537 vdbatch_enqueue(struct vnode *vp)
3541 ASSERT_VI_LOCKED(vp, __func__);
3542 VNASSERT(!VN_IS_DOOMED(vp), vp,
3543 ("%s: deferring requeue of a doomed vnode", __func__));
3545 if (vp->v_dbatchcpu != NOCPU) {
3552 mtx_lock(&vd->lock);
3553 MPASS(vd->index < VDBATCH_SIZE);
3554 MPASS(vd->tab[vd->index] == NULL);
3556 * A hack: we depend on being pinned so that we know what to put in
3559 vp->v_dbatchcpu = curcpu;
3560 vd->tab[vd->index] = vp;
3563 if (vd->index == VDBATCH_SIZE)
3564 vdbatch_process(vd);
3565 mtx_unlock(&vd->lock);
3570 * This routine must only be called for vnodes which are about to be
3571 * deallocated. Supporting dequeue for arbitrary vndoes would require
3572 * validating that the locked batch matches.
3575 vdbatch_dequeue(struct vnode *vp)
3581 VNASSERT(vp->v_type == VBAD || vp->v_type == VNON, vp,
3582 ("%s: called for a used vnode\n", __func__));
3584 cpu = vp->v_dbatchcpu;
3588 vd = DPCPU_ID_PTR(cpu, vd);
3589 mtx_lock(&vd->lock);
3590 for (i = 0; i < vd->index; i++) {
3591 if (vd->tab[i] != vp)
3593 vp->v_dbatchcpu = NOCPU;
3595 vd->tab[i] = vd->tab[vd->index];
3596 vd->tab[vd->index] = NULL;
3599 mtx_unlock(&vd->lock);
3601 * Either we dequeued the vnode above or the target CPU beat us to it.
3603 MPASS(vp->v_dbatchcpu == NOCPU);
3607 * Drop the hold count of the vnode. If this is the last reference to
3608 * the vnode we place it on the free list unless it has been vgone'd
3609 * (marked VIRF_DOOMED) in which case we will free it.
3611 * Because the vnode vm object keeps a hold reference on the vnode if
3612 * there is at least one resident non-cached page, the vnode cannot
3613 * leave the active list without the page cleanup done.
3615 static void __noinline
3616 vdropl_final(struct vnode *vp)
3619 ASSERT_VI_LOCKED(vp, __func__);
3620 VNPASS(VN_IS_DOOMED(vp), vp);
3622 * Set the VHOLD_NO_SMR flag.
3624 * We may be racing against vhold_smr. If they win we can just pretend
3625 * we never got this far, they will vdrop later.
3627 if (__predict_false(!atomic_cmpset_int(&vp->v_holdcnt, 0, VHOLD_NO_SMR))) {
3628 vfs_freevnodes_inc();
3631 * We lost the aforementioned race. Any subsequent access is
3632 * invalid as they might have managed to vdropl on their own.
3637 * Don't bump freevnodes as this one is going away.
3643 vdrop(struct vnode *vp)
3646 ASSERT_VI_UNLOCKED(vp, __func__);
3647 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3648 if (refcount_release_if_not_last(&vp->v_holdcnt))
3654 static void __always_inline
3655 vdropl_impl(struct vnode *vp, bool enqueue)
3658 ASSERT_VI_LOCKED(vp, __func__);
3659 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3660 if (!refcount_release(&vp->v_holdcnt)) {
3664 VNPASS((vp->v_iflag & VI_OWEINACT) == 0, vp);
3665 VNPASS((vp->v_iflag & VI_DEFINACT) == 0, vp);
3666 if (VN_IS_DOOMED(vp)) {
3671 vfs_freevnodes_inc();
3672 if (vp->v_mflag & VMP_LAZYLIST) {
3682 * Also unlocks the interlock. We can't assert on it as we
3683 * released our hold and by now the vnode might have been
3686 vdbatch_enqueue(vp);
3690 vdropl(struct vnode *vp)
3693 vdropl_impl(vp, true);
3697 * vdrop a vnode when recycling
3699 * This is a special case routine only to be used when recycling, differs from
3700 * regular vdrop by not requeieing the vnode on LRU.
3702 * Consider a case where vtryrecycle continuously fails with all vnodes (due to
3703 * e.g., frozen writes on the filesystem), filling the batch and causing it to
3704 * be requeued. Then vnlru will end up revisiting the same vnodes. This is a
3705 * loop which can last for as long as writes are frozen.
3708 vdropl_recycle(struct vnode *vp)
3711 vdropl_impl(vp, false);
3715 vdrop_recycle(struct vnode *vp)
3723 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3724 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3727 vinactivef(struct vnode *vp)
3729 struct vm_object *obj;
3732 ASSERT_VOP_ELOCKED(vp, "vinactive");
3733 ASSERT_VI_LOCKED(vp, "vinactive");
3734 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3735 ("vinactive: recursed on VI_DOINGINACT"));
3736 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3737 vp->v_iflag |= VI_DOINGINACT;
3738 vp->v_iflag &= ~VI_OWEINACT;
3741 * Before moving off the active list, we must be sure that any
3742 * modified pages are converted into the vnode's dirty
3743 * buffers, since these will no longer be checked once the
3744 * vnode is on the inactive list.
3746 * The write-out of the dirty pages is asynchronous. At the
3747 * point that VOP_INACTIVE() is called, there could still be
3748 * pending I/O and dirty pages in the object.
3750 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3751 vm_object_mightbedirty(obj)) {
3752 VM_OBJECT_WLOCK(obj);
3753 vm_object_page_clean(obj, 0, 0, 0);
3754 VM_OBJECT_WUNLOCK(obj);
3756 error = VOP_INACTIVE(vp);
3758 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3759 ("vinactive: lost VI_DOINGINACT"));
3760 vp->v_iflag &= ~VI_DOINGINACT;
3765 vinactive(struct vnode *vp)
3768 ASSERT_VOP_ELOCKED(vp, "vinactive");
3769 ASSERT_VI_LOCKED(vp, "vinactive");
3770 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3772 if ((vp->v_iflag & VI_OWEINACT) == 0)
3774 if (vp->v_iflag & VI_DOINGINACT)
3776 if (vp->v_usecount > 0) {
3777 vp->v_iflag &= ~VI_OWEINACT;
3780 return (vinactivef(vp));
3784 * Remove any vnodes in the vnode table belonging to mount point mp.
3786 * If FORCECLOSE is not specified, there should not be any active ones,
3787 * return error if any are found (nb: this is a user error, not a
3788 * system error). If FORCECLOSE is specified, detach any active vnodes
3791 * If WRITECLOSE is set, only flush out regular file vnodes open for
3794 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3796 * `rootrefs' specifies the base reference count for the root vnode
3797 * of this filesystem. The root vnode is considered busy if its
3798 * v_usecount exceeds this value. On a successful return, vflush(, td)
3799 * will call vrele() on the root vnode exactly rootrefs times.
3800 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3804 static int busyprt = 0; /* print out busy vnodes */
3805 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3809 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3811 struct vnode *vp, *mvp, *rootvp = NULL;
3813 int busy = 0, error;
3815 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3818 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3819 ("vflush: bad args"));
3821 * Get the filesystem root vnode. We can vput() it
3822 * immediately, since with rootrefs > 0, it won't go away.
3824 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3825 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3832 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3834 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3837 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3841 * Skip over a vnodes marked VV_SYSTEM.
3843 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3849 * If WRITECLOSE is set, flush out unlinked but still open
3850 * files (even if open only for reading) and regular file
3851 * vnodes open for writing.
3853 if (flags & WRITECLOSE) {
3854 if (vp->v_object != NULL) {
3855 VM_OBJECT_WLOCK(vp->v_object);
3856 vm_object_page_clean(vp->v_object, 0, 0, 0);
3857 VM_OBJECT_WUNLOCK(vp->v_object);
3860 error = VOP_FSYNC(vp, MNT_WAIT, td);
3861 } while (error == ERELOOKUP);
3865 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3868 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3871 if ((vp->v_type == VNON ||
3872 (error == 0 && vattr.va_nlink > 0)) &&
3873 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3881 * With v_usecount == 0, all we need to do is clear out the
3882 * vnode data structures and we are done.
3884 * If FORCECLOSE is set, forcibly close the vnode.
3886 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3892 vn_printf(vp, "vflush: busy vnode ");
3898 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3900 * If just the root vnode is busy, and if its refcount
3901 * is equal to `rootrefs', then go ahead and kill it.
3904 KASSERT(busy > 0, ("vflush: not busy"));
3905 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3906 ("vflush: usecount %d < rootrefs %d",
3907 rootvp->v_usecount, rootrefs));
3908 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3909 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3917 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3921 for (; rootrefs > 0; rootrefs--)
3927 * Recycle an unused vnode to the front of the free list.
3930 vrecycle(struct vnode *vp)
3935 recycled = vrecyclel(vp);
3941 * vrecycle, with the vp interlock held.
3944 vrecyclel(struct vnode *vp)
3948 ASSERT_VOP_ELOCKED(vp, __func__);
3949 ASSERT_VI_LOCKED(vp, __func__);
3950 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3952 if (vp->v_usecount == 0) {
3960 * Eliminate all activity associated with a vnode
3961 * in preparation for reuse.
3964 vgone(struct vnode *vp)
3972 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3973 struct vnode *lowervp __unused)
3978 * Notify upper mounts about reclaimed or unlinked vnode.
3981 vfs_notify_upper(struct vnode *vp, int event)
3983 static struct vfsops vgonel_vfsops = {
3984 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3985 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3987 struct mount *mp, *ump, *mmp;
3992 if (TAILQ_EMPTY(&mp->mnt_uppers))
3995 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3996 mmp->mnt_op = &vgonel_vfsops;
3997 mmp->mnt_kern_flag |= MNTK_MARKER;
3999 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
4000 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
4001 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
4002 ump = TAILQ_NEXT(ump, mnt_upper_link);
4005 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
4008 case VFS_NOTIFY_UPPER_RECLAIM:
4009 VFS_RECLAIM_LOWERVP(ump, vp);
4011 case VFS_NOTIFY_UPPER_UNLINK:
4012 VFS_UNLINK_LOWERVP(ump, vp);
4015 KASSERT(0, ("invalid event %d", event));
4019 ump = TAILQ_NEXT(mmp, mnt_upper_link);
4020 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
4023 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
4024 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
4025 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
4026 wakeup(&mp->mnt_uppers);
4032 * vgone, with the vp interlock held.
4035 vgonel(struct vnode *vp)
4040 bool active, doinginact, oweinact;
4042 ASSERT_VOP_ELOCKED(vp, "vgonel");
4043 ASSERT_VI_LOCKED(vp, "vgonel");
4044 VNASSERT(vp->v_holdcnt, vp,
4045 ("vgonel: vp %p has no reference.", vp));
4046 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
4050 * Don't vgonel if we're already doomed.
4052 if (VN_IS_DOOMED(vp))
4055 * Paired with freevnode.
4057 vn_seqc_write_begin_locked(vp);
4059 vn_irflag_set_locked(vp, VIRF_DOOMED);
4062 * Check to see if the vnode is in use. If so, we have to
4063 * call VOP_CLOSE() and VOP_INACTIVE().
4065 * It could be that VOP_INACTIVE() requested reclamation, in
4066 * which case we should avoid recursion, so check
4067 * VI_DOINGINACT. This is not precise but good enough.
4069 active = vp->v_usecount > 0;
4070 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4071 doinginact = (vp->v_iflag & VI_DOINGINACT) != 0;
4074 * If we need to do inactive VI_OWEINACT will be set.
4076 if (vp->v_iflag & VI_DEFINACT) {
4077 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
4078 vp->v_iflag &= ~VI_DEFINACT;
4081 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
4084 cache_purge_vgone(vp);
4085 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
4088 * If purging an active vnode, it must be closed and
4089 * deactivated before being reclaimed.
4092 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
4095 if (oweinact || active) {
4098 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4103 if (vp->v_type == VSOCK)
4104 vfs_unp_reclaim(vp);
4107 * Clean out any buffers associated with the vnode.
4108 * If the flush fails, just toss the buffers.
4111 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
4112 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
4113 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
4114 while (vinvalbuf(vp, 0, 0, 0) != 0)
4118 BO_LOCK(&vp->v_bufobj);
4119 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
4120 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
4121 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
4122 vp->v_bufobj.bo_clean.bv_cnt == 0,
4123 ("vp %p bufobj not invalidated", vp));
4126 * For VMIO bufobj, BO_DEAD is set later, or in
4127 * vm_object_terminate() after the object's page queue is
4130 object = vp->v_bufobj.bo_object;
4132 vp->v_bufobj.bo_flag |= BO_DEAD;
4133 BO_UNLOCK(&vp->v_bufobj);
4136 * Handle the VM part. Tmpfs handles v_object on its own (the
4137 * OBJT_VNODE check). Nullfs or other bypassing filesystems
4138 * should not touch the object borrowed from the lower vnode
4139 * (the handle check).
4141 if (object != NULL && object->type == OBJT_VNODE &&
4142 object->handle == vp)
4143 vnode_destroy_vobject(vp);
4146 * Reclaim the vnode.
4148 if (VOP_RECLAIM(vp))
4149 panic("vgone: cannot reclaim");
4151 vn_finished_secondary_write(mp);
4152 VNASSERT(vp->v_object == NULL, vp,
4153 ("vop_reclaim left v_object vp=%p", vp));
4155 * Clear the advisory locks and wake up waiting threads.
4157 (void)VOP_ADVLOCKPURGE(vp);
4160 * Delete from old mount point vnode list.
4164 * Done with purge, reset to the standard lock and invalidate
4168 vp->v_vnlock = &vp->v_lock;
4169 vp->v_op = &dead_vnodeops;
4174 * Print out a description of a vnode.
4176 static const char * const typename[] =
4177 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
4180 _Static_assert((VHOLD_ALL_FLAGS & ~VHOLD_NO_SMR) == 0,
4181 "new hold count flag not added to vn_printf");
4184 vn_printf(struct vnode *vp, const char *fmt, ...)
4187 char buf[256], buf2[16];
4195 printf("%p: ", (void *)vp);
4196 printf("type %s\n", typename[vp->v_type]);
4197 holdcnt = atomic_load_int(&vp->v_holdcnt);
4198 printf(" usecount %d, writecount %d, refcount %d seqc users %d",
4199 vp->v_usecount, vp->v_writecount, holdcnt & ~VHOLD_ALL_FLAGS,
4201 switch (vp->v_type) {
4203 printf(" mountedhere %p\n", vp->v_mountedhere);
4206 printf(" rdev %p\n", vp->v_rdev);
4209 printf(" socket %p\n", vp->v_unpcb);
4212 printf(" fifoinfo %p\n", vp->v_fifoinfo);
4220 if (holdcnt & VHOLD_NO_SMR)
4221 strlcat(buf, "|VHOLD_NO_SMR", sizeof(buf));
4222 printf(" hold count flags (%s)\n", buf + 1);
4226 irflag = vn_irflag_read(vp);
4227 if (irflag & VIRF_DOOMED)
4228 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
4229 if (irflag & VIRF_PGREAD)
4230 strlcat(buf, "|VIRF_PGREAD", sizeof(buf));
4231 if (irflag & VIRF_MOUNTPOINT)
4232 strlcat(buf, "|VIRF_MOUNTPOINT", sizeof(buf));
4233 flags = irflag & ~(VIRF_DOOMED | VIRF_PGREAD | VIRF_MOUNTPOINT);
4235 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
4236 strlcat(buf, buf2, sizeof(buf));
4238 if (vp->v_vflag & VV_ROOT)
4239 strlcat(buf, "|VV_ROOT", sizeof(buf));
4240 if (vp->v_vflag & VV_ISTTY)
4241 strlcat(buf, "|VV_ISTTY", sizeof(buf));
4242 if (vp->v_vflag & VV_NOSYNC)
4243 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
4244 if (vp->v_vflag & VV_ETERNALDEV)
4245 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
4246 if (vp->v_vflag & VV_CACHEDLABEL)
4247 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
4248 if (vp->v_vflag & VV_VMSIZEVNLOCK)
4249 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
4250 if (vp->v_vflag & VV_COPYONWRITE)
4251 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
4252 if (vp->v_vflag & VV_SYSTEM)
4253 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
4254 if (vp->v_vflag & VV_PROCDEP)
4255 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
4256 if (vp->v_vflag & VV_NOKNOTE)
4257 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
4258 if (vp->v_vflag & VV_DELETED)
4259 strlcat(buf, "|VV_DELETED", sizeof(buf));
4260 if (vp->v_vflag & VV_MD)
4261 strlcat(buf, "|VV_MD", sizeof(buf));
4262 if (vp->v_vflag & VV_FORCEINSMQ)
4263 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
4264 if (vp->v_vflag & VV_READLINK)
4265 strlcat(buf, "|VV_READLINK", sizeof(buf));
4266 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4267 VV_CACHEDLABEL | VV_VMSIZEVNLOCK | VV_COPYONWRITE | VV_SYSTEM |
4268 VV_PROCDEP | VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ | VV_READLINK);
4270 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4271 strlcat(buf, buf2, sizeof(buf));
4273 if (vp->v_iflag & VI_TEXT_REF)
4274 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
4275 if (vp->v_iflag & VI_MOUNT)
4276 strlcat(buf, "|VI_MOUNT", sizeof(buf));
4277 if (vp->v_iflag & VI_DOINGINACT)
4278 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4279 if (vp->v_iflag & VI_OWEINACT)
4280 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4281 if (vp->v_iflag & VI_DEFINACT)
4282 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4283 if (vp->v_iflag & VI_FOPENING)
4284 strlcat(buf, "|VI_FOPENING", sizeof(buf));
4285 flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOINGINACT |
4286 VI_OWEINACT | VI_DEFINACT | VI_FOPENING);
4288 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4289 strlcat(buf, buf2, sizeof(buf));
4291 if (vp->v_mflag & VMP_LAZYLIST)
4292 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4293 flags = vp->v_mflag & ~(VMP_LAZYLIST);
4295 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4296 strlcat(buf, buf2, sizeof(buf));
4298 printf(" flags (%s)", buf + 1);
4299 if (mtx_owned(VI_MTX(vp)))
4300 printf(" VI_LOCKed");
4302 if (vp->v_object != NULL)
4303 printf(" v_object %p ref %d pages %d "
4304 "cleanbuf %d dirtybuf %d\n",
4305 vp->v_object, vp->v_object->ref_count,
4306 vp->v_object->resident_page_count,
4307 vp->v_bufobj.bo_clean.bv_cnt,
4308 vp->v_bufobj.bo_dirty.bv_cnt);
4310 lockmgr_printinfo(vp->v_vnlock);
4311 if (vp->v_data != NULL)
4317 * List all of the locked vnodes in the system.
4318 * Called when debugging the kernel.
4320 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
4326 * Note: because this is DDB, we can't obey the locking semantics
4327 * for these structures, which means we could catch an inconsistent
4328 * state and dereference a nasty pointer. Not much to be done
4331 db_printf("Locked vnodes\n");
4332 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4333 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4334 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4335 vn_printf(vp, "vnode ");
4341 * Show details about the given vnode.
4343 DB_SHOW_COMMAND(vnode, db_show_vnode)
4349 vp = (struct vnode *)addr;
4350 vn_printf(vp, "vnode ");
4354 * Show details about the given mount point.
4356 DB_SHOW_COMMAND(mount, db_show_mount)
4367 /* No address given, print short info about all mount points. */
4368 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4369 db_printf("%p %s on %s (%s)\n", mp,
4370 mp->mnt_stat.f_mntfromname,
4371 mp->mnt_stat.f_mntonname,
4372 mp->mnt_stat.f_fstypename);
4376 db_printf("\nMore info: show mount <addr>\n");
4380 mp = (struct mount *)addr;
4381 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4382 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4385 mflags = mp->mnt_flag;
4386 #define MNT_FLAG(flag) do { \
4387 if (mflags & (flag)) { \
4388 if (buf[0] != '\0') \
4389 strlcat(buf, ", ", sizeof(buf)); \
4390 strlcat(buf, (#flag) + 4, sizeof(buf)); \
4391 mflags &= ~(flag); \
4394 MNT_FLAG(MNT_RDONLY);
4395 MNT_FLAG(MNT_SYNCHRONOUS);
4396 MNT_FLAG(MNT_NOEXEC);
4397 MNT_FLAG(MNT_NOSUID);
4398 MNT_FLAG(MNT_NFS4ACLS);
4399 MNT_FLAG(MNT_UNION);
4400 MNT_FLAG(MNT_ASYNC);
4401 MNT_FLAG(MNT_SUIDDIR);
4402 MNT_FLAG(MNT_SOFTDEP);
4403 MNT_FLAG(MNT_NOSYMFOLLOW);
4404 MNT_FLAG(MNT_GJOURNAL);
4405 MNT_FLAG(MNT_MULTILABEL);
4407 MNT_FLAG(MNT_NOATIME);
4408 MNT_FLAG(MNT_NOCLUSTERR);
4409 MNT_FLAG(MNT_NOCLUSTERW);
4411 MNT_FLAG(MNT_EXRDONLY);
4412 MNT_FLAG(MNT_EXPORTED);
4413 MNT_FLAG(MNT_DEFEXPORTED);
4414 MNT_FLAG(MNT_EXPORTANON);
4415 MNT_FLAG(MNT_EXKERB);
4416 MNT_FLAG(MNT_EXPUBLIC);
4417 MNT_FLAG(MNT_LOCAL);
4418 MNT_FLAG(MNT_QUOTA);
4419 MNT_FLAG(MNT_ROOTFS);
4421 MNT_FLAG(MNT_IGNORE);
4422 MNT_FLAG(MNT_UPDATE);
4423 MNT_FLAG(MNT_DELEXPORT);
4424 MNT_FLAG(MNT_RELOAD);
4425 MNT_FLAG(MNT_FORCE);
4426 MNT_FLAG(MNT_SNAPSHOT);
4427 MNT_FLAG(MNT_BYFSID);
4431 strlcat(buf, ", ", sizeof(buf));
4432 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4433 "0x%016jx", mflags);
4435 db_printf(" mnt_flag = %s\n", buf);
4438 flags = mp->mnt_kern_flag;
4439 #define MNT_KERN_FLAG(flag) do { \
4440 if (flags & (flag)) { \
4441 if (buf[0] != '\0') \
4442 strlcat(buf, ", ", sizeof(buf)); \
4443 strlcat(buf, (#flag) + 5, sizeof(buf)); \
4447 MNT_KERN_FLAG(MNTK_UNMOUNTF);
4448 MNT_KERN_FLAG(MNTK_ASYNC);
4449 MNT_KERN_FLAG(MNTK_SOFTDEP);
4450 MNT_KERN_FLAG(MNTK_DRAINING);
4451 MNT_KERN_FLAG(MNTK_REFEXPIRE);
4452 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4453 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4454 MNT_KERN_FLAG(MNTK_NO_IOPF);
4455 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4456 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4457 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4458 MNT_KERN_FLAG(MNTK_MARKER);
4459 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4460 MNT_KERN_FLAG(MNTK_FPLOOKUP);
4461 MNT_KERN_FLAG(MNTK_NOASYNC);
4462 MNT_KERN_FLAG(MNTK_UNMOUNT);
4463 MNT_KERN_FLAG(MNTK_MWAIT);
4464 MNT_KERN_FLAG(MNTK_SUSPEND);
4465 MNT_KERN_FLAG(MNTK_SUSPEND2);
4466 MNT_KERN_FLAG(MNTK_SUSPENDED);
4467 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4468 MNT_KERN_FLAG(MNTK_NOKNOTE);
4469 #undef MNT_KERN_FLAG
4472 strlcat(buf, ", ", sizeof(buf));
4473 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4476 db_printf(" mnt_kern_flag = %s\n", buf);
4478 db_printf(" mnt_opt = ");
4479 opt = TAILQ_FIRST(mp->mnt_opt);
4481 db_printf("%s", opt->name);
4482 opt = TAILQ_NEXT(opt, link);
4483 while (opt != NULL) {
4484 db_printf(", %s", opt->name);
4485 opt = TAILQ_NEXT(opt, link);
4491 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4492 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4493 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4494 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4495 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4496 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4497 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4498 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4499 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4500 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4501 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4502 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4504 db_printf(" mnt_cred = { uid=%u ruid=%u",
4505 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4506 if (jailed(mp->mnt_cred))
4507 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4509 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4510 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4511 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4512 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4513 db_printf(" mnt_lazyvnodelistsize = %d\n",
4514 mp->mnt_lazyvnodelistsize);
4515 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4516 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4517 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4518 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4519 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4520 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4521 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4522 db_printf(" mnt_secondary_accwrites = %d\n",
4523 mp->mnt_secondary_accwrites);
4524 db_printf(" mnt_gjprovider = %s\n",
4525 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4526 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4528 db_printf("\n\nList of active vnodes\n");
4529 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4530 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4531 vn_printf(vp, "vnode ");
4536 db_printf("\n\nList of inactive vnodes\n");
4537 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4538 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4539 vn_printf(vp, "vnode ");
4548 * Fill in a struct xvfsconf based on a struct vfsconf.
4551 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4553 struct xvfsconf xvfsp;
4555 bzero(&xvfsp, sizeof(xvfsp));
4556 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4557 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4558 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4559 xvfsp.vfc_flags = vfsp->vfc_flags;
4561 * These are unused in userland, we keep them
4562 * to not break binary compatibility.
4564 xvfsp.vfc_vfsops = NULL;
4565 xvfsp.vfc_next = NULL;
4566 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4569 #ifdef COMPAT_FREEBSD32
4571 uint32_t vfc_vfsops;
4572 char vfc_name[MFSNAMELEN];
4573 int32_t vfc_typenum;
4574 int32_t vfc_refcount;
4580 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4582 struct xvfsconf32 xvfsp;
4584 bzero(&xvfsp, sizeof(xvfsp));
4585 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4586 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4587 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4588 xvfsp.vfc_flags = vfsp->vfc_flags;
4589 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4594 * Top level filesystem related information gathering.
4597 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4599 struct vfsconf *vfsp;
4604 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4605 #ifdef COMPAT_FREEBSD32
4606 if (req->flags & SCTL_MASK32)
4607 error = vfsconf2x32(req, vfsp);
4610 error = vfsconf2x(req, vfsp);
4618 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4619 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4620 "S,xvfsconf", "List of all configured filesystems");
4622 #ifndef BURN_BRIDGES
4623 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4626 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4628 int *name = (int *)arg1 - 1; /* XXX */
4629 u_int namelen = arg2 + 1; /* XXX */
4630 struct vfsconf *vfsp;
4632 log(LOG_WARNING, "userland calling deprecated sysctl, "
4633 "please rebuild world\n");
4635 #if 1 || defined(COMPAT_PRELITE2)
4636 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4638 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4642 case VFS_MAXTYPENUM:
4645 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4648 return (ENOTDIR); /* overloaded */
4650 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4651 if (vfsp->vfc_typenum == name[2])
4656 return (EOPNOTSUPP);
4657 #ifdef COMPAT_FREEBSD32
4658 if (req->flags & SCTL_MASK32)
4659 return (vfsconf2x32(req, vfsp));
4662 return (vfsconf2x(req, vfsp));
4664 return (EOPNOTSUPP);
4667 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4668 CTLFLAG_MPSAFE, vfs_sysctl,
4669 "Generic filesystem");
4671 #if 1 || defined(COMPAT_PRELITE2)
4674 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4677 struct vfsconf *vfsp;
4678 struct ovfsconf ovfs;
4681 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4682 bzero(&ovfs, sizeof(ovfs));
4683 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4684 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4685 ovfs.vfc_index = vfsp->vfc_typenum;
4686 ovfs.vfc_refcount = vfsp->vfc_refcount;
4687 ovfs.vfc_flags = vfsp->vfc_flags;
4688 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4698 #endif /* 1 || COMPAT_PRELITE2 */
4699 #endif /* !BURN_BRIDGES */
4701 #define KINFO_VNODESLOP 10
4704 * Dump vnode list (via sysctl).
4708 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4716 * Stale numvnodes access is not fatal here.
4719 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4721 /* Make an estimate */
4722 return (SYSCTL_OUT(req, 0, len));
4724 error = sysctl_wire_old_buffer(req, 0);
4727 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4729 mtx_lock(&mountlist_mtx);
4730 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4731 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4734 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4738 xvn[n].xv_size = sizeof *xvn;
4739 xvn[n].xv_vnode = vp;
4740 xvn[n].xv_id = 0; /* XXX compat */
4741 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4743 XV_COPY(writecount);
4749 xvn[n].xv_flag = vp->v_vflag;
4751 switch (vp->v_type) {
4758 if (vp->v_rdev == NULL) {
4762 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4765 xvn[n].xv_socket = vp->v_socket;
4768 xvn[n].xv_fifo = vp->v_fifoinfo;
4773 /* shouldn't happen? */
4781 mtx_lock(&mountlist_mtx);
4786 mtx_unlock(&mountlist_mtx);
4788 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4793 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4794 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4799 unmount_or_warn(struct mount *mp)
4803 error = dounmount(mp, MNT_FORCE, curthread);
4805 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4809 printf("%d)\n", error);
4814 * Unmount all filesystems. The list is traversed in reverse order
4815 * of mounting to avoid dependencies.
4818 vfs_unmountall(void)
4820 struct mount *mp, *tmp;
4822 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4825 * Since this only runs when rebooting, it is not interlocked.
4827 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4831 * Forcibly unmounting "/dev" before "/" would prevent clean
4832 * unmount of the latter.
4834 if (mp == rootdevmp)
4837 unmount_or_warn(mp);
4840 if (rootdevmp != NULL)
4841 unmount_or_warn(rootdevmp);
4845 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4848 ASSERT_VI_LOCKED(vp, __func__);
4849 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4850 if ((vp->v_iflag & VI_OWEINACT) == 0) {
4854 if (vn_lock(vp, lkflags) == 0) {
4861 vdefer_inactive_unlocked(vp);
4865 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4868 return (vp->v_iflag & VI_DEFINACT);
4871 static void __noinline
4872 vfs_periodic_inactive(struct mount *mp, int flags)
4874 struct vnode *vp, *mvp;
4877 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4878 if (flags != MNT_WAIT)
4879 lkflags |= LK_NOWAIT;
4881 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4882 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4886 vp->v_iflag &= ~VI_DEFINACT;
4887 vfs_deferred_inactive(vp, lkflags);
4892 vfs_want_msync(struct vnode *vp)
4894 struct vm_object *obj;
4897 * This test may be performed without any locks held.
4898 * We rely on vm_object's type stability.
4900 if (vp->v_vflag & VV_NOSYNC)
4903 return (obj != NULL && vm_object_mightbedirty(obj));
4907 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4910 if (vp->v_vflag & VV_NOSYNC)
4912 if (vp->v_iflag & VI_DEFINACT)
4914 return (vfs_want_msync(vp));
4917 static void __noinline
4918 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4920 struct vnode *vp, *mvp;
4921 struct vm_object *obj;
4922 int lkflags, objflags;
4925 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4926 if (flags != MNT_WAIT) {
4927 lkflags |= LK_NOWAIT;
4928 objflags = OBJPC_NOSYNC;
4930 objflags = OBJPC_SYNC;
4933 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4935 if (vp->v_iflag & VI_DEFINACT) {
4936 vp->v_iflag &= ~VI_DEFINACT;
4939 if (!vfs_want_msync(vp)) {
4941 vfs_deferred_inactive(vp, lkflags);
4946 if (vget(vp, lkflags) == 0) {
4948 if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4949 VM_OBJECT_WLOCK(obj);
4950 vm_object_page_clean(obj, 0, 0, objflags);
4951 VM_OBJECT_WUNLOCK(obj);
4958 vdefer_inactive_unlocked(vp);
4964 vfs_periodic(struct mount *mp, int flags)
4967 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4969 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4970 vfs_periodic_inactive(mp, flags);
4972 vfs_periodic_msync_inactive(mp, flags);
4976 destroy_vpollinfo_free(struct vpollinfo *vi)
4979 knlist_destroy(&vi->vpi_selinfo.si_note);
4980 mtx_destroy(&vi->vpi_lock);
4981 free(vi, M_VNODEPOLL);
4985 destroy_vpollinfo(struct vpollinfo *vi)
4988 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4989 seldrain(&vi->vpi_selinfo);
4990 destroy_vpollinfo_free(vi);
4994 * Initialize per-vnode helper structure to hold poll-related state.
4997 v_addpollinfo(struct vnode *vp)
4999 struct vpollinfo *vi;
5001 if (vp->v_pollinfo != NULL)
5003 vi = malloc(sizeof(*vi), M_VNODEPOLL, M_WAITOK | M_ZERO);
5004 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
5005 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
5006 vfs_knlunlock, vfs_knl_assert_lock);
5008 if (vp->v_pollinfo != NULL) {
5010 destroy_vpollinfo_free(vi);
5013 vp->v_pollinfo = vi;
5018 * Record a process's interest in events which might happen to
5019 * a vnode. Because poll uses the historic select-style interface
5020 * internally, this routine serves as both the ``check for any
5021 * pending events'' and the ``record my interest in future events''
5022 * functions. (These are done together, while the lock is held,
5023 * to avoid race conditions.)
5026 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
5030 mtx_lock(&vp->v_pollinfo->vpi_lock);
5031 if (vp->v_pollinfo->vpi_revents & events) {
5033 * This leaves events we are not interested
5034 * in available for the other process which
5035 * which presumably had requested them
5036 * (otherwise they would never have been
5039 events &= vp->v_pollinfo->vpi_revents;
5040 vp->v_pollinfo->vpi_revents &= ~events;
5042 mtx_unlock(&vp->v_pollinfo->vpi_lock);
5045 vp->v_pollinfo->vpi_events |= events;
5046 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
5047 mtx_unlock(&vp->v_pollinfo->vpi_lock);
5052 * Routine to create and manage a filesystem syncer vnode.
5054 #define sync_close ((int (*)(struct vop_close_args *))nullop)
5055 static int sync_fsync(struct vop_fsync_args *);
5056 static int sync_inactive(struct vop_inactive_args *);
5057 static int sync_reclaim(struct vop_reclaim_args *);
5059 static struct vop_vector sync_vnodeops = {
5060 .vop_bypass = VOP_EOPNOTSUPP,
5061 .vop_close = sync_close, /* close */
5062 .vop_fsync = sync_fsync, /* fsync */
5063 .vop_getwritemount = vop_stdgetwritemount,
5064 .vop_inactive = sync_inactive, /* inactive */
5065 .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
5066 .vop_reclaim = sync_reclaim, /* reclaim */
5067 .vop_lock1 = vop_stdlock, /* lock */
5068 .vop_unlock = vop_stdunlock, /* unlock */
5069 .vop_islocked = vop_stdislocked, /* islocked */
5071 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
5074 * Create a new filesystem syncer vnode for the specified mount point.
5077 vfs_allocate_syncvnode(struct mount *mp)
5081 static long start, incr, next;
5084 /* Allocate a new vnode */
5085 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
5087 panic("vfs_allocate_syncvnode: getnewvnode() failed");
5089 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5090 vp->v_vflag |= VV_FORCEINSMQ;
5091 error = insmntque(vp, mp);
5093 panic("vfs_allocate_syncvnode: insmntque() failed");
5094 vp->v_vflag &= ~VV_FORCEINSMQ;
5097 * Place the vnode onto the syncer worklist. We attempt to
5098 * scatter them about on the list so that they will go off
5099 * at evenly distributed times even if all the filesystems
5100 * are mounted at once.
5103 if (next == 0 || next > syncer_maxdelay) {
5107 start = syncer_maxdelay / 2;
5108 incr = syncer_maxdelay;
5114 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
5115 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
5116 mtx_lock(&sync_mtx);
5118 if (mp->mnt_syncer == NULL) {
5119 mp->mnt_syncer = vp;
5122 mtx_unlock(&sync_mtx);
5125 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5132 vfs_deallocate_syncvnode(struct mount *mp)
5136 mtx_lock(&sync_mtx);
5137 vp = mp->mnt_syncer;
5139 mp->mnt_syncer = NULL;
5140 mtx_unlock(&sync_mtx);
5146 * Do a lazy sync of the filesystem.
5149 sync_fsync(struct vop_fsync_args *ap)
5151 struct vnode *syncvp = ap->a_vp;
5152 struct mount *mp = syncvp->v_mount;
5157 * We only need to do something if this is a lazy evaluation.
5159 if (ap->a_waitfor != MNT_LAZY)
5163 * Move ourselves to the back of the sync list.
5165 bo = &syncvp->v_bufobj;
5167 vn_syncer_add_to_worklist(bo, syncdelay);
5171 * Walk the list of vnodes pushing all that are dirty and
5172 * not already on the sync list.
5174 if (vfs_busy(mp, MBF_NOWAIT) != 0)
5177 save = curthread_pflags_set(TDP_SYNCIO);
5179 * The filesystem at hand may be idle with free vnodes stored in the
5180 * batch. Return them instead of letting them stay there indefinitely.
5182 vfs_periodic(mp, MNT_NOWAIT);
5183 error = VFS_SYNC(mp, MNT_LAZY);
5184 curthread_pflags_restore(save);
5185 vn_lock(syncvp, LK_EXCLUSIVE | LK_RETRY);
5191 * The syncer vnode is no referenced.
5194 sync_inactive(struct vop_inactive_args *ap)
5202 * The syncer vnode is no longer needed and is being decommissioned.
5204 * Modifications to the worklist must be protected by sync_mtx.
5207 sync_reclaim(struct vop_reclaim_args *ap)
5209 struct vnode *vp = ap->a_vp;
5214 mtx_lock(&sync_mtx);
5215 if (vp->v_mount->mnt_syncer == vp)
5216 vp->v_mount->mnt_syncer = NULL;
5217 if (bo->bo_flag & BO_ONWORKLST) {
5218 LIST_REMOVE(bo, bo_synclist);
5219 syncer_worklist_len--;
5221 bo->bo_flag &= ~BO_ONWORKLST;
5223 mtx_unlock(&sync_mtx);
5230 vn_need_pageq_flush(struct vnode *vp)
5232 struct vm_object *obj;
5235 return (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
5236 vm_object_mightbedirty(obj));
5240 * Check if vnode represents a disk device
5243 vn_isdisk_error(struct vnode *vp, int *errp)
5247 if (vp->v_type != VCHR) {
5253 if (vp->v_rdev == NULL)
5255 else if (vp->v_rdev->si_devsw == NULL)
5257 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5262 return (error == 0);
5266 vn_isdisk(struct vnode *vp)
5270 return (vn_isdisk_error(vp, &error));
5274 * VOP_FPLOOKUP_VEXEC routines are subject to special circumstances, see
5275 * the comment above cache_fplookup for details.
5278 vaccess_vexec_smr(mode_t file_mode, uid_t file_uid, gid_t file_gid, struct ucred *cred)
5282 VFS_SMR_ASSERT_ENTERED();
5284 /* Check the owner. */
5285 if (cred->cr_uid == file_uid) {
5286 if (file_mode & S_IXUSR)
5291 /* Otherwise, check the groups (first match) */
5292 if (groupmember(file_gid, cred)) {
5293 if (file_mode & S_IXGRP)
5298 /* Otherwise, check everyone else. */
5299 if (file_mode & S_IXOTH)
5303 * Permission check failed, but it is possible denial will get overwritten
5304 * (e.g., when root is traversing through a 700 directory owned by someone
5307 * vaccess() calls priv_check_cred which in turn can descent into MAC
5308 * modules overriding this result. It's quite unclear what semantics
5309 * are allowed for them to operate, thus for safety we don't call them
5310 * from within the SMR section. This also means if any such modules
5311 * are present, we have to let the regular lookup decide.
5313 error = priv_check_cred_vfs_lookup_nomac(cred);
5319 * MAC modules present.
5330 * Common filesystem object access control check routine. Accepts a
5331 * vnode's type, "mode", uid and gid, requested access mode, and credentials.
5332 * Returns 0 on success, or an errno on failure.
5335 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5336 accmode_t accmode, struct ucred *cred)
5338 accmode_t dac_granted;
5339 accmode_t priv_granted;
5341 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5342 ("invalid bit in accmode"));
5343 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5344 ("VAPPEND without VWRITE"));
5347 * Look for a normal, non-privileged way to access the file/directory
5348 * as requested. If it exists, go with that.
5353 /* Check the owner. */
5354 if (cred->cr_uid == file_uid) {
5355 dac_granted |= VADMIN;
5356 if (file_mode & S_IXUSR)
5357 dac_granted |= VEXEC;
5358 if (file_mode & S_IRUSR)
5359 dac_granted |= VREAD;
5360 if (file_mode & S_IWUSR)
5361 dac_granted |= (VWRITE | VAPPEND);
5363 if ((accmode & dac_granted) == accmode)
5369 /* Otherwise, check the groups (first match) */
5370 if (groupmember(file_gid, cred)) {
5371 if (file_mode & S_IXGRP)
5372 dac_granted |= VEXEC;
5373 if (file_mode & S_IRGRP)
5374 dac_granted |= VREAD;
5375 if (file_mode & S_IWGRP)
5376 dac_granted |= (VWRITE | VAPPEND);
5378 if ((accmode & dac_granted) == accmode)
5384 /* Otherwise, check everyone else. */
5385 if (file_mode & S_IXOTH)
5386 dac_granted |= VEXEC;
5387 if (file_mode & S_IROTH)
5388 dac_granted |= VREAD;
5389 if (file_mode & S_IWOTH)
5390 dac_granted |= (VWRITE | VAPPEND);
5391 if ((accmode & dac_granted) == accmode)
5396 * Build a privilege mask to determine if the set of privileges
5397 * satisfies the requirements when combined with the granted mask
5398 * from above. For each privilege, if the privilege is required,
5399 * bitwise or the request type onto the priv_granted mask.
5405 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5406 * requests, instead of PRIV_VFS_EXEC.
5408 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5409 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5410 priv_granted |= VEXEC;
5413 * Ensure that at least one execute bit is on. Otherwise,
5414 * a privileged user will always succeed, and we don't want
5415 * this to happen unless the file really is executable.
5417 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5418 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5419 !priv_check_cred(cred, PRIV_VFS_EXEC))
5420 priv_granted |= VEXEC;
5423 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5424 !priv_check_cred(cred, PRIV_VFS_READ))
5425 priv_granted |= VREAD;
5427 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5428 !priv_check_cred(cred, PRIV_VFS_WRITE))
5429 priv_granted |= (VWRITE | VAPPEND);
5431 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5432 !priv_check_cred(cred, PRIV_VFS_ADMIN))
5433 priv_granted |= VADMIN;
5435 if ((accmode & (priv_granted | dac_granted)) == accmode) {
5439 return ((accmode & VADMIN) ? EPERM : EACCES);
5443 * Credential check based on process requesting service, and per-attribute
5447 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5448 struct thread *td, accmode_t accmode)
5452 * Kernel-invoked always succeeds.
5458 * Do not allow privileged processes in jail to directly manipulate
5459 * system attributes.
5461 switch (attrnamespace) {
5462 case EXTATTR_NAMESPACE_SYSTEM:
5463 /* Potentially should be: return (EPERM); */
5464 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5465 case EXTATTR_NAMESPACE_USER:
5466 return (VOP_ACCESS(vp, accmode, cred, td));
5472 #ifdef DEBUG_VFS_LOCKS
5473 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
5474 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5475 "Drop into debugger on lock violation");
5477 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
5478 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5479 0, "Check for interlock across VOPs");
5481 int vfs_badlock_print = 1; /* Print lock violations. */
5482 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5483 0, "Print lock violations");
5485 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
5486 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5487 0, "Print vnode details on lock violations");
5490 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
5491 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5492 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5496 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5500 if (vfs_badlock_backtrace)
5503 if (vfs_badlock_vnode)
5504 vn_printf(vp, "vnode ");
5505 if (vfs_badlock_print)
5506 printf("%s: %p %s\n", str, (void *)vp, msg);
5507 if (vfs_badlock_ddb)
5508 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5512 assert_vi_locked(struct vnode *vp, const char *str)
5515 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5516 vfs_badlock("interlock is not locked but should be", str, vp);
5520 assert_vi_unlocked(struct vnode *vp, const char *str)
5523 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5524 vfs_badlock("interlock is locked but should not be", str, vp);
5528 assert_vop_locked(struct vnode *vp, const char *str)
5530 if (KERNEL_PANICKED() || vp == NULL)
5534 if ((vp->v_irflag & VIRF_CROSSMP) == 0 &&
5535 witness_is_owned(&vp->v_vnlock->lock_object) == -1)
5537 int locked = VOP_ISLOCKED(vp);
5538 if (locked == 0 || locked == LK_EXCLOTHER)
5540 vfs_badlock("is not locked but should be", str, vp);
5544 assert_vop_unlocked(struct vnode *vp, const char *str)
5546 if (KERNEL_PANICKED() || vp == NULL)
5550 if ((vp->v_irflag & VIRF_CROSSMP) == 0 &&
5551 witness_is_owned(&vp->v_vnlock->lock_object) == 1)
5553 if (VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5555 vfs_badlock("is locked but should not be", str, vp);
5559 assert_vop_elocked(struct vnode *vp, const char *str)
5561 if (KERNEL_PANICKED() || vp == NULL)
5564 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5565 vfs_badlock("is not exclusive locked but should be", str, vp);
5567 #endif /* DEBUG_VFS_LOCKS */
5570 vop_rename_fail(struct vop_rename_args *ap)
5573 if (ap->a_tvp != NULL)
5575 if (ap->a_tdvp == ap->a_tvp)
5584 vop_rename_pre(void *ap)
5586 struct vop_rename_args *a = ap;
5588 #ifdef DEBUG_VFS_LOCKS
5590 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5591 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5592 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5593 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5595 /* Check the source (from). */
5596 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5597 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5598 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5599 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5600 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5602 /* Check the target. */
5604 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5605 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5608 * It may be tempting to add vn_seqc_write_begin/end calls here and
5609 * in vop_rename_post but that's not going to work out since some
5610 * filesystems relookup vnodes mid-rename. This is probably a bug.
5612 * For now filesystems are expected to do the relevant calls after they
5613 * decide what vnodes to operate on.
5615 if (a->a_tdvp != a->a_fdvp)
5617 if (a->a_tvp != a->a_fvp)
5624 #ifdef DEBUG_VFS_LOCKS
5626 vop_fplookup_vexec_debugpre(void *ap __unused)
5629 VFS_SMR_ASSERT_ENTERED();
5633 vop_fplookup_vexec_debugpost(void *ap __unused, int rc __unused)
5636 VFS_SMR_ASSERT_ENTERED();
5640 vop_fplookup_symlink_debugpre(void *ap __unused)
5643 VFS_SMR_ASSERT_ENTERED();
5647 vop_fplookup_symlink_debugpost(void *ap __unused, int rc __unused)
5650 VFS_SMR_ASSERT_ENTERED();
5654 vop_fsync_debugprepost(struct vnode *vp, const char *name)
5656 if (vp->v_type == VCHR)
5658 else if (MNT_EXTENDED_SHARED(vp->v_mount))
5659 ASSERT_VOP_LOCKED(vp, name);
5661 ASSERT_VOP_ELOCKED(vp, name);
5665 vop_fsync_debugpre(void *a)
5667 struct vop_fsync_args *ap;
5670 vop_fsync_debugprepost(ap->a_vp, "fsync");
5674 vop_fsync_debugpost(void *a, int rc __unused)
5676 struct vop_fsync_args *ap;
5679 vop_fsync_debugprepost(ap->a_vp, "fsync");
5683 vop_fdatasync_debugpre(void *a)
5685 struct vop_fdatasync_args *ap;
5688 vop_fsync_debugprepost(ap->a_vp, "fsync");
5692 vop_fdatasync_debugpost(void *a, int rc __unused)
5694 struct vop_fdatasync_args *ap;
5697 vop_fsync_debugprepost(ap->a_vp, "fsync");
5701 vop_strategy_debugpre(void *ap)
5703 struct vop_strategy_args *a;
5710 * Cluster ops lock their component buffers but not the IO container.
5712 if ((bp->b_flags & B_CLUSTER) != 0)
5715 if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5716 if (vfs_badlock_print)
5718 "VOP_STRATEGY: bp is not locked but should be\n");
5719 if (vfs_badlock_ddb)
5720 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5725 vop_lock_debugpre(void *ap)
5727 struct vop_lock1_args *a = ap;
5729 if ((a->a_flags & LK_INTERLOCK) == 0)
5730 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5732 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5736 vop_lock_debugpost(void *ap, int rc)
5738 struct vop_lock1_args *a = ap;
5740 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5741 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5742 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5746 vop_unlock_debugpre(void *ap)
5748 struct vop_unlock_args *a = ap;
5750 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5754 vop_need_inactive_debugpre(void *ap)
5756 struct vop_need_inactive_args *a = ap;
5758 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5762 vop_need_inactive_debugpost(void *ap, int rc)
5764 struct vop_need_inactive_args *a = ap;
5766 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5771 vop_create_pre(void *ap)
5773 struct vop_create_args *a;
5778 vn_seqc_write_begin(dvp);
5782 vop_create_post(void *ap, int rc)
5784 struct vop_create_args *a;
5789 vn_seqc_write_end(dvp);
5791 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5795 vop_whiteout_pre(void *ap)
5797 struct vop_whiteout_args *a;
5802 vn_seqc_write_begin(dvp);
5806 vop_whiteout_post(void *ap, int rc)
5808 struct vop_whiteout_args *a;
5813 vn_seqc_write_end(dvp);
5817 vop_deleteextattr_pre(void *ap)
5819 struct vop_deleteextattr_args *a;
5824 vn_seqc_write_begin(vp);
5828 vop_deleteextattr_post(void *ap, int rc)
5830 struct vop_deleteextattr_args *a;
5835 vn_seqc_write_end(vp);
5837 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5841 vop_link_pre(void *ap)
5843 struct vop_link_args *a;
5844 struct vnode *vp, *tdvp;
5849 vn_seqc_write_begin(vp);
5850 vn_seqc_write_begin(tdvp);
5854 vop_link_post(void *ap, int rc)
5856 struct vop_link_args *a;
5857 struct vnode *vp, *tdvp;
5862 vn_seqc_write_end(vp);
5863 vn_seqc_write_end(tdvp);
5865 VFS_KNOTE_LOCKED(vp, NOTE_LINK);
5866 VFS_KNOTE_LOCKED(tdvp, NOTE_WRITE);
5871 vop_mkdir_pre(void *ap)
5873 struct vop_mkdir_args *a;
5878 vn_seqc_write_begin(dvp);
5882 vop_mkdir_post(void *ap, int rc)
5884 struct vop_mkdir_args *a;
5889 vn_seqc_write_end(dvp);
5891 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5894 #ifdef DEBUG_VFS_LOCKS
5896 vop_mkdir_debugpost(void *ap, int rc)
5898 struct vop_mkdir_args *a;
5902 cache_validate(a->a_dvp, *a->a_vpp, a->a_cnp);
5907 vop_mknod_pre(void *ap)
5909 struct vop_mknod_args *a;
5914 vn_seqc_write_begin(dvp);
5918 vop_mknod_post(void *ap, int rc)
5920 struct vop_mknod_args *a;
5925 vn_seqc_write_end(dvp);
5927 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5931 vop_reclaim_post(void *ap, int rc)
5933 struct vop_reclaim_args *a;
5938 ASSERT_VOP_IN_SEQC(vp);
5940 VFS_KNOTE_LOCKED(vp, NOTE_REVOKE);
5944 vop_remove_pre(void *ap)
5946 struct vop_remove_args *a;
5947 struct vnode *dvp, *vp;
5952 vn_seqc_write_begin(dvp);
5953 vn_seqc_write_begin(vp);
5957 vop_remove_post(void *ap, int rc)
5959 struct vop_remove_args *a;
5960 struct vnode *dvp, *vp;
5965 vn_seqc_write_end(dvp);
5966 vn_seqc_write_end(vp);
5968 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5969 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5974 vop_rename_post(void *ap, int rc)
5976 struct vop_rename_args *a = ap;
5981 if (a->a_fdvp == a->a_tdvp) {
5982 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5984 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5985 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5987 hint |= NOTE_EXTEND;
5988 if (a->a_fvp->v_type == VDIR)
5990 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5992 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5993 a->a_tvp->v_type == VDIR)
5995 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5998 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
6000 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
6002 if (a->a_tdvp != a->a_fdvp)
6004 if (a->a_tvp != a->a_fvp)
6012 vop_rmdir_pre(void *ap)
6014 struct vop_rmdir_args *a;
6015 struct vnode *dvp, *vp;
6020 vn_seqc_write_begin(dvp);
6021 vn_seqc_write_begin(vp);
6025 vop_rmdir_post(void *ap, int rc)
6027 struct vop_rmdir_args *a;
6028 struct vnode *dvp, *vp;
6033 vn_seqc_write_end(dvp);
6034 vn_seqc_write_end(vp);
6036 vp->v_vflag |= VV_UNLINKED;
6037 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
6038 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
6043 vop_setattr_pre(void *ap)
6045 struct vop_setattr_args *a;
6050 vn_seqc_write_begin(vp);
6054 vop_setattr_post(void *ap, int rc)
6056 struct vop_setattr_args *a;
6061 vn_seqc_write_end(vp);
6063 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6067 vop_setacl_pre(void *ap)
6069 struct vop_setacl_args *a;
6074 vn_seqc_write_begin(vp);
6078 vop_setacl_post(void *ap, int rc __unused)
6080 struct vop_setacl_args *a;
6085 vn_seqc_write_end(vp);
6089 vop_setextattr_pre(void *ap)
6091 struct vop_setextattr_args *a;
6096 vn_seqc_write_begin(vp);
6100 vop_setextattr_post(void *ap, int rc)
6102 struct vop_setextattr_args *a;
6107 vn_seqc_write_end(vp);
6109 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6113 vop_symlink_pre(void *ap)
6115 struct vop_symlink_args *a;
6120 vn_seqc_write_begin(dvp);
6124 vop_symlink_post(void *ap, int rc)
6126 struct vop_symlink_args *a;
6131 vn_seqc_write_end(dvp);
6133 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6137 vop_open_post(void *ap, int rc)
6139 struct vop_open_args *a = ap;
6142 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
6146 vop_close_post(void *ap, int rc)
6148 struct vop_close_args *a = ap;
6150 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
6151 !VN_IS_DOOMED(a->a_vp))) {
6152 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
6153 NOTE_CLOSE_WRITE : NOTE_CLOSE);
6158 vop_read_post(void *ap, int rc)
6160 struct vop_read_args *a = ap;
6163 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6167 vop_read_pgcache_post(void *ap, int rc)
6169 struct vop_read_pgcache_args *a = ap;
6172 VFS_KNOTE_UNLOCKED(a->a_vp, NOTE_READ);
6176 vop_readdir_post(void *ap, int rc)
6178 struct vop_readdir_args *a = ap;
6181 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6184 static struct knlist fs_knlist;
6187 vfs_event_init(void *arg)
6189 knlist_init_mtx(&fs_knlist, NULL);
6191 /* XXX - correct order? */
6192 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
6195 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
6198 KNOTE_UNLOCKED(&fs_knlist, event);
6201 static int filt_fsattach(struct knote *kn);
6202 static void filt_fsdetach(struct knote *kn);
6203 static int filt_fsevent(struct knote *kn, long hint);
6205 struct filterops fs_filtops = {
6207 .f_attach = filt_fsattach,
6208 .f_detach = filt_fsdetach,
6209 .f_event = filt_fsevent
6213 filt_fsattach(struct knote *kn)
6216 kn->kn_flags |= EV_CLEAR;
6217 knlist_add(&fs_knlist, kn, 0);
6222 filt_fsdetach(struct knote *kn)
6225 knlist_remove(&fs_knlist, kn, 0);
6229 filt_fsevent(struct knote *kn, long hint)
6232 kn->kn_fflags |= hint;
6233 return (kn->kn_fflags != 0);
6237 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
6243 error = SYSCTL_IN(req, &vc, sizeof(vc));
6246 if (vc.vc_vers != VFS_CTL_VERS1)
6248 mp = vfs_getvfs(&vc.vc_fsid);
6251 /* ensure that a specific sysctl goes to the right filesystem. */
6252 if (strcmp(vc.vc_fstypename, "*") != 0 &&
6253 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
6257 VCTLTOREQ(&vc, req);
6258 error = VFS_SYSCTL(mp, vc.vc_op, req);
6263 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
6264 NULL, 0, sysctl_vfs_ctl, "",
6268 * Function to initialize a va_filerev field sensibly.
6269 * XXX: Wouldn't a random number make a lot more sense ??
6272 init_va_filerev(void)
6277 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
6280 static int filt_vfsread(struct knote *kn, long hint);
6281 static int filt_vfswrite(struct knote *kn, long hint);
6282 static int filt_vfsvnode(struct knote *kn, long hint);
6283 static void filt_vfsdetach(struct knote *kn);
6284 static struct filterops vfsread_filtops = {
6286 .f_detach = filt_vfsdetach,
6287 .f_event = filt_vfsread
6289 static struct filterops vfswrite_filtops = {
6291 .f_detach = filt_vfsdetach,
6292 .f_event = filt_vfswrite
6294 static struct filterops vfsvnode_filtops = {
6296 .f_detach = filt_vfsdetach,
6297 .f_event = filt_vfsvnode
6301 vfs_knllock(void *arg)
6303 struct vnode *vp = arg;
6305 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
6309 vfs_knlunlock(void *arg)
6311 struct vnode *vp = arg;
6317 vfs_knl_assert_lock(void *arg, int what)
6319 #ifdef DEBUG_VFS_LOCKS
6320 struct vnode *vp = arg;
6322 if (what == LA_LOCKED)
6323 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
6325 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
6330 vfs_kqfilter(struct vop_kqfilter_args *ap)
6332 struct vnode *vp = ap->a_vp;
6333 struct knote *kn = ap->a_kn;
6336 switch (kn->kn_filter) {
6338 kn->kn_fop = &vfsread_filtops;
6341 kn->kn_fop = &vfswrite_filtops;
6344 kn->kn_fop = &vfsvnode_filtops;
6350 kn->kn_hook = (caddr_t)vp;
6353 if (vp->v_pollinfo == NULL)
6355 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
6357 knlist_add(knl, kn, 0);
6363 * Detach knote from vnode
6366 filt_vfsdetach(struct knote *kn)
6368 struct vnode *vp = (struct vnode *)kn->kn_hook;
6370 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
6371 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
6377 filt_vfsread(struct knote *kn, long hint)
6379 struct vnode *vp = (struct vnode *)kn->kn_hook;
6384 * filesystem is gone, so set the EOF flag and schedule
6385 * the knote for deletion.
6387 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6389 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6394 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
6398 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
6399 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
6406 filt_vfswrite(struct knote *kn, long hint)
6408 struct vnode *vp = (struct vnode *)kn->kn_hook;
6413 * filesystem is gone, so set the EOF flag and schedule
6414 * the knote for deletion.
6416 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
6417 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6425 filt_vfsvnode(struct knote *kn, long hint)
6427 struct vnode *vp = (struct vnode *)kn->kn_hook;
6431 if (kn->kn_sfflags & hint)
6432 kn->kn_fflags |= hint;
6433 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6434 kn->kn_flags |= EV_EOF;
6438 res = (kn->kn_fflags != 0);
6444 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6448 if (dp->d_reclen > ap->a_uio->uio_resid)
6449 return (ENAMETOOLONG);
6450 error = uiomove(dp, dp->d_reclen, ap->a_uio);
6452 if (ap->a_ncookies != NULL) {
6453 if (ap->a_cookies != NULL)
6454 free(ap->a_cookies, M_TEMP);
6455 ap->a_cookies = NULL;
6456 *ap->a_ncookies = 0;
6460 if (ap->a_ncookies == NULL)
6463 KASSERT(ap->a_cookies,
6464 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6466 *ap->a_cookies = realloc(*ap->a_cookies,
6467 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
6468 (*ap->a_cookies)[*ap->a_ncookies] = off;
6469 *ap->a_ncookies += 1;
6474 * The purpose of this routine is to remove granularity from accmode_t,
6475 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6476 * VADMIN and VAPPEND.
6478 * If it returns 0, the caller is supposed to continue with the usual
6479 * access checks using 'accmode' as modified by this routine. If it
6480 * returns nonzero value, the caller is supposed to return that value
6483 * Note that after this routine runs, accmode may be zero.
6486 vfs_unixify_accmode(accmode_t *accmode)
6489 * There is no way to specify explicit "deny" rule using
6490 * file mode or POSIX.1e ACLs.
6492 if (*accmode & VEXPLICIT_DENY) {
6498 * None of these can be translated into usual access bits.
6499 * Also, the common case for NFSv4 ACLs is to not contain
6500 * either of these bits. Caller should check for VWRITE
6501 * on the containing directory instead.
6503 if (*accmode & (VDELETE_CHILD | VDELETE))
6506 if (*accmode & VADMIN_PERMS) {
6507 *accmode &= ~VADMIN_PERMS;
6512 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6513 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6515 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6521 * Clear out a doomed vnode (if any) and replace it with a new one as long
6522 * as the fs is not being unmounted. Return the root vnode to the caller.
6524 static int __noinline
6525 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6531 if (mp->mnt_rootvnode != NULL) {
6533 vp = mp->mnt_rootvnode;
6535 if (!VN_IS_DOOMED(vp)) {
6538 error = vn_lock(vp, flags);
6547 * Clear the old one.
6549 mp->mnt_rootvnode = NULL;
6553 vfs_op_barrier_wait(mp);
6557 error = VFS_CACHEDROOT(mp, flags, vpp);
6560 if (mp->mnt_vfs_ops == 0) {
6562 if (mp->mnt_vfs_ops != 0) {
6566 if (mp->mnt_rootvnode == NULL) {
6568 mp->mnt_rootvnode = *vpp;
6570 if (mp->mnt_rootvnode != *vpp) {
6571 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6572 panic("%s: mismatch between vnode returned "
6573 " by VFS_CACHEDROOT and the one cached "
6575 __func__, *vpp, mp->mnt_rootvnode);
6585 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6587 struct mount_pcpu *mpcpu;
6591 if (!vfs_op_thread_enter(mp, mpcpu))
6592 return (vfs_cache_root_fallback(mp, flags, vpp));
6593 vp = atomic_load_ptr(&mp->mnt_rootvnode);
6594 if (vp == NULL || VN_IS_DOOMED(vp)) {
6595 vfs_op_thread_exit(mp, mpcpu);
6596 return (vfs_cache_root_fallback(mp, flags, vpp));
6599 vfs_op_thread_exit(mp, mpcpu);
6600 error = vn_lock(vp, flags);
6603 return (vfs_cache_root_fallback(mp, flags, vpp));
6610 vfs_cache_root_clear(struct mount *mp)
6615 * ops > 0 guarantees there is nobody who can see this vnode
6617 MPASS(mp->mnt_vfs_ops > 0);
6618 vp = mp->mnt_rootvnode;
6620 vn_seqc_write_begin(vp);
6621 mp->mnt_rootvnode = NULL;
6626 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6629 MPASS(mp->mnt_vfs_ops > 0);
6631 mp->mnt_rootvnode = vp;
6635 * These are helper functions for filesystems to traverse all
6636 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6638 * This interface replaces MNT_VNODE_FOREACH.
6642 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6648 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6649 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6650 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6651 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6652 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6655 if (VN_IS_DOOMED(vp)) {
6662 __mnt_vnode_markerfree_all(mvp, mp);
6663 /* MNT_IUNLOCK(mp); -- done in above function */
6664 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6667 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6668 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6674 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6678 *mvp = vn_alloc_marker(mp);
6682 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6683 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6684 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6687 if (VN_IS_DOOMED(vp)) {
6696 vn_free_marker(*mvp);
6700 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6706 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6714 mtx_assert(MNT_MTX(mp), MA_OWNED);
6716 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6717 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6720 vn_free_marker(*mvp);
6725 * These are helper functions for filesystems to traverse their
6726 * lazy vnodes. See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6729 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6732 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6737 vn_free_marker(*mvp);
6742 * Relock the mp mount vnode list lock with the vp vnode interlock in the
6743 * conventional lock order during mnt_vnode_next_lazy iteration.
6745 * On entry, the mount vnode list lock is held and the vnode interlock is not.
6746 * The list lock is dropped and reacquired. On success, both locks are held.
6747 * On failure, the mount vnode list lock is held but the vnode interlock is
6748 * not, and the procedure may have yielded.
6751 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6755 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6756 TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6757 ("%s: bad marker", __func__));
6758 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6759 ("%s: inappropriate vnode", __func__));
6760 ASSERT_VI_UNLOCKED(vp, __func__);
6761 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6763 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6764 TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6767 * Note we may be racing against vdrop which transitioned the hold
6768 * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
6769 * if we are the only user after we get the interlock we will just
6773 mtx_unlock(&mp->mnt_listmtx);
6775 if (VN_IS_DOOMED(vp)) {
6776 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
6779 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
6781 * There is nothing to do if we are the last user.
6783 if (!refcount_release_if_not_last(&vp->v_holdcnt))
6785 mtx_lock(&mp->mnt_listmtx);
6790 mtx_lock(&mp->mnt_listmtx);
6794 static struct vnode *
6795 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6800 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6801 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6803 vp = TAILQ_NEXT(*mvp, v_lazylist);
6804 while (vp != NULL) {
6805 if (vp->v_type == VMARKER) {
6806 vp = TAILQ_NEXT(vp, v_lazylist);
6810 * See if we want to process the vnode. Note we may encounter a
6811 * long string of vnodes we don't care about and hog the list
6812 * as a result. Check for it and requeue the marker.
6814 VNPASS(!VN_IS_DOOMED(vp), vp);
6815 if (!cb(vp, cbarg)) {
6816 if (!should_yield()) {
6817 vp = TAILQ_NEXT(vp, v_lazylist);
6820 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6822 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6824 mtx_unlock(&mp->mnt_listmtx);
6825 kern_yield(PRI_USER);
6826 mtx_lock(&mp->mnt_listmtx);
6830 * Try-lock because this is the wrong lock order.
6832 if (!VI_TRYLOCK(vp) &&
6833 !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6835 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6836 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6837 ("alien vnode on the lazy list %p %p", vp, mp));
6838 VNPASS(vp->v_mount == mp, vp);
6839 VNPASS(!VN_IS_DOOMED(vp), vp);
6842 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6844 /* Check if we are done */
6846 mtx_unlock(&mp->mnt_listmtx);
6847 mnt_vnode_markerfree_lazy(mvp, mp);
6850 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6851 mtx_unlock(&mp->mnt_listmtx);
6852 ASSERT_VI_LOCKED(vp, "lazy iter");
6857 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6862 mtx_lock(&mp->mnt_listmtx);
6863 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6867 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6872 if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
6875 *mvp = vn_alloc_marker(mp);
6880 mtx_lock(&mp->mnt_listmtx);
6881 vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6883 mtx_unlock(&mp->mnt_listmtx);
6884 mnt_vnode_markerfree_lazy(mvp, mp);
6887 TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6888 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6892 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6898 mtx_lock(&mp->mnt_listmtx);
6899 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6900 mtx_unlock(&mp->mnt_listmtx);
6901 mnt_vnode_markerfree_lazy(mvp, mp);
6905 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
6908 if ((cnp->cn_flags & NOEXECCHECK) != 0) {
6909 cnp->cn_flags &= ~NOEXECCHECK;
6913 return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, cnp->cn_thread));
6917 * Do not use this variant unless you have means other than the hold count
6918 * to prevent the vnode from getting freed.
6921 vn_seqc_write_begin_locked(struct vnode *vp)
6924 ASSERT_VI_LOCKED(vp, __func__);
6925 VNPASS(vp->v_holdcnt > 0, vp);
6926 VNPASS(vp->v_seqc_users >= 0, vp);
6928 if (vp->v_seqc_users == 1)
6929 seqc_sleepable_write_begin(&vp->v_seqc);
6933 vn_seqc_write_begin(struct vnode *vp)
6937 vn_seqc_write_begin_locked(vp);
6942 vn_seqc_write_end_locked(struct vnode *vp)
6945 ASSERT_VI_LOCKED(vp, __func__);
6946 VNPASS(vp->v_seqc_users > 0, vp);
6948 if (vp->v_seqc_users == 0)
6949 seqc_sleepable_write_end(&vp->v_seqc);
6953 vn_seqc_write_end(struct vnode *vp)
6957 vn_seqc_write_end_locked(vp);
6962 * Special case handling for allocating and freeing vnodes.
6964 * The counter remains unchanged on free so that a doomed vnode will
6965 * keep testing as in modify as long as it is accessible with SMR.
6968 vn_seqc_init(struct vnode *vp)
6972 vp->v_seqc_users = 0;
6976 vn_seqc_write_end_free(struct vnode *vp)
6979 VNPASS(seqc_in_modify(vp->v_seqc), vp);
6980 VNPASS(vp->v_seqc_users == 1, vp);
6984 vn_irflag_set_locked(struct vnode *vp, short toset)
6988 ASSERT_VI_LOCKED(vp, __func__);
6989 flags = vn_irflag_read(vp);
6990 VNASSERT((flags & toset) == 0, vp,
6991 ("%s: some of the passed flags already set (have %d, passed %d)\n",
6992 __func__, flags, toset));
6993 atomic_store_short(&vp->v_irflag, flags | toset);
6997 vn_irflag_set(struct vnode *vp, short toset)
7001 vn_irflag_set_locked(vp, toset);
7006 vn_irflag_set_cond_locked(struct vnode *vp, short toset)
7010 ASSERT_VI_LOCKED(vp, __func__);
7011 flags = vn_irflag_read(vp);
7012 atomic_store_short(&vp->v_irflag, flags | toset);
7016 vn_irflag_set_cond(struct vnode *vp, short toset)
7020 vn_irflag_set_cond_locked(vp, toset);
7025 vn_irflag_unset_locked(struct vnode *vp, short tounset)
7029 ASSERT_VI_LOCKED(vp, __func__);
7030 flags = vn_irflag_read(vp);
7031 VNASSERT((flags & tounset) == tounset, vp,
7032 ("%s: some of the passed flags not set (have %d, passed %d)\n",
7033 __func__, flags, tounset));
7034 atomic_store_short(&vp->v_irflag, flags & ~tounset);
7038 vn_irflag_unset(struct vnode *vp, short tounset)
7042 vn_irflag_unset_locked(vp, tounset);