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
38 * External virtual filesystem routines
41 #include <sys/cdefs.h>
43 #include "opt_watchdog.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
50 #include <sys/capsicum.h>
51 #include <sys/condvar.h>
53 #include <sys/counter.h>
54 #include <sys/dirent.h>
55 #include <sys/event.h>
56 #include <sys/eventhandler.h>
57 #include <sys/extattr.h>
59 #include <sys/fcntl.h>
62 #include <sys/kernel.h>
63 #include <sys/kthread.h>
65 #include <sys/limits.h>
66 #include <sys/lockf.h>
67 #include <sys/malloc.h>
68 #include <sys/mount.h>
69 #include <sys/namei.h>
70 #include <sys/pctrie.h>
72 #include <sys/reboot.h>
73 #include <sys/refcount.h>
74 #include <sys/rwlock.h>
75 #include <sys/sched.h>
76 #include <sys/sleepqueue.h>
80 #include <sys/sysctl.h>
81 #include <sys/syslog.h>
82 #include <sys/vmmeter.h>
83 #include <sys/vnode.h>
84 #include <sys/watchdog.h>
86 #include <machine/stdarg.h>
88 #include <security/mac/mac_framework.h>
91 #include <vm/vm_object.h>
92 #include <vm/vm_extern.h>
94 #include <vm/vm_map.h>
95 #include <vm/vm_page.h>
96 #include <vm/vm_kern.h>
97 #include <vm/vnode_pager.h>
100 #if defined(DEBUG_VFS_LOCKS) && (!defined(INVARIANTS) || !defined(WITNESS))
101 #error DEBUG_VFS_LOCKS requires INVARIANTS and WITNESS
108 static void delmntque(struct vnode *vp);
109 static int flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
110 int slpflag, int slptimeo);
111 static void syncer_shutdown(void *arg, int howto);
112 static int vtryrecycle(struct vnode *vp, bool isvnlru);
113 static void v_init_counters(struct vnode *);
114 static void vn_seqc_init(struct vnode *);
115 static void vn_seqc_write_end_free(struct vnode *vp);
116 static void vgonel(struct vnode *);
117 static bool vhold_recycle_free(struct vnode *);
118 static void vdropl_recycle(struct vnode *vp);
119 static void vdrop_recycle(struct vnode *vp);
120 static void vfs_knllock(void *arg);
121 static void vfs_knlunlock(void *arg);
122 static void vfs_knl_assert_lock(void *arg, int what);
123 static void destroy_vpollinfo(struct vpollinfo *vi);
124 static int v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
125 daddr_t startlbn, daddr_t endlbn);
126 static void vnlru_recalc(void);
128 static SYSCTL_NODE(_vfs, OID_AUTO, vnode, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
129 "vnode configuration and statistics");
130 static SYSCTL_NODE(_vfs_vnode, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
131 "vnode configuration");
132 static SYSCTL_NODE(_vfs_vnode, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
134 static SYSCTL_NODE(_vfs_vnode, OID_AUTO, vnlru, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
138 * Number of vnodes in existence. Increased whenever getnewvnode()
139 * allocates a new vnode, decreased in vdropl() for VIRF_DOOMED vnode.
141 static u_long __exclusive_cache_line numvnodes;
143 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
144 "Number of vnodes in existence (legacy)");
145 SYSCTL_ULONG(_vfs_vnode_stats, OID_AUTO, count, CTLFLAG_RD, &numvnodes, 0,
146 "Number of vnodes in existence");
148 static counter_u64_t vnodes_created;
149 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
150 "Number of vnodes created by getnewvnode (legacy)");
151 SYSCTL_COUNTER_U64(_vfs_vnode_stats, OID_AUTO, created, CTLFLAG_RD, &vnodes_created,
152 "Number of vnodes created by getnewvnode");
155 * Conversion tables for conversion from vnode types to inode formats
158 __enum_uint8(vtype) iftovt_tab[16] = {
159 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
160 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
162 int vttoif_tab[10] = {
163 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
164 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
168 * List of allocates vnodes in the system.
170 static TAILQ_HEAD(freelst, vnode) vnode_list;
171 static struct vnode *vnode_list_free_marker;
172 static struct vnode *vnode_list_reclaim_marker;
175 * "Free" vnode target. Free vnodes are rarely completely free, but are
176 * just ones that are cheap to recycle. Usually they are for files which
177 * have been stat'd but not read; these usually have inode and namecache
178 * data attached to them. This target is the preferred minimum size of a
179 * sub-cache consisting mostly of such files. The system balances the size
180 * of this sub-cache with its complement to try to prevent either from
181 * thrashing while the other is relatively inactive. The targets express
182 * a preference for the best balance.
184 * "Above" this target there are 2 further targets (watermarks) related
185 * to recyling of free vnodes. In the best-operating case, the cache is
186 * exactly full, the free list has size between vlowat and vhiwat above the
187 * free target, and recycling from it and normal use maintains this state.
188 * Sometimes the free list is below vlowat or even empty, but this state
189 * is even better for immediate use provided the cache is not full.
190 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
191 * ones) to reach one of these states. The watermarks are currently hard-
192 * coded as 4% and 9% of the available space higher. These and the default
193 * of 25% for wantfreevnodes are too large if the memory size is large.
194 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
195 * whenever vnlru_proc() becomes active.
197 static long wantfreevnodes;
198 static long __exclusive_cache_line freevnodes;
199 static long freevnodes_old;
201 static u_long recycles_count;
202 SYSCTL_ULONG(_vfs, OID_AUTO, recycles, CTLFLAG_RD | CTLFLAG_STATS, &recycles_count, 0,
203 "Number of vnodes recycled to meet vnode cache targets (legacy)");
204 SYSCTL_ULONG(_vfs_vnode_vnlru, OID_AUTO, recycles, CTLFLAG_RD | CTLFLAG_STATS,
206 "Number of vnodes recycled to meet vnode cache targets");
208 static u_long recycles_free_count;
209 SYSCTL_ULONG(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD | CTLFLAG_STATS,
210 &recycles_free_count, 0,
211 "Number of free vnodes recycled to meet vnode cache targets (legacy)");
212 SYSCTL_ULONG(_vfs_vnode_vnlru, OID_AUTO, recycles_free, CTLFLAG_RD | CTLFLAG_STATS,
213 &recycles_free_count, 0,
214 "Number of free vnodes recycled to meet vnode cache targets");
216 static counter_u64_t direct_recycles_free_count;
217 SYSCTL_COUNTER_U64(_vfs_vnode_vnlru, OID_AUTO, direct_recycles_free, CTLFLAG_RD,
218 &direct_recycles_free_count,
219 "Number of free vnodes recycled by vn_alloc callers to meet vnode cache targets");
221 static counter_u64_t vnode_skipped_requeues;
222 SYSCTL_COUNTER_U64(_vfs_vnode_stats, OID_AUTO, skipped_requeues, CTLFLAG_RD, &vnode_skipped_requeues,
223 "Number of times LRU requeue was skipped due to lock contention");
225 static u_long deferred_inact;
226 SYSCTL_ULONG(_vfs, OID_AUTO, deferred_inact, CTLFLAG_RD,
227 &deferred_inact, 0, "Number of times inactive processing was deferred");
229 /* To keep more than one thread at a time from running vfs_getnewfsid */
230 static struct mtx mntid_mtx;
233 * Lock for any access to the following:
238 static struct mtx __exclusive_cache_line vnode_list_mtx;
240 /* Publicly exported FS */
241 struct nfs_public nfs_pub;
243 static uma_zone_t buf_trie_zone;
244 static smr_t buf_trie_smr;
246 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
247 static uma_zone_t vnode_zone;
248 MALLOC_DEFINE(M_VNODEPOLL, "VN POLL", "vnode poll");
250 __read_frequently smr_t vfs_smr;
253 * The workitem queue.
255 * It is useful to delay writes of file data and filesystem metadata
256 * for tens of seconds so that quickly created and deleted files need
257 * not waste disk bandwidth being created and removed. To realize this,
258 * we append vnodes to a "workitem" queue. When running with a soft
259 * updates implementation, most pending metadata dependencies should
260 * not wait for more than a few seconds. Thus, mounted on block devices
261 * are delayed only about a half the time that file data is delayed.
262 * Similarly, directory updates are more critical, so are only delayed
263 * about a third the time that file data is delayed. Thus, there are
264 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
265 * one each second (driven off the filesystem syncer process). The
266 * syncer_delayno variable indicates the next queue that is to be processed.
267 * Items that need to be processed soon are placed in this queue:
269 * syncer_workitem_pending[syncer_delayno]
271 * A delay of fifteen seconds is done by placing the request fifteen
272 * entries later in the queue:
274 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
277 static int syncer_delayno;
278 static long syncer_mask;
279 LIST_HEAD(synclist, bufobj);
280 static struct synclist *syncer_workitem_pending;
282 * The sync_mtx protects:
287 * syncer_workitem_pending
288 * syncer_worklist_len
291 static struct mtx sync_mtx;
292 static struct cv sync_wakeup;
294 #define SYNCER_MAXDELAY 32
295 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
296 static int syncdelay = 30; /* max time to delay syncing data */
297 static int filedelay = 30; /* time to delay syncing files */
298 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
299 "Time to delay syncing files (in seconds)");
300 static int dirdelay = 29; /* time to delay syncing directories */
301 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
302 "Time to delay syncing directories (in seconds)");
303 static int metadelay = 28; /* time to delay syncing metadata */
304 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
305 "Time to delay syncing metadata (in seconds)");
306 static int rushjob; /* number of slots to run ASAP */
307 static int stat_rush_requests; /* number of times I/O speeded up */
308 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
309 "Number of times I/O speeded up (rush requests)");
311 #define VDBATCH_SIZE 8
315 struct vnode *tab[VDBATCH_SIZE];
317 DPCPU_DEFINE_STATIC(struct vdbatch, vd);
319 static void vdbatch_dequeue(struct vnode *vp);
322 * When shutting down the syncer, run it at four times normal speed.
324 #define SYNCER_SHUTDOWN_SPEEDUP 4
325 static int sync_vnode_count;
326 static int syncer_worklist_len;
327 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
330 /* Target for maximum number of vnodes. */
331 u_long desiredvnodes;
332 static u_long gapvnodes; /* gap between wanted and desired */
333 static u_long vhiwat; /* enough extras after expansion */
334 static u_long vlowat; /* minimal extras before expansion */
335 static bool vstir; /* nonzero to stir non-free vnodes */
336 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
338 static u_long vnlru_read_freevnodes(void);
341 * Note that no attempt is made to sanitize these parameters.
344 sysctl_maxvnodes(SYSCTL_HANDLER_ARGS)
350 error = sysctl_handle_long(oidp, &val, 0, req);
351 if (error != 0 || req->newptr == NULL)
354 if (val == desiredvnodes)
356 mtx_lock(&vnode_list_mtx);
358 wantfreevnodes = desiredvnodes / 4;
360 mtx_unlock(&vnode_list_mtx);
362 * XXX There is no protection against multiple threads changing
363 * desiredvnodes at the same time. Locking above only helps vnlru and
366 vfs_hash_changesize(desiredvnodes);
367 cache_changesize(desiredvnodes);
371 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
372 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
373 "LU", "Target for maximum number of vnodes (legacy)");
374 SYSCTL_PROC(_vfs_vnode_param, OID_AUTO, limit,
375 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
376 "LU", "Target for maximum number of vnodes");
379 sysctl_freevnodes(SYSCTL_HANDLER_ARGS)
383 rfreevnodes = vnlru_read_freevnodes();
384 return (sysctl_handle_long(oidp, &rfreevnodes, 0, req));
387 SYSCTL_PROC(_vfs, OID_AUTO, freevnodes,
388 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RD, NULL, 0, sysctl_freevnodes,
389 "LU", "Number of \"free\" vnodes (legacy)");
390 SYSCTL_PROC(_vfs_vnode_stats, OID_AUTO, free,
391 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RD, NULL, 0, sysctl_freevnodes,
392 "LU", "Number of \"free\" vnodes");
395 sysctl_wantfreevnodes(SYSCTL_HANDLER_ARGS)
400 val = wantfreevnodes;
401 error = sysctl_handle_long(oidp, &val, 0, req);
402 if (error != 0 || req->newptr == NULL)
405 if (val == wantfreevnodes)
407 mtx_lock(&vnode_list_mtx);
408 wantfreevnodes = val;
410 mtx_unlock(&vnode_list_mtx);
414 SYSCTL_PROC(_vfs, OID_AUTO, wantfreevnodes,
415 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
416 "LU", "Target for minimum number of \"free\" vnodes (legacy)");
417 SYSCTL_PROC(_vfs_vnode_param, OID_AUTO, wantfree,
418 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
419 "LU", "Target for minimum number of \"free\" vnodes");
421 static int vnlru_nowhere;
422 SYSCTL_INT(_vfs_vnode_vnlru, OID_AUTO, failed_runs, CTLFLAG_RD | CTLFLAG_STATS,
423 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
426 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
431 unsigned long ndflags;
434 if (req->newptr == NULL)
436 if (req->newlen >= PATH_MAX)
439 buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
440 error = SYSCTL_IN(req, buf, req->newlen);
444 buf[req->newlen] = '\0';
446 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1;
447 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf);
448 if ((error = namei(&nd)) != 0)
452 if (VN_IS_DOOMED(vp)) {
454 * This vnode is being recycled. Return != 0 to let the caller
455 * know that the sysctl had no effect. Return EAGAIN because a
456 * subsequent call will likely succeed (since namei will create
457 * a new vnode if necessary)
473 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
475 struct thread *td = curthread;
481 if (req->newptr == NULL)
484 error = sysctl_handle_int(oidp, &fd, 0, req);
487 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
492 error = vn_lock(vp, LK_EXCLUSIVE);
503 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
504 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
505 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
506 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
507 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
508 sysctl_ftry_reclaim_vnode, "I",
509 "Try to reclaim a vnode by its file descriptor");
511 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
514 _Static_assert(sizeof(struct vnode) >= 1UL << vnsz2log &&
515 sizeof(struct vnode) < 1UL << (vnsz2log + 1),
516 "vnsz2log needs to be updated");
520 * Support for the bufobj clean & dirty pctrie.
523 buf_trie_alloc(struct pctrie *ptree)
525 return (uma_zalloc_smr(buf_trie_zone, M_NOWAIT));
529 buf_trie_free(struct pctrie *ptree, void *node)
531 uma_zfree_smr(buf_trie_zone, node);
533 PCTRIE_DEFINE_SMR(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free,
537 * Initialize the vnode management data structures.
539 * Reevaluate the following cap on the number of vnodes after the physical
540 * memory size exceeds 512GB. In the limit, as the physical memory size
541 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
543 #ifndef MAXVNODES_MAX
544 #define MAXVNODES_MAX (512UL * 1024 * 1024 / 64) /* 8M */
547 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
549 static struct vnode *
550 vn_alloc_marker(struct mount *mp)
554 vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
555 vp->v_type = VMARKER;
562 vn_free_marker(struct vnode *vp)
565 MPASS(vp->v_type == VMARKER);
566 free(vp, M_VNODE_MARKER);
571 vnode_ctor(void *mem, int size, void *arg __unused, int flags __unused)
573 kasan_mark(mem, size, roundup2(size, UMA_ALIGN_PTR + 1), 0);
578 vnode_dtor(void *mem, int size, void *arg __unused)
580 size_t end1, end2, off1, off2;
582 _Static_assert(offsetof(struct vnode, v_vnodelist) <
583 offsetof(struct vnode, v_dbatchcpu),
584 "KASAN marks require updating");
586 off1 = offsetof(struct vnode, v_vnodelist);
587 off2 = offsetof(struct vnode, v_dbatchcpu);
588 end1 = off1 + sizeof(((struct vnode *)NULL)->v_vnodelist);
589 end2 = off2 + sizeof(((struct vnode *)NULL)->v_dbatchcpu);
592 * Access to the v_vnodelist and v_dbatchcpu fields are permitted even
593 * after the vnode has been freed. Try to get some KASAN coverage by
594 * marking everything except those two fields as invalid. Because
595 * KASAN's tracking is not byte-granular, any preceding fields sharing
596 * the same 8-byte aligned word must also be marked valid.
599 /* Handle the area from the start until v_vnodelist... */
600 off1 = rounddown2(off1, KASAN_SHADOW_SCALE);
601 kasan_mark(mem, off1, off1, KASAN_UMA_FREED);
603 /* ... then the area between v_vnodelist and v_dbatchcpu ... */
604 off1 = roundup2(end1, KASAN_SHADOW_SCALE);
605 off2 = rounddown2(off2, KASAN_SHADOW_SCALE);
607 kasan_mark((void *)((char *)mem + off1), off2 - off1,
608 off2 - off1, KASAN_UMA_FREED);
610 /* ... and finally the area from v_dbatchcpu to the end. */
611 off2 = roundup2(end2, KASAN_SHADOW_SCALE);
612 kasan_mark((void *)((char *)mem + off2), size - off2, size - off2,
618 * Initialize a vnode as it first enters the zone.
621 vnode_init(void *mem, int size, int flags)
630 vp->v_vnlock = &vp->v_lock;
631 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
633 * By default, don't allow shared locks unless filesystems opt-in.
635 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
636 LK_NOSHARE | LK_IS_VNODE);
640 bufobj_init(&vp->v_bufobj, vp);
642 * Initialize namecache.
644 cache_vnode_init(vp);
646 * Initialize rangelocks.
648 rangelock_init(&vp->v_rl);
650 vp->v_dbatchcpu = NOCPU;
652 vp->v_state = VSTATE_DEAD;
655 * Check vhold_recycle_free for an explanation.
657 vp->v_holdcnt = VHOLD_NO_SMR;
659 mtx_lock(&vnode_list_mtx);
660 TAILQ_INSERT_BEFORE(vnode_list_free_marker, vp, v_vnodelist);
661 mtx_unlock(&vnode_list_mtx);
666 * Free a vnode when it is cleared from the zone.
669 vnode_fini(void *mem, int size)
676 mtx_lock(&vnode_list_mtx);
677 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
678 mtx_unlock(&vnode_list_mtx);
679 rangelock_destroy(&vp->v_rl);
680 lockdestroy(vp->v_vnlock);
681 mtx_destroy(&vp->v_interlock);
683 rw_destroy(BO_LOCKPTR(bo));
685 kasan_mark(mem, size, size, 0);
689 * Provide the size of NFS nclnode and NFS fh for calculation of the
690 * vnode memory consumption. The size is specified directly to
691 * eliminate dependency on NFS-private header.
693 * Other filesystems may use bigger or smaller (like UFS and ZFS)
694 * private inode data, but the NFS-based estimation is ample enough.
695 * Still, we care about differences in the size between 64- and 32-bit
698 * Namecache structure size is heuristically
699 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
702 #define NFS_NCLNODE_SZ (528 + 64)
705 #define NFS_NCLNODE_SZ (360 + 32)
710 vntblinit(void *dummy __unused)
715 int cpu, physvnodes, virtvnodes;
718 * Desiredvnodes is a function of the physical memory size and the
719 * kernel's heap size. Generally speaking, it scales with the
720 * physical memory size. The ratio of desiredvnodes to the physical
721 * memory size is 1:16 until desiredvnodes exceeds 98,304.
723 * marginal ratio of desiredvnodes to the physical memory size is
724 * 1:64. However, desiredvnodes is limited by the kernel's heap
725 * size. The memory required by desiredvnodes vnodes and vm objects
726 * must not exceed 1/10th of the kernel's heap size.
728 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
729 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
730 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
731 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
732 desiredvnodes = min(physvnodes, virtvnodes);
733 if (desiredvnodes > MAXVNODES_MAX) {
735 printf("Reducing kern.maxvnodes %lu -> %lu\n",
736 desiredvnodes, MAXVNODES_MAX);
737 desiredvnodes = MAXVNODES_MAX;
739 wantfreevnodes = desiredvnodes / 4;
740 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
741 TAILQ_INIT(&vnode_list);
742 mtx_init(&vnode_list_mtx, "vnode_list", NULL, MTX_DEF);
744 * The lock is taken to appease WITNESS.
746 mtx_lock(&vnode_list_mtx);
748 mtx_unlock(&vnode_list_mtx);
749 vnode_list_free_marker = vn_alloc_marker(NULL);
750 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_free_marker, v_vnodelist);
751 vnode_list_reclaim_marker = vn_alloc_marker(NULL);
752 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_reclaim_marker, v_vnodelist);
761 vnode_zone = uma_zcreate("VNODE", sizeof(struct vnode), ctor, dtor,
762 vnode_init, vnode_fini, UMA_ALIGN_PTR, UMA_ZONE_NOKASAN);
763 uma_zone_set_smr(vnode_zone, vfs_smr);
766 * Preallocate enough nodes to support one-per buf so that
767 * we can not fail an insert. reassignbuf() callers can not
768 * tolerate the insertion failure.
770 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
771 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
772 UMA_ZONE_NOFREE | UMA_ZONE_SMR);
773 buf_trie_smr = uma_zone_get_smr(buf_trie_zone);
774 uma_prealloc(buf_trie_zone, nbuf);
776 vnodes_created = counter_u64_alloc(M_WAITOK);
777 direct_recycles_free_count = counter_u64_alloc(M_WAITOK);
778 vnode_skipped_requeues = counter_u64_alloc(M_WAITOK);
781 * Initialize the filesystem syncer.
783 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
785 syncer_maxdelay = syncer_mask + 1;
786 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
787 cv_init(&sync_wakeup, "syncer");
790 vd = DPCPU_ID_PTR((cpu), vd);
791 bzero(vd, sizeof(*vd));
792 mtx_init(&vd->lock, "vdbatch", NULL, MTX_DEF);
795 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
798 * Mark a mount point as busy. Used to synchronize access and to delay
799 * unmounting. Eventually, mountlist_mtx is not released on failure.
801 * vfs_busy() is a custom lock, it can block the caller.
802 * vfs_busy() only sleeps if the unmount is active on the mount point.
803 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
804 * vnode belonging to mp.
806 * Lookup uses vfs_busy() to traverse mount points.
808 * / vnode lock A / vnode lock (/var) D
809 * /var vnode lock B /log vnode lock(/var/log) E
810 * vfs_busy lock C vfs_busy lock F
812 * Within each file system, the lock order is C->A->B and F->D->E.
814 * When traversing across mounts, the system follows that lock order:
820 * The lookup() process for namei("/var") illustrates the process:
821 * 1. VOP_LOOKUP() obtains B while A is held
822 * 2. vfs_busy() obtains a shared lock on F while A and B are held
823 * 3. vput() releases lock on B
824 * 4. vput() releases lock on A
825 * 5. VFS_ROOT() obtains lock on D while shared lock on F is held
826 * 6. vfs_unbusy() releases shared lock on F
827 * 7. vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
828 * Attempt to lock A (instead of vp_crossmp) while D is held would
829 * violate the global order, causing deadlocks.
831 * dounmount() locks B while F is drained. Note that for stacked
832 * filesystems, D and B in the example above may be the same lock,
833 * which introdues potential lock order reversal deadlock between
834 * dounmount() and step 5 above. These filesystems may avoid the LOR
835 * by setting VV_CROSSLOCK on the covered vnode so that lock B will
836 * remain held until after step 5.
839 vfs_busy(struct mount *mp, int flags)
841 struct mount_pcpu *mpcpu;
843 MPASS((flags & ~MBF_MASK) == 0);
844 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
846 if (vfs_op_thread_enter(mp, mpcpu)) {
847 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
848 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
849 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
850 vfs_mp_count_add_pcpu(mpcpu, ref, 1);
851 vfs_mp_count_add_pcpu(mpcpu, lockref, 1);
852 vfs_op_thread_exit(mp, mpcpu);
853 if (flags & MBF_MNTLSTLOCK)
854 mtx_unlock(&mountlist_mtx);
859 vfs_assert_mount_counters(mp);
862 * If mount point is currently being unmounted, sleep until the
863 * mount point fate is decided. If thread doing the unmounting fails,
864 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
865 * that this mount point has survived the unmount attempt and vfs_busy
866 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
867 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
868 * about to be really destroyed. vfs_busy needs to release its
869 * reference on the mount point in this case and return with ENOENT,
870 * telling the caller the mount it tried to busy is no longer valid.
872 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
873 KASSERT(TAILQ_EMPTY(&mp->mnt_uppers),
874 ("%s: non-empty upper mount list with pending unmount",
876 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
879 CTR1(KTR_VFS, "%s: failed busying before sleeping",
883 if (flags & MBF_MNTLSTLOCK)
884 mtx_unlock(&mountlist_mtx);
885 mp->mnt_kern_flag |= MNTK_MWAIT;
886 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
887 if (flags & MBF_MNTLSTLOCK)
888 mtx_lock(&mountlist_mtx);
891 if (flags & MBF_MNTLSTLOCK)
892 mtx_unlock(&mountlist_mtx);
899 * Free a busy filesystem.
902 vfs_unbusy(struct mount *mp)
904 struct mount_pcpu *mpcpu;
907 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
909 if (vfs_op_thread_enter(mp, mpcpu)) {
910 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
911 vfs_mp_count_sub_pcpu(mpcpu, lockref, 1);
912 vfs_mp_count_sub_pcpu(mpcpu, ref, 1);
913 vfs_op_thread_exit(mp, mpcpu);
918 vfs_assert_mount_counters(mp);
920 c = --mp->mnt_lockref;
921 if (mp->mnt_vfs_ops == 0) {
922 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
927 vfs_dump_mount_counters(mp);
928 if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
929 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
930 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
931 mp->mnt_kern_flag &= ~MNTK_DRAINING;
932 wakeup(&mp->mnt_lockref);
938 * Lookup a mount point by filesystem identifier.
941 vfs_getvfs(fsid_t *fsid)
945 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
946 mtx_lock(&mountlist_mtx);
947 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
948 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
950 mtx_unlock(&mountlist_mtx);
954 mtx_unlock(&mountlist_mtx);
955 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
956 return ((struct mount *) 0);
960 * Lookup a mount point by filesystem identifier, busying it before
963 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
964 * cache for popular filesystem identifiers. The cache is lockess, using
965 * the fact that struct mount's are never freed. In worst case we may
966 * get pointer to unmounted or even different filesystem, so we have to
967 * check what we got, and go slow way if so.
970 vfs_busyfs(fsid_t *fsid)
972 #define FSID_CACHE_SIZE 256
973 typedef struct mount * volatile vmp_t;
974 static vmp_t cache[FSID_CACHE_SIZE];
979 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
980 hash = fsid->val[0] ^ fsid->val[1];
981 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
983 if (mp == NULL || fsidcmp(&mp->mnt_stat.f_fsid, fsid) != 0)
985 if (vfs_busy(mp, 0) != 0) {
989 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0)
995 mtx_lock(&mountlist_mtx);
996 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
997 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
998 error = vfs_busy(mp, MBF_MNTLSTLOCK);
1001 mtx_unlock(&mountlist_mtx);
1008 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
1009 mtx_unlock(&mountlist_mtx);
1010 return ((struct mount *) 0);
1014 * Check if a user can access privileged mount options.
1017 vfs_suser(struct mount *mp, struct thread *td)
1021 if (jailed(td->td_ucred)) {
1023 * If the jail of the calling thread lacks permission for
1024 * this type of file system, deny immediately.
1026 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
1030 * If the file system was mounted outside the jail of the
1031 * calling thread, deny immediately.
1033 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
1038 * If file system supports delegated administration, we don't check
1039 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
1040 * by the file system itself.
1041 * If this is not the user that did original mount, we check for
1042 * the PRIV_VFS_MOUNT_OWNER privilege.
1044 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
1045 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
1046 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
1053 * Get a new unique fsid. Try to make its val[0] unique, since this value
1054 * will be used to create fake device numbers for stat(). Also try (but
1055 * not so hard) make its val[0] unique mod 2^16, since some emulators only
1056 * support 16-bit device numbers. We end up with unique val[0]'s for the
1057 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
1059 * Keep in mind that several mounts may be running in parallel. Starting
1060 * the search one past where the previous search terminated is both a
1061 * micro-optimization and a defense against returning the same fsid to
1065 vfs_getnewfsid(struct mount *mp)
1067 static uint16_t mntid_base;
1072 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
1073 mtx_lock(&mntid_mtx);
1074 mtype = mp->mnt_vfc->vfc_typenum;
1075 tfsid.val[1] = mtype;
1076 mtype = (mtype & 0xFF) << 24;
1078 tfsid.val[0] = makedev(255,
1079 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
1081 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
1085 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
1086 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
1087 mtx_unlock(&mntid_mtx);
1091 * Knob to control the precision of file timestamps:
1093 * 0 = seconds only; nanoseconds zeroed.
1094 * 1 = seconds and nanoseconds, accurate within 1/HZ.
1095 * 2 = seconds and nanoseconds, truncated to microseconds.
1096 * >=3 = seconds and nanoseconds, maximum precision.
1098 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
1100 static int timestamp_precision = TSP_USEC;
1101 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
1102 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
1103 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
1104 "3+: sec + ns (max. precision))");
1107 * Get a current timestamp.
1110 vfs_timestamp(struct timespec *tsp)
1114 switch (timestamp_precision) {
1116 tsp->tv_sec = time_second;
1124 TIMEVAL_TO_TIMESPEC(&tv, tsp);
1134 * Set vnode attributes to VNOVAL
1137 vattr_null(struct vattr *vap)
1140 vap->va_type = VNON;
1141 vap->va_size = VNOVAL;
1142 vap->va_bytes = VNOVAL;
1143 vap->va_mode = VNOVAL;
1144 vap->va_nlink = VNOVAL;
1145 vap->va_uid = VNOVAL;
1146 vap->va_gid = VNOVAL;
1147 vap->va_fsid = VNOVAL;
1148 vap->va_fileid = VNOVAL;
1149 vap->va_blocksize = VNOVAL;
1150 vap->va_rdev = VNOVAL;
1151 vap->va_atime.tv_sec = VNOVAL;
1152 vap->va_atime.tv_nsec = VNOVAL;
1153 vap->va_mtime.tv_sec = VNOVAL;
1154 vap->va_mtime.tv_nsec = VNOVAL;
1155 vap->va_ctime.tv_sec = VNOVAL;
1156 vap->va_ctime.tv_nsec = VNOVAL;
1157 vap->va_birthtime.tv_sec = VNOVAL;
1158 vap->va_birthtime.tv_nsec = VNOVAL;
1159 vap->va_flags = VNOVAL;
1160 vap->va_gen = VNOVAL;
1161 vap->va_vaflags = 0;
1165 * Try to reduce the total number of vnodes.
1167 * This routine (and its user) are buggy in at least the following ways:
1168 * - all parameters were picked years ago when RAM sizes were significantly
1170 * - it can pick vnodes based on pages used by the vm object, but filesystems
1171 * like ZFS don't use it making the pick broken
1172 * - since ZFS has its own aging policy it gets partially combated by this one
1173 * - a dedicated method should be provided for filesystems to let them decide
1174 * whether the vnode should be recycled
1176 * This routine is called when we have too many vnodes. It attempts
1177 * to free <count> vnodes and will potentially free vnodes that still
1178 * have VM backing store (VM backing store is typically the cause
1179 * of a vnode blowout so we want to do this). Therefore, this operation
1180 * is not considered cheap.
1182 * A number of conditions may prevent a vnode from being reclaimed.
1183 * the buffer cache may have references on the vnode, a directory
1184 * vnode may still have references due to the namei cache representing
1185 * underlying files, or the vnode may be in active use. It is not
1186 * desirable to reuse such vnodes. These conditions may cause the
1187 * number of vnodes to reach some minimum value regardless of what
1188 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
1190 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1191 * entries if this argument is strue
1192 * @param trigger Only reclaim vnodes with fewer than this many resident
1194 * @param target How many vnodes to reclaim.
1195 * @return The number of vnodes that were reclaimed.
1198 vlrureclaim(bool reclaim_nc_src, int trigger, u_long target)
1200 struct vnode *vp, *mvp;
1202 struct vm_object *object;
1206 mtx_assert(&vnode_list_mtx, MA_OWNED);
1211 mvp = vnode_list_reclaim_marker;
1214 while (done < target) {
1215 vp = TAILQ_NEXT(vp, v_vnodelist);
1216 if (__predict_false(vp == NULL))
1219 if (__predict_false(vp->v_type == VMARKER))
1223 * If it's been deconstructed already, it's still
1224 * referenced, or it exceeds the trigger, skip it.
1225 * Also skip free vnodes. We are trying to make space
1226 * for more free vnodes, not reduce their count.
1228 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1229 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)))
1232 if (vp->v_type == VBAD || vp->v_type == VNON)
1235 object = atomic_load_ptr(&vp->v_object);
1236 if (object == NULL || object->resident_page_count > trigger) {
1241 * Handle races against vnode allocation. Filesystems lock the
1242 * vnode some time after it gets returned from getnewvnode,
1243 * despite type and hold count being manipulated earlier.
1244 * Resorting to checking v_mount restores guarantees present
1245 * before the global list was reworked to contain all vnodes.
1247 if (!VI_TRYLOCK(vp))
1249 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1253 if (vp->v_mount == NULL) {
1259 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1260 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1261 mtx_unlock(&vnode_list_mtx);
1263 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1265 goto next_iter_unlocked;
1267 if (VOP_LOCK(vp, LK_EXCLUSIVE|LK_NOWAIT) != 0) {
1269 vn_finished_write(mp);
1270 goto next_iter_unlocked;
1274 if (vp->v_usecount > 0 ||
1275 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1276 (vp->v_object != NULL && vp->v_object->handle == vp &&
1277 vp->v_object->resident_page_count > trigger)) {
1280 vn_finished_write(mp);
1281 goto next_iter_unlocked;
1287 vn_finished_write(mp);
1291 mtx_lock(&vnode_list_mtx);
1294 MPASS(vp->v_type != VMARKER);
1295 if (!should_yield())
1297 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1298 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1299 mtx_unlock(&vnode_list_mtx);
1300 kern_yield(PRI_USER);
1301 mtx_lock(&vnode_list_mtx);
1304 if (done == 0 && !retried) {
1305 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1306 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1313 static int max_free_per_call = 10000;
1314 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_free_per_call, 0,
1315 "limit on vnode free requests per call to the vnlru_free routine (legacy)");
1316 SYSCTL_INT(_vfs_vnode_vnlru, OID_AUTO, max_free_per_call, CTLFLAG_RW,
1317 &max_free_per_call, 0,
1318 "limit on vnode free requests per call to the vnlru_free routine");
1321 * Attempt to recycle requested amount of free vnodes.
1324 vnlru_free_impl(int count, struct vfsops *mnt_op, struct vnode *mvp, bool isvnlru)
1331 mtx_assert(&vnode_list_mtx, MA_OWNED);
1332 if (count > max_free_per_call)
1333 count = max_free_per_call;
1335 mtx_unlock(&vnode_list_mtx);
1342 vp = TAILQ_NEXT(vp, v_vnodelist);
1343 if (__predict_false(vp == NULL)) {
1345 * The free vnode marker can be past eligible vnodes:
1346 * 1. if vdbatch_process trylock failed
1347 * 2. if vtryrecycle failed
1349 * If so, start the scan from scratch.
1351 if (!retried && vnlru_read_freevnodes() > 0) {
1352 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1353 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1362 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1363 TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1364 mtx_unlock(&vnode_list_mtx);
1367 if (__predict_false(vp->v_type == VMARKER))
1369 if (vp->v_holdcnt > 0)
1372 * Don't recycle if our vnode is from different type
1373 * of mount point. Note that mp is type-safe, the
1374 * check does not reach unmapped address even if
1375 * vnode is reclaimed.
1377 if (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1378 mp->mnt_op != mnt_op) {
1381 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1384 if (!vhold_recycle_free(vp))
1386 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1387 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1388 mtx_unlock(&vnode_list_mtx);
1390 * FIXME: ignores the return value, meaning it may be nothing
1391 * got recycled but it claims otherwise to the caller.
1393 * Originally the value started being ignored in 2005 with
1394 * 114a1006a8204aa156e1f9ad6476cdff89cada7f .
1396 * Respecting the value can run into significant stalls if most
1397 * vnodes belong to one file system and it has writes
1398 * suspended. In presence of many threads and millions of
1399 * vnodes they keep contending on the vnode_list_mtx lock only
1400 * to find vnodes they can't recycle.
1402 * The solution would be to pre-check if the vnode is likely to
1403 * be recycle-able, but it needs to happen with the
1404 * vnode_list_mtx lock held. This runs into a problem where
1405 * VOP_GETWRITEMOUNT (currently needed to find out about if
1406 * writes are frozen) can take locks which LOR against it.
1408 * Check nullfs for one example (null_getwritemount).
1410 vtryrecycle(vp, isvnlru);
1415 mtx_lock(&vnode_list_mtx);
1418 mtx_assert(&vnode_list_mtx, MA_NOTOWNED);
1419 return (ocount - count);
1423 * XXX: returns without vnode_list_mtx locked!
1426 vnlru_free_locked_direct(int count)
1430 mtx_assert(&vnode_list_mtx, MA_OWNED);
1431 ret = vnlru_free_impl(count, NULL, vnode_list_free_marker, false);
1432 mtx_assert(&vnode_list_mtx, MA_NOTOWNED);
1437 vnlru_free_locked_vnlru(int count)
1441 mtx_assert(&vnode_list_mtx, MA_OWNED);
1442 ret = vnlru_free_impl(count, NULL, vnode_list_free_marker, true);
1443 mtx_assert(&vnode_list_mtx, MA_NOTOWNED);
1448 vnlru_free_vnlru(int count)
1451 mtx_lock(&vnode_list_mtx);
1452 return (vnlru_free_locked_vnlru(count));
1456 vnlru_free_vfsops(int count, struct vfsops *mnt_op, struct vnode *mvp)
1459 MPASS(mnt_op != NULL);
1461 VNPASS(mvp->v_type == VMARKER, mvp);
1462 mtx_lock(&vnode_list_mtx);
1463 vnlru_free_impl(count, mnt_op, mvp, true);
1464 mtx_assert(&vnode_list_mtx, MA_NOTOWNED);
1468 vnlru_alloc_marker(void)
1472 mvp = vn_alloc_marker(NULL);
1473 mtx_lock(&vnode_list_mtx);
1474 TAILQ_INSERT_BEFORE(vnode_list_free_marker, mvp, v_vnodelist);
1475 mtx_unlock(&vnode_list_mtx);
1480 vnlru_free_marker(struct vnode *mvp)
1482 mtx_lock(&vnode_list_mtx);
1483 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1484 mtx_unlock(&vnode_list_mtx);
1485 vn_free_marker(mvp);
1492 mtx_assert(&vnode_list_mtx, MA_OWNED);
1493 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1494 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1495 vlowat = vhiwat / 2;
1499 * Attempt to recycle vnodes in a context that is always safe to block.
1500 * Calling vlrurecycle() from the bowels of filesystem code has some
1501 * interesting deadlock problems.
1503 static struct proc *vnlruproc;
1504 static int vnlruproc_sig;
1505 static u_long vnlruproc_kicks;
1507 SYSCTL_ULONG(_vfs_vnode_vnlru, OID_AUTO, kicks, CTLFLAG_RD, &vnlruproc_kicks, 0,
1508 "Number of times vnlru awakened due to vnode shortage");
1510 #define VNLRU_COUNT_SLOP 100
1513 * The main freevnodes counter is only updated when a counter local to CPU
1514 * diverges from 0 by more than VNLRU_FREEVNODES_SLOP. CPUs are conditionally
1515 * walked to compute a more accurate total.
1517 * Note: the actual value at any given moment can still exceed slop, but it
1518 * should not be by significant margin in practice.
1520 #define VNLRU_FREEVNODES_SLOP 126
1522 static void __noinline
1523 vfs_freevnodes_rollup(int8_t *lfreevnodes)
1526 atomic_add_long(&freevnodes, *lfreevnodes);
1531 static __inline void
1532 vfs_freevnodes_inc(void)
1534 int8_t *lfreevnodes;
1537 lfreevnodes = PCPU_PTR(vfs_freevnodes);
1539 if (__predict_false(*lfreevnodes == VNLRU_FREEVNODES_SLOP))
1540 vfs_freevnodes_rollup(lfreevnodes);
1545 static __inline void
1546 vfs_freevnodes_dec(void)
1548 int8_t *lfreevnodes;
1551 lfreevnodes = PCPU_PTR(vfs_freevnodes);
1553 if (__predict_false(*lfreevnodes == -VNLRU_FREEVNODES_SLOP))
1554 vfs_freevnodes_rollup(lfreevnodes);
1560 vnlru_read_freevnodes(void)
1562 long slop, rfreevnodes, rfreevnodes_old;
1565 rfreevnodes = atomic_load_long(&freevnodes);
1566 rfreevnodes_old = atomic_load_long(&freevnodes_old);
1568 if (rfreevnodes > rfreevnodes_old)
1569 slop = rfreevnodes - rfreevnodes_old;
1571 slop = rfreevnodes_old - rfreevnodes;
1572 if (slop < VNLRU_FREEVNODES_SLOP)
1573 return (rfreevnodes >= 0 ? rfreevnodes : 0);
1575 rfreevnodes += cpuid_to_pcpu[cpu]->pc_vfs_freevnodes;
1577 atomic_store_long(&freevnodes_old, rfreevnodes);
1578 return (freevnodes_old >= 0 ? freevnodes_old : 0);
1582 vnlru_under(u_long rnumvnodes, u_long limit)
1584 u_long rfreevnodes, space;
1586 if (__predict_false(rnumvnodes > desiredvnodes))
1589 space = desiredvnodes - rnumvnodes;
1590 if (space < limit) {
1591 rfreevnodes = vnlru_read_freevnodes();
1592 if (rfreevnodes > wantfreevnodes)
1593 space += rfreevnodes - wantfreevnodes;
1595 return (space < limit);
1599 vnlru_kick_locked(void)
1602 mtx_assert(&vnode_list_mtx, MA_OWNED);
1603 if (vnlruproc_sig == 0) {
1611 vnlru_kick_cond(void)
1614 if (vnlru_read_freevnodes() > wantfreevnodes)
1619 mtx_lock(&vnode_list_mtx);
1620 vnlru_kick_locked();
1621 mtx_unlock(&vnode_list_mtx);
1625 vnlru_proc_sleep(void)
1628 if (vnlruproc_sig) {
1630 wakeup(&vnlruproc_sig);
1632 msleep(vnlruproc, &vnode_list_mtx, PVFS|PDROP, "vlruwt", hz);
1636 * A lighter version of the machinery below.
1638 * Tries to reach goals only by recycling free vnodes and does not invoke
1639 * uma_reclaim(UMA_RECLAIM_DRAIN).
1641 * This works around pathological behavior in vnlru in presence of tons of free
1642 * vnodes, but without having to rewrite the machinery at this time. Said
1643 * behavior boils down to continuously trying to reclaim all kinds of vnodes
1644 * (cycling through all levels of "force") when the count is transiently above
1645 * limit. This happens a lot when all vnodes are used up and vn_alloc
1646 * speculatively increments the counter.
1648 * Sample testcase: vnode limit 8388608, 20 separate directory trees each with
1649 * 1 million files in total and 20 find(1) processes stating them in parallel
1650 * (one per each tree).
1652 * On a kernel with only stock machinery this needs anywhere between 60 and 120
1653 * seconds to execute (time varies *wildly* between runs). With the workaround
1654 * it consistently stays around 20 seconds [it got further down with later
1657 * That is to say the entire thing needs a fundamental redesign (most notably
1658 * to accommodate faster recycling), the above only tries to get it ouf the way.
1660 * Return values are:
1661 * -1 -- fallback to regular vnlru loop
1662 * 0 -- do nothing, go to sleep
1663 * >0 -- recycle this many vnodes
1666 vnlru_proc_light_pick(void)
1668 u_long rnumvnodes, rfreevnodes;
1670 if (vstir || vnlruproc_sig == 1)
1673 rnumvnodes = atomic_load_long(&numvnodes);
1674 rfreevnodes = vnlru_read_freevnodes();
1677 * vnode limit might have changed and now we may be at a significant
1678 * excess. Bail if we can't sort it out with free vnodes.
1680 * Due to atomic updates the count can legitimately go above
1681 * the limit for a short period, don't bother doing anything in
1684 if (rnumvnodes > desiredvnodes + VNLRU_COUNT_SLOP + 10) {
1685 if (rnumvnodes - rfreevnodes >= desiredvnodes ||
1686 rfreevnodes <= wantfreevnodes) {
1690 return (rnumvnodes - desiredvnodes);
1694 * Don't try to reach wantfreevnodes target if there are too few vnodes
1697 if (rnumvnodes < wantfreevnodes) {
1701 if (rfreevnodes < wantfreevnodes) {
1709 vnlru_proc_light(void)
1713 mtx_assert(&vnode_list_mtx, MA_NOTOWNED);
1715 freecount = vnlru_proc_light_pick();
1716 if (freecount == -1)
1719 if (freecount != 0) {
1720 vnlru_free_vnlru(freecount);
1723 mtx_lock(&vnode_list_mtx);
1725 mtx_assert(&vnode_list_mtx, MA_NOTOWNED);
1729 static u_long uma_reclaim_calls;
1730 SYSCTL_ULONG(_vfs_vnode_vnlru, OID_AUTO, uma_reclaim_calls, CTLFLAG_RD | CTLFLAG_STATS,
1731 &uma_reclaim_calls, 0, "Number of calls to uma_reclaim");
1736 u_long rnumvnodes, rfreevnodes, target;
1737 unsigned long onumvnodes;
1738 int done, force, trigger, usevnodes;
1739 bool reclaim_nc_src, want_reread;
1741 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1742 SHUTDOWN_PRI_FIRST);
1745 want_reread = false;
1747 kproc_suspend_check(vnlruproc);
1749 if (force == 0 && vnlru_proc_light())
1752 mtx_lock(&vnode_list_mtx);
1753 rnumvnodes = atomic_load_long(&numvnodes);
1756 force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1757 want_reread = false;
1761 * If numvnodes is too large (due to desiredvnodes being
1762 * adjusted using its sysctl, or emergency growth), first
1763 * try to reduce it by discarding free vnodes.
1765 if (rnumvnodes > desiredvnodes + 10) {
1766 vnlru_free_locked_vnlru(rnumvnodes - desiredvnodes);
1767 mtx_lock(&vnode_list_mtx);
1768 rnumvnodes = atomic_load_long(&numvnodes);
1771 * Sleep if the vnode cache is in a good state. This is
1772 * when it is not over-full and has space for about a 4%
1773 * or 9% expansion (by growing its size or inexcessively
1774 * reducing free vnode count). Otherwise, try to reclaim
1775 * space for a 10% expansion.
1777 if (vstir && force == 0) {
1781 if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1785 rfreevnodes = vnlru_read_freevnodes();
1787 onumvnodes = rnumvnodes;
1789 * Calculate parameters for recycling. These are the same
1790 * throughout the loop to give some semblance of fairness.
1791 * The trigger point is to avoid recycling vnodes with lots
1792 * of resident pages. We aren't trying to free memory; we
1793 * are trying to recycle or at least free vnodes.
1795 if (rnumvnodes <= desiredvnodes)
1796 usevnodes = rnumvnodes - rfreevnodes;
1798 usevnodes = rnumvnodes;
1802 * The trigger value is chosen to give a conservatively
1803 * large value to ensure that it alone doesn't prevent
1804 * making progress. The value can easily be so large that
1805 * it is effectively infinite in some congested and
1806 * misconfigured cases, and this is necessary. Normally
1807 * it is about 8 to 100 (pages), which is quite large.
1809 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1811 trigger = vsmalltrigger;
1812 reclaim_nc_src = force >= 3;
1813 target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1814 target = target / 10 + 1;
1815 done = vlrureclaim(reclaim_nc_src, trigger, target);
1816 mtx_unlock(&vnode_list_mtx);
1818 * Total number of vnodes can transiently go slightly above the
1819 * limit (see vn_alloc_hard), no need to call uma_reclaim if
1822 if (onumvnodes + VNLRU_COUNT_SLOP + 1000 > desiredvnodes &&
1823 numvnodes <= desiredvnodes) {
1824 uma_reclaim_calls++;
1825 uma_reclaim(UMA_RECLAIM_DRAIN);
1828 if (force == 0 || force == 1) {
1839 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1842 kern_yield(PRI_USER);
1847 static struct kproc_desc vnlru_kp = {
1852 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1856 * Routines having to do with the management of the vnode table.
1860 * Try to recycle a freed vnode.
1863 vtryrecycle(struct vnode *vp, bool isvnlru)
1867 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1868 VNPASS(vp->v_holdcnt > 0, vp);
1870 * This vnode may found and locked via some other list, if so we
1871 * can't recycle it yet.
1873 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1875 "%s: impossible to recycle, vp %p lock is already held",
1878 return (EWOULDBLOCK);
1881 * Don't recycle if its filesystem is being suspended.
1883 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1886 "%s: impossible to recycle, cannot start the write for %p",
1892 * If we got this far, we need to acquire the interlock and see if
1893 * anyone picked up this vnode from another list. If not, we will
1894 * mark it with DOOMED via vgonel() so that anyone who does find it
1895 * will skip over it.
1898 if (vp->v_usecount) {
1901 vn_finished_write(vnmp);
1903 "%s: impossible to recycle, %p is already referenced",
1907 if (!VN_IS_DOOMED(vp)) {
1909 recycles_free_count++;
1911 counter_u64_add(direct_recycles_free_count, 1);
1916 vn_finished_write(vnmp);
1921 * Allocate a new vnode.
1923 * The operation never returns an error. Returning an error was disabled
1924 * in r145385 (dated 2005) with the following comment:
1926 * XXX Not all VFS_VGET/ffs_vget callers check returns.
1928 * Given the age of this commit (almost 15 years at the time of writing this
1929 * comment) restoring the ability to fail requires a significant audit of
1932 * The routine can try to free a vnode or stall for up to 1 second waiting for
1933 * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1935 static u_long vn_alloc_cyclecount;
1936 static u_long vn_alloc_sleeps;
1938 SYSCTL_ULONG(_vfs_vnode_stats, OID_AUTO, alloc_sleeps, CTLFLAG_RD, &vn_alloc_sleeps, 0,
1939 "Number of times vnode allocation blocked waiting on vnlru");
1941 static struct vnode * __noinline
1942 vn_alloc_hard(struct mount *mp, u_long rnumvnodes, bool bumped)
1947 if (rnumvnodes > desiredvnodes + VNLRU_COUNT_SLOP) {
1948 atomic_subtract_long(&numvnodes, 1);
1953 mtx_lock(&vnode_list_mtx);
1955 if (vn_alloc_cyclecount != 0) {
1956 rnumvnodes = atomic_load_long(&numvnodes);
1957 if (rnumvnodes + 1 < desiredvnodes) {
1958 vn_alloc_cyclecount = 0;
1959 mtx_unlock(&vnode_list_mtx);
1963 rfreevnodes = vnlru_read_freevnodes();
1964 if (rfreevnodes < wantfreevnodes) {
1965 if (vn_alloc_cyclecount++ >= rfreevnodes) {
1966 vn_alloc_cyclecount = 0;
1970 vn_alloc_cyclecount = 0;
1975 * Grow the vnode cache if it will not be above its target max after
1976 * growing. Otherwise, if there is at least one free vnode, try to
1977 * reclaim 1 item from it before growing the cache (possibly above its
1978 * target max if the reclamation failed or is delayed).
1980 if (vnlru_free_locked_direct(1) > 0)
1982 mtx_assert(&vnode_list_mtx, MA_NOTOWNED);
1983 if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1985 * Wait for space for a new vnode.
1988 atomic_subtract_long(&numvnodes, 1);
1991 mtx_lock(&vnode_list_mtx);
1992 vnlru_kick_locked();
1994 msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1995 if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1996 vnlru_read_freevnodes() > 1)
1997 vnlru_free_locked_direct(1);
1999 mtx_unlock(&vnode_list_mtx);
2002 mtx_assert(&vnode_list_mtx, MA_NOTOWNED);
2004 atomic_add_long(&numvnodes, 1);
2006 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
2009 static struct vnode *
2010 vn_alloc(struct mount *mp)
2014 if (__predict_false(vn_alloc_cyclecount != 0))
2015 return (vn_alloc_hard(mp, 0, false));
2016 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
2017 if (__predict_false(vnlru_under(rnumvnodes, vlowat))) {
2018 return (vn_alloc_hard(mp, rnumvnodes, true));
2021 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
2025 vn_free(struct vnode *vp)
2028 atomic_subtract_long(&numvnodes, 1);
2029 uma_zfree_smr(vnode_zone, vp);
2033 * Allocate a new vnode.
2036 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
2041 struct lock_object *lo;
2043 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
2045 KASSERT(vops->registered,
2046 ("%s: not registered vector op %p\n", __func__, vops));
2047 cache_validate_vop_vector(mp, vops);
2050 if (td->td_vp_reserved != NULL) {
2051 vp = td->td_vp_reserved;
2052 td->td_vp_reserved = NULL;
2056 counter_u64_add(vnodes_created, 1);
2058 vn_set_state(vp, VSTATE_UNINITIALIZED);
2061 * Locks are given the generic name "vnode" when created.
2062 * Follow the historic practice of using the filesystem
2063 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
2065 * Locks live in a witness group keyed on their name. Thus,
2066 * when a lock is renamed, it must also move from the witness
2067 * group of its old name to the witness group of its new name.
2069 * The change only needs to be made when the vnode moves
2070 * from one filesystem type to another. We ensure that each
2071 * filesystem use a single static name pointer for its tag so
2072 * that we can compare pointers rather than doing a strcmp().
2074 lo = &vp->v_vnlock->lock_object;
2076 if (lo->lo_name != tag) {
2080 WITNESS_DESTROY(lo);
2081 WITNESS_INIT(lo, tag);
2085 * By default, don't allow shared locks unless filesystems opt-in.
2087 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
2089 * Finalize various vnode identity bits.
2091 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
2092 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
2093 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
2097 v_init_counters(vp);
2099 vp->v_bufobj.bo_ops = &buf_ops_bio;
2101 if (mp == NULL && vops != &dead_vnodeops)
2102 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
2106 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
2107 mac_vnode_associate_singlelabel(mp, vp);
2110 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
2114 * For the filesystems which do not use vfs_hash_insert(),
2115 * still initialize v_hash to have vfs_hash_index() useful.
2116 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
2119 vp->v_hash = (uintptr_t)vp >> vnsz2log;
2126 getnewvnode_reserve(void)
2131 MPASS(td->td_vp_reserved == NULL);
2132 td->td_vp_reserved = vn_alloc(NULL);
2136 getnewvnode_drop_reserve(void)
2141 if (td->td_vp_reserved != NULL) {
2142 vn_free(td->td_vp_reserved);
2143 td->td_vp_reserved = NULL;
2147 static void __noinline
2148 freevnode(struct vnode *vp)
2153 * The vnode has been marked for destruction, so free it.
2155 * The vnode will be returned to the zone where it will
2156 * normally remain until it is needed for another vnode. We
2157 * need to cleanup (or verify that the cleanup has already
2158 * been done) any residual data left from its current use
2159 * so as not to contaminate the freshly allocated vnode.
2161 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
2163 * Paired with vgone.
2165 vn_seqc_write_end_free(vp);
2168 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
2169 VNPASS(vp->v_holdcnt == VHOLD_NO_SMR, vp);
2170 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
2171 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
2172 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
2173 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
2174 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
2175 ("clean blk trie not empty"));
2176 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
2177 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
2178 ("dirty blk trie not empty"));
2179 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
2180 ("Dangling rangelock waiters"));
2181 VNASSERT((vp->v_iflag & (VI_DOINGINACT | VI_OWEINACT)) == 0, vp,
2182 ("Leaked inactivation"));
2184 cache_assert_no_entries(vp);
2187 mac_vnode_destroy(vp);
2189 if (vp->v_pollinfo != NULL) {
2191 * Use LK_NOWAIT to shut up witness about the lock. We may get
2192 * here while having another vnode locked when trying to
2193 * satisfy a lookup and needing to recycle.
2195 VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT);
2196 destroy_vpollinfo(vp->v_pollinfo);
2198 vp->v_pollinfo = NULL;
2200 vp->v_mountedhere = NULL;
2203 vp->v_fifoinfo = NULL;
2211 * Delete from old mount point vnode list, if on one.
2214 delmntque(struct vnode *vp)
2218 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
2224 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
2225 ("bad mount point vnode list size"));
2226 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
2227 mp->mnt_nvnodelistsize--;
2231 * The caller expects the interlock to be still held.
2233 ASSERT_VI_LOCKED(vp, __func__);
2237 insmntque1_int(struct vnode *vp, struct mount *mp, bool dtr)
2240 KASSERT(vp->v_mount == NULL,
2241 ("insmntque: vnode already on per mount vnode list"));
2242 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
2243 if ((mp->mnt_kern_flag & MNTK_UNLOCKED_INSMNTQUE) == 0) {
2244 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
2247 ("%s: can't have MNTK_UNLOCKED_INSMNTQUE and cleanup",
2252 * We acquire the vnode interlock early to ensure that the
2253 * vnode cannot be recycled by another process releasing a
2254 * holdcnt on it before we get it on both the vnode list
2255 * and the active vnode list. The mount mutex protects only
2256 * manipulation of the vnode list and the vnode freelist
2257 * mutex protects only manipulation of the active vnode list.
2258 * Hence the need to hold the vnode interlock throughout.
2262 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
2263 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
2264 mp->mnt_nvnodelistsize == 0)) &&
2265 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
2270 vp->v_op = &dead_vnodeops;
2278 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
2279 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
2280 ("neg mount point vnode list size"));
2281 mp->mnt_nvnodelistsize++;
2288 * Insert into list of vnodes for the new mount point, if available.
2289 * insmntque() reclaims the vnode on insertion failure, insmntque1()
2290 * leaves handling of the vnode to the caller.
2293 insmntque(struct vnode *vp, struct mount *mp)
2295 return (insmntque1_int(vp, mp, true));
2299 insmntque1(struct vnode *vp, struct mount *mp)
2301 return (insmntque1_int(vp, mp, false));
2305 * Flush out and invalidate all buffers associated with a bufobj
2306 * Called with the underlying object locked.
2309 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
2314 if (flags & V_SAVE) {
2315 error = bufobj_wwait(bo, slpflag, slptimeo);
2320 if (bo->bo_dirty.bv_cnt > 0) {
2323 error = BO_SYNC(bo, MNT_WAIT);
2324 } while (error == ERELOOKUP);
2328 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0) {
2335 * If you alter this loop please notice that interlock is dropped and
2336 * reacquired in flushbuflist. Special care is needed to ensure that
2337 * no race conditions occur from this.
2340 error = flushbuflist(&bo->bo_clean,
2341 flags, bo, slpflag, slptimeo);
2342 if (error == 0 && !(flags & V_CLEANONLY))
2343 error = flushbuflist(&bo->bo_dirty,
2344 flags, bo, slpflag, slptimeo);
2345 if (error != 0 && error != EAGAIN) {
2349 } while (error != 0);
2352 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
2353 * have write I/O in-progress but if there is a VM object then the
2354 * VM object can also have read-I/O in-progress.
2357 bufobj_wwait(bo, 0, 0);
2358 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
2360 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
2363 } while (bo->bo_numoutput > 0);
2367 * Destroy the copy in the VM cache, too.
2369 if (bo->bo_object != NULL &&
2370 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
2371 VM_OBJECT_WLOCK(bo->bo_object);
2372 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
2373 OBJPR_CLEANONLY : 0);
2374 VM_OBJECT_WUNLOCK(bo->bo_object);
2379 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
2380 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
2381 bo->bo_clean.bv_cnt > 0))
2382 panic("vinvalbuf: flush failed");
2383 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
2384 bo->bo_dirty.bv_cnt > 0)
2385 panic("vinvalbuf: flush dirty failed");
2392 * Flush out and invalidate all buffers associated with a vnode.
2393 * Called with the underlying object locked.
2396 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
2399 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2400 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
2401 if (vp->v_object != NULL && vp->v_object->handle != vp)
2403 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
2407 * Flush out buffers on the specified list.
2411 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
2414 struct buf *bp, *nbp;
2419 ASSERT_BO_WLOCKED(bo);
2422 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2424 * If we are flushing both V_NORMAL and V_ALT buffers then
2425 * do not skip any buffers. If we are flushing only V_NORMAL
2426 * buffers then skip buffers marked as BX_ALTDATA. If we are
2427 * flushing only V_ALT buffers then skip buffers not marked
2430 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2431 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2432 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2436 lblkno = nbp->b_lblkno;
2437 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2440 error = BUF_TIMELOCK(bp,
2441 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2442 "flushbuf", slpflag, slptimeo);
2445 return (error != ENOLCK ? error : EAGAIN);
2447 KASSERT(bp->b_bufobj == bo,
2448 ("bp %p wrong b_bufobj %p should be %p",
2449 bp, bp->b_bufobj, bo));
2451 * XXX Since there are no node locks for NFS, I
2452 * believe there is a slight chance that a delayed
2453 * write will occur while sleeping just above, so
2456 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2459 bp->b_flags |= B_ASYNC;
2462 return (EAGAIN); /* XXX: why not loop ? */
2465 bp->b_flags |= (B_INVAL | B_RELBUF);
2466 bp->b_flags &= ~B_ASYNC;
2471 nbp = gbincore(bo, lblkno);
2472 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2474 break; /* nbp invalid */
2480 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2486 ASSERT_BO_LOCKED(bo);
2488 for (lblkno = startn;;) {
2490 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2491 if (bp == NULL || bp->b_lblkno >= endn ||
2492 bp->b_lblkno < startn)
2494 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2495 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2498 if (error == ENOLCK)
2502 KASSERT(bp->b_bufobj == bo,
2503 ("bp %p wrong b_bufobj %p should be %p",
2504 bp, bp->b_bufobj, bo));
2505 lblkno = bp->b_lblkno + 1;
2506 if ((bp->b_flags & B_MANAGED) == 0)
2508 bp->b_flags |= B_RELBUF;
2510 * In the VMIO case, use the B_NOREUSE flag to hint that the
2511 * pages backing each buffer in the range are unlikely to be
2512 * reused. Dirty buffers will have the hint applied once
2513 * they've been written.
2515 if ((bp->b_flags & B_VMIO) != 0)
2516 bp->b_flags |= B_NOREUSE;
2524 * Truncate a file's buffer and pages to a specified length. This
2525 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2529 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2531 struct buf *bp, *nbp;
2535 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2536 vp, blksize, (uintmax_t)length);
2539 * Round up to the *next* lbn.
2541 startlbn = howmany(length, blksize);
2543 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2549 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2554 * Write out vnode metadata, e.g. indirect blocks.
2557 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2558 if (bp->b_lblkno >= 0)
2561 * Since we hold the vnode lock this should only
2562 * fail if we're racing with the buf daemon.
2565 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2566 BO_LOCKPTR(bo)) == ENOLCK)
2567 goto restart_unlocked;
2569 VNASSERT((bp->b_flags & B_DELWRI), vp,
2570 ("buf(%p) on dirty queue without DELWRI", bp));
2579 bufobj_wwait(bo, 0, 0);
2581 vnode_pager_setsize(vp, length);
2587 * Invalidate the cached pages of a file's buffer within the range of block
2588 * numbers [startlbn, endlbn).
2591 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2597 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2599 start = blksize * startlbn;
2600 end = blksize * endlbn;
2604 MPASS(blksize == bo->bo_bsize);
2606 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2610 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2614 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2615 daddr_t startlbn, daddr_t endlbn)
2617 struct buf *bp, *nbp;
2620 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2621 ASSERT_BO_LOCKED(bo);
2625 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2626 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2629 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2630 BO_LOCKPTR(bo)) == ENOLCK) {
2636 bp->b_flags |= B_INVAL | B_RELBUF;
2637 bp->b_flags &= ~B_ASYNC;
2643 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2645 (nbp->b_flags & B_DELWRI) != 0))
2649 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2650 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2653 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2654 BO_LOCKPTR(bo)) == ENOLCK) {
2659 bp->b_flags |= B_INVAL | B_RELBUF;
2660 bp->b_flags &= ~B_ASYNC;
2666 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2667 (nbp->b_vp != vp) ||
2668 (nbp->b_flags & B_DELWRI) == 0))
2676 buf_vlist_remove(struct buf *bp)
2681 flags = bp->b_xflags;
2683 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2684 ASSERT_BO_WLOCKED(bp->b_bufobj);
2685 KASSERT((flags & (BX_VNDIRTY | BX_VNCLEAN)) != 0 &&
2686 (flags & (BX_VNDIRTY | BX_VNCLEAN)) != (BX_VNDIRTY | BX_VNCLEAN),
2687 ("%s: buffer %p has invalid queue state", __func__, bp));
2689 if ((flags & BX_VNDIRTY) != 0)
2690 bv = &bp->b_bufobj->bo_dirty;
2692 bv = &bp->b_bufobj->bo_clean;
2693 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2694 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2696 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2700 * Add the buffer to the sorted clean or dirty block list.
2702 * NOTE: xflags is passed as a constant, optimizing this inline function!
2705 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2711 ASSERT_BO_WLOCKED(bo);
2712 KASSERT((bo->bo_flag & BO_NOBUFS) == 0,
2713 ("buf_vlist_add: bo %p does not allow bufs", bo));
2714 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2715 ("dead bo %p", bo));
2716 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2717 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2718 bp->b_xflags |= xflags;
2719 if (xflags & BX_VNDIRTY)
2725 * Keep the list ordered. Optimize empty list insertion. Assume
2726 * we tend to grow at the tail so lookup_le should usually be cheaper
2729 if (bv->bv_cnt == 0 ||
2730 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2731 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2732 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2733 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2735 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2736 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2738 panic("buf_vlist_add: Preallocated nodes insufficient.");
2743 * Look up a buffer using the buffer tries.
2746 gbincore(struct bufobj *bo, daddr_t lblkno)
2750 ASSERT_BO_LOCKED(bo);
2751 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2754 return (BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno));
2758 * Look up a buf using the buffer tries, without the bufobj lock. This relies
2759 * on SMR for safe lookup, and bufs being in a no-free zone to provide type
2760 * stability of the result. Like other lockless lookups, the found buf may
2761 * already be invalid by the time this function returns.
2764 gbincore_unlocked(struct bufobj *bo, daddr_t lblkno)
2768 ASSERT_BO_UNLOCKED(bo);
2769 bp = BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_clean.bv_root, lblkno);
2772 return (BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_dirty.bv_root, lblkno));
2776 * Associate a buffer with a vnode.
2779 bgetvp(struct vnode *vp, struct buf *bp)
2784 ASSERT_BO_WLOCKED(bo);
2785 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2787 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2788 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2789 ("bgetvp: bp already attached! %p", bp));
2795 * Insert onto list for new vnode.
2797 buf_vlist_add(bp, bo, BX_VNCLEAN);
2801 * Disassociate a buffer from a vnode.
2804 brelvp(struct buf *bp)
2809 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2810 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2813 * Delete from old vnode list, if on one.
2815 vp = bp->b_vp; /* XXX */
2818 buf_vlist_remove(bp);
2819 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2820 bo->bo_flag &= ~BO_ONWORKLST;
2821 mtx_lock(&sync_mtx);
2822 LIST_REMOVE(bo, bo_synclist);
2823 syncer_worklist_len--;
2824 mtx_unlock(&sync_mtx);
2827 bp->b_bufobj = NULL;
2833 * Add an item to the syncer work queue.
2836 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2840 ASSERT_BO_WLOCKED(bo);
2842 mtx_lock(&sync_mtx);
2843 if (bo->bo_flag & BO_ONWORKLST)
2844 LIST_REMOVE(bo, bo_synclist);
2846 bo->bo_flag |= BO_ONWORKLST;
2847 syncer_worklist_len++;
2850 if (delay > syncer_maxdelay - 2)
2851 delay = syncer_maxdelay - 2;
2852 slot = (syncer_delayno + delay) & syncer_mask;
2854 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2855 mtx_unlock(&sync_mtx);
2859 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2863 mtx_lock(&sync_mtx);
2864 len = syncer_worklist_len - sync_vnode_count;
2865 mtx_unlock(&sync_mtx);
2866 error = SYSCTL_OUT(req, &len, sizeof(len));
2870 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2871 CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2872 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2874 static struct proc *updateproc;
2875 static void sched_sync(void);
2876 static struct kproc_desc up_kp = {
2881 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2884 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2889 *bo = LIST_FIRST(slp);
2893 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2896 * We use vhold in case the vnode does not
2897 * successfully sync. vhold prevents the vnode from
2898 * going away when we unlock the sync_mtx so that
2899 * we can acquire the vnode interlock.
2902 mtx_unlock(&sync_mtx);
2904 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2906 mtx_lock(&sync_mtx);
2907 return (*bo == LIST_FIRST(slp));
2909 MPASSERT(mp == NULL || (curthread->td_pflags & TDP_IGNSUSP) != 0 ||
2910 (mp->mnt_kern_flag & MNTK_SUSPENDED) == 0, mp,
2911 ("suspended mp syncing vp %p", vp));
2912 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2913 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2915 vn_finished_write(mp);
2917 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2919 * Put us back on the worklist. The worklist
2920 * routine will remove us from our current
2921 * position and then add us back in at a later
2924 vn_syncer_add_to_worklist(*bo, syncdelay);
2928 mtx_lock(&sync_mtx);
2932 static int first_printf = 1;
2935 * System filesystem synchronizer daemon.
2940 struct synclist *next, *slp;
2943 struct thread *td = curthread;
2945 int net_worklist_len;
2946 int syncer_final_iter;
2950 syncer_final_iter = 0;
2951 syncer_state = SYNCER_RUNNING;
2952 starttime = time_uptime;
2953 td->td_pflags |= TDP_NORUNNINGBUF;
2955 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2958 mtx_lock(&sync_mtx);
2960 if (syncer_state == SYNCER_FINAL_DELAY &&
2961 syncer_final_iter == 0) {
2962 mtx_unlock(&sync_mtx);
2963 kproc_suspend_check(td->td_proc);
2964 mtx_lock(&sync_mtx);
2966 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2967 if (syncer_state != SYNCER_RUNNING &&
2968 starttime != time_uptime) {
2970 printf("\nSyncing disks, vnodes remaining... ");
2973 printf("%d ", net_worklist_len);
2975 starttime = time_uptime;
2978 * Push files whose dirty time has expired. Be careful
2979 * of interrupt race on slp queue.
2981 * Skip over empty worklist slots when shutting down.
2984 slp = &syncer_workitem_pending[syncer_delayno];
2985 syncer_delayno += 1;
2986 if (syncer_delayno == syncer_maxdelay)
2988 next = &syncer_workitem_pending[syncer_delayno];
2990 * If the worklist has wrapped since the
2991 * it was emptied of all but syncer vnodes,
2992 * switch to the FINAL_DELAY state and run
2993 * for one more second.
2995 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2996 net_worklist_len == 0 &&
2997 last_work_seen == syncer_delayno) {
2998 syncer_state = SYNCER_FINAL_DELAY;
2999 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
3001 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
3002 syncer_worklist_len > 0);
3005 * Keep track of the last time there was anything
3006 * on the worklist other than syncer vnodes.
3007 * Return to the SHUTTING_DOWN state if any
3010 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
3011 last_work_seen = syncer_delayno;
3012 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
3013 syncer_state = SYNCER_SHUTTING_DOWN;
3014 while (!LIST_EMPTY(slp)) {
3015 error = sync_vnode(slp, &bo, td);
3017 LIST_REMOVE(bo, bo_synclist);
3018 LIST_INSERT_HEAD(next, bo, bo_synclist);
3022 if (first_printf == 0) {
3024 * Drop the sync mutex, because some watchdog
3025 * drivers need to sleep while patting
3027 mtx_unlock(&sync_mtx);
3028 wdog_kern_pat(WD_LASTVAL);
3029 mtx_lock(&sync_mtx);
3032 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
3033 syncer_final_iter--;
3035 * The variable rushjob allows the kernel to speed up the
3036 * processing of the filesystem syncer process. A rushjob
3037 * value of N tells the filesystem syncer to process the next
3038 * N seconds worth of work on its queue ASAP. Currently rushjob
3039 * is used by the soft update code to speed up the filesystem
3040 * syncer process when the incore state is getting so far
3041 * ahead of the disk that the kernel memory pool is being
3042 * threatened with exhaustion.
3049 * Just sleep for a short period of time between
3050 * iterations when shutting down to allow some I/O
3053 * If it has taken us less than a second to process the
3054 * current work, then wait. Otherwise start right over
3055 * again. We can still lose time if any single round
3056 * takes more than two seconds, but it does not really
3057 * matter as we are just trying to generally pace the
3058 * filesystem activity.
3060 if (syncer_state != SYNCER_RUNNING ||
3061 time_uptime == starttime) {
3063 sched_prio(td, PPAUSE);
3066 if (syncer_state != SYNCER_RUNNING)
3067 cv_timedwait(&sync_wakeup, &sync_mtx,
3068 hz / SYNCER_SHUTDOWN_SPEEDUP);
3069 else if (time_uptime == starttime)
3070 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
3075 * Request the syncer daemon to speed up its work.
3076 * We never push it to speed up more than half of its
3077 * normal turn time, otherwise it could take over the cpu.
3080 speedup_syncer(void)
3084 mtx_lock(&sync_mtx);
3085 if (rushjob < syncdelay / 2) {
3087 stat_rush_requests += 1;
3090 mtx_unlock(&sync_mtx);
3091 cv_broadcast(&sync_wakeup);
3096 * Tell the syncer to speed up its work and run though its work
3097 * list several times, then tell it to shut down.
3100 syncer_shutdown(void *arg, int howto)
3103 if (howto & RB_NOSYNC)
3105 mtx_lock(&sync_mtx);
3106 syncer_state = SYNCER_SHUTTING_DOWN;
3108 mtx_unlock(&sync_mtx);
3109 cv_broadcast(&sync_wakeup);
3110 kproc_shutdown(arg, howto);
3114 syncer_suspend(void)
3117 syncer_shutdown(updateproc, 0);
3124 mtx_lock(&sync_mtx);
3126 syncer_state = SYNCER_RUNNING;
3127 mtx_unlock(&sync_mtx);
3128 cv_broadcast(&sync_wakeup);
3129 kproc_resume(updateproc);
3133 * Move the buffer between the clean and dirty lists of its vnode.
3136 reassignbuf(struct buf *bp)
3148 KASSERT((bp->b_flags & B_PAGING) == 0,
3149 ("%s: cannot reassign paging buffer %p", __func__, bp));
3151 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
3152 bp, bp->b_vp, bp->b_flags);
3155 buf_vlist_remove(bp);
3158 * If dirty, put on list of dirty buffers; otherwise insert onto list
3161 if (bp->b_flags & B_DELWRI) {
3162 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
3163 switch (vp->v_type) {
3173 vn_syncer_add_to_worklist(bo, delay);
3175 buf_vlist_add(bp, bo, BX_VNDIRTY);
3177 buf_vlist_add(bp, bo, BX_VNCLEAN);
3179 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
3180 mtx_lock(&sync_mtx);
3181 LIST_REMOVE(bo, bo_synclist);
3182 syncer_worklist_len--;
3183 mtx_unlock(&sync_mtx);
3184 bo->bo_flag &= ~BO_ONWORKLST;
3189 bp = TAILQ_FIRST(&bv->bv_hd);
3190 KASSERT(bp == NULL || bp->b_bufobj == bo,
3191 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3192 bp = TAILQ_LAST(&bv->bv_hd, buflists);
3193 KASSERT(bp == NULL || bp->b_bufobj == bo,
3194 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3196 bp = TAILQ_FIRST(&bv->bv_hd);
3197 KASSERT(bp == NULL || bp->b_bufobj == bo,
3198 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3199 bp = TAILQ_LAST(&bv->bv_hd, buflists);
3200 KASSERT(bp == NULL || bp->b_bufobj == bo,
3201 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3207 v_init_counters(struct vnode *vp)
3210 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
3211 vp, ("%s called for an initialized vnode", __FUNCTION__));
3212 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
3214 refcount_init(&vp->v_holdcnt, 1);
3215 refcount_init(&vp->v_usecount, 1);
3219 * Get a usecount on a vnode.
3221 * vget and vget_finish may fail to lock the vnode if they lose a race against
3222 * it being doomed. LK_RETRY can be passed in flags to lock it anyway.
3224 * Consumers which don't guarantee liveness of the vnode can use SMR to
3225 * try to get a reference. Note this operation can fail since the vnode
3226 * may be awaiting getting freed by the time they get to it.
3229 vget_prep_smr(struct vnode *vp)
3233 VFS_SMR_ASSERT_ENTERED();
3235 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3247 vget_prep(struct vnode *vp)
3251 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3261 vget_abort(struct vnode *vp, enum vgetstate vs)
3272 __assert_unreachable();
3277 vget(struct vnode *vp, int flags)
3282 return (vget_finish(vp, flags, vs));
3286 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
3290 if ((flags & LK_INTERLOCK) != 0)
3291 ASSERT_VI_LOCKED(vp, __func__);
3293 ASSERT_VI_UNLOCKED(vp, __func__);
3294 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3295 VNPASS(vp->v_holdcnt > 0, vp);
3296 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3298 error = vn_lock(vp, flags);
3299 if (__predict_false(error != 0)) {
3301 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
3306 vget_finish_ref(vp, vs);
3311 vget_finish_ref(struct vnode *vp, enum vgetstate vs)
3315 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3316 VNPASS(vp->v_holdcnt > 0, vp);
3317 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3319 if (vs == VGET_USECOUNT)
3323 * We hold the vnode. If the usecount is 0 it will be utilized to keep
3324 * the vnode around. Otherwise someone else lended their hold count and
3325 * we have to drop ours.
3327 old = atomic_fetchadd_int(&vp->v_usecount, 1);
3328 VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
3331 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
3332 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
3334 refcount_release(&vp->v_holdcnt);
3340 vref(struct vnode *vp)
3344 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3346 vget_finish_ref(vp, vs);
3350 vrefact(struct vnode *vp)
3354 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3355 old = refcount_acquire(&vp->v_usecount);
3356 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3360 vlazy(struct vnode *vp)
3364 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
3366 if ((vp->v_mflag & VMP_LAZYLIST) != 0)
3369 * We may get here for inactive routines after the vnode got doomed.
3371 if (VN_IS_DOOMED(vp))
3374 mtx_lock(&mp->mnt_listmtx);
3375 if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
3376 vp->v_mflag |= VMP_LAZYLIST;
3377 TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3378 mp->mnt_lazyvnodelistsize++;
3380 mtx_unlock(&mp->mnt_listmtx);
3384 vunlazy(struct vnode *vp)
3388 ASSERT_VI_LOCKED(vp, __func__);
3389 VNPASS(!VN_IS_DOOMED(vp), vp);
3392 mtx_lock(&mp->mnt_listmtx);
3393 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3395 * Don't remove the vnode from the lazy list if another thread
3396 * has increased the hold count. It may have re-enqueued the
3397 * vnode to the lazy list and is now responsible for its
3400 if (vp->v_holdcnt == 0) {
3401 vp->v_mflag &= ~VMP_LAZYLIST;
3402 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3403 mp->mnt_lazyvnodelistsize--;
3405 mtx_unlock(&mp->mnt_listmtx);
3409 * This routine is only meant to be called from vgonel prior to dooming
3413 vunlazy_gone(struct vnode *vp)
3417 ASSERT_VOP_ELOCKED(vp, __func__);
3418 ASSERT_VI_LOCKED(vp, __func__);
3419 VNPASS(!VN_IS_DOOMED(vp), vp);
3421 if (vp->v_mflag & VMP_LAZYLIST) {
3423 mtx_lock(&mp->mnt_listmtx);
3424 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3425 vp->v_mflag &= ~VMP_LAZYLIST;
3426 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3427 mp->mnt_lazyvnodelistsize--;
3428 mtx_unlock(&mp->mnt_listmtx);
3433 vdefer_inactive(struct vnode *vp)
3436 ASSERT_VI_LOCKED(vp, __func__);
3437 VNPASS(vp->v_holdcnt > 0, vp);
3438 if (VN_IS_DOOMED(vp)) {
3442 if (vp->v_iflag & VI_DEFINACT) {
3443 VNPASS(vp->v_holdcnt > 1, vp);
3447 if (vp->v_usecount > 0) {
3448 vp->v_iflag &= ~VI_OWEINACT;
3453 vp->v_iflag |= VI_DEFINACT;
3455 atomic_add_long(&deferred_inact, 1);
3459 vdefer_inactive_unlocked(struct vnode *vp)
3463 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3467 vdefer_inactive(vp);
3470 enum vput_op { VRELE, VPUT, VUNREF };
3473 * Handle ->v_usecount transitioning to 0.
3475 * By releasing the last usecount we take ownership of the hold count which
3476 * provides liveness of the vnode, meaning we have to vdrop.
3478 * For all vnodes we may need to perform inactive processing. It requires an
3479 * exclusive lock on the vnode, while it is legal to call here with only a
3480 * shared lock (or no locks). If locking the vnode in an expected manner fails,
3481 * inactive processing gets deferred to the syncer.
3483 * XXX Some filesystems pass in an exclusively locked vnode and strongly depend
3484 * on the lock being held all the way until VOP_INACTIVE. This in particular
3485 * happens with UFS which adds half-constructed vnodes to the hash, where they
3486 * can be found by other code.
3489 vput_final(struct vnode *vp, enum vput_op func)
3494 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3495 VNPASS(vp->v_holdcnt > 0, vp);
3500 * By the time we got here someone else might have transitioned
3501 * the count back to > 0.
3503 if (vp->v_usecount > 0)
3507 * If the vnode is doomed vgone already performed inactive processing
3510 if (VN_IS_DOOMED(vp))
3513 if (__predict_true(VOP_NEED_INACTIVE(vp) == 0))
3516 if (vp->v_iflag & VI_DOINGINACT)
3520 * Locking operations here will drop the interlock and possibly the
3521 * vnode lock, opening a window where the vnode can get doomed all the
3522 * while ->v_usecount is 0. Set VI_OWEINACT to let vgone know to
3525 vp->v_iflag |= VI_OWEINACT;
3526 want_unlock = false;
3530 switch (VOP_ISLOCKED(vp)) {
3536 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3541 * The lock has at least one sharer, but we have no way
3542 * to conclude whether this is us. Play it safe and
3551 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3552 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3558 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3559 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3565 if (func == VUNREF) {
3566 VNASSERT((vp->v_vflag & VV_UNREF) == 0, vp,
3567 ("recursive vunref"));
3568 vp->v_vflag |= VV_UNREF;
3571 error = vinactive(vp);
3574 if (error != ERELOOKUP || !want_unlock)
3576 VOP_LOCK(vp, LK_EXCLUSIVE);
3579 vp->v_vflag &= ~VV_UNREF;
3582 vdefer_inactive(vp);
3592 * Decrement ->v_usecount for a vnode.
3594 * Releasing the last use count requires additional processing, see vput_final
3595 * above for details.
3597 * Comment above each variant denotes lock state on entry and exit.
3602 * out: same as passed in
3605 vrele(struct vnode *vp)
3608 ASSERT_VI_UNLOCKED(vp, __func__);
3609 if (!refcount_release(&vp->v_usecount))
3611 vput_final(vp, VRELE);
3619 vput(struct vnode *vp)
3622 ASSERT_VOP_LOCKED(vp, __func__);
3623 ASSERT_VI_UNLOCKED(vp, __func__);
3624 if (!refcount_release(&vp->v_usecount)) {
3628 vput_final(vp, VPUT);
3636 vunref(struct vnode *vp)
3639 ASSERT_VOP_LOCKED(vp, __func__);
3640 ASSERT_VI_UNLOCKED(vp, __func__);
3641 if (!refcount_release(&vp->v_usecount))
3643 vput_final(vp, VUNREF);
3647 vhold(struct vnode *vp)
3651 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3652 old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3653 VNASSERT(old >= 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3654 ("%s: wrong hold count %d", __func__, old));
3656 vfs_freevnodes_dec();
3660 vholdnz(struct vnode *vp)
3663 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3665 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3666 VNASSERT(old > 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3667 ("%s: wrong hold count %d", __func__, old));
3669 atomic_add_int(&vp->v_holdcnt, 1);
3674 * Grab a hold count unless the vnode is freed.
3676 * Only use this routine if vfs smr is the only protection you have against
3677 * freeing the vnode.
3679 * The code loops trying to add a hold count as long as the VHOLD_NO_SMR flag
3680 * is not set. After the flag is set the vnode becomes immutable to anyone but
3681 * the thread which managed to set the flag.
3683 * It may be tempting to replace the loop with:
3684 * count = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3685 * if (count & VHOLD_NO_SMR) {
3686 * backpedal and error out;
3689 * However, while this is more performant, it hinders debugging by eliminating
3690 * the previously mentioned invariant.
3693 vhold_smr(struct vnode *vp)
3697 VFS_SMR_ASSERT_ENTERED();
3699 count = atomic_load_int(&vp->v_holdcnt);
3701 if (count & VHOLD_NO_SMR) {
3702 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3703 ("non-zero hold count with flags %d\n", count));
3706 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3707 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3709 vfs_freevnodes_dec();
3716 * Hold a free vnode for recycling.
3718 * Note: vnode_init references this comment.
3720 * Attempts to recycle only need the global vnode list lock and have no use for
3723 * However, vnodes get inserted into the global list before they get fully
3724 * initialized and stay there until UMA decides to free the memory. This in
3725 * particular means the target can be found before it becomes usable and after
3726 * it becomes recycled. Picking up such vnodes is guarded with v_holdcnt set to
3729 * Note: the vnode may gain more references after we transition the count 0->1.
3732 vhold_recycle_free(struct vnode *vp)
3736 mtx_assert(&vnode_list_mtx, MA_OWNED);
3738 count = atomic_load_int(&vp->v_holdcnt);
3740 if (count & VHOLD_NO_SMR) {
3741 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3742 ("non-zero hold count with flags %d\n", count));
3745 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3749 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3750 vfs_freevnodes_dec();
3756 static void __noinline
3757 vdbatch_process(struct vdbatch *vd)
3762 mtx_assert(&vd->lock, MA_OWNED);
3763 MPASS(curthread->td_pinned > 0);
3764 MPASS(vd->index == VDBATCH_SIZE);
3767 * Attempt to requeue the passed batch, but give up easily.
3769 * Despite batching the mechanism is prone to transient *significant*
3770 * lock contention, where vnode_list_mtx becomes the primary bottleneck
3771 * if multiple CPUs get here (one real-world example is highly parallel
3772 * do-nothing make , which will stat *tons* of vnodes). Since it is
3773 * quasi-LRU (read: not that great even if fully honoured) just dodge
3774 * the problem. Parties which don't like it are welcome to implement
3778 if (mtx_trylock(&vnode_list_mtx)) {
3779 for (i = 0; i < VDBATCH_SIZE; i++) {
3782 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3783 TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3784 MPASS(vp->v_dbatchcpu != NOCPU);
3785 vp->v_dbatchcpu = NOCPU;
3787 mtx_unlock(&vnode_list_mtx);
3789 counter_u64_add(vnode_skipped_requeues, 1);
3791 for (i = 0; i < VDBATCH_SIZE; i++) {
3794 MPASS(vp->v_dbatchcpu != NOCPU);
3795 vp->v_dbatchcpu = NOCPU;
3803 vdbatch_enqueue(struct vnode *vp)
3807 ASSERT_VI_LOCKED(vp, __func__);
3808 VNPASS(!VN_IS_DOOMED(vp), vp);
3810 if (vp->v_dbatchcpu != NOCPU) {
3817 mtx_lock(&vd->lock);
3818 MPASS(vd->index < VDBATCH_SIZE);
3819 MPASS(vd->tab[vd->index] == NULL);
3821 * A hack: we depend on being pinned so that we know what to put in
3824 vp->v_dbatchcpu = curcpu;
3825 vd->tab[vd->index] = vp;
3828 if (vd->index == VDBATCH_SIZE)
3829 vdbatch_process(vd);
3830 mtx_unlock(&vd->lock);
3835 * This routine must only be called for vnodes which are about to be
3836 * deallocated. Supporting dequeue for arbitrary vndoes would require
3837 * validating that the locked batch matches.
3840 vdbatch_dequeue(struct vnode *vp)
3846 VNPASS(vp->v_type == VBAD || vp->v_type == VNON, vp);
3848 cpu = vp->v_dbatchcpu;
3852 vd = DPCPU_ID_PTR(cpu, vd);
3853 mtx_lock(&vd->lock);
3854 for (i = 0; i < vd->index; i++) {
3855 if (vd->tab[i] != vp)
3857 vp->v_dbatchcpu = NOCPU;
3859 vd->tab[i] = vd->tab[vd->index];
3860 vd->tab[vd->index] = NULL;
3863 mtx_unlock(&vd->lock);
3865 * Either we dequeued the vnode above or the target CPU beat us to it.
3867 MPASS(vp->v_dbatchcpu == NOCPU);
3871 * Drop the hold count of the vnode.
3873 * It will only get freed if this is the last hold *and* it has been vgone'd.
3875 * Because the vnode vm object keeps a hold reference on the vnode if
3876 * there is at least one resident non-cached page, the vnode cannot
3877 * leave the active list without the page cleanup done.
3879 static void __noinline
3880 vdropl_final(struct vnode *vp)
3883 ASSERT_VI_LOCKED(vp, __func__);
3884 VNPASS(VN_IS_DOOMED(vp), vp);
3886 * Set the VHOLD_NO_SMR flag.
3888 * We may be racing against vhold_smr. If they win we can just pretend
3889 * we never got this far, they will vdrop later.
3891 if (__predict_false(!atomic_cmpset_int(&vp->v_holdcnt, 0, VHOLD_NO_SMR))) {
3892 vfs_freevnodes_inc();
3895 * We lost the aforementioned race. Any subsequent access is
3896 * invalid as they might have managed to vdropl on their own.
3901 * Don't bump freevnodes as this one is going away.
3907 vdrop(struct vnode *vp)
3910 ASSERT_VI_UNLOCKED(vp, __func__);
3911 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3912 if (refcount_release_if_not_last(&vp->v_holdcnt))
3918 static void __always_inline
3919 vdropl_impl(struct vnode *vp, bool enqueue)
3922 ASSERT_VI_LOCKED(vp, __func__);
3923 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3924 if (!refcount_release(&vp->v_holdcnt)) {
3928 VNPASS((vp->v_iflag & VI_OWEINACT) == 0, vp);
3929 VNPASS((vp->v_iflag & VI_DEFINACT) == 0, vp);
3930 if (VN_IS_DOOMED(vp)) {
3935 vfs_freevnodes_inc();
3936 if (vp->v_mflag & VMP_LAZYLIST) {
3946 * Also unlocks the interlock. We can't assert on it as we
3947 * released our hold and by now the vnode might have been
3950 vdbatch_enqueue(vp);
3954 vdropl(struct vnode *vp)
3957 vdropl_impl(vp, true);
3961 * vdrop a vnode when recycling
3963 * This is a special case routine only to be used when recycling, differs from
3964 * regular vdrop by not requeieing the vnode on LRU.
3966 * Consider a case where vtryrecycle continuously fails with all vnodes (due to
3967 * e.g., frozen writes on the filesystem), filling the batch and causing it to
3968 * be requeued. Then vnlru will end up revisiting the same vnodes. This is a
3969 * loop which can last for as long as writes are frozen.
3972 vdropl_recycle(struct vnode *vp)
3975 vdropl_impl(vp, false);
3979 vdrop_recycle(struct vnode *vp)
3987 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3988 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3991 vinactivef(struct vnode *vp)
3995 ASSERT_VOP_ELOCKED(vp, "vinactive");
3996 ASSERT_VI_LOCKED(vp, "vinactive");
3997 VNPASS((vp->v_iflag & VI_DOINGINACT) == 0, vp);
3998 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3999 vp->v_iflag |= VI_DOINGINACT;
4000 vp->v_iflag &= ~VI_OWEINACT;
4004 * Before moving off the active list, we must be sure that any
4005 * modified pages are converted into the vnode's dirty
4006 * buffers, since these will no longer be checked once the
4007 * vnode is on the inactive list.
4009 * The write-out of the dirty pages is asynchronous. At the
4010 * point that VOP_INACTIVE() is called, there could still be
4011 * pending I/O and dirty pages in the object.
4013 if ((vp->v_vflag & VV_NOSYNC) == 0)
4014 vnode_pager_clean_async(vp);
4016 error = VOP_INACTIVE(vp);
4018 VNPASS(vp->v_iflag & VI_DOINGINACT, vp);
4019 vp->v_iflag &= ~VI_DOINGINACT;
4024 vinactive(struct vnode *vp)
4027 ASSERT_VOP_ELOCKED(vp, "vinactive");
4028 ASSERT_VI_LOCKED(vp, "vinactive");
4029 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
4031 if ((vp->v_iflag & VI_OWEINACT) == 0)
4033 if (vp->v_iflag & VI_DOINGINACT)
4035 if (vp->v_usecount > 0) {
4036 vp->v_iflag &= ~VI_OWEINACT;
4039 return (vinactivef(vp));
4043 * Remove any vnodes in the vnode table belonging to mount point mp.
4045 * If FORCECLOSE is not specified, there should not be any active ones,
4046 * return error if any are found (nb: this is a user error, not a
4047 * system error). If FORCECLOSE is specified, detach any active vnodes
4050 * If WRITECLOSE is set, only flush out regular file vnodes open for
4053 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
4055 * `rootrefs' specifies the base reference count for the root vnode
4056 * of this filesystem. The root vnode is considered busy if its
4057 * v_usecount exceeds this value. On a successful return, vflush(, td)
4058 * will call vrele() on the root vnode exactly rootrefs times.
4059 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
4063 static int busyprt = 0; /* print out busy vnodes */
4064 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
4068 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
4070 struct vnode *vp, *mvp, *rootvp = NULL;
4072 int busy = 0, error;
4074 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
4077 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
4078 ("vflush: bad args"));
4080 * Get the filesystem root vnode. We can vput() it
4081 * immediately, since with rootrefs > 0, it won't go away.
4083 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
4084 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
4091 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
4093 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
4096 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
4100 * Skip over a vnodes marked VV_SYSTEM.
4102 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
4108 * If WRITECLOSE is set, flush out unlinked but still open
4109 * files (even if open only for reading) and regular file
4110 * vnodes open for writing.
4112 if (flags & WRITECLOSE) {
4113 vnode_pager_clean_async(vp);
4115 error = VOP_FSYNC(vp, MNT_WAIT, td);
4116 } while (error == ERELOOKUP);
4120 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
4123 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
4126 if ((vp->v_type == VNON ||
4127 (error == 0 && vattr.va_nlink > 0)) &&
4128 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
4136 * With v_usecount == 0, all we need to do is clear out the
4137 * vnode data structures and we are done.
4139 * If FORCECLOSE is set, forcibly close the vnode.
4141 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
4147 vn_printf(vp, "vflush: busy vnode ");
4153 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
4155 * If just the root vnode is busy, and if its refcount
4156 * is equal to `rootrefs', then go ahead and kill it.
4159 KASSERT(busy > 0, ("vflush: not busy"));
4160 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
4161 ("vflush: usecount %d < rootrefs %d",
4162 rootvp->v_usecount, rootrefs));
4163 if (busy == 1 && rootvp->v_usecount == rootrefs) {
4164 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
4172 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
4176 for (; rootrefs > 0; rootrefs--)
4182 * Recycle an unused vnode.
4185 vrecycle(struct vnode *vp)
4190 recycled = vrecyclel(vp);
4196 * vrecycle, with the vp interlock held.
4199 vrecyclel(struct vnode *vp)
4203 ASSERT_VOP_ELOCKED(vp, __func__);
4204 ASSERT_VI_LOCKED(vp, __func__);
4205 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
4207 if (vp->v_usecount == 0) {
4215 * Eliminate all activity associated with a vnode
4216 * in preparation for reuse.
4219 vgone(struct vnode *vp)
4227 * Notify upper mounts about reclaimed or unlinked vnode.
4230 vfs_notify_upper(struct vnode *vp, enum vfs_notify_upper_type event)
4233 struct mount_upper_node *ump;
4235 mp = atomic_load_ptr(&vp->v_mount);
4238 if (TAILQ_EMPTY(&mp->mnt_notify))
4242 mp->mnt_upper_pending++;
4243 KASSERT(mp->mnt_upper_pending > 0,
4244 ("%s: mnt_upper_pending %d", __func__, mp->mnt_upper_pending));
4245 TAILQ_FOREACH(ump, &mp->mnt_notify, mnt_upper_link) {
4248 case VFS_NOTIFY_UPPER_RECLAIM:
4249 VFS_RECLAIM_LOWERVP(ump->mp, vp);
4251 case VFS_NOTIFY_UPPER_UNLINK:
4252 VFS_UNLINK_LOWERVP(ump->mp, vp);
4257 mp->mnt_upper_pending--;
4258 if ((mp->mnt_kern_flag & MNTK_UPPER_WAITER) != 0 &&
4259 mp->mnt_upper_pending == 0) {
4260 mp->mnt_kern_flag &= ~MNTK_UPPER_WAITER;
4261 wakeup(&mp->mnt_uppers);
4267 * vgone, with the vp interlock held.
4270 vgonel(struct vnode *vp)
4275 bool active, doinginact, oweinact;
4277 ASSERT_VOP_ELOCKED(vp, "vgonel");
4278 ASSERT_VI_LOCKED(vp, "vgonel");
4279 VNASSERT(vp->v_holdcnt, vp,
4280 ("vgonel: vp %p has no reference.", vp));
4281 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
4285 * Don't vgonel if we're already doomed.
4287 if (VN_IS_DOOMED(vp)) {
4288 VNPASS(vn_get_state(vp) == VSTATE_DESTROYING || \
4289 vn_get_state(vp) == VSTATE_DEAD, vp);
4293 * Paired with freevnode.
4295 vn_seqc_write_begin_locked(vp);
4297 vn_irflag_set_locked(vp, VIRF_DOOMED);
4298 vn_set_state(vp, VSTATE_DESTROYING);
4301 * Check to see if the vnode is in use. If so, we have to
4302 * call VOP_CLOSE() and VOP_INACTIVE().
4304 * It could be that VOP_INACTIVE() requested reclamation, in
4305 * which case we should avoid recursion, so check
4306 * VI_DOINGINACT. This is not precise but good enough.
4308 active = vp->v_usecount > 0;
4309 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4310 doinginact = (vp->v_iflag & VI_DOINGINACT) != 0;
4313 * If we need to do inactive VI_OWEINACT will be set.
4315 if (vp->v_iflag & VI_DEFINACT) {
4316 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
4317 vp->v_iflag &= ~VI_DEFINACT;
4320 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
4323 cache_purge_vgone(vp);
4324 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
4327 * If purging an active vnode, it must be closed and
4328 * deactivated before being reclaimed.
4331 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
4334 if (oweinact || active) {
4337 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4342 if (vp->v_type == VSOCK)
4343 vfs_unp_reclaim(vp);
4346 * Clean out any buffers associated with the vnode.
4347 * If the flush fails, just toss the buffers.
4350 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
4351 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
4352 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
4353 while (vinvalbuf(vp, 0, 0, 0) != 0)
4357 BO_LOCK(&vp->v_bufobj);
4358 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
4359 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
4360 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
4361 vp->v_bufobj.bo_clean.bv_cnt == 0,
4362 ("vp %p bufobj not invalidated", vp));
4365 * For VMIO bufobj, BO_DEAD is set later, or in
4366 * vm_object_terminate() after the object's page queue is
4369 object = vp->v_bufobj.bo_object;
4371 vp->v_bufobj.bo_flag |= BO_DEAD;
4372 BO_UNLOCK(&vp->v_bufobj);
4375 * Handle the VM part. Tmpfs handles v_object on its own (the
4376 * OBJT_VNODE check). Nullfs or other bypassing filesystems
4377 * should not touch the object borrowed from the lower vnode
4378 * (the handle check).
4380 if (object != NULL && object->type == OBJT_VNODE &&
4381 object->handle == vp)
4382 vnode_destroy_vobject(vp);
4385 * Reclaim the vnode.
4387 if (VOP_RECLAIM(vp))
4388 panic("vgone: cannot reclaim");
4390 vn_finished_secondary_write(mp);
4391 VNASSERT(vp->v_object == NULL, vp,
4392 ("vop_reclaim left v_object vp=%p", vp));
4394 * Clear the advisory locks and wake up waiting threads.
4396 if (vp->v_lockf != NULL) {
4397 (void)VOP_ADVLOCKPURGE(vp);
4401 * Delete from old mount point vnode list.
4403 if (vp->v_mount == NULL) {
4407 ASSERT_VI_LOCKED(vp, "vgonel 2");
4410 * Done with purge, reset to the standard lock and invalidate
4413 vp->v_vnlock = &vp->v_lock;
4414 vp->v_op = &dead_vnodeops;
4416 vn_set_state(vp, VSTATE_DEAD);
4420 * Print out a description of a vnode.
4422 static const char *const vtypename[] = {
4432 [VMARKER] = "VMARKER",
4434 _Static_assert(nitems(vtypename) == VLASTTYPE + 1,
4435 "vnode type name not added to vtypename");
4437 static const char *const vstatename[] = {
4438 [VSTATE_UNINITIALIZED] = "VSTATE_UNINITIALIZED",
4439 [VSTATE_CONSTRUCTED] = "VSTATE_CONSTRUCTED",
4440 [VSTATE_DESTROYING] = "VSTATE_DESTROYING",
4441 [VSTATE_DEAD] = "VSTATE_DEAD",
4443 _Static_assert(nitems(vstatename) == VLASTSTATE + 1,
4444 "vnode state name not added to vstatename");
4446 _Static_assert((VHOLD_ALL_FLAGS & ~VHOLD_NO_SMR) == 0,
4447 "new hold count flag not added to vn_printf");
4450 vn_printf(struct vnode *vp, const char *fmt, ...)
4453 char buf[256], buf2[16];
4461 printf("%p: ", (void *)vp);
4462 printf("type %s state %s op %p\n", vtypename[vp->v_type],
4463 vstatename[vp->v_state], vp->v_op);
4464 holdcnt = atomic_load_int(&vp->v_holdcnt);
4465 printf(" usecount %d, writecount %d, refcount %d seqc users %d",
4466 vp->v_usecount, vp->v_writecount, holdcnt & ~VHOLD_ALL_FLAGS,
4468 switch (vp->v_type) {
4470 printf(" mountedhere %p\n", vp->v_mountedhere);
4473 printf(" rdev %p\n", vp->v_rdev);
4476 printf(" socket %p\n", vp->v_unpcb);
4479 printf(" fifoinfo %p\n", vp->v_fifoinfo);
4487 if (holdcnt & VHOLD_NO_SMR)
4488 strlcat(buf, "|VHOLD_NO_SMR", sizeof(buf));
4489 printf(" hold count flags (%s)\n", buf + 1);
4493 irflag = vn_irflag_read(vp);
4494 if (irflag & VIRF_DOOMED)
4495 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
4496 if (irflag & VIRF_PGREAD)
4497 strlcat(buf, "|VIRF_PGREAD", sizeof(buf));
4498 if (irflag & VIRF_MOUNTPOINT)
4499 strlcat(buf, "|VIRF_MOUNTPOINT", sizeof(buf));
4500 if (irflag & VIRF_TEXT_REF)
4501 strlcat(buf, "|VIRF_TEXT_REF", sizeof(buf));
4502 flags = irflag & ~(VIRF_DOOMED | VIRF_PGREAD | VIRF_MOUNTPOINT | VIRF_TEXT_REF);
4504 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
4505 strlcat(buf, buf2, sizeof(buf));
4507 if (vp->v_vflag & VV_ROOT)
4508 strlcat(buf, "|VV_ROOT", sizeof(buf));
4509 if (vp->v_vflag & VV_ISTTY)
4510 strlcat(buf, "|VV_ISTTY", sizeof(buf));
4511 if (vp->v_vflag & VV_NOSYNC)
4512 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
4513 if (vp->v_vflag & VV_ETERNALDEV)
4514 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
4515 if (vp->v_vflag & VV_CACHEDLABEL)
4516 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
4517 if (vp->v_vflag & VV_VMSIZEVNLOCK)
4518 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
4519 if (vp->v_vflag & VV_COPYONWRITE)
4520 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
4521 if (vp->v_vflag & VV_SYSTEM)
4522 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
4523 if (vp->v_vflag & VV_PROCDEP)
4524 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
4525 if (vp->v_vflag & VV_DELETED)
4526 strlcat(buf, "|VV_DELETED", sizeof(buf));
4527 if (vp->v_vflag & VV_MD)
4528 strlcat(buf, "|VV_MD", sizeof(buf));
4529 if (vp->v_vflag & VV_FORCEINSMQ)
4530 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
4531 if (vp->v_vflag & VV_READLINK)
4532 strlcat(buf, "|VV_READLINK", sizeof(buf));
4533 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4534 VV_CACHEDLABEL | VV_VMSIZEVNLOCK | VV_COPYONWRITE | VV_SYSTEM |
4535 VV_PROCDEP | VV_DELETED | VV_MD | VV_FORCEINSMQ | VV_READLINK);
4537 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4538 strlcat(buf, buf2, sizeof(buf));
4540 if (vp->v_iflag & VI_MOUNT)
4541 strlcat(buf, "|VI_MOUNT", sizeof(buf));
4542 if (vp->v_iflag & VI_DOINGINACT)
4543 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4544 if (vp->v_iflag & VI_OWEINACT)
4545 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4546 if (vp->v_iflag & VI_DEFINACT)
4547 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4548 if (vp->v_iflag & VI_FOPENING)
4549 strlcat(buf, "|VI_FOPENING", sizeof(buf));
4550 flags = vp->v_iflag & ~(VI_MOUNT | VI_DOINGINACT |
4551 VI_OWEINACT | VI_DEFINACT | VI_FOPENING);
4553 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4554 strlcat(buf, buf2, sizeof(buf));
4556 if (vp->v_mflag & VMP_LAZYLIST)
4557 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4558 flags = vp->v_mflag & ~(VMP_LAZYLIST);
4560 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4561 strlcat(buf, buf2, sizeof(buf));
4563 printf(" flags (%s)", buf + 1);
4564 if (mtx_owned(VI_MTX(vp)))
4565 printf(" VI_LOCKed");
4567 if (vp->v_object != NULL)
4568 printf(" v_object %p ref %d pages %d "
4569 "cleanbuf %d dirtybuf %d\n",
4570 vp->v_object, vp->v_object->ref_count,
4571 vp->v_object->resident_page_count,
4572 vp->v_bufobj.bo_clean.bv_cnt,
4573 vp->v_bufobj.bo_dirty.bv_cnt);
4575 lockmgr_printinfo(vp->v_vnlock);
4576 if (vp->v_data != NULL)
4582 * List all of the locked vnodes in the system.
4583 * Called when debugging the kernel.
4585 DB_SHOW_COMMAND_FLAGS(lockedvnods, lockedvnodes, DB_CMD_MEMSAFE)
4591 * Note: because this is DDB, we can't obey the locking semantics
4592 * for these structures, which means we could catch an inconsistent
4593 * state and dereference a nasty pointer. Not much to be done
4596 db_printf("Locked vnodes\n");
4597 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4598 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4599 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4600 vn_printf(vp, "vnode ");
4606 * Show details about the given vnode.
4608 DB_SHOW_COMMAND(vnode, db_show_vnode)
4614 vp = (struct vnode *)addr;
4615 vn_printf(vp, "vnode ");
4619 * Show details about the given mount point.
4621 DB_SHOW_COMMAND(mount, db_show_mount)
4632 /* No address given, print short info about all mount points. */
4633 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4634 db_printf("%p %s on %s (%s)\n", mp,
4635 mp->mnt_stat.f_mntfromname,
4636 mp->mnt_stat.f_mntonname,
4637 mp->mnt_stat.f_fstypename);
4641 db_printf("\nMore info: show mount <addr>\n");
4645 mp = (struct mount *)addr;
4646 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4647 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4650 mflags = mp->mnt_flag;
4651 #define MNT_FLAG(flag) do { \
4652 if (mflags & (flag)) { \
4653 if (buf[0] != '\0') \
4654 strlcat(buf, ", ", sizeof(buf)); \
4655 strlcat(buf, (#flag) + 4, sizeof(buf)); \
4656 mflags &= ~(flag); \
4659 MNT_FLAG(MNT_RDONLY);
4660 MNT_FLAG(MNT_SYNCHRONOUS);
4661 MNT_FLAG(MNT_NOEXEC);
4662 MNT_FLAG(MNT_NOSUID);
4663 MNT_FLAG(MNT_NFS4ACLS);
4664 MNT_FLAG(MNT_UNION);
4665 MNT_FLAG(MNT_ASYNC);
4666 MNT_FLAG(MNT_SUIDDIR);
4667 MNT_FLAG(MNT_SOFTDEP);
4668 MNT_FLAG(MNT_NOSYMFOLLOW);
4669 MNT_FLAG(MNT_GJOURNAL);
4670 MNT_FLAG(MNT_MULTILABEL);
4672 MNT_FLAG(MNT_NOATIME);
4673 MNT_FLAG(MNT_NOCLUSTERR);
4674 MNT_FLAG(MNT_NOCLUSTERW);
4676 MNT_FLAG(MNT_EXRDONLY);
4677 MNT_FLAG(MNT_EXPORTED);
4678 MNT_FLAG(MNT_DEFEXPORTED);
4679 MNT_FLAG(MNT_EXPORTANON);
4680 MNT_FLAG(MNT_EXKERB);
4681 MNT_FLAG(MNT_EXPUBLIC);
4682 MNT_FLAG(MNT_LOCAL);
4683 MNT_FLAG(MNT_QUOTA);
4684 MNT_FLAG(MNT_ROOTFS);
4686 MNT_FLAG(MNT_IGNORE);
4687 MNT_FLAG(MNT_UPDATE);
4688 MNT_FLAG(MNT_DELEXPORT);
4689 MNT_FLAG(MNT_RELOAD);
4690 MNT_FLAG(MNT_FORCE);
4691 MNT_FLAG(MNT_SNAPSHOT);
4692 MNT_FLAG(MNT_BYFSID);
4696 strlcat(buf, ", ", sizeof(buf));
4697 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4698 "0x%016jx", mflags);
4700 db_printf(" mnt_flag = %s\n", buf);
4703 flags = mp->mnt_kern_flag;
4704 #define MNT_KERN_FLAG(flag) do { \
4705 if (flags & (flag)) { \
4706 if (buf[0] != '\0') \
4707 strlcat(buf, ", ", sizeof(buf)); \
4708 strlcat(buf, (#flag) + 5, sizeof(buf)); \
4712 MNT_KERN_FLAG(MNTK_UNMOUNTF);
4713 MNT_KERN_FLAG(MNTK_ASYNC);
4714 MNT_KERN_FLAG(MNTK_SOFTDEP);
4715 MNT_KERN_FLAG(MNTK_NOMSYNC);
4716 MNT_KERN_FLAG(MNTK_DRAINING);
4717 MNT_KERN_FLAG(MNTK_REFEXPIRE);
4718 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4719 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4720 MNT_KERN_FLAG(MNTK_NO_IOPF);
4721 MNT_KERN_FLAG(MNTK_RECURSE);
4722 MNT_KERN_FLAG(MNTK_UPPER_WAITER);
4723 MNT_KERN_FLAG(MNTK_UNLOCKED_INSMNTQUE);
4724 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4725 MNT_KERN_FLAG(MNTK_VMSETSIZE_BUG);
4726 MNT_KERN_FLAG(MNTK_FPLOOKUP);
4727 MNT_KERN_FLAG(MNTK_TASKQUEUE_WAITER);
4728 MNT_KERN_FLAG(MNTK_NOASYNC);
4729 MNT_KERN_FLAG(MNTK_UNMOUNT);
4730 MNT_KERN_FLAG(MNTK_MWAIT);
4731 MNT_KERN_FLAG(MNTK_SUSPEND);
4732 MNT_KERN_FLAG(MNTK_SUSPEND2);
4733 MNT_KERN_FLAG(MNTK_SUSPENDED);
4734 MNT_KERN_FLAG(MNTK_NULL_NOCACHE);
4735 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4736 #undef MNT_KERN_FLAG
4739 strlcat(buf, ", ", sizeof(buf));
4740 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4743 db_printf(" mnt_kern_flag = %s\n", buf);
4745 db_printf(" mnt_opt = ");
4746 opt = TAILQ_FIRST(mp->mnt_opt);
4748 db_printf("%s", opt->name);
4749 opt = TAILQ_NEXT(opt, link);
4750 while (opt != NULL) {
4751 db_printf(", %s", opt->name);
4752 opt = TAILQ_NEXT(opt, link);
4758 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4759 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4760 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4761 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4762 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4763 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4764 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4765 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4766 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4767 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4768 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4769 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4771 db_printf(" mnt_cred = { uid=%u ruid=%u",
4772 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4773 if (jailed(mp->mnt_cred))
4774 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4776 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4777 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4778 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4779 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4780 db_printf(" mnt_lazyvnodelistsize = %d\n",
4781 mp->mnt_lazyvnodelistsize);
4782 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4783 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4784 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4785 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4786 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4787 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4788 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4789 db_printf(" mnt_secondary_accwrites = %d\n",
4790 mp->mnt_secondary_accwrites);
4791 db_printf(" mnt_gjprovider = %s\n",
4792 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4793 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4795 db_printf("\n\nList of active vnodes\n");
4796 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4797 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4798 vn_printf(vp, "vnode ");
4803 db_printf("\n\nList of inactive vnodes\n");
4804 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4805 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4806 vn_printf(vp, "vnode ");
4815 * Fill in a struct xvfsconf based on a struct vfsconf.
4818 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4820 struct xvfsconf xvfsp;
4822 bzero(&xvfsp, sizeof(xvfsp));
4823 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4824 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4825 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4826 xvfsp.vfc_flags = vfsp->vfc_flags;
4828 * These are unused in userland, we keep them
4829 * to not break binary compatibility.
4831 xvfsp.vfc_vfsops = NULL;
4832 xvfsp.vfc_next = NULL;
4833 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4836 #ifdef COMPAT_FREEBSD32
4838 uint32_t vfc_vfsops;
4839 char vfc_name[MFSNAMELEN];
4840 int32_t vfc_typenum;
4841 int32_t vfc_refcount;
4847 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4849 struct xvfsconf32 xvfsp;
4851 bzero(&xvfsp, sizeof(xvfsp));
4852 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4853 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4854 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4855 xvfsp.vfc_flags = vfsp->vfc_flags;
4856 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4861 * Top level filesystem related information gathering.
4864 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4866 struct vfsconf *vfsp;
4871 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4872 #ifdef COMPAT_FREEBSD32
4873 if (req->flags & SCTL_MASK32)
4874 error = vfsconf2x32(req, vfsp);
4877 error = vfsconf2x(req, vfsp);
4885 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4886 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4887 "S,xvfsconf", "List of all configured filesystems");
4889 #ifndef BURN_BRIDGES
4890 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4893 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4895 int *name = (int *)arg1 - 1; /* XXX */
4896 u_int namelen = arg2 + 1; /* XXX */
4897 struct vfsconf *vfsp;
4899 log(LOG_WARNING, "userland calling deprecated sysctl, "
4900 "please rebuild world\n");
4902 #if 1 || defined(COMPAT_PRELITE2)
4903 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4905 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4909 case VFS_MAXTYPENUM:
4912 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4915 return (ENOTDIR); /* overloaded */
4917 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4918 if (vfsp->vfc_typenum == name[2])
4923 return (EOPNOTSUPP);
4924 #ifdef COMPAT_FREEBSD32
4925 if (req->flags & SCTL_MASK32)
4926 return (vfsconf2x32(req, vfsp));
4929 return (vfsconf2x(req, vfsp));
4931 return (EOPNOTSUPP);
4934 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4935 CTLFLAG_MPSAFE, vfs_sysctl,
4936 "Generic filesystem");
4938 #if 1 || defined(COMPAT_PRELITE2)
4941 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4944 struct vfsconf *vfsp;
4945 struct ovfsconf ovfs;
4948 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4949 bzero(&ovfs, sizeof(ovfs));
4950 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4951 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4952 ovfs.vfc_index = vfsp->vfc_typenum;
4953 ovfs.vfc_refcount = vfsp->vfc_refcount;
4954 ovfs.vfc_flags = vfsp->vfc_flags;
4955 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4965 #endif /* 1 || COMPAT_PRELITE2 */
4966 #endif /* !BURN_BRIDGES */
4969 unmount_or_warn(struct mount *mp)
4973 error = dounmount(mp, MNT_FORCE, curthread);
4975 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4979 printf("%d)\n", error);
4984 * Unmount all filesystems. The list is traversed in reverse order
4985 * of mounting to avoid dependencies.
4988 vfs_unmountall(void)
4990 struct mount *mp, *tmp;
4992 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4995 * Since this only runs when rebooting, it is not interlocked.
4997 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
5001 * Forcibly unmounting "/dev" before "/" would prevent clean
5002 * unmount of the latter.
5004 if (mp == rootdevmp)
5007 unmount_or_warn(mp);
5010 if (rootdevmp != NULL)
5011 unmount_or_warn(rootdevmp);
5015 vfs_deferred_inactive(struct vnode *vp, int lkflags)
5018 ASSERT_VI_LOCKED(vp, __func__);
5019 VNPASS((vp->v_iflag & VI_DEFINACT) == 0, vp);
5020 if ((vp->v_iflag & VI_OWEINACT) == 0) {
5024 if (vn_lock(vp, lkflags) == 0) {
5031 vdefer_inactive_unlocked(vp);
5035 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
5038 return (vp->v_iflag & VI_DEFINACT);
5041 static void __noinline
5042 vfs_periodic_inactive(struct mount *mp, int flags)
5044 struct vnode *vp, *mvp;
5047 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
5048 if (flags != MNT_WAIT)
5049 lkflags |= LK_NOWAIT;
5051 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
5052 if ((vp->v_iflag & VI_DEFINACT) == 0) {
5056 vp->v_iflag &= ~VI_DEFINACT;
5057 vfs_deferred_inactive(vp, lkflags);
5062 vfs_want_msync(struct vnode *vp)
5064 struct vm_object *obj;
5067 * This test may be performed without any locks held.
5068 * We rely on vm_object's type stability.
5070 if (vp->v_vflag & VV_NOSYNC)
5073 return (obj != NULL && vm_object_mightbedirty(obj));
5077 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
5080 if (vp->v_vflag & VV_NOSYNC)
5082 if (vp->v_iflag & VI_DEFINACT)
5084 return (vfs_want_msync(vp));
5087 static void __noinline
5088 vfs_periodic_msync_inactive(struct mount *mp, int flags)
5090 struct vnode *vp, *mvp;
5094 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
5095 if (flags != MNT_WAIT)
5096 lkflags |= LK_NOWAIT;
5098 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
5100 if (vp->v_iflag & VI_DEFINACT) {
5101 vp->v_iflag &= ~VI_DEFINACT;
5104 if (!vfs_want_msync(vp)) {
5106 vfs_deferred_inactive(vp, lkflags);
5111 if (vget(vp, lkflags) == 0) {
5112 if ((vp->v_vflag & VV_NOSYNC) == 0) {
5113 if (flags == MNT_WAIT)
5114 vnode_pager_clean_sync(vp);
5116 vnode_pager_clean_async(vp);
5123 vdefer_inactive_unlocked(vp);
5129 vfs_periodic(struct mount *mp, int flags)
5132 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
5134 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
5135 vfs_periodic_inactive(mp, flags);
5137 vfs_periodic_msync_inactive(mp, flags);
5141 destroy_vpollinfo_free(struct vpollinfo *vi)
5144 knlist_destroy(&vi->vpi_selinfo.si_note);
5145 mtx_destroy(&vi->vpi_lock);
5146 free(vi, M_VNODEPOLL);
5150 destroy_vpollinfo(struct vpollinfo *vi)
5153 knlist_clear(&vi->vpi_selinfo.si_note, 1);
5154 seldrain(&vi->vpi_selinfo);
5155 destroy_vpollinfo_free(vi);
5159 * Initialize per-vnode helper structure to hold poll-related state.
5162 v_addpollinfo(struct vnode *vp)
5164 struct vpollinfo *vi;
5166 if (vp->v_pollinfo != NULL)
5168 vi = malloc(sizeof(*vi), M_VNODEPOLL, M_WAITOK | M_ZERO);
5169 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
5170 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
5171 vfs_knlunlock, vfs_knl_assert_lock);
5173 if (vp->v_pollinfo != NULL) {
5175 destroy_vpollinfo_free(vi);
5178 vp->v_pollinfo = vi;
5183 * Record a process's interest in events which might happen to
5184 * a vnode. Because poll uses the historic select-style interface
5185 * internally, this routine serves as both the ``check for any
5186 * pending events'' and the ``record my interest in future events''
5187 * functions. (These are done together, while the lock is held,
5188 * to avoid race conditions.)
5191 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
5195 mtx_lock(&vp->v_pollinfo->vpi_lock);
5196 if (vp->v_pollinfo->vpi_revents & events) {
5198 * This leaves events we are not interested
5199 * in available for the other process which
5200 * which presumably had requested them
5201 * (otherwise they would never have been
5204 events &= vp->v_pollinfo->vpi_revents;
5205 vp->v_pollinfo->vpi_revents &= ~events;
5207 mtx_unlock(&vp->v_pollinfo->vpi_lock);
5210 vp->v_pollinfo->vpi_events |= events;
5211 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
5212 mtx_unlock(&vp->v_pollinfo->vpi_lock);
5217 * Routine to create and manage a filesystem syncer vnode.
5219 #define sync_close ((int (*)(struct vop_close_args *))nullop)
5220 static int sync_fsync(struct vop_fsync_args *);
5221 static int sync_inactive(struct vop_inactive_args *);
5222 static int sync_reclaim(struct vop_reclaim_args *);
5224 static struct vop_vector sync_vnodeops = {
5225 .vop_bypass = VOP_EOPNOTSUPP,
5226 .vop_close = sync_close,
5227 .vop_fsync = sync_fsync,
5228 .vop_getwritemount = vop_stdgetwritemount,
5229 .vop_inactive = sync_inactive,
5230 .vop_need_inactive = vop_stdneed_inactive,
5231 .vop_reclaim = sync_reclaim,
5232 .vop_lock1 = vop_stdlock,
5233 .vop_unlock = vop_stdunlock,
5234 .vop_islocked = vop_stdislocked,
5235 .vop_fplookup_vexec = VOP_EAGAIN,
5236 .vop_fplookup_symlink = VOP_EAGAIN,
5238 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
5241 * Create a new filesystem syncer vnode for the specified mount point.
5244 vfs_allocate_syncvnode(struct mount *mp)
5248 static long start, incr, next;
5251 /* Allocate a new vnode */
5252 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
5254 panic("vfs_allocate_syncvnode: getnewvnode() failed");
5256 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5257 vp->v_vflag |= VV_FORCEINSMQ;
5258 error = insmntque1(vp, mp);
5260 panic("vfs_allocate_syncvnode: insmntque() failed");
5261 vp->v_vflag &= ~VV_FORCEINSMQ;
5262 vn_set_state(vp, VSTATE_CONSTRUCTED);
5265 * Place the vnode onto the syncer worklist. We attempt to
5266 * scatter them about on the list so that they will go off
5267 * at evenly distributed times even if all the filesystems
5268 * are mounted at once.
5271 if (next == 0 || next > syncer_maxdelay) {
5275 start = syncer_maxdelay / 2;
5276 incr = syncer_maxdelay;
5282 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
5283 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
5284 mtx_lock(&sync_mtx);
5286 if (mp->mnt_syncer == NULL) {
5287 mp->mnt_syncer = vp;
5290 mtx_unlock(&sync_mtx);
5293 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5300 vfs_deallocate_syncvnode(struct mount *mp)
5304 mtx_lock(&sync_mtx);
5305 vp = mp->mnt_syncer;
5307 mp->mnt_syncer = NULL;
5308 mtx_unlock(&sync_mtx);
5314 * Do a lazy sync of the filesystem.
5317 sync_fsync(struct vop_fsync_args *ap)
5319 struct vnode *syncvp = ap->a_vp;
5320 struct mount *mp = syncvp->v_mount;
5325 * We only need to do something if this is a lazy evaluation.
5327 if (ap->a_waitfor != MNT_LAZY)
5331 * Move ourselves to the back of the sync list.
5333 bo = &syncvp->v_bufobj;
5335 vn_syncer_add_to_worklist(bo, syncdelay);
5339 * Walk the list of vnodes pushing all that are dirty and
5340 * not already on the sync list.
5342 if (vfs_busy(mp, MBF_NOWAIT) != 0)
5345 save = curthread_pflags_set(TDP_SYNCIO);
5347 * The filesystem at hand may be idle with free vnodes stored in the
5348 * batch. Return them instead of letting them stay there indefinitely.
5350 vfs_periodic(mp, MNT_NOWAIT);
5351 error = VFS_SYNC(mp, MNT_LAZY);
5352 curthread_pflags_restore(save);
5353 vn_lock(syncvp, LK_EXCLUSIVE | LK_RETRY);
5359 * The syncer vnode is no referenced.
5362 sync_inactive(struct vop_inactive_args *ap)
5370 * The syncer vnode is no longer needed and is being decommissioned.
5372 * Modifications to the worklist must be protected by sync_mtx.
5375 sync_reclaim(struct vop_reclaim_args *ap)
5377 struct vnode *vp = ap->a_vp;
5382 mtx_lock(&sync_mtx);
5383 if (vp->v_mount->mnt_syncer == vp)
5384 vp->v_mount->mnt_syncer = NULL;
5385 if (bo->bo_flag & BO_ONWORKLST) {
5386 LIST_REMOVE(bo, bo_synclist);
5387 syncer_worklist_len--;
5389 bo->bo_flag &= ~BO_ONWORKLST;
5391 mtx_unlock(&sync_mtx);
5398 vn_need_pageq_flush(struct vnode *vp)
5400 struct vm_object *obj;
5403 return (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
5404 vm_object_mightbedirty(obj));
5408 * Check if vnode represents a disk device
5411 vn_isdisk_error(struct vnode *vp, int *errp)
5415 if (vp->v_type != VCHR) {
5421 if (vp->v_rdev == NULL)
5423 else if (vp->v_rdev->si_devsw == NULL)
5425 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5430 return (error == 0);
5434 vn_isdisk(struct vnode *vp)
5438 return (vn_isdisk_error(vp, &error));
5442 * VOP_FPLOOKUP_VEXEC routines are subject to special circumstances, see
5443 * the comment above cache_fplookup for details.
5446 vaccess_vexec_smr(mode_t file_mode, uid_t file_uid, gid_t file_gid, struct ucred *cred)
5450 VFS_SMR_ASSERT_ENTERED();
5452 /* Check the owner. */
5453 if (cred->cr_uid == file_uid) {
5454 if (file_mode & S_IXUSR)
5459 /* Otherwise, check the groups (first match) */
5460 if (groupmember(file_gid, cred)) {
5461 if (file_mode & S_IXGRP)
5466 /* Otherwise, check everyone else. */
5467 if (file_mode & S_IXOTH)
5471 * Permission check failed, but it is possible denial will get overwritten
5472 * (e.g., when root is traversing through a 700 directory owned by someone
5475 * vaccess() calls priv_check_cred which in turn can descent into MAC
5476 * modules overriding this result. It's quite unclear what semantics
5477 * are allowed for them to operate, thus for safety we don't call them
5478 * from within the SMR section. This also means if any such modules
5479 * are present, we have to let the regular lookup decide.
5481 error = priv_check_cred_vfs_lookup_nomac(cred);
5487 * MAC modules present.
5498 * Common filesystem object access control check routine. Accepts a
5499 * vnode's type, "mode", uid and gid, requested access mode, and credentials.
5500 * Returns 0 on success, or an errno on failure.
5503 vaccess(__enum_uint8(vtype) type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5504 accmode_t accmode, struct ucred *cred)
5506 accmode_t dac_granted;
5507 accmode_t priv_granted;
5509 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5510 ("invalid bit in accmode"));
5511 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5512 ("VAPPEND without VWRITE"));
5515 * Look for a normal, non-privileged way to access the file/directory
5516 * as requested. If it exists, go with that.
5521 /* Check the owner. */
5522 if (cred->cr_uid == file_uid) {
5523 dac_granted |= VADMIN;
5524 if (file_mode & S_IXUSR)
5525 dac_granted |= VEXEC;
5526 if (file_mode & S_IRUSR)
5527 dac_granted |= VREAD;
5528 if (file_mode & S_IWUSR)
5529 dac_granted |= (VWRITE | VAPPEND);
5531 if ((accmode & dac_granted) == accmode)
5537 /* Otherwise, check the groups (first match) */
5538 if (groupmember(file_gid, cred)) {
5539 if (file_mode & S_IXGRP)
5540 dac_granted |= VEXEC;
5541 if (file_mode & S_IRGRP)
5542 dac_granted |= VREAD;
5543 if (file_mode & S_IWGRP)
5544 dac_granted |= (VWRITE | VAPPEND);
5546 if ((accmode & dac_granted) == accmode)
5552 /* Otherwise, check everyone else. */
5553 if (file_mode & S_IXOTH)
5554 dac_granted |= VEXEC;
5555 if (file_mode & S_IROTH)
5556 dac_granted |= VREAD;
5557 if (file_mode & S_IWOTH)
5558 dac_granted |= (VWRITE | VAPPEND);
5559 if ((accmode & dac_granted) == accmode)
5564 * Build a privilege mask to determine if the set of privileges
5565 * satisfies the requirements when combined with the granted mask
5566 * from above. For each privilege, if the privilege is required,
5567 * bitwise or the request type onto the priv_granted mask.
5573 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5574 * requests, instead of PRIV_VFS_EXEC.
5576 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5577 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5578 priv_granted |= VEXEC;
5581 * Ensure that at least one execute bit is on. Otherwise,
5582 * a privileged user will always succeed, and we don't want
5583 * this to happen unless the file really is executable.
5585 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5586 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5587 !priv_check_cred(cred, PRIV_VFS_EXEC))
5588 priv_granted |= VEXEC;
5591 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5592 !priv_check_cred(cred, PRIV_VFS_READ))
5593 priv_granted |= VREAD;
5595 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5596 !priv_check_cred(cred, PRIV_VFS_WRITE))
5597 priv_granted |= (VWRITE | VAPPEND);
5599 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5600 !priv_check_cred(cred, PRIV_VFS_ADMIN))
5601 priv_granted |= VADMIN;
5603 if ((accmode & (priv_granted | dac_granted)) == accmode) {
5607 return ((accmode & VADMIN) ? EPERM : EACCES);
5611 * Credential check based on process requesting service, and per-attribute
5615 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5616 struct thread *td, accmode_t accmode)
5620 * Kernel-invoked always succeeds.
5626 * Do not allow privileged processes in jail to directly manipulate
5627 * system attributes.
5629 switch (attrnamespace) {
5630 case EXTATTR_NAMESPACE_SYSTEM:
5631 /* Potentially should be: return (EPERM); */
5632 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5633 case EXTATTR_NAMESPACE_USER:
5634 return (VOP_ACCESS(vp, accmode, cred, td));
5640 #ifdef DEBUG_VFS_LOCKS
5641 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
5642 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5643 "Drop into debugger on lock violation");
5645 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
5646 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5647 0, "Check for interlock across VOPs");
5649 int vfs_badlock_print = 1; /* Print lock violations. */
5650 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5651 0, "Print lock violations");
5653 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
5654 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5655 0, "Print vnode details on lock violations");
5658 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
5659 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5660 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5664 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5668 if (vfs_badlock_backtrace)
5671 if (vfs_badlock_vnode)
5672 vn_printf(vp, "vnode ");
5673 if (vfs_badlock_print)
5674 printf("%s: %p %s\n", str, (void *)vp, msg);
5675 if (vfs_badlock_ddb)
5676 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5680 assert_vi_locked(struct vnode *vp, const char *str)
5683 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5684 vfs_badlock("interlock is not locked but should be", str, vp);
5688 assert_vi_unlocked(struct vnode *vp, const char *str)
5691 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5692 vfs_badlock("interlock is locked but should not be", str, vp);
5696 assert_vop_locked(struct vnode *vp, const char *str)
5698 if (KERNEL_PANICKED() || vp == NULL)
5702 if ((vp->v_irflag & VIRF_CROSSMP) == 0 &&
5703 witness_is_owned(&vp->v_vnlock->lock_object) == -1)
5705 int locked = VOP_ISLOCKED(vp);
5706 if (locked == 0 || locked == LK_EXCLOTHER)
5708 vfs_badlock("is not locked but should be", str, vp);
5712 assert_vop_unlocked(struct vnode *vp, const char *str)
5714 if (KERNEL_PANICKED() || vp == NULL)
5718 if ((vp->v_irflag & VIRF_CROSSMP) == 0 &&
5719 witness_is_owned(&vp->v_vnlock->lock_object) == 1)
5721 if (VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5723 vfs_badlock("is locked but should not be", str, vp);
5727 assert_vop_elocked(struct vnode *vp, const char *str)
5729 if (KERNEL_PANICKED() || vp == NULL)
5732 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5733 vfs_badlock("is not exclusive locked but should be", str, vp);
5735 #endif /* DEBUG_VFS_LOCKS */
5738 vop_rename_fail(struct vop_rename_args *ap)
5741 if (ap->a_tvp != NULL)
5743 if (ap->a_tdvp == ap->a_tvp)
5752 vop_rename_pre(void *ap)
5754 struct vop_rename_args *a = ap;
5756 #ifdef DEBUG_VFS_LOCKS
5758 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5759 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5760 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5761 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5763 /* Check the source (from). */
5764 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5765 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5766 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5767 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5768 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5770 /* Check the target. */
5772 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5773 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5776 * It may be tempting to add vn_seqc_write_begin/end calls here and
5777 * in vop_rename_post but that's not going to work out since some
5778 * filesystems relookup vnodes mid-rename. This is probably a bug.
5780 * For now filesystems are expected to do the relevant calls after they
5781 * decide what vnodes to operate on.
5783 if (a->a_tdvp != a->a_fdvp)
5785 if (a->a_tvp != a->a_fvp)
5792 #ifdef DEBUG_VFS_LOCKS
5794 vop_fplookup_vexec_debugpre(void *ap __unused)
5797 VFS_SMR_ASSERT_ENTERED();
5801 vop_fplookup_vexec_debugpost(void *ap, int rc)
5803 struct vop_fplookup_vexec_args *a;
5809 VFS_SMR_ASSERT_ENTERED();
5810 if (rc == EOPNOTSUPP)
5811 VNPASS(VN_IS_DOOMED(vp), vp);
5815 vop_fplookup_symlink_debugpre(void *ap __unused)
5818 VFS_SMR_ASSERT_ENTERED();
5822 vop_fplookup_symlink_debugpost(void *ap __unused, int rc __unused)
5825 VFS_SMR_ASSERT_ENTERED();
5829 vop_fsync_debugprepost(struct vnode *vp, const char *name)
5831 if (vp->v_type == VCHR)
5833 else if (MNT_EXTENDED_SHARED(vp->v_mount))
5834 ASSERT_VOP_LOCKED(vp, name);
5836 ASSERT_VOP_ELOCKED(vp, name);
5840 vop_fsync_debugpre(void *a)
5842 struct vop_fsync_args *ap;
5845 vop_fsync_debugprepost(ap->a_vp, "fsync");
5849 vop_fsync_debugpost(void *a, int rc __unused)
5851 struct vop_fsync_args *ap;
5854 vop_fsync_debugprepost(ap->a_vp, "fsync");
5858 vop_fdatasync_debugpre(void *a)
5860 struct vop_fdatasync_args *ap;
5863 vop_fsync_debugprepost(ap->a_vp, "fsync");
5867 vop_fdatasync_debugpost(void *a, int rc __unused)
5869 struct vop_fdatasync_args *ap;
5872 vop_fsync_debugprepost(ap->a_vp, "fsync");
5876 vop_strategy_debugpre(void *ap)
5878 struct vop_strategy_args *a;
5885 * Cluster ops lock their component buffers but not the IO container.
5887 if ((bp->b_flags & B_CLUSTER) != 0)
5890 if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5891 if (vfs_badlock_print)
5893 "VOP_STRATEGY: bp is not locked but should be\n");
5894 if (vfs_badlock_ddb)
5895 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5900 vop_lock_debugpre(void *ap)
5902 struct vop_lock1_args *a = ap;
5904 if ((a->a_flags & LK_INTERLOCK) == 0)
5905 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5907 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5911 vop_lock_debugpost(void *ap, int rc)
5913 struct vop_lock1_args *a = ap;
5915 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5916 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5917 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5921 vop_unlock_debugpre(void *ap)
5923 struct vop_unlock_args *a = ap;
5924 struct vnode *vp = a->a_vp;
5926 VNPASS(vn_get_state(vp) != VSTATE_UNINITIALIZED, vp);
5927 ASSERT_VOP_LOCKED(vp, "VOP_UNLOCK");
5931 vop_need_inactive_debugpre(void *ap)
5933 struct vop_need_inactive_args *a = ap;
5935 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5939 vop_need_inactive_debugpost(void *ap, int rc)
5941 struct vop_need_inactive_args *a = ap;
5943 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5948 vop_create_pre(void *ap)
5950 struct vop_create_args *a;
5955 vn_seqc_write_begin(dvp);
5959 vop_create_post(void *ap, int rc)
5961 struct vop_create_args *a;
5966 vn_seqc_write_end(dvp);
5968 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5972 vop_whiteout_pre(void *ap)
5974 struct vop_whiteout_args *a;
5979 vn_seqc_write_begin(dvp);
5983 vop_whiteout_post(void *ap, int rc)
5985 struct vop_whiteout_args *a;
5990 vn_seqc_write_end(dvp);
5994 vop_deleteextattr_pre(void *ap)
5996 struct vop_deleteextattr_args *a;
6001 vn_seqc_write_begin(vp);
6005 vop_deleteextattr_post(void *ap, int rc)
6007 struct vop_deleteextattr_args *a;
6012 vn_seqc_write_end(vp);
6014 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
6018 vop_link_pre(void *ap)
6020 struct vop_link_args *a;
6021 struct vnode *vp, *tdvp;
6026 vn_seqc_write_begin(vp);
6027 vn_seqc_write_begin(tdvp);
6031 vop_link_post(void *ap, int rc)
6033 struct vop_link_args *a;
6034 struct vnode *vp, *tdvp;
6039 vn_seqc_write_end(vp);
6040 vn_seqc_write_end(tdvp);
6042 VFS_KNOTE_LOCKED(vp, NOTE_LINK);
6043 VFS_KNOTE_LOCKED(tdvp, NOTE_WRITE);
6048 vop_mkdir_pre(void *ap)
6050 struct vop_mkdir_args *a;
6055 vn_seqc_write_begin(dvp);
6059 vop_mkdir_post(void *ap, int rc)
6061 struct vop_mkdir_args *a;
6066 vn_seqc_write_end(dvp);
6068 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
6071 #ifdef DEBUG_VFS_LOCKS
6073 vop_mkdir_debugpost(void *ap, int rc)
6075 struct vop_mkdir_args *a;
6079 cache_validate(a->a_dvp, *a->a_vpp, a->a_cnp);
6084 vop_mknod_pre(void *ap)
6086 struct vop_mknod_args *a;
6091 vn_seqc_write_begin(dvp);
6095 vop_mknod_post(void *ap, int rc)
6097 struct vop_mknod_args *a;
6102 vn_seqc_write_end(dvp);
6104 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6108 vop_reclaim_post(void *ap, int rc)
6110 struct vop_reclaim_args *a;
6115 ASSERT_VOP_IN_SEQC(vp);
6117 VFS_KNOTE_LOCKED(vp, NOTE_REVOKE);
6121 vop_remove_pre(void *ap)
6123 struct vop_remove_args *a;
6124 struct vnode *dvp, *vp;
6129 vn_seqc_write_begin(dvp);
6130 vn_seqc_write_begin(vp);
6134 vop_remove_post(void *ap, int rc)
6136 struct vop_remove_args *a;
6137 struct vnode *dvp, *vp;
6142 vn_seqc_write_end(dvp);
6143 vn_seqc_write_end(vp);
6145 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6146 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
6151 vop_rename_post(void *ap, int rc)
6153 struct vop_rename_args *a = ap;
6158 if (a->a_fdvp == a->a_tdvp) {
6159 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
6161 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
6162 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
6164 hint |= NOTE_EXTEND;
6165 if (a->a_fvp->v_type == VDIR)
6167 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
6169 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
6170 a->a_tvp->v_type == VDIR)
6172 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
6175 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
6177 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
6179 if (a->a_tdvp != a->a_fdvp)
6181 if (a->a_tvp != a->a_fvp)
6189 vop_rmdir_pre(void *ap)
6191 struct vop_rmdir_args *a;
6192 struct vnode *dvp, *vp;
6197 vn_seqc_write_begin(dvp);
6198 vn_seqc_write_begin(vp);
6202 vop_rmdir_post(void *ap, int rc)
6204 struct vop_rmdir_args *a;
6205 struct vnode *dvp, *vp;
6210 vn_seqc_write_end(dvp);
6211 vn_seqc_write_end(vp);
6213 vp->v_vflag |= VV_UNLINKED;
6214 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
6215 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
6220 vop_setattr_pre(void *ap)
6222 struct vop_setattr_args *a;
6227 vn_seqc_write_begin(vp);
6231 vop_setattr_post(void *ap, int rc)
6233 struct vop_setattr_args *a;
6238 vn_seqc_write_end(vp);
6240 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6244 vop_setacl_pre(void *ap)
6246 struct vop_setacl_args *a;
6251 vn_seqc_write_begin(vp);
6255 vop_setacl_post(void *ap, int rc __unused)
6257 struct vop_setacl_args *a;
6262 vn_seqc_write_end(vp);
6266 vop_setextattr_pre(void *ap)
6268 struct vop_setextattr_args *a;
6273 vn_seqc_write_begin(vp);
6277 vop_setextattr_post(void *ap, int rc)
6279 struct vop_setextattr_args *a;
6284 vn_seqc_write_end(vp);
6286 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6290 vop_symlink_pre(void *ap)
6292 struct vop_symlink_args *a;
6297 vn_seqc_write_begin(dvp);
6301 vop_symlink_post(void *ap, int rc)
6303 struct vop_symlink_args *a;
6308 vn_seqc_write_end(dvp);
6310 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6314 vop_open_post(void *ap, int rc)
6316 struct vop_open_args *a = ap;
6319 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
6323 vop_close_post(void *ap, int rc)
6325 struct vop_close_args *a = ap;
6327 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
6328 !VN_IS_DOOMED(a->a_vp))) {
6329 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
6330 NOTE_CLOSE_WRITE : NOTE_CLOSE);
6335 vop_read_post(void *ap, int rc)
6337 struct vop_read_args *a = ap;
6340 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6344 vop_read_pgcache_post(void *ap, int rc)
6346 struct vop_read_pgcache_args *a = ap;
6349 VFS_KNOTE_UNLOCKED(a->a_vp, NOTE_READ);
6353 vop_readdir_post(void *ap, int rc)
6355 struct vop_readdir_args *a = ap;
6358 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6361 static struct knlist fs_knlist;
6364 vfs_event_init(void *arg)
6366 knlist_init_mtx(&fs_knlist, NULL);
6368 /* XXX - correct order? */
6369 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
6372 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
6375 KNOTE_UNLOCKED(&fs_knlist, event);
6378 static int filt_fsattach(struct knote *kn);
6379 static void filt_fsdetach(struct knote *kn);
6380 static int filt_fsevent(struct knote *kn, long hint);
6382 struct filterops fs_filtops = {
6384 .f_attach = filt_fsattach,
6385 .f_detach = filt_fsdetach,
6386 .f_event = filt_fsevent
6390 filt_fsattach(struct knote *kn)
6393 kn->kn_flags |= EV_CLEAR;
6394 knlist_add(&fs_knlist, kn, 0);
6399 filt_fsdetach(struct knote *kn)
6402 knlist_remove(&fs_knlist, kn, 0);
6406 filt_fsevent(struct knote *kn, long hint)
6409 kn->kn_fflags |= kn->kn_sfflags & hint;
6411 return (kn->kn_fflags != 0);
6415 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
6421 error = SYSCTL_IN(req, &vc, sizeof(vc));
6424 if (vc.vc_vers != VFS_CTL_VERS1)
6426 mp = vfs_getvfs(&vc.vc_fsid);
6429 /* ensure that a specific sysctl goes to the right filesystem. */
6430 if (strcmp(vc.vc_fstypename, "*") != 0 &&
6431 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
6435 VCTLTOREQ(&vc, req);
6436 error = VFS_SYSCTL(mp, vc.vc_op, req);
6441 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
6442 NULL, 0, sysctl_vfs_ctl, "",
6446 * Function to initialize a va_filerev field sensibly.
6447 * XXX: Wouldn't a random number make a lot more sense ??
6450 init_va_filerev(void)
6455 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
6458 static int filt_vfsread(struct knote *kn, long hint);
6459 static int filt_vfswrite(struct knote *kn, long hint);
6460 static int filt_vfsvnode(struct knote *kn, long hint);
6461 static void filt_vfsdetach(struct knote *kn);
6462 static struct filterops vfsread_filtops = {
6464 .f_detach = filt_vfsdetach,
6465 .f_event = filt_vfsread
6467 static struct filterops vfswrite_filtops = {
6469 .f_detach = filt_vfsdetach,
6470 .f_event = filt_vfswrite
6472 static struct filterops vfsvnode_filtops = {
6474 .f_detach = filt_vfsdetach,
6475 .f_event = filt_vfsvnode
6479 vfs_knllock(void *arg)
6481 struct vnode *vp = arg;
6483 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
6487 vfs_knlunlock(void *arg)
6489 struct vnode *vp = arg;
6495 vfs_knl_assert_lock(void *arg, int what)
6497 #ifdef DEBUG_VFS_LOCKS
6498 struct vnode *vp = arg;
6500 if (what == LA_LOCKED)
6501 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
6503 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
6508 vfs_kqfilter(struct vop_kqfilter_args *ap)
6510 struct vnode *vp = ap->a_vp;
6511 struct knote *kn = ap->a_kn;
6514 KASSERT(vp->v_type != VFIFO || (kn->kn_filter != EVFILT_READ &&
6515 kn->kn_filter != EVFILT_WRITE),
6516 ("READ/WRITE filter on a FIFO leaked through"));
6517 switch (kn->kn_filter) {
6519 kn->kn_fop = &vfsread_filtops;
6522 kn->kn_fop = &vfswrite_filtops;
6525 kn->kn_fop = &vfsvnode_filtops;
6531 kn->kn_hook = (caddr_t)vp;
6534 if (vp->v_pollinfo == NULL)
6536 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
6538 knlist_add(knl, kn, 0);
6544 * Detach knote from vnode
6547 filt_vfsdetach(struct knote *kn)
6549 struct vnode *vp = (struct vnode *)kn->kn_hook;
6551 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
6552 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
6558 filt_vfsread(struct knote *kn, long hint)
6560 struct vnode *vp = (struct vnode *)kn->kn_hook;
6565 * filesystem is gone, so set the EOF flag and schedule
6566 * the knote for deletion.
6568 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6570 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6575 if (vn_getsize_locked(vp, &size, curthread->td_ucred) != 0)
6579 kn->kn_data = size - kn->kn_fp->f_offset;
6580 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
6587 filt_vfswrite(struct knote *kn, long hint)
6589 struct vnode *vp = (struct vnode *)kn->kn_hook;
6594 * filesystem is gone, so set the EOF flag and schedule
6595 * the knote for deletion.
6597 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
6598 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6606 filt_vfsvnode(struct knote *kn, long hint)
6608 struct vnode *vp = (struct vnode *)kn->kn_hook;
6612 if (kn->kn_sfflags & hint)
6613 kn->kn_fflags |= hint;
6614 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6615 kn->kn_flags |= EV_EOF;
6619 res = (kn->kn_fflags != 0);
6625 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6629 if (dp->d_reclen > ap->a_uio->uio_resid)
6630 return (ENAMETOOLONG);
6631 error = uiomove(dp, dp->d_reclen, ap->a_uio);
6633 if (ap->a_ncookies != NULL) {
6634 if (ap->a_cookies != NULL)
6635 free(ap->a_cookies, M_TEMP);
6636 ap->a_cookies = NULL;
6637 *ap->a_ncookies = 0;
6641 if (ap->a_ncookies == NULL)
6644 KASSERT(ap->a_cookies,
6645 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6647 *ap->a_cookies = realloc(*ap->a_cookies,
6648 (*ap->a_ncookies + 1) * sizeof(uint64_t), M_TEMP, M_WAITOK | M_ZERO);
6649 (*ap->a_cookies)[*ap->a_ncookies] = off;
6650 *ap->a_ncookies += 1;
6655 * The purpose of this routine is to remove granularity from accmode_t,
6656 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6657 * VADMIN and VAPPEND.
6659 * If it returns 0, the caller is supposed to continue with the usual
6660 * access checks using 'accmode' as modified by this routine. If it
6661 * returns nonzero value, the caller is supposed to return that value
6664 * Note that after this routine runs, accmode may be zero.
6667 vfs_unixify_accmode(accmode_t *accmode)
6670 * There is no way to specify explicit "deny" rule using
6671 * file mode or POSIX.1e ACLs.
6673 if (*accmode & VEXPLICIT_DENY) {
6679 * None of these can be translated into usual access bits.
6680 * Also, the common case for NFSv4 ACLs is to not contain
6681 * either of these bits. Caller should check for VWRITE
6682 * on the containing directory instead.
6684 if (*accmode & (VDELETE_CHILD | VDELETE))
6687 if (*accmode & VADMIN_PERMS) {
6688 *accmode &= ~VADMIN_PERMS;
6693 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6694 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6696 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6702 * Clear out a doomed vnode (if any) and replace it with a new one as long
6703 * as the fs is not being unmounted. Return the root vnode to the caller.
6705 static int __noinline
6706 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6712 if (mp->mnt_rootvnode != NULL) {
6714 vp = mp->mnt_rootvnode;
6716 if (!VN_IS_DOOMED(vp)) {
6719 error = vn_lock(vp, flags);
6728 * Clear the old one.
6730 mp->mnt_rootvnode = NULL;
6734 vfs_op_barrier_wait(mp);
6738 error = VFS_CACHEDROOT(mp, flags, vpp);
6741 if (mp->mnt_vfs_ops == 0) {
6743 if (mp->mnt_vfs_ops != 0) {
6747 if (mp->mnt_rootvnode == NULL) {
6749 mp->mnt_rootvnode = *vpp;
6751 if (mp->mnt_rootvnode != *vpp) {
6752 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6753 panic("%s: mismatch between vnode returned "
6754 " by VFS_CACHEDROOT and the one cached "
6756 __func__, *vpp, mp->mnt_rootvnode);
6766 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6768 struct mount_pcpu *mpcpu;
6772 if (!vfs_op_thread_enter(mp, mpcpu))
6773 return (vfs_cache_root_fallback(mp, flags, vpp));
6774 vp = atomic_load_ptr(&mp->mnt_rootvnode);
6775 if (vp == NULL || VN_IS_DOOMED(vp)) {
6776 vfs_op_thread_exit(mp, mpcpu);
6777 return (vfs_cache_root_fallback(mp, flags, vpp));
6780 vfs_op_thread_exit(mp, mpcpu);
6781 error = vn_lock(vp, flags);
6784 return (vfs_cache_root_fallback(mp, flags, vpp));
6791 vfs_cache_root_clear(struct mount *mp)
6796 * ops > 0 guarantees there is nobody who can see this vnode
6798 MPASS(mp->mnt_vfs_ops > 0);
6799 vp = mp->mnt_rootvnode;
6801 vn_seqc_write_begin(vp);
6802 mp->mnt_rootvnode = NULL;
6807 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6810 MPASS(mp->mnt_vfs_ops > 0);
6812 mp->mnt_rootvnode = vp;
6816 * These are helper functions for filesystems to traverse all
6817 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6819 * This interface replaces MNT_VNODE_FOREACH.
6823 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6829 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6830 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6831 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6832 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6833 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6836 if (VN_IS_DOOMED(vp)) {
6843 __mnt_vnode_markerfree_all(mvp, mp);
6844 /* MNT_IUNLOCK(mp); -- done in above function */
6845 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6848 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6849 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6855 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6859 *mvp = vn_alloc_marker(mp);
6863 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6864 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6865 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6868 if (VN_IS_DOOMED(vp)) {
6877 vn_free_marker(*mvp);
6881 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6887 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6895 mtx_assert(MNT_MTX(mp), MA_OWNED);
6897 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6898 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6901 vn_free_marker(*mvp);
6906 * These are helper functions for filesystems to traverse their
6907 * lazy vnodes. See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6910 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6913 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6918 vn_free_marker(*mvp);
6923 * Relock the mp mount vnode list lock with the vp vnode interlock in the
6924 * conventional lock order during mnt_vnode_next_lazy iteration.
6926 * On entry, the mount vnode list lock is held and the vnode interlock is not.
6927 * The list lock is dropped and reacquired. On success, both locks are held.
6928 * On failure, the mount vnode list lock is held but the vnode interlock is
6929 * not, and the procedure may have yielded.
6932 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6936 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6937 TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6938 ("%s: bad marker", __func__));
6939 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6940 ("%s: inappropriate vnode", __func__));
6941 ASSERT_VI_UNLOCKED(vp, __func__);
6942 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6944 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6945 TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6948 * Note we may be racing against vdrop which transitioned the hold
6949 * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
6950 * if we are the only user after we get the interlock we will just
6954 mtx_unlock(&mp->mnt_listmtx);
6956 if (VN_IS_DOOMED(vp)) {
6957 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
6960 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
6962 * There is nothing to do if we are the last user.
6964 if (!refcount_release_if_not_last(&vp->v_holdcnt))
6966 mtx_lock(&mp->mnt_listmtx);
6971 mtx_lock(&mp->mnt_listmtx);
6975 static struct vnode *
6976 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6981 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6982 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6984 vp = TAILQ_NEXT(*mvp, v_lazylist);
6985 while (vp != NULL) {
6986 if (vp->v_type == VMARKER) {
6987 vp = TAILQ_NEXT(vp, v_lazylist);
6991 * See if we want to process the vnode. Note we may encounter a
6992 * long string of vnodes we don't care about and hog the list
6993 * as a result. Check for it and requeue the marker.
6995 VNPASS(!VN_IS_DOOMED(vp), vp);
6996 if (!cb(vp, cbarg)) {
6997 if (!should_yield()) {
6998 vp = TAILQ_NEXT(vp, v_lazylist);
7001 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
7003 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
7005 mtx_unlock(&mp->mnt_listmtx);
7006 kern_yield(PRI_USER);
7007 mtx_lock(&mp->mnt_listmtx);
7011 * Try-lock because this is the wrong lock order.
7013 if (!VI_TRYLOCK(vp) &&
7014 !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
7016 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
7017 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
7018 ("alien vnode on the lazy list %p %p", vp, mp));
7019 VNPASS(vp->v_mount == mp, vp);
7020 VNPASS(!VN_IS_DOOMED(vp), vp);
7023 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
7025 /* Check if we are done */
7027 mtx_unlock(&mp->mnt_listmtx);
7028 mnt_vnode_markerfree_lazy(mvp, mp);
7031 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
7032 mtx_unlock(&mp->mnt_listmtx);
7033 ASSERT_VI_LOCKED(vp, "lazy iter");
7038 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
7043 mtx_lock(&mp->mnt_listmtx);
7044 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
7048 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
7053 if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
7056 *mvp = vn_alloc_marker(mp);
7061 mtx_lock(&mp->mnt_listmtx);
7062 vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
7064 mtx_unlock(&mp->mnt_listmtx);
7065 mnt_vnode_markerfree_lazy(mvp, mp);
7068 TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
7069 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
7073 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
7079 mtx_lock(&mp->mnt_listmtx);
7080 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
7081 mtx_unlock(&mp->mnt_listmtx);
7082 mnt_vnode_markerfree_lazy(mvp, mp);
7086 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
7089 if ((cnp->cn_flags & NOEXECCHECK) != 0) {
7090 cnp->cn_flags &= ~NOEXECCHECK;
7094 return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, curthread));
7098 * Do not use this variant unless you have means other than the hold count
7099 * to prevent the vnode from getting freed.
7102 vn_seqc_write_begin_locked(struct vnode *vp)
7105 ASSERT_VI_LOCKED(vp, __func__);
7106 VNPASS(vp->v_holdcnt > 0, vp);
7107 VNPASS(vp->v_seqc_users >= 0, vp);
7109 if (vp->v_seqc_users == 1)
7110 seqc_sleepable_write_begin(&vp->v_seqc);
7114 vn_seqc_write_begin(struct vnode *vp)
7118 vn_seqc_write_begin_locked(vp);
7123 vn_seqc_write_end_locked(struct vnode *vp)
7126 ASSERT_VI_LOCKED(vp, __func__);
7127 VNPASS(vp->v_seqc_users > 0, vp);
7129 if (vp->v_seqc_users == 0)
7130 seqc_sleepable_write_end(&vp->v_seqc);
7134 vn_seqc_write_end(struct vnode *vp)
7138 vn_seqc_write_end_locked(vp);
7143 * Special case handling for allocating and freeing vnodes.
7145 * The counter remains unchanged on free so that a doomed vnode will
7146 * keep testing as in modify as long as it is accessible with SMR.
7149 vn_seqc_init(struct vnode *vp)
7153 vp->v_seqc_users = 0;
7157 vn_seqc_write_end_free(struct vnode *vp)
7160 VNPASS(seqc_in_modify(vp->v_seqc), vp);
7161 VNPASS(vp->v_seqc_users == 1, vp);
7165 vn_irflag_set_locked(struct vnode *vp, short toset)
7169 ASSERT_VI_LOCKED(vp, __func__);
7170 flags = vn_irflag_read(vp);
7171 VNASSERT((flags & toset) == 0, vp,
7172 ("%s: some of the passed flags already set (have %d, passed %d)\n",
7173 __func__, flags, toset));
7174 atomic_store_short(&vp->v_irflag, flags | toset);
7178 vn_irflag_set(struct vnode *vp, short toset)
7182 vn_irflag_set_locked(vp, toset);
7187 vn_irflag_set_cond_locked(struct vnode *vp, short toset)
7191 ASSERT_VI_LOCKED(vp, __func__);
7192 flags = vn_irflag_read(vp);
7193 atomic_store_short(&vp->v_irflag, flags | toset);
7197 vn_irflag_set_cond(struct vnode *vp, short toset)
7201 vn_irflag_set_cond_locked(vp, toset);
7206 vn_irflag_unset_locked(struct vnode *vp, short tounset)
7210 ASSERT_VI_LOCKED(vp, __func__);
7211 flags = vn_irflag_read(vp);
7212 VNASSERT((flags & tounset) == tounset, vp,
7213 ("%s: some of the passed flags not set (have %d, passed %d)\n",
7214 __func__, flags, tounset));
7215 atomic_store_short(&vp->v_irflag, flags & ~tounset);
7219 vn_irflag_unset(struct vnode *vp, short tounset)
7223 vn_irflag_unset_locked(vp, tounset);
7228 vn_getsize_locked(struct vnode *vp, off_t *size, struct ucred *cred)
7233 ASSERT_VOP_LOCKED(vp, __func__);
7234 error = VOP_GETATTR(vp, &vattr, cred);
7235 if (__predict_true(error == 0)) {
7236 if (vattr.va_size <= OFF_MAX)
7237 *size = vattr.va_size;
7245 vn_getsize(struct vnode *vp, off_t *size, struct ucred *cred)
7249 VOP_LOCK(vp, LK_SHARED);
7250 error = vn_getsize_locked(vp, size, cred);
7257 vn_set_state_validate(struct vnode *vp, __enum_uint8(vstate) state)
7260 switch (vp->v_state) {
7261 case VSTATE_UNINITIALIZED:
7263 case VSTATE_CONSTRUCTED:
7264 case VSTATE_DESTROYING:
7270 case VSTATE_CONSTRUCTED:
7271 ASSERT_VOP_ELOCKED(vp, __func__);
7273 case VSTATE_DESTROYING:
7279 case VSTATE_DESTROYING:
7280 ASSERT_VOP_ELOCKED(vp, __func__);
7290 case VSTATE_UNINITIALIZED:
7298 vn_printf(vp, "invalid state transition %d -> %d\n", vp->v_state, state);
7299 panic("invalid state transition %d -> %d\n", vp->v_state, state);