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/limits.h>
70 #include <sys/lockf.h>
71 #include <sys/malloc.h>
72 #include <sys/mount.h>
73 #include <sys/namei.h>
74 #include <sys/pctrie.h>
76 #include <sys/reboot.h>
77 #include <sys/refcount.h>
78 #include <sys/rwlock.h>
79 #include <sys/sched.h>
80 #include <sys/sleepqueue.h>
84 #include <sys/sysctl.h>
85 #include <sys/syslog.h>
86 #include <sys/vmmeter.h>
87 #include <sys/vnode.h>
88 #include <sys/watchdog.h>
90 #include <machine/stdarg.h>
92 #include <security/mac/mac_framework.h>
95 #include <vm/vm_object.h>
96 #include <vm/vm_extern.h>
98 #include <vm/vm_map.h>
99 #include <vm/vm_page.h>
100 #include <vm/vm_kern.h>
103 #if defined(DEBUG_VFS_LOCKS) && (!defined(INVARIANTS) || !defined(WITNESS))
104 #error DEBUG_VFS_LOCKS requires INVARIANTS and WITNESS
111 static void delmntque(struct vnode *vp);
112 static int flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
113 int slpflag, int slptimeo);
114 static void syncer_shutdown(void *arg, int howto);
115 static int vtryrecycle(struct vnode *vp);
116 static void v_init_counters(struct vnode *);
117 static void vn_seqc_init(struct vnode *);
118 static void vn_seqc_write_end_free(struct vnode *vp);
119 static void vgonel(struct vnode *);
120 static bool vhold_recycle_free(struct vnode *);
121 static void vdropl_recycle(struct vnode *vp);
122 static void vdrop_recycle(struct vnode *vp);
123 static void vfs_knllock(void *arg);
124 static void vfs_knlunlock(void *arg);
125 static void vfs_knl_assert_lock(void *arg, int what);
126 static void destroy_vpollinfo(struct vpollinfo *vi);
127 static int v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
128 daddr_t startlbn, daddr_t endlbn);
129 static void vnlru_recalc(void);
132 * Number of vnodes in existence. Increased whenever getnewvnode()
133 * allocates a new vnode, decreased in vdropl() for VIRF_DOOMED vnode.
135 static u_long __exclusive_cache_line numvnodes;
137 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
138 "Number of vnodes in existence");
140 static counter_u64_t vnodes_created;
141 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
142 "Number of vnodes created by getnewvnode");
145 * Conversion tables for conversion from vnode types to inode formats
148 enum vtype iftovt_tab[16] = {
149 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
150 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
152 int vttoif_tab[10] = {
153 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
154 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
158 * List of allocates vnodes in the system.
160 static TAILQ_HEAD(freelst, vnode) vnode_list;
161 static struct vnode *vnode_list_free_marker;
162 static struct vnode *vnode_list_reclaim_marker;
165 * "Free" vnode target. Free vnodes are rarely completely free, but are
166 * just ones that are cheap to recycle. Usually they are for files which
167 * have been stat'd but not read; these usually have inode and namecache
168 * data attached to them. This target is the preferred minimum size of a
169 * sub-cache consisting mostly of such files. The system balances the size
170 * of this sub-cache with its complement to try to prevent either from
171 * thrashing while the other is relatively inactive. The targets express
172 * a preference for the best balance.
174 * "Above" this target there are 2 further targets (watermarks) related
175 * to recyling of free vnodes. In the best-operating case, the cache is
176 * exactly full, the free list has size between vlowat and vhiwat above the
177 * free target, and recycling from it and normal use maintains this state.
178 * Sometimes the free list is below vlowat or even empty, but this state
179 * is even better for immediate use provided the cache is not full.
180 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
181 * ones) to reach one of these states. The watermarks are currently hard-
182 * coded as 4% and 9% of the available space higher. These and the default
183 * of 25% for wantfreevnodes are too large if the memory size is large.
184 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
185 * whenever vnlru_proc() becomes active.
187 static long wantfreevnodes;
188 static long __exclusive_cache_line freevnodes;
189 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
190 &freevnodes, 0, "Number of \"free\" vnodes");
191 static long freevnodes_old;
193 static counter_u64_t recycles_count;
194 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
195 "Number of vnodes recycled to meet vnode cache targets");
197 static counter_u64_t recycles_free_count;
198 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD, &recycles_free_count,
199 "Number of free vnodes recycled to meet vnode cache targets");
201 static u_long deferred_inact;
202 SYSCTL_ULONG(_vfs, OID_AUTO, deferred_inact, CTLFLAG_RD,
203 &deferred_inact, 0, "Number of times inactive processing was deferred");
205 /* To keep more than one thread at a time from running vfs_getnewfsid */
206 static struct mtx mntid_mtx;
209 * Lock for any access to the following:
214 static struct mtx __exclusive_cache_line vnode_list_mtx;
216 /* Publicly exported FS */
217 struct nfs_public nfs_pub;
219 static uma_zone_t buf_trie_zone;
220 static smr_t buf_trie_smr;
222 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
223 static uma_zone_t vnode_zone;
224 MALLOC_DEFINE(M_VNODEPOLL, "VN POLL", "vnode poll");
226 __read_frequently smr_t vfs_smr;
229 * The workitem queue.
231 * It is useful to delay writes of file data and filesystem metadata
232 * for tens of seconds so that quickly created and deleted files need
233 * not waste disk bandwidth being created and removed. To realize this,
234 * we append vnodes to a "workitem" queue. When running with a soft
235 * updates implementation, most pending metadata dependencies should
236 * not wait for more than a few seconds. Thus, mounted on block devices
237 * are delayed only about a half the time that file data is delayed.
238 * Similarly, directory updates are more critical, so are only delayed
239 * about a third the time that file data is delayed. Thus, there are
240 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
241 * one each second (driven off the filesystem syncer process). The
242 * syncer_delayno variable indicates the next queue that is to be processed.
243 * Items that need to be processed soon are placed in this queue:
245 * syncer_workitem_pending[syncer_delayno]
247 * A delay of fifteen seconds is done by placing the request fifteen
248 * entries later in the queue:
250 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
253 static int syncer_delayno;
254 static long syncer_mask;
255 LIST_HEAD(synclist, bufobj);
256 static struct synclist *syncer_workitem_pending;
258 * The sync_mtx protects:
263 * syncer_workitem_pending
264 * syncer_worklist_len
267 static struct mtx sync_mtx;
268 static struct cv sync_wakeup;
270 #define SYNCER_MAXDELAY 32
271 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
272 static int syncdelay = 30; /* max time to delay syncing data */
273 static int filedelay = 30; /* time to delay syncing files */
274 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
275 "Time to delay syncing files (in seconds)");
276 static int dirdelay = 29; /* time to delay syncing directories */
277 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
278 "Time to delay syncing directories (in seconds)");
279 static int metadelay = 28; /* time to delay syncing metadata */
280 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
281 "Time to delay syncing metadata (in seconds)");
282 static int rushjob; /* number of slots to run ASAP */
283 static int stat_rush_requests; /* number of times I/O speeded up */
284 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
285 "Number of times I/O speeded up (rush requests)");
287 #define VDBATCH_SIZE 8
291 struct vnode *tab[VDBATCH_SIZE];
293 DPCPU_DEFINE_STATIC(struct vdbatch, vd);
295 static void vdbatch_dequeue(struct vnode *vp);
298 * When shutting down the syncer, run it at four times normal speed.
300 #define SYNCER_SHUTDOWN_SPEEDUP 4
301 static int sync_vnode_count;
302 static int syncer_worklist_len;
303 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
306 /* Target for maximum number of vnodes. */
307 u_long desiredvnodes;
308 static u_long gapvnodes; /* gap between wanted and desired */
309 static u_long vhiwat; /* enough extras after expansion */
310 static u_long vlowat; /* minimal extras before expansion */
311 static u_long vstir; /* nonzero to stir non-free vnodes */
312 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
314 static u_long vnlru_read_freevnodes(void);
317 * Note that no attempt is made to sanitize these parameters.
320 sysctl_maxvnodes(SYSCTL_HANDLER_ARGS)
326 error = sysctl_handle_long(oidp, &val, 0, req);
327 if (error != 0 || req->newptr == NULL)
330 if (val == desiredvnodes)
332 mtx_lock(&vnode_list_mtx);
334 wantfreevnodes = desiredvnodes / 4;
336 mtx_unlock(&vnode_list_mtx);
338 * XXX There is no protection against multiple threads changing
339 * desiredvnodes at the same time. Locking above only helps vnlru and
342 vfs_hash_changesize(desiredvnodes);
343 cache_changesize(desiredvnodes);
347 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
348 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
349 "LU", "Target for maximum number of vnodes");
352 sysctl_wantfreevnodes(SYSCTL_HANDLER_ARGS)
357 val = wantfreevnodes;
358 error = sysctl_handle_long(oidp, &val, 0, req);
359 if (error != 0 || req->newptr == NULL)
362 if (val == wantfreevnodes)
364 mtx_lock(&vnode_list_mtx);
365 wantfreevnodes = val;
367 mtx_unlock(&vnode_list_mtx);
371 SYSCTL_PROC(_vfs, OID_AUTO, wantfreevnodes,
372 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
373 "LU", "Target for minimum number of \"free\" vnodes");
375 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
376 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
377 static int vnlru_nowhere;
378 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW | CTLFLAG_STATS,
379 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
382 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
387 unsigned long ndflags;
390 if (req->newptr == NULL)
392 if (req->newlen >= PATH_MAX)
395 buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
396 error = SYSCTL_IN(req, buf, req->newlen);
400 buf[req->newlen] = '\0';
402 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1;
403 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf);
404 if ((error = namei(&nd)) != 0)
408 if (VN_IS_DOOMED(vp)) {
410 * This vnode is being recycled. Return != 0 to let the caller
411 * know that the sysctl had no effect. Return EAGAIN because a
412 * subsequent call will likely succeed (since namei will create
413 * a new vnode if necessary)
419 counter_u64_add(recycles_count, 1);
430 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
432 struct thread *td = curthread;
438 if (req->newptr == NULL)
441 error = sysctl_handle_int(oidp, &fd, 0, req);
444 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
449 error = vn_lock(vp, LK_EXCLUSIVE);
453 counter_u64_add(recycles_count, 1);
461 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
462 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
463 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
464 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
465 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
466 sysctl_ftry_reclaim_vnode, "I",
467 "Try to reclaim a vnode by its file descriptor");
469 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
472 _Static_assert(sizeof(struct vnode) >= 1UL << vnsz2log &&
473 sizeof(struct vnode) < 1UL << (vnsz2log + 1),
474 "vnsz2log needs to be updated");
478 * Support for the bufobj clean & dirty pctrie.
481 buf_trie_alloc(struct pctrie *ptree)
483 return (uma_zalloc_smr(buf_trie_zone, M_NOWAIT));
487 buf_trie_free(struct pctrie *ptree, void *node)
489 uma_zfree_smr(buf_trie_zone, node);
491 PCTRIE_DEFINE_SMR(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free,
495 * Initialize the vnode management data structures.
497 * Reevaluate the following cap on the number of vnodes after the physical
498 * memory size exceeds 512GB. In the limit, as the physical memory size
499 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
501 #ifndef MAXVNODES_MAX
502 #define MAXVNODES_MAX (512UL * 1024 * 1024 / 64) /* 8M */
505 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
507 static struct vnode *
508 vn_alloc_marker(struct mount *mp)
512 vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
513 vp->v_type = VMARKER;
520 vn_free_marker(struct vnode *vp)
523 MPASS(vp->v_type == VMARKER);
524 free(vp, M_VNODE_MARKER);
529 vnode_ctor(void *mem, int size, void *arg __unused, int flags __unused)
531 kasan_mark(mem, size, roundup2(size, UMA_ALIGN_PTR + 1), 0);
536 vnode_dtor(void *mem, int size, void *arg __unused)
538 size_t end1, end2, off1, off2;
540 _Static_assert(offsetof(struct vnode, v_vnodelist) <
541 offsetof(struct vnode, v_dbatchcpu),
542 "KASAN marks require updating");
544 off1 = offsetof(struct vnode, v_vnodelist);
545 off2 = offsetof(struct vnode, v_dbatchcpu);
546 end1 = off1 + sizeof(((struct vnode *)NULL)->v_vnodelist);
547 end2 = off2 + sizeof(((struct vnode *)NULL)->v_dbatchcpu);
550 * Access to the v_vnodelist and v_dbatchcpu fields are permitted even
551 * after the vnode has been freed. Try to get some KASAN coverage by
552 * marking everything except those two fields as invalid. Because
553 * KASAN's tracking is not byte-granular, any preceding fields sharing
554 * the same 8-byte aligned word must also be marked valid.
557 /* Handle the area from the start until v_vnodelist... */
558 off1 = rounddown2(off1, KASAN_SHADOW_SCALE);
559 kasan_mark(mem, off1, off1, KASAN_UMA_FREED);
561 /* ... then the area between v_vnodelist and v_dbatchcpu ... */
562 off1 = roundup2(end1, KASAN_SHADOW_SCALE);
563 off2 = rounddown2(off2, KASAN_SHADOW_SCALE);
565 kasan_mark((void *)((char *)mem + off1), off2 - off1,
566 off2 - off1, KASAN_UMA_FREED);
568 /* ... and finally the area from v_dbatchcpu to the end. */
569 off2 = roundup2(end2, KASAN_SHADOW_SCALE);
570 kasan_mark((void *)((char *)mem + off2), size - off2, size - off2,
576 * Initialize a vnode as it first enters the zone.
579 vnode_init(void *mem, int size, int flags)
588 vp->v_vnlock = &vp->v_lock;
589 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
591 * By default, don't allow shared locks unless filesystems opt-in.
593 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
594 LK_NOSHARE | LK_IS_VNODE);
598 bufobj_init(&vp->v_bufobj, vp);
600 * Initialize namecache.
602 cache_vnode_init(vp);
604 * Initialize rangelocks.
606 rangelock_init(&vp->v_rl);
608 vp->v_dbatchcpu = NOCPU;
610 vp->v_state = VSTATE_DEAD;
613 * Check vhold_recycle_free for an explanation.
615 vp->v_holdcnt = VHOLD_NO_SMR;
617 mtx_lock(&vnode_list_mtx);
618 TAILQ_INSERT_BEFORE(vnode_list_free_marker, vp, v_vnodelist);
619 mtx_unlock(&vnode_list_mtx);
624 * Free a vnode when it is cleared from the zone.
627 vnode_fini(void *mem, int size)
634 mtx_lock(&vnode_list_mtx);
635 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
636 mtx_unlock(&vnode_list_mtx);
637 rangelock_destroy(&vp->v_rl);
638 lockdestroy(vp->v_vnlock);
639 mtx_destroy(&vp->v_interlock);
641 rw_destroy(BO_LOCKPTR(bo));
643 kasan_mark(mem, size, size, 0);
647 * Provide the size of NFS nclnode and NFS fh for calculation of the
648 * vnode memory consumption. The size is specified directly to
649 * eliminate dependency on NFS-private header.
651 * Other filesystems may use bigger or smaller (like UFS and ZFS)
652 * private inode data, but the NFS-based estimation is ample enough.
653 * Still, we care about differences in the size between 64- and 32-bit
656 * Namecache structure size is heuristically
657 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
660 #define NFS_NCLNODE_SZ (528 + 64)
663 #define NFS_NCLNODE_SZ (360 + 32)
668 vntblinit(void *dummy __unused)
673 int cpu, physvnodes, virtvnodes;
676 * Desiredvnodes is a function of the physical memory size and the
677 * kernel's heap size. Generally speaking, it scales with the
678 * physical memory size. The ratio of desiredvnodes to the physical
679 * memory size is 1:16 until desiredvnodes exceeds 98,304.
681 * marginal ratio of desiredvnodes to the physical memory size is
682 * 1:64. However, desiredvnodes is limited by the kernel's heap
683 * size. The memory required by desiredvnodes vnodes and vm objects
684 * must not exceed 1/10th of the kernel's heap size.
686 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
687 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
688 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
689 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
690 desiredvnodes = min(physvnodes, virtvnodes);
691 if (desiredvnodes > MAXVNODES_MAX) {
693 printf("Reducing kern.maxvnodes %lu -> %lu\n",
694 desiredvnodes, MAXVNODES_MAX);
695 desiredvnodes = MAXVNODES_MAX;
697 wantfreevnodes = desiredvnodes / 4;
698 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
699 TAILQ_INIT(&vnode_list);
700 mtx_init(&vnode_list_mtx, "vnode_list", NULL, MTX_DEF);
702 * The lock is taken to appease WITNESS.
704 mtx_lock(&vnode_list_mtx);
706 mtx_unlock(&vnode_list_mtx);
707 vnode_list_free_marker = vn_alloc_marker(NULL);
708 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_free_marker, v_vnodelist);
709 vnode_list_reclaim_marker = vn_alloc_marker(NULL);
710 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_reclaim_marker, v_vnodelist);
719 vnode_zone = uma_zcreate("VNODE", sizeof(struct vnode), ctor, dtor,
720 vnode_init, vnode_fini, UMA_ALIGN_PTR, UMA_ZONE_NOKASAN);
721 uma_zone_set_smr(vnode_zone, vfs_smr);
724 * Preallocate enough nodes to support one-per buf so that
725 * we can not fail an insert. reassignbuf() callers can not
726 * tolerate the insertion failure.
728 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
729 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
730 UMA_ZONE_NOFREE | UMA_ZONE_SMR);
731 buf_trie_smr = uma_zone_get_smr(buf_trie_zone);
732 uma_prealloc(buf_trie_zone, nbuf);
734 vnodes_created = counter_u64_alloc(M_WAITOK);
735 recycles_count = counter_u64_alloc(M_WAITOK);
736 recycles_free_count = counter_u64_alloc(M_WAITOK);
739 * Initialize the filesystem syncer.
741 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
743 syncer_maxdelay = syncer_mask + 1;
744 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
745 cv_init(&sync_wakeup, "syncer");
748 vd = DPCPU_ID_PTR((cpu), vd);
749 bzero(vd, sizeof(*vd));
750 mtx_init(&vd->lock, "vdbatch", NULL, MTX_DEF);
753 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
756 * Mark a mount point as busy. Used to synchronize access and to delay
757 * unmounting. Eventually, mountlist_mtx is not released on failure.
759 * vfs_busy() is a custom lock, it can block the caller.
760 * vfs_busy() only sleeps if the unmount is active on the mount point.
761 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
762 * vnode belonging to mp.
764 * Lookup uses vfs_busy() to traverse mount points.
766 * / vnode lock A / vnode lock (/var) D
767 * /var vnode lock B /log vnode lock(/var/log) E
768 * vfs_busy lock C vfs_busy lock F
770 * Within each file system, the lock order is C->A->B and F->D->E.
772 * When traversing across mounts, the system follows that lock order:
778 * The lookup() process for namei("/var") illustrates the process:
779 * 1. VOP_LOOKUP() obtains B while A is held
780 * 2. vfs_busy() obtains a shared lock on F while A and B are held
781 * 3. vput() releases lock on B
782 * 4. vput() releases lock on A
783 * 5. VFS_ROOT() obtains lock on D while shared lock on F is held
784 * 6. vfs_unbusy() releases shared lock on F
785 * 7. vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
786 * Attempt to lock A (instead of vp_crossmp) while D is held would
787 * violate the global order, causing deadlocks.
789 * dounmount() locks B while F is drained. Note that for stacked
790 * filesystems, D and B in the example above may be the same lock,
791 * which introdues potential lock order reversal deadlock between
792 * dounmount() and step 5 above. These filesystems may avoid the LOR
793 * by setting VV_CROSSLOCK on the covered vnode so that lock B will
794 * remain held until after step 5.
797 vfs_busy(struct mount *mp, int flags)
799 struct mount_pcpu *mpcpu;
801 MPASS((flags & ~MBF_MASK) == 0);
802 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
804 if (vfs_op_thread_enter(mp, mpcpu)) {
805 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
806 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
807 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
808 vfs_mp_count_add_pcpu(mpcpu, ref, 1);
809 vfs_mp_count_add_pcpu(mpcpu, lockref, 1);
810 vfs_op_thread_exit(mp, mpcpu);
811 if (flags & MBF_MNTLSTLOCK)
812 mtx_unlock(&mountlist_mtx);
817 vfs_assert_mount_counters(mp);
820 * If mount point is currently being unmounted, sleep until the
821 * mount point fate is decided. If thread doing the unmounting fails,
822 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
823 * that this mount point has survived the unmount attempt and vfs_busy
824 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
825 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
826 * about to be really destroyed. vfs_busy needs to release its
827 * reference on the mount point in this case and return with ENOENT,
828 * telling the caller the mount it tried to busy is no longer valid.
830 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
831 KASSERT(TAILQ_EMPTY(&mp->mnt_uppers),
832 ("%s: non-empty upper mount list with pending 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 mtx_lock(&vnode_list_mtx);
1252 MPASS(vp->v_type != VMARKER);
1253 if (!should_yield())
1255 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1256 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1257 mtx_unlock(&vnode_list_mtx);
1258 kern_yield(PRI_USER);
1259 mtx_lock(&vnode_list_mtx);
1262 if (done == 0 && !retried) {
1263 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1264 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1271 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1272 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1274 "limit on vnode free requests per call to the vnlru_free routine");
1277 * Attempt to reduce the free list by the requested amount.
1280 vnlru_free_impl(int count, struct vfsops *mnt_op, struct vnode *mvp)
1286 mtx_assert(&vnode_list_mtx, MA_OWNED);
1287 if (count > max_vnlru_free)
1288 count = max_vnlru_free;
1295 vp = TAILQ_NEXT(vp, v_vnodelist);
1296 if (__predict_false(vp == NULL)) {
1297 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1298 TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1301 if (__predict_false(vp->v_type == VMARKER))
1303 if (vp->v_holdcnt > 0)
1306 * Don't recycle if our vnode is from different type
1307 * of mount point. Note that mp is type-safe, the
1308 * check does not reach unmapped address even if
1309 * vnode is reclaimed.
1311 if (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1312 mp->mnt_op != mnt_op) {
1315 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1318 if (!vhold_recycle_free(vp))
1320 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1321 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1322 mtx_unlock(&vnode_list_mtx);
1324 * FIXME: ignores the return value, meaning it may be nothing
1325 * got recycled but it claims otherwise to the caller.
1327 * Originally the value started being ignored in 2005 with
1328 * 114a1006a8204aa156e1f9ad6476cdff89cada7f .
1330 * Respecting the value can run into significant stalls if most
1331 * vnodes belong to one file system and it has writes
1332 * suspended. In presence of many threads and millions of
1333 * vnodes they keep contending on the vnode_list_mtx lock only
1334 * to find vnodes they can't recycle.
1336 * The solution would be to pre-check if the vnode is likely to
1337 * be recycle-able, but it needs to happen with the
1338 * vnode_list_mtx lock held. This runs into a problem where
1339 * VOP_GETWRITEMOUNT (currently needed to find out about if
1340 * writes are frozen) can take locks which LOR against it.
1342 * Check nullfs for one example (null_getwritemount).
1346 mtx_lock(&vnode_list_mtx);
1349 return (ocount - count);
1353 vnlru_free_locked(int count)
1356 mtx_assert(&vnode_list_mtx, MA_OWNED);
1357 return (vnlru_free_impl(count, NULL, vnode_list_free_marker));
1361 vnlru_free_vfsops(int count, struct vfsops *mnt_op, struct vnode *mvp)
1364 MPASS(mnt_op != NULL);
1366 VNPASS(mvp->v_type == VMARKER, mvp);
1367 mtx_lock(&vnode_list_mtx);
1368 vnlru_free_impl(count, mnt_op, mvp);
1369 mtx_unlock(&vnode_list_mtx);
1373 vnlru_alloc_marker(void)
1377 mvp = vn_alloc_marker(NULL);
1378 mtx_lock(&vnode_list_mtx);
1379 TAILQ_INSERT_BEFORE(vnode_list_free_marker, mvp, v_vnodelist);
1380 mtx_unlock(&vnode_list_mtx);
1385 vnlru_free_marker(struct vnode *mvp)
1387 mtx_lock(&vnode_list_mtx);
1388 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1389 mtx_unlock(&vnode_list_mtx);
1390 vn_free_marker(mvp);
1397 mtx_assert(&vnode_list_mtx, MA_OWNED);
1398 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1399 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1400 vlowat = vhiwat / 2;
1404 * Attempt to recycle vnodes in a context that is always safe to block.
1405 * Calling vlrurecycle() from the bowels of filesystem code has some
1406 * interesting deadlock problems.
1408 static struct proc *vnlruproc;
1409 static int vnlruproc_sig;
1412 * The main freevnodes counter is only updated when threads requeue their vnode
1413 * batches. CPUs are conditionally walked to compute a more accurate total.
1415 * Limit how much of a slop are we willing to tolerate. Note: the actual value
1416 * at any given moment can still exceed slop, but it should not be by significant
1417 * margin in practice.
1419 #define VNLRU_FREEVNODES_SLOP 126
1421 static void __noinline
1422 vfs_freevnodes_rollup(int8_t *lfreevnodes)
1425 atomic_add_long(&freevnodes, *lfreevnodes);
1430 static __inline void
1431 vfs_freevnodes_inc(void)
1433 int8_t *lfreevnodes;
1436 lfreevnodes = PCPU_PTR(vfs_freevnodes);
1438 if (__predict_false(*lfreevnodes == VNLRU_FREEVNODES_SLOP))
1439 vfs_freevnodes_rollup(lfreevnodes);
1444 static __inline void
1445 vfs_freevnodes_dec(void)
1447 int8_t *lfreevnodes;
1450 lfreevnodes = PCPU_PTR(vfs_freevnodes);
1452 if (__predict_false(*lfreevnodes == -VNLRU_FREEVNODES_SLOP))
1453 vfs_freevnodes_rollup(lfreevnodes);
1459 vnlru_read_freevnodes(void)
1461 long slop, rfreevnodes;
1464 rfreevnodes = atomic_load_long(&freevnodes);
1466 if (rfreevnodes > freevnodes_old)
1467 slop = rfreevnodes - freevnodes_old;
1469 slop = freevnodes_old - rfreevnodes;
1470 if (slop < VNLRU_FREEVNODES_SLOP)
1471 return (rfreevnodes >= 0 ? rfreevnodes : 0);
1472 freevnodes_old = rfreevnodes;
1474 freevnodes_old += cpuid_to_pcpu[cpu]->pc_vfs_freevnodes;
1476 return (freevnodes_old >= 0 ? freevnodes_old : 0);
1480 vnlru_under(u_long rnumvnodes, u_long limit)
1482 u_long rfreevnodes, space;
1484 if (__predict_false(rnumvnodes > desiredvnodes))
1487 space = desiredvnodes - rnumvnodes;
1488 if (space < limit) {
1489 rfreevnodes = vnlru_read_freevnodes();
1490 if (rfreevnodes > wantfreevnodes)
1491 space += rfreevnodes - wantfreevnodes;
1493 return (space < limit);
1497 vnlru_under_unlocked(u_long rnumvnodes, u_long limit)
1499 long rfreevnodes, space;
1501 if (__predict_false(rnumvnodes > desiredvnodes))
1504 space = desiredvnodes - rnumvnodes;
1505 if (space < limit) {
1506 rfreevnodes = atomic_load_long(&freevnodes);
1507 if (rfreevnodes > wantfreevnodes)
1508 space += rfreevnodes - wantfreevnodes;
1510 return (space < limit);
1517 mtx_assert(&vnode_list_mtx, MA_OWNED);
1518 if (vnlruproc_sig == 0) {
1527 u_long rnumvnodes, rfreevnodes, target;
1528 unsigned long onumvnodes;
1529 int done, force, trigger, usevnodes;
1530 bool reclaim_nc_src, want_reread;
1532 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1533 SHUTDOWN_PRI_FIRST);
1536 want_reread = false;
1538 kproc_suspend_check(vnlruproc);
1539 mtx_lock(&vnode_list_mtx);
1540 rnumvnodes = atomic_load_long(&numvnodes);
1543 force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1544 want_reread = false;
1548 * If numvnodes is too large (due to desiredvnodes being
1549 * adjusted using its sysctl, or emergency growth), first
1550 * try to reduce it by discarding from the free list.
1552 if (rnumvnodes > desiredvnodes) {
1553 vnlru_free_locked(rnumvnodes - desiredvnodes);
1554 rnumvnodes = atomic_load_long(&numvnodes);
1557 * Sleep if the vnode cache is in a good state. This is
1558 * when it is not over-full and has space for about a 4%
1559 * or 9% expansion (by growing its size or inexcessively
1560 * reducing its free list). Otherwise, try to reclaim
1561 * space for a 10% expansion.
1563 if (vstir && force == 0) {
1567 if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1569 wakeup(&vnlruproc_sig);
1570 msleep(vnlruproc, &vnode_list_mtx,
1571 PVFS|PDROP, "vlruwt", hz);
1574 rfreevnodes = vnlru_read_freevnodes();
1576 onumvnodes = rnumvnodes;
1578 * Calculate parameters for recycling. These are the same
1579 * throughout the loop to give some semblance of fairness.
1580 * The trigger point is to avoid recycling vnodes with lots
1581 * of resident pages. We aren't trying to free memory; we
1582 * are trying to recycle or at least free vnodes.
1584 if (rnumvnodes <= desiredvnodes)
1585 usevnodes = rnumvnodes - rfreevnodes;
1587 usevnodes = rnumvnodes;
1591 * The trigger value is chosen to give a conservatively
1592 * large value to ensure that it alone doesn't prevent
1593 * making progress. The value can easily be so large that
1594 * it is effectively infinite in some congested and
1595 * misconfigured cases, and this is necessary. Normally
1596 * it is about 8 to 100 (pages), which is quite large.
1598 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1600 trigger = vsmalltrigger;
1601 reclaim_nc_src = force >= 3;
1602 target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1603 target = target / 10 + 1;
1604 done = vlrureclaim(reclaim_nc_src, trigger, target);
1605 mtx_unlock(&vnode_list_mtx);
1606 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1607 uma_reclaim(UMA_RECLAIM_DRAIN);
1609 if (force == 0 || force == 1) {
1620 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1623 kern_yield(PRI_USER);
1628 static struct kproc_desc vnlru_kp = {
1633 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1637 * Routines having to do with the management of the vnode table.
1641 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1642 * before we actually vgone(). This function must be called with the vnode
1643 * held to prevent the vnode from being returned to the free list midway
1647 vtryrecycle(struct vnode *vp)
1651 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1652 VNPASS(vp->v_holdcnt > 0, vp);
1654 * This vnode may found and locked via some other list, if so we
1655 * can't recycle it yet.
1657 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1659 "%s: impossible to recycle, vp %p lock is already held",
1662 return (EWOULDBLOCK);
1665 * Don't recycle if its filesystem is being suspended.
1667 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1670 "%s: impossible to recycle, cannot start the write for %p",
1676 * If we got this far, we need to acquire the interlock and see if
1677 * anyone picked up this vnode from another list. If not, we will
1678 * mark it with DOOMED via vgonel() so that anyone who does find it
1679 * will skip over it.
1682 if (vp->v_usecount) {
1685 vn_finished_write(vnmp);
1687 "%s: impossible to recycle, %p is already referenced",
1691 if (!VN_IS_DOOMED(vp)) {
1692 counter_u64_add(recycles_free_count, 1);
1697 vn_finished_write(vnmp);
1702 * Allocate a new vnode.
1704 * The operation never returns an error. Returning an error was disabled
1705 * in r145385 (dated 2005) with the following comment:
1707 * XXX Not all VFS_VGET/ffs_vget callers check returns.
1709 * Given the age of this commit (almost 15 years at the time of writing this
1710 * comment) restoring the ability to fail requires a significant audit of
1713 * The routine can try to free a vnode or stall for up to 1 second waiting for
1714 * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1716 static u_long vn_alloc_cyclecount;
1718 static struct vnode * __noinline
1719 vn_alloc_hard(struct mount *mp)
1721 u_long rnumvnodes, rfreevnodes;
1723 mtx_lock(&vnode_list_mtx);
1724 rnumvnodes = atomic_load_long(&numvnodes);
1725 if (rnumvnodes + 1 < desiredvnodes) {
1726 vn_alloc_cyclecount = 0;
1729 rfreevnodes = vnlru_read_freevnodes();
1730 if (vn_alloc_cyclecount++ >= rfreevnodes) {
1731 vn_alloc_cyclecount = 0;
1735 * Grow the vnode cache if it will not be above its target max
1736 * after growing. Otherwise, if the free list is nonempty, try
1737 * to reclaim 1 item from it before growing the cache (possibly
1738 * above its target max if the reclamation failed or is delayed).
1739 * Otherwise, wait for some space. In all cases, schedule
1740 * vnlru_proc() if we are getting short of space. The watermarks
1741 * should be chosen so that we never wait or even reclaim from
1742 * the free list to below its target minimum.
1744 if (vnlru_free_locked(1) > 0)
1746 if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1748 * Wait for space for a new vnode.
1751 msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1752 if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1753 vnlru_read_freevnodes() > 1)
1754 vnlru_free_locked(1);
1757 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1758 if (vnlru_under(rnumvnodes, vlowat))
1760 mtx_unlock(&vnode_list_mtx);
1761 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1764 static struct vnode *
1765 vn_alloc(struct mount *mp)
1769 if (__predict_false(vn_alloc_cyclecount != 0))
1770 return (vn_alloc_hard(mp));
1771 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1772 if (__predict_false(vnlru_under_unlocked(rnumvnodes, vlowat))) {
1773 atomic_subtract_long(&numvnodes, 1);
1774 return (vn_alloc_hard(mp));
1777 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1781 vn_free(struct vnode *vp)
1784 atomic_subtract_long(&numvnodes, 1);
1785 uma_zfree_smr(vnode_zone, vp);
1789 * Return the next vnode from the free list.
1792 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1797 struct lock_object *lo;
1799 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1801 KASSERT(vops->registered,
1802 ("%s: not registered vector op %p\n", __func__, vops));
1803 cache_validate_vop_vector(mp, vops);
1806 if (td->td_vp_reserved != NULL) {
1807 vp = td->td_vp_reserved;
1808 td->td_vp_reserved = NULL;
1812 counter_u64_add(vnodes_created, 1);
1814 vn_set_state(vp, VSTATE_UNINITIALIZED);
1817 * Locks are given the generic name "vnode" when created.
1818 * Follow the historic practice of using the filesystem
1819 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1821 * Locks live in a witness group keyed on their name. Thus,
1822 * when a lock is renamed, it must also move from the witness
1823 * group of its old name to the witness group of its new name.
1825 * The change only needs to be made when the vnode moves
1826 * from one filesystem type to another. We ensure that each
1827 * filesystem use a single static name pointer for its tag so
1828 * that we can compare pointers rather than doing a strcmp().
1830 lo = &vp->v_vnlock->lock_object;
1832 if (lo->lo_name != tag) {
1836 WITNESS_DESTROY(lo);
1837 WITNESS_INIT(lo, tag);
1841 * By default, don't allow shared locks unless filesystems opt-in.
1843 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1845 * Finalize various vnode identity bits.
1847 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1848 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1849 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1853 v_init_counters(vp);
1855 vp->v_bufobj.bo_ops = &buf_ops_bio;
1857 if (mp == NULL && vops != &dead_vnodeops)
1858 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1862 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1863 mac_vnode_associate_singlelabel(mp, vp);
1866 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1870 * For the filesystems which do not use vfs_hash_insert(),
1871 * still initialize v_hash to have vfs_hash_index() useful.
1872 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1875 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1882 getnewvnode_reserve(void)
1887 MPASS(td->td_vp_reserved == NULL);
1888 td->td_vp_reserved = vn_alloc(NULL);
1892 getnewvnode_drop_reserve(void)
1897 if (td->td_vp_reserved != NULL) {
1898 vn_free(td->td_vp_reserved);
1899 td->td_vp_reserved = NULL;
1903 static void __noinline
1904 freevnode(struct vnode *vp)
1909 * The vnode has been marked for destruction, so free it.
1911 * The vnode will be returned to the zone where it will
1912 * normally remain until it is needed for another vnode. We
1913 * need to cleanup (or verify that the cleanup has already
1914 * been done) any residual data left from its current use
1915 * so as not to contaminate the freshly allocated vnode.
1917 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1919 * Paired with vgone.
1921 vn_seqc_write_end_free(vp);
1924 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1925 VNPASS(vp->v_holdcnt == VHOLD_NO_SMR, vp);
1926 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1927 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1928 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1929 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1930 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1931 ("clean blk trie not empty"));
1932 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1933 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1934 ("dirty blk trie not empty"));
1935 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1936 ("Dangling rangelock waiters"));
1937 VNASSERT((vp->v_iflag & (VI_DOINGINACT | VI_OWEINACT)) == 0, vp,
1938 ("Leaked inactivation"));
1940 cache_assert_no_entries(vp);
1943 mac_vnode_destroy(vp);
1945 if (vp->v_pollinfo != NULL) {
1947 * Use LK_NOWAIT to shut up witness about the lock. We may get
1948 * here while having another vnode locked when trying to
1949 * satisfy a lookup and needing to recycle.
1951 VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT);
1952 destroy_vpollinfo(vp->v_pollinfo);
1954 vp->v_pollinfo = NULL;
1956 vp->v_mountedhere = NULL;
1959 vp->v_fifoinfo = NULL;
1967 * Delete from old mount point vnode list, if on one.
1970 delmntque(struct vnode *vp)
1974 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
1980 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1981 ("bad mount point vnode list size"));
1982 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1983 mp->mnt_nvnodelistsize--;
1987 * The caller expects the interlock to be still held.
1989 ASSERT_VI_LOCKED(vp, __func__);
1993 insmntque1_int(struct vnode *vp, struct mount *mp, bool dtr)
1996 KASSERT(vp->v_mount == NULL,
1997 ("insmntque: vnode already on per mount vnode list"));
1998 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1999 if ((mp->mnt_kern_flag & MNTK_UNLOCKED_INSMNTQUE) == 0) {
2000 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
2003 ("%s: can't have MNTK_UNLOCKED_INSMNTQUE and cleanup",
2008 * We acquire the vnode interlock early to ensure that the
2009 * vnode cannot be recycled by another process releasing a
2010 * holdcnt on it before we get it on both the vnode list
2011 * and the active vnode list. The mount mutex protects only
2012 * manipulation of the vnode list and the vnode freelist
2013 * mutex protects only manipulation of the active vnode list.
2014 * Hence the need to hold the vnode interlock throughout.
2018 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
2019 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
2020 mp->mnt_nvnodelistsize == 0)) &&
2021 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
2026 vp->v_op = &dead_vnodeops;
2034 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
2035 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
2036 ("neg mount point vnode list size"));
2037 mp->mnt_nvnodelistsize++;
2044 * Insert into list of vnodes for the new mount point, if available.
2045 * insmntque() reclaims the vnode on insertion failure, insmntque1()
2046 * leaves handling of the vnode to the caller.
2049 insmntque(struct vnode *vp, struct mount *mp)
2051 return (insmntque1_int(vp, mp, true));
2055 insmntque1(struct vnode *vp, struct mount *mp)
2057 return (insmntque1_int(vp, mp, false));
2061 * Flush out and invalidate all buffers associated with a bufobj
2062 * Called with the underlying object locked.
2065 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
2070 if (flags & V_SAVE) {
2071 error = bufobj_wwait(bo, slpflag, slptimeo);
2076 if (bo->bo_dirty.bv_cnt > 0) {
2079 error = BO_SYNC(bo, MNT_WAIT);
2080 } while (error == ERELOOKUP);
2084 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0) {
2091 * If you alter this loop please notice that interlock is dropped and
2092 * reacquired in flushbuflist. Special care is needed to ensure that
2093 * no race conditions occur from this.
2096 error = flushbuflist(&bo->bo_clean,
2097 flags, bo, slpflag, slptimeo);
2098 if (error == 0 && !(flags & V_CLEANONLY))
2099 error = flushbuflist(&bo->bo_dirty,
2100 flags, bo, slpflag, slptimeo);
2101 if (error != 0 && error != EAGAIN) {
2105 } while (error != 0);
2108 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
2109 * have write I/O in-progress but if there is a VM object then the
2110 * VM object can also have read-I/O in-progress.
2113 bufobj_wwait(bo, 0, 0);
2114 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
2116 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
2119 } while (bo->bo_numoutput > 0);
2123 * Destroy the copy in the VM cache, too.
2125 if (bo->bo_object != NULL &&
2126 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
2127 VM_OBJECT_WLOCK(bo->bo_object);
2128 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
2129 OBJPR_CLEANONLY : 0);
2130 VM_OBJECT_WUNLOCK(bo->bo_object);
2135 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
2136 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
2137 bo->bo_clean.bv_cnt > 0))
2138 panic("vinvalbuf: flush failed");
2139 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
2140 bo->bo_dirty.bv_cnt > 0)
2141 panic("vinvalbuf: flush dirty failed");
2148 * Flush out and invalidate all buffers associated with a vnode.
2149 * Called with the underlying object locked.
2152 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
2155 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2156 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
2157 if (vp->v_object != NULL && vp->v_object->handle != vp)
2159 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
2163 * Flush out buffers on the specified list.
2167 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
2170 struct buf *bp, *nbp;
2175 ASSERT_BO_WLOCKED(bo);
2178 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2180 * If we are flushing both V_NORMAL and V_ALT buffers then
2181 * do not skip any buffers. If we are flushing only V_NORMAL
2182 * buffers then skip buffers marked as BX_ALTDATA. If we are
2183 * flushing only V_ALT buffers then skip buffers not marked
2186 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2187 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2188 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2192 lblkno = nbp->b_lblkno;
2193 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2196 error = BUF_TIMELOCK(bp,
2197 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2198 "flushbuf", slpflag, slptimeo);
2201 return (error != ENOLCK ? error : EAGAIN);
2203 KASSERT(bp->b_bufobj == bo,
2204 ("bp %p wrong b_bufobj %p should be %p",
2205 bp, bp->b_bufobj, bo));
2207 * XXX Since there are no node locks for NFS, I
2208 * believe there is a slight chance that a delayed
2209 * write will occur while sleeping just above, so
2212 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2215 bp->b_flags |= B_ASYNC;
2218 return (EAGAIN); /* XXX: why not loop ? */
2221 bp->b_flags |= (B_INVAL | B_RELBUF);
2222 bp->b_flags &= ~B_ASYNC;
2227 nbp = gbincore(bo, lblkno);
2228 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2230 break; /* nbp invalid */
2236 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2242 ASSERT_BO_LOCKED(bo);
2244 for (lblkno = startn;;) {
2246 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2247 if (bp == NULL || bp->b_lblkno >= endn ||
2248 bp->b_lblkno < startn)
2250 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2251 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2254 if (error == ENOLCK)
2258 KASSERT(bp->b_bufobj == bo,
2259 ("bp %p wrong b_bufobj %p should be %p",
2260 bp, bp->b_bufobj, bo));
2261 lblkno = bp->b_lblkno + 1;
2262 if ((bp->b_flags & B_MANAGED) == 0)
2264 bp->b_flags |= B_RELBUF;
2266 * In the VMIO case, use the B_NOREUSE flag to hint that the
2267 * pages backing each buffer in the range are unlikely to be
2268 * reused. Dirty buffers will have the hint applied once
2269 * they've been written.
2271 if ((bp->b_flags & B_VMIO) != 0)
2272 bp->b_flags |= B_NOREUSE;
2280 * Truncate a file's buffer and pages to a specified length. This
2281 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2285 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2287 struct buf *bp, *nbp;
2291 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2292 vp, blksize, (uintmax_t)length);
2295 * Round up to the *next* lbn.
2297 startlbn = howmany(length, blksize);
2299 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2305 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2310 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2311 if (bp->b_lblkno > 0)
2314 * Since we hold the vnode lock this should only
2315 * fail if we're racing with the buf daemon.
2318 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2319 BO_LOCKPTR(bo)) == ENOLCK)
2320 goto restart_unlocked;
2322 VNASSERT((bp->b_flags & B_DELWRI), vp,
2323 ("buf(%p) on dirty queue without DELWRI", bp));
2332 bufobj_wwait(bo, 0, 0);
2334 vnode_pager_setsize(vp, length);
2340 * Invalidate the cached pages of a file's buffer within the range of block
2341 * numbers [startlbn, endlbn).
2344 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2350 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2352 start = blksize * startlbn;
2353 end = blksize * endlbn;
2357 MPASS(blksize == bo->bo_bsize);
2359 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2363 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2367 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2368 daddr_t startlbn, daddr_t endlbn)
2370 struct buf *bp, *nbp;
2373 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2374 ASSERT_BO_LOCKED(bo);
2378 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2379 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2382 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2383 BO_LOCKPTR(bo)) == ENOLCK) {
2389 bp->b_flags |= B_INVAL | B_RELBUF;
2390 bp->b_flags &= ~B_ASYNC;
2396 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2398 (nbp->b_flags & B_DELWRI) != 0))
2402 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2403 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2406 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2407 BO_LOCKPTR(bo)) == ENOLCK) {
2412 bp->b_flags |= B_INVAL | B_RELBUF;
2413 bp->b_flags &= ~B_ASYNC;
2419 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2420 (nbp->b_vp != vp) ||
2421 (nbp->b_flags & B_DELWRI) == 0))
2429 buf_vlist_remove(struct buf *bp)
2434 flags = bp->b_xflags;
2436 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2437 ASSERT_BO_WLOCKED(bp->b_bufobj);
2438 KASSERT((flags & (BX_VNDIRTY | BX_VNCLEAN)) != 0 &&
2439 (flags & (BX_VNDIRTY | BX_VNCLEAN)) != (BX_VNDIRTY | BX_VNCLEAN),
2440 ("%s: buffer %p has invalid queue state", __func__, bp));
2442 if ((flags & BX_VNDIRTY) != 0)
2443 bv = &bp->b_bufobj->bo_dirty;
2445 bv = &bp->b_bufobj->bo_clean;
2446 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2447 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2449 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2453 * Add the buffer to the sorted clean or dirty block list.
2455 * NOTE: xflags is passed as a constant, optimizing this inline function!
2458 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2464 ASSERT_BO_WLOCKED(bo);
2465 KASSERT((bo->bo_flag & BO_NOBUFS) == 0,
2466 ("buf_vlist_add: bo %p does not allow bufs", bo));
2467 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2468 ("dead bo %p", bo));
2469 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2470 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2471 bp->b_xflags |= xflags;
2472 if (xflags & BX_VNDIRTY)
2478 * Keep the list ordered. Optimize empty list insertion. Assume
2479 * we tend to grow at the tail so lookup_le should usually be cheaper
2482 if (bv->bv_cnt == 0 ||
2483 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2484 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2485 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2486 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2488 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2489 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2491 panic("buf_vlist_add: Preallocated nodes insufficient.");
2496 * Look up a buffer using the buffer tries.
2499 gbincore(struct bufobj *bo, daddr_t lblkno)
2503 ASSERT_BO_LOCKED(bo);
2504 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2507 return (BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno));
2511 * Look up a buf using the buffer tries, without the bufobj lock. This relies
2512 * on SMR for safe lookup, and bufs being in a no-free zone to provide type
2513 * stability of the result. Like other lockless lookups, the found buf may
2514 * already be invalid by the time this function returns.
2517 gbincore_unlocked(struct bufobj *bo, daddr_t lblkno)
2521 ASSERT_BO_UNLOCKED(bo);
2522 bp = BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_clean.bv_root, lblkno);
2525 return (BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_dirty.bv_root, lblkno));
2529 * Associate a buffer with a vnode.
2532 bgetvp(struct vnode *vp, struct buf *bp)
2537 ASSERT_BO_WLOCKED(bo);
2538 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2540 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2541 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2542 ("bgetvp: bp already attached! %p", bp));
2548 * Insert onto list for new vnode.
2550 buf_vlist_add(bp, bo, BX_VNCLEAN);
2554 * Disassociate a buffer from a vnode.
2557 brelvp(struct buf *bp)
2562 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2563 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2566 * Delete from old vnode list, if on one.
2568 vp = bp->b_vp; /* XXX */
2571 buf_vlist_remove(bp);
2572 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2573 bo->bo_flag &= ~BO_ONWORKLST;
2574 mtx_lock(&sync_mtx);
2575 LIST_REMOVE(bo, bo_synclist);
2576 syncer_worklist_len--;
2577 mtx_unlock(&sync_mtx);
2580 bp->b_bufobj = NULL;
2586 * Add an item to the syncer work queue.
2589 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2593 ASSERT_BO_WLOCKED(bo);
2595 mtx_lock(&sync_mtx);
2596 if (bo->bo_flag & BO_ONWORKLST)
2597 LIST_REMOVE(bo, bo_synclist);
2599 bo->bo_flag |= BO_ONWORKLST;
2600 syncer_worklist_len++;
2603 if (delay > syncer_maxdelay - 2)
2604 delay = syncer_maxdelay - 2;
2605 slot = (syncer_delayno + delay) & syncer_mask;
2607 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2608 mtx_unlock(&sync_mtx);
2612 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2616 mtx_lock(&sync_mtx);
2617 len = syncer_worklist_len - sync_vnode_count;
2618 mtx_unlock(&sync_mtx);
2619 error = SYSCTL_OUT(req, &len, sizeof(len));
2623 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2624 CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2625 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2627 static struct proc *updateproc;
2628 static void sched_sync(void);
2629 static struct kproc_desc up_kp = {
2634 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2637 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2642 *bo = LIST_FIRST(slp);
2646 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2649 * We use vhold in case the vnode does not
2650 * successfully sync. vhold prevents the vnode from
2651 * going away when we unlock the sync_mtx so that
2652 * we can acquire the vnode interlock.
2655 mtx_unlock(&sync_mtx);
2657 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2659 mtx_lock(&sync_mtx);
2660 return (*bo == LIST_FIRST(slp));
2662 MPASSERT(mp == NULL || (curthread->td_pflags & TDP_IGNSUSP) != 0 ||
2663 (mp->mnt_kern_flag & MNTK_SUSPENDED) == 0, mp,
2664 ("suspended mp syncing vp %p", vp));
2665 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2666 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2668 vn_finished_write(mp);
2670 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2672 * Put us back on the worklist. The worklist
2673 * routine will remove us from our current
2674 * position and then add us back in at a later
2677 vn_syncer_add_to_worklist(*bo, syncdelay);
2681 mtx_lock(&sync_mtx);
2685 static int first_printf = 1;
2688 * System filesystem synchronizer daemon.
2693 struct synclist *next, *slp;
2696 struct thread *td = curthread;
2698 int net_worklist_len;
2699 int syncer_final_iter;
2703 syncer_final_iter = 0;
2704 syncer_state = SYNCER_RUNNING;
2705 starttime = time_uptime;
2706 td->td_pflags |= TDP_NORUNNINGBUF;
2708 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2711 mtx_lock(&sync_mtx);
2713 if (syncer_state == SYNCER_FINAL_DELAY &&
2714 syncer_final_iter == 0) {
2715 mtx_unlock(&sync_mtx);
2716 kproc_suspend_check(td->td_proc);
2717 mtx_lock(&sync_mtx);
2719 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2720 if (syncer_state != SYNCER_RUNNING &&
2721 starttime != time_uptime) {
2723 printf("\nSyncing disks, vnodes remaining... ");
2726 printf("%d ", net_worklist_len);
2728 starttime = time_uptime;
2731 * Push files whose dirty time has expired. Be careful
2732 * of interrupt race on slp queue.
2734 * Skip over empty worklist slots when shutting down.
2737 slp = &syncer_workitem_pending[syncer_delayno];
2738 syncer_delayno += 1;
2739 if (syncer_delayno == syncer_maxdelay)
2741 next = &syncer_workitem_pending[syncer_delayno];
2743 * If the worklist has wrapped since the
2744 * it was emptied of all but syncer vnodes,
2745 * switch to the FINAL_DELAY state and run
2746 * for one more second.
2748 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2749 net_worklist_len == 0 &&
2750 last_work_seen == syncer_delayno) {
2751 syncer_state = SYNCER_FINAL_DELAY;
2752 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2754 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2755 syncer_worklist_len > 0);
2758 * Keep track of the last time there was anything
2759 * on the worklist other than syncer vnodes.
2760 * Return to the SHUTTING_DOWN state if any
2763 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2764 last_work_seen = syncer_delayno;
2765 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2766 syncer_state = SYNCER_SHUTTING_DOWN;
2767 while (!LIST_EMPTY(slp)) {
2768 error = sync_vnode(slp, &bo, td);
2770 LIST_REMOVE(bo, bo_synclist);
2771 LIST_INSERT_HEAD(next, bo, bo_synclist);
2775 if (first_printf == 0) {
2777 * Drop the sync mutex, because some watchdog
2778 * drivers need to sleep while patting
2780 mtx_unlock(&sync_mtx);
2781 wdog_kern_pat(WD_LASTVAL);
2782 mtx_lock(&sync_mtx);
2785 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2786 syncer_final_iter--;
2788 * The variable rushjob allows the kernel to speed up the
2789 * processing of the filesystem syncer process. A rushjob
2790 * value of N tells the filesystem syncer to process the next
2791 * N seconds worth of work on its queue ASAP. Currently rushjob
2792 * is used by the soft update code to speed up the filesystem
2793 * syncer process when the incore state is getting so far
2794 * ahead of the disk that the kernel memory pool is being
2795 * threatened with exhaustion.
2802 * Just sleep for a short period of time between
2803 * iterations when shutting down to allow some I/O
2806 * If it has taken us less than a second to process the
2807 * current work, then wait. Otherwise start right over
2808 * again. We can still lose time if any single round
2809 * takes more than two seconds, but it does not really
2810 * matter as we are just trying to generally pace the
2811 * filesystem activity.
2813 if (syncer_state != SYNCER_RUNNING ||
2814 time_uptime == starttime) {
2816 sched_prio(td, PPAUSE);
2819 if (syncer_state != SYNCER_RUNNING)
2820 cv_timedwait(&sync_wakeup, &sync_mtx,
2821 hz / SYNCER_SHUTDOWN_SPEEDUP);
2822 else if (time_uptime == starttime)
2823 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2828 * Request the syncer daemon to speed up its work.
2829 * We never push it to speed up more than half of its
2830 * normal turn time, otherwise it could take over the cpu.
2833 speedup_syncer(void)
2837 mtx_lock(&sync_mtx);
2838 if (rushjob < syncdelay / 2) {
2840 stat_rush_requests += 1;
2843 mtx_unlock(&sync_mtx);
2844 cv_broadcast(&sync_wakeup);
2849 * Tell the syncer to speed up its work and run though its work
2850 * list several times, then tell it to shut down.
2853 syncer_shutdown(void *arg, int howto)
2856 if (howto & RB_NOSYNC)
2858 mtx_lock(&sync_mtx);
2859 syncer_state = SYNCER_SHUTTING_DOWN;
2861 mtx_unlock(&sync_mtx);
2862 cv_broadcast(&sync_wakeup);
2863 kproc_shutdown(arg, howto);
2867 syncer_suspend(void)
2870 syncer_shutdown(updateproc, 0);
2877 mtx_lock(&sync_mtx);
2879 syncer_state = SYNCER_RUNNING;
2880 mtx_unlock(&sync_mtx);
2881 cv_broadcast(&sync_wakeup);
2882 kproc_resume(updateproc);
2886 * Move the buffer between the clean and dirty lists of its vnode.
2889 reassignbuf(struct buf *bp)
2901 KASSERT((bp->b_flags & B_PAGING) == 0,
2902 ("%s: cannot reassign paging buffer %p", __func__, bp));
2904 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2905 bp, bp->b_vp, bp->b_flags);
2908 buf_vlist_remove(bp);
2911 * If dirty, put on list of dirty buffers; otherwise insert onto list
2914 if (bp->b_flags & B_DELWRI) {
2915 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2916 switch (vp->v_type) {
2926 vn_syncer_add_to_worklist(bo, delay);
2928 buf_vlist_add(bp, bo, BX_VNDIRTY);
2930 buf_vlist_add(bp, bo, BX_VNCLEAN);
2932 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2933 mtx_lock(&sync_mtx);
2934 LIST_REMOVE(bo, bo_synclist);
2935 syncer_worklist_len--;
2936 mtx_unlock(&sync_mtx);
2937 bo->bo_flag &= ~BO_ONWORKLST;
2942 bp = TAILQ_FIRST(&bv->bv_hd);
2943 KASSERT(bp == NULL || bp->b_bufobj == bo,
2944 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2945 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2946 KASSERT(bp == NULL || bp->b_bufobj == bo,
2947 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2949 bp = TAILQ_FIRST(&bv->bv_hd);
2950 KASSERT(bp == NULL || bp->b_bufobj == bo,
2951 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2952 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2953 KASSERT(bp == NULL || bp->b_bufobj == bo,
2954 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2960 v_init_counters(struct vnode *vp)
2963 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2964 vp, ("%s called for an initialized vnode", __FUNCTION__));
2965 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2967 refcount_init(&vp->v_holdcnt, 1);
2968 refcount_init(&vp->v_usecount, 1);
2972 * Grab a particular vnode from the free list, increment its
2973 * reference count and lock it. VIRF_DOOMED is set if the vnode
2974 * is being destroyed. Only callers who specify LK_RETRY will
2975 * see doomed vnodes. If inactive processing was delayed in
2976 * vput try to do it here.
2978 * usecount is manipulated using atomics without holding any locks.
2980 * holdcnt can be manipulated using atomics without holding any locks,
2981 * except when transitioning 1<->0, in which case the interlock is held.
2983 * Consumers which don't guarantee liveness of the vnode can use SMR to
2984 * try to get a reference. Note this operation can fail since the vnode
2985 * may be awaiting getting freed by the time they get to it.
2988 vget_prep_smr(struct vnode *vp)
2992 VFS_SMR_ASSERT_ENTERED();
2994 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3006 vget_prep(struct vnode *vp)
3010 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3020 vget_abort(struct vnode *vp, enum vgetstate vs)
3031 __assert_unreachable();
3036 vget(struct vnode *vp, int flags)
3041 return (vget_finish(vp, flags, vs));
3045 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
3049 if ((flags & LK_INTERLOCK) != 0)
3050 ASSERT_VI_LOCKED(vp, __func__);
3052 ASSERT_VI_UNLOCKED(vp, __func__);
3053 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3054 VNPASS(vp->v_holdcnt > 0, vp);
3055 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3057 error = vn_lock(vp, flags);
3058 if (__predict_false(error != 0)) {
3060 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
3065 vget_finish_ref(vp, vs);
3070 vget_finish_ref(struct vnode *vp, enum vgetstate vs)
3074 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3075 VNPASS(vp->v_holdcnt > 0, vp);
3076 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3078 if (vs == VGET_USECOUNT)
3082 * We hold the vnode. If the usecount is 0 it will be utilized to keep
3083 * the vnode around. Otherwise someone else lended their hold count and
3084 * we have to drop ours.
3086 old = atomic_fetchadd_int(&vp->v_usecount, 1);
3087 VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
3090 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
3091 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
3093 refcount_release(&vp->v_holdcnt);
3099 vref(struct vnode *vp)
3103 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3105 vget_finish_ref(vp, vs);
3109 vrefact(struct vnode *vp)
3112 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3114 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
3115 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3117 refcount_acquire(&vp->v_usecount);
3122 vlazy(struct vnode *vp)
3126 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
3128 if ((vp->v_mflag & VMP_LAZYLIST) != 0)
3131 * We may get here for inactive routines after the vnode got doomed.
3133 if (VN_IS_DOOMED(vp))
3136 mtx_lock(&mp->mnt_listmtx);
3137 if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
3138 vp->v_mflag |= VMP_LAZYLIST;
3139 TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3140 mp->mnt_lazyvnodelistsize++;
3142 mtx_unlock(&mp->mnt_listmtx);
3146 vunlazy(struct vnode *vp)
3150 ASSERT_VI_LOCKED(vp, __func__);
3151 VNPASS(!VN_IS_DOOMED(vp), vp);
3154 mtx_lock(&mp->mnt_listmtx);
3155 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3157 * Don't remove the vnode from the lazy list if another thread
3158 * has increased the hold count. It may have re-enqueued the
3159 * vnode to the lazy list and is now responsible for its
3162 if (vp->v_holdcnt == 0) {
3163 vp->v_mflag &= ~VMP_LAZYLIST;
3164 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3165 mp->mnt_lazyvnodelistsize--;
3167 mtx_unlock(&mp->mnt_listmtx);
3171 * This routine is only meant to be called from vgonel prior to dooming
3175 vunlazy_gone(struct vnode *vp)
3179 ASSERT_VOP_ELOCKED(vp, __func__);
3180 ASSERT_VI_LOCKED(vp, __func__);
3181 VNPASS(!VN_IS_DOOMED(vp), vp);
3183 if (vp->v_mflag & VMP_LAZYLIST) {
3185 mtx_lock(&mp->mnt_listmtx);
3186 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3187 vp->v_mflag &= ~VMP_LAZYLIST;
3188 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3189 mp->mnt_lazyvnodelistsize--;
3190 mtx_unlock(&mp->mnt_listmtx);
3195 vdefer_inactive(struct vnode *vp)
3198 ASSERT_VI_LOCKED(vp, __func__);
3199 VNPASS(vp->v_holdcnt > 0, vp);
3200 if (VN_IS_DOOMED(vp)) {
3204 if (vp->v_iflag & VI_DEFINACT) {
3205 VNPASS(vp->v_holdcnt > 1, vp);
3209 if (vp->v_usecount > 0) {
3210 vp->v_iflag &= ~VI_OWEINACT;
3215 vp->v_iflag |= VI_DEFINACT;
3217 atomic_add_long(&deferred_inact, 1);
3221 vdefer_inactive_unlocked(struct vnode *vp)
3225 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3229 vdefer_inactive(vp);
3232 enum vput_op { VRELE, VPUT, VUNREF };
3235 * Handle ->v_usecount transitioning to 0.
3237 * By releasing the last usecount we take ownership of the hold count which
3238 * provides liveness of the vnode, meaning we have to vdrop.
3240 * For all vnodes we may need to perform inactive processing. It requires an
3241 * exclusive lock on the vnode, while it is legal to call here with only a
3242 * shared lock (or no locks). If locking the vnode in an expected manner fails,
3243 * inactive processing gets deferred to the syncer.
3245 * XXX Some filesystems pass in an exclusively locked vnode and strongly depend
3246 * on the lock being held all the way until VOP_INACTIVE. This in particular
3247 * happens with UFS which adds half-constructed vnodes to the hash, where they
3248 * can be found by other code.
3251 vput_final(struct vnode *vp, enum vput_op func)
3256 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3257 VNPASS(vp->v_holdcnt > 0, vp);
3262 * By the time we got here someone else might have transitioned
3263 * the count back to > 0.
3265 if (vp->v_usecount > 0)
3269 * If the vnode is doomed vgone already performed inactive processing
3272 if (VN_IS_DOOMED(vp))
3275 if (__predict_true(VOP_NEED_INACTIVE(vp) == 0))
3278 if (vp->v_iflag & VI_DOINGINACT)
3282 * Locking operations here will drop the interlock and possibly the
3283 * vnode lock, opening a window where the vnode can get doomed all the
3284 * while ->v_usecount is 0. Set VI_OWEINACT to let vgone know to
3287 vp->v_iflag |= VI_OWEINACT;
3288 want_unlock = false;
3292 switch (VOP_ISLOCKED(vp)) {
3298 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3303 * The lock has at least one sharer, but we have no way
3304 * to conclude whether this is us. Play it safe and
3313 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3314 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3320 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3321 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3327 if (func == VUNREF) {
3328 VNASSERT((vp->v_vflag & VV_UNREF) == 0, vp,
3329 ("recursive vunref"));
3330 vp->v_vflag |= VV_UNREF;
3333 error = vinactive(vp);
3336 if (error != ERELOOKUP || !want_unlock)
3338 VOP_LOCK(vp, LK_EXCLUSIVE);
3341 vp->v_vflag &= ~VV_UNREF;
3344 vdefer_inactive(vp);
3354 * Decrement ->v_usecount for a vnode.
3356 * Releasing the last use count requires additional processing, see vput_final
3357 * above for details.
3359 * Comment above each variant denotes lock state on entry and exit.
3364 * out: same as passed in
3367 vrele(struct vnode *vp)
3370 ASSERT_VI_UNLOCKED(vp, __func__);
3371 if (!refcount_release(&vp->v_usecount))
3373 vput_final(vp, VRELE);
3381 vput(struct vnode *vp)
3384 ASSERT_VOP_LOCKED(vp, __func__);
3385 ASSERT_VI_UNLOCKED(vp, __func__);
3386 if (!refcount_release(&vp->v_usecount)) {
3390 vput_final(vp, VPUT);
3398 vunref(struct vnode *vp)
3401 ASSERT_VOP_LOCKED(vp, __func__);
3402 ASSERT_VI_UNLOCKED(vp, __func__);
3403 if (!refcount_release(&vp->v_usecount))
3405 vput_final(vp, VUNREF);
3409 vhold(struct vnode *vp)
3413 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3414 old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3415 VNASSERT(old >= 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3416 ("%s: wrong hold count %d", __func__, old));
3418 vfs_freevnodes_dec();
3422 vholdnz(struct vnode *vp)
3425 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3427 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3428 VNASSERT(old > 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3429 ("%s: wrong hold count %d", __func__, old));
3431 atomic_add_int(&vp->v_holdcnt, 1);
3436 * Grab a hold count unless the vnode is freed.
3438 * Only use this routine if vfs smr is the only protection you have against
3439 * freeing the vnode.
3441 * The code loops trying to add a hold count as long as the VHOLD_NO_SMR flag
3442 * is not set. After the flag is set the vnode becomes immutable to anyone but
3443 * the thread which managed to set the flag.
3445 * It may be tempting to replace the loop with:
3446 * count = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3447 * if (count & VHOLD_NO_SMR) {
3448 * backpedal and error out;
3451 * However, while this is more performant, it hinders debugging by eliminating
3452 * the previously mentioned invariant.
3455 vhold_smr(struct vnode *vp)
3459 VFS_SMR_ASSERT_ENTERED();
3461 count = atomic_load_int(&vp->v_holdcnt);
3463 if (count & VHOLD_NO_SMR) {
3464 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3465 ("non-zero hold count with flags %d\n", count));
3468 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3469 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3471 vfs_freevnodes_dec();
3478 * Hold a free vnode for recycling.
3480 * Note: vnode_init references this comment.
3482 * Attempts to recycle only need the global vnode list lock and have no use for
3485 * However, vnodes get inserted into the global list before they get fully
3486 * initialized and stay there until UMA decides to free the memory. This in
3487 * particular means the target can be found before it becomes usable and after
3488 * it becomes recycled. Picking up such vnodes is guarded with v_holdcnt set to
3491 * Note: the vnode may gain more references after we transition the count 0->1.
3494 vhold_recycle_free(struct vnode *vp)
3498 mtx_assert(&vnode_list_mtx, MA_OWNED);
3500 count = atomic_load_int(&vp->v_holdcnt);
3502 if (count & VHOLD_NO_SMR) {
3503 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3504 ("non-zero hold count with flags %d\n", count));
3507 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3511 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3512 vfs_freevnodes_dec();
3518 static void __noinline
3519 vdbatch_process(struct vdbatch *vd)
3524 mtx_assert(&vd->lock, MA_OWNED);
3525 MPASS(curthread->td_pinned > 0);
3526 MPASS(vd->index == VDBATCH_SIZE);
3529 if (mtx_trylock(&vnode_list_mtx)) {
3530 for (i = 0; i < VDBATCH_SIZE; i++) {
3533 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3534 TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3535 MPASS(vp->v_dbatchcpu != NOCPU);
3536 vp->v_dbatchcpu = NOCPU;
3538 mtx_unlock(&vnode_list_mtx);
3540 for (i = 0; i < VDBATCH_SIZE; i++) {
3543 MPASS(vp->v_dbatchcpu != NOCPU);
3544 vp->v_dbatchcpu = NOCPU;
3552 vdbatch_enqueue(struct vnode *vp)
3556 ASSERT_VI_LOCKED(vp, __func__);
3557 VNPASS(!VN_IS_DOOMED(vp), vp);
3559 if (vp->v_dbatchcpu != NOCPU) {
3566 mtx_lock(&vd->lock);
3567 MPASS(vd->index < VDBATCH_SIZE);
3568 MPASS(vd->tab[vd->index] == NULL);
3570 * A hack: we depend on being pinned so that we know what to put in
3573 vp->v_dbatchcpu = curcpu;
3574 vd->tab[vd->index] = vp;
3577 if (vd->index == VDBATCH_SIZE)
3578 vdbatch_process(vd);
3579 mtx_unlock(&vd->lock);
3584 * This routine must only be called for vnodes which are about to be
3585 * deallocated. Supporting dequeue for arbitrary vndoes would require
3586 * validating that the locked batch matches.
3589 vdbatch_dequeue(struct vnode *vp)
3595 VNPASS(vp->v_type == VBAD || vp->v_type == VNON, vp);
3597 cpu = vp->v_dbatchcpu;
3601 vd = DPCPU_ID_PTR(cpu, vd);
3602 mtx_lock(&vd->lock);
3603 for (i = 0; i < vd->index; i++) {
3604 if (vd->tab[i] != vp)
3606 vp->v_dbatchcpu = NOCPU;
3608 vd->tab[i] = vd->tab[vd->index];
3609 vd->tab[vd->index] = NULL;
3612 mtx_unlock(&vd->lock);
3614 * Either we dequeued the vnode above or the target CPU beat us to it.
3616 MPASS(vp->v_dbatchcpu == NOCPU);
3620 * Drop the hold count of the vnode. If this is the last reference to
3621 * the vnode we place it on the free list unless it has been vgone'd
3622 * (marked VIRF_DOOMED) in which case we will free it.
3624 * Because the vnode vm object keeps a hold reference on the vnode if
3625 * there is at least one resident non-cached page, the vnode cannot
3626 * leave the active list without the page cleanup done.
3628 static void __noinline
3629 vdropl_final(struct vnode *vp)
3632 ASSERT_VI_LOCKED(vp, __func__);
3633 VNPASS(VN_IS_DOOMED(vp), vp);
3635 * Set the VHOLD_NO_SMR flag.
3637 * We may be racing against vhold_smr. If they win we can just pretend
3638 * we never got this far, they will vdrop later.
3640 if (__predict_false(!atomic_cmpset_int(&vp->v_holdcnt, 0, VHOLD_NO_SMR))) {
3641 vfs_freevnodes_inc();
3644 * We lost the aforementioned race. Any subsequent access is
3645 * invalid as they might have managed to vdropl on their own.
3650 * Don't bump freevnodes as this one is going away.
3656 vdrop(struct vnode *vp)
3659 ASSERT_VI_UNLOCKED(vp, __func__);
3660 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3661 if (refcount_release_if_not_last(&vp->v_holdcnt))
3667 static void __always_inline
3668 vdropl_impl(struct vnode *vp, bool enqueue)
3671 ASSERT_VI_LOCKED(vp, __func__);
3672 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3673 if (!refcount_release(&vp->v_holdcnt)) {
3677 VNPASS((vp->v_iflag & VI_OWEINACT) == 0, vp);
3678 VNPASS((vp->v_iflag & VI_DEFINACT) == 0, vp);
3679 if (VN_IS_DOOMED(vp)) {
3684 vfs_freevnodes_inc();
3685 if (vp->v_mflag & VMP_LAZYLIST) {
3695 * Also unlocks the interlock. We can't assert on it as we
3696 * released our hold and by now the vnode might have been
3699 vdbatch_enqueue(vp);
3703 vdropl(struct vnode *vp)
3706 vdropl_impl(vp, true);
3710 * vdrop a vnode when recycling
3712 * This is a special case routine only to be used when recycling, differs from
3713 * regular vdrop by not requeieing the vnode on LRU.
3715 * Consider a case where vtryrecycle continuously fails with all vnodes (due to
3716 * e.g., frozen writes on the filesystem), filling the batch and causing it to
3717 * be requeued. Then vnlru will end up revisiting the same vnodes. This is a
3718 * loop which can last for as long as writes are frozen.
3721 vdropl_recycle(struct vnode *vp)
3724 vdropl_impl(vp, false);
3728 vdrop_recycle(struct vnode *vp)
3736 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3737 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3740 vinactivef(struct vnode *vp)
3742 struct vm_object *obj;
3745 ASSERT_VOP_ELOCKED(vp, "vinactive");
3746 ASSERT_VI_LOCKED(vp, "vinactive");
3747 VNPASS((vp->v_iflag & VI_DOINGINACT) == 0, vp);
3748 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3749 vp->v_iflag |= VI_DOINGINACT;
3750 vp->v_iflag &= ~VI_OWEINACT;
3753 * Before moving off the active list, we must be sure that any
3754 * modified pages are converted into the vnode's dirty
3755 * buffers, since these will no longer be checked once the
3756 * vnode is on the inactive list.
3758 * The write-out of the dirty pages is asynchronous. At the
3759 * point that VOP_INACTIVE() is called, there could still be
3760 * pending I/O and dirty pages in the object.
3762 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3763 vm_object_mightbedirty(obj)) {
3764 VM_OBJECT_WLOCK(obj);
3765 vm_object_page_clean(obj, 0, 0, 0);
3766 VM_OBJECT_WUNLOCK(obj);
3768 error = VOP_INACTIVE(vp);
3770 VNPASS(vp->v_iflag & VI_DOINGINACT, vp);
3771 vp->v_iflag &= ~VI_DOINGINACT;
3776 vinactive(struct vnode *vp)
3779 ASSERT_VOP_ELOCKED(vp, "vinactive");
3780 ASSERT_VI_LOCKED(vp, "vinactive");
3781 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3783 if ((vp->v_iflag & VI_OWEINACT) == 0)
3785 if (vp->v_iflag & VI_DOINGINACT)
3787 if (vp->v_usecount > 0) {
3788 vp->v_iflag &= ~VI_OWEINACT;
3791 return (vinactivef(vp));
3795 * Remove any vnodes in the vnode table belonging to mount point mp.
3797 * If FORCECLOSE is not specified, there should not be any active ones,
3798 * return error if any are found (nb: this is a user error, not a
3799 * system error). If FORCECLOSE is specified, detach any active vnodes
3802 * If WRITECLOSE is set, only flush out regular file vnodes open for
3805 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3807 * `rootrefs' specifies the base reference count for the root vnode
3808 * of this filesystem. The root vnode is considered busy if its
3809 * v_usecount exceeds this value. On a successful return, vflush(, td)
3810 * will call vrele() on the root vnode exactly rootrefs times.
3811 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3815 static int busyprt = 0; /* print out busy vnodes */
3816 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3820 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3822 struct vnode *vp, *mvp, *rootvp = NULL;
3824 int busy = 0, error;
3826 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3829 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3830 ("vflush: bad args"));
3832 * Get the filesystem root vnode. We can vput() it
3833 * immediately, since with rootrefs > 0, it won't go away.
3835 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3836 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3843 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3845 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3848 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3852 * Skip over a vnodes marked VV_SYSTEM.
3854 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3860 * If WRITECLOSE is set, flush out unlinked but still open
3861 * files (even if open only for reading) and regular file
3862 * vnodes open for writing.
3864 if (flags & WRITECLOSE) {
3865 if (vp->v_object != NULL) {
3866 VM_OBJECT_WLOCK(vp->v_object);
3867 vm_object_page_clean(vp->v_object, 0, 0, 0);
3868 VM_OBJECT_WUNLOCK(vp->v_object);
3871 error = VOP_FSYNC(vp, MNT_WAIT, td);
3872 } while (error == ERELOOKUP);
3876 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3879 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3882 if ((vp->v_type == VNON ||
3883 (error == 0 && vattr.va_nlink > 0)) &&
3884 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3892 * With v_usecount == 0, all we need to do is clear out the
3893 * vnode data structures and we are done.
3895 * If FORCECLOSE is set, forcibly close the vnode.
3897 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3903 vn_printf(vp, "vflush: busy vnode ");
3909 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3911 * If just the root vnode is busy, and if its refcount
3912 * is equal to `rootrefs', then go ahead and kill it.
3915 KASSERT(busy > 0, ("vflush: not busy"));
3916 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3917 ("vflush: usecount %d < rootrefs %d",
3918 rootvp->v_usecount, rootrefs));
3919 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3920 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3928 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3932 for (; rootrefs > 0; rootrefs--)
3938 * Recycle an unused vnode to the front of the free list.
3941 vrecycle(struct vnode *vp)
3946 recycled = vrecyclel(vp);
3952 * vrecycle, with the vp interlock held.
3955 vrecyclel(struct vnode *vp)
3959 ASSERT_VOP_ELOCKED(vp, __func__);
3960 ASSERT_VI_LOCKED(vp, __func__);
3961 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3963 if (vp->v_usecount == 0) {
3971 * Eliminate all activity associated with a vnode
3972 * in preparation for reuse.
3975 vgone(struct vnode *vp)
3983 * Notify upper mounts about reclaimed or unlinked vnode.
3986 vfs_notify_upper(struct vnode *vp, enum vfs_notify_upper_type event)
3989 struct mount_upper_node *ump;
3991 mp = atomic_load_ptr(&vp->v_mount);
3994 if (TAILQ_EMPTY(&mp->mnt_notify))
3998 mp->mnt_upper_pending++;
3999 KASSERT(mp->mnt_upper_pending > 0,
4000 ("%s: mnt_upper_pending %d", __func__, mp->mnt_upper_pending));
4001 TAILQ_FOREACH(ump, &mp->mnt_notify, mnt_upper_link) {
4004 case VFS_NOTIFY_UPPER_RECLAIM:
4005 VFS_RECLAIM_LOWERVP(ump->mp, vp);
4007 case VFS_NOTIFY_UPPER_UNLINK:
4008 VFS_UNLINK_LOWERVP(ump->mp, vp);
4013 mp->mnt_upper_pending--;
4014 if ((mp->mnt_kern_flag & MNTK_UPPER_WAITER) != 0 &&
4015 mp->mnt_upper_pending == 0) {
4016 mp->mnt_kern_flag &= ~MNTK_UPPER_WAITER;
4017 wakeup(&mp->mnt_uppers);
4023 * vgone, with the vp interlock held.
4026 vgonel(struct vnode *vp)
4031 bool active, doinginact, oweinact;
4033 ASSERT_VOP_ELOCKED(vp, "vgonel");
4034 ASSERT_VI_LOCKED(vp, "vgonel");
4035 VNASSERT(vp->v_holdcnt, vp,
4036 ("vgonel: vp %p has no reference.", vp));
4037 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
4041 * Don't vgonel if we're already doomed.
4043 if (VN_IS_DOOMED(vp)) {
4044 VNPASS(vn_get_state(vp) == VSTATE_DESTROYING || \
4045 vn_get_state(vp) == VSTATE_DEAD, vp);
4049 * Paired with freevnode.
4051 vn_seqc_write_begin_locked(vp);
4053 vn_irflag_set_locked(vp, VIRF_DOOMED);
4054 vn_set_state(vp, VSTATE_DESTROYING);
4057 * Check to see if the vnode is in use. If so, we have to
4058 * call VOP_CLOSE() and VOP_INACTIVE().
4060 * It could be that VOP_INACTIVE() requested reclamation, in
4061 * which case we should avoid recursion, so check
4062 * VI_DOINGINACT. This is not precise but good enough.
4064 active = vp->v_usecount > 0;
4065 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4066 doinginact = (vp->v_iflag & VI_DOINGINACT) != 0;
4069 * If we need to do inactive VI_OWEINACT will be set.
4071 if (vp->v_iflag & VI_DEFINACT) {
4072 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
4073 vp->v_iflag &= ~VI_DEFINACT;
4076 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
4079 cache_purge_vgone(vp);
4080 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
4083 * If purging an active vnode, it must be closed and
4084 * deactivated before being reclaimed.
4087 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
4090 if (oweinact || active) {
4093 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4098 if (vp->v_type == VSOCK)
4099 vfs_unp_reclaim(vp);
4102 * Clean out any buffers associated with the vnode.
4103 * If the flush fails, just toss the buffers.
4106 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
4107 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
4108 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
4109 while (vinvalbuf(vp, 0, 0, 0) != 0)
4113 BO_LOCK(&vp->v_bufobj);
4114 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
4115 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
4116 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
4117 vp->v_bufobj.bo_clean.bv_cnt == 0,
4118 ("vp %p bufobj not invalidated", vp));
4121 * For VMIO bufobj, BO_DEAD is set later, or in
4122 * vm_object_terminate() after the object's page queue is
4125 object = vp->v_bufobj.bo_object;
4127 vp->v_bufobj.bo_flag |= BO_DEAD;
4128 BO_UNLOCK(&vp->v_bufobj);
4131 * Handle the VM part. Tmpfs handles v_object on its own (the
4132 * OBJT_VNODE check). Nullfs or other bypassing filesystems
4133 * should not touch the object borrowed from the lower vnode
4134 * (the handle check).
4136 if (object != NULL && object->type == OBJT_VNODE &&
4137 object->handle == vp)
4138 vnode_destroy_vobject(vp);
4141 * Reclaim the vnode.
4143 if (VOP_RECLAIM(vp))
4144 panic("vgone: cannot reclaim");
4146 vn_finished_secondary_write(mp);
4147 VNASSERT(vp->v_object == NULL, vp,
4148 ("vop_reclaim left v_object vp=%p", vp));
4150 * Clear the advisory locks and wake up waiting threads.
4152 if (vp->v_lockf != NULL) {
4153 (void)VOP_ADVLOCKPURGE(vp);
4157 * Delete from old mount point vnode list.
4159 if (vp->v_mount == NULL) {
4163 ASSERT_VI_LOCKED(vp, "vgonel 2");
4166 * Done with purge, reset to the standard lock and invalidate
4169 vp->v_vnlock = &vp->v_lock;
4170 vp->v_op = &dead_vnodeops;
4172 vn_set_state(vp, VSTATE_DEAD);
4176 * Print out a description of a vnode.
4178 static const char *const vtypename[] = {
4188 [VMARKER] = "VMARKER",
4190 _Static_assert(nitems(vtypename) == VLASTTYPE + 1,
4191 "vnode type name not added to vtypename");
4193 static const char *const vstatename[] = {
4194 [VSTATE_UNINITIALIZED] = "VSTATE_UNINITIALIZED",
4195 [VSTATE_CONSTRUCTED] = "VSTATE_CONSTRUCTED",
4196 [VSTATE_DESTROYING] = "VSTATE_DESTROYING",
4197 [VSTATE_DEAD] = "VSTATE_DEAD",
4199 _Static_assert(nitems(vstatename) == VLASTSTATE + 1,
4200 "vnode state name not added to vstatename");
4202 _Static_assert((VHOLD_ALL_FLAGS & ~VHOLD_NO_SMR) == 0,
4203 "new hold count flag not added to vn_printf");
4206 vn_printf(struct vnode *vp, const char *fmt, ...)
4209 char buf[256], buf2[16];
4217 printf("%p: ", (void *)vp);
4218 printf("type %s state %s op %p\n", vtypename[vp->v_type],
4219 vstatename[vp->v_state], vp->v_op);
4220 holdcnt = atomic_load_int(&vp->v_holdcnt);
4221 printf(" usecount %d, writecount %d, refcount %d seqc users %d",
4222 vp->v_usecount, vp->v_writecount, holdcnt & ~VHOLD_ALL_FLAGS,
4224 switch (vp->v_type) {
4226 printf(" mountedhere %p\n", vp->v_mountedhere);
4229 printf(" rdev %p\n", vp->v_rdev);
4232 printf(" socket %p\n", vp->v_unpcb);
4235 printf(" fifoinfo %p\n", vp->v_fifoinfo);
4243 if (holdcnt & VHOLD_NO_SMR)
4244 strlcat(buf, "|VHOLD_NO_SMR", sizeof(buf));
4245 printf(" hold count flags (%s)\n", buf + 1);
4249 irflag = vn_irflag_read(vp);
4250 if (irflag & VIRF_DOOMED)
4251 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
4252 if (irflag & VIRF_PGREAD)
4253 strlcat(buf, "|VIRF_PGREAD", sizeof(buf));
4254 if (irflag & VIRF_MOUNTPOINT)
4255 strlcat(buf, "|VIRF_MOUNTPOINT", sizeof(buf));
4256 if (irflag & VIRF_TEXT_REF)
4257 strlcat(buf, "|VIRF_TEXT_REF", sizeof(buf));
4258 flags = irflag & ~(VIRF_DOOMED | VIRF_PGREAD | VIRF_MOUNTPOINT | VIRF_TEXT_REF);
4260 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
4261 strlcat(buf, buf2, sizeof(buf));
4263 if (vp->v_vflag & VV_ROOT)
4264 strlcat(buf, "|VV_ROOT", sizeof(buf));
4265 if (vp->v_vflag & VV_ISTTY)
4266 strlcat(buf, "|VV_ISTTY", sizeof(buf));
4267 if (vp->v_vflag & VV_NOSYNC)
4268 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
4269 if (vp->v_vflag & VV_ETERNALDEV)
4270 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
4271 if (vp->v_vflag & VV_CACHEDLABEL)
4272 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
4273 if (vp->v_vflag & VV_VMSIZEVNLOCK)
4274 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
4275 if (vp->v_vflag & VV_COPYONWRITE)
4276 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
4277 if (vp->v_vflag & VV_SYSTEM)
4278 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
4279 if (vp->v_vflag & VV_PROCDEP)
4280 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
4281 if (vp->v_vflag & VV_DELETED)
4282 strlcat(buf, "|VV_DELETED", sizeof(buf));
4283 if (vp->v_vflag & VV_MD)
4284 strlcat(buf, "|VV_MD", sizeof(buf));
4285 if (vp->v_vflag & VV_FORCEINSMQ)
4286 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
4287 if (vp->v_vflag & VV_READLINK)
4288 strlcat(buf, "|VV_READLINK", sizeof(buf));
4289 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4290 VV_CACHEDLABEL | VV_VMSIZEVNLOCK | VV_COPYONWRITE | VV_SYSTEM |
4291 VV_PROCDEP | VV_DELETED | VV_MD | VV_FORCEINSMQ | VV_READLINK);
4293 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4294 strlcat(buf, buf2, sizeof(buf));
4296 if (vp->v_iflag & VI_MOUNT)
4297 strlcat(buf, "|VI_MOUNT", sizeof(buf));
4298 if (vp->v_iflag & VI_DOINGINACT)
4299 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4300 if (vp->v_iflag & VI_OWEINACT)
4301 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4302 if (vp->v_iflag & VI_DEFINACT)
4303 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4304 if (vp->v_iflag & VI_FOPENING)
4305 strlcat(buf, "|VI_FOPENING", sizeof(buf));
4306 flags = vp->v_iflag & ~(VI_MOUNT | VI_DOINGINACT |
4307 VI_OWEINACT | VI_DEFINACT | VI_FOPENING);
4309 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4310 strlcat(buf, buf2, sizeof(buf));
4312 if (vp->v_mflag & VMP_LAZYLIST)
4313 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4314 flags = vp->v_mflag & ~(VMP_LAZYLIST);
4316 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4317 strlcat(buf, buf2, sizeof(buf));
4319 printf(" flags (%s)", buf + 1);
4320 if (mtx_owned(VI_MTX(vp)))
4321 printf(" VI_LOCKed");
4323 if (vp->v_object != NULL)
4324 printf(" v_object %p ref %d pages %d "
4325 "cleanbuf %d dirtybuf %d\n",
4326 vp->v_object, vp->v_object->ref_count,
4327 vp->v_object->resident_page_count,
4328 vp->v_bufobj.bo_clean.bv_cnt,
4329 vp->v_bufobj.bo_dirty.bv_cnt);
4331 lockmgr_printinfo(vp->v_vnlock);
4332 if (vp->v_data != NULL)
4338 * List all of the locked vnodes in the system.
4339 * Called when debugging the kernel.
4341 DB_SHOW_COMMAND_FLAGS(lockedvnods, lockedvnodes, DB_CMD_MEMSAFE)
4347 * Note: because this is DDB, we can't obey the locking semantics
4348 * for these structures, which means we could catch an inconsistent
4349 * state and dereference a nasty pointer. Not much to be done
4352 db_printf("Locked vnodes\n");
4353 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4354 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4355 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4356 vn_printf(vp, "vnode ");
4362 * Show details about the given vnode.
4364 DB_SHOW_COMMAND(vnode, db_show_vnode)
4370 vp = (struct vnode *)addr;
4371 vn_printf(vp, "vnode ");
4375 * Show details about the given mount point.
4377 DB_SHOW_COMMAND(mount, db_show_mount)
4388 /* No address given, print short info about all mount points. */
4389 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4390 db_printf("%p %s on %s (%s)\n", mp,
4391 mp->mnt_stat.f_mntfromname,
4392 mp->mnt_stat.f_mntonname,
4393 mp->mnt_stat.f_fstypename);
4397 db_printf("\nMore info: show mount <addr>\n");
4401 mp = (struct mount *)addr;
4402 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4403 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4406 mflags = mp->mnt_flag;
4407 #define MNT_FLAG(flag) do { \
4408 if (mflags & (flag)) { \
4409 if (buf[0] != '\0') \
4410 strlcat(buf, ", ", sizeof(buf)); \
4411 strlcat(buf, (#flag) + 4, sizeof(buf)); \
4412 mflags &= ~(flag); \
4415 MNT_FLAG(MNT_RDONLY);
4416 MNT_FLAG(MNT_SYNCHRONOUS);
4417 MNT_FLAG(MNT_NOEXEC);
4418 MNT_FLAG(MNT_NOSUID);
4419 MNT_FLAG(MNT_NFS4ACLS);
4420 MNT_FLAG(MNT_UNION);
4421 MNT_FLAG(MNT_ASYNC);
4422 MNT_FLAG(MNT_SUIDDIR);
4423 MNT_FLAG(MNT_SOFTDEP);
4424 MNT_FLAG(MNT_NOSYMFOLLOW);
4425 MNT_FLAG(MNT_GJOURNAL);
4426 MNT_FLAG(MNT_MULTILABEL);
4428 MNT_FLAG(MNT_NOATIME);
4429 MNT_FLAG(MNT_NOCLUSTERR);
4430 MNT_FLAG(MNT_NOCLUSTERW);
4432 MNT_FLAG(MNT_EXRDONLY);
4433 MNT_FLAG(MNT_EXPORTED);
4434 MNT_FLAG(MNT_DEFEXPORTED);
4435 MNT_FLAG(MNT_EXPORTANON);
4436 MNT_FLAG(MNT_EXKERB);
4437 MNT_FLAG(MNT_EXPUBLIC);
4438 MNT_FLAG(MNT_LOCAL);
4439 MNT_FLAG(MNT_QUOTA);
4440 MNT_FLAG(MNT_ROOTFS);
4442 MNT_FLAG(MNT_IGNORE);
4443 MNT_FLAG(MNT_UPDATE);
4444 MNT_FLAG(MNT_DELEXPORT);
4445 MNT_FLAG(MNT_RELOAD);
4446 MNT_FLAG(MNT_FORCE);
4447 MNT_FLAG(MNT_SNAPSHOT);
4448 MNT_FLAG(MNT_BYFSID);
4452 strlcat(buf, ", ", sizeof(buf));
4453 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4454 "0x%016jx", mflags);
4456 db_printf(" mnt_flag = %s\n", buf);
4459 flags = mp->mnt_kern_flag;
4460 #define MNT_KERN_FLAG(flag) do { \
4461 if (flags & (flag)) { \
4462 if (buf[0] != '\0') \
4463 strlcat(buf, ", ", sizeof(buf)); \
4464 strlcat(buf, (#flag) + 5, sizeof(buf)); \
4468 MNT_KERN_FLAG(MNTK_UNMOUNTF);
4469 MNT_KERN_FLAG(MNTK_ASYNC);
4470 MNT_KERN_FLAG(MNTK_SOFTDEP);
4471 MNT_KERN_FLAG(MNTK_NOMSYNC);
4472 MNT_KERN_FLAG(MNTK_DRAINING);
4473 MNT_KERN_FLAG(MNTK_REFEXPIRE);
4474 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4475 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4476 MNT_KERN_FLAG(MNTK_NO_IOPF);
4477 MNT_KERN_FLAG(MNTK_RECURSE);
4478 MNT_KERN_FLAG(MNTK_UPPER_WAITER);
4479 MNT_KERN_FLAG(MNTK_UNLOCKED_INSMNTQUE);
4480 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4481 MNT_KERN_FLAG(MNTK_VMSETSIZE_BUG);
4482 MNT_KERN_FLAG(MNTK_FPLOOKUP);
4483 MNT_KERN_FLAG(MNTK_TASKQUEUE_WAITER);
4484 MNT_KERN_FLAG(MNTK_NOASYNC);
4485 MNT_KERN_FLAG(MNTK_UNMOUNT);
4486 MNT_KERN_FLAG(MNTK_MWAIT);
4487 MNT_KERN_FLAG(MNTK_SUSPEND);
4488 MNT_KERN_FLAG(MNTK_SUSPEND2);
4489 MNT_KERN_FLAG(MNTK_SUSPENDED);
4490 MNT_KERN_FLAG(MNTK_NULL_NOCACHE);
4491 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4492 #undef MNT_KERN_FLAG
4495 strlcat(buf, ", ", sizeof(buf));
4496 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4499 db_printf(" mnt_kern_flag = %s\n", buf);
4501 db_printf(" mnt_opt = ");
4502 opt = TAILQ_FIRST(mp->mnt_opt);
4504 db_printf("%s", opt->name);
4505 opt = TAILQ_NEXT(opt, link);
4506 while (opt != NULL) {
4507 db_printf(", %s", opt->name);
4508 opt = TAILQ_NEXT(opt, link);
4514 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4515 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4516 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4517 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4518 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4519 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4520 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4521 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4522 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4523 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4524 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4525 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4527 db_printf(" mnt_cred = { uid=%u ruid=%u",
4528 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4529 if (jailed(mp->mnt_cred))
4530 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4532 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4533 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4534 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4535 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4536 db_printf(" mnt_lazyvnodelistsize = %d\n",
4537 mp->mnt_lazyvnodelistsize);
4538 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4539 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4540 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4541 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4542 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4543 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4544 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4545 db_printf(" mnt_secondary_accwrites = %d\n",
4546 mp->mnt_secondary_accwrites);
4547 db_printf(" mnt_gjprovider = %s\n",
4548 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4549 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4551 db_printf("\n\nList of active vnodes\n");
4552 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4553 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4554 vn_printf(vp, "vnode ");
4559 db_printf("\n\nList of inactive vnodes\n");
4560 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4561 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4562 vn_printf(vp, "vnode ");
4571 * Fill in a struct xvfsconf based on a struct vfsconf.
4574 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4576 struct xvfsconf xvfsp;
4578 bzero(&xvfsp, sizeof(xvfsp));
4579 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4580 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4581 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4582 xvfsp.vfc_flags = vfsp->vfc_flags;
4584 * These are unused in userland, we keep them
4585 * to not break binary compatibility.
4587 xvfsp.vfc_vfsops = NULL;
4588 xvfsp.vfc_next = NULL;
4589 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4592 #ifdef COMPAT_FREEBSD32
4594 uint32_t vfc_vfsops;
4595 char vfc_name[MFSNAMELEN];
4596 int32_t vfc_typenum;
4597 int32_t vfc_refcount;
4603 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4605 struct xvfsconf32 xvfsp;
4607 bzero(&xvfsp, sizeof(xvfsp));
4608 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4609 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4610 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4611 xvfsp.vfc_flags = vfsp->vfc_flags;
4612 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4617 * Top level filesystem related information gathering.
4620 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4622 struct vfsconf *vfsp;
4627 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4628 #ifdef COMPAT_FREEBSD32
4629 if (req->flags & SCTL_MASK32)
4630 error = vfsconf2x32(req, vfsp);
4633 error = vfsconf2x(req, vfsp);
4641 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4642 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4643 "S,xvfsconf", "List of all configured filesystems");
4645 #ifndef BURN_BRIDGES
4646 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4649 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4651 int *name = (int *)arg1 - 1; /* XXX */
4652 u_int namelen = arg2 + 1; /* XXX */
4653 struct vfsconf *vfsp;
4655 log(LOG_WARNING, "userland calling deprecated sysctl, "
4656 "please rebuild world\n");
4658 #if 1 || defined(COMPAT_PRELITE2)
4659 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4661 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4665 case VFS_MAXTYPENUM:
4668 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4671 return (ENOTDIR); /* overloaded */
4673 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4674 if (vfsp->vfc_typenum == name[2])
4679 return (EOPNOTSUPP);
4680 #ifdef COMPAT_FREEBSD32
4681 if (req->flags & SCTL_MASK32)
4682 return (vfsconf2x32(req, vfsp));
4685 return (vfsconf2x(req, vfsp));
4687 return (EOPNOTSUPP);
4690 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4691 CTLFLAG_MPSAFE, vfs_sysctl,
4692 "Generic filesystem");
4694 #if 1 || defined(COMPAT_PRELITE2)
4697 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4700 struct vfsconf *vfsp;
4701 struct ovfsconf ovfs;
4704 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4705 bzero(&ovfs, sizeof(ovfs));
4706 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4707 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4708 ovfs.vfc_index = vfsp->vfc_typenum;
4709 ovfs.vfc_refcount = vfsp->vfc_refcount;
4710 ovfs.vfc_flags = vfsp->vfc_flags;
4711 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4721 #endif /* 1 || COMPAT_PRELITE2 */
4722 #endif /* !BURN_BRIDGES */
4725 unmount_or_warn(struct mount *mp)
4729 error = dounmount(mp, MNT_FORCE, curthread);
4731 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4735 printf("%d)\n", error);
4740 * Unmount all filesystems. The list is traversed in reverse order
4741 * of mounting to avoid dependencies.
4744 vfs_unmountall(void)
4746 struct mount *mp, *tmp;
4748 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4751 * Since this only runs when rebooting, it is not interlocked.
4753 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4757 * Forcibly unmounting "/dev" before "/" would prevent clean
4758 * unmount of the latter.
4760 if (mp == rootdevmp)
4763 unmount_or_warn(mp);
4766 if (rootdevmp != NULL)
4767 unmount_or_warn(rootdevmp);
4771 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4774 ASSERT_VI_LOCKED(vp, __func__);
4775 VNPASS((vp->v_iflag & VI_DEFINACT) == 0, vp);
4776 if ((vp->v_iflag & VI_OWEINACT) == 0) {
4780 if (vn_lock(vp, lkflags) == 0) {
4787 vdefer_inactive_unlocked(vp);
4791 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4794 return (vp->v_iflag & VI_DEFINACT);
4797 static void __noinline
4798 vfs_periodic_inactive(struct mount *mp, int flags)
4800 struct vnode *vp, *mvp;
4803 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4804 if (flags != MNT_WAIT)
4805 lkflags |= LK_NOWAIT;
4807 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4808 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4812 vp->v_iflag &= ~VI_DEFINACT;
4813 vfs_deferred_inactive(vp, lkflags);
4818 vfs_want_msync(struct vnode *vp)
4820 struct vm_object *obj;
4823 * This test may be performed without any locks held.
4824 * We rely on vm_object's type stability.
4826 if (vp->v_vflag & VV_NOSYNC)
4829 return (obj != NULL && vm_object_mightbedirty(obj));
4833 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4836 if (vp->v_vflag & VV_NOSYNC)
4838 if (vp->v_iflag & VI_DEFINACT)
4840 return (vfs_want_msync(vp));
4843 static void __noinline
4844 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4846 struct vnode *vp, *mvp;
4847 struct vm_object *obj;
4848 int lkflags, objflags;
4851 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4852 if (flags != MNT_WAIT) {
4853 lkflags |= LK_NOWAIT;
4854 objflags = OBJPC_NOSYNC;
4856 objflags = OBJPC_SYNC;
4859 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4861 if (vp->v_iflag & VI_DEFINACT) {
4862 vp->v_iflag &= ~VI_DEFINACT;
4865 if (!vfs_want_msync(vp)) {
4867 vfs_deferred_inactive(vp, lkflags);
4872 if (vget(vp, lkflags) == 0) {
4874 if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4875 VM_OBJECT_WLOCK(obj);
4876 vm_object_page_clean(obj, 0, 0, objflags);
4877 VM_OBJECT_WUNLOCK(obj);
4884 vdefer_inactive_unlocked(vp);
4890 vfs_periodic(struct mount *mp, int flags)
4893 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4895 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4896 vfs_periodic_inactive(mp, flags);
4898 vfs_periodic_msync_inactive(mp, flags);
4902 destroy_vpollinfo_free(struct vpollinfo *vi)
4905 knlist_destroy(&vi->vpi_selinfo.si_note);
4906 mtx_destroy(&vi->vpi_lock);
4907 free(vi, M_VNODEPOLL);
4911 destroy_vpollinfo(struct vpollinfo *vi)
4914 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4915 seldrain(&vi->vpi_selinfo);
4916 destroy_vpollinfo_free(vi);
4920 * Initialize per-vnode helper structure to hold poll-related state.
4923 v_addpollinfo(struct vnode *vp)
4925 struct vpollinfo *vi;
4927 if (vp->v_pollinfo != NULL)
4929 vi = malloc(sizeof(*vi), M_VNODEPOLL, M_WAITOK | M_ZERO);
4930 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4931 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4932 vfs_knlunlock, vfs_knl_assert_lock);
4934 if (vp->v_pollinfo != NULL) {
4936 destroy_vpollinfo_free(vi);
4939 vp->v_pollinfo = vi;
4944 * Record a process's interest in events which might happen to
4945 * a vnode. Because poll uses the historic select-style interface
4946 * internally, this routine serves as both the ``check for any
4947 * pending events'' and the ``record my interest in future events''
4948 * functions. (These are done together, while the lock is held,
4949 * to avoid race conditions.)
4952 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4956 mtx_lock(&vp->v_pollinfo->vpi_lock);
4957 if (vp->v_pollinfo->vpi_revents & events) {
4959 * This leaves events we are not interested
4960 * in available for the other process which
4961 * which presumably had requested them
4962 * (otherwise they would never have been
4965 events &= vp->v_pollinfo->vpi_revents;
4966 vp->v_pollinfo->vpi_revents &= ~events;
4968 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4971 vp->v_pollinfo->vpi_events |= events;
4972 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4973 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4978 * Routine to create and manage a filesystem syncer vnode.
4980 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4981 static int sync_fsync(struct vop_fsync_args *);
4982 static int sync_inactive(struct vop_inactive_args *);
4983 static int sync_reclaim(struct vop_reclaim_args *);
4985 static struct vop_vector sync_vnodeops = {
4986 .vop_bypass = VOP_EOPNOTSUPP,
4987 .vop_close = sync_close,
4988 .vop_fsync = sync_fsync,
4989 .vop_getwritemount = vop_stdgetwritemount,
4990 .vop_inactive = sync_inactive,
4991 .vop_need_inactive = vop_stdneed_inactive,
4992 .vop_reclaim = sync_reclaim,
4993 .vop_lock1 = vop_stdlock,
4994 .vop_unlock = vop_stdunlock,
4995 .vop_islocked = vop_stdislocked,
4996 .vop_fplookup_vexec = VOP_EAGAIN,
4997 .vop_fplookup_symlink = VOP_EAGAIN,
4999 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
5002 * Create a new filesystem syncer vnode for the specified mount point.
5005 vfs_allocate_syncvnode(struct mount *mp)
5009 static long start, incr, next;
5012 /* Allocate a new vnode */
5013 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
5015 panic("vfs_allocate_syncvnode: getnewvnode() failed");
5017 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5018 vp->v_vflag |= VV_FORCEINSMQ;
5019 error = insmntque1(vp, mp);
5021 panic("vfs_allocate_syncvnode: insmntque() failed");
5022 vp->v_vflag &= ~VV_FORCEINSMQ;
5023 vn_set_state(vp, VSTATE_CONSTRUCTED);
5026 * Place the vnode onto the syncer worklist. We attempt to
5027 * scatter them about on the list so that they will go off
5028 * at evenly distributed times even if all the filesystems
5029 * are mounted at once.
5032 if (next == 0 || next > syncer_maxdelay) {
5036 start = syncer_maxdelay / 2;
5037 incr = syncer_maxdelay;
5043 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
5044 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
5045 mtx_lock(&sync_mtx);
5047 if (mp->mnt_syncer == NULL) {
5048 mp->mnt_syncer = vp;
5051 mtx_unlock(&sync_mtx);
5054 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5061 vfs_deallocate_syncvnode(struct mount *mp)
5065 mtx_lock(&sync_mtx);
5066 vp = mp->mnt_syncer;
5068 mp->mnt_syncer = NULL;
5069 mtx_unlock(&sync_mtx);
5075 * Do a lazy sync of the filesystem.
5078 sync_fsync(struct vop_fsync_args *ap)
5080 struct vnode *syncvp = ap->a_vp;
5081 struct mount *mp = syncvp->v_mount;
5086 * We only need to do something if this is a lazy evaluation.
5088 if (ap->a_waitfor != MNT_LAZY)
5092 * Move ourselves to the back of the sync list.
5094 bo = &syncvp->v_bufobj;
5096 vn_syncer_add_to_worklist(bo, syncdelay);
5100 * Walk the list of vnodes pushing all that are dirty and
5101 * not already on the sync list.
5103 if (vfs_busy(mp, MBF_NOWAIT) != 0)
5106 save = curthread_pflags_set(TDP_SYNCIO);
5108 * The filesystem at hand may be idle with free vnodes stored in the
5109 * batch. Return them instead of letting them stay there indefinitely.
5111 vfs_periodic(mp, MNT_NOWAIT);
5112 error = VFS_SYNC(mp, MNT_LAZY);
5113 curthread_pflags_restore(save);
5114 vn_lock(syncvp, LK_EXCLUSIVE | LK_RETRY);
5120 * The syncer vnode is no referenced.
5123 sync_inactive(struct vop_inactive_args *ap)
5131 * The syncer vnode is no longer needed and is being decommissioned.
5133 * Modifications to the worklist must be protected by sync_mtx.
5136 sync_reclaim(struct vop_reclaim_args *ap)
5138 struct vnode *vp = ap->a_vp;
5143 mtx_lock(&sync_mtx);
5144 if (vp->v_mount->mnt_syncer == vp)
5145 vp->v_mount->mnt_syncer = NULL;
5146 if (bo->bo_flag & BO_ONWORKLST) {
5147 LIST_REMOVE(bo, bo_synclist);
5148 syncer_worklist_len--;
5150 bo->bo_flag &= ~BO_ONWORKLST;
5152 mtx_unlock(&sync_mtx);
5159 vn_need_pageq_flush(struct vnode *vp)
5161 struct vm_object *obj;
5164 return (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
5165 vm_object_mightbedirty(obj));
5169 * Check if vnode represents a disk device
5172 vn_isdisk_error(struct vnode *vp, int *errp)
5176 if (vp->v_type != VCHR) {
5182 if (vp->v_rdev == NULL)
5184 else if (vp->v_rdev->si_devsw == NULL)
5186 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5191 return (error == 0);
5195 vn_isdisk(struct vnode *vp)
5199 return (vn_isdisk_error(vp, &error));
5203 * VOP_FPLOOKUP_VEXEC routines are subject to special circumstances, see
5204 * the comment above cache_fplookup for details.
5207 vaccess_vexec_smr(mode_t file_mode, uid_t file_uid, gid_t file_gid, struct ucred *cred)
5211 VFS_SMR_ASSERT_ENTERED();
5213 /* Check the owner. */
5214 if (cred->cr_uid == file_uid) {
5215 if (file_mode & S_IXUSR)
5220 /* Otherwise, check the groups (first match) */
5221 if (groupmember(file_gid, cred)) {
5222 if (file_mode & S_IXGRP)
5227 /* Otherwise, check everyone else. */
5228 if (file_mode & S_IXOTH)
5232 * Permission check failed, but it is possible denial will get overwritten
5233 * (e.g., when root is traversing through a 700 directory owned by someone
5236 * vaccess() calls priv_check_cred which in turn can descent into MAC
5237 * modules overriding this result. It's quite unclear what semantics
5238 * are allowed for them to operate, thus for safety we don't call them
5239 * from within the SMR section. This also means if any such modules
5240 * are present, we have to let the regular lookup decide.
5242 error = priv_check_cred_vfs_lookup_nomac(cred);
5248 * MAC modules present.
5259 * Common filesystem object access control check routine. Accepts a
5260 * vnode's type, "mode", uid and gid, requested access mode, and credentials.
5261 * Returns 0 on success, or an errno on failure.
5264 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5265 accmode_t accmode, struct ucred *cred)
5267 accmode_t dac_granted;
5268 accmode_t priv_granted;
5270 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5271 ("invalid bit in accmode"));
5272 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5273 ("VAPPEND without VWRITE"));
5276 * Look for a normal, non-privileged way to access the file/directory
5277 * as requested. If it exists, go with that.
5282 /* Check the owner. */
5283 if (cred->cr_uid == file_uid) {
5284 dac_granted |= VADMIN;
5285 if (file_mode & S_IXUSR)
5286 dac_granted |= VEXEC;
5287 if (file_mode & S_IRUSR)
5288 dac_granted |= VREAD;
5289 if (file_mode & S_IWUSR)
5290 dac_granted |= (VWRITE | VAPPEND);
5292 if ((accmode & dac_granted) == accmode)
5298 /* Otherwise, check the groups (first match) */
5299 if (groupmember(file_gid, cred)) {
5300 if (file_mode & S_IXGRP)
5301 dac_granted |= VEXEC;
5302 if (file_mode & S_IRGRP)
5303 dac_granted |= VREAD;
5304 if (file_mode & S_IWGRP)
5305 dac_granted |= (VWRITE | VAPPEND);
5307 if ((accmode & dac_granted) == accmode)
5313 /* Otherwise, check everyone else. */
5314 if (file_mode & S_IXOTH)
5315 dac_granted |= VEXEC;
5316 if (file_mode & S_IROTH)
5317 dac_granted |= VREAD;
5318 if (file_mode & S_IWOTH)
5319 dac_granted |= (VWRITE | VAPPEND);
5320 if ((accmode & dac_granted) == accmode)
5325 * Build a privilege mask to determine if the set of privileges
5326 * satisfies the requirements when combined with the granted mask
5327 * from above. For each privilege, if the privilege is required,
5328 * bitwise or the request type onto the priv_granted mask.
5334 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5335 * requests, instead of PRIV_VFS_EXEC.
5337 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5338 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5339 priv_granted |= VEXEC;
5342 * Ensure that at least one execute bit is on. Otherwise,
5343 * a privileged user will always succeed, and we don't want
5344 * this to happen unless the file really is executable.
5346 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5347 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5348 !priv_check_cred(cred, PRIV_VFS_EXEC))
5349 priv_granted |= VEXEC;
5352 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5353 !priv_check_cred(cred, PRIV_VFS_READ))
5354 priv_granted |= VREAD;
5356 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5357 !priv_check_cred(cred, PRIV_VFS_WRITE))
5358 priv_granted |= (VWRITE | VAPPEND);
5360 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5361 !priv_check_cred(cred, PRIV_VFS_ADMIN))
5362 priv_granted |= VADMIN;
5364 if ((accmode & (priv_granted | dac_granted)) == accmode) {
5368 return ((accmode & VADMIN) ? EPERM : EACCES);
5372 * Credential check based on process requesting service, and per-attribute
5376 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5377 struct thread *td, accmode_t accmode)
5381 * Kernel-invoked always succeeds.
5387 * Do not allow privileged processes in jail to directly manipulate
5388 * system attributes.
5390 switch (attrnamespace) {
5391 case EXTATTR_NAMESPACE_SYSTEM:
5392 /* Potentially should be: return (EPERM); */
5393 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5394 case EXTATTR_NAMESPACE_USER:
5395 return (VOP_ACCESS(vp, accmode, cred, td));
5401 #ifdef DEBUG_VFS_LOCKS
5402 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
5403 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5404 "Drop into debugger on lock violation");
5406 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
5407 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5408 0, "Check for interlock across VOPs");
5410 int vfs_badlock_print = 1; /* Print lock violations. */
5411 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5412 0, "Print lock violations");
5414 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
5415 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5416 0, "Print vnode details on lock violations");
5419 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
5420 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5421 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5425 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5429 if (vfs_badlock_backtrace)
5432 if (vfs_badlock_vnode)
5433 vn_printf(vp, "vnode ");
5434 if (vfs_badlock_print)
5435 printf("%s: %p %s\n", str, (void *)vp, msg);
5436 if (vfs_badlock_ddb)
5437 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5441 assert_vi_locked(struct vnode *vp, const char *str)
5444 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5445 vfs_badlock("interlock is not locked but should be", str, vp);
5449 assert_vi_unlocked(struct vnode *vp, const char *str)
5452 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5453 vfs_badlock("interlock is locked but should not be", str, vp);
5457 assert_vop_locked(struct vnode *vp, const char *str)
5459 if (KERNEL_PANICKED() || vp == NULL)
5463 if ((vp->v_irflag & VIRF_CROSSMP) == 0 &&
5464 witness_is_owned(&vp->v_vnlock->lock_object) == -1)
5466 int locked = VOP_ISLOCKED(vp);
5467 if (locked == 0 || locked == LK_EXCLOTHER)
5469 vfs_badlock("is not locked but should be", str, vp);
5473 assert_vop_unlocked(struct vnode *vp, const char *str)
5475 if (KERNEL_PANICKED() || vp == NULL)
5479 if ((vp->v_irflag & VIRF_CROSSMP) == 0 &&
5480 witness_is_owned(&vp->v_vnlock->lock_object) == 1)
5482 if (VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5484 vfs_badlock("is locked but should not be", str, vp);
5488 assert_vop_elocked(struct vnode *vp, const char *str)
5490 if (KERNEL_PANICKED() || vp == NULL)
5493 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5494 vfs_badlock("is not exclusive locked but should be", str, vp);
5496 #endif /* DEBUG_VFS_LOCKS */
5499 vop_rename_fail(struct vop_rename_args *ap)
5502 if (ap->a_tvp != NULL)
5504 if (ap->a_tdvp == ap->a_tvp)
5513 vop_rename_pre(void *ap)
5515 struct vop_rename_args *a = ap;
5517 #ifdef DEBUG_VFS_LOCKS
5519 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5520 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5521 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5522 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5524 /* Check the source (from). */
5525 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5526 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5527 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5528 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5529 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5531 /* Check the target. */
5533 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5534 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5537 * It may be tempting to add vn_seqc_write_begin/end calls here and
5538 * in vop_rename_post but that's not going to work out since some
5539 * filesystems relookup vnodes mid-rename. This is probably a bug.
5541 * For now filesystems are expected to do the relevant calls after they
5542 * decide what vnodes to operate on.
5544 if (a->a_tdvp != a->a_fdvp)
5546 if (a->a_tvp != a->a_fvp)
5553 #ifdef DEBUG_VFS_LOCKS
5555 vop_fplookup_vexec_debugpre(void *ap __unused)
5558 VFS_SMR_ASSERT_ENTERED();
5562 vop_fplookup_vexec_debugpost(void *ap, int rc)
5564 struct vop_fplookup_vexec_args *a;
5570 VFS_SMR_ASSERT_ENTERED();
5571 if (rc == EOPNOTSUPP)
5572 VNPASS(VN_IS_DOOMED(vp), vp);
5576 vop_fplookup_symlink_debugpre(void *ap __unused)
5579 VFS_SMR_ASSERT_ENTERED();
5583 vop_fplookup_symlink_debugpost(void *ap __unused, int rc __unused)
5586 VFS_SMR_ASSERT_ENTERED();
5590 vop_fsync_debugprepost(struct vnode *vp, const char *name)
5592 if (vp->v_type == VCHR)
5594 else if (MNT_EXTENDED_SHARED(vp->v_mount))
5595 ASSERT_VOP_LOCKED(vp, name);
5597 ASSERT_VOP_ELOCKED(vp, name);
5601 vop_fsync_debugpre(void *a)
5603 struct vop_fsync_args *ap;
5606 vop_fsync_debugprepost(ap->a_vp, "fsync");
5610 vop_fsync_debugpost(void *a, int rc __unused)
5612 struct vop_fsync_args *ap;
5615 vop_fsync_debugprepost(ap->a_vp, "fsync");
5619 vop_fdatasync_debugpre(void *a)
5621 struct vop_fdatasync_args *ap;
5624 vop_fsync_debugprepost(ap->a_vp, "fsync");
5628 vop_fdatasync_debugpost(void *a, int rc __unused)
5630 struct vop_fdatasync_args *ap;
5633 vop_fsync_debugprepost(ap->a_vp, "fsync");
5637 vop_strategy_debugpre(void *ap)
5639 struct vop_strategy_args *a;
5646 * Cluster ops lock their component buffers but not the IO container.
5648 if ((bp->b_flags & B_CLUSTER) != 0)
5651 if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5652 if (vfs_badlock_print)
5654 "VOP_STRATEGY: bp is not locked but should be\n");
5655 if (vfs_badlock_ddb)
5656 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5661 vop_lock_debugpre(void *ap)
5663 struct vop_lock1_args *a = ap;
5665 if ((a->a_flags & LK_INTERLOCK) == 0)
5666 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5668 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5672 vop_lock_debugpost(void *ap, int rc)
5674 struct vop_lock1_args *a = ap;
5676 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5677 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5678 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5682 vop_unlock_debugpre(void *ap)
5684 struct vop_unlock_args *a = ap;
5685 struct vnode *vp = a->a_vp;
5687 VNPASS(vn_get_state(vp) != VSTATE_UNINITIALIZED, vp);
5688 ASSERT_VOP_LOCKED(vp, "VOP_UNLOCK");
5692 vop_need_inactive_debugpre(void *ap)
5694 struct vop_need_inactive_args *a = ap;
5696 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5700 vop_need_inactive_debugpost(void *ap, int rc)
5702 struct vop_need_inactive_args *a = ap;
5704 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5709 vop_create_pre(void *ap)
5711 struct vop_create_args *a;
5716 vn_seqc_write_begin(dvp);
5720 vop_create_post(void *ap, int rc)
5722 struct vop_create_args *a;
5727 vn_seqc_write_end(dvp);
5729 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5733 vop_whiteout_pre(void *ap)
5735 struct vop_whiteout_args *a;
5740 vn_seqc_write_begin(dvp);
5744 vop_whiteout_post(void *ap, int rc)
5746 struct vop_whiteout_args *a;
5751 vn_seqc_write_end(dvp);
5755 vop_deleteextattr_pre(void *ap)
5757 struct vop_deleteextattr_args *a;
5762 vn_seqc_write_begin(vp);
5766 vop_deleteextattr_post(void *ap, int rc)
5768 struct vop_deleteextattr_args *a;
5773 vn_seqc_write_end(vp);
5775 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5779 vop_link_pre(void *ap)
5781 struct vop_link_args *a;
5782 struct vnode *vp, *tdvp;
5787 vn_seqc_write_begin(vp);
5788 vn_seqc_write_begin(tdvp);
5792 vop_link_post(void *ap, int rc)
5794 struct vop_link_args *a;
5795 struct vnode *vp, *tdvp;
5800 vn_seqc_write_end(vp);
5801 vn_seqc_write_end(tdvp);
5803 VFS_KNOTE_LOCKED(vp, NOTE_LINK);
5804 VFS_KNOTE_LOCKED(tdvp, NOTE_WRITE);
5809 vop_mkdir_pre(void *ap)
5811 struct vop_mkdir_args *a;
5816 vn_seqc_write_begin(dvp);
5820 vop_mkdir_post(void *ap, int rc)
5822 struct vop_mkdir_args *a;
5827 vn_seqc_write_end(dvp);
5829 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5832 #ifdef DEBUG_VFS_LOCKS
5834 vop_mkdir_debugpost(void *ap, int rc)
5836 struct vop_mkdir_args *a;
5840 cache_validate(a->a_dvp, *a->a_vpp, a->a_cnp);
5845 vop_mknod_pre(void *ap)
5847 struct vop_mknod_args *a;
5852 vn_seqc_write_begin(dvp);
5856 vop_mknod_post(void *ap, int rc)
5858 struct vop_mknod_args *a;
5863 vn_seqc_write_end(dvp);
5865 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5869 vop_reclaim_post(void *ap, int rc)
5871 struct vop_reclaim_args *a;
5876 ASSERT_VOP_IN_SEQC(vp);
5878 VFS_KNOTE_LOCKED(vp, NOTE_REVOKE);
5882 vop_remove_pre(void *ap)
5884 struct vop_remove_args *a;
5885 struct vnode *dvp, *vp;
5890 vn_seqc_write_begin(dvp);
5891 vn_seqc_write_begin(vp);
5895 vop_remove_post(void *ap, int rc)
5897 struct vop_remove_args *a;
5898 struct vnode *dvp, *vp;
5903 vn_seqc_write_end(dvp);
5904 vn_seqc_write_end(vp);
5906 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5907 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5912 vop_rename_post(void *ap, int rc)
5914 struct vop_rename_args *a = ap;
5919 if (a->a_fdvp == a->a_tdvp) {
5920 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5922 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5923 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5925 hint |= NOTE_EXTEND;
5926 if (a->a_fvp->v_type == VDIR)
5928 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5930 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5931 a->a_tvp->v_type == VDIR)
5933 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5936 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5938 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5940 if (a->a_tdvp != a->a_fdvp)
5942 if (a->a_tvp != a->a_fvp)
5950 vop_rmdir_pre(void *ap)
5952 struct vop_rmdir_args *a;
5953 struct vnode *dvp, *vp;
5958 vn_seqc_write_begin(dvp);
5959 vn_seqc_write_begin(vp);
5963 vop_rmdir_post(void *ap, int rc)
5965 struct vop_rmdir_args *a;
5966 struct vnode *dvp, *vp;
5971 vn_seqc_write_end(dvp);
5972 vn_seqc_write_end(vp);
5974 vp->v_vflag |= VV_UNLINKED;
5975 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5976 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5981 vop_setattr_pre(void *ap)
5983 struct vop_setattr_args *a;
5988 vn_seqc_write_begin(vp);
5992 vop_setattr_post(void *ap, int rc)
5994 struct vop_setattr_args *a;
5999 vn_seqc_write_end(vp);
6001 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6005 vop_setacl_pre(void *ap)
6007 struct vop_setacl_args *a;
6012 vn_seqc_write_begin(vp);
6016 vop_setacl_post(void *ap, int rc __unused)
6018 struct vop_setacl_args *a;
6023 vn_seqc_write_end(vp);
6027 vop_setextattr_pre(void *ap)
6029 struct vop_setextattr_args *a;
6034 vn_seqc_write_begin(vp);
6038 vop_setextattr_post(void *ap, int rc)
6040 struct vop_setextattr_args *a;
6045 vn_seqc_write_end(vp);
6047 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6051 vop_symlink_pre(void *ap)
6053 struct vop_symlink_args *a;
6058 vn_seqc_write_begin(dvp);
6062 vop_symlink_post(void *ap, int rc)
6064 struct vop_symlink_args *a;
6069 vn_seqc_write_end(dvp);
6071 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6075 vop_open_post(void *ap, int rc)
6077 struct vop_open_args *a = ap;
6080 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
6084 vop_close_post(void *ap, int rc)
6086 struct vop_close_args *a = ap;
6088 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
6089 !VN_IS_DOOMED(a->a_vp))) {
6090 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
6091 NOTE_CLOSE_WRITE : NOTE_CLOSE);
6096 vop_read_post(void *ap, int rc)
6098 struct vop_read_args *a = ap;
6101 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6105 vop_read_pgcache_post(void *ap, int rc)
6107 struct vop_read_pgcache_args *a = ap;
6110 VFS_KNOTE_UNLOCKED(a->a_vp, NOTE_READ);
6114 vop_readdir_post(void *ap, int rc)
6116 struct vop_readdir_args *a = ap;
6119 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6122 static struct knlist fs_knlist;
6125 vfs_event_init(void *arg)
6127 knlist_init_mtx(&fs_knlist, NULL);
6129 /* XXX - correct order? */
6130 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
6133 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
6136 KNOTE_UNLOCKED(&fs_knlist, event);
6139 static int filt_fsattach(struct knote *kn);
6140 static void filt_fsdetach(struct knote *kn);
6141 static int filt_fsevent(struct knote *kn, long hint);
6143 struct filterops fs_filtops = {
6145 .f_attach = filt_fsattach,
6146 .f_detach = filt_fsdetach,
6147 .f_event = filt_fsevent
6151 filt_fsattach(struct knote *kn)
6154 kn->kn_flags |= EV_CLEAR;
6155 knlist_add(&fs_knlist, kn, 0);
6160 filt_fsdetach(struct knote *kn)
6163 knlist_remove(&fs_knlist, kn, 0);
6167 filt_fsevent(struct knote *kn, long hint)
6170 kn->kn_fflags |= kn->kn_sfflags & hint;
6172 return (kn->kn_fflags != 0);
6176 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
6182 error = SYSCTL_IN(req, &vc, sizeof(vc));
6185 if (vc.vc_vers != VFS_CTL_VERS1)
6187 mp = vfs_getvfs(&vc.vc_fsid);
6190 /* ensure that a specific sysctl goes to the right filesystem. */
6191 if (strcmp(vc.vc_fstypename, "*") != 0 &&
6192 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
6196 VCTLTOREQ(&vc, req);
6197 error = VFS_SYSCTL(mp, vc.vc_op, req);
6202 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
6203 NULL, 0, sysctl_vfs_ctl, "",
6207 * Function to initialize a va_filerev field sensibly.
6208 * XXX: Wouldn't a random number make a lot more sense ??
6211 init_va_filerev(void)
6216 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
6219 static int filt_vfsread(struct knote *kn, long hint);
6220 static int filt_vfswrite(struct knote *kn, long hint);
6221 static int filt_vfsvnode(struct knote *kn, long hint);
6222 static void filt_vfsdetach(struct knote *kn);
6223 static struct filterops vfsread_filtops = {
6225 .f_detach = filt_vfsdetach,
6226 .f_event = filt_vfsread
6228 static struct filterops vfswrite_filtops = {
6230 .f_detach = filt_vfsdetach,
6231 .f_event = filt_vfswrite
6233 static struct filterops vfsvnode_filtops = {
6235 .f_detach = filt_vfsdetach,
6236 .f_event = filt_vfsvnode
6240 vfs_knllock(void *arg)
6242 struct vnode *vp = arg;
6244 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
6248 vfs_knlunlock(void *arg)
6250 struct vnode *vp = arg;
6256 vfs_knl_assert_lock(void *arg, int what)
6258 #ifdef DEBUG_VFS_LOCKS
6259 struct vnode *vp = arg;
6261 if (what == LA_LOCKED)
6262 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
6264 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
6269 vfs_kqfilter(struct vop_kqfilter_args *ap)
6271 struct vnode *vp = ap->a_vp;
6272 struct knote *kn = ap->a_kn;
6275 KASSERT(vp->v_type != VFIFO || (kn->kn_filter != EVFILT_READ &&
6276 kn->kn_filter != EVFILT_WRITE),
6277 ("READ/WRITE filter on a FIFO leaked through"));
6278 switch (kn->kn_filter) {
6280 kn->kn_fop = &vfsread_filtops;
6283 kn->kn_fop = &vfswrite_filtops;
6286 kn->kn_fop = &vfsvnode_filtops;
6292 kn->kn_hook = (caddr_t)vp;
6295 if (vp->v_pollinfo == NULL)
6297 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
6299 knlist_add(knl, kn, 0);
6305 * Detach knote from vnode
6308 filt_vfsdetach(struct knote *kn)
6310 struct vnode *vp = (struct vnode *)kn->kn_hook;
6312 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
6313 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
6319 filt_vfsread(struct knote *kn, long hint)
6321 struct vnode *vp = (struct vnode *)kn->kn_hook;
6326 * filesystem is gone, so set the EOF flag and schedule
6327 * the knote for deletion.
6329 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6331 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6336 if (vn_getsize_locked(vp, &size, curthread->td_ucred) != 0)
6340 kn->kn_data = size - kn->kn_fp->f_offset;
6341 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
6348 filt_vfswrite(struct knote *kn, long hint)
6350 struct vnode *vp = (struct vnode *)kn->kn_hook;
6355 * filesystem is gone, so set the EOF flag and schedule
6356 * the knote for deletion.
6358 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
6359 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6367 filt_vfsvnode(struct knote *kn, long hint)
6369 struct vnode *vp = (struct vnode *)kn->kn_hook;
6373 if (kn->kn_sfflags & hint)
6374 kn->kn_fflags |= hint;
6375 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6376 kn->kn_flags |= EV_EOF;
6380 res = (kn->kn_fflags != 0);
6386 * Returns whether the directory is empty or not.
6387 * If it is empty, the return value is 0; otherwise
6388 * the return value is an error value (which may
6392 vfs_emptydir(struct vnode *vp)
6394 struct thread *const td = curthread;
6396 size_t dirbuflen, len;
6402 ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
6403 VNPASS(vp->v_type == VDIR, vp);
6405 error = VOP_GETATTR(vp, &va, td->td_ucred);
6409 dirbuflen = max(DEV_BSIZE, GENERIC_MAXDIRSIZ);
6410 if (dirbuflen < va.va_blocksize)
6411 dirbuflen = va.va_blocksize;
6412 dirbuf = malloc(dirbuflen, M_TEMP, M_WAITOK);
6419 error = vn_dir_next_dirent(vp, td, dirbuf, dirbuflen,
6420 &dp, &len, &off, &eofflag);
6431 * Skip whiteouts. Unionfs operates on filesystems only and not
6432 * on hierarchies, so these whiteouts would be shadowed on the
6433 * system hierarchy but not for a union using the filesystem of
6434 * their directories as the upper layer. Additionally, unionfs
6435 * currently transparently exposes union-specific metadata of
6436 * its upper layer, meaning that whiteouts can be seen through
6437 * the union view in empty directories. Taking into account
6438 * these whiteouts would then prevent mounting another
6439 * filesystem on such effectively empty directories.
6441 if (dp->d_type == DT_WHT)
6445 * Any file in the directory which is not '.' or '..' indicates
6446 * the directory is not empty.
6448 switch (dp->d_namlen) {
6450 if (dp->d_name[1] != '.') {
6451 /* Can't be '..' (nor '.') */
6457 if (dp->d_name[0] != '.') {
6458 /* Can't be '..' nor '.' */
6471 free(dirbuf, M_TEMP);
6476 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6480 if (dp->d_reclen > ap->a_uio->uio_resid)
6481 return (ENAMETOOLONG);
6482 error = uiomove(dp, dp->d_reclen, ap->a_uio);
6484 if (ap->a_ncookies != NULL) {
6485 if (ap->a_cookies != NULL)
6486 free(ap->a_cookies, M_TEMP);
6487 ap->a_cookies = NULL;
6488 *ap->a_ncookies = 0;
6492 if (ap->a_ncookies == NULL)
6495 KASSERT(ap->a_cookies,
6496 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6498 *ap->a_cookies = realloc(*ap->a_cookies,
6499 (*ap->a_ncookies + 1) * sizeof(uint64_t), M_TEMP, M_WAITOK | M_ZERO);
6500 (*ap->a_cookies)[*ap->a_ncookies] = off;
6501 *ap->a_ncookies += 1;
6506 * The purpose of this routine is to remove granularity from accmode_t,
6507 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6508 * VADMIN and VAPPEND.
6510 * If it returns 0, the caller is supposed to continue with the usual
6511 * access checks using 'accmode' as modified by this routine. If it
6512 * returns nonzero value, the caller is supposed to return that value
6515 * Note that after this routine runs, accmode may be zero.
6518 vfs_unixify_accmode(accmode_t *accmode)
6521 * There is no way to specify explicit "deny" rule using
6522 * file mode or POSIX.1e ACLs.
6524 if (*accmode & VEXPLICIT_DENY) {
6530 * None of these can be translated into usual access bits.
6531 * Also, the common case for NFSv4 ACLs is to not contain
6532 * either of these bits. Caller should check for VWRITE
6533 * on the containing directory instead.
6535 if (*accmode & (VDELETE_CHILD | VDELETE))
6538 if (*accmode & VADMIN_PERMS) {
6539 *accmode &= ~VADMIN_PERMS;
6544 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6545 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6547 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6553 * Clear out a doomed vnode (if any) and replace it with a new one as long
6554 * as the fs is not being unmounted. Return the root vnode to the caller.
6556 static int __noinline
6557 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6563 if (mp->mnt_rootvnode != NULL) {
6565 vp = mp->mnt_rootvnode;
6567 if (!VN_IS_DOOMED(vp)) {
6570 error = vn_lock(vp, flags);
6579 * Clear the old one.
6581 mp->mnt_rootvnode = NULL;
6585 vfs_op_barrier_wait(mp);
6589 error = VFS_CACHEDROOT(mp, flags, vpp);
6592 if (mp->mnt_vfs_ops == 0) {
6594 if (mp->mnt_vfs_ops != 0) {
6598 if (mp->mnt_rootvnode == NULL) {
6600 mp->mnt_rootvnode = *vpp;
6602 if (mp->mnt_rootvnode != *vpp) {
6603 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6604 panic("%s: mismatch between vnode returned "
6605 " by VFS_CACHEDROOT and the one cached "
6607 __func__, *vpp, mp->mnt_rootvnode);
6617 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6619 struct mount_pcpu *mpcpu;
6623 if (!vfs_op_thread_enter(mp, mpcpu))
6624 return (vfs_cache_root_fallback(mp, flags, vpp));
6625 vp = atomic_load_ptr(&mp->mnt_rootvnode);
6626 if (vp == NULL || VN_IS_DOOMED(vp)) {
6627 vfs_op_thread_exit(mp, mpcpu);
6628 return (vfs_cache_root_fallback(mp, flags, vpp));
6631 vfs_op_thread_exit(mp, mpcpu);
6632 error = vn_lock(vp, flags);
6635 return (vfs_cache_root_fallback(mp, flags, vpp));
6642 vfs_cache_root_clear(struct mount *mp)
6647 * ops > 0 guarantees there is nobody who can see this vnode
6649 MPASS(mp->mnt_vfs_ops > 0);
6650 vp = mp->mnt_rootvnode;
6652 vn_seqc_write_begin(vp);
6653 mp->mnt_rootvnode = NULL;
6658 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6661 MPASS(mp->mnt_vfs_ops > 0);
6663 mp->mnt_rootvnode = vp;
6667 * These are helper functions for filesystems to traverse all
6668 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6670 * This interface replaces MNT_VNODE_FOREACH.
6674 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6680 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6681 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6682 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6683 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6684 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6687 if (VN_IS_DOOMED(vp)) {
6694 __mnt_vnode_markerfree_all(mvp, mp);
6695 /* MNT_IUNLOCK(mp); -- done in above function */
6696 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6699 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6700 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6706 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6710 *mvp = vn_alloc_marker(mp);
6714 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6715 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6716 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6719 if (VN_IS_DOOMED(vp)) {
6728 vn_free_marker(*mvp);
6732 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6738 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6746 mtx_assert(MNT_MTX(mp), MA_OWNED);
6748 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6749 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6752 vn_free_marker(*mvp);
6757 * These are helper functions for filesystems to traverse their
6758 * lazy vnodes. See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6761 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6764 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6769 vn_free_marker(*mvp);
6774 * Relock the mp mount vnode list lock with the vp vnode interlock in the
6775 * conventional lock order during mnt_vnode_next_lazy iteration.
6777 * On entry, the mount vnode list lock is held and the vnode interlock is not.
6778 * The list lock is dropped and reacquired. On success, both locks are held.
6779 * On failure, the mount vnode list lock is held but the vnode interlock is
6780 * not, and the procedure may have yielded.
6783 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6787 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6788 TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6789 ("%s: bad marker", __func__));
6790 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6791 ("%s: inappropriate vnode", __func__));
6792 ASSERT_VI_UNLOCKED(vp, __func__);
6793 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6795 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6796 TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6799 * Note we may be racing against vdrop which transitioned the hold
6800 * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
6801 * if we are the only user after we get the interlock we will just
6805 mtx_unlock(&mp->mnt_listmtx);
6807 if (VN_IS_DOOMED(vp)) {
6808 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
6811 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
6813 * There is nothing to do if we are the last user.
6815 if (!refcount_release_if_not_last(&vp->v_holdcnt))
6817 mtx_lock(&mp->mnt_listmtx);
6822 mtx_lock(&mp->mnt_listmtx);
6826 static struct vnode *
6827 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6832 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6833 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6835 vp = TAILQ_NEXT(*mvp, v_lazylist);
6836 while (vp != NULL) {
6837 if (vp->v_type == VMARKER) {
6838 vp = TAILQ_NEXT(vp, v_lazylist);
6842 * See if we want to process the vnode. Note we may encounter a
6843 * long string of vnodes we don't care about and hog the list
6844 * as a result. Check for it and requeue the marker.
6846 VNPASS(!VN_IS_DOOMED(vp), vp);
6847 if (!cb(vp, cbarg)) {
6848 if (!should_yield()) {
6849 vp = TAILQ_NEXT(vp, v_lazylist);
6852 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6854 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6856 mtx_unlock(&mp->mnt_listmtx);
6857 kern_yield(PRI_USER);
6858 mtx_lock(&mp->mnt_listmtx);
6862 * Try-lock because this is the wrong lock order.
6864 if (!VI_TRYLOCK(vp) &&
6865 !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6867 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6868 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6869 ("alien vnode on the lazy list %p %p", vp, mp));
6870 VNPASS(vp->v_mount == mp, vp);
6871 VNPASS(!VN_IS_DOOMED(vp), vp);
6874 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6876 /* Check if we are done */
6878 mtx_unlock(&mp->mnt_listmtx);
6879 mnt_vnode_markerfree_lazy(mvp, mp);
6882 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6883 mtx_unlock(&mp->mnt_listmtx);
6884 ASSERT_VI_LOCKED(vp, "lazy iter");
6889 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6894 mtx_lock(&mp->mnt_listmtx);
6895 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6899 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6904 if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
6907 *mvp = vn_alloc_marker(mp);
6912 mtx_lock(&mp->mnt_listmtx);
6913 vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6915 mtx_unlock(&mp->mnt_listmtx);
6916 mnt_vnode_markerfree_lazy(mvp, mp);
6919 TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6920 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6924 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6930 mtx_lock(&mp->mnt_listmtx);
6931 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6932 mtx_unlock(&mp->mnt_listmtx);
6933 mnt_vnode_markerfree_lazy(mvp, mp);
6937 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
6940 if ((cnp->cn_flags & NOEXECCHECK) != 0) {
6941 cnp->cn_flags &= ~NOEXECCHECK;
6945 return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, curthread));
6949 * Do not use this variant unless you have means other than the hold count
6950 * to prevent the vnode from getting freed.
6953 vn_seqc_write_begin_locked(struct vnode *vp)
6956 ASSERT_VI_LOCKED(vp, __func__);
6957 VNPASS(vp->v_holdcnt > 0, vp);
6958 VNPASS(vp->v_seqc_users >= 0, vp);
6960 if (vp->v_seqc_users == 1)
6961 seqc_sleepable_write_begin(&vp->v_seqc);
6965 vn_seqc_write_begin(struct vnode *vp)
6969 vn_seqc_write_begin_locked(vp);
6974 vn_seqc_write_end_locked(struct vnode *vp)
6977 ASSERT_VI_LOCKED(vp, __func__);
6978 VNPASS(vp->v_seqc_users > 0, vp);
6980 if (vp->v_seqc_users == 0)
6981 seqc_sleepable_write_end(&vp->v_seqc);
6985 vn_seqc_write_end(struct vnode *vp)
6989 vn_seqc_write_end_locked(vp);
6994 * Special case handling for allocating and freeing vnodes.
6996 * The counter remains unchanged on free so that a doomed vnode will
6997 * keep testing as in modify as long as it is accessible with SMR.
7000 vn_seqc_init(struct vnode *vp)
7004 vp->v_seqc_users = 0;
7008 vn_seqc_write_end_free(struct vnode *vp)
7011 VNPASS(seqc_in_modify(vp->v_seqc), vp);
7012 VNPASS(vp->v_seqc_users == 1, vp);
7016 vn_irflag_set_locked(struct vnode *vp, short toset)
7020 ASSERT_VI_LOCKED(vp, __func__);
7021 flags = vn_irflag_read(vp);
7022 VNASSERT((flags & toset) == 0, vp,
7023 ("%s: some of the passed flags already set (have %d, passed %d)\n",
7024 __func__, flags, toset));
7025 atomic_store_short(&vp->v_irflag, flags | toset);
7029 vn_irflag_set(struct vnode *vp, short toset)
7033 vn_irflag_set_locked(vp, toset);
7038 vn_irflag_set_cond_locked(struct vnode *vp, short toset)
7042 ASSERT_VI_LOCKED(vp, __func__);
7043 flags = vn_irflag_read(vp);
7044 atomic_store_short(&vp->v_irflag, flags | toset);
7048 vn_irflag_set_cond(struct vnode *vp, short toset)
7052 vn_irflag_set_cond_locked(vp, toset);
7057 vn_irflag_unset_locked(struct vnode *vp, short tounset)
7061 ASSERT_VI_LOCKED(vp, __func__);
7062 flags = vn_irflag_read(vp);
7063 VNASSERT((flags & tounset) == tounset, vp,
7064 ("%s: some of the passed flags not set (have %d, passed %d)\n",
7065 __func__, flags, tounset));
7066 atomic_store_short(&vp->v_irflag, flags & ~tounset);
7070 vn_irflag_unset(struct vnode *vp, short tounset)
7074 vn_irflag_unset_locked(vp, tounset);
7079 vn_getsize_locked(struct vnode *vp, off_t *size, struct ucred *cred)
7084 ASSERT_VOP_LOCKED(vp, __func__);
7085 error = VOP_GETATTR(vp, &vattr, cred);
7086 if (__predict_true(error == 0)) {
7087 if (vattr.va_size <= OFF_MAX)
7088 *size = vattr.va_size;
7096 vn_getsize(struct vnode *vp, off_t *size, struct ucred *cred)
7100 VOP_LOCK(vp, LK_SHARED);
7101 error = vn_getsize_locked(vp, size, cred);
7108 vn_set_state_validate(struct vnode *vp, enum vstate state)
7111 switch (vp->v_state) {
7112 case VSTATE_UNINITIALIZED:
7114 case VSTATE_CONSTRUCTED:
7115 case VSTATE_DESTROYING:
7121 case VSTATE_CONSTRUCTED:
7122 ASSERT_VOP_ELOCKED(vp, __func__);
7124 case VSTATE_DESTROYING:
7130 case VSTATE_DESTROYING:
7131 ASSERT_VOP_ELOCKED(vp, __func__);
7141 case VSTATE_UNINITIALIZED:
7149 vn_printf(vp, "invalid state transition %d -> %d\n", vp->v_state, state);
7150 panic("invalid state transition %d -> %d\n", vp->v_state, state);