2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)vfs_subr.c 8.31 (Berkeley) 5/26/95
40 * External virtual filesystem routines
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
47 #include "opt_watchdog.h"
49 #include <sys/param.h>
50 #include <sys/systm.h>
54 #include <sys/capsicum.h>
55 #include <sys/condvar.h>
57 #include <sys/counter.h>
58 #include <sys/dirent.h>
59 #include <sys/event.h>
60 #include <sys/eventhandler.h>
61 #include <sys/extattr.h>
63 #include <sys/fcntl.h>
66 #include <sys/kernel.h>
67 #include <sys/kthread.h>
69 #include <sys/lockf.h>
70 #include <sys/malloc.h>
71 #include <sys/mount.h>
72 #include <sys/namei.h>
73 #include <sys/pctrie.h>
75 #include <sys/reboot.h>
76 #include <sys/refcount.h>
77 #include <sys/rwlock.h>
78 #include <sys/sched.h>
79 #include <sys/sleepqueue.h>
83 #include <sys/sysctl.h>
84 #include <sys/syslog.h>
85 #include <sys/vmmeter.h>
86 #include <sys/vnode.h>
87 #include <sys/watchdog.h>
89 #include <machine/stdarg.h>
91 #include <security/mac/mac_framework.h>
94 #include <vm/vm_object.h>
95 #include <vm/vm_extern.h>
97 #include <vm/vm_map.h>
98 #include <vm/vm_page.h>
99 #include <vm/vm_kern.h>
106 static void delmntque(struct vnode *vp);
107 static int flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
108 int slpflag, int slptimeo);
109 static void syncer_shutdown(void *arg, int howto);
110 static int vtryrecycle(struct vnode *vp);
111 static void v_init_counters(struct vnode *);
112 static void vn_seqc_init(struct vnode *);
113 static void vn_seqc_write_end_free(struct vnode *vp);
114 static void vgonel(struct vnode *);
115 static bool vhold_recycle_free(struct vnode *);
116 static void vdropl_recycle(struct vnode *vp);
117 static void vdrop_recycle(struct vnode *vp);
118 static void vfs_knllock(void *arg);
119 static void vfs_knlunlock(void *arg);
120 static void vfs_knl_assert_lock(void *arg, int what);
121 static void destroy_vpollinfo(struct vpollinfo *vi);
122 static int v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
123 daddr_t startlbn, daddr_t endlbn);
124 static void vnlru_recalc(void);
127 * Number of vnodes in existence. Increased whenever getnewvnode()
128 * allocates a new vnode, decreased in vdropl() for VIRF_DOOMED vnode.
130 static u_long __exclusive_cache_line numvnodes;
132 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
133 "Number of vnodes in existence");
135 static counter_u64_t vnodes_created;
136 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
137 "Number of vnodes created by getnewvnode");
140 * Conversion tables for conversion from vnode types to inode formats
143 enum vtype iftovt_tab[16] = {
144 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
145 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
147 int vttoif_tab[10] = {
148 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
149 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
153 * List of allocates vnodes in the system.
155 static TAILQ_HEAD(freelst, vnode) vnode_list;
156 static struct vnode *vnode_list_free_marker;
157 static struct vnode *vnode_list_reclaim_marker;
160 * "Free" vnode target. Free vnodes are rarely completely free, but are
161 * just ones that are cheap to recycle. Usually they are for files which
162 * have been stat'd but not read; these usually have inode and namecache
163 * data attached to them. This target is the preferred minimum size of a
164 * sub-cache consisting mostly of such files. The system balances the size
165 * of this sub-cache with its complement to try to prevent either from
166 * thrashing while the other is relatively inactive. The targets express
167 * a preference for the best balance.
169 * "Above" this target there are 2 further targets (watermarks) related
170 * to recyling of free vnodes. In the best-operating case, the cache is
171 * exactly full, the free list has size between vlowat and vhiwat above the
172 * free target, and recycling from it and normal use maintains this state.
173 * Sometimes the free list is below vlowat or even empty, but this state
174 * is even better for immediate use provided the cache is not full.
175 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
176 * ones) to reach one of these states. The watermarks are currently hard-
177 * coded as 4% and 9% of the available space higher. These and the default
178 * of 25% for wantfreevnodes are too large if the memory size is large.
179 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
180 * whenever vnlru_proc() becomes active.
182 static long wantfreevnodes;
183 static long __exclusive_cache_line freevnodes;
184 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
185 &freevnodes, 0, "Number of \"free\" vnodes");
186 static long freevnodes_old;
188 static counter_u64_t recycles_count;
189 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
190 "Number of vnodes recycled to meet vnode cache targets");
192 static counter_u64_t recycles_free_count;
193 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD, &recycles_free_count,
194 "Number of free vnodes recycled to meet vnode cache targets");
196 static counter_u64_t deferred_inact;
197 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, deferred_inact, CTLFLAG_RD, &deferred_inact,
198 "Number of times inactive processing was deferred");
200 /* To keep more than one thread at a time from running vfs_getnewfsid */
201 static struct mtx mntid_mtx;
204 * Lock for any access to the following:
209 static struct mtx __exclusive_cache_line vnode_list_mtx;
211 /* Publicly exported FS */
212 struct nfs_public nfs_pub;
214 static uma_zone_t buf_trie_zone;
215 static smr_t buf_trie_smr;
217 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
218 static uma_zone_t vnode_zone;
219 MALLOC_DEFINE(M_VNODEPOLL, "VN POLL", "vnode poll");
221 __read_frequently smr_t vfs_smr;
224 * The workitem queue.
226 * It is useful to delay writes of file data and filesystem metadata
227 * for tens of seconds so that quickly created and deleted files need
228 * not waste disk bandwidth being created and removed. To realize this,
229 * we append vnodes to a "workitem" queue. When running with a soft
230 * updates implementation, most pending metadata dependencies should
231 * not wait for more than a few seconds. Thus, mounted on block devices
232 * are delayed only about a half the time that file data is delayed.
233 * Similarly, directory updates are more critical, so are only delayed
234 * about a third the time that file data is delayed. Thus, there are
235 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
236 * one each second (driven off the filesystem syncer process). The
237 * syncer_delayno variable indicates the next queue that is to be processed.
238 * Items that need to be processed soon are placed in this queue:
240 * syncer_workitem_pending[syncer_delayno]
242 * A delay of fifteen seconds is done by placing the request fifteen
243 * entries later in the queue:
245 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
248 static int syncer_delayno;
249 static long syncer_mask;
250 LIST_HEAD(synclist, bufobj);
251 static struct synclist *syncer_workitem_pending;
253 * The sync_mtx protects:
258 * syncer_workitem_pending
259 * syncer_worklist_len
262 static struct mtx sync_mtx;
263 static struct cv sync_wakeup;
265 #define SYNCER_MAXDELAY 32
266 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
267 static int syncdelay = 30; /* max time to delay syncing data */
268 static int filedelay = 30; /* time to delay syncing files */
269 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
270 "Time to delay syncing files (in seconds)");
271 static int dirdelay = 29; /* time to delay syncing directories */
272 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
273 "Time to delay syncing directories (in seconds)");
274 static int metadelay = 28; /* time to delay syncing metadata */
275 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
276 "Time to delay syncing metadata (in seconds)");
277 static int rushjob; /* number of slots to run ASAP */
278 static int stat_rush_requests; /* number of times I/O speeded up */
279 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
280 "Number of times I/O speeded up (rush requests)");
282 #define VDBATCH_SIZE 8
287 struct vnode *tab[VDBATCH_SIZE];
289 DPCPU_DEFINE_STATIC(struct vdbatch, vd);
291 static void vdbatch_dequeue(struct vnode *vp);
294 * When shutting down the syncer, run it at four times normal speed.
296 #define SYNCER_SHUTDOWN_SPEEDUP 4
297 static int sync_vnode_count;
298 static int syncer_worklist_len;
299 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
302 /* Target for maximum number of vnodes. */
303 u_long desiredvnodes;
304 static u_long gapvnodes; /* gap between wanted and desired */
305 static u_long vhiwat; /* enough extras after expansion */
306 static u_long vlowat; /* minimal extras before expansion */
307 static u_long vstir; /* nonzero to stir non-free vnodes */
308 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
310 static u_long vnlru_read_freevnodes(void);
313 * Note that no attempt is made to sanitize these parameters.
316 sysctl_maxvnodes(SYSCTL_HANDLER_ARGS)
322 error = sysctl_handle_long(oidp, &val, 0, req);
323 if (error != 0 || req->newptr == NULL)
326 if (val == desiredvnodes)
328 mtx_lock(&vnode_list_mtx);
330 wantfreevnodes = desiredvnodes / 4;
332 mtx_unlock(&vnode_list_mtx);
334 * XXX There is no protection against multiple threads changing
335 * desiredvnodes at the same time. Locking above only helps vnlru and
338 vfs_hash_changesize(desiredvnodes);
339 cache_changesize(desiredvnodes);
343 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
344 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
345 "LU", "Target for maximum number of vnodes");
348 sysctl_wantfreevnodes(SYSCTL_HANDLER_ARGS)
353 val = wantfreevnodes;
354 error = sysctl_handle_long(oidp, &val, 0, req);
355 if (error != 0 || req->newptr == NULL)
358 if (val == wantfreevnodes)
360 mtx_lock(&vnode_list_mtx);
361 wantfreevnodes = val;
363 mtx_unlock(&vnode_list_mtx);
367 SYSCTL_PROC(_vfs, OID_AUTO, wantfreevnodes,
368 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
369 "LU", "Target for minimum number of \"free\" vnodes");
371 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
372 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
373 static int vnlru_nowhere;
374 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
375 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
378 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
383 unsigned long ndflags;
386 if (req->newptr == NULL)
388 if (req->newlen >= PATH_MAX)
391 buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
392 error = SYSCTL_IN(req, buf, req->newlen);
396 buf[req->newlen] = '\0';
398 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | SAVENAME;
399 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
400 if ((error = namei(&nd)) != 0)
404 if (VN_IS_DOOMED(vp)) {
406 * This vnode is being recycled. Return != 0 to let the caller
407 * know that the sysctl had no effect. Return EAGAIN because a
408 * subsequent call will likely succeed (since namei will create
409 * a new vnode if necessary)
415 counter_u64_add(recycles_count, 1);
425 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
427 struct thread *td = curthread;
433 if (req->newptr == NULL)
436 error = sysctl_handle_int(oidp, &fd, 0, req);
439 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
444 error = vn_lock(vp, LK_EXCLUSIVE);
448 counter_u64_add(recycles_count, 1);
456 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
457 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
458 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
459 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
460 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
461 sysctl_ftry_reclaim_vnode, "I",
462 "Try to reclaim a vnode by its file descriptor");
464 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
468 * Support for the bufobj clean & dirty pctrie.
471 buf_trie_alloc(struct pctrie *ptree)
473 return (uma_zalloc_smr(buf_trie_zone, M_NOWAIT));
477 buf_trie_free(struct pctrie *ptree, void *node)
479 uma_zfree_smr(buf_trie_zone, node);
481 PCTRIE_DEFINE_SMR(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free,
485 * Initialize the vnode management data structures.
487 * Reevaluate the following cap on the number of vnodes after the physical
488 * memory size exceeds 512GB. In the limit, as the physical memory size
489 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
491 #ifndef MAXVNODES_MAX
492 #define MAXVNODES_MAX (512UL * 1024 * 1024 / 64) /* 8M */
495 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
497 static struct vnode *
498 vn_alloc_marker(struct mount *mp)
502 vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
503 vp->v_type = VMARKER;
510 vn_free_marker(struct vnode *vp)
513 MPASS(vp->v_type == VMARKER);
514 free(vp, M_VNODE_MARKER);
519 vnode_ctor(void *mem, int size, void *arg __unused, int flags __unused)
521 kasan_mark(mem, size, roundup2(size, UMA_ALIGN_PTR + 1), 0);
526 vnode_dtor(void *mem, int size, void *arg __unused)
528 size_t end1, end2, off1, off2;
530 _Static_assert(offsetof(struct vnode, v_vnodelist) <
531 offsetof(struct vnode, v_dbatchcpu),
532 "KASAN marks require updating");
534 off1 = offsetof(struct vnode, v_vnodelist);
535 off2 = offsetof(struct vnode, v_dbatchcpu);
536 end1 = off1 + sizeof(((struct vnode *)NULL)->v_vnodelist);
537 end2 = off2 + sizeof(((struct vnode *)NULL)->v_dbatchcpu);
540 * Access to the v_vnodelist and v_dbatchcpu fields are permitted even
541 * after the vnode has been freed. Try to get some KASAN coverage by
542 * marking everything except those two fields as invalid. Because
543 * KASAN's tracking is not byte-granular, any preceding fields sharing
544 * the same 8-byte aligned word must also be marked valid.
547 /* Handle the area from the start until v_vnodelist... */
548 off1 = rounddown2(off1, KASAN_SHADOW_SCALE);
549 kasan_mark(mem, off1, off1, KASAN_UMA_FREED);
551 /* ... then the area between v_vnodelist and v_dbatchcpu ... */
552 off1 = roundup2(end1, KASAN_SHADOW_SCALE);
553 off2 = rounddown2(off2, KASAN_SHADOW_SCALE);
555 kasan_mark((void *)((char *)mem + off1), off2 - off1,
556 off2 - off1, KASAN_UMA_FREED);
558 /* ... and finally the area from v_dbatchcpu to the end. */
559 off2 = roundup2(end2, KASAN_SHADOW_SCALE);
560 kasan_mark((void *)((char *)mem + off2), size - off2, size - off2,
566 * Initialize a vnode as it first enters the zone.
569 vnode_init(void *mem, int size, int flags)
578 vp->v_vnlock = &vp->v_lock;
579 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
581 * By default, don't allow shared locks unless filesystems opt-in.
583 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
584 LK_NOSHARE | LK_IS_VNODE);
588 bufobj_init(&vp->v_bufobj, vp);
590 * Initialize namecache.
592 cache_vnode_init(vp);
594 * Initialize rangelocks.
596 rangelock_init(&vp->v_rl);
598 vp->v_dbatchcpu = NOCPU;
601 * Check vhold_recycle_free for an explanation.
603 vp->v_holdcnt = VHOLD_NO_SMR;
605 mtx_lock(&vnode_list_mtx);
606 TAILQ_INSERT_BEFORE(vnode_list_free_marker, vp, v_vnodelist);
607 mtx_unlock(&vnode_list_mtx);
612 * Free a vnode when it is cleared from the zone.
615 vnode_fini(void *mem, int size)
622 mtx_lock(&vnode_list_mtx);
623 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
624 mtx_unlock(&vnode_list_mtx);
625 rangelock_destroy(&vp->v_rl);
626 lockdestroy(vp->v_vnlock);
627 mtx_destroy(&vp->v_interlock);
629 rw_destroy(BO_LOCKPTR(bo));
631 kasan_mark(mem, size, size, 0);
635 * Provide the size of NFS nclnode and NFS fh for calculation of the
636 * vnode memory consumption. The size is specified directly to
637 * eliminate dependency on NFS-private header.
639 * Other filesystems may use bigger or smaller (like UFS and ZFS)
640 * private inode data, but the NFS-based estimation is ample enough.
641 * Still, we care about differences in the size between 64- and 32-bit
644 * Namecache structure size is heuristically
645 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
648 #define NFS_NCLNODE_SZ (528 + 64)
651 #define NFS_NCLNODE_SZ (360 + 32)
656 vntblinit(void *dummy __unused)
661 int cpu, physvnodes, virtvnodes;
665 * Desiredvnodes is a function of the physical memory size and the
666 * kernel's heap size. Generally speaking, it scales with the
667 * physical memory size. The ratio of desiredvnodes to the physical
668 * memory size is 1:16 until desiredvnodes exceeds 98,304.
670 * marginal ratio of desiredvnodes to the physical memory size is
671 * 1:64. However, desiredvnodes is limited by the kernel's heap
672 * size. The memory required by desiredvnodes vnodes and vm objects
673 * must not exceed 1/10th of the kernel's heap size.
675 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
676 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
677 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
678 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
679 desiredvnodes = min(physvnodes, virtvnodes);
680 if (desiredvnodes > MAXVNODES_MAX) {
682 printf("Reducing kern.maxvnodes %lu -> %lu\n",
683 desiredvnodes, MAXVNODES_MAX);
684 desiredvnodes = MAXVNODES_MAX;
686 wantfreevnodes = desiredvnodes / 4;
687 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
688 TAILQ_INIT(&vnode_list);
689 mtx_init(&vnode_list_mtx, "vnode_list", NULL, MTX_DEF);
691 * The lock is taken to appease WITNESS.
693 mtx_lock(&vnode_list_mtx);
695 mtx_unlock(&vnode_list_mtx);
696 vnode_list_free_marker = vn_alloc_marker(NULL);
697 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_free_marker, v_vnodelist);
698 vnode_list_reclaim_marker = vn_alloc_marker(NULL);
699 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_reclaim_marker, v_vnodelist);
708 vnode_zone = uma_zcreate("VNODE", sizeof(struct vnode), ctor, dtor,
709 vnode_init, vnode_fini, UMA_ALIGN_PTR, UMA_ZONE_NOKASAN);
710 uma_zone_set_smr(vnode_zone, vfs_smr);
713 * Preallocate enough nodes to support one-per buf so that
714 * we can not fail an insert. reassignbuf() callers can not
715 * tolerate the insertion failure.
717 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
718 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
719 UMA_ZONE_NOFREE | UMA_ZONE_SMR);
720 buf_trie_smr = uma_zone_get_smr(buf_trie_zone);
721 uma_prealloc(buf_trie_zone, nbuf);
723 vnodes_created = counter_u64_alloc(M_WAITOK);
724 recycles_count = counter_u64_alloc(M_WAITOK);
725 recycles_free_count = counter_u64_alloc(M_WAITOK);
726 deferred_inact = counter_u64_alloc(M_WAITOK);
729 * Initialize the filesystem syncer.
731 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
733 syncer_maxdelay = syncer_mask + 1;
734 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
735 cv_init(&sync_wakeup, "syncer");
736 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
741 vd = DPCPU_ID_PTR((cpu), vd);
742 bzero(vd, sizeof(*vd));
743 mtx_init(&vd->lock, "vdbatch", NULL, MTX_DEF);
746 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
749 * Mark a mount point as busy. Used to synchronize access and to delay
750 * unmounting. Eventually, mountlist_mtx is not released on failure.
752 * vfs_busy() is a custom lock, it can block the caller.
753 * vfs_busy() only sleeps if the unmount is active on the mount point.
754 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
755 * vnode belonging to mp.
757 * Lookup uses vfs_busy() to traverse mount points.
759 * / vnode lock A / vnode lock (/var) D
760 * /var vnode lock B /log vnode lock(/var/log) E
761 * vfs_busy lock C vfs_busy lock F
763 * Within each file system, the lock order is C->A->B and F->D->E.
765 * When traversing across mounts, the system follows that lock order:
771 * The lookup() process for namei("/var") illustrates the process:
772 * VOP_LOOKUP() obtains B while A is held
773 * vfs_busy() obtains a shared lock on F while A and B are held
774 * vput() releases lock on B
775 * vput() releases lock on A
776 * VFS_ROOT() obtains lock on D while shared lock on F is held
777 * vfs_unbusy() releases shared lock on F
778 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
779 * Attempt to lock A (instead of vp_crossmp) while D is held would
780 * violate the global order, causing deadlocks.
782 * dounmount() locks B while F is drained.
785 vfs_busy(struct mount *mp, int flags)
787 struct mount_pcpu *mpcpu;
789 MPASS((flags & ~MBF_MASK) == 0);
790 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
792 if (vfs_op_thread_enter(mp, mpcpu)) {
793 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
794 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
795 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
796 vfs_mp_count_add_pcpu(mpcpu, ref, 1);
797 vfs_mp_count_add_pcpu(mpcpu, lockref, 1);
798 vfs_op_thread_exit(mp, mpcpu);
799 if (flags & MBF_MNTLSTLOCK)
800 mtx_unlock(&mountlist_mtx);
805 vfs_assert_mount_counters(mp);
808 * If mount point is currently being unmounted, sleep until the
809 * mount point fate is decided. If thread doing the unmounting fails,
810 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
811 * that this mount point has survived the unmount attempt and vfs_busy
812 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
813 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
814 * about to be really destroyed. vfs_busy needs to release its
815 * reference on the mount point in this case and return with ENOENT,
816 * telling the caller that mount mount it tried to busy is no longer
819 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
820 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
823 CTR1(KTR_VFS, "%s: failed busying before sleeping",
827 if (flags & MBF_MNTLSTLOCK)
828 mtx_unlock(&mountlist_mtx);
829 mp->mnt_kern_flag |= MNTK_MWAIT;
830 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
831 if (flags & MBF_MNTLSTLOCK)
832 mtx_lock(&mountlist_mtx);
835 if (flags & MBF_MNTLSTLOCK)
836 mtx_unlock(&mountlist_mtx);
843 * Free a busy filesystem.
846 vfs_unbusy(struct mount *mp)
848 struct mount_pcpu *mpcpu;
851 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
853 if (vfs_op_thread_enter(mp, mpcpu)) {
854 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
855 vfs_mp_count_sub_pcpu(mpcpu, lockref, 1);
856 vfs_mp_count_sub_pcpu(mpcpu, ref, 1);
857 vfs_op_thread_exit(mp, mpcpu);
862 vfs_assert_mount_counters(mp);
864 c = --mp->mnt_lockref;
865 if (mp->mnt_vfs_ops == 0) {
866 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
871 vfs_dump_mount_counters(mp);
872 if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
873 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
874 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
875 mp->mnt_kern_flag &= ~MNTK_DRAINING;
876 wakeup(&mp->mnt_lockref);
882 * Lookup a mount point by filesystem identifier.
885 vfs_getvfs(fsid_t *fsid)
889 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
890 mtx_lock(&mountlist_mtx);
891 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
892 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
894 mtx_unlock(&mountlist_mtx);
898 mtx_unlock(&mountlist_mtx);
899 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
900 return ((struct mount *) 0);
904 * Lookup a mount point by filesystem identifier, busying it before
907 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
908 * cache for popular filesystem identifiers. The cache is lockess, using
909 * the fact that struct mount's are never freed. In worst case we may
910 * get pointer to unmounted or even different filesystem, so we have to
911 * check what we got, and go slow way if so.
914 vfs_busyfs(fsid_t *fsid)
916 #define FSID_CACHE_SIZE 256
917 typedef struct mount * volatile vmp_t;
918 static vmp_t cache[FSID_CACHE_SIZE];
923 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
924 hash = fsid->val[0] ^ fsid->val[1];
925 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
927 if (mp == NULL || fsidcmp(&mp->mnt_stat.f_fsid, fsid) != 0)
929 if (vfs_busy(mp, 0) != 0) {
933 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0)
939 mtx_lock(&mountlist_mtx);
940 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
941 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
942 error = vfs_busy(mp, MBF_MNTLSTLOCK);
945 mtx_unlock(&mountlist_mtx);
952 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
953 mtx_unlock(&mountlist_mtx);
954 return ((struct mount *) 0);
958 * Check if a user can access privileged mount options.
961 vfs_suser(struct mount *mp, struct thread *td)
965 if (jailed(td->td_ucred)) {
967 * If the jail of the calling thread lacks permission for
968 * this type of file system, deny immediately.
970 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
974 * If the file system was mounted outside the jail of the
975 * calling thread, deny immediately.
977 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
982 * If file system supports delegated administration, we don't check
983 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
984 * by the file system itself.
985 * If this is not the user that did original mount, we check for
986 * the PRIV_VFS_MOUNT_OWNER privilege.
988 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
989 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
990 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
997 * Get a new unique fsid. Try to make its val[0] unique, since this value
998 * will be used to create fake device numbers for stat(). Also try (but
999 * not so hard) make its val[0] unique mod 2^16, since some emulators only
1000 * support 16-bit device numbers. We end up with unique val[0]'s for the
1001 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
1003 * Keep in mind that several mounts may be running in parallel. Starting
1004 * the search one past where the previous search terminated is both a
1005 * micro-optimization and a defense against returning the same fsid to
1009 vfs_getnewfsid(struct mount *mp)
1011 static uint16_t mntid_base;
1016 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
1017 mtx_lock(&mntid_mtx);
1018 mtype = mp->mnt_vfc->vfc_typenum;
1019 tfsid.val[1] = mtype;
1020 mtype = (mtype & 0xFF) << 24;
1022 tfsid.val[0] = makedev(255,
1023 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
1025 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
1029 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
1030 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
1031 mtx_unlock(&mntid_mtx);
1035 * Knob to control the precision of file timestamps:
1037 * 0 = seconds only; nanoseconds zeroed.
1038 * 1 = seconds and nanoseconds, accurate within 1/HZ.
1039 * 2 = seconds and nanoseconds, truncated to microseconds.
1040 * >=3 = seconds and nanoseconds, maximum precision.
1042 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
1044 static int timestamp_precision = TSP_USEC;
1045 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
1046 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
1047 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
1048 "3+: sec + ns (max. precision))");
1051 * Get a current timestamp.
1054 vfs_timestamp(struct timespec *tsp)
1058 switch (timestamp_precision) {
1060 tsp->tv_sec = time_second;
1068 TIMEVAL_TO_TIMESPEC(&tv, tsp);
1078 * Set vnode attributes to VNOVAL
1081 vattr_null(struct vattr *vap)
1084 vap->va_type = VNON;
1085 vap->va_size = VNOVAL;
1086 vap->va_bytes = VNOVAL;
1087 vap->va_mode = VNOVAL;
1088 vap->va_nlink = VNOVAL;
1089 vap->va_uid = VNOVAL;
1090 vap->va_gid = VNOVAL;
1091 vap->va_fsid = VNOVAL;
1092 vap->va_fileid = VNOVAL;
1093 vap->va_blocksize = VNOVAL;
1094 vap->va_rdev = VNOVAL;
1095 vap->va_atime.tv_sec = VNOVAL;
1096 vap->va_atime.tv_nsec = VNOVAL;
1097 vap->va_mtime.tv_sec = VNOVAL;
1098 vap->va_mtime.tv_nsec = VNOVAL;
1099 vap->va_ctime.tv_sec = VNOVAL;
1100 vap->va_ctime.tv_nsec = VNOVAL;
1101 vap->va_birthtime.tv_sec = VNOVAL;
1102 vap->va_birthtime.tv_nsec = VNOVAL;
1103 vap->va_flags = VNOVAL;
1104 vap->va_gen = VNOVAL;
1105 vap->va_vaflags = 0;
1109 * Try to reduce the total number of vnodes.
1111 * This routine (and its user) are buggy in at least the following ways:
1112 * - all parameters were picked years ago when RAM sizes were significantly
1114 * - it can pick vnodes based on pages used by the vm object, but filesystems
1115 * like ZFS don't use it making the pick broken
1116 * - since ZFS has its own aging policy it gets partially combated by this one
1117 * - a dedicated method should be provided for filesystems to let them decide
1118 * whether the vnode should be recycled
1120 * This routine is called when we have too many vnodes. It attempts
1121 * to free <count> vnodes and will potentially free vnodes that still
1122 * have VM backing store (VM backing store is typically the cause
1123 * of a vnode blowout so we want to do this). Therefore, this operation
1124 * is not considered cheap.
1126 * A number of conditions may prevent a vnode from being reclaimed.
1127 * the buffer cache may have references on the vnode, a directory
1128 * vnode may still have references due to the namei cache representing
1129 * underlying files, or the vnode may be in active use. It is not
1130 * desirable to reuse such vnodes. These conditions may cause the
1131 * number of vnodes to reach some minimum value regardless of what
1132 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
1134 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1135 * entries if this argument is strue
1136 * @param trigger Only reclaim vnodes with fewer than this many resident
1138 * @param target How many vnodes to reclaim.
1139 * @return The number of vnodes that were reclaimed.
1142 vlrureclaim(bool reclaim_nc_src, int trigger, u_long target)
1144 struct vnode *vp, *mvp;
1146 struct vm_object *object;
1150 mtx_assert(&vnode_list_mtx, MA_OWNED);
1155 mvp = vnode_list_reclaim_marker;
1158 while (done < target) {
1159 vp = TAILQ_NEXT(vp, v_vnodelist);
1160 if (__predict_false(vp == NULL))
1163 if (__predict_false(vp->v_type == VMARKER))
1167 * If it's been deconstructed already, it's still
1168 * referenced, or it exceeds the trigger, skip it.
1169 * Also skip free vnodes. We are trying to make space
1170 * to expand the free list, not reduce it.
1172 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1173 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)))
1176 if (vp->v_type == VBAD || vp->v_type == VNON)
1179 object = atomic_load_ptr(&vp->v_object);
1180 if (object == NULL || object->resident_page_count > trigger) {
1185 * Handle races against vnode allocation. Filesystems lock the
1186 * vnode some time after it gets returned from getnewvnode,
1187 * despite type and hold count being manipulated earlier.
1188 * Resorting to checking v_mount restores guarantees present
1189 * before the global list was reworked to contain all vnodes.
1191 if (!VI_TRYLOCK(vp))
1193 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1197 if (vp->v_mount == NULL) {
1203 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1204 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1205 mtx_unlock(&vnode_list_mtx);
1207 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1209 goto next_iter_unlocked;
1211 if (VOP_LOCK(vp, LK_EXCLUSIVE|LK_NOWAIT) != 0) {
1213 vn_finished_write(mp);
1214 goto next_iter_unlocked;
1218 if (vp->v_usecount > 0 ||
1219 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1220 (vp->v_object != NULL && vp->v_object->handle == vp &&
1221 vp->v_object->resident_page_count > trigger)) {
1224 vn_finished_write(mp);
1225 goto next_iter_unlocked;
1227 counter_u64_add(recycles_count, 1);
1231 vn_finished_write(mp);
1235 kern_yield(PRI_USER);
1236 mtx_lock(&vnode_list_mtx);
1239 MPASS(vp->v_type != VMARKER);
1240 if (!should_yield())
1242 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1243 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1244 mtx_unlock(&vnode_list_mtx);
1245 kern_yield(PRI_USER);
1246 mtx_lock(&vnode_list_mtx);
1249 if (done == 0 && !retried) {
1250 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1251 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1258 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1259 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1261 "limit on vnode free requests per call to the vnlru_free routine");
1264 * Attempt to reduce the free list by the requested amount.
1267 vnlru_free_impl(int count, struct vfsops *mnt_op, struct vnode *mvp)
1273 mtx_assert(&vnode_list_mtx, MA_OWNED);
1274 if (count > max_vnlru_free)
1275 count = max_vnlru_free;
1282 vp = TAILQ_NEXT(vp, v_vnodelist);
1283 if (__predict_false(vp == NULL)) {
1284 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1285 TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1288 if (__predict_false(vp->v_type == VMARKER))
1290 if (vp->v_holdcnt > 0)
1293 * Don't recycle if our vnode is from different type
1294 * of mount point. Note that mp is type-safe, the
1295 * check does not reach unmapped address even if
1296 * vnode is reclaimed.
1298 if (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1299 mp->mnt_op != mnt_op) {
1302 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1305 if (!vhold_recycle_free(vp))
1307 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1308 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1309 mtx_unlock(&vnode_list_mtx);
1310 if (vtryrecycle(vp) == 0)
1312 mtx_lock(&vnode_list_mtx);
1315 return (ocount - count);
1319 vnlru_free_locked(int count)
1322 mtx_assert(&vnode_list_mtx, MA_OWNED);
1323 return (vnlru_free_impl(count, NULL, vnode_list_free_marker));
1327 vnlru_free_vfsops(int count, struct vfsops *mnt_op, struct vnode *mvp)
1330 MPASS(mnt_op != NULL);
1332 VNPASS(mvp->v_type == VMARKER, mvp);
1333 mtx_lock(&vnode_list_mtx);
1334 vnlru_free_impl(count, mnt_op, mvp);
1335 mtx_unlock(&vnode_list_mtx);
1339 * Temporary binary compat, don't use. Call vnlru_free_vfsops instead.
1342 vnlru_free(int count, struct vfsops *mnt_op)
1348 mtx_lock(&vnode_list_mtx);
1349 mvp = vnode_list_free_marker;
1350 if (vnlru_free_impl(count, mnt_op, mvp) == 0) {
1352 * It is possible the marker was moved over eligible vnodes by
1353 * callers which filtered by different ops. If so, start from
1356 if (vnlru_read_freevnodes() > 0) {
1357 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1358 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1360 vnlru_free_impl(count, mnt_op, mvp);
1362 mtx_unlock(&vnode_list_mtx);
1366 vnlru_alloc_marker(void)
1370 mvp = vn_alloc_marker(NULL);
1371 mtx_lock(&vnode_list_mtx);
1372 TAILQ_INSERT_BEFORE(vnode_list_free_marker, mvp, v_vnodelist);
1373 mtx_unlock(&vnode_list_mtx);
1378 vnlru_free_marker(struct vnode *mvp)
1380 mtx_lock(&vnode_list_mtx);
1381 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1382 mtx_unlock(&vnode_list_mtx);
1383 vn_free_marker(mvp);
1390 mtx_assert(&vnode_list_mtx, MA_OWNED);
1391 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1392 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1393 vlowat = vhiwat / 2;
1397 * Attempt to recycle vnodes in a context that is always safe to block.
1398 * Calling vlrurecycle() from the bowels of filesystem code has some
1399 * interesting deadlock problems.
1401 static struct proc *vnlruproc;
1402 static int vnlruproc_sig;
1405 * The main freevnodes counter is only updated when threads requeue their vnode
1406 * batches. CPUs are conditionally walked to compute a more accurate total.
1408 * Limit how much of a slop are we willing to tolerate. Note: the actual value
1409 * at any given moment can still exceed slop, but it should not be by significant
1410 * margin in practice.
1412 #define VNLRU_FREEVNODES_SLOP 128
1414 static __inline void
1415 vfs_freevnodes_inc(void)
1425 static __inline void
1426 vfs_freevnodes_dec(void)
1437 vnlru_read_freevnodes(void)
1443 mtx_assert(&vnode_list_mtx, MA_OWNED);
1444 if (freevnodes > freevnodes_old)
1445 slop = freevnodes - freevnodes_old;
1447 slop = freevnodes_old - freevnodes;
1448 if (slop < VNLRU_FREEVNODES_SLOP)
1449 return (freevnodes >= 0 ? freevnodes : 0);
1450 freevnodes_old = freevnodes;
1452 vd = DPCPU_ID_PTR((cpu), vd);
1453 freevnodes_old += vd->freevnodes;
1455 return (freevnodes_old >= 0 ? freevnodes_old : 0);
1459 vnlru_under(u_long rnumvnodes, u_long limit)
1461 u_long rfreevnodes, space;
1463 if (__predict_false(rnumvnodes > desiredvnodes))
1466 space = desiredvnodes - rnumvnodes;
1467 if (space < limit) {
1468 rfreevnodes = vnlru_read_freevnodes();
1469 if (rfreevnodes > wantfreevnodes)
1470 space += rfreevnodes - wantfreevnodes;
1472 return (space < limit);
1476 vnlru_under_unlocked(u_long rnumvnodes, u_long limit)
1478 long rfreevnodes, space;
1480 if (__predict_false(rnumvnodes > desiredvnodes))
1483 space = desiredvnodes - rnumvnodes;
1484 if (space < limit) {
1485 rfreevnodes = atomic_load_long(&freevnodes);
1486 if (rfreevnodes > wantfreevnodes)
1487 space += rfreevnodes - wantfreevnodes;
1489 return (space < limit);
1496 mtx_assert(&vnode_list_mtx, MA_OWNED);
1497 if (vnlruproc_sig == 0) {
1506 u_long rnumvnodes, rfreevnodes, target;
1507 unsigned long onumvnodes;
1508 int done, force, trigger, usevnodes;
1509 bool reclaim_nc_src, want_reread;
1511 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1512 SHUTDOWN_PRI_FIRST);
1515 want_reread = false;
1517 kproc_suspend_check(vnlruproc);
1518 mtx_lock(&vnode_list_mtx);
1519 rnumvnodes = atomic_load_long(&numvnodes);
1522 force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1523 want_reread = false;
1527 * If numvnodes is too large (due to desiredvnodes being
1528 * adjusted using its sysctl, or emergency growth), first
1529 * try to reduce it by discarding from the free list.
1531 if (rnumvnodes > desiredvnodes) {
1532 vnlru_free_locked(rnumvnodes - desiredvnodes);
1533 rnumvnodes = atomic_load_long(&numvnodes);
1536 * Sleep if the vnode cache is in a good state. This is
1537 * when it is not over-full and has space for about a 4%
1538 * or 9% expansion (by growing its size or inexcessively
1539 * reducing its free list). Otherwise, try to reclaim
1540 * space for a 10% expansion.
1542 if (vstir && force == 0) {
1546 if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1548 wakeup(&vnlruproc_sig);
1549 msleep(vnlruproc, &vnode_list_mtx,
1550 PVFS|PDROP, "vlruwt", hz);
1553 rfreevnodes = vnlru_read_freevnodes();
1555 onumvnodes = rnumvnodes;
1557 * Calculate parameters for recycling. These are the same
1558 * throughout the loop to give some semblance of fairness.
1559 * The trigger point is to avoid recycling vnodes with lots
1560 * of resident pages. We aren't trying to free memory; we
1561 * are trying to recycle or at least free vnodes.
1563 if (rnumvnodes <= desiredvnodes)
1564 usevnodes = rnumvnodes - rfreevnodes;
1566 usevnodes = rnumvnodes;
1570 * The trigger value is is chosen to give a conservatively
1571 * large value to ensure that it alone doesn't prevent
1572 * making progress. The value can easily be so large that
1573 * it is effectively infinite in some congested and
1574 * misconfigured cases, and this is necessary. Normally
1575 * it is about 8 to 100 (pages), which is quite large.
1577 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1579 trigger = vsmalltrigger;
1580 reclaim_nc_src = force >= 3;
1581 target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1582 target = target / 10 + 1;
1583 done = vlrureclaim(reclaim_nc_src, trigger, target);
1584 mtx_unlock(&vnode_list_mtx);
1585 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1586 uma_reclaim(UMA_RECLAIM_DRAIN);
1588 if (force == 0 || force == 1) {
1599 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1602 kern_yield(PRI_USER);
1607 static struct kproc_desc vnlru_kp = {
1612 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1616 * Routines having to do with the management of the vnode table.
1620 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1621 * before we actually vgone(). This function must be called with the vnode
1622 * held to prevent the vnode from being returned to the free list midway
1626 vtryrecycle(struct vnode *vp)
1630 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1631 VNASSERT(vp->v_holdcnt, vp,
1632 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1634 * This vnode may found and locked via some other list, if so we
1635 * can't recycle it yet.
1637 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1639 "%s: impossible to recycle, vp %p lock is already held",
1642 return (EWOULDBLOCK);
1645 * Don't recycle if its filesystem is being suspended.
1647 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1650 "%s: impossible to recycle, cannot start the write for %p",
1656 * If we got this far, we need to acquire the interlock and see if
1657 * anyone picked up this vnode from another list. If not, we will
1658 * mark it with DOOMED via vgonel() so that anyone who does find it
1659 * will skip over it.
1662 if (vp->v_usecount) {
1665 vn_finished_write(vnmp);
1667 "%s: impossible to recycle, %p is already referenced",
1671 if (!VN_IS_DOOMED(vp)) {
1672 counter_u64_add(recycles_free_count, 1);
1677 vn_finished_write(vnmp);
1682 * Allocate a new vnode.
1684 * The operation never returns an error. Returning an error was disabled
1685 * in r145385 (dated 2005) with the following comment:
1687 * XXX Not all VFS_VGET/ffs_vget callers check returns.
1689 * Given the age of this commit (almost 15 years at the time of writing this
1690 * comment) restoring the ability to fail requires a significant audit of
1693 * The routine can try to free a vnode or stall for up to 1 second waiting for
1694 * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1696 static u_long vn_alloc_cyclecount;
1698 static struct vnode * __noinline
1699 vn_alloc_hard(struct mount *mp)
1701 u_long rnumvnodes, rfreevnodes;
1703 mtx_lock(&vnode_list_mtx);
1704 rnumvnodes = atomic_load_long(&numvnodes);
1705 if (rnumvnodes + 1 < desiredvnodes) {
1706 vn_alloc_cyclecount = 0;
1709 rfreevnodes = vnlru_read_freevnodes();
1710 if (vn_alloc_cyclecount++ >= rfreevnodes) {
1711 vn_alloc_cyclecount = 0;
1715 * Grow the vnode cache if it will not be above its target max
1716 * after growing. Otherwise, if the free list is nonempty, try
1717 * to reclaim 1 item from it before growing the cache (possibly
1718 * above its target max if the reclamation failed or is delayed).
1719 * Otherwise, wait for some space. In all cases, schedule
1720 * vnlru_proc() if we are getting short of space. The watermarks
1721 * should be chosen so that we never wait or even reclaim from
1722 * the free list to below its target minimum.
1724 if (vnlru_free_locked(1) > 0)
1726 if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1728 * Wait for space for a new vnode.
1731 msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1732 if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1733 vnlru_read_freevnodes() > 1)
1734 vnlru_free_locked(1);
1737 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1738 if (vnlru_under(rnumvnodes, vlowat))
1740 mtx_unlock(&vnode_list_mtx);
1741 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1744 static struct vnode *
1745 vn_alloc(struct mount *mp)
1749 if (__predict_false(vn_alloc_cyclecount != 0))
1750 return (vn_alloc_hard(mp));
1751 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1752 if (__predict_false(vnlru_under_unlocked(rnumvnodes, vlowat))) {
1753 atomic_subtract_long(&numvnodes, 1);
1754 return (vn_alloc_hard(mp));
1757 return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1761 vn_free(struct vnode *vp)
1764 atomic_subtract_long(&numvnodes, 1);
1765 uma_zfree_smr(vnode_zone, vp);
1769 * Return the next vnode from the free list.
1772 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1777 struct lock_object *lo;
1779 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1781 KASSERT(vops->registered,
1782 ("%s: not registered vector op %p\n", __func__, vops));
1785 if (td->td_vp_reserved != NULL) {
1786 vp = td->td_vp_reserved;
1787 td->td_vp_reserved = NULL;
1791 counter_u64_add(vnodes_created, 1);
1793 * Locks are given the generic name "vnode" when created.
1794 * Follow the historic practice of using the filesystem
1795 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1797 * Locks live in a witness group keyed on their name. Thus,
1798 * when a lock is renamed, it must also move from the witness
1799 * group of its old name to the witness group of its new name.
1801 * The change only needs to be made when the vnode moves
1802 * from one filesystem type to another. We ensure that each
1803 * filesystem use a single static name pointer for its tag so
1804 * that we can compare pointers rather than doing a strcmp().
1806 lo = &vp->v_vnlock->lock_object;
1808 if (lo->lo_name != tag) {
1812 WITNESS_DESTROY(lo);
1813 WITNESS_INIT(lo, tag);
1817 * By default, don't allow shared locks unless filesystems opt-in.
1819 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1821 * Finalize various vnode identity bits.
1823 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1824 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1825 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1829 v_init_counters(vp);
1831 vp->v_bufobj.bo_ops = &buf_ops_bio;
1833 if (mp == NULL && vops != &dead_vnodeops)
1834 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1838 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1839 mac_vnode_associate_singlelabel(mp, vp);
1842 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1843 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1844 vp->v_vflag |= VV_NOKNOTE;
1848 * For the filesystems which do not use vfs_hash_insert(),
1849 * still initialize v_hash to have vfs_hash_index() useful.
1850 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1853 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1860 getnewvnode_reserve(void)
1865 MPASS(td->td_vp_reserved == NULL);
1866 td->td_vp_reserved = vn_alloc(NULL);
1870 getnewvnode_drop_reserve(void)
1875 if (td->td_vp_reserved != NULL) {
1876 vn_free(td->td_vp_reserved);
1877 td->td_vp_reserved = NULL;
1881 static void __noinline
1882 freevnode(struct vnode *vp)
1887 * The vnode has been marked for destruction, so free it.
1889 * The vnode will be returned to the zone where it will
1890 * normally remain until it is needed for another vnode. We
1891 * need to cleanup (or verify that the cleanup has already
1892 * been done) any residual data left from its current use
1893 * so as not to contaminate the freshly allocated vnode.
1895 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1897 * Paired with vgone.
1899 vn_seqc_write_end_free(vp);
1902 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1903 VNPASS(vp->v_holdcnt == VHOLD_NO_SMR, vp);
1904 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1905 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1906 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1907 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1908 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1909 ("clean blk trie not empty"));
1910 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1911 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1912 ("dirty blk trie not empty"));
1913 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1914 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1915 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1916 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1917 ("Dangling rangelock waiters"));
1918 VNASSERT((vp->v_iflag & (VI_DOINGINACT | VI_OWEINACT)) == 0, vp,
1919 ("Leaked inactivation"));
1922 mac_vnode_destroy(vp);
1924 if (vp->v_pollinfo != NULL) {
1925 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1926 destroy_vpollinfo(vp->v_pollinfo);
1928 vp->v_pollinfo = NULL;
1930 vp->v_mountedhere = NULL;
1933 vp->v_fifoinfo = NULL;
1934 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
1942 * Delete from old mount point vnode list, if on one.
1945 delmntque(struct vnode *vp)
1949 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
1958 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1959 ("bad mount point vnode list size"));
1960 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1961 mp->mnt_nvnodelistsize--;
1967 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1971 vp->v_op = &dead_vnodeops;
1977 * Insert into list of vnodes for the new mount point, if available.
1980 insmntque1(struct vnode *vp, struct mount *mp,
1981 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1984 KASSERT(vp->v_mount == NULL,
1985 ("insmntque: vnode already on per mount vnode list"));
1986 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1987 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1990 * We acquire the vnode interlock early to ensure that the
1991 * vnode cannot be recycled by another process releasing a
1992 * holdcnt on it before we get it on both the vnode list
1993 * and the active vnode list. The mount mutex protects only
1994 * manipulation of the vnode list and the vnode freelist
1995 * mutex protects only manipulation of the active vnode list.
1996 * Hence the need to hold the vnode interlock throughout.
2000 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
2001 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
2002 mp->mnt_nvnodelistsize == 0)) &&
2003 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
2012 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
2013 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
2014 ("neg mount point vnode list size"));
2015 mp->mnt_nvnodelistsize++;
2022 insmntque(struct vnode *vp, struct mount *mp)
2025 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
2029 * Flush out and invalidate all buffers associated with a bufobj
2030 * Called with the underlying object locked.
2033 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
2038 if (flags & V_SAVE) {
2039 error = bufobj_wwait(bo, slpflag, slptimeo);
2044 if (bo->bo_dirty.bv_cnt > 0) {
2047 error = BO_SYNC(bo, MNT_WAIT);
2048 } while (error == ERELOOKUP);
2052 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0) {
2059 * If you alter this loop please notice that interlock is dropped and
2060 * reacquired in flushbuflist. Special care is needed to ensure that
2061 * no race conditions occur from this.
2064 error = flushbuflist(&bo->bo_clean,
2065 flags, bo, slpflag, slptimeo);
2066 if (error == 0 && !(flags & V_CLEANONLY))
2067 error = flushbuflist(&bo->bo_dirty,
2068 flags, bo, slpflag, slptimeo);
2069 if (error != 0 && error != EAGAIN) {
2073 } while (error != 0);
2076 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
2077 * have write I/O in-progress but if there is a VM object then the
2078 * VM object can also have read-I/O in-progress.
2081 bufobj_wwait(bo, 0, 0);
2082 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
2084 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
2087 } while (bo->bo_numoutput > 0);
2091 * Destroy the copy in the VM cache, too.
2093 if (bo->bo_object != NULL &&
2094 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
2095 VM_OBJECT_WLOCK(bo->bo_object);
2096 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
2097 OBJPR_CLEANONLY : 0);
2098 VM_OBJECT_WUNLOCK(bo->bo_object);
2103 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
2104 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
2105 bo->bo_clean.bv_cnt > 0))
2106 panic("vinvalbuf: flush failed");
2107 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
2108 bo->bo_dirty.bv_cnt > 0)
2109 panic("vinvalbuf: flush dirty failed");
2116 * Flush out and invalidate all buffers associated with a vnode.
2117 * Called with the underlying object locked.
2120 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
2123 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2124 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
2125 if (vp->v_object != NULL && vp->v_object->handle != vp)
2127 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
2131 * Flush out buffers on the specified list.
2135 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
2138 struct buf *bp, *nbp;
2143 ASSERT_BO_WLOCKED(bo);
2146 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2148 * If we are flushing both V_NORMAL and V_ALT buffers then
2149 * do not skip any buffers. If we are flushing only V_NORMAL
2150 * buffers then skip buffers marked as BX_ALTDATA. If we are
2151 * flushing only V_ALT buffers then skip buffers not marked
2154 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2155 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2156 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2160 lblkno = nbp->b_lblkno;
2161 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2164 error = BUF_TIMELOCK(bp,
2165 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2166 "flushbuf", slpflag, slptimeo);
2169 return (error != ENOLCK ? error : EAGAIN);
2171 KASSERT(bp->b_bufobj == bo,
2172 ("bp %p wrong b_bufobj %p should be %p",
2173 bp, bp->b_bufobj, bo));
2175 * XXX Since there are no node locks for NFS, I
2176 * believe there is a slight chance that a delayed
2177 * write will occur while sleeping just above, so
2180 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2183 bp->b_flags |= B_ASYNC;
2186 return (EAGAIN); /* XXX: why not loop ? */
2189 bp->b_flags |= (B_INVAL | B_RELBUF);
2190 bp->b_flags &= ~B_ASYNC;
2195 nbp = gbincore(bo, lblkno);
2196 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2198 break; /* nbp invalid */
2204 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2210 ASSERT_BO_LOCKED(bo);
2212 for (lblkno = startn;;) {
2214 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2215 if (bp == NULL || bp->b_lblkno >= endn ||
2216 bp->b_lblkno < startn)
2218 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2219 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2222 if (error == ENOLCK)
2226 KASSERT(bp->b_bufobj == bo,
2227 ("bp %p wrong b_bufobj %p should be %p",
2228 bp, bp->b_bufobj, bo));
2229 lblkno = bp->b_lblkno + 1;
2230 if ((bp->b_flags & B_MANAGED) == 0)
2232 bp->b_flags |= B_RELBUF;
2234 * In the VMIO case, use the B_NOREUSE flag to hint that the
2235 * pages backing each buffer in the range are unlikely to be
2236 * reused. Dirty buffers will have the hint applied once
2237 * they've been written.
2239 if ((bp->b_flags & B_VMIO) != 0)
2240 bp->b_flags |= B_NOREUSE;
2248 * Truncate a file's buffer and pages to a specified length. This
2249 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2253 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2255 struct buf *bp, *nbp;
2259 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2260 vp, blksize, (uintmax_t)length);
2263 * Round up to the *next* lbn.
2265 startlbn = howmany(length, blksize);
2267 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2273 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2278 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2279 if (bp->b_lblkno > 0)
2282 * Since we hold the vnode lock this should only
2283 * fail if we're racing with the buf daemon.
2286 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2287 BO_LOCKPTR(bo)) == ENOLCK)
2288 goto restart_unlocked;
2290 VNASSERT((bp->b_flags & B_DELWRI), vp,
2291 ("buf(%p) on dirty queue without DELWRI", bp));
2300 bufobj_wwait(bo, 0, 0);
2302 vnode_pager_setsize(vp, length);
2308 * Invalidate the cached pages of a file's buffer within the range of block
2309 * numbers [startlbn, endlbn).
2312 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2318 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2320 start = blksize * startlbn;
2321 end = blksize * endlbn;
2325 MPASS(blksize == bo->bo_bsize);
2327 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2331 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2335 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2336 daddr_t startlbn, daddr_t endlbn)
2338 struct buf *bp, *nbp;
2341 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2342 ASSERT_BO_LOCKED(bo);
2346 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2347 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2350 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2351 BO_LOCKPTR(bo)) == ENOLCK) {
2357 bp->b_flags |= B_INVAL | B_RELBUF;
2358 bp->b_flags &= ~B_ASYNC;
2364 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2366 (nbp->b_flags & B_DELWRI) != 0))
2370 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2371 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2374 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2375 BO_LOCKPTR(bo)) == ENOLCK) {
2380 bp->b_flags |= B_INVAL | B_RELBUF;
2381 bp->b_flags &= ~B_ASYNC;
2387 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2388 (nbp->b_vp != vp) ||
2389 (nbp->b_flags & B_DELWRI) == 0))
2397 buf_vlist_remove(struct buf *bp)
2402 flags = bp->b_xflags;
2404 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2405 ASSERT_BO_WLOCKED(bp->b_bufobj);
2406 KASSERT((flags & (BX_VNDIRTY | BX_VNCLEAN)) != 0 &&
2407 (flags & (BX_VNDIRTY | BX_VNCLEAN)) != (BX_VNDIRTY | BX_VNCLEAN),
2408 ("%s: buffer %p has invalid queue state", __func__, bp));
2410 if ((flags & BX_VNDIRTY) != 0)
2411 bv = &bp->b_bufobj->bo_dirty;
2413 bv = &bp->b_bufobj->bo_clean;
2414 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2415 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2417 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2421 * Add the buffer to the sorted clean or dirty block list.
2423 * NOTE: xflags is passed as a constant, optimizing this inline function!
2426 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2432 ASSERT_BO_WLOCKED(bo);
2433 KASSERT((bo->bo_flag & BO_NOBUFS) == 0,
2434 ("buf_vlist_add: bo %p does not allow bufs", bo));
2435 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2436 ("dead bo %p", bo));
2437 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2438 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2439 bp->b_xflags |= xflags;
2440 if (xflags & BX_VNDIRTY)
2446 * Keep the list ordered. Optimize empty list insertion. Assume
2447 * we tend to grow at the tail so lookup_le should usually be cheaper
2450 if (bv->bv_cnt == 0 ||
2451 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2452 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2453 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2454 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2456 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2457 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2459 panic("buf_vlist_add: Preallocated nodes insufficient.");
2464 * Look up a buffer using the buffer tries.
2467 gbincore(struct bufobj *bo, daddr_t lblkno)
2471 ASSERT_BO_LOCKED(bo);
2472 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2475 return (BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno));
2479 * Look up a buf using the buffer tries, without the bufobj lock. This relies
2480 * on SMR for safe lookup, and bufs being in a no-free zone to provide type
2481 * stability of the result. Like other lockless lookups, the found buf may
2482 * already be invalid by the time this function returns.
2485 gbincore_unlocked(struct bufobj *bo, daddr_t lblkno)
2489 ASSERT_BO_UNLOCKED(bo);
2490 bp = BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_clean.bv_root, lblkno);
2493 return (BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_dirty.bv_root, lblkno));
2497 * Associate a buffer with a vnode.
2500 bgetvp(struct vnode *vp, struct buf *bp)
2505 ASSERT_BO_WLOCKED(bo);
2506 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2508 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2509 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2510 ("bgetvp: bp already attached! %p", bp));
2516 * Insert onto list for new vnode.
2518 buf_vlist_add(bp, bo, BX_VNCLEAN);
2522 * Disassociate a buffer from a vnode.
2525 brelvp(struct buf *bp)
2530 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2531 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2534 * Delete from old vnode list, if on one.
2536 vp = bp->b_vp; /* XXX */
2539 buf_vlist_remove(bp);
2540 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2541 bo->bo_flag &= ~BO_ONWORKLST;
2542 mtx_lock(&sync_mtx);
2543 LIST_REMOVE(bo, bo_synclist);
2544 syncer_worklist_len--;
2545 mtx_unlock(&sync_mtx);
2548 bp->b_bufobj = NULL;
2554 * Add an item to the syncer work queue.
2557 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2561 ASSERT_BO_WLOCKED(bo);
2563 mtx_lock(&sync_mtx);
2564 if (bo->bo_flag & BO_ONWORKLST)
2565 LIST_REMOVE(bo, bo_synclist);
2567 bo->bo_flag |= BO_ONWORKLST;
2568 syncer_worklist_len++;
2571 if (delay > syncer_maxdelay - 2)
2572 delay = syncer_maxdelay - 2;
2573 slot = (syncer_delayno + delay) & syncer_mask;
2575 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2576 mtx_unlock(&sync_mtx);
2580 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2584 mtx_lock(&sync_mtx);
2585 len = syncer_worklist_len - sync_vnode_count;
2586 mtx_unlock(&sync_mtx);
2587 error = SYSCTL_OUT(req, &len, sizeof(len));
2591 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2592 CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2593 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2595 static struct proc *updateproc;
2596 static void sched_sync(void);
2597 static struct kproc_desc up_kp = {
2602 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2605 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2610 *bo = LIST_FIRST(slp);
2614 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2617 * We use vhold in case the vnode does not
2618 * successfully sync. vhold prevents the vnode from
2619 * going away when we unlock the sync_mtx so that
2620 * we can acquire the vnode interlock.
2623 mtx_unlock(&sync_mtx);
2625 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2627 mtx_lock(&sync_mtx);
2628 return (*bo == LIST_FIRST(slp));
2630 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2631 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2633 vn_finished_write(mp);
2635 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2637 * Put us back on the worklist. The worklist
2638 * routine will remove us from our current
2639 * position and then add us back in at a later
2642 vn_syncer_add_to_worklist(*bo, syncdelay);
2646 mtx_lock(&sync_mtx);
2650 static int first_printf = 1;
2653 * System filesystem synchronizer daemon.
2658 struct synclist *next, *slp;
2661 struct thread *td = curthread;
2663 int net_worklist_len;
2664 int syncer_final_iter;
2668 syncer_final_iter = 0;
2669 syncer_state = SYNCER_RUNNING;
2670 starttime = time_uptime;
2671 td->td_pflags |= TDP_NORUNNINGBUF;
2673 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2676 mtx_lock(&sync_mtx);
2678 if (syncer_state == SYNCER_FINAL_DELAY &&
2679 syncer_final_iter == 0) {
2680 mtx_unlock(&sync_mtx);
2681 kproc_suspend_check(td->td_proc);
2682 mtx_lock(&sync_mtx);
2684 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2685 if (syncer_state != SYNCER_RUNNING &&
2686 starttime != time_uptime) {
2688 printf("\nSyncing disks, vnodes remaining... ");
2691 printf("%d ", net_worklist_len);
2693 starttime = time_uptime;
2696 * Push files whose dirty time has expired. Be careful
2697 * of interrupt race on slp queue.
2699 * Skip over empty worklist slots when shutting down.
2702 slp = &syncer_workitem_pending[syncer_delayno];
2703 syncer_delayno += 1;
2704 if (syncer_delayno == syncer_maxdelay)
2706 next = &syncer_workitem_pending[syncer_delayno];
2708 * If the worklist has wrapped since the
2709 * it was emptied of all but syncer vnodes,
2710 * switch to the FINAL_DELAY state and run
2711 * for one more second.
2713 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2714 net_worklist_len == 0 &&
2715 last_work_seen == syncer_delayno) {
2716 syncer_state = SYNCER_FINAL_DELAY;
2717 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2719 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2720 syncer_worklist_len > 0);
2723 * Keep track of the last time there was anything
2724 * on the worklist other than syncer vnodes.
2725 * Return to the SHUTTING_DOWN state if any
2728 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2729 last_work_seen = syncer_delayno;
2730 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2731 syncer_state = SYNCER_SHUTTING_DOWN;
2732 while (!LIST_EMPTY(slp)) {
2733 error = sync_vnode(slp, &bo, td);
2735 LIST_REMOVE(bo, bo_synclist);
2736 LIST_INSERT_HEAD(next, bo, bo_synclist);
2740 if (first_printf == 0) {
2742 * Drop the sync mutex, because some watchdog
2743 * drivers need to sleep while patting
2745 mtx_unlock(&sync_mtx);
2746 wdog_kern_pat(WD_LASTVAL);
2747 mtx_lock(&sync_mtx);
2750 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2751 syncer_final_iter--;
2753 * The variable rushjob allows the kernel to speed up the
2754 * processing of the filesystem syncer process. A rushjob
2755 * value of N tells the filesystem syncer to process the next
2756 * N seconds worth of work on its queue ASAP. Currently rushjob
2757 * is used by the soft update code to speed up the filesystem
2758 * syncer process when the incore state is getting so far
2759 * ahead of the disk that the kernel memory pool is being
2760 * threatened with exhaustion.
2767 * Just sleep for a short period of time between
2768 * iterations when shutting down to allow some I/O
2771 * If it has taken us less than a second to process the
2772 * current work, then wait. Otherwise start right over
2773 * again. We can still lose time if any single round
2774 * takes more than two seconds, but it does not really
2775 * matter as we are just trying to generally pace the
2776 * filesystem activity.
2778 if (syncer_state != SYNCER_RUNNING ||
2779 time_uptime == starttime) {
2781 sched_prio(td, PPAUSE);
2784 if (syncer_state != SYNCER_RUNNING)
2785 cv_timedwait(&sync_wakeup, &sync_mtx,
2786 hz / SYNCER_SHUTDOWN_SPEEDUP);
2787 else if (time_uptime == starttime)
2788 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2793 * Request the syncer daemon to speed up its work.
2794 * We never push it to speed up more than half of its
2795 * normal turn time, otherwise it could take over the cpu.
2798 speedup_syncer(void)
2802 mtx_lock(&sync_mtx);
2803 if (rushjob < syncdelay / 2) {
2805 stat_rush_requests += 1;
2808 mtx_unlock(&sync_mtx);
2809 cv_broadcast(&sync_wakeup);
2814 * Tell the syncer to speed up its work and run though its work
2815 * list several times, then tell it to shut down.
2818 syncer_shutdown(void *arg, int howto)
2821 if (howto & RB_NOSYNC)
2823 mtx_lock(&sync_mtx);
2824 syncer_state = SYNCER_SHUTTING_DOWN;
2826 mtx_unlock(&sync_mtx);
2827 cv_broadcast(&sync_wakeup);
2828 kproc_shutdown(arg, howto);
2832 syncer_suspend(void)
2835 syncer_shutdown(updateproc, 0);
2842 mtx_lock(&sync_mtx);
2844 syncer_state = SYNCER_RUNNING;
2845 mtx_unlock(&sync_mtx);
2846 cv_broadcast(&sync_wakeup);
2847 kproc_resume(updateproc);
2851 * Move the buffer between the clean and dirty lists of its vnode.
2854 reassignbuf(struct buf *bp)
2866 KASSERT((bp->b_flags & B_PAGING) == 0,
2867 ("%s: cannot reassign paging buffer %p", __func__, bp));
2869 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2870 bp, bp->b_vp, bp->b_flags);
2873 buf_vlist_remove(bp);
2876 * If dirty, put on list of dirty buffers; otherwise insert onto list
2879 if (bp->b_flags & B_DELWRI) {
2880 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2881 switch (vp->v_type) {
2891 vn_syncer_add_to_worklist(bo, delay);
2893 buf_vlist_add(bp, bo, BX_VNDIRTY);
2895 buf_vlist_add(bp, bo, BX_VNCLEAN);
2897 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2898 mtx_lock(&sync_mtx);
2899 LIST_REMOVE(bo, bo_synclist);
2900 syncer_worklist_len--;
2901 mtx_unlock(&sync_mtx);
2902 bo->bo_flag &= ~BO_ONWORKLST;
2907 bp = TAILQ_FIRST(&bv->bv_hd);
2908 KASSERT(bp == NULL || bp->b_bufobj == bo,
2909 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2910 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2911 KASSERT(bp == NULL || bp->b_bufobj == bo,
2912 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2914 bp = TAILQ_FIRST(&bv->bv_hd);
2915 KASSERT(bp == NULL || bp->b_bufobj == bo,
2916 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2917 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2918 KASSERT(bp == NULL || bp->b_bufobj == bo,
2919 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2925 v_init_counters(struct vnode *vp)
2928 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2929 vp, ("%s called for an initialized vnode", __FUNCTION__));
2930 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2932 refcount_init(&vp->v_holdcnt, 1);
2933 refcount_init(&vp->v_usecount, 1);
2937 * Grab a particular vnode from the free list, increment its
2938 * reference count and lock it. VIRF_DOOMED is set if the vnode
2939 * is being destroyed. Only callers who specify LK_RETRY will
2940 * see doomed vnodes. If inactive processing was delayed in
2941 * vput try to do it here.
2943 * usecount is manipulated using atomics without holding any locks.
2945 * holdcnt can be manipulated using atomics without holding any locks,
2946 * except when transitioning 1<->0, in which case the interlock is held.
2948 * Consumers which don't guarantee liveness of the vnode can use SMR to
2949 * try to get a reference. Note this operation can fail since the vnode
2950 * may be awaiting getting freed by the time they get to it.
2953 vget_prep_smr(struct vnode *vp)
2957 VFS_SMR_ASSERT_ENTERED();
2959 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2971 vget_prep(struct vnode *vp)
2975 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2985 vget_abort(struct vnode *vp, enum vgetstate vs)
2996 __assert_unreachable();
3001 vget(struct vnode *vp, int flags)
3006 return (vget_finish(vp, flags, vs));
3010 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
3014 if ((flags & LK_INTERLOCK) != 0)
3015 ASSERT_VI_LOCKED(vp, __func__);
3017 ASSERT_VI_UNLOCKED(vp, __func__);
3018 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3019 VNPASS(vp->v_holdcnt > 0, vp);
3020 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3022 error = vn_lock(vp, flags);
3023 if (__predict_false(error != 0)) {
3025 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
3030 vget_finish_ref(vp, vs);
3035 vget_finish_ref(struct vnode *vp, enum vgetstate vs)
3039 VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3040 VNPASS(vp->v_holdcnt > 0, vp);
3041 VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3043 if (vs == VGET_USECOUNT)
3047 * We hold the vnode. If the usecount is 0 it will be utilized to keep
3048 * the vnode around. Otherwise someone else lended their hold count and
3049 * we have to drop ours.
3051 old = atomic_fetchadd_int(&vp->v_usecount, 1);
3052 VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
3055 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
3056 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
3058 refcount_release(&vp->v_holdcnt);
3064 vref(struct vnode *vp)
3068 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3070 vget_finish_ref(vp, vs);
3074 vrefact(struct vnode *vp)
3077 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3079 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
3080 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3082 refcount_acquire(&vp->v_usecount);
3087 vlazy(struct vnode *vp)
3091 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
3093 if ((vp->v_mflag & VMP_LAZYLIST) != 0)
3096 * We may get here for inactive routines after the vnode got doomed.
3098 if (VN_IS_DOOMED(vp))
3101 mtx_lock(&mp->mnt_listmtx);
3102 if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
3103 vp->v_mflag |= VMP_LAZYLIST;
3104 TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3105 mp->mnt_lazyvnodelistsize++;
3107 mtx_unlock(&mp->mnt_listmtx);
3111 vunlazy(struct vnode *vp)
3115 ASSERT_VI_LOCKED(vp, __func__);
3116 VNPASS(!VN_IS_DOOMED(vp), vp);
3119 mtx_lock(&mp->mnt_listmtx);
3120 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3122 * Don't remove the vnode from the lazy list if another thread
3123 * has increased the hold count. It may have re-enqueued the
3124 * vnode to the lazy list and is now responsible for its
3127 if (vp->v_holdcnt == 0) {
3128 vp->v_mflag &= ~VMP_LAZYLIST;
3129 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3130 mp->mnt_lazyvnodelistsize--;
3132 mtx_unlock(&mp->mnt_listmtx);
3136 * This routine is only meant to be called from vgonel prior to dooming
3140 vunlazy_gone(struct vnode *vp)
3144 ASSERT_VOP_ELOCKED(vp, __func__);
3145 ASSERT_VI_LOCKED(vp, __func__);
3146 VNPASS(!VN_IS_DOOMED(vp), vp);
3148 if (vp->v_mflag & VMP_LAZYLIST) {
3150 mtx_lock(&mp->mnt_listmtx);
3151 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3152 vp->v_mflag &= ~VMP_LAZYLIST;
3153 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3154 mp->mnt_lazyvnodelistsize--;
3155 mtx_unlock(&mp->mnt_listmtx);
3160 vdefer_inactive(struct vnode *vp)
3163 ASSERT_VI_LOCKED(vp, __func__);
3164 VNASSERT(vp->v_holdcnt > 0, vp,
3165 ("%s: vnode without hold count", __func__));
3166 if (VN_IS_DOOMED(vp)) {
3170 if (vp->v_iflag & VI_DEFINACT) {
3171 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3175 if (vp->v_usecount > 0) {
3176 vp->v_iflag &= ~VI_OWEINACT;
3181 vp->v_iflag |= VI_DEFINACT;
3183 counter_u64_add(deferred_inact, 1);
3187 vdefer_inactive_unlocked(struct vnode *vp)
3191 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3195 vdefer_inactive(vp);
3198 enum vput_op { VRELE, VPUT, VUNREF };
3201 * Handle ->v_usecount transitioning to 0.
3203 * By releasing the last usecount we take ownership of the hold count which
3204 * provides liveness of the vnode, meaning we have to vdrop.
3206 * For all vnodes we may need to perform inactive processing. It requires an
3207 * exclusive lock on the vnode, while it is legal to call here with only a
3208 * shared lock (or no locks). If locking the vnode in an expected manner fails,
3209 * inactive processing gets deferred to the syncer.
3211 * XXX Some filesystems pass in an exclusively locked vnode and strongly depend
3212 * on the lock being held all the way until VOP_INACTIVE. This in particular
3213 * happens with UFS which adds half-constructed vnodes to the hash, where they
3214 * can be found by other code.
3217 vput_final(struct vnode *vp, enum vput_op func)
3222 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3223 VNPASS(vp->v_holdcnt > 0, vp);
3228 * By the time we got here someone else might have transitioned
3229 * the count back to > 0.
3231 if (vp->v_usecount > 0)
3235 * If the vnode is doomed vgone already performed inactive processing
3238 if (VN_IS_DOOMED(vp))
3241 if (__predict_true(VOP_NEED_INACTIVE(vp) == 0))
3244 if (vp->v_iflag & VI_DOINGINACT)
3248 * Locking operations here will drop the interlock and possibly the
3249 * vnode lock, opening a window where the vnode can get doomed all the
3250 * while ->v_usecount is 0. Set VI_OWEINACT to let vgone know to
3253 vp->v_iflag |= VI_OWEINACT;
3254 want_unlock = false;
3258 switch (VOP_ISLOCKED(vp)) {
3264 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3269 * The lock has at least one sharer, but we have no way
3270 * to conclude whether this is us. Play it safe and
3279 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3280 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3286 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3287 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3293 if (func == VUNREF) {
3294 VNASSERT((vp->v_vflag & VV_UNREF) == 0, vp,
3295 ("recursive vunref"));
3296 vp->v_vflag |= VV_UNREF;
3299 error = vinactive(vp);
3302 if (error != ERELOOKUP || !want_unlock)
3304 VOP_LOCK(vp, LK_EXCLUSIVE);
3307 vp->v_vflag &= ~VV_UNREF;
3310 vdefer_inactive(vp);
3320 * Decrement ->v_usecount for a vnode.
3322 * Releasing the last use count requires additional processing, see vput_final
3323 * above for details.
3325 * Comment above each variant denotes lock state on entry and exit.
3330 * out: same as passed in
3333 vrele(struct vnode *vp)
3336 ASSERT_VI_UNLOCKED(vp, __func__);
3337 if (!refcount_release(&vp->v_usecount))
3339 vput_final(vp, VRELE);
3347 vput(struct vnode *vp)
3350 ASSERT_VOP_LOCKED(vp, __func__);
3351 ASSERT_VI_UNLOCKED(vp, __func__);
3352 if (!refcount_release(&vp->v_usecount)) {
3356 vput_final(vp, VPUT);
3364 vunref(struct vnode *vp)
3367 ASSERT_VOP_LOCKED(vp, __func__);
3368 ASSERT_VI_UNLOCKED(vp, __func__);
3369 if (!refcount_release(&vp->v_usecount))
3371 vput_final(vp, VUNREF);
3375 vhold(struct vnode *vp)
3379 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3380 old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3381 VNASSERT(old >= 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3382 ("%s: wrong hold count %d", __func__, old));
3384 vfs_freevnodes_dec();
3388 vholdnz(struct vnode *vp)
3391 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3393 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3394 VNASSERT(old > 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3395 ("%s: wrong hold count %d", __func__, old));
3397 atomic_add_int(&vp->v_holdcnt, 1);
3402 * Grab a hold count unless the vnode is freed.
3404 * Only use this routine if vfs smr is the only protection you have against
3405 * freeing the vnode.
3407 * The code loops trying to add a hold count as long as the VHOLD_NO_SMR flag
3408 * is not set. After the flag is set the vnode becomes immutable to anyone but
3409 * the thread which managed to set the flag.
3411 * It may be tempting to replace the loop with:
3412 * count = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3413 * if (count & VHOLD_NO_SMR) {
3414 * backpedal and error out;
3417 * However, while this is more performant, it hinders debugging by eliminating
3418 * the previously mentioned invariant.
3421 vhold_smr(struct vnode *vp)
3425 VFS_SMR_ASSERT_ENTERED();
3427 count = atomic_load_int(&vp->v_holdcnt);
3429 if (count & VHOLD_NO_SMR) {
3430 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3431 ("non-zero hold count with flags %d\n", count));
3434 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3435 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3437 vfs_freevnodes_dec();
3444 * Hold a free vnode for recycling.
3446 * Note: vnode_init references this comment.
3448 * Attempts to recycle only need the global vnode list lock and have no use for
3451 * However, vnodes get inserted into the global list before they get fully
3452 * initialized and stay there until UMA decides to free the memory. This in
3453 * particular means the target can be found before it becomes usable and after
3454 * it becomes recycled. Picking up such vnodes is guarded with v_holdcnt set to
3457 * Note: the vnode may gain more references after we transition the count 0->1.
3460 vhold_recycle_free(struct vnode *vp)
3464 mtx_assert(&vnode_list_mtx, MA_OWNED);
3466 count = atomic_load_int(&vp->v_holdcnt);
3468 if (count & VHOLD_NO_SMR) {
3469 VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3470 ("non-zero hold count with flags %d\n", count));
3473 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3477 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3478 vfs_freevnodes_dec();
3484 static void __noinline
3485 vdbatch_process(struct vdbatch *vd)
3490 mtx_assert(&vd->lock, MA_OWNED);
3491 MPASS(curthread->td_pinned > 0);
3492 MPASS(vd->index == VDBATCH_SIZE);
3494 mtx_lock(&vnode_list_mtx);
3496 freevnodes += vd->freevnodes;
3497 for (i = 0; i < VDBATCH_SIZE; i++) {
3499 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3500 TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3501 MPASS(vp->v_dbatchcpu != NOCPU);
3502 vp->v_dbatchcpu = NOCPU;
3504 mtx_unlock(&vnode_list_mtx);
3506 bzero(vd->tab, sizeof(vd->tab));
3512 vdbatch_enqueue(struct vnode *vp)
3516 ASSERT_VI_LOCKED(vp, __func__);
3517 VNASSERT(!VN_IS_DOOMED(vp), vp,
3518 ("%s: deferring requeue of a doomed vnode", __func__));
3520 if (vp->v_dbatchcpu != NOCPU) {
3527 mtx_lock(&vd->lock);
3528 MPASS(vd->index < VDBATCH_SIZE);
3529 MPASS(vd->tab[vd->index] == NULL);
3531 * A hack: we depend on being pinned so that we know what to put in
3534 vp->v_dbatchcpu = curcpu;
3535 vd->tab[vd->index] = vp;
3538 if (vd->index == VDBATCH_SIZE)
3539 vdbatch_process(vd);
3540 mtx_unlock(&vd->lock);
3545 * This routine must only be called for vnodes which are about to be
3546 * deallocated. Supporting dequeue for arbitrary vndoes would require
3547 * validating that the locked batch matches.
3550 vdbatch_dequeue(struct vnode *vp)
3556 VNASSERT(vp->v_type == VBAD || vp->v_type == VNON, vp,
3557 ("%s: called for a used vnode\n", __func__));
3559 cpu = vp->v_dbatchcpu;
3563 vd = DPCPU_ID_PTR(cpu, vd);
3564 mtx_lock(&vd->lock);
3565 for (i = 0; i < vd->index; i++) {
3566 if (vd->tab[i] != vp)
3568 vp->v_dbatchcpu = NOCPU;
3570 vd->tab[i] = vd->tab[vd->index];
3571 vd->tab[vd->index] = NULL;
3574 mtx_unlock(&vd->lock);
3576 * Either we dequeued the vnode above or the target CPU beat us to it.
3578 MPASS(vp->v_dbatchcpu == NOCPU);
3582 * Drop the hold count of the vnode. If this is the last reference to
3583 * the vnode we place it on the free list unless it has been vgone'd
3584 * (marked VIRF_DOOMED) in which case we will free it.
3586 * Because the vnode vm object keeps a hold reference on the vnode if
3587 * there is at least one resident non-cached page, the vnode cannot
3588 * leave the active list without the page cleanup done.
3590 static void __noinline
3591 vdropl_final(struct vnode *vp)
3594 ASSERT_VI_LOCKED(vp, __func__);
3595 VNPASS(VN_IS_DOOMED(vp), vp);
3597 * Set the VHOLD_NO_SMR flag.
3599 * We may be racing against vhold_smr. If they win we can just pretend
3600 * we never got this far, they will vdrop later.
3602 if (__predict_false(!atomic_cmpset_int(&vp->v_holdcnt, 0, VHOLD_NO_SMR))) {
3603 vfs_freevnodes_inc();
3606 * We lost the aforementioned race. Any subsequent access is
3607 * invalid as they might have managed to vdropl on their own.
3612 * Don't bump freevnodes as this one is going away.
3618 vdrop(struct vnode *vp)
3621 ASSERT_VI_UNLOCKED(vp, __func__);
3622 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3623 if (refcount_release_if_not_last(&vp->v_holdcnt))
3629 static void __always_inline
3630 vdropl_impl(struct vnode *vp, bool enqueue)
3633 ASSERT_VI_LOCKED(vp, __func__);
3634 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3635 if (!refcount_release(&vp->v_holdcnt)) {
3639 VNPASS((vp->v_iflag & VI_OWEINACT) == 0, vp);
3640 VNPASS((vp->v_iflag & VI_DEFINACT) == 0, vp);
3641 if (VN_IS_DOOMED(vp)) {
3646 vfs_freevnodes_inc();
3647 if (vp->v_mflag & VMP_LAZYLIST) {
3651 * Also unlocks the interlock. We can't assert on it as we
3652 * released our hold and by now the vnode might have been
3655 vdbatch_enqueue(vp);
3659 vdropl(struct vnode *vp)
3662 vdropl_impl(vp, true);
3666 * vdrop a vnode when recycling
3668 * This is a special case routine only to be used when recycling, differs from
3669 * regular vdrop by not requeieing the vnode on LRU.
3671 * Consider a case where vtryrecycle continuously fails with all vnodes (due to
3672 * e.g., frozen writes on the filesystem), filling the batch and causing it to
3673 * be requeued. Then vnlru will end up revisiting the same vnodes. This is a
3674 * loop which can last for as long as writes are frozen.
3677 vdropl_recycle(struct vnode *vp)
3680 vdropl_impl(vp, false);
3684 vdrop_recycle(struct vnode *vp)
3692 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3693 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3696 vinactivef(struct vnode *vp)
3698 struct vm_object *obj;
3701 ASSERT_VOP_ELOCKED(vp, "vinactive");
3702 ASSERT_VI_LOCKED(vp, "vinactive");
3703 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3704 ("vinactive: recursed on VI_DOINGINACT"));
3705 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3706 vp->v_iflag |= VI_DOINGINACT;
3707 vp->v_iflag &= ~VI_OWEINACT;
3710 * Before moving off the active list, we must be sure that any
3711 * modified pages are converted into the vnode's dirty
3712 * buffers, since these will no longer be checked once the
3713 * vnode is on the inactive list.
3715 * The write-out of the dirty pages is asynchronous. At the
3716 * point that VOP_INACTIVE() is called, there could still be
3717 * pending I/O and dirty pages in the object.
3719 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3720 vm_object_mightbedirty(obj)) {
3721 VM_OBJECT_WLOCK(obj);
3722 vm_object_page_clean(obj, 0, 0, 0);
3723 VM_OBJECT_WUNLOCK(obj);
3725 error = VOP_INACTIVE(vp);
3727 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3728 ("vinactive: lost VI_DOINGINACT"));
3729 vp->v_iflag &= ~VI_DOINGINACT;
3734 vinactive(struct vnode *vp)
3737 ASSERT_VOP_ELOCKED(vp, "vinactive");
3738 ASSERT_VI_LOCKED(vp, "vinactive");
3739 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3741 if ((vp->v_iflag & VI_OWEINACT) == 0)
3743 if (vp->v_iflag & VI_DOINGINACT)
3745 if (vp->v_usecount > 0) {
3746 vp->v_iflag &= ~VI_OWEINACT;
3749 return (vinactivef(vp));
3753 * Remove any vnodes in the vnode table belonging to mount point mp.
3755 * If FORCECLOSE is not specified, there should not be any active ones,
3756 * return error if any are found (nb: this is a user error, not a
3757 * system error). If FORCECLOSE is specified, detach any active vnodes
3760 * If WRITECLOSE is set, only flush out regular file vnodes open for
3763 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3765 * `rootrefs' specifies the base reference count for the root vnode
3766 * of this filesystem. The root vnode is considered busy if its
3767 * v_usecount exceeds this value. On a successful return, vflush(, td)
3768 * will call vrele() on the root vnode exactly rootrefs times.
3769 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3773 static int busyprt = 0; /* print out busy vnodes */
3774 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3778 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3780 struct vnode *vp, *mvp, *rootvp = NULL;
3782 int busy = 0, error;
3784 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3787 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3788 ("vflush: bad args"));
3790 * Get the filesystem root vnode. We can vput() it
3791 * immediately, since with rootrefs > 0, it won't go away.
3793 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3794 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3801 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3803 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3806 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3810 * Skip over a vnodes marked VV_SYSTEM.
3812 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3818 * If WRITECLOSE is set, flush out unlinked but still open
3819 * files (even if open only for reading) and regular file
3820 * vnodes open for writing.
3822 if (flags & WRITECLOSE) {
3823 if (vp->v_object != NULL) {
3824 VM_OBJECT_WLOCK(vp->v_object);
3825 vm_object_page_clean(vp->v_object, 0, 0, 0);
3826 VM_OBJECT_WUNLOCK(vp->v_object);
3829 error = VOP_FSYNC(vp, MNT_WAIT, td);
3830 } while (error == ERELOOKUP);
3834 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3837 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3840 if ((vp->v_type == VNON ||
3841 (error == 0 && vattr.va_nlink > 0)) &&
3842 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3850 * With v_usecount == 0, all we need to do is clear out the
3851 * vnode data structures and we are done.
3853 * If FORCECLOSE is set, forcibly close the vnode.
3855 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3861 vn_printf(vp, "vflush: busy vnode ");
3867 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3869 * If just the root vnode is busy, and if its refcount
3870 * is equal to `rootrefs', then go ahead and kill it.
3873 KASSERT(busy > 0, ("vflush: not busy"));
3874 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3875 ("vflush: usecount %d < rootrefs %d",
3876 rootvp->v_usecount, rootrefs));
3877 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3878 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3886 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3890 for (; rootrefs > 0; rootrefs--)
3896 * Recycle an unused vnode to the front of the free list.
3899 vrecycle(struct vnode *vp)
3904 recycled = vrecyclel(vp);
3910 * vrecycle, with the vp interlock held.
3913 vrecyclel(struct vnode *vp)
3917 ASSERT_VOP_ELOCKED(vp, __func__);
3918 ASSERT_VI_LOCKED(vp, __func__);
3919 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3921 if (vp->v_usecount == 0) {
3929 * Eliminate all activity associated with a vnode
3930 * in preparation for reuse.
3933 vgone(struct vnode *vp)
3941 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3942 struct vnode *lowervp __unused)
3947 * Notify upper mounts about reclaimed or unlinked vnode.
3950 vfs_notify_upper(struct vnode *vp, int event)
3952 static struct vfsops vgonel_vfsops = {
3953 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3954 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3956 struct mount *mp, *ump, *mmp;
3961 if (TAILQ_EMPTY(&mp->mnt_uppers))
3964 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3965 mmp->mnt_op = &vgonel_vfsops;
3966 mmp->mnt_kern_flag |= MNTK_MARKER;
3968 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3969 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3970 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3971 ump = TAILQ_NEXT(ump, mnt_upper_link);
3974 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3977 case VFS_NOTIFY_UPPER_RECLAIM:
3978 VFS_RECLAIM_LOWERVP(ump, vp);
3980 case VFS_NOTIFY_UPPER_UNLINK:
3981 VFS_UNLINK_LOWERVP(ump, vp);
3984 KASSERT(0, ("invalid event %d", event));
3988 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3989 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3992 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3993 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3994 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3995 wakeup(&mp->mnt_uppers);
4001 * vgone, with the vp interlock held.
4004 vgonel(struct vnode *vp)
4009 bool active, doinginact, oweinact;
4011 ASSERT_VOP_ELOCKED(vp, "vgonel");
4012 ASSERT_VI_LOCKED(vp, "vgonel");
4013 VNASSERT(vp->v_holdcnt, vp,
4014 ("vgonel: vp %p has no reference.", vp));
4015 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
4019 * Don't vgonel if we're already doomed.
4021 if (VN_IS_DOOMED(vp))
4024 * Paired with freevnode.
4026 vn_seqc_write_begin_locked(vp);
4028 vn_irflag_set_locked(vp, VIRF_DOOMED);
4031 * Check to see if the vnode is in use. If so, we have to
4032 * call VOP_CLOSE() and VOP_INACTIVE().
4034 * It could be that VOP_INACTIVE() requested reclamation, in
4035 * which case we should avoid recursion, so check
4036 * VI_DOINGINACT. This is not precise but good enough.
4038 active = vp->v_usecount > 0;
4039 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4040 doinginact = (vp->v_iflag & VI_DOINGINACT) != 0;
4043 * If we need to do inactive VI_OWEINACT will be set.
4045 if (vp->v_iflag & VI_DEFINACT) {
4046 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
4047 vp->v_iflag &= ~VI_DEFINACT;
4050 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
4053 cache_purge_vgone(vp);
4054 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
4057 * If purging an active vnode, it must be closed and
4058 * deactivated before being reclaimed.
4061 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
4064 if (oweinact || active) {
4067 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4072 if (vp->v_type == VSOCK)
4073 vfs_unp_reclaim(vp);
4076 * Clean out any buffers associated with the vnode.
4077 * If the flush fails, just toss the buffers.
4080 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
4081 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
4082 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
4083 while (vinvalbuf(vp, 0, 0, 0) != 0)
4087 BO_LOCK(&vp->v_bufobj);
4088 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
4089 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
4090 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
4091 vp->v_bufobj.bo_clean.bv_cnt == 0,
4092 ("vp %p bufobj not invalidated", vp));
4095 * For VMIO bufobj, BO_DEAD is set later, or in
4096 * vm_object_terminate() after the object's page queue is
4099 object = vp->v_bufobj.bo_object;
4101 vp->v_bufobj.bo_flag |= BO_DEAD;
4102 BO_UNLOCK(&vp->v_bufobj);
4105 * Handle the VM part. Tmpfs handles v_object on its own (the
4106 * OBJT_VNODE check). Nullfs or other bypassing filesystems
4107 * should not touch the object borrowed from the lower vnode
4108 * (the handle check).
4110 if (object != NULL && object->type == OBJT_VNODE &&
4111 object->handle == vp)
4112 vnode_destroy_vobject(vp);
4115 * Reclaim the vnode.
4117 if (VOP_RECLAIM(vp))
4118 panic("vgone: cannot reclaim");
4120 vn_finished_secondary_write(mp);
4121 VNASSERT(vp->v_object == NULL, vp,
4122 ("vop_reclaim left v_object vp=%p", vp));
4124 * Clear the advisory locks and wake up waiting threads.
4126 (void)VOP_ADVLOCKPURGE(vp);
4129 * Delete from old mount point vnode list.
4133 * Done with purge, reset to the standard lock and invalidate
4137 vp->v_vnlock = &vp->v_lock;
4138 vp->v_op = &dead_vnodeops;
4143 * Print out a description of a vnode.
4145 static const char * const typename[] =
4146 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
4149 _Static_assert((VHOLD_ALL_FLAGS & ~VHOLD_NO_SMR) == 0,
4150 "new hold count flag not added to vn_printf");
4153 vn_printf(struct vnode *vp, const char *fmt, ...)
4156 char buf[256], buf2[16];
4164 printf("%p: ", (void *)vp);
4165 printf("type %s\n", typename[vp->v_type]);
4166 holdcnt = atomic_load_int(&vp->v_holdcnt);
4167 printf(" usecount %d, writecount %d, refcount %d seqc users %d",
4168 vp->v_usecount, vp->v_writecount, holdcnt & ~VHOLD_ALL_FLAGS,
4170 switch (vp->v_type) {
4172 printf(" mountedhere %p\n", vp->v_mountedhere);
4175 printf(" rdev %p\n", vp->v_rdev);
4178 printf(" socket %p\n", vp->v_unpcb);
4181 printf(" fifoinfo %p\n", vp->v_fifoinfo);
4189 if (holdcnt & VHOLD_NO_SMR)
4190 strlcat(buf, "|VHOLD_NO_SMR", sizeof(buf));
4191 printf(" hold count flags (%s)\n", buf + 1);
4195 irflag = vn_irflag_read(vp);
4196 if (irflag & VIRF_DOOMED)
4197 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
4198 if (irflag & VIRF_PGREAD)
4199 strlcat(buf, "|VIRF_PGREAD", sizeof(buf));
4200 if (irflag & VIRF_MOUNTPOINT)
4201 strlcat(buf, "|VIRF_MOUNTPOINT", sizeof(buf));
4202 flags = irflag & ~(VIRF_DOOMED | VIRF_PGREAD | VIRF_MOUNTPOINT);
4204 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
4205 strlcat(buf, buf2, sizeof(buf));
4207 if (vp->v_vflag & VV_ROOT)
4208 strlcat(buf, "|VV_ROOT", sizeof(buf));
4209 if (vp->v_vflag & VV_ISTTY)
4210 strlcat(buf, "|VV_ISTTY", sizeof(buf));
4211 if (vp->v_vflag & VV_NOSYNC)
4212 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
4213 if (vp->v_vflag & VV_ETERNALDEV)
4214 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
4215 if (vp->v_vflag & VV_CACHEDLABEL)
4216 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
4217 if (vp->v_vflag & VV_VMSIZEVNLOCK)
4218 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
4219 if (vp->v_vflag & VV_COPYONWRITE)
4220 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
4221 if (vp->v_vflag & VV_SYSTEM)
4222 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
4223 if (vp->v_vflag & VV_PROCDEP)
4224 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
4225 if (vp->v_vflag & VV_NOKNOTE)
4226 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
4227 if (vp->v_vflag & VV_DELETED)
4228 strlcat(buf, "|VV_DELETED", sizeof(buf));
4229 if (vp->v_vflag & VV_MD)
4230 strlcat(buf, "|VV_MD", sizeof(buf));
4231 if (vp->v_vflag & VV_FORCEINSMQ)
4232 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
4233 if (vp->v_vflag & VV_READLINK)
4234 strlcat(buf, "|VV_READLINK", sizeof(buf));
4235 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4236 VV_CACHEDLABEL | VV_VMSIZEVNLOCK | VV_COPYONWRITE | VV_SYSTEM |
4237 VV_PROCDEP | VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ |
4240 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4241 strlcat(buf, buf2, sizeof(buf));
4243 if (vp->v_iflag & VI_TEXT_REF)
4244 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
4245 if (vp->v_iflag & VI_MOUNT)
4246 strlcat(buf, "|VI_MOUNT", sizeof(buf));
4247 if (vp->v_iflag & VI_DOINGINACT)
4248 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4249 if (vp->v_iflag & VI_OWEINACT)
4250 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4251 if (vp->v_iflag & VI_DEFINACT)
4252 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4253 if (vp->v_iflag & VI_FOPENING)
4254 strlcat(buf, "|VI_FOPENING", sizeof(buf));
4255 flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOINGINACT |
4256 VI_OWEINACT | VI_DEFINACT | VI_FOPENING);
4258 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4259 strlcat(buf, buf2, sizeof(buf));
4261 if (vp->v_mflag & VMP_LAZYLIST)
4262 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4263 flags = vp->v_mflag & ~(VMP_LAZYLIST);
4265 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4266 strlcat(buf, buf2, sizeof(buf));
4268 printf(" flags (%s)", buf + 1);
4269 if (mtx_owned(VI_MTX(vp)))
4270 printf(" VI_LOCKed");
4272 if (vp->v_object != NULL)
4273 printf(" v_object %p ref %d pages %d "
4274 "cleanbuf %d dirtybuf %d\n",
4275 vp->v_object, vp->v_object->ref_count,
4276 vp->v_object->resident_page_count,
4277 vp->v_bufobj.bo_clean.bv_cnt,
4278 vp->v_bufobj.bo_dirty.bv_cnt);
4280 lockmgr_printinfo(vp->v_vnlock);
4281 if (vp->v_data != NULL)
4287 * List all of the locked vnodes in the system.
4288 * Called when debugging the kernel.
4290 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
4296 * Note: because this is DDB, we can't obey the locking semantics
4297 * for these structures, which means we could catch an inconsistent
4298 * state and dereference a nasty pointer. Not much to be done
4301 db_printf("Locked vnodes\n");
4302 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4303 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4304 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4305 vn_printf(vp, "vnode ");
4311 * Show details about the given vnode.
4313 DB_SHOW_COMMAND(vnode, db_show_vnode)
4319 vp = (struct vnode *)addr;
4320 vn_printf(vp, "vnode ");
4324 * Show details about the given mount point.
4326 DB_SHOW_COMMAND(mount, db_show_mount)
4337 /* No address given, print short info about all mount points. */
4338 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4339 db_printf("%p %s on %s (%s)\n", mp,
4340 mp->mnt_stat.f_mntfromname,
4341 mp->mnt_stat.f_mntonname,
4342 mp->mnt_stat.f_fstypename);
4346 db_printf("\nMore info: show mount <addr>\n");
4350 mp = (struct mount *)addr;
4351 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4352 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4355 mflags = mp->mnt_flag;
4356 #define MNT_FLAG(flag) do { \
4357 if (mflags & (flag)) { \
4358 if (buf[0] != '\0') \
4359 strlcat(buf, ", ", sizeof(buf)); \
4360 strlcat(buf, (#flag) + 4, sizeof(buf)); \
4361 mflags &= ~(flag); \
4364 MNT_FLAG(MNT_RDONLY);
4365 MNT_FLAG(MNT_SYNCHRONOUS);
4366 MNT_FLAG(MNT_NOEXEC);
4367 MNT_FLAG(MNT_NOSUID);
4368 MNT_FLAG(MNT_NFS4ACLS);
4369 MNT_FLAG(MNT_UNION);
4370 MNT_FLAG(MNT_ASYNC);
4371 MNT_FLAG(MNT_SUIDDIR);
4372 MNT_FLAG(MNT_SOFTDEP);
4373 MNT_FLAG(MNT_NOSYMFOLLOW);
4374 MNT_FLAG(MNT_GJOURNAL);
4375 MNT_FLAG(MNT_MULTILABEL);
4377 MNT_FLAG(MNT_NOATIME);
4378 MNT_FLAG(MNT_NOCLUSTERR);
4379 MNT_FLAG(MNT_NOCLUSTERW);
4381 MNT_FLAG(MNT_EXRDONLY);
4382 MNT_FLAG(MNT_EXPORTED);
4383 MNT_FLAG(MNT_DEFEXPORTED);
4384 MNT_FLAG(MNT_EXPORTANON);
4385 MNT_FLAG(MNT_EXKERB);
4386 MNT_FLAG(MNT_EXPUBLIC);
4387 MNT_FLAG(MNT_LOCAL);
4388 MNT_FLAG(MNT_QUOTA);
4389 MNT_FLAG(MNT_ROOTFS);
4391 MNT_FLAG(MNT_IGNORE);
4392 MNT_FLAG(MNT_UPDATE);
4393 MNT_FLAG(MNT_DELEXPORT);
4394 MNT_FLAG(MNT_RELOAD);
4395 MNT_FLAG(MNT_FORCE);
4396 MNT_FLAG(MNT_SNAPSHOT);
4397 MNT_FLAG(MNT_BYFSID);
4401 strlcat(buf, ", ", sizeof(buf));
4402 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4403 "0x%016jx", mflags);
4405 db_printf(" mnt_flag = %s\n", buf);
4408 flags = mp->mnt_kern_flag;
4409 #define MNT_KERN_FLAG(flag) do { \
4410 if (flags & (flag)) { \
4411 if (buf[0] != '\0') \
4412 strlcat(buf, ", ", sizeof(buf)); \
4413 strlcat(buf, (#flag) + 5, sizeof(buf)); \
4417 MNT_KERN_FLAG(MNTK_UNMOUNTF);
4418 MNT_KERN_FLAG(MNTK_ASYNC);
4419 MNT_KERN_FLAG(MNTK_SOFTDEP);
4420 MNT_KERN_FLAG(MNTK_DRAINING);
4421 MNT_KERN_FLAG(MNTK_REFEXPIRE);
4422 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4423 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4424 MNT_KERN_FLAG(MNTK_NO_IOPF);
4425 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4426 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4427 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4428 MNT_KERN_FLAG(MNTK_MARKER);
4429 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4430 MNT_KERN_FLAG(MNTK_FPLOOKUP);
4431 MNT_KERN_FLAG(MNTK_NOASYNC);
4432 MNT_KERN_FLAG(MNTK_UNMOUNT);
4433 MNT_KERN_FLAG(MNTK_MWAIT);
4434 MNT_KERN_FLAG(MNTK_SUSPEND);
4435 MNT_KERN_FLAG(MNTK_SUSPEND2);
4436 MNT_KERN_FLAG(MNTK_SUSPENDED);
4437 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4438 MNT_KERN_FLAG(MNTK_NOKNOTE);
4439 #undef MNT_KERN_FLAG
4442 strlcat(buf, ", ", sizeof(buf));
4443 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4446 db_printf(" mnt_kern_flag = %s\n", buf);
4448 db_printf(" mnt_opt = ");
4449 opt = TAILQ_FIRST(mp->mnt_opt);
4451 db_printf("%s", opt->name);
4452 opt = TAILQ_NEXT(opt, link);
4453 while (opt != NULL) {
4454 db_printf(", %s", opt->name);
4455 opt = TAILQ_NEXT(opt, link);
4461 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4462 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4463 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4464 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4465 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4466 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4467 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4468 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4469 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4470 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4471 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4472 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4474 db_printf(" mnt_cred = { uid=%u ruid=%u",
4475 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4476 if (jailed(mp->mnt_cred))
4477 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4479 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4480 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4481 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4482 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4483 db_printf(" mnt_lazyvnodelistsize = %d\n",
4484 mp->mnt_lazyvnodelistsize);
4485 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4486 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4487 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4488 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4489 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4490 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4491 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4492 db_printf(" mnt_secondary_accwrites = %d\n",
4493 mp->mnt_secondary_accwrites);
4494 db_printf(" mnt_gjprovider = %s\n",
4495 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4496 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4498 db_printf("\n\nList of active vnodes\n");
4499 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4500 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4501 vn_printf(vp, "vnode ");
4506 db_printf("\n\nList of inactive vnodes\n");
4507 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4508 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4509 vn_printf(vp, "vnode ");
4518 * Fill in a struct xvfsconf based on a struct vfsconf.
4521 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4523 struct xvfsconf xvfsp;
4525 bzero(&xvfsp, sizeof(xvfsp));
4526 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4527 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4528 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4529 xvfsp.vfc_flags = vfsp->vfc_flags;
4531 * These are unused in userland, we keep them
4532 * to not break binary compatibility.
4534 xvfsp.vfc_vfsops = NULL;
4535 xvfsp.vfc_next = NULL;
4536 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4539 #ifdef COMPAT_FREEBSD32
4541 uint32_t vfc_vfsops;
4542 char vfc_name[MFSNAMELEN];
4543 int32_t vfc_typenum;
4544 int32_t vfc_refcount;
4550 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4552 struct xvfsconf32 xvfsp;
4554 bzero(&xvfsp, sizeof(xvfsp));
4555 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4556 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4557 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4558 xvfsp.vfc_flags = vfsp->vfc_flags;
4559 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4564 * Top level filesystem related information gathering.
4567 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4569 struct vfsconf *vfsp;
4574 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4575 #ifdef COMPAT_FREEBSD32
4576 if (req->flags & SCTL_MASK32)
4577 error = vfsconf2x32(req, vfsp);
4580 error = vfsconf2x(req, vfsp);
4588 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4589 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4590 "S,xvfsconf", "List of all configured filesystems");
4592 #ifndef BURN_BRIDGES
4593 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4596 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4598 int *name = (int *)arg1 - 1; /* XXX */
4599 u_int namelen = arg2 + 1; /* XXX */
4600 struct vfsconf *vfsp;
4602 log(LOG_WARNING, "userland calling deprecated sysctl, "
4603 "please rebuild world\n");
4605 #if 1 || defined(COMPAT_PRELITE2)
4606 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4608 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4612 case VFS_MAXTYPENUM:
4615 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4618 return (ENOTDIR); /* overloaded */
4620 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4621 if (vfsp->vfc_typenum == name[2])
4626 return (EOPNOTSUPP);
4627 #ifdef COMPAT_FREEBSD32
4628 if (req->flags & SCTL_MASK32)
4629 return (vfsconf2x32(req, vfsp));
4632 return (vfsconf2x(req, vfsp));
4634 return (EOPNOTSUPP);
4637 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4638 CTLFLAG_MPSAFE, vfs_sysctl,
4639 "Generic filesystem");
4641 #if 1 || defined(COMPAT_PRELITE2)
4644 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4647 struct vfsconf *vfsp;
4648 struct ovfsconf ovfs;
4651 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4652 bzero(&ovfs, sizeof(ovfs));
4653 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4654 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4655 ovfs.vfc_index = vfsp->vfc_typenum;
4656 ovfs.vfc_refcount = vfsp->vfc_refcount;
4657 ovfs.vfc_flags = vfsp->vfc_flags;
4658 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4668 #endif /* 1 || COMPAT_PRELITE2 */
4669 #endif /* !BURN_BRIDGES */
4671 #define KINFO_VNODESLOP 10
4674 * Dump vnode list (via sysctl).
4678 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4686 * Stale numvnodes access is not fatal here.
4689 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4691 /* Make an estimate */
4692 return (SYSCTL_OUT(req, 0, len));
4694 error = sysctl_wire_old_buffer(req, 0);
4697 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4699 mtx_lock(&mountlist_mtx);
4700 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4701 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4704 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4708 xvn[n].xv_size = sizeof *xvn;
4709 xvn[n].xv_vnode = vp;
4710 xvn[n].xv_id = 0; /* XXX compat */
4711 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4713 XV_COPY(writecount);
4719 xvn[n].xv_flag = vp->v_vflag;
4721 switch (vp->v_type) {
4728 if (vp->v_rdev == NULL) {
4732 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4735 xvn[n].xv_socket = vp->v_socket;
4738 xvn[n].xv_fifo = vp->v_fifoinfo;
4743 /* shouldn't happen? */
4751 mtx_lock(&mountlist_mtx);
4756 mtx_unlock(&mountlist_mtx);
4758 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4763 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4764 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4769 unmount_or_warn(struct mount *mp)
4773 error = dounmount(mp, MNT_FORCE, curthread);
4775 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4779 printf("%d)\n", error);
4784 * Unmount all filesystems. The list is traversed in reverse order
4785 * of mounting to avoid dependencies.
4788 vfs_unmountall(void)
4790 struct mount *mp, *tmp;
4792 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4795 * Since this only runs when rebooting, it is not interlocked.
4797 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4801 * Forcibly unmounting "/dev" before "/" would prevent clean
4802 * unmount of the latter.
4804 if (mp == rootdevmp)
4807 unmount_or_warn(mp);
4810 if (rootdevmp != NULL)
4811 unmount_or_warn(rootdevmp);
4815 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4818 ASSERT_VI_LOCKED(vp, __func__);
4819 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4820 if ((vp->v_iflag & VI_OWEINACT) == 0) {
4824 if (vn_lock(vp, lkflags) == 0) {
4831 vdefer_inactive_unlocked(vp);
4835 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4838 return (vp->v_iflag & VI_DEFINACT);
4841 static void __noinline
4842 vfs_periodic_inactive(struct mount *mp, int flags)
4844 struct vnode *vp, *mvp;
4847 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4848 if (flags != MNT_WAIT)
4849 lkflags |= LK_NOWAIT;
4851 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4852 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4856 vp->v_iflag &= ~VI_DEFINACT;
4857 vfs_deferred_inactive(vp, lkflags);
4862 vfs_want_msync(struct vnode *vp)
4864 struct vm_object *obj;
4867 * This test may be performed without any locks held.
4868 * We rely on vm_object's type stability.
4870 if (vp->v_vflag & VV_NOSYNC)
4873 return (obj != NULL && vm_object_mightbedirty(obj));
4877 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4880 if (vp->v_vflag & VV_NOSYNC)
4882 if (vp->v_iflag & VI_DEFINACT)
4884 return (vfs_want_msync(vp));
4887 static void __noinline
4888 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4890 struct vnode *vp, *mvp;
4891 struct vm_object *obj;
4892 int lkflags, objflags;
4895 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4896 if (flags != MNT_WAIT) {
4897 lkflags |= LK_NOWAIT;
4898 objflags = OBJPC_NOSYNC;
4900 objflags = OBJPC_SYNC;
4903 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4905 if (vp->v_iflag & VI_DEFINACT) {
4906 vp->v_iflag &= ~VI_DEFINACT;
4909 if (!vfs_want_msync(vp)) {
4911 vfs_deferred_inactive(vp, lkflags);
4916 if (vget(vp, lkflags) == 0) {
4918 if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4919 VM_OBJECT_WLOCK(obj);
4920 vm_object_page_clean(obj, 0, 0, objflags);
4921 VM_OBJECT_WUNLOCK(obj);
4928 vdefer_inactive_unlocked(vp);
4934 vfs_periodic(struct mount *mp, int flags)
4937 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4939 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4940 vfs_periodic_inactive(mp, flags);
4942 vfs_periodic_msync_inactive(mp, flags);
4946 destroy_vpollinfo_free(struct vpollinfo *vi)
4949 knlist_destroy(&vi->vpi_selinfo.si_note);
4950 mtx_destroy(&vi->vpi_lock);
4951 free(vi, M_VNODEPOLL);
4955 destroy_vpollinfo(struct vpollinfo *vi)
4958 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4959 seldrain(&vi->vpi_selinfo);
4960 destroy_vpollinfo_free(vi);
4964 * Initialize per-vnode helper structure to hold poll-related state.
4967 v_addpollinfo(struct vnode *vp)
4969 struct vpollinfo *vi;
4971 if (vp->v_pollinfo != NULL)
4973 vi = malloc(sizeof(*vi), M_VNODEPOLL, M_WAITOK | M_ZERO);
4974 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4975 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4976 vfs_knlunlock, vfs_knl_assert_lock);
4978 if (vp->v_pollinfo != NULL) {
4980 destroy_vpollinfo_free(vi);
4983 vp->v_pollinfo = vi;
4988 * Record a process's interest in events which might happen to
4989 * a vnode. Because poll uses the historic select-style interface
4990 * internally, this routine serves as both the ``check for any
4991 * pending events'' and the ``record my interest in future events''
4992 * functions. (These are done together, while the lock is held,
4993 * to avoid race conditions.)
4996 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
5000 mtx_lock(&vp->v_pollinfo->vpi_lock);
5001 if (vp->v_pollinfo->vpi_revents & events) {
5003 * This leaves events we are not interested
5004 * in available for the other process which
5005 * which presumably had requested them
5006 * (otherwise they would never have been
5009 events &= vp->v_pollinfo->vpi_revents;
5010 vp->v_pollinfo->vpi_revents &= ~events;
5012 mtx_unlock(&vp->v_pollinfo->vpi_lock);
5015 vp->v_pollinfo->vpi_events |= events;
5016 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
5017 mtx_unlock(&vp->v_pollinfo->vpi_lock);
5022 * Routine to create and manage a filesystem syncer vnode.
5024 #define sync_close ((int (*)(struct vop_close_args *))nullop)
5025 static int sync_fsync(struct vop_fsync_args *);
5026 static int sync_inactive(struct vop_inactive_args *);
5027 static int sync_reclaim(struct vop_reclaim_args *);
5029 static struct vop_vector sync_vnodeops = {
5030 .vop_bypass = VOP_EOPNOTSUPP,
5031 .vop_close = sync_close, /* close */
5032 .vop_fsync = sync_fsync, /* fsync */
5033 .vop_inactive = sync_inactive, /* inactive */
5034 .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
5035 .vop_reclaim = sync_reclaim, /* reclaim */
5036 .vop_lock1 = vop_stdlock, /* lock */
5037 .vop_unlock = vop_stdunlock, /* unlock */
5038 .vop_islocked = vop_stdislocked, /* islocked */
5040 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
5043 * Create a new filesystem syncer vnode for the specified mount point.
5046 vfs_allocate_syncvnode(struct mount *mp)
5050 static long start, incr, next;
5053 /* Allocate a new vnode */
5054 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
5056 panic("vfs_allocate_syncvnode: getnewvnode() failed");
5058 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5059 vp->v_vflag |= VV_FORCEINSMQ;
5060 error = insmntque(vp, mp);
5062 panic("vfs_allocate_syncvnode: insmntque() failed");
5063 vp->v_vflag &= ~VV_FORCEINSMQ;
5066 * Place the vnode onto the syncer worklist. We attempt to
5067 * scatter them about on the list so that they will go off
5068 * at evenly distributed times even if all the filesystems
5069 * are mounted at once.
5072 if (next == 0 || next > syncer_maxdelay) {
5076 start = syncer_maxdelay / 2;
5077 incr = syncer_maxdelay;
5083 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
5084 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
5085 mtx_lock(&sync_mtx);
5087 if (mp->mnt_syncer == NULL) {
5088 mp->mnt_syncer = vp;
5091 mtx_unlock(&sync_mtx);
5094 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5101 vfs_deallocate_syncvnode(struct mount *mp)
5105 mtx_lock(&sync_mtx);
5106 vp = mp->mnt_syncer;
5108 mp->mnt_syncer = NULL;
5109 mtx_unlock(&sync_mtx);
5115 * Do a lazy sync of the filesystem.
5118 sync_fsync(struct vop_fsync_args *ap)
5120 struct vnode *syncvp = ap->a_vp;
5121 struct mount *mp = syncvp->v_mount;
5126 * We only need to do something if this is a lazy evaluation.
5128 if (ap->a_waitfor != MNT_LAZY)
5132 * Move ourselves to the back of the sync list.
5134 bo = &syncvp->v_bufobj;
5136 vn_syncer_add_to_worklist(bo, syncdelay);
5140 * Walk the list of vnodes pushing all that are dirty and
5141 * not already on the sync list.
5143 if (vfs_busy(mp, MBF_NOWAIT) != 0)
5146 save = curthread_pflags_set(TDP_SYNCIO);
5148 * The filesystem at hand may be idle with free vnodes stored in the
5149 * batch. Return them instead of letting them stay there indefinitely.
5151 vfs_periodic(mp, MNT_NOWAIT);
5152 error = VFS_SYNC(mp, MNT_LAZY);
5153 curthread_pflags_restore(save);
5154 vn_lock(syncvp, LK_EXCLUSIVE | LK_RETRY);
5160 * The syncer vnode is no referenced.
5163 sync_inactive(struct vop_inactive_args *ap)
5171 * The syncer vnode is no longer needed and is being decommissioned.
5173 * Modifications to the worklist must be protected by sync_mtx.
5176 sync_reclaim(struct vop_reclaim_args *ap)
5178 struct vnode *vp = ap->a_vp;
5183 mtx_lock(&sync_mtx);
5184 if (vp->v_mount->mnt_syncer == vp)
5185 vp->v_mount->mnt_syncer = NULL;
5186 if (bo->bo_flag & BO_ONWORKLST) {
5187 LIST_REMOVE(bo, bo_synclist);
5188 syncer_worklist_len--;
5190 bo->bo_flag &= ~BO_ONWORKLST;
5192 mtx_unlock(&sync_mtx);
5199 vn_need_pageq_flush(struct vnode *vp)
5201 struct vm_object *obj;
5204 return (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
5205 vm_object_mightbedirty(obj));
5209 * Check if vnode represents a disk device
5212 vn_isdisk_error(struct vnode *vp, int *errp)
5216 if (vp->v_type != VCHR) {
5222 if (vp->v_rdev == NULL)
5224 else if (vp->v_rdev->si_devsw == NULL)
5226 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5231 return (error == 0);
5235 vn_isdisk(struct vnode *vp)
5239 return (vn_isdisk_error(vp, &error));
5243 * VOP_FPLOOKUP_VEXEC routines are subject to special circumstances, see
5244 * the comment above cache_fplookup for details.
5247 vaccess_vexec_smr(mode_t file_mode, uid_t file_uid, gid_t file_gid, struct ucred *cred)
5251 VFS_SMR_ASSERT_ENTERED();
5253 /* Check the owner. */
5254 if (cred->cr_uid == file_uid) {
5255 if (file_mode & S_IXUSR)
5260 /* Otherwise, check the groups (first match) */
5261 if (groupmember(file_gid, cred)) {
5262 if (file_mode & S_IXGRP)
5267 /* Otherwise, check everyone else. */
5268 if (file_mode & S_IXOTH)
5272 * Permission check failed, but it is possible denial will get overwritten
5273 * (e.g., when root is traversing through a 700 directory owned by someone
5276 * vaccess() calls priv_check_cred which in turn can descent into MAC
5277 * modules overriding this result. It's quite unclear what semantics
5278 * are allowed for them to operate, thus for safety we don't call them
5279 * from within the SMR section. This also means if any such modules
5280 * are present, we have to let the regular lookup decide.
5282 error = priv_check_cred_vfs_lookup_nomac(cred);
5288 * MAC modules present.
5299 * Common filesystem object access control check routine. Accepts a
5300 * vnode's type, "mode", uid and gid, requested access mode, and credentials.
5301 * Returns 0 on success, or an errno on failure.
5304 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5305 accmode_t accmode, struct ucred *cred)
5307 accmode_t dac_granted;
5308 accmode_t priv_granted;
5310 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5311 ("invalid bit in accmode"));
5312 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5313 ("VAPPEND without VWRITE"));
5316 * Look for a normal, non-privileged way to access the file/directory
5317 * as requested. If it exists, go with that.
5322 /* Check the owner. */
5323 if (cred->cr_uid == file_uid) {
5324 dac_granted |= VADMIN;
5325 if (file_mode & S_IXUSR)
5326 dac_granted |= VEXEC;
5327 if (file_mode & S_IRUSR)
5328 dac_granted |= VREAD;
5329 if (file_mode & S_IWUSR)
5330 dac_granted |= (VWRITE | VAPPEND);
5332 if ((accmode & dac_granted) == accmode)
5338 /* Otherwise, check the groups (first match) */
5339 if (groupmember(file_gid, cred)) {
5340 if (file_mode & S_IXGRP)
5341 dac_granted |= VEXEC;
5342 if (file_mode & S_IRGRP)
5343 dac_granted |= VREAD;
5344 if (file_mode & S_IWGRP)
5345 dac_granted |= (VWRITE | VAPPEND);
5347 if ((accmode & dac_granted) == accmode)
5353 /* Otherwise, check everyone else. */
5354 if (file_mode & S_IXOTH)
5355 dac_granted |= VEXEC;
5356 if (file_mode & S_IROTH)
5357 dac_granted |= VREAD;
5358 if (file_mode & S_IWOTH)
5359 dac_granted |= (VWRITE | VAPPEND);
5360 if ((accmode & dac_granted) == accmode)
5365 * Build a privilege mask to determine if the set of privileges
5366 * satisfies the requirements when combined with the granted mask
5367 * from above. For each privilege, if the privilege is required,
5368 * bitwise or the request type onto the priv_granted mask.
5374 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5375 * requests, instead of PRIV_VFS_EXEC.
5377 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5378 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5379 priv_granted |= VEXEC;
5382 * Ensure that at least one execute bit is on. Otherwise,
5383 * a privileged user will always succeed, and we don't want
5384 * this to happen unless the file really is executable.
5386 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5387 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5388 !priv_check_cred(cred, PRIV_VFS_EXEC))
5389 priv_granted |= VEXEC;
5392 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5393 !priv_check_cred(cred, PRIV_VFS_READ))
5394 priv_granted |= VREAD;
5396 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5397 !priv_check_cred(cred, PRIV_VFS_WRITE))
5398 priv_granted |= (VWRITE | VAPPEND);
5400 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5401 !priv_check_cred(cred, PRIV_VFS_ADMIN))
5402 priv_granted |= VADMIN;
5404 if ((accmode & (priv_granted | dac_granted)) == accmode) {
5408 return ((accmode & VADMIN) ? EPERM : EACCES);
5412 * Credential check based on process requesting service, and per-attribute
5416 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5417 struct thread *td, accmode_t accmode)
5421 * Kernel-invoked always succeeds.
5427 * Do not allow privileged processes in jail to directly manipulate
5428 * system attributes.
5430 switch (attrnamespace) {
5431 case EXTATTR_NAMESPACE_SYSTEM:
5432 /* Potentially should be: return (EPERM); */
5433 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5434 case EXTATTR_NAMESPACE_USER:
5435 return (VOP_ACCESS(vp, accmode, cred, td));
5441 #ifdef DEBUG_VFS_LOCKS
5442 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
5443 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5444 "Drop into debugger on lock violation");
5446 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
5447 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5448 0, "Check for interlock across VOPs");
5450 int vfs_badlock_print = 1; /* Print lock violations. */
5451 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5452 0, "Print lock violations");
5454 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
5455 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5456 0, "Print vnode details on lock violations");
5459 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
5460 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5461 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5465 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5469 if (vfs_badlock_backtrace)
5472 if (vfs_badlock_vnode)
5473 vn_printf(vp, "vnode ");
5474 if (vfs_badlock_print)
5475 printf("%s: %p %s\n", str, (void *)vp, msg);
5476 if (vfs_badlock_ddb)
5477 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5481 assert_vi_locked(struct vnode *vp, const char *str)
5484 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5485 vfs_badlock("interlock is not locked but should be", str, vp);
5489 assert_vi_unlocked(struct vnode *vp, const char *str)
5492 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5493 vfs_badlock("interlock is locked but should not be", str, vp);
5497 assert_vop_locked(struct vnode *vp, const char *str)
5501 if (KERNEL_PANICKED() || vp == NULL)
5504 locked = VOP_ISLOCKED(vp);
5505 if (locked == 0 || locked == LK_EXCLOTHER)
5506 vfs_badlock("is not locked but should be", str, vp);
5510 assert_vop_unlocked(struct vnode *vp, const char *str)
5512 if (KERNEL_PANICKED() || vp == NULL)
5515 if (VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5516 vfs_badlock("is locked but should not be", str, vp);
5520 assert_vop_elocked(struct vnode *vp, const char *str)
5522 if (KERNEL_PANICKED() || vp == NULL)
5525 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5526 vfs_badlock("is not exclusive locked but should be", str, vp);
5528 #endif /* DEBUG_VFS_LOCKS */
5531 vop_rename_fail(struct vop_rename_args *ap)
5534 if (ap->a_tvp != NULL)
5536 if (ap->a_tdvp == ap->a_tvp)
5545 vop_rename_pre(void *ap)
5547 struct vop_rename_args *a = ap;
5549 #ifdef DEBUG_VFS_LOCKS
5551 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5552 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5553 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5554 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5556 /* Check the source (from). */
5557 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5558 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5559 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5560 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5561 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5563 /* Check the target. */
5565 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5566 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5569 * It may be tempting to add vn_seqc_write_begin/end calls here and
5570 * in vop_rename_post but that's not going to work out since some
5571 * filesystems relookup vnodes mid-rename. This is probably a bug.
5573 * For now filesystems are expected to do the relevant calls after they
5574 * decide what vnodes to operate on.
5576 if (a->a_tdvp != a->a_fdvp)
5578 if (a->a_tvp != a->a_fvp)
5585 #ifdef DEBUG_VFS_LOCKS
5587 vop_fplookup_vexec_debugpre(void *ap __unused)
5590 VFS_SMR_ASSERT_ENTERED();
5594 vop_fplookup_vexec_debugpost(void *ap __unused, int rc __unused)
5597 VFS_SMR_ASSERT_ENTERED();
5601 vop_fplookup_symlink_debugpre(void *ap __unused)
5604 VFS_SMR_ASSERT_ENTERED();
5608 vop_fplookup_symlink_debugpost(void *ap __unused, int rc __unused)
5611 VFS_SMR_ASSERT_ENTERED();
5615 vop_fsync_debugprepost(struct vnode *vp, const char *name)
5617 if (vp->v_type == VCHR)
5619 else if (MNT_EXTENDED_SHARED(vp->v_mount))
5620 ASSERT_VOP_LOCKED(vp, name);
5622 ASSERT_VOP_ELOCKED(vp, name);
5626 vop_fsync_debugpre(void *a)
5628 struct vop_fsync_args *ap;
5631 vop_fsync_debugprepost(ap->a_vp, "fsync");
5635 vop_fsync_debugpost(void *a, int rc __unused)
5637 struct vop_fsync_args *ap;
5640 vop_fsync_debugprepost(ap->a_vp, "fsync");
5644 vop_fdatasync_debugpre(void *a)
5646 struct vop_fdatasync_args *ap;
5649 vop_fsync_debugprepost(ap->a_vp, "fsync");
5653 vop_fdatasync_debugpost(void *a, int rc __unused)
5655 struct vop_fdatasync_args *ap;
5658 vop_fsync_debugprepost(ap->a_vp, "fsync");
5662 vop_strategy_debugpre(void *ap)
5664 struct vop_strategy_args *a;
5671 * Cluster ops lock their component buffers but not the IO container.
5673 if ((bp->b_flags & B_CLUSTER) != 0)
5676 if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5677 if (vfs_badlock_print)
5679 "VOP_STRATEGY: bp is not locked but should be\n");
5680 if (vfs_badlock_ddb)
5681 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5686 vop_lock_debugpre(void *ap)
5688 struct vop_lock1_args *a = ap;
5690 if ((a->a_flags & LK_INTERLOCK) == 0)
5691 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5693 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5697 vop_lock_debugpost(void *ap, int rc)
5699 struct vop_lock1_args *a = ap;
5701 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5702 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5703 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5707 vop_unlock_debugpre(void *ap)
5709 struct vop_unlock_args *a = ap;
5711 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5715 vop_need_inactive_debugpre(void *ap)
5717 struct vop_need_inactive_args *a = ap;
5719 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5723 vop_need_inactive_debugpost(void *ap, int rc)
5725 struct vop_need_inactive_args *a = ap;
5727 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5732 vop_create_pre(void *ap)
5734 struct vop_create_args *a;
5739 vn_seqc_write_begin(dvp);
5743 vop_create_post(void *ap, int rc)
5745 struct vop_create_args *a;
5750 vn_seqc_write_end(dvp);
5752 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5756 vop_whiteout_pre(void *ap)
5758 struct vop_whiteout_args *a;
5763 vn_seqc_write_begin(dvp);
5767 vop_whiteout_post(void *ap, int rc)
5769 struct vop_whiteout_args *a;
5774 vn_seqc_write_end(dvp);
5778 vop_deleteextattr_pre(void *ap)
5780 struct vop_deleteextattr_args *a;
5785 vn_seqc_write_begin(vp);
5789 vop_deleteextattr_post(void *ap, int rc)
5791 struct vop_deleteextattr_args *a;
5796 vn_seqc_write_end(vp);
5798 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5802 vop_link_pre(void *ap)
5804 struct vop_link_args *a;
5805 struct vnode *vp, *tdvp;
5810 vn_seqc_write_begin(vp);
5811 vn_seqc_write_begin(tdvp);
5815 vop_link_post(void *ap, int rc)
5817 struct vop_link_args *a;
5818 struct vnode *vp, *tdvp;
5823 vn_seqc_write_end(vp);
5824 vn_seqc_write_end(tdvp);
5826 VFS_KNOTE_LOCKED(vp, NOTE_LINK);
5827 VFS_KNOTE_LOCKED(tdvp, NOTE_WRITE);
5832 vop_mkdir_pre(void *ap)
5834 struct vop_mkdir_args *a;
5839 vn_seqc_write_begin(dvp);
5843 vop_mkdir_post(void *ap, int rc)
5845 struct vop_mkdir_args *a;
5850 vn_seqc_write_end(dvp);
5852 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5855 #ifdef DEBUG_VFS_LOCKS
5857 vop_mkdir_debugpost(void *ap, int rc)
5859 struct vop_mkdir_args *a;
5863 cache_validate(a->a_dvp, *a->a_vpp, a->a_cnp);
5868 vop_mknod_pre(void *ap)
5870 struct vop_mknod_args *a;
5875 vn_seqc_write_begin(dvp);
5879 vop_mknod_post(void *ap, int rc)
5881 struct vop_mknod_args *a;
5886 vn_seqc_write_end(dvp);
5888 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5892 vop_reclaim_post(void *ap, int rc)
5894 struct vop_reclaim_args *a;
5899 ASSERT_VOP_IN_SEQC(vp);
5901 VFS_KNOTE_LOCKED(vp, NOTE_REVOKE);
5905 vop_remove_pre(void *ap)
5907 struct vop_remove_args *a;
5908 struct vnode *dvp, *vp;
5913 vn_seqc_write_begin(dvp);
5914 vn_seqc_write_begin(vp);
5918 vop_remove_post(void *ap, int rc)
5920 struct vop_remove_args *a;
5921 struct vnode *dvp, *vp;
5926 vn_seqc_write_end(dvp);
5927 vn_seqc_write_end(vp);
5929 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5930 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5935 vop_rename_post(void *ap, int rc)
5937 struct vop_rename_args *a = ap;
5942 if (a->a_fdvp == a->a_tdvp) {
5943 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5945 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5946 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5948 hint |= NOTE_EXTEND;
5949 if (a->a_fvp->v_type == VDIR)
5951 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5953 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5954 a->a_tvp->v_type == VDIR)
5956 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5959 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5961 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5963 if (a->a_tdvp != a->a_fdvp)
5965 if (a->a_tvp != a->a_fvp)
5973 vop_rmdir_pre(void *ap)
5975 struct vop_rmdir_args *a;
5976 struct vnode *dvp, *vp;
5981 vn_seqc_write_begin(dvp);
5982 vn_seqc_write_begin(vp);
5986 vop_rmdir_post(void *ap, int rc)
5988 struct vop_rmdir_args *a;
5989 struct vnode *dvp, *vp;
5994 vn_seqc_write_end(dvp);
5995 vn_seqc_write_end(vp);
5997 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5998 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
6003 vop_setattr_pre(void *ap)
6005 struct vop_setattr_args *a;
6010 vn_seqc_write_begin(vp);
6014 vop_setattr_post(void *ap, int rc)
6016 struct vop_setattr_args *a;
6021 vn_seqc_write_end(vp);
6023 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6027 vop_setacl_pre(void *ap)
6029 struct vop_setacl_args *a;
6034 vn_seqc_write_begin(vp);
6038 vop_setacl_post(void *ap, int rc __unused)
6040 struct vop_setacl_args *a;
6045 vn_seqc_write_end(vp);
6049 vop_setextattr_pre(void *ap)
6051 struct vop_setextattr_args *a;
6056 vn_seqc_write_begin(vp);
6060 vop_setextattr_post(void *ap, int rc)
6062 struct vop_setextattr_args *a;
6067 vn_seqc_write_end(vp);
6069 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6073 vop_symlink_pre(void *ap)
6075 struct vop_symlink_args *a;
6080 vn_seqc_write_begin(dvp);
6084 vop_symlink_post(void *ap, int rc)
6086 struct vop_symlink_args *a;
6091 vn_seqc_write_end(dvp);
6093 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6097 vop_open_post(void *ap, int rc)
6099 struct vop_open_args *a = ap;
6102 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
6106 vop_close_post(void *ap, int rc)
6108 struct vop_close_args *a = ap;
6110 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
6111 !VN_IS_DOOMED(a->a_vp))) {
6112 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
6113 NOTE_CLOSE_WRITE : NOTE_CLOSE);
6118 vop_read_post(void *ap, int rc)
6120 struct vop_read_args *a = ap;
6123 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6127 vop_read_pgcache_post(void *ap, int rc)
6129 struct vop_read_pgcache_args *a = ap;
6132 VFS_KNOTE_UNLOCKED(a->a_vp, NOTE_READ);
6136 vop_readdir_post(void *ap, int rc)
6138 struct vop_readdir_args *a = ap;
6141 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6144 static struct knlist fs_knlist;
6147 vfs_event_init(void *arg)
6149 knlist_init_mtx(&fs_knlist, NULL);
6151 /* XXX - correct order? */
6152 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
6155 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
6158 KNOTE_UNLOCKED(&fs_knlist, event);
6161 static int filt_fsattach(struct knote *kn);
6162 static void filt_fsdetach(struct knote *kn);
6163 static int filt_fsevent(struct knote *kn, long hint);
6165 struct filterops fs_filtops = {
6167 .f_attach = filt_fsattach,
6168 .f_detach = filt_fsdetach,
6169 .f_event = filt_fsevent
6173 filt_fsattach(struct knote *kn)
6176 kn->kn_flags |= EV_CLEAR;
6177 knlist_add(&fs_knlist, kn, 0);
6182 filt_fsdetach(struct knote *kn)
6185 knlist_remove(&fs_knlist, kn, 0);
6189 filt_fsevent(struct knote *kn, long hint)
6192 kn->kn_fflags |= hint;
6193 return (kn->kn_fflags != 0);
6197 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
6203 error = SYSCTL_IN(req, &vc, sizeof(vc));
6206 if (vc.vc_vers != VFS_CTL_VERS1)
6208 mp = vfs_getvfs(&vc.vc_fsid);
6211 /* ensure that a specific sysctl goes to the right filesystem. */
6212 if (strcmp(vc.vc_fstypename, "*") != 0 &&
6213 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
6217 VCTLTOREQ(&vc, req);
6218 error = VFS_SYSCTL(mp, vc.vc_op, req);
6223 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
6224 NULL, 0, sysctl_vfs_ctl, "",
6228 * Function to initialize a va_filerev field sensibly.
6229 * XXX: Wouldn't a random number make a lot more sense ??
6232 init_va_filerev(void)
6237 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
6240 static int filt_vfsread(struct knote *kn, long hint);
6241 static int filt_vfswrite(struct knote *kn, long hint);
6242 static int filt_vfsvnode(struct knote *kn, long hint);
6243 static void filt_vfsdetach(struct knote *kn);
6244 static struct filterops vfsread_filtops = {
6246 .f_detach = filt_vfsdetach,
6247 .f_event = filt_vfsread
6249 static struct filterops vfswrite_filtops = {
6251 .f_detach = filt_vfsdetach,
6252 .f_event = filt_vfswrite
6254 static struct filterops vfsvnode_filtops = {
6256 .f_detach = filt_vfsdetach,
6257 .f_event = filt_vfsvnode
6261 vfs_knllock(void *arg)
6263 struct vnode *vp = arg;
6265 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
6269 vfs_knlunlock(void *arg)
6271 struct vnode *vp = arg;
6277 vfs_knl_assert_lock(void *arg, int what)
6279 #ifdef DEBUG_VFS_LOCKS
6280 struct vnode *vp = arg;
6282 if (what == LA_LOCKED)
6283 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
6285 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
6290 vfs_kqfilter(struct vop_kqfilter_args *ap)
6292 struct vnode *vp = ap->a_vp;
6293 struct knote *kn = ap->a_kn;
6296 switch (kn->kn_filter) {
6298 kn->kn_fop = &vfsread_filtops;
6301 kn->kn_fop = &vfswrite_filtops;
6304 kn->kn_fop = &vfsvnode_filtops;
6310 kn->kn_hook = (caddr_t)vp;
6313 if (vp->v_pollinfo == NULL)
6315 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
6317 knlist_add(knl, kn, 0);
6323 * Detach knote from vnode
6326 filt_vfsdetach(struct knote *kn)
6328 struct vnode *vp = (struct vnode *)kn->kn_hook;
6330 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
6331 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
6337 filt_vfsread(struct knote *kn, long hint)
6339 struct vnode *vp = (struct vnode *)kn->kn_hook;
6344 * filesystem is gone, so set the EOF flag and schedule
6345 * the knote for deletion.
6347 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6349 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6354 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
6358 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
6359 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
6366 filt_vfswrite(struct knote *kn, long hint)
6368 struct vnode *vp = (struct vnode *)kn->kn_hook;
6373 * filesystem is gone, so set the EOF flag and schedule
6374 * the knote for deletion.
6376 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
6377 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6385 filt_vfsvnode(struct knote *kn, long hint)
6387 struct vnode *vp = (struct vnode *)kn->kn_hook;
6391 if (kn->kn_sfflags & hint)
6392 kn->kn_fflags |= hint;
6393 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6394 kn->kn_flags |= EV_EOF;
6398 res = (kn->kn_fflags != 0);
6404 * Returns whether the directory is empty or not.
6405 * If it is empty, the return value is 0; otherwise
6406 * the return value is an error value (which may
6410 vfs_emptydir(struct vnode *vp)
6414 struct dirent *dirent, *dp, *endp;
6420 ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
6421 VNASSERT(vp->v_type == VDIR, vp, ("vp is not a directory"));
6423 dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
6424 iov.iov_base = dirent;
6425 iov.iov_len = sizeof(struct dirent);
6430 uio.uio_resid = sizeof(struct dirent);
6431 uio.uio_segflg = UIO_SYSSPACE;
6432 uio.uio_rw = UIO_READ;
6433 uio.uio_td = curthread;
6435 while (eof == 0 && error == 0) {
6436 error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
6440 endp = (void *)((uint8_t *)dirent +
6441 sizeof(struct dirent) - uio.uio_resid);
6442 for (dp = dirent; dp < endp;
6443 dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
6444 if (dp->d_type == DT_WHT)
6446 if (dp->d_namlen == 0)
6448 if (dp->d_type != DT_DIR &&
6449 dp->d_type != DT_UNKNOWN) {
6453 if (dp->d_namlen > 2) {
6457 if (dp->d_namlen == 1 &&
6458 dp->d_name[0] != '.') {
6462 if (dp->d_namlen == 2 &&
6463 dp->d_name[1] != '.') {
6467 uio.uio_resid = sizeof(struct dirent);
6470 free(dirent, M_TEMP);
6475 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6479 if (dp->d_reclen > ap->a_uio->uio_resid)
6480 return (ENAMETOOLONG);
6481 error = uiomove(dp, dp->d_reclen, ap->a_uio);
6483 if (ap->a_ncookies != NULL) {
6484 if (ap->a_cookies != NULL)
6485 free(ap->a_cookies, M_TEMP);
6486 ap->a_cookies = NULL;
6487 *ap->a_ncookies = 0;
6491 if (ap->a_ncookies == NULL)
6494 KASSERT(ap->a_cookies,
6495 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6497 *ap->a_cookies = realloc(*ap->a_cookies,
6498 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
6499 (*ap->a_cookies)[*ap->a_ncookies] = off;
6500 *ap->a_ncookies += 1;
6505 * The purpose of this routine is to remove granularity from accmode_t,
6506 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6507 * VADMIN and VAPPEND.
6509 * If it returns 0, the caller is supposed to continue with the usual
6510 * access checks using 'accmode' as modified by this routine. If it
6511 * returns nonzero value, the caller is supposed to return that value
6514 * Note that after this routine runs, accmode may be zero.
6517 vfs_unixify_accmode(accmode_t *accmode)
6520 * There is no way to specify explicit "deny" rule using
6521 * file mode or POSIX.1e ACLs.
6523 if (*accmode & VEXPLICIT_DENY) {
6529 * None of these can be translated into usual access bits.
6530 * Also, the common case for NFSv4 ACLs is to not contain
6531 * either of these bits. Caller should check for VWRITE
6532 * on the containing directory instead.
6534 if (*accmode & (VDELETE_CHILD | VDELETE))
6537 if (*accmode & VADMIN_PERMS) {
6538 *accmode &= ~VADMIN_PERMS;
6543 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6544 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6546 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6552 * Clear out a doomed vnode (if any) and replace it with a new one as long
6553 * as the fs is not being unmounted. Return the root vnode to the caller.
6555 static int __noinline
6556 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6562 if (mp->mnt_rootvnode != NULL) {
6564 vp = mp->mnt_rootvnode;
6566 if (!VN_IS_DOOMED(vp)) {
6569 error = vn_lock(vp, flags);
6578 * Clear the old one.
6580 mp->mnt_rootvnode = NULL;
6584 vfs_op_barrier_wait(mp);
6588 error = VFS_CACHEDROOT(mp, flags, vpp);
6591 if (mp->mnt_vfs_ops == 0) {
6593 if (mp->mnt_vfs_ops != 0) {
6597 if (mp->mnt_rootvnode == NULL) {
6599 mp->mnt_rootvnode = *vpp;
6601 if (mp->mnt_rootvnode != *vpp) {
6602 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6603 panic("%s: mismatch between vnode returned "
6604 " by VFS_CACHEDROOT and the one cached "
6606 __func__, *vpp, mp->mnt_rootvnode);
6616 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6618 struct mount_pcpu *mpcpu;
6622 if (!vfs_op_thread_enter(mp, mpcpu))
6623 return (vfs_cache_root_fallback(mp, flags, vpp));
6624 vp = atomic_load_ptr(&mp->mnt_rootvnode);
6625 if (vp == NULL || VN_IS_DOOMED(vp)) {
6626 vfs_op_thread_exit(mp, mpcpu);
6627 return (vfs_cache_root_fallback(mp, flags, vpp));
6630 vfs_op_thread_exit(mp, mpcpu);
6631 error = vn_lock(vp, flags);
6634 return (vfs_cache_root_fallback(mp, flags, vpp));
6641 vfs_cache_root_clear(struct mount *mp)
6646 * ops > 0 guarantees there is nobody who can see this vnode
6648 MPASS(mp->mnt_vfs_ops > 0);
6649 vp = mp->mnt_rootvnode;
6651 vn_seqc_write_begin(vp);
6652 mp->mnt_rootvnode = NULL;
6657 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6660 MPASS(mp->mnt_vfs_ops > 0);
6662 mp->mnt_rootvnode = vp;
6666 * These are helper functions for filesystems to traverse all
6667 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6669 * This interface replaces MNT_VNODE_FOREACH.
6673 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6678 kern_yield(PRI_USER);
6680 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6681 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6682 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6683 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6684 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6687 if (VN_IS_DOOMED(vp)) {
6694 __mnt_vnode_markerfree_all(mvp, mp);
6695 /* MNT_IUNLOCK(mp); -- done in above function */
6696 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6699 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6700 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6706 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6710 *mvp = vn_alloc_marker(mp);
6714 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6715 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6716 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6719 if (VN_IS_DOOMED(vp)) {
6728 vn_free_marker(*mvp);
6732 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6738 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6746 mtx_assert(MNT_MTX(mp), MA_OWNED);
6748 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6749 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6752 vn_free_marker(*mvp);
6757 * These are helper functions for filesystems to traverse their
6758 * lazy vnodes. See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6761 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6764 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6769 vn_free_marker(*mvp);
6774 * Relock the mp mount vnode list lock with the vp vnode interlock in the
6775 * conventional lock order during mnt_vnode_next_lazy iteration.
6777 * On entry, the mount vnode list lock is held and the vnode interlock is not.
6778 * The list lock is dropped and reacquired. On success, both locks are held.
6779 * On failure, the mount vnode list lock is held but the vnode interlock is
6780 * not, and the procedure may have yielded.
6783 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6787 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6788 TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6789 ("%s: bad marker", __func__));
6790 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6791 ("%s: inappropriate vnode", __func__));
6792 ASSERT_VI_UNLOCKED(vp, __func__);
6793 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6795 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6796 TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6799 * Note we may be racing against vdrop which transitioned the hold
6800 * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
6801 * if we are the only user after we get the interlock we will just
6805 mtx_unlock(&mp->mnt_listmtx);
6807 if (VN_IS_DOOMED(vp)) {
6808 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
6811 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
6813 * There is nothing to do if we are the last user.
6815 if (!refcount_release_if_not_last(&vp->v_holdcnt))
6817 mtx_lock(&mp->mnt_listmtx);
6822 mtx_lock(&mp->mnt_listmtx);
6826 static struct vnode *
6827 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6832 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6833 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6835 vp = TAILQ_NEXT(*mvp, v_lazylist);
6836 while (vp != NULL) {
6837 if (vp->v_type == VMARKER) {
6838 vp = TAILQ_NEXT(vp, v_lazylist);
6842 * See if we want to process the vnode. Note we may encounter a
6843 * long string of vnodes we don't care about and hog the list
6844 * as a result. Check for it and requeue the marker.
6846 VNPASS(!VN_IS_DOOMED(vp), vp);
6847 if (!cb(vp, cbarg)) {
6848 if (!should_yield()) {
6849 vp = TAILQ_NEXT(vp, v_lazylist);
6852 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6854 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6856 mtx_unlock(&mp->mnt_listmtx);
6857 kern_yield(PRI_USER);
6858 mtx_lock(&mp->mnt_listmtx);
6862 * Try-lock because this is the wrong lock order.
6864 if (!VI_TRYLOCK(vp) &&
6865 !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6867 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6868 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6869 ("alien vnode on the lazy list %p %p", vp, mp));
6870 VNPASS(vp->v_mount == mp, vp);
6871 VNPASS(!VN_IS_DOOMED(vp), vp);
6874 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6876 /* Check if we are done */
6878 mtx_unlock(&mp->mnt_listmtx);
6879 mnt_vnode_markerfree_lazy(mvp, mp);
6882 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6883 mtx_unlock(&mp->mnt_listmtx);
6884 ASSERT_VI_LOCKED(vp, "lazy iter");
6889 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6894 kern_yield(PRI_USER);
6895 mtx_lock(&mp->mnt_listmtx);
6896 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6900 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6905 if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
6908 *mvp = vn_alloc_marker(mp);
6913 mtx_lock(&mp->mnt_listmtx);
6914 vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6916 mtx_unlock(&mp->mnt_listmtx);
6917 mnt_vnode_markerfree_lazy(mvp, mp);
6920 TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6921 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6925 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6931 mtx_lock(&mp->mnt_listmtx);
6932 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6933 mtx_unlock(&mp->mnt_listmtx);
6934 mnt_vnode_markerfree_lazy(mvp, mp);
6938 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
6941 if ((cnp->cn_flags & NOEXECCHECK) != 0) {
6942 cnp->cn_flags &= ~NOEXECCHECK;
6946 return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, cnp->cn_thread));
6950 * Do not use this variant unless you have means other than the hold count
6951 * to prevent the vnode from getting freed.
6954 vn_seqc_write_begin_locked(struct vnode *vp)
6957 ASSERT_VI_LOCKED(vp, __func__);
6958 VNPASS(vp->v_holdcnt > 0, vp);
6959 VNPASS(vp->v_seqc_users >= 0, vp);
6961 if (vp->v_seqc_users == 1)
6962 seqc_sleepable_write_begin(&vp->v_seqc);
6966 vn_seqc_write_begin(struct vnode *vp)
6970 vn_seqc_write_begin_locked(vp);
6975 vn_seqc_write_end_locked(struct vnode *vp)
6978 ASSERT_VI_LOCKED(vp, __func__);
6979 VNPASS(vp->v_seqc_users > 0, vp);
6981 if (vp->v_seqc_users == 0)
6982 seqc_sleepable_write_end(&vp->v_seqc);
6986 vn_seqc_write_end(struct vnode *vp)
6990 vn_seqc_write_end_locked(vp);
6995 * Special case handling for allocating and freeing vnodes.
6997 * The counter remains unchanged on free so that a doomed vnode will
6998 * keep testing as in modify as long as it is accessible with SMR.
7001 vn_seqc_init(struct vnode *vp)
7005 vp->v_seqc_users = 0;
7009 vn_seqc_write_end_free(struct vnode *vp)
7012 VNPASS(seqc_in_modify(vp->v_seqc), vp);
7013 VNPASS(vp->v_seqc_users == 1, vp);
7017 vn_irflag_set_locked(struct vnode *vp, short toset)
7021 ASSERT_VI_LOCKED(vp, __func__);
7022 flags = vn_irflag_read(vp);
7023 VNASSERT((flags & toset) == 0, vp,
7024 ("%s: some of the passed flags already set (have %d, passed %d)\n",
7025 __func__, flags, toset));
7026 atomic_store_short(&vp->v_irflag, flags | toset);
7030 vn_irflag_set(struct vnode *vp, short toset)
7034 vn_irflag_set_locked(vp, toset);
7039 vn_irflag_set_cond_locked(struct vnode *vp, short toset)
7043 ASSERT_VI_LOCKED(vp, __func__);
7044 flags = vn_irflag_read(vp);
7045 atomic_store_short(&vp->v_irflag, flags | toset);
7049 vn_irflag_set_cond(struct vnode *vp, short toset)
7053 vn_irflag_set_cond_locked(vp, toset);
7058 vn_irflag_unset_locked(struct vnode *vp, short tounset)
7062 ASSERT_VI_LOCKED(vp, __func__);
7063 flags = vn_irflag_read(vp);
7064 VNASSERT((flags & tounset) == tounset, vp,
7065 ("%s: some of the passed flags not set (have %d, passed %d)\n",
7066 __func__, flags, tounset));
7067 atomic_store_short(&vp->v_irflag, flags & ~tounset);
7071 vn_irflag_unset(struct vnode *vp, short tounset)
7075 vn_irflag_unset_locked(vp, tounset);