2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)vfs_subr.c 8.31 (Berkeley) 5/26/95
40 * External virtual filesystem routines
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
47 #include "opt_watchdog.h"
49 #include <sys/param.h>
50 #include <sys/systm.h>
54 #include <sys/capsicum.h>
55 #include <sys/condvar.h>
57 #include <sys/counter.h>
58 #include <sys/dirent.h>
59 #include <sys/event.h>
60 #include <sys/eventhandler.h>
61 #include <sys/extattr.h>
63 #include <sys/fcntl.h>
66 #include <sys/kernel.h>
67 #include <sys/kthread.h>
69 #include <sys/lockf.h>
70 #include <sys/malloc.h>
71 #include <sys/mount.h>
72 #include <sys/namei.h>
73 #include <sys/pctrie.h>
75 #include <sys/reboot.h>
76 #include <sys/refcount.h>
77 #include <sys/rwlock.h>
78 #include <sys/sched.h>
79 #include <sys/sleepqueue.h>
83 #include <sys/sysctl.h>
84 #include <sys/syslog.h>
85 #include <sys/vmmeter.h>
86 #include <sys/vnode.h>
87 #include <sys/watchdog.h>
89 #include <machine/stdarg.h>
91 #include <security/mac/mac_framework.h>
94 #include <vm/vm_object.h>
95 #include <vm/vm_extern.h>
97 #include <vm/vm_map.h>
98 #include <vm/vm_page.h>
99 #include <vm/vm_kern.h>
106 static void delmntque(struct vnode *vp);
107 static int flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
108 int slpflag, int slptimeo);
109 static void syncer_shutdown(void *arg, int howto);
110 static int vtryrecycle(struct vnode *vp);
111 static void v_init_counters(struct vnode *);
112 static void vn_seqc_init(struct vnode *);
113 static void vn_seqc_write_end_free(struct vnode *vp);
114 static void vgonel(struct vnode *);
115 static bool vhold_recycle_free(struct vnode *);
116 static void vfs_knllock(void *arg);
117 static void vfs_knlunlock(void *arg);
118 static void vfs_knl_assert_lock(void *arg, int what);
119 static void destroy_vpollinfo(struct vpollinfo *vi);
120 static int v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
121 daddr_t startlbn, daddr_t endlbn);
122 static void vnlru_recalc(void);
125 * These fences are intended for cases where some synchronization is
126 * needed between access of v_iflags and lockless vnode refcount (v_holdcnt
127 * and v_usecount) updates. Access to v_iflags is generally synchronized
128 * by the interlock, but we have some internal assertions that check vnode
129 * flags without acquiring the lock. Thus, these fences are INVARIANTS-only
133 #define VNODE_REFCOUNT_FENCE_ACQ() atomic_thread_fence_acq()
134 #define VNODE_REFCOUNT_FENCE_REL() atomic_thread_fence_rel()
136 #define VNODE_REFCOUNT_FENCE_ACQ()
137 #define VNODE_REFCOUNT_FENCE_REL()
141 * Number of vnodes in existence. Increased whenever getnewvnode()
142 * allocates a new vnode, decreased in vdropl() for VIRF_DOOMED vnode.
144 static u_long __exclusive_cache_line numvnodes;
146 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
147 "Number of vnodes in existence");
149 static counter_u64_t vnodes_created;
150 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
151 "Number of vnodes created by getnewvnode");
154 * Conversion tables for conversion from vnode types to inode formats
157 enum vtype iftovt_tab[16] = {
158 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
159 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
161 int vttoif_tab[10] = {
162 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
163 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
167 * List of allocates vnodes in the system.
169 static TAILQ_HEAD(freelst, vnode) vnode_list;
170 static struct vnode *vnode_list_free_marker;
171 static struct vnode *vnode_list_reclaim_marker;
174 * "Free" vnode target. Free vnodes are rarely completely free, but are
175 * just ones that are cheap to recycle. Usually they are for files which
176 * have been stat'd but not read; these usually have inode and namecache
177 * data attached to them. This target is the preferred minimum size of a
178 * sub-cache consisting mostly of such files. The system balances the size
179 * of this sub-cache with its complement to try to prevent either from
180 * thrashing while the other is relatively inactive. The targets express
181 * a preference for the best balance.
183 * "Above" this target there are 2 further targets (watermarks) related
184 * to recyling of free vnodes. In the best-operating case, the cache is
185 * exactly full, the free list has size between vlowat and vhiwat above the
186 * free target, and recycling from it and normal use maintains this state.
187 * Sometimes the free list is below vlowat or even empty, but this state
188 * is even better for immediate use provided the cache is not full.
189 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
190 * ones) to reach one of these states. The watermarks are currently hard-
191 * coded as 4% and 9% of the available space higher. These and the default
192 * of 25% for wantfreevnodes are too large if the memory size is large.
193 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
194 * whenever vnlru_proc() becomes active.
196 static long wantfreevnodes;
197 static long __exclusive_cache_line freevnodes;
198 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
199 &freevnodes, 0, "Number of \"free\" vnodes");
200 static long freevnodes_old;
202 static counter_u64_t recycles_count;
203 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
204 "Number of vnodes recycled to meet vnode cache targets");
206 static counter_u64_t recycles_free_count;
207 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD, &recycles_free_count,
208 "Number of free vnodes recycled to meet vnode cache targets");
210 static counter_u64_t deferred_inact;
211 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, deferred_inact, CTLFLAG_RD, &deferred_inact,
212 "Number of times inactive processing was deferred");
214 /* To keep more than one thread at a time from running vfs_getnewfsid */
215 static struct mtx mntid_mtx;
218 * Lock for any access to the following:
223 static struct mtx __exclusive_cache_line vnode_list_mtx;
225 /* Publicly exported FS */
226 struct nfs_public nfs_pub;
228 static uma_zone_t buf_trie_zone;
229 static smr_t buf_trie_smr;
231 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
232 static uma_zone_t vnode_zone;
233 MALLOC_DEFINE(M_VNODEPOLL, "VN POLL", "vnode poll");
235 __read_frequently smr_t vfs_smr;
238 * The workitem queue.
240 * It is useful to delay writes of file data and filesystem metadata
241 * for tens of seconds so that quickly created and deleted files need
242 * not waste disk bandwidth being created and removed. To realize this,
243 * we append vnodes to a "workitem" queue. When running with a soft
244 * updates implementation, most pending metadata dependencies should
245 * not wait for more than a few seconds. Thus, mounted on block devices
246 * are delayed only about a half the time that file data is delayed.
247 * Similarly, directory updates are more critical, so are only delayed
248 * about a third the time that file data is delayed. Thus, there are
249 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
250 * one each second (driven off the filesystem syncer process). The
251 * syncer_delayno variable indicates the next queue that is to be processed.
252 * Items that need to be processed soon are placed in this queue:
254 * syncer_workitem_pending[syncer_delayno]
256 * A delay of fifteen seconds is done by placing the request fifteen
257 * entries later in the queue:
259 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
262 static int syncer_delayno;
263 static long syncer_mask;
264 LIST_HEAD(synclist, bufobj);
265 static struct synclist *syncer_workitem_pending;
267 * The sync_mtx protects:
272 * syncer_workitem_pending
273 * syncer_worklist_len
276 static struct mtx sync_mtx;
277 static struct cv sync_wakeup;
279 #define SYNCER_MAXDELAY 32
280 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
281 static int syncdelay = 30; /* max time to delay syncing data */
282 static int filedelay = 30; /* time to delay syncing files */
283 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
284 "Time to delay syncing files (in seconds)");
285 static int dirdelay = 29; /* time to delay syncing directories */
286 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
287 "Time to delay syncing directories (in seconds)");
288 static int metadelay = 28; /* time to delay syncing metadata */
289 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
290 "Time to delay syncing metadata (in seconds)");
291 static int rushjob; /* number of slots to run ASAP */
292 static int stat_rush_requests; /* number of times I/O speeded up */
293 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
294 "Number of times I/O speeded up (rush requests)");
296 #define VDBATCH_SIZE 8
301 struct vnode *tab[VDBATCH_SIZE];
303 DPCPU_DEFINE_STATIC(struct vdbatch, vd);
305 static void vdbatch_dequeue(struct vnode *vp);
308 * When shutting down the syncer, run it at four times normal speed.
310 #define SYNCER_SHUTDOWN_SPEEDUP 4
311 static int sync_vnode_count;
312 static int syncer_worklist_len;
313 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
316 /* Target for maximum number of vnodes. */
317 u_long desiredvnodes;
318 static u_long gapvnodes; /* gap between wanted and desired */
319 static u_long vhiwat; /* enough extras after expansion */
320 static u_long vlowat; /* minimal extras before expansion */
321 static u_long vstir; /* nonzero to stir non-free vnodes */
322 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
324 static u_long vnlru_read_freevnodes(void);
327 * Note that no attempt is made to sanitize these parameters.
330 sysctl_maxvnodes(SYSCTL_HANDLER_ARGS)
336 error = sysctl_handle_long(oidp, &val, 0, req);
337 if (error != 0 || req->newptr == NULL)
340 if (val == desiredvnodes)
342 mtx_lock(&vnode_list_mtx);
344 wantfreevnodes = desiredvnodes / 4;
346 mtx_unlock(&vnode_list_mtx);
348 * XXX There is no protection against multiple threads changing
349 * desiredvnodes at the same time. Locking above only helps vnlru and
352 vfs_hash_changesize(desiredvnodes);
353 cache_changesize(desiredvnodes);
357 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
358 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
359 "LU", "Target for maximum number of vnodes");
362 sysctl_wantfreevnodes(SYSCTL_HANDLER_ARGS)
367 val = wantfreevnodes;
368 error = sysctl_handle_long(oidp, &val, 0, req);
369 if (error != 0 || req->newptr == NULL)
372 if (val == wantfreevnodes)
374 mtx_lock(&vnode_list_mtx);
375 wantfreevnodes = val;
377 mtx_unlock(&vnode_list_mtx);
381 SYSCTL_PROC(_vfs, OID_AUTO, wantfreevnodes,
382 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
383 "LU", "Target for minimum number of \"free\" vnodes");
385 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
386 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
387 static int vnlru_nowhere;
388 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
389 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
392 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
397 unsigned long ndflags;
400 if (req->newptr == NULL)
402 if (req->newlen >= PATH_MAX)
405 buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
406 error = SYSCTL_IN(req, buf, req->newlen);
410 buf[req->newlen] = '\0';
412 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | SAVENAME;
413 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
414 if ((error = namei(&nd)) != 0)
418 if (VN_IS_DOOMED(vp)) {
420 * This vnode is being recycled. Return != 0 to let the caller
421 * know that the sysctl had no effect. Return EAGAIN because a
422 * subsequent call will likely succeed (since namei will create
423 * a new vnode if necessary)
429 counter_u64_add(recycles_count, 1);
439 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
441 struct thread *td = curthread;
447 if (req->newptr == NULL)
450 error = sysctl_handle_int(oidp, &fd, 0, req);
453 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
458 error = vn_lock(vp, LK_EXCLUSIVE);
462 counter_u64_add(recycles_count, 1);
470 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
471 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
472 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
473 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
474 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
475 sysctl_ftry_reclaim_vnode, "I",
476 "Try to reclaim a vnode by its file descriptor");
478 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
482 * Support for the bufobj clean & dirty pctrie.
485 buf_trie_alloc(struct pctrie *ptree)
487 return (uma_zalloc_smr(buf_trie_zone, M_NOWAIT));
491 buf_trie_free(struct pctrie *ptree, void *node)
493 uma_zfree_smr(buf_trie_zone, node);
495 PCTRIE_DEFINE_SMR(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free,
499 * Initialize the vnode management data structures.
501 * Reevaluate the following cap on the number of vnodes after the physical
502 * memory size exceeds 512GB. In the limit, as the physical memory size
503 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
505 #ifndef MAXVNODES_MAX
506 #define MAXVNODES_MAX (512UL * 1024 * 1024 / 64) /* 8M */
509 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
511 static struct vnode *
512 vn_alloc_marker(struct mount *mp)
516 vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
517 vp->v_type = VMARKER;
524 vn_free_marker(struct vnode *vp)
527 MPASS(vp->v_type == VMARKER);
528 free(vp, M_VNODE_MARKER);
533 vnode_ctor(void *mem, int size, void *arg __unused, int flags __unused)
535 kasan_mark(mem, size, roundup2(size, UMA_ALIGN_PTR + 1), 0);
540 vnode_dtor(void *mem, int size, void *arg __unused)
542 size_t end1, end2, off1, off2;
544 _Static_assert(offsetof(struct vnode, v_vnodelist) <
545 offsetof(struct vnode, v_dbatchcpu),
546 "KASAN marks require updating");
548 off1 = offsetof(struct vnode, v_vnodelist);
549 off2 = offsetof(struct vnode, v_dbatchcpu);
550 end1 = off1 + sizeof(((struct vnode *)NULL)->v_vnodelist);
551 end2 = off2 + sizeof(((struct vnode *)NULL)->v_dbatchcpu);
554 * Access to the v_vnodelist and v_dbatchcpu fields are permitted even
555 * after the vnode has been freed. Try to get some KASAN coverage by
556 * marking everything except those two fields as invalid. Because
557 * KASAN's tracking is not byte-granular, any preceding fields sharing
558 * the same 8-byte aligned word must also be marked valid.
561 /* Handle the area from the start until v_vnodelist... */
562 off1 = rounddown2(off1, KASAN_SHADOW_SCALE);
563 kasan_mark(mem, off1, off1, KASAN_UMA_FREED);
565 /* ... then the area between v_vnodelist and v_dbatchcpu ... */
566 off1 = roundup2(end1, KASAN_SHADOW_SCALE);
567 off2 = rounddown2(off2, KASAN_SHADOW_SCALE);
569 kasan_mark((void *)((char *)mem + off1), off2 - off1,
570 off2 - off1, KASAN_UMA_FREED);
572 /* ... and finally the area from v_dbatchcpu to the end. */
573 off2 = roundup2(end2, KASAN_SHADOW_SCALE);
574 kasan_mark((void *)((char *)mem + off2), size - off2, size - off2,
580 * Initialize a vnode as it first enters the zone.
583 vnode_init(void *mem, int size, int flags)
592 vp->v_vnlock = &vp->v_lock;
593 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
595 * By default, don't allow shared locks unless filesystems opt-in.
597 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
598 LK_NOSHARE | LK_IS_VNODE);
602 bufobj_init(&vp->v_bufobj, vp);
604 * Initialize namecache.
606 cache_vnode_init(vp);
608 * Initialize rangelocks.
610 rangelock_init(&vp->v_rl);
612 vp->v_dbatchcpu = NOCPU;
615 * Check vhold_recycle_free for an explanation.
617 vp->v_holdcnt = VHOLD_NO_SMR;
619 mtx_lock(&vnode_list_mtx);
620 TAILQ_INSERT_BEFORE(vnode_list_free_marker, vp, v_vnodelist);
621 mtx_unlock(&vnode_list_mtx);
626 * Free a vnode when it is cleared from the zone.
629 vnode_fini(void *mem, int size)
636 mtx_lock(&vnode_list_mtx);
637 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
638 mtx_unlock(&vnode_list_mtx);
639 rangelock_destroy(&vp->v_rl);
640 lockdestroy(vp->v_vnlock);
641 mtx_destroy(&vp->v_interlock);
643 rw_destroy(BO_LOCKPTR(bo));
645 kasan_mark(mem, size, size, 0);
649 * Provide the size of NFS nclnode and NFS fh for calculation of the
650 * vnode memory consumption. The size is specified directly to
651 * eliminate dependency on NFS-private header.
653 * Other filesystems may use bigger or smaller (like UFS and ZFS)
654 * private inode data, but the NFS-based estimation is ample enough.
655 * Still, we care about differences in the size between 64- and 32-bit
658 * Namecache structure size is heuristically
659 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
662 #define NFS_NCLNODE_SZ (528 + 64)
665 #define NFS_NCLNODE_SZ (360 + 32)
670 vntblinit(void *dummy __unused)
675 int cpu, physvnodes, virtvnodes;
679 * Desiredvnodes is a function of the physical memory size and the
680 * kernel's heap size. Generally speaking, it scales with the
681 * physical memory size. The ratio of desiredvnodes to the physical
682 * memory size is 1:16 until desiredvnodes exceeds 98,304.
684 * marginal ratio of desiredvnodes to the physical memory size is
685 * 1:64. However, desiredvnodes is limited by the kernel's heap
686 * size. The memory required by desiredvnodes vnodes and vm objects
687 * must not exceed 1/10th of the kernel's heap size.
689 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
690 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
691 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
692 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
693 desiredvnodes = min(physvnodes, virtvnodes);
694 if (desiredvnodes > MAXVNODES_MAX) {
696 printf("Reducing kern.maxvnodes %lu -> %lu\n",
697 desiredvnodes, MAXVNODES_MAX);
698 desiredvnodes = MAXVNODES_MAX;
700 wantfreevnodes = desiredvnodes / 4;
701 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
702 TAILQ_INIT(&vnode_list);
703 mtx_init(&vnode_list_mtx, "vnode_list", NULL, MTX_DEF);
705 * The lock is taken to appease WITNESS.
707 mtx_lock(&vnode_list_mtx);
709 mtx_unlock(&vnode_list_mtx);
710 vnode_list_free_marker = vn_alloc_marker(NULL);
711 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_free_marker, v_vnodelist);
712 vnode_list_reclaim_marker = vn_alloc_marker(NULL);
713 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_reclaim_marker, v_vnodelist);
722 vnode_zone = uma_zcreate("VNODE", sizeof(struct vnode), ctor, dtor,
723 vnode_init, vnode_fini, UMA_ALIGN_PTR, UMA_ZONE_NOKASAN);
724 uma_zone_set_smr(vnode_zone, vfs_smr);
727 * Preallocate enough nodes to support one-per buf so that
728 * we can not fail an insert. reassignbuf() callers can not
729 * tolerate the insertion failure.
731 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
732 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
733 UMA_ZONE_NOFREE | UMA_ZONE_SMR);
734 buf_trie_smr = uma_zone_get_smr(buf_trie_zone);
735 uma_prealloc(buf_trie_zone, nbuf);
737 vnodes_created = counter_u64_alloc(M_WAITOK);
738 recycles_count = counter_u64_alloc(M_WAITOK);
739 recycles_free_count = counter_u64_alloc(M_WAITOK);
740 deferred_inact = counter_u64_alloc(M_WAITOK);
743 * Initialize the filesystem syncer.
745 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
747 syncer_maxdelay = syncer_mask + 1;
748 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
749 cv_init(&sync_wakeup, "syncer");
750 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
755 vd = DPCPU_ID_PTR((cpu), vd);
756 bzero(vd, sizeof(*vd));
757 mtx_init(&vd->lock, "vdbatch", NULL, MTX_DEF);
760 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
763 * Mark a mount point as busy. Used to synchronize access and to delay
764 * unmounting. Eventually, mountlist_mtx is not released on failure.
766 * vfs_busy() is a custom lock, it can block the caller.
767 * vfs_busy() only sleeps if the unmount is active on the mount point.
768 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
769 * vnode belonging to mp.
771 * Lookup uses vfs_busy() to traverse mount points.
773 * / vnode lock A / vnode lock (/var) D
774 * /var vnode lock B /log vnode lock(/var/log) E
775 * vfs_busy lock C vfs_busy lock F
777 * Within each file system, the lock order is C->A->B and F->D->E.
779 * When traversing across mounts, the system follows that lock order:
785 * The lookup() process for namei("/var") illustrates the process:
786 * VOP_LOOKUP() obtains B while A is held
787 * vfs_busy() obtains a shared lock on F while A and B are held
788 * vput() releases lock on B
789 * vput() releases lock on A
790 * VFS_ROOT() obtains lock on D while shared lock on F is held
791 * vfs_unbusy() releases shared lock on F
792 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
793 * Attempt to lock A (instead of vp_crossmp) while D is held would
794 * violate the global order, causing deadlocks.
796 * dounmount() locks B while F is drained.
799 vfs_busy(struct mount *mp, int flags)
801 struct mount_pcpu *mpcpu;
803 MPASS((flags & ~MBF_MASK) == 0);
804 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
806 if (vfs_op_thread_enter(mp, mpcpu)) {
807 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
808 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
809 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
810 vfs_mp_count_add_pcpu(mpcpu, ref, 1);
811 vfs_mp_count_add_pcpu(mpcpu, lockref, 1);
812 vfs_op_thread_exit(mp, mpcpu);
813 if (flags & MBF_MNTLSTLOCK)
814 mtx_unlock(&mountlist_mtx);
819 vfs_assert_mount_counters(mp);
822 * If mount point is currently being unmounted, sleep until the
823 * mount point fate is decided. If thread doing the unmounting fails,
824 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
825 * that this mount point has survived the unmount attempt and vfs_busy
826 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
827 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
828 * about to be really destroyed. vfs_busy needs to release its
829 * reference on the mount point in this case and return with ENOENT,
830 * telling the caller that mount mount it tried to busy is no longer
833 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
834 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
837 CTR1(KTR_VFS, "%s: failed busying before sleeping",
841 if (flags & MBF_MNTLSTLOCK)
842 mtx_unlock(&mountlist_mtx);
843 mp->mnt_kern_flag |= MNTK_MWAIT;
844 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
845 if (flags & MBF_MNTLSTLOCK)
846 mtx_lock(&mountlist_mtx);
849 if (flags & MBF_MNTLSTLOCK)
850 mtx_unlock(&mountlist_mtx);
857 * Free a busy filesystem.
860 vfs_unbusy(struct mount *mp)
862 struct mount_pcpu *mpcpu;
865 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
867 if (vfs_op_thread_enter(mp, mpcpu)) {
868 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
869 vfs_mp_count_sub_pcpu(mpcpu, lockref, 1);
870 vfs_mp_count_sub_pcpu(mpcpu, ref, 1);
871 vfs_op_thread_exit(mp, mpcpu);
876 vfs_assert_mount_counters(mp);
878 c = --mp->mnt_lockref;
879 if (mp->mnt_vfs_ops == 0) {
880 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
885 vfs_dump_mount_counters(mp);
886 if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
887 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
888 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
889 mp->mnt_kern_flag &= ~MNTK_DRAINING;
890 wakeup(&mp->mnt_lockref);
896 * Lookup a mount point by filesystem identifier.
899 vfs_getvfs(fsid_t *fsid)
903 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
904 mtx_lock(&mountlist_mtx);
905 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
906 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
908 mtx_unlock(&mountlist_mtx);
912 mtx_unlock(&mountlist_mtx);
913 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
914 return ((struct mount *) 0);
918 * Lookup a mount point by filesystem identifier, busying it before
921 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
922 * cache for popular filesystem identifiers. The cache is lockess, using
923 * the fact that struct mount's are never freed. In worst case we may
924 * get pointer to unmounted or even different filesystem, so we have to
925 * check what we got, and go slow way if so.
928 vfs_busyfs(fsid_t *fsid)
930 #define FSID_CACHE_SIZE 256
931 typedef struct mount * volatile vmp_t;
932 static vmp_t cache[FSID_CACHE_SIZE];
937 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
938 hash = fsid->val[0] ^ fsid->val[1];
939 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
941 if (mp == NULL || fsidcmp(&mp->mnt_stat.f_fsid, fsid) != 0)
943 if (vfs_busy(mp, 0) != 0) {
947 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0)
953 mtx_lock(&mountlist_mtx);
954 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
955 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
956 error = vfs_busy(mp, MBF_MNTLSTLOCK);
959 mtx_unlock(&mountlist_mtx);
966 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
967 mtx_unlock(&mountlist_mtx);
968 return ((struct mount *) 0);
972 * Check if a user can access privileged mount options.
975 vfs_suser(struct mount *mp, struct thread *td)
979 if (jailed(td->td_ucred)) {
981 * If the jail of the calling thread lacks permission for
982 * this type of file system, deny immediately.
984 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
988 * If the file system was mounted outside the jail of the
989 * calling thread, deny immediately.
991 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
996 * If file system supports delegated administration, we don't check
997 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
998 * by the file system itself.
999 * If this is not the user that did original mount, we check for
1000 * the PRIV_VFS_MOUNT_OWNER privilege.
1002 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
1003 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
1004 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
1011 * Get a new unique fsid. Try to make its val[0] unique, since this value
1012 * will be used to create fake device numbers for stat(). Also try (but
1013 * not so hard) make its val[0] unique mod 2^16, since some emulators only
1014 * support 16-bit device numbers. We end up with unique val[0]'s for the
1015 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
1017 * Keep in mind that several mounts may be running in parallel. Starting
1018 * the search one past where the previous search terminated is both a
1019 * micro-optimization and a defense against returning the same fsid to
1023 vfs_getnewfsid(struct mount *mp)
1025 static uint16_t mntid_base;
1030 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
1031 mtx_lock(&mntid_mtx);
1032 mtype = mp->mnt_vfc->vfc_typenum;
1033 tfsid.val[1] = mtype;
1034 mtype = (mtype & 0xFF) << 24;
1036 tfsid.val[0] = makedev(255,
1037 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
1039 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
1043 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
1044 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
1045 mtx_unlock(&mntid_mtx);
1049 * Knob to control the precision of file timestamps:
1051 * 0 = seconds only; nanoseconds zeroed.
1052 * 1 = seconds and nanoseconds, accurate within 1/HZ.
1053 * 2 = seconds and nanoseconds, truncated to microseconds.
1054 * >=3 = seconds and nanoseconds, maximum precision.
1056 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
1058 static int timestamp_precision = TSP_USEC;
1059 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
1060 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
1061 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
1062 "3+: sec + ns (max. precision))");
1065 * Get a current timestamp.
1068 vfs_timestamp(struct timespec *tsp)
1072 switch (timestamp_precision) {
1074 tsp->tv_sec = time_second;
1082 TIMEVAL_TO_TIMESPEC(&tv, tsp);
1092 * Set vnode attributes to VNOVAL
1095 vattr_null(struct vattr *vap)
1098 vap->va_type = VNON;
1099 vap->va_size = VNOVAL;
1100 vap->va_bytes = VNOVAL;
1101 vap->va_mode = VNOVAL;
1102 vap->va_nlink = VNOVAL;
1103 vap->va_uid = VNOVAL;
1104 vap->va_gid = VNOVAL;
1105 vap->va_fsid = VNOVAL;
1106 vap->va_fileid = VNOVAL;
1107 vap->va_blocksize = VNOVAL;
1108 vap->va_rdev = VNOVAL;
1109 vap->va_atime.tv_sec = VNOVAL;
1110 vap->va_atime.tv_nsec = VNOVAL;
1111 vap->va_mtime.tv_sec = VNOVAL;
1112 vap->va_mtime.tv_nsec = VNOVAL;
1113 vap->va_ctime.tv_sec = VNOVAL;
1114 vap->va_ctime.tv_nsec = VNOVAL;
1115 vap->va_birthtime.tv_sec = VNOVAL;
1116 vap->va_birthtime.tv_nsec = VNOVAL;
1117 vap->va_flags = VNOVAL;
1118 vap->va_gen = VNOVAL;
1119 vap->va_vaflags = 0;
1123 * Try to reduce the total number of vnodes.
1125 * This routine (and its user) are buggy in at least the following ways:
1126 * - all parameters were picked years ago when RAM sizes were significantly
1128 * - it can pick vnodes based on pages used by the vm object, but filesystems
1129 * like ZFS don't use it making the pick broken
1130 * - since ZFS has its own aging policy it gets partially combated by this one
1131 * - a dedicated method should be provided for filesystems to let them decide
1132 * whether the vnode should be recycled
1134 * This routine is called when we have too many vnodes. It attempts
1135 * to free <count> vnodes and will potentially free vnodes that still
1136 * have VM backing store (VM backing store is typically the cause
1137 * of a vnode blowout so we want to do this). Therefore, this operation
1138 * is not considered cheap.
1140 * A number of conditions may prevent a vnode from being reclaimed.
1141 * the buffer cache may have references on the vnode, a directory
1142 * vnode may still have references due to the namei cache representing
1143 * underlying files, or the vnode may be in active use. It is not
1144 * desirable to reuse such vnodes. These conditions may cause the
1145 * number of vnodes to reach some minimum value regardless of what
1146 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
1148 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1149 * entries if this argument is strue
1150 * @param trigger Only reclaim vnodes with fewer than this many resident
1152 * @param target How many vnodes to reclaim.
1153 * @return The number of vnodes that were reclaimed.
1156 vlrureclaim(bool reclaim_nc_src, int trigger, u_long target)
1158 struct vnode *vp, *mvp;
1160 struct vm_object *object;
1164 mtx_assert(&vnode_list_mtx, MA_OWNED);
1169 mvp = vnode_list_reclaim_marker;
1172 while (done < target) {
1173 vp = TAILQ_NEXT(vp, v_vnodelist);
1174 if (__predict_false(vp == NULL))
1177 if (__predict_false(vp->v_type == VMARKER))
1181 * If it's been deconstructed already, it's still
1182 * referenced, or it exceeds the trigger, skip it.
1183 * Also skip free vnodes. We are trying to make space
1184 * to expand the free list, not reduce it.
1186 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1187 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)))
1190 if (vp->v_type == VBAD || vp->v_type == VNON)
1193 object = atomic_load_ptr(&vp->v_object);
1194 if (object == NULL || object->resident_page_count > trigger) {
1199 * Handle races against vnode allocation. Filesystems lock the
1200 * vnode some time after it gets returned from getnewvnode,
1201 * despite type and hold count being manipulated earlier.
1202 * Resorting to checking v_mount restores guarantees present
1203 * before the global list was reworked to contain all vnodes.
1205 if (!VI_TRYLOCK(vp))
1207 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1211 if (vp->v_mount == NULL) {
1217 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1218 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1219 mtx_unlock(&vnode_list_mtx);
1221 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1223 goto next_iter_unlocked;
1225 if (VOP_LOCK(vp, LK_EXCLUSIVE|LK_NOWAIT) != 0) {
1227 vn_finished_write(mp);
1228 goto next_iter_unlocked;
1232 if (vp->v_usecount > 0 ||
1233 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1234 (vp->v_object != NULL && vp->v_object->handle == vp &&
1235 vp->v_object->resident_page_count > trigger)) {
1238 vn_finished_write(mp);
1239 goto next_iter_unlocked;
1241 counter_u64_add(recycles_count, 1);
1245 vn_finished_write(mp);
1249 kern_yield(PRI_USER);
1250 mtx_lock(&vnode_list_mtx);
1253 MPASS(vp->v_type != VMARKER);
1254 if (!should_yield())
1256 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1257 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1258 mtx_unlock(&vnode_list_mtx);
1259 kern_yield(PRI_USER);
1260 mtx_lock(&vnode_list_mtx);
1263 if (done == 0 && !retried) {
1264 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1265 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1272 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1273 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1275 "limit on vnode free requests per call to the vnlru_free routine");
1278 * Attempt to reduce the free list by the requested amount.
1281 vnlru_free_impl(int count, struct vfsops *mnt_op, struct vnode *mvp)
1287 mtx_assert(&vnode_list_mtx, MA_OWNED);
1288 if (count > max_vnlru_free)
1289 count = max_vnlru_free;
1296 vp = TAILQ_NEXT(vp, v_vnodelist);
1297 if (__predict_false(vp == NULL)) {
1298 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1299 TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1302 if (__predict_false(vp->v_type == VMARKER))
1304 if (vp->v_holdcnt > 0)
1307 * Don't recycle if our vnode is from different type
1308 * of mount point. Note that mp is type-safe, the
1309 * check does not reach unmapped address even if
1310 * vnode is reclaimed.
1312 if (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1313 mp->mnt_op != mnt_op) {
1316 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1319 if (!vhold_recycle_free(vp))
1321 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1322 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1323 mtx_unlock(&vnode_list_mtx);
1324 if (vtryrecycle(vp) == 0)
1326 mtx_lock(&vnode_list_mtx);
1329 return (ocount - count);
1333 vnlru_free_locked(int count)
1336 mtx_assert(&vnode_list_mtx, MA_OWNED);
1337 return (vnlru_free_impl(count, NULL, vnode_list_free_marker));
1341 vnlru_free_vfsops(int count, struct vfsops *mnt_op, struct vnode *mvp)
1344 MPASS(mnt_op != NULL);
1346 VNPASS(mvp->v_type == VMARKER, mvp);
1347 mtx_lock(&vnode_list_mtx);
1348 vnlru_free_impl(count, mnt_op, mvp);
1349 mtx_unlock(&vnode_list_mtx);
1353 * Temporary binary compat, don't use. Call vnlru_free_vfsops instead.
1356 vnlru_free(int count, struct vfsops *mnt_op)
1362 mtx_lock(&vnode_list_mtx);
1363 mvp = vnode_list_free_marker;
1364 if (vnlru_free_impl(count, mnt_op, mvp) == 0) {
1366 * It is possible the marker was moved over eligible vnodes by
1367 * callers which filtered by different ops. If so, start from
1370 if (vnlru_read_freevnodes() > 0) {
1371 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1372 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1374 vnlru_free_impl(count, mnt_op, mvp);
1376 mtx_unlock(&vnode_list_mtx);
1380 vnlru_alloc_marker(void)
1384 mvp = vn_alloc_marker(NULL);
1385 mtx_lock(&vnode_list_mtx);
1386 TAILQ_INSERT_BEFORE(vnode_list_free_marker, mvp, v_vnodelist);
1387 mtx_unlock(&vnode_list_mtx);
1392 vnlru_free_marker(struct vnode *mvp)
1394 mtx_lock(&vnode_list_mtx);
1395 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1396 mtx_unlock(&vnode_list_mtx);
1397 vn_free_marker(mvp);
1404 mtx_assert(&vnode_list_mtx, MA_OWNED);
1405 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1406 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1407 vlowat = vhiwat / 2;
1411 * Attempt to recycle vnodes in a context that is always safe to block.
1412 * Calling vlrurecycle() from the bowels of filesystem code has some
1413 * interesting deadlock problems.
1415 static struct proc *vnlruproc;
1416 static int vnlruproc_sig;
1419 * The main freevnodes counter is only updated when threads requeue their vnode
1420 * batches. CPUs are conditionally walked to compute a more accurate total.
1422 * Limit how much of a slop are we willing to tolerate. Note: the actual value
1423 * at any given moment can still exceed slop, but it should not be by significant
1424 * margin in practice.
1426 #define VNLRU_FREEVNODES_SLOP 128
1428 static __inline void
1429 vfs_freevnodes_inc(void)
1439 static __inline void
1440 vfs_freevnodes_dec(void)
1451 vnlru_read_freevnodes(void)
1457 mtx_assert(&vnode_list_mtx, MA_OWNED);
1458 if (freevnodes > freevnodes_old)
1459 slop = freevnodes - freevnodes_old;
1461 slop = freevnodes_old - freevnodes;
1462 if (slop < VNLRU_FREEVNODES_SLOP)
1463 return (freevnodes >= 0 ? freevnodes : 0);
1464 freevnodes_old = freevnodes;
1466 vd = DPCPU_ID_PTR((cpu), vd);
1467 freevnodes_old += vd->freevnodes;
1469 return (freevnodes_old >= 0 ? freevnodes_old : 0);
1473 vnlru_under(u_long rnumvnodes, u_long limit)
1475 u_long rfreevnodes, space;
1477 if (__predict_false(rnumvnodes > desiredvnodes))
1480 space = desiredvnodes - rnumvnodes;
1481 if (space < limit) {
1482 rfreevnodes = vnlru_read_freevnodes();
1483 if (rfreevnodes > wantfreevnodes)
1484 space += rfreevnodes - wantfreevnodes;
1486 return (space < limit);
1490 vnlru_under_unlocked(u_long rnumvnodes, u_long limit)
1492 long rfreevnodes, space;
1494 if (__predict_false(rnumvnodes > desiredvnodes))
1497 space = desiredvnodes - rnumvnodes;
1498 if (space < limit) {
1499 rfreevnodes = atomic_load_long(&freevnodes);
1500 if (rfreevnodes > wantfreevnodes)
1501 space += rfreevnodes - wantfreevnodes;
1503 return (space < limit);
1510 mtx_assert(&vnode_list_mtx, MA_OWNED);
1511 if (vnlruproc_sig == 0) {
1520 u_long rnumvnodes, rfreevnodes, target;
1521 unsigned long onumvnodes;
1522 int done, force, trigger, usevnodes;
1523 bool reclaim_nc_src, want_reread;
1525 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1526 SHUTDOWN_PRI_FIRST);
1529 want_reread = false;
1531 kproc_suspend_check(vnlruproc);
1532 mtx_lock(&vnode_list_mtx);
1533 rnumvnodes = atomic_load_long(&numvnodes);
1536 force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1537 want_reread = false;
1541 * If numvnodes is too large (due to desiredvnodes being
1542 * adjusted using its sysctl, or emergency growth), first
1543 * try to reduce it by discarding from the free list.
1545 if (rnumvnodes > desiredvnodes) {
1546 vnlru_free_locked(rnumvnodes - desiredvnodes);
1547 rnumvnodes = atomic_load_long(&numvnodes);
1550 * Sleep if the vnode cache is in a good state. This is
1551 * when it is not over-full and has space for about a 4%
1552 * or 9% expansion (by growing its size or inexcessively
1553 * reducing its free list). Otherwise, try to reclaim
1554 * space for a 10% expansion.
1556 if (vstir && force == 0) {
1560 if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1562 wakeup(&vnlruproc_sig);
1563 msleep(vnlruproc, &vnode_list_mtx,
1564 PVFS|PDROP, "vlruwt", hz);
1567 rfreevnodes = vnlru_read_freevnodes();
1569 onumvnodes = rnumvnodes;
1571 * Calculate parameters for recycling. These are the same
1572 * throughout the loop to give some semblance of fairness.
1573 * The trigger point is to avoid recycling vnodes with lots
1574 * of resident pages. We aren't trying to free memory; we
1575 * are trying to recycle or at least free vnodes.
1577 if (rnumvnodes <= desiredvnodes)
1578 usevnodes = rnumvnodes - rfreevnodes;
1580 usevnodes = rnumvnodes;
1584 * The trigger value is is chosen to give a conservatively
1585 * large value to ensure that it alone doesn't prevent
1586 * making progress. The value can easily be so large that
1587 * it is effectively infinite in some congested and
1588 * misconfigured cases, and this is necessary. Normally
1589 * it is about 8 to 100 (pages), which is quite large.
1591 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1593 trigger = vsmalltrigger;
1594 reclaim_nc_src = force >= 3;
1595 target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1596 target = target / 10 + 1;
1597 done = vlrureclaim(reclaim_nc_src, trigger, target);
1598 mtx_unlock(&vnode_list_mtx);
1599 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1600 uma_reclaim(UMA_RECLAIM_DRAIN);
1602 if (force == 0 || force == 1) {
1613 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1616 kern_yield(PRI_USER);
1621 static struct kproc_desc vnlru_kp = {
1626 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1630 * Routines having to do with the management of the vnode table.
1634 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1635 * before we actually vgone(). This function must be called with the vnode
1636 * held to prevent the vnode from being returned to the free list midway
1640 vtryrecycle(struct vnode *vp)
1644 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1645 VNASSERT(vp->v_holdcnt, vp,
1646 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1648 * This vnode may found and locked via some other list, if so we
1649 * can't recycle it yet.
1651 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1653 "%s: impossible to recycle, vp %p lock is already held",
1656 return (EWOULDBLOCK);
1659 * Don't recycle if its filesystem is being suspended.
1661 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1664 "%s: impossible to recycle, cannot start the write for %p",
1670 * If we got this far, we need to acquire the interlock and see if
1671 * anyone picked up this vnode from another list. If not, we will
1672 * mark it with DOOMED via vgonel() so that anyone who does find it
1673 * will skip over it.
1676 if (vp->v_usecount) {
1679 vn_finished_write(vnmp);
1681 "%s: impossible to recycle, %p is already referenced",
1685 if (!VN_IS_DOOMED(vp)) {
1686 counter_u64_add(recycles_free_count, 1);
1691 vn_finished_write(vnmp);
1696 * Allocate a new vnode.
1698 * The operation never returns an error. Returning an error was disabled
1699 * in r145385 (dated 2005) with the following comment:
1701 * XXX Not all VFS_VGET/ffs_vget callers check returns.
1703 * Given the age of this commit (almost 15 years at the time of writing this
1704 * comment) restoring the ability to fail requires a significant audit of
1707 * The routine can try to free a vnode or stall for up to 1 second waiting for
1708 * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1710 static u_long vn_alloc_cyclecount;
1712 static struct vnode * __noinline
1713 vn_alloc_hard(struct mount *mp)
1715 u_long rnumvnodes, rfreevnodes;
1717 mtx_lock(&vnode_list_mtx);
1718 rnumvnodes = atomic_load_long(&numvnodes);
1719 if (rnumvnodes + 1 < desiredvnodes) {
1720 vn_alloc_cyclecount = 0;
1723 rfreevnodes = vnlru_read_freevnodes();
1724 if (vn_alloc_cyclecount++ >= rfreevnodes) {
1725 vn_alloc_cyclecount = 0;
1729 * Grow the vnode cache if it will not be above its target max
1730 * after growing. Otherwise, if the free list is nonempty, try
1731 * to reclaim 1 item from it before growing the cache (possibly
1732 * above its target max if the reclamation failed or is delayed).
1733 * Otherwise, wait for some space. In all cases, schedule
1734 * vnlru_proc() if we are getting short of space. The watermarks
1735 * should be chosen so that we never wait or even reclaim from
1736 * the free list to below its target minimum.
1738 if (vnlru_free_locked(1) > 0)
1740 if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1742 * Wait for space for a new vnode.
1745 msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1746 if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1747 vnlru_read_freevnodes() > 1)
1748 vnlru_free_locked(1);
1751 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1752 if (vnlru_under(rnumvnodes, vlowat))
1754 mtx_unlock(&vnode_list_mtx);
1755 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1758 static struct vnode *
1759 vn_alloc(struct mount *mp)
1763 if (__predict_false(vn_alloc_cyclecount != 0))
1764 return (vn_alloc_hard(mp));
1765 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1766 if (__predict_false(vnlru_under_unlocked(rnumvnodes, vlowat))) {
1767 atomic_subtract_long(&numvnodes, 1);
1768 return (vn_alloc_hard(mp));
1771 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1775 vn_free(struct vnode *vp)
1778 atomic_subtract_long(&numvnodes, 1);
1779 uma_zfree_smr(vnode_zone, vp);
1783 * Return the next vnode from the free list.
1786 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1791 struct lock_object *lo;
1793 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1795 KASSERT(vops->registered,
1796 ("%s: not registered vector op %p\n", __func__, vops));
1799 if (td->td_vp_reserved != NULL) {
1800 vp = td->td_vp_reserved;
1801 td->td_vp_reserved = NULL;
1805 counter_u64_add(vnodes_created, 1);
1807 * Locks are given the generic name "vnode" when created.
1808 * Follow the historic practice of using the filesystem
1809 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1811 * Locks live in a witness group keyed on their name. Thus,
1812 * when a lock is renamed, it must also move from the witness
1813 * group of its old name to the witness group of its new name.
1815 * The change only needs to be made when the vnode moves
1816 * from one filesystem type to another. We ensure that each
1817 * filesystem use a single static name pointer for its tag so
1818 * that we can compare pointers rather than doing a strcmp().
1820 lo = &vp->v_vnlock->lock_object;
1822 if (lo->lo_name != tag) {
1826 WITNESS_DESTROY(lo);
1827 WITNESS_INIT(lo, tag);
1831 * By default, don't allow shared locks unless filesystems opt-in.
1833 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1835 * Finalize various vnode identity bits.
1837 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1838 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1839 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1843 v_init_counters(vp);
1845 vp->v_bufobj.bo_ops = &buf_ops_bio;
1847 if (mp == NULL && vops != &dead_vnodeops)
1848 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1852 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1853 mac_vnode_associate_singlelabel(mp, vp);
1856 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1857 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1858 vp->v_vflag |= VV_NOKNOTE;
1862 * For the filesystems which do not use vfs_hash_insert(),
1863 * still initialize v_hash to have vfs_hash_index() useful.
1864 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1867 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1874 getnewvnode_reserve(void)
1879 MPASS(td->td_vp_reserved == NULL);
1880 td->td_vp_reserved = vn_alloc(NULL);
1884 getnewvnode_drop_reserve(void)
1889 if (td->td_vp_reserved != NULL) {
1890 vn_free(td->td_vp_reserved);
1891 td->td_vp_reserved = NULL;
1895 static void __noinline
1896 freevnode(struct vnode *vp)
1901 * The vnode has been marked for destruction, so free it.
1903 * The vnode will be returned to the zone where it will
1904 * normally remain until it is needed for another vnode. We
1905 * need to cleanup (or verify that the cleanup has already
1906 * been done) any residual data left from its current use
1907 * so as not to contaminate the freshly allocated vnode.
1909 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1911 * Paired with vgone.
1913 vn_seqc_write_end_free(vp);
1916 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1917 VNPASS(vp->v_holdcnt == VHOLD_NO_SMR, vp);
1918 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1919 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1920 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1921 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1922 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1923 ("clean blk trie not empty"));
1924 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1925 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1926 ("dirty blk trie not empty"));
1927 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1928 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1929 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1930 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1931 ("Dangling rangelock waiters"));
1932 VNASSERT((vp->v_iflag & (VI_DOINGINACT | VI_OWEINACT)) == 0, vp,
1933 ("Leaked inactivation"));
1936 mac_vnode_destroy(vp);
1938 if (vp->v_pollinfo != NULL) {
1939 destroy_vpollinfo(vp->v_pollinfo);
1940 vp->v_pollinfo = NULL;
1942 vp->v_mountedhere = NULL;
1945 vp->v_fifoinfo = NULL;
1953 * Delete from old mount point vnode list, if on one.
1956 delmntque(struct vnode *vp)
1960 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
1969 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1970 ("bad mount point vnode list size"));
1971 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1972 mp->mnt_nvnodelistsize--;
1978 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1982 vp->v_op = &dead_vnodeops;
1988 * Insert into list of vnodes for the new mount point, if available.
1991 insmntque1(struct vnode *vp, struct mount *mp,
1992 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1995 KASSERT(vp->v_mount == NULL,
1996 ("insmntque: vnode already on per mount vnode list"));
1997 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1998 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
2001 * We acquire the vnode interlock early to ensure that the
2002 * vnode cannot be recycled by another process releasing a
2003 * holdcnt on it before we get it on both the vnode list
2004 * and the active vnode list. The mount mutex protects only
2005 * manipulation of the vnode list and the vnode freelist
2006 * mutex protects only manipulation of the active vnode list.
2007 * Hence the need to hold the vnode interlock throughout.
2011 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
2012 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
2013 mp->mnt_nvnodelistsize == 0)) &&
2014 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
2023 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
2024 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
2025 ("neg mount point vnode list size"));
2026 mp->mnt_nvnodelistsize++;
2033 insmntque(struct vnode *vp, struct mount *mp)
2036 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
2040 * Flush out and invalidate all buffers associated with a bufobj
2041 * Called with the underlying object locked.
2044 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
2049 if (flags & V_SAVE) {
2050 error = bufobj_wwait(bo, slpflag, slptimeo);
2055 if (bo->bo_dirty.bv_cnt > 0) {
2058 error = BO_SYNC(bo, MNT_WAIT);
2059 } while (error == ERELOOKUP);
2063 * XXX We could save a lock/unlock if this was only
2064 * enabled under INVARIANTS
2067 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
2068 panic("vinvalbuf: dirty bufs");
2072 * If you alter this loop please notice that interlock is dropped and
2073 * reacquired in flushbuflist. Special care is needed to ensure that
2074 * no race conditions occur from this.
2077 error = flushbuflist(&bo->bo_clean,
2078 flags, bo, slpflag, slptimeo);
2079 if (error == 0 && !(flags & V_CLEANONLY))
2080 error = flushbuflist(&bo->bo_dirty,
2081 flags, bo, slpflag, slptimeo);
2082 if (error != 0 && error != EAGAIN) {
2086 } while (error != 0);
2089 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
2090 * have write I/O in-progress but if there is a VM object then the
2091 * VM object can also have read-I/O in-progress.
2094 bufobj_wwait(bo, 0, 0);
2095 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
2097 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
2100 } while (bo->bo_numoutput > 0);
2104 * Destroy the copy in the VM cache, too.
2106 if (bo->bo_object != NULL &&
2107 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
2108 VM_OBJECT_WLOCK(bo->bo_object);
2109 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
2110 OBJPR_CLEANONLY : 0);
2111 VM_OBJECT_WUNLOCK(bo->bo_object);
2116 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
2117 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
2118 bo->bo_clean.bv_cnt > 0))
2119 panic("vinvalbuf: flush failed");
2120 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
2121 bo->bo_dirty.bv_cnt > 0)
2122 panic("vinvalbuf: flush dirty failed");
2129 * Flush out and invalidate all buffers associated with a vnode.
2130 * Called with the underlying object locked.
2133 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
2136 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2137 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
2138 if (vp->v_object != NULL && vp->v_object->handle != vp)
2140 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
2144 * Flush out buffers on the specified list.
2148 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
2151 struct buf *bp, *nbp;
2156 ASSERT_BO_WLOCKED(bo);
2159 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2161 * If we are flushing both V_NORMAL and V_ALT buffers then
2162 * do not skip any buffers. If we are flushing only V_NORMAL
2163 * buffers then skip buffers marked as BX_ALTDATA. If we are
2164 * flushing only V_ALT buffers then skip buffers not marked
2167 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2168 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2169 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2173 lblkno = nbp->b_lblkno;
2174 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2177 error = BUF_TIMELOCK(bp,
2178 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2179 "flushbuf", slpflag, slptimeo);
2182 return (error != ENOLCK ? error : EAGAIN);
2184 KASSERT(bp->b_bufobj == bo,
2185 ("bp %p wrong b_bufobj %p should be %p",
2186 bp, bp->b_bufobj, bo));
2188 * XXX Since there are no node locks for NFS, I
2189 * believe there is a slight chance that a delayed
2190 * write will occur while sleeping just above, so
2193 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2196 bp->b_flags |= B_ASYNC;
2199 return (EAGAIN); /* XXX: why not loop ? */
2202 bp->b_flags |= (B_INVAL | B_RELBUF);
2203 bp->b_flags &= ~B_ASYNC;
2208 nbp = gbincore(bo, lblkno);
2209 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2211 break; /* nbp invalid */
2217 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2223 ASSERT_BO_LOCKED(bo);
2225 for (lblkno = startn;;) {
2227 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2228 if (bp == NULL || bp->b_lblkno >= endn ||
2229 bp->b_lblkno < startn)
2231 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2232 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2235 if (error == ENOLCK)
2239 KASSERT(bp->b_bufobj == bo,
2240 ("bp %p wrong b_bufobj %p should be %p",
2241 bp, bp->b_bufobj, bo));
2242 lblkno = bp->b_lblkno + 1;
2243 if ((bp->b_flags & B_MANAGED) == 0)
2245 bp->b_flags |= B_RELBUF;
2247 * In the VMIO case, use the B_NOREUSE flag to hint that the
2248 * pages backing each buffer in the range are unlikely to be
2249 * reused. Dirty buffers will have the hint applied once
2250 * they've been written.
2252 if ((bp->b_flags & B_VMIO) != 0)
2253 bp->b_flags |= B_NOREUSE;
2261 * Truncate a file's buffer and pages to a specified length. This
2262 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2266 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2268 struct buf *bp, *nbp;
2272 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2273 vp, blksize, (uintmax_t)length);
2276 * Round up to the *next* lbn.
2278 startlbn = howmany(length, blksize);
2280 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2286 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2291 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2292 if (bp->b_lblkno > 0)
2295 * Since we hold the vnode lock this should only
2296 * fail if we're racing with the buf daemon.
2299 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2300 BO_LOCKPTR(bo)) == ENOLCK)
2301 goto restart_unlocked;
2303 VNASSERT((bp->b_flags & B_DELWRI), vp,
2304 ("buf(%p) on dirty queue without DELWRI", bp));
2313 bufobj_wwait(bo, 0, 0);
2315 vnode_pager_setsize(vp, length);
2321 * Invalidate the cached pages of a file's buffer within the range of block
2322 * numbers [startlbn, endlbn).
2325 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2331 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2333 start = blksize * startlbn;
2334 end = blksize * endlbn;
2338 MPASS(blksize == bo->bo_bsize);
2340 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2344 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2348 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2349 daddr_t startlbn, daddr_t endlbn)
2351 struct buf *bp, *nbp;
2354 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2355 ASSERT_BO_LOCKED(bo);
2359 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2360 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2363 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2364 BO_LOCKPTR(bo)) == ENOLCK) {
2370 bp->b_flags |= B_INVAL | B_RELBUF;
2371 bp->b_flags &= ~B_ASYNC;
2377 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2379 (nbp->b_flags & B_DELWRI) != 0))
2383 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2384 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2387 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2388 BO_LOCKPTR(bo)) == ENOLCK) {
2393 bp->b_flags |= B_INVAL | B_RELBUF;
2394 bp->b_flags &= ~B_ASYNC;
2400 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2401 (nbp->b_vp != vp) ||
2402 (nbp->b_flags & B_DELWRI) == 0))
2410 buf_vlist_remove(struct buf *bp)
2415 flags = bp->b_xflags;
2417 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2418 ASSERT_BO_WLOCKED(bp->b_bufobj);
2419 KASSERT((flags & (BX_VNDIRTY | BX_VNCLEAN)) != 0 &&
2420 (flags & (BX_VNDIRTY | BX_VNCLEAN)) != (BX_VNDIRTY | BX_VNCLEAN),
2421 ("%s: buffer %p has invalid queue state", __func__, bp));
2423 if ((flags & BX_VNDIRTY) != 0)
2424 bv = &bp->b_bufobj->bo_dirty;
2426 bv = &bp->b_bufobj->bo_clean;
2427 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2428 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2430 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2434 * Add the buffer to the sorted clean or dirty block list.
2436 * NOTE: xflags is passed as a constant, optimizing this inline function!
2439 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2445 ASSERT_BO_WLOCKED(bo);
2446 KASSERT((bo->bo_flag & BO_NOBUFS) == 0,
2447 ("buf_vlist_add: bo %p does not allow bufs", bo));
2448 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2449 ("dead bo %p", bo));
2450 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2451 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2452 bp->b_xflags |= xflags;
2453 if (xflags & BX_VNDIRTY)
2459 * Keep the list ordered. Optimize empty list insertion. Assume
2460 * we tend to grow at the tail so lookup_le should usually be cheaper
2463 if (bv->bv_cnt == 0 ||
2464 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2465 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2466 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2467 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2469 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2470 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2472 panic("buf_vlist_add: Preallocated nodes insufficient.");
2477 * Look up a buffer using the buffer tries.
2480 gbincore(struct bufobj *bo, daddr_t lblkno)
2484 ASSERT_BO_LOCKED(bo);
2485 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2488 return (BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno));
2492 * Look up a buf using the buffer tries, without the bufobj lock. This relies
2493 * on SMR for safe lookup, and bufs being in a no-free zone to provide type
2494 * stability of the result. Like other lockless lookups, the found buf may
2495 * already be invalid by the time this function returns.
2498 gbincore_unlocked(struct bufobj *bo, daddr_t lblkno)
2502 ASSERT_BO_UNLOCKED(bo);
2503 bp = BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_clean.bv_root, lblkno);
2506 return (BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_dirty.bv_root, lblkno));
2510 * Associate a buffer with a vnode.
2513 bgetvp(struct vnode *vp, struct buf *bp)
2518 ASSERT_BO_WLOCKED(bo);
2519 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2521 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2522 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2523 ("bgetvp: bp already attached! %p", bp));
2529 * Insert onto list for new vnode.
2531 buf_vlist_add(bp, bo, BX_VNCLEAN);
2535 * Disassociate a buffer from a vnode.
2538 brelvp(struct buf *bp)
2543 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2544 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2547 * Delete from old vnode list, if on one.
2549 vp = bp->b_vp; /* XXX */
2552 buf_vlist_remove(bp);
2553 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2554 bo->bo_flag &= ~BO_ONWORKLST;
2555 mtx_lock(&sync_mtx);
2556 LIST_REMOVE(bo, bo_synclist);
2557 syncer_worklist_len--;
2558 mtx_unlock(&sync_mtx);
2561 bp->b_bufobj = NULL;
2567 * Add an item to the syncer work queue.
2570 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2574 ASSERT_BO_WLOCKED(bo);
2576 mtx_lock(&sync_mtx);
2577 if (bo->bo_flag & BO_ONWORKLST)
2578 LIST_REMOVE(bo, bo_synclist);
2580 bo->bo_flag |= BO_ONWORKLST;
2581 syncer_worklist_len++;
2584 if (delay > syncer_maxdelay - 2)
2585 delay = syncer_maxdelay - 2;
2586 slot = (syncer_delayno + delay) & syncer_mask;
2588 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2589 mtx_unlock(&sync_mtx);
2593 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2597 mtx_lock(&sync_mtx);
2598 len = syncer_worklist_len - sync_vnode_count;
2599 mtx_unlock(&sync_mtx);
2600 error = SYSCTL_OUT(req, &len, sizeof(len));
2604 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2605 CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2606 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2608 static struct proc *updateproc;
2609 static void sched_sync(void);
2610 static struct kproc_desc up_kp = {
2615 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2618 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2623 *bo = LIST_FIRST(slp);
2627 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2630 * We use vhold in case the vnode does not
2631 * successfully sync. vhold prevents the vnode from
2632 * going away when we unlock the sync_mtx so that
2633 * we can acquire the vnode interlock.
2636 mtx_unlock(&sync_mtx);
2638 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2640 mtx_lock(&sync_mtx);
2641 return (*bo == LIST_FIRST(slp));
2643 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2644 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2646 vn_finished_write(mp);
2648 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2650 * Put us back on the worklist. The worklist
2651 * routine will remove us from our current
2652 * position and then add us back in at a later
2655 vn_syncer_add_to_worklist(*bo, syncdelay);
2659 mtx_lock(&sync_mtx);
2663 static int first_printf = 1;
2666 * System filesystem synchronizer daemon.
2671 struct synclist *next, *slp;
2674 struct thread *td = curthread;
2676 int net_worklist_len;
2677 int syncer_final_iter;
2681 syncer_final_iter = 0;
2682 syncer_state = SYNCER_RUNNING;
2683 starttime = time_uptime;
2684 td->td_pflags |= TDP_NORUNNINGBUF;
2686 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2689 mtx_lock(&sync_mtx);
2691 if (syncer_state == SYNCER_FINAL_DELAY &&
2692 syncer_final_iter == 0) {
2693 mtx_unlock(&sync_mtx);
2694 kproc_suspend_check(td->td_proc);
2695 mtx_lock(&sync_mtx);
2697 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2698 if (syncer_state != SYNCER_RUNNING &&
2699 starttime != time_uptime) {
2701 printf("\nSyncing disks, vnodes remaining... ");
2704 printf("%d ", net_worklist_len);
2706 starttime = time_uptime;
2709 * Push files whose dirty time has expired. Be careful
2710 * of interrupt race on slp queue.
2712 * Skip over empty worklist slots when shutting down.
2715 slp = &syncer_workitem_pending[syncer_delayno];
2716 syncer_delayno += 1;
2717 if (syncer_delayno == syncer_maxdelay)
2719 next = &syncer_workitem_pending[syncer_delayno];
2721 * If the worklist has wrapped since the
2722 * it was emptied of all but syncer vnodes,
2723 * switch to the FINAL_DELAY state and run
2724 * for one more second.
2726 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2727 net_worklist_len == 0 &&
2728 last_work_seen == syncer_delayno) {
2729 syncer_state = SYNCER_FINAL_DELAY;
2730 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2732 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2733 syncer_worklist_len > 0);
2736 * Keep track of the last time there was anything
2737 * on the worklist other than syncer vnodes.
2738 * Return to the SHUTTING_DOWN state if any
2741 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2742 last_work_seen = syncer_delayno;
2743 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2744 syncer_state = SYNCER_SHUTTING_DOWN;
2745 while (!LIST_EMPTY(slp)) {
2746 error = sync_vnode(slp, &bo, td);
2748 LIST_REMOVE(bo, bo_synclist);
2749 LIST_INSERT_HEAD(next, bo, bo_synclist);
2753 if (first_printf == 0) {
2755 * Drop the sync mutex, because some watchdog
2756 * drivers need to sleep while patting
2758 mtx_unlock(&sync_mtx);
2759 wdog_kern_pat(WD_LASTVAL);
2760 mtx_lock(&sync_mtx);
2763 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2764 syncer_final_iter--;
2766 * The variable rushjob allows the kernel to speed up the
2767 * processing of the filesystem syncer process. A rushjob
2768 * value of N tells the filesystem syncer to process the next
2769 * N seconds worth of work on its queue ASAP. Currently rushjob
2770 * is used by the soft update code to speed up the filesystem
2771 * syncer process when the incore state is getting so far
2772 * ahead of the disk that the kernel memory pool is being
2773 * threatened with exhaustion.
2780 * Just sleep for a short period of time between
2781 * iterations when shutting down to allow some I/O
2784 * If it has taken us less than a second to process the
2785 * current work, then wait. Otherwise start right over
2786 * again. We can still lose time if any single round
2787 * takes more than two seconds, but it does not really
2788 * matter as we are just trying to generally pace the
2789 * filesystem activity.
2791 if (syncer_state != SYNCER_RUNNING ||
2792 time_uptime == starttime) {
2794 sched_prio(td, PPAUSE);
2797 if (syncer_state != SYNCER_RUNNING)
2798 cv_timedwait(&sync_wakeup, &sync_mtx,
2799 hz / SYNCER_SHUTDOWN_SPEEDUP);
2800 else if (time_uptime == starttime)
2801 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2806 * Request the syncer daemon to speed up its work.
2807 * We never push it to speed up more than half of its
2808 * normal turn time, otherwise it could take over the cpu.
2811 speedup_syncer(void)
2815 mtx_lock(&sync_mtx);
2816 if (rushjob < syncdelay / 2) {
2818 stat_rush_requests += 1;
2821 mtx_unlock(&sync_mtx);
2822 cv_broadcast(&sync_wakeup);
2827 * Tell the syncer to speed up its work and run though its work
2828 * list several times, then tell it to shut down.
2831 syncer_shutdown(void *arg, int howto)
2834 if (howto & RB_NOSYNC)
2836 mtx_lock(&sync_mtx);
2837 syncer_state = SYNCER_SHUTTING_DOWN;
2839 mtx_unlock(&sync_mtx);
2840 cv_broadcast(&sync_wakeup);
2841 kproc_shutdown(arg, howto);
2845 syncer_suspend(void)
2848 syncer_shutdown(updateproc, 0);
2855 mtx_lock(&sync_mtx);
2857 syncer_state = SYNCER_RUNNING;
2858 mtx_unlock(&sync_mtx);
2859 cv_broadcast(&sync_wakeup);
2860 kproc_resume(updateproc);
2864 * Move the buffer between the clean and dirty lists of its vnode.
2867 reassignbuf(struct buf *bp)
2879 KASSERT((bp->b_flags & B_PAGING) == 0,
2880 ("%s: cannot reassign paging buffer %p", __func__, bp));
2882 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2883 bp, bp->b_vp, bp->b_flags);
2886 buf_vlist_remove(bp);
2889 * If dirty, put on list of dirty buffers; otherwise insert onto list
2892 if (bp->b_flags & B_DELWRI) {
2893 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2894 switch (vp->v_type) {
2904 vn_syncer_add_to_worklist(bo, delay);
2906 buf_vlist_add(bp, bo, BX_VNDIRTY);
2908 buf_vlist_add(bp, bo, BX_VNCLEAN);
2910 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2911 mtx_lock(&sync_mtx);
2912 LIST_REMOVE(bo, bo_synclist);
2913 syncer_worklist_len--;
2914 mtx_unlock(&sync_mtx);
2915 bo->bo_flag &= ~BO_ONWORKLST;
2920 bp = TAILQ_FIRST(&bv->bv_hd);
2921 KASSERT(bp == NULL || bp->b_bufobj == bo,
2922 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2923 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2924 KASSERT(bp == NULL || bp->b_bufobj == bo,
2925 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2927 bp = TAILQ_FIRST(&bv->bv_hd);
2928 KASSERT(bp == NULL || bp->b_bufobj == bo,
2929 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2930 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2931 KASSERT(bp == NULL || bp->b_bufobj == bo,
2932 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2938 v_init_counters(struct vnode *vp)
2941 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2942 vp, ("%s called for an initialized vnode", __FUNCTION__));
2943 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2945 refcount_init(&vp->v_holdcnt, 1);
2946 refcount_init(&vp->v_usecount, 1);
2950 * Grab a particular vnode from the free list, increment its
2951 * reference count and lock it. VIRF_DOOMED is set if the vnode
2952 * is being destroyed. Only callers who specify LK_RETRY will
2953 * see doomed vnodes. If inactive processing was delayed in
2954 * vput try to do it here.
2956 * usecount is manipulated using atomics without holding any locks.
2958 * holdcnt can be manipulated using atomics without holding any locks,
2959 * except when transitioning 1<->0, in which case the interlock is held.
2961 * Consumers which don't guarantee liveness of the vnode can use SMR to
2962 * try to get a reference. Note this operation can fail since the vnode
2963 * may be awaiting getting freed by the time they get to it.
2966 vget_prep_smr(struct vnode *vp)
2970 VFS_SMR_ASSERT_ENTERED();
2972 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2984 vget_prep(struct vnode *vp)
2988 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2998 vget_abort(struct vnode *vp, enum vgetstate vs)
3009 __assert_unreachable();
3014 vget(struct vnode *vp, int flags)
3019 return (vget_finish(vp, flags, vs));
3023 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
3027 if ((flags & LK_INTERLOCK) != 0)
3028 ASSERT_VI_LOCKED(vp, __func__);
3030 ASSERT_VI_UNLOCKED(vp, __func__);
3031 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3032 VNPASS(vp->v_holdcnt > 0, vp);
3033 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3035 error = vn_lock(vp, flags);
3036 if (__predict_false(error != 0)) {
3038 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
3043 vget_finish_ref(vp, vs);
3048 vget_finish_ref(struct vnode *vp, enum vgetstate vs)
3052 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3053 VNPASS(vp->v_holdcnt > 0, vp);
3054 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3056 if (vs == VGET_USECOUNT)
3060 * We hold the vnode. If the usecount is 0 it will be utilized to keep
3061 * the vnode around. Otherwise someone else lended their hold count and
3062 * we have to drop ours.
3064 old = atomic_fetchadd_int(&vp->v_usecount, 1);
3065 VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
3068 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
3069 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
3071 refcount_release(&vp->v_holdcnt);
3077 vref(struct vnode *vp)
3081 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3083 vget_finish_ref(vp, vs);
3087 vrefact(struct vnode *vp)
3090 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3092 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
3093 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3095 refcount_acquire(&vp->v_usecount);
3100 vlazy(struct vnode *vp)
3104 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
3106 if ((vp->v_mflag & VMP_LAZYLIST) != 0)
3109 * We may get here for inactive routines after the vnode got doomed.
3111 if (VN_IS_DOOMED(vp))
3114 mtx_lock(&mp->mnt_listmtx);
3115 if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
3116 vp->v_mflag |= VMP_LAZYLIST;
3117 TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3118 mp->mnt_lazyvnodelistsize++;
3120 mtx_unlock(&mp->mnt_listmtx);
3124 vunlazy(struct vnode *vp)
3128 ASSERT_VI_LOCKED(vp, __func__);
3129 VNPASS(!VN_IS_DOOMED(vp), vp);
3132 mtx_lock(&mp->mnt_listmtx);
3133 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3135 * Don't remove the vnode from the lazy list if another thread
3136 * has increased the hold count. It may have re-enqueued the
3137 * vnode to the lazy list and is now responsible for its
3140 if (vp->v_holdcnt == 0) {
3141 vp->v_mflag &= ~VMP_LAZYLIST;
3142 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3143 mp->mnt_lazyvnodelistsize--;
3145 mtx_unlock(&mp->mnt_listmtx);
3149 * This routine is only meant to be called from vgonel prior to dooming
3153 vunlazy_gone(struct vnode *vp)
3157 ASSERT_VOP_ELOCKED(vp, __func__);
3158 ASSERT_VI_LOCKED(vp, __func__);
3159 VNPASS(!VN_IS_DOOMED(vp), vp);
3161 if (vp->v_mflag & VMP_LAZYLIST) {
3163 mtx_lock(&mp->mnt_listmtx);
3164 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3165 vp->v_mflag &= ~VMP_LAZYLIST;
3166 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3167 mp->mnt_lazyvnodelistsize--;
3168 mtx_unlock(&mp->mnt_listmtx);
3173 vdefer_inactive(struct vnode *vp)
3176 ASSERT_VI_LOCKED(vp, __func__);
3177 VNASSERT(vp->v_holdcnt > 0, vp,
3178 ("%s: vnode without hold count", __func__));
3179 if (VN_IS_DOOMED(vp)) {
3183 if (vp->v_iflag & VI_DEFINACT) {
3184 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3188 if (vp->v_usecount > 0) {
3189 vp->v_iflag &= ~VI_OWEINACT;
3194 vp->v_iflag |= VI_DEFINACT;
3196 counter_u64_add(deferred_inact, 1);
3200 vdefer_inactive_unlocked(struct vnode *vp)
3204 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3208 vdefer_inactive(vp);
3211 enum vput_op { VRELE, VPUT, VUNREF };
3214 * Handle ->v_usecount transitioning to 0.
3216 * By releasing the last usecount we take ownership of the hold count which
3217 * provides liveness of the vnode, meaning we have to vdrop.
3219 * For all vnodes we may need to perform inactive processing. It requires an
3220 * exclusive lock on the vnode, while it is legal to call here with only a
3221 * shared lock (or no locks). If locking the vnode in an expected manner fails,
3222 * inactive processing gets deferred to the syncer.
3224 * XXX Some filesystems pass in an exclusively locked vnode and strongly depend
3225 * on the lock being held all the way until VOP_INACTIVE. This in particular
3226 * happens with UFS which adds half-constructed vnodes to the hash, where they
3227 * can be found by other code.
3230 vput_final(struct vnode *vp, enum vput_op func)
3235 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3236 VNPASS(vp->v_holdcnt > 0, vp);
3241 * By the time we got here someone else might have transitioned
3242 * the count back to > 0.
3244 if (vp->v_usecount > 0)
3248 * If the vnode is doomed vgone already performed inactive processing
3251 if (VN_IS_DOOMED(vp))
3254 if (__predict_true(VOP_NEED_INACTIVE(vp) == 0))
3257 if (vp->v_iflag & VI_DOINGINACT)
3261 * Locking operations here will drop the interlock and possibly the
3262 * vnode lock, opening a window where the vnode can get doomed all the
3263 * while ->v_usecount is 0. Set VI_OWEINACT to let vgone know to
3266 vp->v_iflag |= VI_OWEINACT;
3267 want_unlock = false;
3271 switch (VOP_ISLOCKED(vp)) {
3277 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3282 * The lock has at least one sharer, but we have no way
3283 * to conclude whether this is us. Play it safe and
3292 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3293 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3299 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3300 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3306 if (func == VUNREF) {
3307 VNASSERT((vp->v_vflag & VV_UNREF) == 0, vp,
3308 ("recursive vunref"));
3309 vp->v_vflag |= VV_UNREF;
3312 error = vinactive(vp);
3315 if (error != ERELOOKUP || !want_unlock)
3317 VOP_LOCK(vp, LK_EXCLUSIVE);
3320 vp->v_vflag &= ~VV_UNREF;
3323 vdefer_inactive(vp);
3333 * Decrement ->v_usecount for a vnode.
3335 * Releasing the last use count requires additional processing, see vput_final
3336 * above for details.
3338 * Comment above each variant denotes lock state on entry and exit.
3343 * out: same as passed in
3346 vrele(struct vnode *vp)
3349 ASSERT_VI_UNLOCKED(vp, __func__);
3350 if (!refcount_release(&vp->v_usecount))
3352 vput_final(vp, VRELE);
3360 vput(struct vnode *vp)
3363 ASSERT_VOP_LOCKED(vp, __func__);
3364 ASSERT_VI_UNLOCKED(vp, __func__);
3365 if (!refcount_release(&vp->v_usecount)) {
3369 vput_final(vp, VPUT);
3377 vunref(struct vnode *vp)
3380 ASSERT_VOP_LOCKED(vp, __func__);
3381 ASSERT_VI_UNLOCKED(vp, __func__);
3382 if (!refcount_release(&vp->v_usecount))
3384 vput_final(vp, VUNREF);
3388 vhold(struct vnode *vp)
3392 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3393 old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3394 VNASSERT(old >= 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3395 ("%s: wrong hold count %d", __func__, old));
3397 vfs_freevnodes_dec();
3401 vholdnz(struct vnode *vp)
3404 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3406 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3407 VNASSERT(old > 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3408 ("%s: wrong hold count %d", __func__, old));
3410 atomic_add_int(&vp->v_holdcnt, 1);
3415 * Grab a hold count unless the vnode is freed.
3417 * Only use this routine if vfs smr is the only protection you have against
3418 * freeing the vnode.
3420 * The code loops trying to add a hold count as long as the VHOLD_NO_SMR flag
3421 * is not set. After the flag is set the vnode becomes immutable to anyone but
3422 * the thread which managed to set the flag.
3424 * It may be tempting to replace the loop with:
3425 * count = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3426 * if (count & VHOLD_NO_SMR) {
3427 * backpedal and error out;
3430 * However, while this is more performant, it hinders debugging by eliminating
3431 * the previously mentioned invariant.
3434 vhold_smr(struct vnode *vp)
3438 VFS_SMR_ASSERT_ENTERED();
3440 count = atomic_load_int(&vp->v_holdcnt);
3442 if (count & VHOLD_NO_SMR) {
3443 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3444 ("non-zero hold count with flags %d\n", count));
3447 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3448 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3450 vfs_freevnodes_dec();
3457 * Hold a free vnode for recycling.
3459 * Note: vnode_init references this comment.
3461 * Attempts to recycle only need the global vnode list lock and have no use for
3464 * However, vnodes get inserted into the global list before they get fully
3465 * initialized and stay there until UMA decides to free the memory. This in
3466 * particular means the target can be found before it becomes usable and after
3467 * it becomes recycled. Picking up such vnodes is guarded with v_holdcnt set to
3470 * Note: the vnode may gain more references after we transition the count 0->1.
3473 vhold_recycle_free(struct vnode *vp)
3477 mtx_assert(&vnode_list_mtx, MA_OWNED);
3479 count = atomic_load_int(&vp->v_holdcnt);
3481 if (count & VHOLD_NO_SMR) {
3482 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3483 ("non-zero hold count with flags %d\n", count));
3486 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3490 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3491 vfs_freevnodes_dec();
3497 static void __noinline
3498 vdbatch_process(struct vdbatch *vd)
3503 mtx_assert(&vd->lock, MA_OWNED);
3504 MPASS(curthread->td_pinned > 0);
3505 MPASS(vd->index == VDBATCH_SIZE);
3507 mtx_lock(&vnode_list_mtx);
3509 freevnodes += vd->freevnodes;
3510 for (i = 0; i < VDBATCH_SIZE; i++) {
3512 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3513 TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3514 MPASS(vp->v_dbatchcpu != NOCPU);
3515 vp->v_dbatchcpu = NOCPU;
3517 mtx_unlock(&vnode_list_mtx);
3519 bzero(vd->tab, sizeof(vd->tab));
3525 vdbatch_enqueue(struct vnode *vp)
3529 ASSERT_VI_LOCKED(vp, __func__);
3530 VNASSERT(!VN_IS_DOOMED(vp), vp,
3531 ("%s: deferring requeue of a doomed vnode", __func__));
3533 if (vp->v_dbatchcpu != NOCPU) {
3540 mtx_lock(&vd->lock);
3541 MPASS(vd->index < VDBATCH_SIZE);
3542 MPASS(vd->tab[vd->index] == NULL);
3544 * A hack: we depend on being pinned so that we know what to put in
3547 vp->v_dbatchcpu = curcpu;
3548 vd->tab[vd->index] = vp;
3551 if (vd->index == VDBATCH_SIZE)
3552 vdbatch_process(vd);
3553 mtx_unlock(&vd->lock);
3558 * This routine must only be called for vnodes which are about to be
3559 * deallocated. Supporting dequeue for arbitrary vndoes would require
3560 * validating that the locked batch matches.
3563 vdbatch_dequeue(struct vnode *vp)
3569 VNASSERT(vp->v_type == VBAD || vp->v_type == VNON, vp,
3570 ("%s: called for a used vnode\n", __func__));
3572 cpu = vp->v_dbatchcpu;
3576 vd = DPCPU_ID_PTR(cpu, vd);
3577 mtx_lock(&vd->lock);
3578 for (i = 0; i < vd->index; i++) {
3579 if (vd->tab[i] != vp)
3581 vp->v_dbatchcpu = NOCPU;
3583 vd->tab[i] = vd->tab[vd->index];
3584 vd->tab[vd->index] = NULL;
3587 mtx_unlock(&vd->lock);
3589 * Either we dequeued the vnode above or the target CPU beat us to it.
3591 MPASS(vp->v_dbatchcpu == NOCPU);
3595 * Drop the hold count of the vnode. If this is the last reference to
3596 * the vnode we place it on the free list unless it has been vgone'd
3597 * (marked VIRF_DOOMED) in which case we will free it.
3599 * Because the vnode vm object keeps a hold reference on the vnode if
3600 * there is at least one resident non-cached page, the vnode cannot
3601 * leave the active list without the page cleanup done.
3603 static void __noinline
3604 vdropl_final(struct vnode *vp)
3607 ASSERT_VI_LOCKED(vp, __func__);
3608 VNPASS(VN_IS_DOOMED(vp), vp);
3610 * Set the VHOLD_NO_SMR flag.
3612 * We may be racing against vhold_smr. If they win we can just pretend
3613 * we never got this far, they will vdrop later.
3615 if (__predict_false(!atomic_cmpset_int(&vp->v_holdcnt, 0, VHOLD_NO_SMR))) {
3616 vfs_freevnodes_inc();
3619 * We lost the aforementioned race. Any subsequent access is
3620 * invalid as they might have managed to vdropl on their own.
3625 * Don't bump freevnodes as this one is going away.
3631 vdrop(struct vnode *vp)
3634 ASSERT_VI_UNLOCKED(vp, __func__);
3635 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3636 if (refcount_release_if_not_last(&vp->v_holdcnt))
3643 vdropl(struct vnode *vp)
3646 ASSERT_VI_LOCKED(vp, __func__);
3647 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3648 if (!refcount_release(&vp->v_holdcnt)) {
3652 VNPASS((vp->v_iflag & VI_OWEINACT) == 0, vp);
3653 VNPASS((vp->v_iflag & VI_DEFINACT) == 0, vp);
3654 if (VN_IS_DOOMED(vp)) {
3659 vfs_freevnodes_inc();
3660 if (vp->v_mflag & VMP_LAZYLIST) {
3664 * Also unlocks the interlock. We can't assert on it as we
3665 * released our hold and by now the vnode might have been
3668 vdbatch_enqueue(vp);
3672 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3673 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3676 vinactivef(struct vnode *vp)
3678 struct vm_object *obj;
3681 ASSERT_VOP_ELOCKED(vp, "vinactive");
3682 ASSERT_VI_LOCKED(vp, "vinactive");
3683 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3684 ("vinactive: recursed on VI_DOINGINACT"));
3685 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3686 vp->v_iflag |= VI_DOINGINACT;
3687 vp->v_iflag &= ~VI_OWEINACT;
3690 * Before moving off the active list, we must be sure that any
3691 * modified pages are converted into the vnode's dirty
3692 * buffers, since these will no longer be checked once the
3693 * vnode is on the inactive list.
3695 * The write-out of the dirty pages is asynchronous. At the
3696 * point that VOP_INACTIVE() is called, there could still be
3697 * pending I/O and dirty pages in the object.
3699 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3700 vm_object_mightbedirty(obj)) {
3701 VM_OBJECT_WLOCK(obj);
3702 vm_object_page_clean(obj, 0, 0, 0);
3703 VM_OBJECT_WUNLOCK(obj);
3705 error = VOP_INACTIVE(vp);
3707 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3708 ("vinactive: lost VI_DOINGINACT"));
3709 vp->v_iflag &= ~VI_DOINGINACT;
3714 vinactive(struct vnode *vp)
3717 ASSERT_VOP_ELOCKED(vp, "vinactive");
3718 ASSERT_VI_LOCKED(vp, "vinactive");
3719 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3721 if ((vp->v_iflag & VI_OWEINACT) == 0)
3723 if (vp->v_iflag & VI_DOINGINACT)
3725 if (vp->v_usecount > 0) {
3726 vp->v_iflag &= ~VI_OWEINACT;
3729 return (vinactivef(vp));
3733 * Remove any vnodes in the vnode table belonging to mount point mp.
3735 * If FORCECLOSE is not specified, there should not be any active ones,
3736 * return error if any are found (nb: this is a user error, not a
3737 * system error). If FORCECLOSE is specified, detach any active vnodes
3740 * If WRITECLOSE is set, only flush out regular file vnodes open for
3743 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3745 * `rootrefs' specifies the base reference count for the root vnode
3746 * of this filesystem. The root vnode is considered busy if its
3747 * v_usecount exceeds this value. On a successful return, vflush(, td)
3748 * will call vrele() on the root vnode exactly rootrefs times.
3749 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3753 static int busyprt = 0; /* print out busy vnodes */
3754 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3758 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3760 struct vnode *vp, *mvp, *rootvp = NULL;
3762 int busy = 0, error;
3764 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3767 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3768 ("vflush: bad args"));
3770 * Get the filesystem root vnode. We can vput() it
3771 * immediately, since with rootrefs > 0, it won't go away.
3773 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3774 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3781 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3783 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3786 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3790 * Skip over a vnodes marked VV_SYSTEM.
3792 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3798 * If WRITECLOSE is set, flush out unlinked but still open
3799 * files (even if open only for reading) and regular file
3800 * vnodes open for writing.
3802 if (flags & WRITECLOSE) {
3803 if (vp->v_object != NULL) {
3804 VM_OBJECT_WLOCK(vp->v_object);
3805 vm_object_page_clean(vp->v_object, 0, 0, 0);
3806 VM_OBJECT_WUNLOCK(vp->v_object);
3809 error = VOP_FSYNC(vp, MNT_WAIT, td);
3810 } while (error == ERELOOKUP);
3814 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3817 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3820 if ((vp->v_type == VNON ||
3821 (error == 0 && vattr.va_nlink > 0)) &&
3822 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3830 * With v_usecount == 0, all we need to do is clear out the
3831 * vnode data structures and we are done.
3833 * If FORCECLOSE is set, forcibly close the vnode.
3835 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3841 vn_printf(vp, "vflush: busy vnode ");
3847 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3849 * If just the root vnode is busy, and if its refcount
3850 * is equal to `rootrefs', then go ahead and kill it.
3853 KASSERT(busy > 0, ("vflush: not busy"));
3854 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3855 ("vflush: usecount %d < rootrefs %d",
3856 rootvp->v_usecount, rootrefs));
3857 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3858 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3866 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3870 for (; rootrefs > 0; rootrefs--)
3876 * Recycle an unused vnode to the front of the free list.
3879 vrecycle(struct vnode *vp)
3884 recycled = vrecyclel(vp);
3890 * vrecycle, with the vp interlock held.
3893 vrecyclel(struct vnode *vp)
3897 ASSERT_VOP_ELOCKED(vp, __func__);
3898 ASSERT_VI_LOCKED(vp, __func__);
3899 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3901 if (vp->v_usecount == 0) {
3909 * Eliminate all activity associated with a vnode
3910 * in preparation for reuse.
3913 vgone(struct vnode *vp)
3921 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3922 struct vnode *lowervp __unused)
3927 * Notify upper mounts about reclaimed or unlinked vnode.
3930 vfs_notify_upper(struct vnode *vp, int event)
3932 static struct vfsops vgonel_vfsops = {
3933 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3934 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3936 struct mount *mp, *ump, *mmp;
3941 if (TAILQ_EMPTY(&mp->mnt_uppers))
3944 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3945 mmp->mnt_op = &vgonel_vfsops;
3946 mmp->mnt_kern_flag |= MNTK_MARKER;
3948 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3949 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3950 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3951 ump = TAILQ_NEXT(ump, mnt_upper_link);
3954 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3957 case VFS_NOTIFY_UPPER_RECLAIM:
3958 VFS_RECLAIM_LOWERVP(ump, vp);
3960 case VFS_NOTIFY_UPPER_UNLINK:
3961 VFS_UNLINK_LOWERVP(ump, vp);
3964 KASSERT(0, ("invalid event %d", event));
3968 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3969 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3972 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3973 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3974 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3975 wakeup(&mp->mnt_uppers);
3981 * vgone, with the vp interlock held.
3984 vgonel(struct vnode *vp)
3989 bool active, doinginact, oweinact;
3991 ASSERT_VOP_ELOCKED(vp, "vgonel");
3992 ASSERT_VI_LOCKED(vp, "vgonel");
3993 VNASSERT(vp->v_holdcnt, vp,
3994 ("vgonel: vp %p has no reference.", vp));
3995 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3999 * Don't vgonel if we're already doomed.
4001 if (VN_IS_DOOMED(vp))
4004 * Paired with freevnode.
4006 vn_seqc_write_begin_locked(vp);
4008 vn_irflag_set_locked(vp, VIRF_DOOMED);
4011 * Check to see if the vnode is in use. If so, we have to
4012 * call VOP_CLOSE() and VOP_INACTIVE().
4014 * It could be that VOP_INACTIVE() requested reclamation, in
4015 * which case we should avoid recursion, so check
4016 * VI_DOINGINACT. This is not precise but good enough.
4018 active = vp->v_usecount > 0;
4019 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4020 doinginact = (vp->v_iflag & VI_DOINGINACT) != 0;
4023 * If we need to do inactive VI_OWEINACT will be set.
4025 if (vp->v_iflag & VI_DEFINACT) {
4026 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
4027 vp->v_iflag &= ~VI_DEFINACT;
4030 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
4033 cache_purge_vgone(vp);
4034 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
4037 * If purging an active vnode, it must be closed and
4038 * deactivated before being reclaimed.
4041 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
4044 if (oweinact || active) {
4047 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4052 if (vp->v_type == VSOCK)
4053 vfs_unp_reclaim(vp);
4056 * Clean out any buffers associated with the vnode.
4057 * If the flush fails, just toss the buffers.
4060 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
4061 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
4062 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
4063 while (vinvalbuf(vp, 0, 0, 0) != 0)
4067 BO_LOCK(&vp->v_bufobj);
4068 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
4069 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
4070 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
4071 vp->v_bufobj.bo_clean.bv_cnt == 0,
4072 ("vp %p bufobj not invalidated", vp));
4075 * For VMIO bufobj, BO_DEAD is set later, or in
4076 * vm_object_terminate() after the object's page queue is
4079 object = vp->v_bufobj.bo_object;
4081 vp->v_bufobj.bo_flag |= BO_DEAD;
4082 BO_UNLOCK(&vp->v_bufobj);
4085 * Handle the VM part. Tmpfs handles v_object on its own (the
4086 * OBJT_VNODE check). Nullfs or other bypassing filesystems
4087 * should not touch the object borrowed from the lower vnode
4088 * (the handle check).
4090 if (object != NULL && object->type == OBJT_VNODE &&
4091 object->handle == vp)
4092 vnode_destroy_vobject(vp);
4095 * Reclaim the vnode.
4097 if (VOP_RECLAIM(vp))
4098 panic("vgone: cannot reclaim");
4100 vn_finished_secondary_write(mp);
4101 VNASSERT(vp->v_object == NULL, vp,
4102 ("vop_reclaim left v_object vp=%p", vp));
4104 * Clear the advisory locks and wake up waiting threads.
4106 (void)VOP_ADVLOCKPURGE(vp);
4109 * Delete from old mount point vnode list.
4113 * Done with purge, reset to the standard lock and invalidate
4117 vp->v_vnlock = &vp->v_lock;
4118 vp->v_op = &dead_vnodeops;
4123 * Print out a description of a vnode.
4125 static const char * const typename[] =
4126 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
4129 _Static_assert((VHOLD_ALL_FLAGS & ~VHOLD_NO_SMR) == 0,
4130 "new hold count flag not added to vn_printf");
4133 vn_printf(struct vnode *vp, const char *fmt, ...)
4136 char buf[256], buf2[16];
4144 printf("%p: ", (void *)vp);
4145 printf("type %s\n", typename[vp->v_type]);
4146 holdcnt = atomic_load_int(&vp->v_holdcnt);
4147 printf(" usecount %d, writecount %d, refcount %d seqc users %d",
4148 vp->v_usecount, vp->v_writecount, holdcnt & ~VHOLD_ALL_FLAGS,
4150 switch (vp->v_type) {
4152 printf(" mountedhere %p\n", vp->v_mountedhere);
4155 printf(" rdev %p\n", vp->v_rdev);
4158 printf(" socket %p\n", vp->v_unpcb);
4161 printf(" fifoinfo %p\n", vp->v_fifoinfo);
4169 if (holdcnt & VHOLD_NO_SMR)
4170 strlcat(buf, "|VHOLD_NO_SMR", sizeof(buf));
4171 printf(" hold count flags (%s)\n", buf + 1);
4175 irflag = vn_irflag_read(vp);
4176 if (irflag & VIRF_DOOMED)
4177 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
4178 if (irflag & VIRF_PGREAD)
4179 strlcat(buf, "|VIRF_PGREAD", sizeof(buf));
4180 if (irflag & VIRF_MOUNTPOINT)
4181 strlcat(buf, "|VIRF_MOUNTPOINT", sizeof(buf));
4182 flags = irflag & ~(VIRF_DOOMED | VIRF_PGREAD | VIRF_MOUNTPOINT);
4184 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
4185 strlcat(buf, buf2, sizeof(buf));
4187 if (vp->v_vflag & VV_ROOT)
4188 strlcat(buf, "|VV_ROOT", sizeof(buf));
4189 if (vp->v_vflag & VV_ISTTY)
4190 strlcat(buf, "|VV_ISTTY", sizeof(buf));
4191 if (vp->v_vflag & VV_NOSYNC)
4192 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
4193 if (vp->v_vflag & VV_ETERNALDEV)
4194 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
4195 if (vp->v_vflag & VV_CACHEDLABEL)
4196 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
4197 if (vp->v_vflag & VV_VMSIZEVNLOCK)
4198 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
4199 if (vp->v_vflag & VV_COPYONWRITE)
4200 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
4201 if (vp->v_vflag & VV_SYSTEM)
4202 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
4203 if (vp->v_vflag & VV_PROCDEP)
4204 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
4205 if (vp->v_vflag & VV_NOKNOTE)
4206 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
4207 if (vp->v_vflag & VV_DELETED)
4208 strlcat(buf, "|VV_DELETED", sizeof(buf));
4209 if (vp->v_vflag & VV_MD)
4210 strlcat(buf, "|VV_MD", sizeof(buf));
4211 if (vp->v_vflag & VV_FORCEINSMQ)
4212 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
4213 if (vp->v_vflag & VV_READLINK)
4214 strlcat(buf, "|VV_READLINK", sizeof(buf));
4215 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4216 VV_CACHEDLABEL | VV_VMSIZEVNLOCK | VV_COPYONWRITE | VV_SYSTEM |
4217 VV_PROCDEP | VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ |
4220 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4221 strlcat(buf, buf2, sizeof(buf));
4223 if (vp->v_iflag & VI_TEXT_REF)
4224 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
4225 if (vp->v_iflag & VI_MOUNT)
4226 strlcat(buf, "|VI_MOUNT", sizeof(buf));
4227 if (vp->v_iflag & VI_DOINGINACT)
4228 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4229 if (vp->v_iflag & VI_OWEINACT)
4230 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4231 if (vp->v_iflag & VI_DEFINACT)
4232 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4233 if (vp->v_iflag & VI_FOPENING)
4234 strlcat(buf, "|VI_FOPENING", sizeof(buf));
4235 flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOINGINACT |
4236 VI_OWEINACT | VI_DEFINACT | VI_FOPENING);
4238 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4239 strlcat(buf, buf2, sizeof(buf));
4241 if (vp->v_mflag & VMP_LAZYLIST)
4242 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4243 flags = vp->v_mflag & ~(VMP_LAZYLIST);
4245 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4246 strlcat(buf, buf2, sizeof(buf));
4248 printf(" flags (%s)", buf + 1);
4249 if (mtx_owned(VI_MTX(vp)))
4250 printf(" VI_LOCKed");
4252 if (vp->v_object != NULL)
4253 printf(" v_object %p ref %d pages %d "
4254 "cleanbuf %d dirtybuf %d\n",
4255 vp->v_object, vp->v_object->ref_count,
4256 vp->v_object->resident_page_count,
4257 vp->v_bufobj.bo_clean.bv_cnt,
4258 vp->v_bufobj.bo_dirty.bv_cnt);
4260 lockmgr_printinfo(vp->v_vnlock);
4261 if (vp->v_data != NULL)
4267 * List all of the locked vnodes in the system.
4268 * Called when debugging the kernel.
4270 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
4276 * Note: because this is DDB, we can't obey the locking semantics
4277 * for these structures, which means we could catch an inconsistent
4278 * state and dereference a nasty pointer. Not much to be done
4281 db_printf("Locked vnodes\n");
4282 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4283 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4284 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4285 vn_printf(vp, "vnode ");
4291 * Show details about the given vnode.
4293 DB_SHOW_COMMAND(vnode, db_show_vnode)
4299 vp = (struct vnode *)addr;
4300 vn_printf(vp, "vnode ");
4304 * Show details about the given mount point.
4306 DB_SHOW_COMMAND(mount, db_show_mount)
4317 /* No address given, print short info about all mount points. */
4318 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4319 db_printf("%p %s on %s (%s)\n", mp,
4320 mp->mnt_stat.f_mntfromname,
4321 mp->mnt_stat.f_mntonname,
4322 mp->mnt_stat.f_fstypename);
4326 db_printf("\nMore info: show mount <addr>\n");
4330 mp = (struct mount *)addr;
4331 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4332 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4335 mflags = mp->mnt_flag;
4336 #define MNT_FLAG(flag) do { \
4337 if (mflags & (flag)) { \
4338 if (buf[0] != '\0') \
4339 strlcat(buf, ", ", sizeof(buf)); \
4340 strlcat(buf, (#flag) + 4, sizeof(buf)); \
4341 mflags &= ~(flag); \
4344 MNT_FLAG(MNT_RDONLY);
4345 MNT_FLAG(MNT_SYNCHRONOUS);
4346 MNT_FLAG(MNT_NOEXEC);
4347 MNT_FLAG(MNT_NOSUID);
4348 MNT_FLAG(MNT_NFS4ACLS);
4349 MNT_FLAG(MNT_UNION);
4350 MNT_FLAG(MNT_ASYNC);
4351 MNT_FLAG(MNT_SUIDDIR);
4352 MNT_FLAG(MNT_SOFTDEP);
4353 MNT_FLAG(MNT_NOSYMFOLLOW);
4354 MNT_FLAG(MNT_GJOURNAL);
4355 MNT_FLAG(MNT_MULTILABEL);
4357 MNT_FLAG(MNT_NOATIME);
4358 MNT_FLAG(MNT_NOCLUSTERR);
4359 MNT_FLAG(MNT_NOCLUSTERW);
4361 MNT_FLAG(MNT_EXRDONLY);
4362 MNT_FLAG(MNT_EXPORTED);
4363 MNT_FLAG(MNT_DEFEXPORTED);
4364 MNT_FLAG(MNT_EXPORTANON);
4365 MNT_FLAG(MNT_EXKERB);
4366 MNT_FLAG(MNT_EXPUBLIC);
4367 MNT_FLAG(MNT_LOCAL);
4368 MNT_FLAG(MNT_QUOTA);
4369 MNT_FLAG(MNT_ROOTFS);
4371 MNT_FLAG(MNT_IGNORE);
4372 MNT_FLAG(MNT_UPDATE);
4373 MNT_FLAG(MNT_DELEXPORT);
4374 MNT_FLAG(MNT_RELOAD);
4375 MNT_FLAG(MNT_FORCE);
4376 MNT_FLAG(MNT_SNAPSHOT);
4377 MNT_FLAG(MNT_BYFSID);
4381 strlcat(buf, ", ", sizeof(buf));
4382 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4383 "0x%016jx", mflags);
4385 db_printf(" mnt_flag = %s\n", buf);
4388 flags = mp->mnt_kern_flag;
4389 #define MNT_KERN_FLAG(flag) do { \
4390 if (flags & (flag)) { \
4391 if (buf[0] != '\0') \
4392 strlcat(buf, ", ", sizeof(buf)); \
4393 strlcat(buf, (#flag) + 5, sizeof(buf)); \
4397 MNT_KERN_FLAG(MNTK_UNMOUNTF);
4398 MNT_KERN_FLAG(MNTK_ASYNC);
4399 MNT_KERN_FLAG(MNTK_SOFTDEP);
4400 MNT_KERN_FLAG(MNTK_DRAINING);
4401 MNT_KERN_FLAG(MNTK_REFEXPIRE);
4402 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4403 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4404 MNT_KERN_FLAG(MNTK_NO_IOPF);
4405 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4406 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4407 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4408 MNT_KERN_FLAG(MNTK_MARKER);
4409 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4410 MNT_KERN_FLAG(MNTK_FPLOOKUP);
4411 MNT_KERN_FLAG(MNTK_NOASYNC);
4412 MNT_KERN_FLAG(MNTK_UNMOUNT);
4413 MNT_KERN_FLAG(MNTK_MWAIT);
4414 MNT_KERN_FLAG(MNTK_SUSPEND);
4415 MNT_KERN_FLAG(MNTK_SUSPEND2);
4416 MNT_KERN_FLAG(MNTK_SUSPENDED);
4417 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4418 MNT_KERN_FLAG(MNTK_NOKNOTE);
4419 #undef MNT_KERN_FLAG
4422 strlcat(buf, ", ", sizeof(buf));
4423 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4426 db_printf(" mnt_kern_flag = %s\n", buf);
4428 db_printf(" mnt_opt = ");
4429 opt = TAILQ_FIRST(mp->mnt_opt);
4431 db_printf("%s", opt->name);
4432 opt = TAILQ_NEXT(opt, link);
4433 while (opt != NULL) {
4434 db_printf(", %s", opt->name);
4435 opt = TAILQ_NEXT(opt, link);
4441 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4442 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4443 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4444 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4445 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4446 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4447 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4448 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4449 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4450 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4451 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4452 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4454 db_printf(" mnt_cred = { uid=%u ruid=%u",
4455 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4456 if (jailed(mp->mnt_cred))
4457 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4459 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4460 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4461 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4462 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4463 db_printf(" mnt_lazyvnodelistsize = %d\n",
4464 mp->mnt_lazyvnodelistsize);
4465 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4466 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4467 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4468 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4469 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4470 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4471 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4472 db_printf(" mnt_secondary_accwrites = %d\n",
4473 mp->mnt_secondary_accwrites);
4474 db_printf(" mnt_gjprovider = %s\n",
4475 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4476 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4478 db_printf("\n\nList of active vnodes\n");
4479 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4480 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4481 vn_printf(vp, "vnode ");
4486 db_printf("\n\nList of inactive vnodes\n");
4487 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4488 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4489 vn_printf(vp, "vnode ");
4498 * Fill in a struct xvfsconf based on a struct vfsconf.
4501 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4503 struct xvfsconf xvfsp;
4505 bzero(&xvfsp, sizeof(xvfsp));
4506 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4507 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4508 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4509 xvfsp.vfc_flags = vfsp->vfc_flags;
4511 * These are unused in userland, we keep them
4512 * to not break binary compatibility.
4514 xvfsp.vfc_vfsops = NULL;
4515 xvfsp.vfc_next = NULL;
4516 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4519 #ifdef COMPAT_FREEBSD32
4521 uint32_t vfc_vfsops;
4522 char vfc_name[MFSNAMELEN];
4523 int32_t vfc_typenum;
4524 int32_t vfc_refcount;
4530 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4532 struct xvfsconf32 xvfsp;
4534 bzero(&xvfsp, sizeof(xvfsp));
4535 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4536 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4537 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4538 xvfsp.vfc_flags = vfsp->vfc_flags;
4539 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4544 * Top level filesystem related information gathering.
4547 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4549 struct vfsconf *vfsp;
4554 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4555 #ifdef COMPAT_FREEBSD32
4556 if (req->flags & SCTL_MASK32)
4557 error = vfsconf2x32(req, vfsp);
4560 error = vfsconf2x(req, vfsp);
4568 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4569 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4570 "S,xvfsconf", "List of all configured filesystems");
4572 #ifndef BURN_BRIDGES
4573 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4576 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4578 int *name = (int *)arg1 - 1; /* XXX */
4579 u_int namelen = arg2 + 1; /* XXX */
4580 struct vfsconf *vfsp;
4582 log(LOG_WARNING, "userland calling deprecated sysctl, "
4583 "please rebuild world\n");
4585 #if 1 || defined(COMPAT_PRELITE2)
4586 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4588 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4592 case VFS_MAXTYPENUM:
4595 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4598 return (ENOTDIR); /* overloaded */
4600 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4601 if (vfsp->vfc_typenum == name[2])
4606 return (EOPNOTSUPP);
4607 #ifdef COMPAT_FREEBSD32
4608 if (req->flags & SCTL_MASK32)
4609 return (vfsconf2x32(req, vfsp));
4612 return (vfsconf2x(req, vfsp));
4614 return (EOPNOTSUPP);
4617 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4618 CTLFLAG_MPSAFE, vfs_sysctl,
4619 "Generic filesystem");
4621 #if 1 || defined(COMPAT_PRELITE2)
4624 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4627 struct vfsconf *vfsp;
4628 struct ovfsconf ovfs;
4631 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4632 bzero(&ovfs, sizeof(ovfs));
4633 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4634 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4635 ovfs.vfc_index = vfsp->vfc_typenum;
4636 ovfs.vfc_refcount = vfsp->vfc_refcount;
4637 ovfs.vfc_flags = vfsp->vfc_flags;
4638 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4648 #endif /* 1 || COMPAT_PRELITE2 */
4649 #endif /* !BURN_BRIDGES */
4651 #define KINFO_VNODESLOP 10
4654 * Dump vnode list (via sysctl).
4658 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4666 * Stale numvnodes access is not fatal here.
4669 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4671 /* Make an estimate */
4672 return (SYSCTL_OUT(req, 0, len));
4674 error = sysctl_wire_old_buffer(req, 0);
4677 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4679 mtx_lock(&mountlist_mtx);
4680 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4681 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4684 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4688 xvn[n].xv_size = sizeof *xvn;
4689 xvn[n].xv_vnode = vp;
4690 xvn[n].xv_id = 0; /* XXX compat */
4691 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4693 XV_COPY(writecount);
4699 xvn[n].xv_flag = vp->v_vflag;
4701 switch (vp->v_type) {
4708 if (vp->v_rdev == NULL) {
4712 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4715 xvn[n].xv_socket = vp->v_socket;
4718 xvn[n].xv_fifo = vp->v_fifoinfo;
4723 /* shouldn't happen? */
4731 mtx_lock(&mountlist_mtx);
4736 mtx_unlock(&mountlist_mtx);
4738 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4743 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4744 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4749 unmount_or_warn(struct mount *mp)
4753 error = dounmount(mp, MNT_FORCE, curthread);
4755 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4759 printf("%d)\n", error);
4764 * Unmount all filesystems. The list is traversed in reverse order
4765 * of mounting to avoid dependencies.
4768 vfs_unmountall(void)
4770 struct mount *mp, *tmp;
4772 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4775 * Since this only runs when rebooting, it is not interlocked.
4777 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4781 * Forcibly unmounting "/dev" before "/" would prevent clean
4782 * unmount of the latter.
4784 if (mp == rootdevmp)
4787 unmount_or_warn(mp);
4790 if (rootdevmp != NULL)
4791 unmount_or_warn(rootdevmp);
4795 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4798 ASSERT_VI_LOCKED(vp, __func__);
4799 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4800 if ((vp->v_iflag & VI_OWEINACT) == 0) {
4804 if (vn_lock(vp, lkflags) == 0) {
4811 vdefer_inactive_unlocked(vp);
4815 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4818 return (vp->v_iflag & VI_DEFINACT);
4821 static void __noinline
4822 vfs_periodic_inactive(struct mount *mp, int flags)
4824 struct vnode *vp, *mvp;
4827 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4828 if (flags != MNT_WAIT)
4829 lkflags |= LK_NOWAIT;
4831 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4832 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4836 vp->v_iflag &= ~VI_DEFINACT;
4837 vfs_deferred_inactive(vp, lkflags);
4842 vfs_want_msync(struct vnode *vp)
4844 struct vm_object *obj;
4847 * This test may be performed without any locks held.
4848 * We rely on vm_object's type stability.
4850 if (vp->v_vflag & VV_NOSYNC)
4853 return (obj != NULL && vm_object_mightbedirty(obj));
4857 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4860 if (vp->v_vflag & VV_NOSYNC)
4862 if (vp->v_iflag & VI_DEFINACT)
4864 return (vfs_want_msync(vp));
4867 static void __noinline
4868 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4870 struct vnode *vp, *mvp;
4871 struct vm_object *obj;
4872 int lkflags, objflags;
4875 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4876 if (flags != MNT_WAIT) {
4877 lkflags |= LK_NOWAIT;
4878 objflags = OBJPC_NOSYNC;
4880 objflags = OBJPC_SYNC;
4883 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4885 if (vp->v_iflag & VI_DEFINACT) {
4886 vp->v_iflag &= ~VI_DEFINACT;
4889 if (!vfs_want_msync(vp)) {
4891 vfs_deferred_inactive(vp, lkflags);
4896 if (vget(vp, lkflags) == 0) {
4898 if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4899 VM_OBJECT_WLOCK(obj);
4900 vm_object_page_clean(obj, 0, 0, objflags);
4901 VM_OBJECT_WUNLOCK(obj);
4908 vdefer_inactive_unlocked(vp);
4914 vfs_periodic(struct mount *mp, int flags)
4917 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4919 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4920 vfs_periodic_inactive(mp, flags);
4922 vfs_periodic_msync_inactive(mp, flags);
4926 destroy_vpollinfo_free(struct vpollinfo *vi)
4929 knlist_destroy(&vi->vpi_selinfo.si_note);
4930 mtx_destroy(&vi->vpi_lock);
4931 free(vi, M_VNODEPOLL);
4935 destroy_vpollinfo(struct vpollinfo *vi)
4938 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4939 seldrain(&vi->vpi_selinfo);
4940 destroy_vpollinfo_free(vi);
4944 * Initialize per-vnode helper structure to hold poll-related state.
4947 v_addpollinfo(struct vnode *vp)
4949 struct vpollinfo *vi;
4951 if (vp->v_pollinfo != NULL)
4953 vi = malloc(sizeof(*vi), M_VNODEPOLL, M_WAITOK | M_ZERO);
4954 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4955 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4956 vfs_knlunlock, vfs_knl_assert_lock);
4958 if (vp->v_pollinfo != NULL) {
4960 destroy_vpollinfo_free(vi);
4963 vp->v_pollinfo = vi;
4968 * Record a process's interest in events which might happen to
4969 * a vnode. Because poll uses the historic select-style interface
4970 * internally, this routine serves as both the ``check for any
4971 * pending events'' and the ``record my interest in future events''
4972 * functions. (These are done together, while the lock is held,
4973 * to avoid race conditions.)
4976 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4980 mtx_lock(&vp->v_pollinfo->vpi_lock);
4981 if (vp->v_pollinfo->vpi_revents & events) {
4983 * This leaves events we are not interested
4984 * in available for the other process which
4985 * which presumably had requested them
4986 * (otherwise they would never have been
4989 events &= vp->v_pollinfo->vpi_revents;
4990 vp->v_pollinfo->vpi_revents &= ~events;
4992 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4995 vp->v_pollinfo->vpi_events |= events;
4996 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4997 mtx_unlock(&vp->v_pollinfo->vpi_lock);
5002 * Routine to create and manage a filesystem syncer vnode.
5004 #define sync_close ((int (*)(struct vop_close_args *))nullop)
5005 static int sync_fsync(struct vop_fsync_args *);
5006 static int sync_inactive(struct vop_inactive_args *);
5007 static int sync_reclaim(struct vop_reclaim_args *);
5009 static struct vop_vector sync_vnodeops = {
5010 .vop_bypass = VOP_EOPNOTSUPP,
5011 .vop_close = sync_close, /* close */
5012 .vop_fsync = sync_fsync, /* fsync */
5013 .vop_inactive = sync_inactive, /* inactive */
5014 .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
5015 .vop_reclaim = sync_reclaim, /* reclaim */
5016 .vop_lock1 = vop_stdlock, /* lock */
5017 .vop_unlock = vop_stdunlock, /* unlock */
5018 .vop_islocked = vop_stdislocked, /* islocked */
5020 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
5023 * Create a new filesystem syncer vnode for the specified mount point.
5026 vfs_allocate_syncvnode(struct mount *mp)
5030 static long start, incr, next;
5033 /* Allocate a new vnode */
5034 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
5036 panic("vfs_allocate_syncvnode: getnewvnode() failed");
5038 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5039 vp->v_vflag |= VV_FORCEINSMQ;
5040 error = insmntque(vp, mp);
5042 panic("vfs_allocate_syncvnode: insmntque() failed");
5043 vp->v_vflag &= ~VV_FORCEINSMQ;
5046 * Place the vnode onto the syncer worklist. We attempt to
5047 * scatter them about on the list so that they will go off
5048 * at evenly distributed times even if all the filesystems
5049 * are mounted at once.
5052 if (next == 0 || next > syncer_maxdelay) {
5056 start = syncer_maxdelay / 2;
5057 incr = syncer_maxdelay;
5063 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
5064 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
5065 mtx_lock(&sync_mtx);
5067 if (mp->mnt_syncer == NULL) {
5068 mp->mnt_syncer = vp;
5071 mtx_unlock(&sync_mtx);
5074 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5081 vfs_deallocate_syncvnode(struct mount *mp)
5085 mtx_lock(&sync_mtx);
5086 vp = mp->mnt_syncer;
5088 mp->mnt_syncer = NULL;
5089 mtx_unlock(&sync_mtx);
5095 * Do a lazy sync of the filesystem.
5098 sync_fsync(struct vop_fsync_args *ap)
5100 struct vnode *syncvp = ap->a_vp;
5101 struct mount *mp = syncvp->v_mount;
5106 * We only need to do something if this is a lazy evaluation.
5108 if (ap->a_waitfor != MNT_LAZY)
5112 * Move ourselves to the back of the sync list.
5114 bo = &syncvp->v_bufobj;
5116 vn_syncer_add_to_worklist(bo, syncdelay);
5120 * Walk the list of vnodes pushing all that are dirty and
5121 * not already on the sync list.
5123 if (vfs_busy(mp, MBF_NOWAIT) != 0)
5125 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
5129 save = curthread_pflags_set(TDP_SYNCIO);
5131 * The filesystem at hand may be idle with free vnodes stored in the
5132 * batch. Return them instead of letting them stay there indefinitely.
5134 vfs_periodic(mp, MNT_NOWAIT);
5135 error = VFS_SYNC(mp, MNT_LAZY);
5136 curthread_pflags_restore(save);
5137 vn_finished_write(mp);
5143 * The syncer vnode is no referenced.
5146 sync_inactive(struct vop_inactive_args *ap)
5154 * The syncer vnode is no longer needed and is being decommissioned.
5156 * Modifications to the worklist must be protected by sync_mtx.
5159 sync_reclaim(struct vop_reclaim_args *ap)
5161 struct vnode *vp = ap->a_vp;
5166 mtx_lock(&sync_mtx);
5167 if (vp->v_mount->mnt_syncer == vp)
5168 vp->v_mount->mnt_syncer = NULL;
5169 if (bo->bo_flag & BO_ONWORKLST) {
5170 LIST_REMOVE(bo, bo_synclist);
5171 syncer_worklist_len--;
5173 bo->bo_flag &= ~BO_ONWORKLST;
5175 mtx_unlock(&sync_mtx);
5182 vn_need_pageq_flush(struct vnode *vp)
5184 struct vm_object *obj;
5187 return (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
5188 vm_object_mightbedirty(obj));
5192 * Check if vnode represents a disk device
5195 vn_isdisk_error(struct vnode *vp, int *errp)
5199 if (vp->v_type != VCHR) {
5205 if (vp->v_rdev == NULL)
5207 else if (vp->v_rdev->si_devsw == NULL)
5209 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5214 return (error == 0);
5218 vn_isdisk(struct vnode *vp)
5222 return (vn_isdisk_error(vp, &error));
5226 * VOP_FPLOOKUP_VEXEC routines are subject to special circumstances, see
5227 * the comment above cache_fplookup for details.
5230 vaccess_vexec_smr(mode_t file_mode, uid_t file_uid, gid_t file_gid, struct ucred *cred)
5234 VFS_SMR_ASSERT_ENTERED();
5236 /* Check the owner. */
5237 if (cred->cr_uid == file_uid) {
5238 if (file_mode & S_IXUSR)
5243 /* Otherwise, check the groups (first match) */
5244 if (groupmember(file_gid, cred)) {
5245 if (file_mode & S_IXGRP)
5250 /* Otherwise, check everyone else. */
5251 if (file_mode & S_IXOTH)
5255 * Permission check failed, but it is possible denial will get overwritten
5256 * (e.g., when root is traversing through a 700 directory owned by someone
5259 * vaccess() calls priv_check_cred which in turn can descent into MAC
5260 * modules overriding this result. It's quite unclear what semantics
5261 * are allowed for them to operate, thus for safety we don't call them
5262 * from within the SMR section. This also means if any such modules
5263 * are present, we have to let the regular lookup decide.
5265 error = priv_check_cred_vfs_lookup_nomac(cred);
5271 * MAC modules present.
5282 * Common filesystem object access control check routine. Accepts a
5283 * vnode's type, "mode", uid and gid, requested access mode, and credentials.
5284 * Returns 0 on success, or an errno on failure.
5287 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5288 accmode_t accmode, struct ucred *cred)
5290 accmode_t dac_granted;
5291 accmode_t priv_granted;
5293 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5294 ("invalid bit in accmode"));
5295 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5296 ("VAPPEND without VWRITE"));
5299 * Look for a normal, non-privileged way to access the file/directory
5300 * as requested. If it exists, go with that.
5305 /* Check the owner. */
5306 if (cred->cr_uid == file_uid) {
5307 dac_granted |= VADMIN;
5308 if (file_mode & S_IXUSR)
5309 dac_granted |= VEXEC;
5310 if (file_mode & S_IRUSR)
5311 dac_granted |= VREAD;
5312 if (file_mode & S_IWUSR)
5313 dac_granted |= (VWRITE | VAPPEND);
5315 if ((accmode & dac_granted) == accmode)
5321 /* Otherwise, check the groups (first match) */
5322 if (groupmember(file_gid, cred)) {
5323 if (file_mode & S_IXGRP)
5324 dac_granted |= VEXEC;
5325 if (file_mode & S_IRGRP)
5326 dac_granted |= VREAD;
5327 if (file_mode & S_IWGRP)
5328 dac_granted |= (VWRITE | VAPPEND);
5330 if ((accmode & dac_granted) == accmode)
5336 /* Otherwise, check everyone else. */
5337 if (file_mode & S_IXOTH)
5338 dac_granted |= VEXEC;
5339 if (file_mode & S_IROTH)
5340 dac_granted |= VREAD;
5341 if (file_mode & S_IWOTH)
5342 dac_granted |= (VWRITE | VAPPEND);
5343 if ((accmode & dac_granted) == accmode)
5348 * Build a privilege mask to determine if the set of privileges
5349 * satisfies the requirements when combined with the granted mask
5350 * from above. For each privilege, if the privilege is required,
5351 * bitwise or the request type onto the priv_granted mask.
5357 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5358 * requests, instead of PRIV_VFS_EXEC.
5360 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5361 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5362 priv_granted |= VEXEC;
5365 * Ensure that at least one execute bit is on. Otherwise,
5366 * a privileged user will always succeed, and we don't want
5367 * this to happen unless the file really is executable.
5369 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5370 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5371 !priv_check_cred(cred, PRIV_VFS_EXEC))
5372 priv_granted |= VEXEC;
5375 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5376 !priv_check_cred(cred, PRIV_VFS_READ))
5377 priv_granted |= VREAD;
5379 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5380 !priv_check_cred(cred, PRIV_VFS_WRITE))
5381 priv_granted |= (VWRITE | VAPPEND);
5383 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5384 !priv_check_cred(cred, PRIV_VFS_ADMIN))
5385 priv_granted |= VADMIN;
5387 if ((accmode & (priv_granted | dac_granted)) == accmode) {
5391 return ((accmode & VADMIN) ? EPERM : EACCES);
5395 * Credential check based on process requesting service, and per-attribute
5399 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5400 struct thread *td, accmode_t accmode)
5404 * Kernel-invoked always succeeds.
5410 * Do not allow privileged processes in jail to directly manipulate
5411 * system attributes.
5413 switch (attrnamespace) {
5414 case EXTATTR_NAMESPACE_SYSTEM:
5415 /* Potentially should be: return (EPERM); */
5416 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5417 case EXTATTR_NAMESPACE_USER:
5418 return (VOP_ACCESS(vp, accmode, cred, td));
5424 #ifdef DEBUG_VFS_LOCKS
5426 * This only exists to suppress warnings from unlocked specfs accesses. It is
5427 * no longer ok to have an unlocked VFS.
5429 #define IGNORE_LOCK(vp) (KERNEL_PANICKED() || (vp) == NULL || \
5430 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
5432 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
5433 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5434 "Drop into debugger on lock violation");
5436 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
5437 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5438 0, "Check for interlock across VOPs");
5440 int vfs_badlock_print = 1; /* Print lock violations. */
5441 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5442 0, "Print lock violations");
5444 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
5445 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5446 0, "Print vnode details on lock violations");
5449 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
5450 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5451 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5455 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5459 if (vfs_badlock_backtrace)
5462 if (vfs_badlock_vnode)
5463 vn_printf(vp, "vnode ");
5464 if (vfs_badlock_print)
5465 printf("%s: %p %s\n", str, (void *)vp, msg);
5466 if (vfs_badlock_ddb)
5467 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5471 assert_vi_locked(struct vnode *vp, const char *str)
5474 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5475 vfs_badlock("interlock is not locked but should be", str, vp);
5479 assert_vi_unlocked(struct vnode *vp, const char *str)
5482 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5483 vfs_badlock("interlock is locked but should not be", str, vp);
5487 assert_vop_locked(struct vnode *vp, const char *str)
5491 if (!IGNORE_LOCK(vp)) {
5492 locked = VOP_ISLOCKED(vp);
5493 if (locked == 0 || locked == LK_EXCLOTHER)
5494 vfs_badlock("is not locked but should be", str, vp);
5499 assert_vop_unlocked(struct vnode *vp, const char *str)
5502 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5503 vfs_badlock("is locked but should not be", str, vp);
5507 assert_vop_elocked(struct vnode *vp, const char *str)
5510 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5511 vfs_badlock("is not exclusive locked but should be", str, vp);
5513 #endif /* DEBUG_VFS_LOCKS */
5516 vop_rename_fail(struct vop_rename_args *ap)
5519 if (ap->a_tvp != NULL)
5521 if (ap->a_tdvp == ap->a_tvp)
5530 vop_rename_pre(void *ap)
5532 struct vop_rename_args *a = ap;
5534 #ifdef DEBUG_VFS_LOCKS
5536 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5537 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5538 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5539 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5541 /* Check the source (from). */
5542 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5543 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5544 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5545 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5546 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5548 /* Check the target. */
5550 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5551 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5554 * It may be tempting to add vn_seqc_write_begin/end calls here and
5555 * in vop_rename_post but that's not going to work out since some
5556 * filesystems relookup vnodes mid-rename. This is probably a bug.
5558 * For now filesystems are expected to do the relevant calls after they
5559 * decide what vnodes to operate on.
5561 if (a->a_tdvp != a->a_fdvp)
5563 if (a->a_tvp != a->a_fvp)
5570 #ifdef DEBUG_VFS_LOCKS
5572 vop_fplookup_vexec_debugpre(void *ap __unused)
5575 VFS_SMR_ASSERT_ENTERED();
5579 vop_fplookup_vexec_debugpost(void *ap __unused, int rc __unused)
5582 VFS_SMR_ASSERT_ENTERED();
5586 vop_fplookup_symlink_debugpre(void *ap __unused)
5589 VFS_SMR_ASSERT_ENTERED();
5593 vop_fplookup_symlink_debugpost(void *ap __unused, int rc __unused)
5596 VFS_SMR_ASSERT_ENTERED();
5599 vop_strategy_debugpre(void *ap)
5601 struct vop_strategy_args *a;
5608 * Cluster ops lock their component buffers but not the IO container.
5610 if ((bp->b_flags & B_CLUSTER) != 0)
5613 if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5614 if (vfs_badlock_print)
5616 "VOP_STRATEGY: bp is not locked but should be\n");
5617 if (vfs_badlock_ddb)
5618 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5623 vop_lock_debugpre(void *ap)
5625 struct vop_lock1_args *a = ap;
5627 if ((a->a_flags & LK_INTERLOCK) == 0)
5628 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5630 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5634 vop_lock_debugpost(void *ap, int rc)
5636 struct vop_lock1_args *a = ap;
5638 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5639 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5640 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5644 vop_unlock_debugpre(void *ap)
5646 struct vop_unlock_args *a = ap;
5648 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5652 vop_need_inactive_debugpre(void *ap)
5654 struct vop_need_inactive_args *a = ap;
5656 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5660 vop_need_inactive_debugpost(void *ap, int rc)
5662 struct vop_need_inactive_args *a = ap;
5664 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5669 vop_create_pre(void *ap)
5671 struct vop_create_args *a;
5676 vn_seqc_write_begin(dvp);
5680 vop_create_post(void *ap, int rc)
5682 struct vop_create_args *a;
5687 vn_seqc_write_end(dvp);
5689 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5693 vop_whiteout_pre(void *ap)
5695 struct vop_whiteout_args *a;
5700 vn_seqc_write_begin(dvp);
5704 vop_whiteout_post(void *ap, int rc)
5706 struct vop_whiteout_args *a;
5711 vn_seqc_write_end(dvp);
5715 vop_deleteextattr_pre(void *ap)
5717 struct vop_deleteextattr_args *a;
5722 vn_seqc_write_begin(vp);
5726 vop_deleteextattr_post(void *ap, int rc)
5728 struct vop_deleteextattr_args *a;
5733 vn_seqc_write_end(vp);
5735 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5739 vop_link_pre(void *ap)
5741 struct vop_link_args *a;
5742 struct vnode *vp, *tdvp;
5747 vn_seqc_write_begin(vp);
5748 vn_seqc_write_begin(tdvp);
5752 vop_link_post(void *ap, int rc)
5754 struct vop_link_args *a;
5755 struct vnode *vp, *tdvp;
5760 vn_seqc_write_end(vp);
5761 vn_seqc_write_end(tdvp);
5763 VFS_KNOTE_LOCKED(vp, NOTE_LINK);
5764 VFS_KNOTE_LOCKED(tdvp, NOTE_WRITE);
5769 vop_mkdir_pre(void *ap)
5771 struct vop_mkdir_args *a;
5776 vn_seqc_write_begin(dvp);
5780 vop_mkdir_post(void *ap, int rc)
5782 struct vop_mkdir_args *a;
5787 vn_seqc_write_end(dvp);
5789 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5792 #ifdef DEBUG_VFS_LOCKS
5794 vop_mkdir_debugpost(void *ap, int rc)
5796 struct vop_mkdir_args *a;
5800 cache_validate(a->a_dvp, *a->a_vpp, a->a_cnp);
5805 vop_mknod_pre(void *ap)
5807 struct vop_mknod_args *a;
5812 vn_seqc_write_begin(dvp);
5816 vop_mknod_post(void *ap, int rc)
5818 struct vop_mknod_args *a;
5823 vn_seqc_write_end(dvp);
5825 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5829 vop_reclaim_post(void *ap, int rc)
5831 struct vop_reclaim_args *a;
5836 ASSERT_VOP_IN_SEQC(vp);
5838 VFS_KNOTE_LOCKED(vp, NOTE_REVOKE);
5842 vop_remove_pre(void *ap)
5844 struct vop_remove_args *a;
5845 struct vnode *dvp, *vp;
5850 vn_seqc_write_begin(dvp);
5851 vn_seqc_write_begin(vp);
5855 vop_remove_post(void *ap, int rc)
5857 struct vop_remove_args *a;
5858 struct vnode *dvp, *vp;
5863 vn_seqc_write_end(dvp);
5864 vn_seqc_write_end(vp);
5866 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5867 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5872 vop_rename_post(void *ap, int rc)
5874 struct vop_rename_args *a = ap;
5879 if (a->a_fdvp == a->a_tdvp) {
5880 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5882 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5883 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5885 hint |= NOTE_EXTEND;
5886 if (a->a_fvp->v_type == VDIR)
5888 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5890 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5891 a->a_tvp->v_type == VDIR)
5893 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5896 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5898 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5900 if (a->a_tdvp != a->a_fdvp)
5902 if (a->a_tvp != a->a_fvp)
5910 vop_rmdir_pre(void *ap)
5912 struct vop_rmdir_args *a;
5913 struct vnode *dvp, *vp;
5918 vn_seqc_write_begin(dvp);
5919 vn_seqc_write_begin(vp);
5923 vop_rmdir_post(void *ap, int rc)
5925 struct vop_rmdir_args *a;
5926 struct vnode *dvp, *vp;
5931 vn_seqc_write_end(dvp);
5932 vn_seqc_write_end(vp);
5934 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5935 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5940 vop_setattr_pre(void *ap)
5942 struct vop_setattr_args *a;
5947 vn_seqc_write_begin(vp);
5951 vop_setattr_post(void *ap, int rc)
5953 struct vop_setattr_args *a;
5958 vn_seqc_write_end(vp);
5960 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
5964 vop_setacl_pre(void *ap)
5966 struct vop_setacl_args *a;
5971 vn_seqc_write_begin(vp);
5975 vop_setacl_post(void *ap, int rc __unused)
5977 struct vop_setacl_args *a;
5982 vn_seqc_write_end(vp);
5986 vop_setextattr_pre(void *ap)
5988 struct vop_setextattr_args *a;
5993 vn_seqc_write_begin(vp);
5997 vop_setextattr_post(void *ap, int rc)
5999 struct vop_setextattr_args *a;
6004 vn_seqc_write_end(vp);
6006 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6010 vop_symlink_pre(void *ap)
6012 struct vop_symlink_args *a;
6017 vn_seqc_write_begin(dvp);
6021 vop_symlink_post(void *ap, int rc)
6023 struct vop_symlink_args *a;
6028 vn_seqc_write_end(dvp);
6030 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6034 vop_open_post(void *ap, int rc)
6036 struct vop_open_args *a = ap;
6039 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
6043 vop_close_post(void *ap, int rc)
6045 struct vop_close_args *a = ap;
6047 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
6048 !VN_IS_DOOMED(a->a_vp))) {
6049 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
6050 NOTE_CLOSE_WRITE : NOTE_CLOSE);
6055 vop_read_post(void *ap, int rc)
6057 struct vop_read_args *a = ap;
6060 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6064 vop_read_pgcache_post(void *ap, int rc)
6066 struct vop_read_pgcache_args *a = ap;
6069 VFS_KNOTE_UNLOCKED(a->a_vp, NOTE_READ);
6073 vop_readdir_post(void *ap, int rc)
6075 struct vop_readdir_args *a = ap;
6078 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6081 static struct knlist fs_knlist;
6084 vfs_event_init(void *arg)
6086 knlist_init_mtx(&fs_knlist, NULL);
6088 /* XXX - correct order? */
6089 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
6092 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
6095 KNOTE_UNLOCKED(&fs_knlist, event);
6098 static int filt_fsattach(struct knote *kn);
6099 static void filt_fsdetach(struct knote *kn);
6100 static int filt_fsevent(struct knote *kn, long hint);
6102 struct filterops fs_filtops = {
6104 .f_attach = filt_fsattach,
6105 .f_detach = filt_fsdetach,
6106 .f_event = filt_fsevent
6110 filt_fsattach(struct knote *kn)
6113 kn->kn_flags |= EV_CLEAR;
6114 knlist_add(&fs_knlist, kn, 0);
6119 filt_fsdetach(struct knote *kn)
6122 knlist_remove(&fs_knlist, kn, 0);
6126 filt_fsevent(struct knote *kn, long hint)
6129 kn->kn_fflags |= kn->kn_sfflags & hint;
6131 return (kn->kn_fflags != 0);
6135 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
6141 error = SYSCTL_IN(req, &vc, sizeof(vc));
6144 if (vc.vc_vers != VFS_CTL_VERS1)
6146 mp = vfs_getvfs(&vc.vc_fsid);
6149 /* ensure that a specific sysctl goes to the right filesystem. */
6150 if (strcmp(vc.vc_fstypename, "*") != 0 &&
6151 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
6155 VCTLTOREQ(&vc, req);
6156 error = VFS_SYSCTL(mp, vc.vc_op, req);
6161 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
6162 NULL, 0, sysctl_vfs_ctl, "",
6166 * Function to initialize a va_filerev field sensibly.
6167 * XXX: Wouldn't a random number make a lot more sense ??
6170 init_va_filerev(void)
6175 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
6178 static int filt_vfsread(struct knote *kn, long hint);
6179 static int filt_vfswrite(struct knote *kn, long hint);
6180 static int filt_vfsvnode(struct knote *kn, long hint);
6181 static void filt_vfsdetach(struct knote *kn);
6182 static struct filterops vfsread_filtops = {
6184 .f_detach = filt_vfsdetach,
6185 .f_event = filt_vfsread
6187 static struct filterops vfswrite_filtops = {
6189 .f_detach = filt_vfsdetach,
6190 .f_event = filt_vfswrite
6192 static struct filterops vfsvnode_filtops = {
6194 .f_detach = filt_vfsdetach,
6195 .f_event = filt_vfsvnode
6199 vfs_knllock(void *arg)
6201 struct vnode *vp = arg;
6203 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
6207 vfs_knlunlock(void *arg)
6209 struct vnode *vp = arg;
6215 vfs_knl_assert_lock(void *arg, int what)
6217 #ifdef DEBUG_VFS_LOCKS
6218 struct vnode *vp = arg;
6220 if (what == LA_LOCKED)
6221 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
6223 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
6228 vfs_kqfilter(struct vop_kqfilter_args *ap)
6230 struct vnode *vp = ap->a_vp;
6231 struct knote *kn = ap->a_kn;
6234 switch (kn->kn_filter) {
6236 kn->kn_fop = &vfsread_filtops;
6239 kn->kn_fop = &vfswrite_filtops;
6242 kn->kn_fop = &vfsvnode_filtops;
6248 kn->kn_hook = (caddr_t)vp;
6251 if (vp->v_pollinfo == NULL)
6253 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
6255 knlist_add(knl, kn, 0);
6261 * Detach knote from vnode
6264 filt_vfsdetach(struct knote *kn)
6266 struct vnode *vp = (struct vnode *)kn->kn_hook;
6268 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
6269 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
6275 filt_vfsread(struct knote *kn, long hint)
6277 struct vnode *vp = (struct vnode *)kn->kn_hook;
6282 * filesystem is gone, so set the EOF flag and schedule
6283 * the knote for deletion.
6285 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6287 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6292 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
6296 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
6297 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
6304 filt_vfswrite(struct knote *kn, long hint)
6306 struct vnode *vp = (struct vnode *)kn->kn_hook;
6311 * filesystem is gone, so set the EOF flag and schedule
6312 * the knote for deletion.
6314 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
6315 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6323 filt_vfsvnode(struct knote *kn, long hint)
6325 struct vnode *vp = (struct vnode *)kn->kn_hook;
6329 if (kn->kn_sfflags & hint)
6330 kn->kn_fflags |= hint;
6331 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6332 kn->kn_flags |= EV_EOF;
6336 res = (kn->kn_fflags != 0);
6342 * Returns whether the directory is empty or not.
6343 * If it is empty, the return value is 0; otherwise
6344 * the return value is an error value (which may
6348 vfs_emptydir(struct vnode *vp)
6352 struct dirent *dirent, *dp, *endp;
6358 ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
6360 dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
6361 iov.iov_base = dirent;
6362 iov.iov_len = sizeof(struct dirent);
6367 uio.uio_resid = sizeof(struct dirent);
6368 uio.uio_segflg = UIO_SYSSPACE;
6369 uio.uio_rw = UIO_READ;
6370 uio.uio_td = curthread;
6372 while (eof == 0 && error == 0) {
6373 error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
6377 endp = (void *)((uint8_t *)dirent +
6378 sizeof(struct dirent) - uio.uio_resid);
6379 for (dp = dirent; dp < endp;
6380 dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
6381 if (dp->d_type == DT_WHT)
6383 if (dp->d_namlen == 0)
6385 if (dp->d_type != DT_DIR &&
6386 dp->d_type != DT_UNKNOWN) {
6390 if (dp->d_namlen > 2) {
6394 if (dp->d_namlen == 1 &&
6395 dp->d_name[0] != '.') {
6399 if (dp->d_namlen == 2 &&
6400 dp->d_name[1] != '.') {
6404 uio.uio_resid = sizeof(struct dirent);
6407 free(dirent, M_TEMP);
6412 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6416 if (dp->d_reclen > ap->a_uio->uio_resid)
6417 return (ENAMETOOLONG);
6418 error = uiomove(dp, dp->d_reclen, ap->a_uio);
6420 if (ap->a_ncookies != NULL) {
6421 if (ap->a_cookies != NULL)
6422 free(ap->a_cookies, M_TEMP);
6423 ap->a_cookies = NULL;
6424 *ap->a_ncookies = 0;
6428 if (ap->a_ncookies == NULL)
6431 KASSERT(ap->a_cookies,
6432 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6434 *ap->a_cookies = realloc(*ap->a_cookies,
6435 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
6436 (*ap->a_cookies)[*ap->a_ncookies] = off;
6437 *ap->a_ncookies += 1;
6442 * The purpose of this routine is to remove granularity from accmode_t,
6443 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6444 * VADMIN and VAPPEND.
6446 * If it returns 0, the caller is supposed to continue with the usual
6447 * access checks using 'accmode' as modified by this routine. If it
6448 * returns nonzero value, the caller is supposed to return that value
6451 * Note that after this routine runs, accmode may be zero.
6454 vfs_unixify_accmode(accmode_t *accmode)
6457 * There is no way to specify explicit "deny" rule using
6458 * file mode or POSIX.1e ACLs.
6460 if (*accmode & VEXPLICIT_DENY) {
6466 * None of these can be translated into usual access bits.
6467 * Also, the common case for NFSv4 ACLs is to not contain
6468 * either of these bits. Caller should check for VWRITE
6469 * on the containing directory instead.
6471 if (*accmode & (VDELETE_CHILD | VDELETE))
6474 if (*accmode & VADMIN_PERMS) {
6475 *accmode &= ~VADMIN_PERMS;
6480 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6481 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6483 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6489 * Clear out a doomed vnode (if any) and replace it with a new one as long
6490 * as the fs is not being unmounted. Return the root vnode to the caller.
6492 static int __noinline
6493 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6499 if (mp->mnt_rootvnode != NULL) {
6501 vp = mp->mnt_rootvnode;
6503 if (!VN_IS_DOOMED(vp)) {
6506 error = vn_lock(vp, flags);
6515 * Clear the old one.
6517 mp->mnt_rootvnode = NULL;
6521 vfs_op_barrier_wait(mp);
6525 error = VFS_CACHEDROOT(mp, flags, vpp);
6528 if (mp->mnt_vfs_ops == 0) {
6530 if (mp->mnt_vfs_ops != 0) {
6534 if (mp->mnt_rootvnode == NULL) {
6536 mp->mnt_rootvnode = *vpp;
6538 if (mp->mnt_rootvnode != *vpp) {
6539 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6540 panic("%s: mismatch between vnode returned "
6541 " by VFS_CACHEDROOT and the one cached "
6543 __func__, *vpp, mp->mnt_rootvnode);
6553 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6555 struct mount_pcpu *mpcpu;
6559 if (!vfs_op_thread_enter(mp, mpcpu))
6560 return (vfs_cache_root_fallback(mp, flags, vpp));
6561 vp = atomic_load_ptr(&mp->mnt_rootvnode);
6562 if (vp == NULL || VN_IS_DOOMED(vp)) {
6563 vfs_op_thread_exit(mp, mpcpu);
6564 return (vfs_cache_root_fallback(mp, flags, vpp));
6567 vfs_op_thread_exit(mp, mpcpu);
6568 error = vn_lock(vp, flags);
6571 return (vfs_cache_root_fallback(mp, flags, vpp));
6578 vfs_cache_root_clear(struct mount *mp)
6583 * ops > 0 guarantees there is nobody who can see this vnode
6585 MPASS(mp->mnt_vfs_ops > 0);
6586 vp = mp->mnt_rootvnode;
6588 vn_seqc_write_begin(vp);
6589 mp->mnt_rootvnode = NULL;
6594 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6597 MPASS(mp->mnt_vfs_ops > 0);
6599 mp->mnt_rootvnode = vp;
6603 * These are helper functions for filesystems to traverse all
6604 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6606 * This interface replaces MNT_VNODE_FOREACH.
6610 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6615 kern_yield(PRI_USER);
6617 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6618 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6619 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6620 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6621 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6624 if (VN_IS_DOOMED(vp)) {
6631 __mnt_vnode_markerfree_all(mvp, mp);
6632 /* MNT_IUNLOCK(mp); -- done in above function */
6633 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6636 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6637 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6643 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6647 *mvp = vn_alloc_marker(mp);
6651 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6652 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6653 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6656 if (VN_IS_DOOMED(vp)) {
6665 vn_free_marker(*mvp);
6669 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6675 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6683 mtx_assert(MNT_MTX(mp), MA_OWNED);
6685 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6686 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6689 vn_free_marker(*mvp);
6694 * These are helper functions for filesystems to traverse their
6695 * lazy vnodes. See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6698 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6701 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6706 vn_free_marker(*mvp);
6711 * Relock the mp mount vnode list lock with the vp vnode interlock in the
6712 * conventional lock order during mnt_vnode_next_lazy iteration.
6714 * On entry, the mount vnode list lock is held and the vnode interlock is not.
6715 * The list lock is dropped and reacquired. On success, both locks are held.
6716 * On failure, the mount vnode list lock is held but the vnode interlock is
6717 * not, and the procedure may have yielded.
6720 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6724 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6725 TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6726 ("%s: bad marker", __func__));
6727 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6728 ("%s: inappropriate vnode", __func__));
6729 ASSERT_VI_UNLOCKED(vp, __func__);
6730 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6732 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6733 TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6736 * Note we may be racing against vdrop which transitioned the hold
6737 * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
6738 * if we are the only user after we get the interlock we will just
6742 mtx_unlock(&mp->mnt_listmtx);
6744 if (VN_IS_DOOMED(vp)) {
6745 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
6748 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
6750 * There is nothing to do if we are the last user.
6752 if (!refcount_release_if_not_last(&vp->v_holdcnt))
6754 mtx_lock(&mp->mnt_listmtx);
6759 mtx_lock(&mp->mnt_listmtx);
6763 static struct vnode *
6764 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6769 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6770 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6772 vp = TAILQ_NEXT(*mvp, v_lazylist);
6773 while (vp != NULL) {
6774 if (vp->v_type == VMARKER) {
6775 vp = TAILQ_NEXT(vp, v_lazylist);
6779 * See if we want to process the vnode. Note we may encounter a
6780 * long string of vnodes we don't care about and hog the list
6781 * as a result. Check for it and requeue the marker.
6783 VNPASS(!VN_IS_DOOMED(vp), vp);
6784 if (!cb(vp, cbarg)) {
6785 if (!should_yield()) {
6786 vp = TAILQ_NEXT(vp, v_lazylist);
6789 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6791 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6793 mtx_unlock(&mp->mnt_listmtx);
6794 kern_yield(PRI_USER);
6795 mtx_lock(&mp->mnt_listmtx);
6799 * Try-lock because this is the wrong lock order.
6801 if (!VI_TRYLOCK(vp) &&
6802 !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6804 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6805 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6806 ("alien vnode on the lazy list %p %p", vp, mp));
6807 VNPASS(vp->v_mount == mp, vp);
6808 VNPASS(!VN_IS_DOOMED(vp), vp);
6811 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6813 /* Check if we are done */
6815 mtx_unlock(&mp->mnt_listmtx);
6816 mnt_vnode_markerfree_lazy(mvp, mp);
6819 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6820 mtx_unlock(&mp->mnt_listmtx);
6821 ASSERT_VI_LOCKED(vp, "lazy iter");
6826 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6831 kern_yield(PRI_USER);
6832 mtx_lock(&mp->mnt_listmtx);
6833 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6837 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6842 if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
6845 *mvp = vn_alloc_marker(mp);
6850 mtx_lock(&mp->mnt_listmtx);
6851 vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6853 mtx_unlock(&mp->mnt_listmtx);
6854 mnt_vnode_markerfree_lazy(mvp, mp);
6857 TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6858 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6862 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6868 mtx_lock(&mp->mnt_listmtx);
6869 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6870 mtx_unlock(&mp->mnt_listmtx);
6871 mnt_vnode_markerfree_lazy(mvp, mp);
6875 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
6878 if ((cnp->cn_flags & NOEXECCHECK) != 0) {
6879 cnp->cn_flags &= ~NOEXECCHECK;
6883 return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, cnp->cn_thread));
6887 * Do not use this variant unless you have means other than the hold count
6888 * to prevent the vnode from getting freed.
6891 vn_seqc_write_begin_unheld_locked(struct vnode *vp)
6894 ASSERT_VI_LOCKED(vp, __func__);
6895 VNPASS(vp->v_seqc_users >= 0, vp);
6897 if (vp->v_seqc_users == 1)
6898 seqc_sleepable_write_begin(&vp->v_seqc);
6902 vn_seqc_write_begin_locked(struct vnode *vp)
6905 ASSERT_VI_LOCKED(vp, __func__);
6906 VNPASS(vp->v_holdcnt > 0, vp);
6907 vn_seqc_write_begin_unheld_locked(vp);
6911 vn_seqc_write_begin(struct vnode *vp)
6915 vn_seqc_write_begin_locked(vp);
6920 vn_seqc_write_begin_unheld(struct vnode *vp)
6924 vn_seqc_write_begin_unheld_locked(vp);
6929 vn_seqc_write_end_locked(struct vnode *vp)
6932 ASSERT_VI_LOCKED(vp, __func__);
6933 VNPASS(vp->v_seqc_users > 0, vp);
6935 if (vp->v_seqc_users == 0)
6936 seqc_sleepable_write_end(&vp->v_seqc);
6940 vn_seqc_write_end(struct vnode *vp)
6944 vn_seqc_write_end_locked(vp);
6949 * Special case handling for allocating and freeing vnodes.
6951 * The counter remains unchanged on free so that a doomed vnode will
6952 * keep testing as in modify as long as it is accessible with SMR.
6955 vn_seqc_init(struct vnode *vp)
6959 vp->v_seqc_users = 0;
6963 vn_seqc_write_end_free(struct vnode *vp)
6966 VNPASS(seqc_in_modify(vp->v_seqc), vp);
6967 VNPASS(vp->v_seqc_users == 1, vp);
6971 vn_irflag_set_locked(struct vnode *vp, short toset)
6975 ASSERT_VI_LOCKED(vp, __func__);
6976 flags = vn_irflag_read(vp);
6977 VNASSERT((flags & toset) == 0, vp,
6978 ("%s: some of the passed flags already set (have %d, passed %d)\n",
6979 __func__, flags, toset));
6980 atomic_store_short(&vp->v_irflag, flags | toset);
6984 vn_irflag_set(struct vnode *vp, short toset)
6988 vn_irflag_set_locked(vp, toset);
6993 vn_irflag_set_cond_locked(struct vnode *vp, short toset)
6997 ASSERT_VI_LOCKED(vp, __func__);
6998 flags = vn_irflag_read(vp);
6999 atomic_store_short(&vp->v_irflag, flags | toset);
7003 vn_irflag_set_cond(struct vnode *vp, short toset)
7007 vn_irflag_set_cond_locked(vp, toset);
7012 vn_irflag_unset_locked(struct vnode *vp, short tounset)
7016 ASSERT_VI_LOCKED(vp, __func__);
7017 flags = vn_irflag_read(vp);
7018 VNASSERT((flags & tounset) == tounset, vp,
7019 ("%s: some of the passed flags not set (have %d, passed %d)\n",
7020 __func__, flags, tounset));
7021 atomic_store_short(&vp->v_irflag, flags & ~tounset);
7025 vn_irflag_unset(struct vnode *vp, short tounset)
7029 vn_irflag_unset_locked(vp, tounset);