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>
53 #include <sys/capsicum.h>
54 #include <sys/condvar.h>
56 #include <sys/counter.h>
57 #include <sys/dirent.h>
58 #include <sys/event.h>
59 #include <sys/eventhandler.h>
60 #include <sys/extattr.h>
62 #include <sys/fcntl.h>
65 #include <sys/kernel.h>
66 #include <sys/kthread.h>
68 #include <sys/lockf.h>
69 #include <sys/malloc.h>
70 #include <sys/mount.h>
71 #include <sys/namei.h>
72 #include <sys/pctrie.h>
74 #include <sys/reboot.h>
75 #include <sys/refcount.h>
76 #include <sys/rwlock.h>
77 #include <sys/sched.h>
78 #include <sys/sleepqueue.h>
81 #include <sys/sysctl.h>
82 #include <sys/syslog.h>
83 #include <sys/vmmeter.h>
84 #include <sys/vnode.h>
85 #include <sys/watchdog.h>
87 #include <machine/stdarg.h>
89 #include <security/mac/mac_framework.h>
92 #include <vm/vm_object.h>
93 #include <vm/vm_extern.h>
95 #include <vm/vm_map.h>
96 #include <vm/vm_page.h>
97 #include <vm/vm_kern.h>
104 static void delmntque(struct vnode *vp);
105 static int flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
106 int slpflag, int slptimeo);
107 static void syncer_shutdown(void *arg, int howto);
108 static int vtryrecycle(struct vnode *vp);
109 static void v_init_counters(struct vnode *);
110 static void v_incr_devcount(struct vnode *);
111 static void v_decr_devcount(struct vnode *);
112 static void vgonel(struct vnode *);
113 static void vfs_knllock(void *arg);
114 static void vfs_knlunlock(void *arg);
115 static void vfs_knl_assert_locked(void *arg);
116 static void vfs_knl_assert_unlocked(void *arg);
117 static void destroy_vpollinfo(struct vpollinfo *vi);
118 static int v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
119 daddr_t startlbn, daddr_t endlbn);
120 static void vnlru_recalc(void);
123 * These fences are intended for cases where some synchronization is
124 * needed between access of v_iflags and lockless vnode refcount (v_holdcnt
125 * and v_usecount) updates. Access to v_iflags is generally synchronized
126 * by the interlock, but we have some internal assertions that check vnode
127 * flags without acquiring the lock. Thus, these fences are INVARIANTS-only
131 #define VNODE_REFCOUNT_FENCE_ACQ() atomic_thread_fence_acq()
132 #define VNODE_REFCOUNT_FENCE_REL() atomic_thread_fence_rel()
134 #define VNODE_REFCOUNT_FENCE_ACQ()
135 #define VNODE_REFCOUNT_FENCE_REL()
139 * Number of vnodes in existence. Increased whenever getnewvnode()
140 * allocates a new vnode, decreased in vdropl() for VIRF_DOOMED vnode.
142 static u_long __exclusive_cache_line numvnodes;
144 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
145 "Number of vnodes in existence");
147 static counter_u64_t vnodes_created;
148 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
149 "Number of vnodes created by getnewvnode");
152 * Conversion tables for conversion from vnode types to inode formats
155 enum vtype iftovt_tab[16] = {
156 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
157 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
159 int vttoif_tab[10] = {
160 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
161 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
165 * List of allocates vnodes in the system.
167 static TAILQ_HEAD(freelst, vnode) vnode_list;
168 static struct vnode *vnode_list_free_marker;
169 static struct vnode *vnode_list_reclaim_marker;
172 * "Free" vnode target. Free vnodes are rarely completely free, but are
173 * just ones that are cheap to recycle. Usually they are for files which
174 * have been stat'd but not read; these usually have inode and namecache
175 * data attached to them. This target is the preferred minimum size of a
176 * sub-cache consisting mostly of such files. The system balances the size
177 * of this sub-cache with its complement to try to prevent either from
178 * thrashing while the other is relatively inactive. The targets express
179 * a preference for the best balance.
181 * "Above" this target there are 2 further targets (watermarks) related
182 * to recyling of free vnodes. In the best-operating case, the cache is
183 * exactly full, the free list has size between vlowat and vhiwat above the
184 * free target, and recycling from it and normal use maintains this state.
185 * Sometimes the free list is below vlowat or even empty, but this state
186 * is even better for immediate use provided the cache is not full.
187 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
188 * ones) to reach one of these states. The watermarks are currently hard-
189 * coded as 4% and 9% of the available space higher. These and the default
190 * of 25% for wantfreevnodes are too large if the memory size is large.
191 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
192 * whenever vnlru_proc() becomes active.
194 static long wantfreevnodes;
195 static long __exclusive_cache_line freevnodes;
196 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
197 &freevnodes, 0, "Number of \"free\" vnodes");
198 static long freevnodes_old;
200 static counter_u64_t recycles_count;
201 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
202 "Number of vnodes recycled to meet vnode cache targets");
204 static counter_u64_t recycles_free_count;
205 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD, &recycles_free_count,
206 "Number of free vnodes recycled to meet vnode cache targets");
209 * Various variables used for debugging the new implementation of
211 * XXX these are probably of (very) limited utility now.
213 static int reassignbufcalls;
214 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW | CTLFLAG_STATS,
215 &reassignbufcalls, 0, "Number of calls to reassignbuf");
217 static counter_u64_t deferred_inact;
218 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, deferred_inact, CTLFLAG_RD, &deferred_inact,
219 "Number of times inactive processing was deferred");
221 /* To keep more than one thread at a time from running vfs_getnewfsid */
222 static struct mtx mntid_mtx;
225 * Lock for any access to the following:
230 static struct mtx __exclusive_cache_line vnode_list_mtx;
232 /* Publicly exported FS */
233 struct nfs_public nfs_pub;
235 static uma_zone_t buf_trie_zone;
237 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
238 static uma_zone_t vnode_zone;
239 static uma_zone_t vnodepoll_zone;
242 * The workitem queue.
244 * It is useful to delay writes of file data and filesystem metadata
245 * for tens of seconds so that quickly created and deleted files need
246 * not waste disk bandwidth being created and removed. To realize this,
247 * we append vnodes to a "workitem" queue. When running with a soft
248 * updates implementation, most pending metadata dependencies should
249 * not wait for more than a few seconds. Thus, mounted on block devices
250 * are delayed only about a half the time that file data is delayed.
251 * Similarly, directory updates are more critical, so are only delayed
252 * about a third the time that file data is delayed. Thus, there are
253 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
254 * one each second (driven off the filesystem syncer process). The
255 * syncer_delayno variable indicates the next queue that is to be processed.
256 * Items that need to be processed soon are placed in this queue:
258 * syncer_workitem_pending[syncer_delayno]
260 * A delay of fifteen seconds is done by placing the request fifteen
261 * entries later in the queue:
263 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
266 static int syncer_delayno;
267 static long syncer_mask;
268 LIST_HEAD(synclist, bufobj);
269 static struct synclist *syncer_workitem_pending;
271 * The sync_mtx protects:
276 * syncer_workitem_pending
277 * syncer_worklist_len
280 static struct mtx sync_mtx;
281 static struct cv sync_wakeup;
283 #define SYNCER_MAXDELAY 32
284 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
285 static int syncdelay = 30; /* max time to delay syncing data */
286 static int filedelay = 30; /* time to delay syncing files */
287 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
288 "Time to delay syncing files (in seconds)");
289 static int dirdelay = 29; /* time to delay syncing directories */
290 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
291 "Time to delay syncing directories (in seconds)");
292 static int metadelay = 28; /* time to delay syncing metadata */
293 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
294 "Time to delay syncing metadata (in seconds)");
295 static int rushjob; /* number of slots to run ASAP */
296 static int stat_rush_requests; /* number of times I/O speeded up */
297 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
298 "Number of times I/O speeded up (rush requests)");
300 #define VDBATCH_SIZE 8
305 struct vnode *tab[VDBATCH_SIZE];
307 DPCPU_DEFINE_STATIC(struct vdbatch, vd);
309 static void vdbatch_dequeue(struct vnode *vp);
312 * When shutting down the syncer, run it at four times normal speed.
314 #define SYNCER_SHUTDOWN_SPEEDUP 4
315 static int sync_vnode_count;
316 static int syncer_worklist_len;
317 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
320 /* Target for maximum number of vnodes. */
321 u_long desiredvnodes;
322 static u_long gapvnodes; /* gap between wanted and desired */
323 static u_long vhiwat; /* enough extras after expansion */
324 static u_long vlowat; /* minimal extras before expansion */
325 static u_long vstir; /* nonzero to stir non-free vnodes */
326 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
328 static u_long vnlru_read_freevnodes(void);
331 * Note that no attempt is made to sanitize these parameters.
334 sysctl_maxvnodes(SYSCTL_HANDLER_ARGS)
340 error = sysctl_handle_long(oidp, &val, 0, req);
341 if (error != 0 || req->newptr == NULL)
344 if (val == desiredvnodes)
346 mtx_lock(&vnode_list_mtx);
348 wantfreevnodes = desiredvnodes / 4;
350 mtx_unlock(&vnode_list_mtx);
352 * XXX There is no protection against multiple threads changing
353 * desiredvnodes at the same time. Locking above only helps vnlru and
356 vfs_hash_changesize(desiredvnodes);
357 cache_changesize(desiredvnodes);
361 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
362 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
363 "UL", "Target for maximum number of vnodes");
366 sysctl_wantfreevnodes(SYSCTL_HANDLER_ARGS)
371 val = wantfreevnodes;
372 error = sysctl_handle_long(oidp, &val, 0, req);
373 if (error != 0 || req->newptr == NULL)
376 if (val == wantfreevnodes)
378 mtx_lock(&vnode_list_mtx);
379 wantfreevnodes = val;
381 mtx_unlock(&vnode_list_mtx);
385 SYSCTL_PROC(_vfs, OID_AUTO, wantfreevnodes,
386 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
387 "UL", "Target for minimum number of \"free\" vnodes");
389 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
390 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
391 static int vnlru_nowhere;
392 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
393 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
396 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
401 unsigned long ndflags;
404 if (req->newptr == NULL)
406 if (req->newlen >= PATH_MAX)
409 buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
410 error = SYSCTL_IN(req, buf, req->newlen);
414 buf[req->newlen] = '\0';
416 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | NOCACHE | SAVENAME;
417 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
418 if ((error = namei(&nd)) != 0)
422 if (VN_IS_DOOMED(vp)) {
424 * This vnode is being recycled. Return != 0 to let the caller
425 * know that the sysctl had no effect. Return EAGAIN because a
426 * subsequent call will likely succeed (since namei will create
427 * a new vnode if necessary)
433 counter_u64_add(recycles_count, 1);
443 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
445 struct thread *td = curthread;
451 if (req->newptr == NULL)
454 error = sysctl_handle_int(oidp, &fd, 0, req);
457 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
462 error = vn_lock(vp, LK_EXCLUSIVE);
466 counter_u64_add(recycles_count, 1);
474 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
475 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
476 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
477 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
478 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
479 sysctl_ftry_reclaim_vnode, "I",
480 "Try to reclaim a vnode by its file descriptor");
482 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
486 * Support for the bufobj clean & dirty pctrie.
489 buf_trie_alloc(struct pctrie *ptree)
492 return uma_zalloc(buf_trie_zone, M_NOWAIT);
496 buf_trie_free(struct pctrie *ptree, void *node)
499 uma_zfree(buf_trie_zone, node);
501 PCTRIE_DEFINE(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free);
504 * Initialize the vnode management data structures.
506 * Reevaluate the following cap on the number of vnodes after the physical
507 * memory size exceeds 512GB. In the limit, as the physical memory size
508 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
510 #ifndef MAXVNODES_MAX
511 #define MAXVNODES_MAX (512UL * 1024 * 1024 / 64) /* 8M */
514 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
516 static struct vnode *
517 vn_alloc_marker(struct mount *mp)
521 vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
522 vp->v_type = VMARKER;
529 vn_free_marker(struct vnode *vp)
532 MPASS(vp->v_type == VMARKER);
533 free(vp, M_VNODE_MARKER);
537 * Initialize a vnode as it first enters the zone.
540 vnode_init(void *mem, int size, int flags)
549 vp->v_vnlock = &vp->v_lock;
550 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
552 * By default, don't allow shared locks unless filesystems opt-in.
554 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
555 LK_NOSHARE | LK_IS_VNODE);
559 bufobj_init(&vp->v_bufobj, vp);
561 * Initialize namecache.
563 LIST_INIT(&vp->v_cache_src);
564 TAILQ_INIT(&vp->v_cache_dst);
566 * Initialize rangelocks.
568 rangelock_init(&vp->v_rl);
570 vp->v_dbatchcpu = NOCPU;
572 mtx_lock(&vnode_list_mtx);
573 TAILQ_INSERT_BEFORE(vnode_list_free_marker, vp, v_vnodelist);
574 mtx_unlock(&vnode_list_mtx);
579 * Free a vnode when it is cleared from the zone.
582 vnode_fini(void *mem, int size)
589 mtx_lock(&vnode_list_mtx);
590 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
591 mtx_unlock(&vnode_list_mtx);
592 rangelock_destroy(&vp->v_rl);
593 lockdestroy(vp->v_vnlock);
594 mtx_destroy(&vp->v_interlock);
596 rw_destroy(BO_LOCKPTR(bo));
600 * Provide the size of NFS nclnode and NFS fh for calculation of the
601 * vnode memory consumption. The size is specified directly to
602 * eliminate dependency on NFS-private header.
604 * Other filesystems may use bigger or smaller (like UFS and ZFS)
605 * private inode data, but the NFS-based estimation is ample enough.
606 * Still, we care about differences in the size between 64- and 32-bit
609 * Namecache structure size is heuristically
610 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
613 #define NFS_NCLNODE_SZ (528 + 64)
616 #define NFS_NCLNODE_SZ (360 + 32)
621 vntblinit(void *dummy __unused)
624 int cpu, physvnodes, virtvnodes;
628 * Desiredvnodes is a function of the physical memory size and the
629 * kernel's heap size. Generally speaking, it scales with the
630 * physical memory size. The ratio of desiredvnodes to the physical
631 * memory size is 1:16 until desiredvnodes exceeds 98,304.
633 * marginal ratio of desiredvnodes to the physical memory size is
634 * 1:64. However, desiredvnodes is limited by the kernel's heap
635 * size. The memory required by desiredvnodes vnodes and vm objects
636 * must not exceed 1/10th of the kernel's heap size.
638 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
639 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
640 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
641 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
642 desiredvnodes = min(physvnodes, virtvnodes);
643 if (desiredvnodes > MAXVNODES_MAX) {
645 printf("Reducing kern.maxvnodes %lu -> %lu\n",
646 desiredvnodes, MAXVNODES_MAX);
647 desiredvnodes = MAXVNODES_MAX;
649 wantfreevnodes = desiredvnodes / 4;
650 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
651 TAILQ_INIT(&vnode_list);
652 mtx_init(&vnode_list_mtx, "vnode_list", NULL, MTX_DEF);
654 * The lock is taken to appease WITNESS.
656 mtx_lock(&vnode_list_mtx);
658 mtx_unlock(&vnode_list_mtx);
659 vnode_list_free_marker = vn_alloc_marker(NULL);
660 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_free_marker, v_vnodelist);
661 vnode_list_reclaim_marker = vn_alloc_marker(NULL);
662 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_reclaim_marker, v_vnodelist);
663 vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
664 vnode_init, vnode_fini, UMA_ALIGN_PTR, 0);
665 vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
666 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
668 * Preallocate enough nodes to support one-per buf so that
669 * we can not fail an insert. reassignbuf() callers can not
670 * tolerate the insertion failure.
672 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
673 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
674 UMA_ZONE_NOFREE | UMA_ZONE_VM);
675 uma_prealloc(buf_trie_zone, nbuf);
677 vnodes_created = counter_u64_alloc(M_WAITOK);
678 recycles_count = counter_u64_alloc(M_WAITOK);
679 recycles_free_count = counter_u64_alloc(M_WAITOK);
680 deferred_inact = counter_u64_alloc(M_WAITOK);
683 * Initialize the filesystem syncer.
685 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
687 syncer_maxdelay = syncer_mask + 1;
688 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
689 cv_init(&sync_wakeup, "syncer");
690 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
695 vd = DPCPU_ID_PTR((cpu), vd);
696 bzero(vd, sizeof(*vd));
697 mtx_init(&vd->lock, "vdbatch", NULL, MTX_DEF);
700 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
704 * Mark a mount point as busy. Used to synchronize access and to delay
705 * unmounting. Eventually, mountlist_mtx is not released on failure.
707 * vfs_busy() is a custom lock, it can block the caller.
708 * vfs_busy() only sleeps if the unmount is active on the mount point.
709 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
710 * vnode belonging to mp.
712 * Lookup uses vfs_busy() to traverse mount points.
714 * / vnode lock A / vnode lock (/var) D
715 * /var vnode lock B /log vnode lock(/var/log) E
716 * vfs_busy lock C vfs_busy lock F
718 * Within each file system, the lock order is C->A->B and F->D->E.
720 * When traversing across mounts, the system follows that lock order:
726 * The lookup() process for namei("/var") illustrates the process:
727 * VOP_LOOKUP() obtains B while A is held
728 * vfs_busy() obtains a shared lock on F while A and B are held
729 * vput() releases lock on B
730 * vput() releases lock on A
731 * VFS_ROOT() obtains lock on D while shared lock on F is held
732 * vfs_unbusy() releases shared lock on F
733 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
734 * Attempt to lock A (instead of vp_crossmp) while D is held would
735 * violate the global order, causing deadlocks.
737 * dounmount() locks B while F is drained.
740 vfs_busy(struct mount *mp, int flags)
743 MPASS((flags & ~MBF_MASK) == 0);
744 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
746 if (vfs_op_thread_enter(mp)) {
747 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
748 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
749 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
750 vfs_mp_count_add_pcpu(mp, ref, 1);
751 vfs_mp_count_add_pcpu(mp, lockref, 1);
752 vfs_op_thread_exit(mp);
753 if (flags & MBF_MNTLSTLOCK)
754 mtx_unlock(&mountlist_mtx);
759 vfs_assert_mount_counters(mp);
762 * If mount point is currently being unmounted, sleep until the
763 * mount point fate is decided. If thread doing the unmounting fails,
764 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
765 * that this mount point has survived the unmount attempt and vfs_busy
766 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
767 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
768 * about to be really destroyed. vfs_busy needs to release its
769 * reference on the mount point in this case and return with ENOENT,
770 * telling the caller that mount mount it tried to busy is no longer
773 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
774 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
777 CTR1(KTR_VFS, "%s: failed busying before sleeping",
781 if (flags & MBF_MNTLSTLOCK)
782 mtx_unlock(&mountlist_mtx);
783 mp->mnt_kern_flag |= MNTK_MWAIT;
784 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
785 if (flags & MBF_MNTLSTLOCK)
786 mtx_lock(&mountlist_mtx);
789 if (flags & MBF_MNTLSTLOCK)
790 mtx_unlock(&mountlist_mtx);
797 * Free a busy filesystem.
800 vfs_unbusy(struct mount *mp)
804 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
806 if (vfs_op_thread_enter(mp)) {
807 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
808 vfs_mp_count_sub_pcpu(mp, lockref, 1);
809 vfs_mp_count_sub_pcpu(mp, ref, 1);
810 vfs_op_thread_exit(mp);
815 vfs_assert_mount_counters(mp);
817 c = --mp->mnt_lockref;
818 if (mp->mnt_vfs_ops == 0) {
819 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
824 vfs_dump_mount_counters(mp);
825 if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
826 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
827 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
828 mp->mnt_kern_flag &= ~MNTK_DRAINING;
829 wakeup(&mp->mnt_lockref);
835 * Lookup a mount point by filesystem identifier.
838 vfs_getvfs(fsid_t *fsid)
842 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
843 mtx_lock(&mountlist_mtx);
844 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
845 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
846 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
848 mtx_unlock(&mountlist_mtx);
852 mtx_unlock(&mountlist_mtx);
853 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
854 return ((struct mount *) 0);
858 * Lookup a mount point by filesystem identifier, busying it before
861 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
862 * cache for popular filesystem identifiers. The cache is lockess, using
863 * the fact that struct mount's are never freed. In worst case we may
864 * get pointer to unmounted or even different filesystem, so we have to
865 * check what we got, and go slow way if so.
868 vfs_busyfs(fsid_t *fsid)
870 #define FSID_CACHE_SIZE 256
871 typedef struct mount * volatile vmp_t;
872 static vmp_t cache[FSID_CACHE_SIZE];
877 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
878 hash = fsid->val[0] ^ fsid->val[1];
879 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
882 mp->mnt_stat.f_fsid.val[0] != fsid->val[0] ||
883 mp->mnt_stat.f_fsid.val[1] != fsid->val[1])
885 if (vfs_busy(mp, 0) != 0) {
889 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
890 mp->mnt_stat.f_fsid.val[1] == fsid->val[1])
896 mtx_lock(&mountlist_mtx);
897 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
898 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
899 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
900 error = vfs_busy(mp, MBF_MNTLSTLOCK);
903 mtx_unlock(&mountlist_mtx);
910 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
911 mtx_unlock(&mountlist_mtx);
912 return ((struct mount *) 0);
916 * Check if a user can access privileged mount options.
919 vfs_suser(struct mount *mp, struct thread *td)
923 if (jailed(td->td_ucred)) {
925 * If the jail of the calling thread lacks permission for
926 * this type of file system, deny immediately.
928 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
932 * If the file system was mounted outside the jail of the
933 * calling thread, deny immediately.
935 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
940 * If file system supports delegated administration, we don't check
941 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
942 * by the file system itself.
943 * If this is not the user that did original mount, we check for
944 * the PRIV_VFS_MOUNT_OWNER privilege.
946 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
947 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
948 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
955 * Get a new unique fsid. Try to make its val[0] unique, since this value
956 * will be used to create fake device numbers for stat(). Also try (but
957 * not so hard) make its val[0] unique mod 2^16, since some emulators only
958 * support 16-bit device numbers. We end up with unique val[0]'s for the
959 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
961 * Keep in mind that several mounts may be running in parallel. Starting
962 * the search one past where the previous search terminated is both a
963 * micro-optimization and a defense against returning the same fsid to
967 vfs_getnewfsid(struct mount *mp)
969 static uint16_t mntid_base;
974 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
975 mtx_lock(&mntid_mtx);
976 mtype = mp->mnt_vfc->vfc_typenum;
977 tfsid.val[1] = mtype;
978 mtype = (mtype & 0xFF) << 24;
980 tfsid.val[0] = makedev(255,
981 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
983 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
987 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
988 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
989 mtx_unlock(&mntid_mtx);
993 * Knob to control the precision of file timestamps:
995 * 0 = seconds only; nanoseconds zeroed.
996 * 1 = seconds and nanoseconds, accurate within 1/HZ.
997 * 2 = seconds and nanoseconds, truncated to microseconds.
998 * >=3 = seconds and nanoseconds, maximum precision.
1000 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
1002 static int timestamp_precision = TSP_USEC;
1003 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
1004 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
1005 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
1006 "3+: sec + ns (max. precision))");
1009 * Get a current timestamp.
1012 vfs_timestamp(struct timespec *tsp)
1016 switch (timestamp_precision) {
1018 tsp->tv_sec = time_second;
1026 TIMEVAL_TO_TIMESPEC(&tv, tsp);
1036 * Set vnode attributes to VNOVAL
1039 vattr_null(struct vattr *vap)
1042 vap->va_type = VNON;
1043 vap->va_size = VNOVAL;
1044 vap->va_bytes = VNOVAL;
1045 vap->va_mode = VNOVAL;
1046 vap->va_nlink = VNOVAL;
1047 vap->va_uid = VNOVAL;
1048 vap->va_gid = VNOVAL;
1049 vap->va_fsid = VNOVAL;
1050 vap->va_fileid = VNOVAL;
1051 vap->va_blocksize = VNOVAL;
1052 vap->va_rdev = VNOVAL;
1053 vap->va_atime.tv_sec = VNOVAL;
1054 vap->va_atime.tv_nsec = VNOVAL;
1055 vap->va_mtime.tv_sec = VNOVAL;
1056 vap->va_mtime.tv_nsec = VNOVAL;
1057 vap->va_ctime.tv_sec = VNOVAL;
1058 vap->va_ctime.tv_nsec = VNOVAL;
1059 vap->va_birthtime.tv_sec = VNOVAL;
1060 vap->va_birthtime.tv_nsec = VNOVAL;
1061 vap->va_flags = VNOVAL;
1062 vap->va_gen = VNOVAL;
1063 vap->va_vaflags = 0;
1067 * Try to reduce the total number of vnodes.
1069 * This routine (and its user) are buggy in at least the following ways:
1070 * - all parameters were picked years ago when RAM sizes were significantly
1072 * - it can pick vnodes based on pages used by the vm object, but filesystems
1073 * like ZFS don't use it making the pick broken
1074 * - since ZFS has its own aging policy it gets partially combated by this one
1075 * - a dedicated method should be provided for filesystems to let them decide
1076 * whether the vnode should be recycled
1078 * This routine is called when we have too many vnodes. It attempts
1079 * to free <count> vnodes and will potentially free vnodes that still
1080 * have VM backing store (VM backing store is typically the cause
1081 * of a vnode blowout so we want to do this). Therefore, this operation
1082 * is not considered cheap.
1084 * A number of conditions may prevent a vnode from being reclaimed.
1085 * the buffer cache may have references on the vnode, a directory
1086 * vnode may still have references due to the namei cache representing
1087 * underlying files, or the vnode may be in active use. It is not
1088 * desirable to reuse such vnodes. These conditions may cause the
1089 * number of vnodes to reach some minimum value regardless of what
1090 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
1092 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1093 * entries if this argument is strue
1094 * @param trigger Only reclaim vnodes with fewer than this many resident
1096 * @param target How many vnodes to reclaim.
1097 * @return The number of vnodes that were reclaimed.
1100 vlrureclaim(bool reclaim_nc_src, int trigger, u_long target)
1102 struct vnode *vp, *mvp;
1107 mtx_assert(&vnode_list_mtx, MA_OWNED);
1112 mvp = vnode_list_reclaim_marker;
1115 while (done < target) {
1116 vp = TAILQ_NEXT(vp, v_vnodelist);
1117 if (__predict_false(vp == NULL))
1120 if (__predict_false(vp->v_type == VMARKER))
1124 * If it's been deconstructed already, it's still
1125 * referenced, or it exceeds the trigger, skip it.
1126 * Also skip free vnodes. We are trying to make space
1127 * to expand the free list, not reduce it.
1129 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1130 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)))
1133 if (vp->v_type == VBAD || vp->v_type == VNON)
1136 if (!VI_TRYLOCK(vp))
1139 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1140 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1141 vp->v_type == VBAD || vp->v_type == VNON ||
1142 (vp->v_object != NULL &&
1143 vp->v_object->resident_page_count > trigger)) {
1149 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1150 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1151 mtx_unlock(&vnode_list_mtx);
1153 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1155 goto next_iter_unlocked;
1157 if (VOP_LOCK(vp, LK_EXCLUSIVE|LK_NOWAIT) != 0) {
1159 vn_finished_write(mp);
1160 goto next_iter_unlocked;
1164 if (vp->v_usecount > 0 ||
1165 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1166 (vp->v_object != NULL &&
1167 vp->v_object->resident_page_count > trigger)) {
1170 vn_finished_write(mp);
1171 goto next_iter_unlocked;
1173 counter_u64_add(recycles_count, 1);
1177 vn_finished_write(mp);
1181 kern_yield(PRI_USER);
1182 mtx_lock(&vnode_list_mtx);
1185 MPASS(vp->v_type != VMARKER);
1186 if (!should_yield())
1188 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1189 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1190 mtx_unlock(&vnode_list_mtx);
1191 kern_yield(PRI_USER);
1192 mtx_lock(&vnode_list_mtx);
1195 if (done == 0 && !retried) {
1196 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1197 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1204 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1205 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1207 "limit on vnode free requests per call to the vnlru_free routine");
1210 * Attempt to reduce the free list by the requested amount.
1213 vnlru_free_locked(int count, struct vfsops *mnt_op)
1215 struct vnode *vp, *mvp;
1219 mtx_assert(&vnode_list_mtx, MA_OWNED);
1220 if (count > max_vnlru_free)
1221 count = max_vnlru_free;
1223 mvp = vnode_list_free_marker;
1227 vp = TAILQ_NEXT(vp, v_vnodelist);
1228 if (__predict_false(vp == NULL)) {
1229 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1230 TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1233 if (__predict_false(vp->v_type == VMARKER))
1237 * Don't recycle if our vnode is from different type
1238 * of mount point. Note that mp is type-safe, the
1239 * check does not reach unmapped address even if
1240 * vnode is reclaimed.
1241 * Don't recycle if we can't get the interlock without
1244 if (vp->v_holdcnt > 0 || (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1245 mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
1248 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1249 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1250 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1256 mtx_unlock(&vnode_list_mtx);
1260 mtx_lock(&vnode_list_mtx);
1263 return (ocount - count);
1267 vnlru_free(int count, struct vfsops *mnt_op)
1270 mtx_lock(&vnode_list_mtx);
1271 vnlru_free_locked(count, mnt_op);
1272 mtx_unlock(&vnode_list_mtx);
1279 mtx_assert(&vnode_list_mtx, MA_OWNED);
1280 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1281 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1282 vlowat = vhiwat / 2;
1286 * Attempt to recycle vnodes in a context that is always safe to block.
1287 * Calling vlrurecycle() from the bowels of filesystem code has some
1288 * interesting deadlock problems.
1290 static struct proc *vnlruproc;
1291 static int vnlruproc_sig;
1294 * The main freevnodes counter is only updated when threads requeue their vnode
1295 * batches. CPUs are conditionally walked to compute a more accurate total.
1297 * Limit how much of a slop are we willing to tolerate. Note: the actual value
1298 * at any given moment can still exceed slop, but it should not be by significant
1299 * margin in practice.
1301 #define VNLRU_FREEVNODES_SLOP 128
1304 vnlru_read_freevnodes(void)
1310 mtx_assert(&vnode_list_mtx, MA_OWNED);
1311 if (freevnodes > freevnodes_old)
1312 slop = freevnodes - freevnodes_old;
1314 slop = freevnodes_old - freevnodes;
1315 if (slop < VNLRU_FREEVNODES_SLOP)
1316 return (freevnodes >= 0 ? freevnodes : 0);
1317 freevnodes_old = freevnodes;
1319 vd = DPCPU_ID_PTR((cpu), vd);
1320 freevnodes_old += vd->freevnodes;
1322 return (freevnodes_old >= 0 ? freevnodes_old : 0);
1326 vnlru_under(u_long rnumvnodes, u_long limit)
1328 u_long rfreevnodes, space;
1330 if (__predict_false(rnumvnodes > desiredvnodes))
1333 space = desiredvnodes - rnumvnodes;
1334 if (space < limit) {
1335 rfreevnodes = vnlru_read_freevnodes();
1336 if (rfreevnodes > wantfreevnodes)
1337 space += rfreevnodes - wantfreevnodes;
1339 return (space < limit);
1343 vnlru_under_unlocked(u_long rnumvnodes, u_long limit)
1345 long rfreevnodes, space;
1347 if (__predict_false(rnumvnodes > desiredvnodes))
1350 space = desiredvnodes - rnumvnodes;
1351 if (space < limit) {
1352 rfreevnodes = atomic_load_long(&freevnodes);
1353 if (rfreevnodes > wantfreevnodes)
1354 space += rfreevnodes - wantfreevnodes;
1356 return (space < limit);
1363 mtx_assert(&vnode_list_mtx, MA_OWNED);
1364 if (vnlruproc_sig == 0) {
1373 u_long rnumvnodes, rfreevnodes, target;
1374 unsigned long onumvnodes;
1375 int done, force, trigger, usevnodes;
1376 bool reclaim_nc_src, want_reread;
1378 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1379 SHUTDOWN_PRI_FIRST);
1382 want_reread = false;
1384 kproc_suspend_check(vnlruproc);
1385 mtx_lock(&vnode_list_mtx);
1386 rnumvnodes = atomic_load_long(&numvnodes);
1389 force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1390 want_reread = false;
1394 * If numvnodes is too large (due to desiredvnodes being
1395 * adjusted using its sysctl, or emergency growth), first
1396 * try to reduce it by discarding from the free list.
1398 if (rnumvnodes > desiredvnodes) {
1399 vnlru_free_locked(rnumvnodes - desiredvnodes, NULL);
1400 rnumvnodes = atomic_load_long(&numvnodes);
1403 * Sleep if the vnode cache is in a good state. This is
1404 * when it is not over-full and has space for about a 4%
1405 * or 9% expansion (by growing its size or inexcessively
1406 * reducing its free list). Otherwise, try to reclaim
1407 * space for a 10% expansion.
1409 if (vstir && force == 0) {
1413 if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1415 wakeup(&vnlruproc_sig);
1416 msleep(vnlruproc, &vnode_list_mtx,
1417 PVFS|PDROP, "vlruwt", hz);
1420 rfreevnodes = vnlru_read_freevnodes();
1422 onumvnodes = rnumvnodes;
1424 * Calculate parameters for recycling. These are the same
1425 * throughout the loop to give some semblance of fairness.
1426 * The trigger point is to avoid recycling vnodes with lots
1427 * of resident pages. We aren't trying to free memory; we
1428 * are trying to recycle or at least free vnodes.
1430 if (rnumvnodes <= desiredvnodes)
1431 usevnodes = rnumvnodes - rfreevnodes;
1433 usevnodes = rnumvnodes;
1437 * The trigger value is is chosen to give a conservatively
1438 * large value to ensure that it alone doesn't prevent
1439 * making progress. The value can easily be so large that
1440 * it is effectively infinite in some congested and
1441 * misconfigured cases, and this is necessary. Normally
1442 * it is about 8 to 100 (pages), which is quite large.
1444 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1446 trigger = vsmalltrigger;
1447 reclaim_nc_src = force >= 3;
1448 target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1449 target = target / 10 + 1;
1450 done = vlrureclaim(reclaim_nc_src, trigger, target);
1451 mtx_unlock(&vnode_list_mtx);
1452 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1453 uma_reclaim(UMA_RECLAIM_DRAIN);
1455 if (force == 0 || force == 1) {
1466 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1469 kern_yield(PRI_USER);
1474 static struct kproc_desc vnlru_kp = {
1479 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1483 * Routines having to do with the management of the vnode table.
1487 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1488 * before we actually vgone(). This function must be called with the vnode
1489 * held to prevent the vnode from being returned to the free list midway
1493 vtryrecycle(struct vnode *vp)
1497 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1498 VNASSERT(vp->v_holdcnt, vp,
1499 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1501 * This vnode may found and locked via some other list, if so we
1502 * can't recycle it yet.
1504 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1506 "%s: impossible to recycle, vp %p lock is already held",
1508 return (EWOULDBLOCK);
1511 * Don't recycle if its filesystem is being suspended.
1513 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1516 "%s: impossible to recycle, cannot start the write for %p",
1521 * If we got this far, we need to acquire the interlock and see if
1522 * anyone picked up this vnode from another list. If not, we will
1523 * mark it with DOOMED via vgonel() so that anyone who does find it
1524 * will skip over it.
1527 if (vp->v_usecount) {
1530 vn_finished_write(vnmp);
1532 "%s: impossible to recycle, %p is already referenced",
1536 if (!VN_IS_DOOMED(vp)) {
1537 counter_u64_add(recycles_free_count, 1);
1542 vn_finished_write(vnmp);
1547 * Allocate a new vnode.
1549 * The operation never returns an error. Returning an error was disabled
1550 * in r145385 (dated 2005) with the following comment:
1552 * XXX Not all VFS_VGET/ffs_vget callers check returns.
1554 * Given the age of this commit (almost 15 years at the time of writing this
1555 * comment) restoring the ability to fail requires a significant audit of
1558 * The routine can try to free a vnode or stall for up to 1 second waiting for
1559 * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1561 static u_long vn_alloc_cyclecount;
1563 static struct vnode * __noinline
1564 vn_alloc_hard(struct mount *mp)
1566 u_long rnumvnodes, rfreevnodes;
1568 mtx_lock(&vnode_list_mtx);
1569 rnumvnodes = atomic_load_long(&numvnodes);
1570 if (rnumvnodes + 1 < desiredvnodes) {
1571 vn_alloc_cyclecount = 0;
1574 rfreevnodes = vnlru_read_freevnodes();
1575 if (vn_alloc_cyclecount++ >= rfreevnodes) {
1576 vn_alloc_cyclecount = 0;
1580 * Grow the vnode cache if it will not be above its target max
1581 * after growing. Otherwise, if the free list is nonempty, try
1582 * to reclaim 1 item from it before growing the cache (possibly
1583 * above its target max if the reclamation failed or is delayed).
1584 * Otherwise, wait for some space. In all cases, schedule
1585 * vnlru_proc() if we are getting short of space. The watermarks
1586 * should be chosen so that we never wait or even reclaim from
1587 * the free list to below its target minimum.
1589 if (vnlru_free_locked(1, NULL) > 0)
1591 if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1593 * Wait for space for a new vnode.
1596 msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1597 if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1598 vnlru_read_freevnodes() > 1)
1599 vnlru_free_locked(1, NULL);
1602 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1603 if (vnlru_under(rnumvnodes, vlowat))
1605 mtx_unlock(&vnode_list_mtx);
1606 return (uma_zalloc(vnode_zone, M_WAITOK));
1609 static struct vnode *
1610 vn_alloc(struct mount *mp)
1614 if (__predict_false(vn_alloc_cyclecount != 0))
1615 return (vn_alloc_hard(mp));
1616 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1617 if (__predict_false(vnlru_under_unlocked(rnumvnodes, vlowat))) {
1618 atomic_subtract_long(&numvnodes, 1);
1619 return (vn_alloc_hard(mp));
1622 return (uma_zalloc(vnode_zone, M_WAITOK));
1626 vn_free(struct vnode *vp)
1629 atomic_subtract_long(&numvnodes, 1);
1630 uma_zfree(vnode_zone, vp);
1634 * Return the next vnode from the free list.
1637 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1642 struct lock_object *lo;
1644 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1646 KASSERT(vops->registered,
1647 ("%s: not registered vector op %p\n", __func__, vops));
1650 if (td->td_vp_reserved != NULL) {
1651 vp = td->td_vp_reserved;
1652 td->td_vp_reserved = NULL;
1656 counter_u64_add(vnodes_created, 1);
1658 * Locks are given the generic name "vnode" when created.
1659 * Follow the historic practice of using the filesystem
1660 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1662 * Locks live in a witness group keyed on their name. Thus,
1663 * when a lock is renamed, it must also move from the witness
1664 * group of its old name to the witness group of its new name.
1666 * The change only needs to be made when the vnode moves
1667 * from one filesystem type to another. We ensure that each
1668 * filesystem use a single static name pointer for its tag so
1669 * that we can compare pointers rather than doing a strcmp().
1671 lo = &vp->v_vnlock->lock_object;
1673 if (lo->lo_name != tag) {
1677 WITNESS_DESTROY(lo);
1678 WITNESS_INIT(lo, tag);
1682 * By default, don't allow shared locks unless filesystems opt-in.
1684 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1686 * Finalize various vnode identity bits.
1688 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1689 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1690 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1693 v_init_counters(vp);
1694 vp->v_bufobj.bo_ops = &buf_ops_bio;
1696 if (mp == NULL && vops != &dead_vnodeops)
1697 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1701 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1702 mac_vnode_associate_singlelabel(mp, vp);
1705 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1706 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1707 vp->v_vflag |= VV_NOKNOTE;
1711 * For the filesystems which do not use vfs_hash_insert(),
1712 * still initialize v_hash to have vfs_hash_index() useful.
1713 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1716 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1723 getnewvnode_reserve(void)
1728 MPASS(td->td_vp_reserved == NULL);
1729 td->td_vp_reserved = vn_alloc(NULL);
1733 getnewvnode_drop_reserve(void)
1738 if (td->td_vp_reserved != NULL) {
1739 vn_free(td->td_vp_reserved);
1740 td->td_vp_reserved = NULL;
1745 freevnode(struct vnode *vp)
1750 * The vnode has been marked for destruction, so free it.
1752 * The vnode will be returned to the zone where it will
1753 * normally remain until it is needed for another vnode. We
1754 * need to cleanup (or verify that the cleanup has already
1755 * been done) any residual data left from its current use
1756 * so as not to contaminate the freshly allocated vnode.
1758 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1760 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1761 VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
1762 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1763 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1764 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1765 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1766 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1767 ("clean blk trie not empty"));
1768 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1769 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1770 ("dirty blk trie not empty"));
1771 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1772 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1773 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1774 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1775 ("Dangling rangelock waiters"));
1778 mac_vnode_destroy(vp);
1780 if (vp->v_pollinfo != NULL) {
1781 destroy_vpollinfo(vp->v_pollinfo);
1782 vp->v_pollinfo = NULL;
1785 /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
1788 vp->v_mountedhere = NULL;
1791 vp->v_fifoinfo = NULL;
1792 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
1801 * Delete from old mount point vnode list, if on one.
1804 delmntque(struct vnode *vp)
1813 if (vp->v_mflag & VMP_LAZYLIST) {
1814 mtx_lock(&mp->mnt_listmtx);
1815 if (vp->v_mflag & VMP_LAZYLIST) {
1816 vp->v_mflag &= ~VMP_LAZYLIST;
1817 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
1818 mp->mnt_lazyvnodelistsize--;
1820 mtx_unlock(&mp->mnt_listmtx);
1824 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1825 ("bad mount point vnode list size"));
1826 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1827 mp->mnt_nvnodelistsize--;
1833 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1837 vp->v_op = &dead_vnodeops;
1843 * Insert into list of vnodes for the new mount point, if available.
1846 insmntque1(struct vnode *vp, struct mount *mp,
1847 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1850 KASSERT(vp->v_mount == NULL,
1851 ("insmntque: vnode already on per mount vnode list"));
1852 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1853 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1856 * We acquire the vnode interlock early to ensure that the
1857 * vnode cannot be recycled by another process releasing a
1858 * holdcnt on it before we get it on both the vnode list
1859 * and the active vnode list. The mount mutex protects only
1860 * manipulation of the vnode list and the vnode freelist
1861 * mutex protects only manipulation of the active vnode list.
1862 * Hence the need to hold the vnode interlock throughout.
1866 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1867 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1868 mp->mnt_nvnodelistsize == 0)) &&
1869 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1878 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1879 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1880 ("neg mount point vnode list size"));
1881 mp->mnt_nvnodelistsize++;
1888 insmntque(struct vnode *vp, struct mount *mp)
1891 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1895 * Flush out and invalidate all buffers associated with a bufobj
1896 * Called with the underlying object locked.
1899 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1904 if (flags & V_SAVE) {
1905 error = bufobj_wwait(bo, slpflag, slptimeo);
1910 if (bo->bo_dirty.bv_cnt > 0) {
1912 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1915 * XXX We could save a lock/unlock if this was only
1916 * enabled under INVARIANTS
1919 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1920 panic("vinvalbuf: dirty bufs");
1924 * If you alter this loop please notice that interlock is dropped and
1925 * reacquired in flushbuflist. Special care is needed to ensure that
1926 * no race conditions occur from this.
1929 error = flushbuflist(&bo->bo_clean,
1930 flags, bo, slpflag, slptimeo);
1931 if (error == 0 && !(flags & V_CLEANONLY))
1932 error = flushbuflist(&bo->bo_dirty,
1933 flags, bo, slpflag, slptimeo);
1934 if (error != 0 && error != EAGAIN) {
1938 } while (error != 0);
1941 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1942 * have write I/O in-progress but if there is a VM object then the
1943 * VM object can also have read-I/O in-progress.
1946 bufobj_wwait(bo, 0, 0);
1947 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
1949 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
1952 } while (bo->bo_numoutput > 0);
1956 * Destroy the copy in the VM cache, too.
1958 if (bo->bo_object != NULL &&
1959 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1960 VM_OBJECT_WLOCK(bo->bo_object);
1961 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1962 OBJPR_CLEANONLY : 0);
1963 VM_OBJECT_WUNLOCK(bo->bo_object);
1968 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1969 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1970 bo->bo_clean.bv_cnt > 0))
1971 panic("vinvalbuf: flush failed");
1972 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1973 bo->bo_dirty.bv_cnt > 0)
1974 panic("vinvalbuf: flush dirty failed");
1981 * Flush out and invalidate all buffers associated with a vnode.
1982 * Called with the underlying object locked.
1985 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1988 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1989 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1990 if (vp->v_object != NULL && vp->v_object->handle != vp)
1992 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1996 * Flush out buffers on the specified list.
2000 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
2003 struct buf *bp, *nbp;
2008 ASSERT_BO_WLOCKED(bo);
2011 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2013 * If we are flushing both V_NORMAL and V_ALT buffers then
2014 * do not skip any buffers. If we are flushing only V_NORMAL
2015 * buffers then skip buffers marked as BX_ALTDATA. If we are
2016 * flushing only V_ALT buffers then skip buffers not marked
2019 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2020 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2021 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2025 lblkno = nbp->b_lblkno;
2026 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2029 error = BUF_TIMELOCK(bp,
2030 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2031 "flushbuf", slpflag, slptimeo);
2034 return (error != ENOLCK ? error : EAGAIN);
2036 KASSERT(bp->b_bufobj == bo,
2037 ("bp %p wrong b_bufobj %p should be %p",
2038 bp, bp->b_bufobj, bo));
2040 * XXX Since there are no node locks for NFS, I
2041 * believe there is a slight chance that a delayed
2042 * write will occur while sleeping just above, so
2045 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2048 bp->b_flags |= B_ASYNC;
2051 return (EAGAIN); /* XXX: why not loop ? */
2054 bp->b_flags |= (B_INVAL | B_RELBUF);
2055 bp->b_flags &= ~B_ASYNC;
2060 nbp = gbincore(bo, lblkno);
2061 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2063 break; /* nbp invalid */
2069 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2075 ASSERT_BO_LOCKED(bo);
2077 for (lblkno = startn;;) {
2079 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2080 if (bp == NULL || bp->b_lblkno >= endn ||
2081 bp->b_lblkno < startn)
2083 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2084 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2087 if (error == ENOLCK)
2091 KASSERT(bp->b_bufobj == bo,
2092 ("bp %p wrong b_bufobj %p should be %p",
2093 bp, bp->b_bufobj, bo));
2094 lblkno = bp->b_lblkno + 1;
2095 if ((bp->b_flags & B_MANAGED) == 0)
2097 bp->b_flags |= B_RELBUF;
2099 * In the VMIO case, use the B_NOREUSE flag to hint that the
2100 * pages backing each buffer in the range are unlikely to be
2101 * reused. Dirty buffers will have the hint applied once
2102 * they've been written.
2104 if ((bp->b_flags & B_VMIO) != 0)
2105 bp->b_flags |= B_NOREUSE;
2113 * Truncate a file's buffer and pages to a specified length. This
2114 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2118 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2120 struct buf *bp, *nbp;
2124 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2125 vp, blksize, (uintmax_t)length);
2128 * Round up to the *next* lbn.
2130 startlbn = howmany(length, blksize);
2132 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2138 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2143 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2144 if (bp->b_lblkno > 0)
2147 * Since we hold the vnode lock this should only
2148 * fail if we're racing with the buf daemon.
2151 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2152 BO_LOCKPTR(bo)) == ENOLCK)
2153 goto restart_unlocked;
2155 VNASSERT((bp->b_flags & B_DELWRI), vp,
2156 ("buf(%p) on dirty queue without DELWRI", bp));
2165 bufobj_wwait(bo, 0, 0);
2167 vnode_pager_setsize(vp, length);
2173 * Invalidate the cached pages of a file's buffer within the range of block
2174 * numbers [startlbn, endlbn).
2177 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2183 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2185 start = blksize * startlbn;
2186 end = blksize * endlbn;
2190 MPASS(blksize == bo->bo_bsize);
2192 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2196 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2200 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2201 daddr_t startlbn, daddr_t endlbn)
2203 struct buf *bp, *nbp;
2206 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2207 ASSERT_BO_LOCKED(bo);
2211 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2212 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2215 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2216 BO_LOCKPTR(bo)) == ENOLCK) {
2222 bp->b_flags |= B_INVAL | B_RELBUF;
2223 bp->b_flags &= ~B_ASYNC;
2229 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2231 (nbp->b_flags & B_DELWRI) != 0))
2235 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2236 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2239 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2240 BO_LOCKPTR(bo)) == ENOLCK) {
2245 bp->b_flags |= B_INVAL | B_RELBUF;
2246 bp->b_flags &= ~B_ASYNC;
2252 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2253 (nbp->b_vp != vp) ||
2254 (nbp->b_flags & B_DELWRI) == 0))
2262 buf_vlist_remove(struct buf *bp)
2266 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2267 ASSERT_BO_WLOCKED(bp->b_bufobj);
2268 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
2269 (BX_VNDIRTY|BX_VNCLEAN),
2270 ("buf_vlist_remove: Buf %p is on two lists", bp));
2271 if (bp->b_xflags & BX_VNDIRTY)
2272 bv = &bp->b_bufobj->bo_dirty;
2274 bv = &bp->b_bufobj->bo_clean;
2275 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2276 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2278 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2282 * Add the buffer to the sorted clean or dirty block list.
2284 * NOTE: xflags is passed as a constant, optimizing this inline function!
2287 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2293 ASSERT_BO_WLOCKED(bo);
2294 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2295 ("dead bo %p", bo));
2296 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2297 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2298 bp->b_xflags |= xflags;
2299 if (xflags & BX_VNDIRTY)
2305 * Keep the list ordered. Optimize empty list insertion. Assume
2306 * we tend to grow at the tail so lookup_le should usually be cheaper
2309 if (bv->bv_cnt == 0 ||
2310 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2311 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2312 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2313 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2315 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2316 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2318 panic("buf_vlist_add: Preallocated nodes insufficient.");
2323 * Look up a buffer using the buffer tries.
2326 gbincore(struct bufobj *bo, daddr_t lblkno)
2330 ASSERT_BO_LOCKED(bo);
2331 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2334 return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
2338 * Associate a buffer with a vnode.
2341 bgetvp(struct vnode *vp, struct buf *bp)
2346 ASSERT_BO_WLOCKED(bo);
2347 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2349 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2350 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2351 ("bgetvp: bp already attached! %p", bp));
2357 * Insert onto list for new vnode.
2359 buf_vlist_add(bp, bo, BX_VNCLEAN);
2363 * Disassociate a buffer from a vnode.
2366 brelvp(struct buf *bp)
2371 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2372 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2375 * Delete from old vnode list, if on one.
2377 vp = bp->b_vp; /* XXX */
2380 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2381 buf_vlist_remove(bp);
2383 panic("brelvp: Buffer %p not on queue.", bp);
2384 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2385 bo->bo_flag &= ~BO_ONWORKLST;
2386 mtx_lock(&sync_mtx);
2387 LIST_REMOVE(bo, bo_synclist);
2388 syncer_worklist_len--;
2389 mtx_unlock(&sync_mtx);
2392 bp->b_bufobj = NULL;
2398 * Add an item to the syncer work queue.
2401 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2405 ASSERT_BO_WLOCKED(bo);
2407 mtx_lock(&sync_mtx);
2408 if (bo->bo_flag & BO_ONWORKLST)
2409 LIST_REMOVE(bo, bo_synclist);
2411 bo->bo_flag |= BO_ONWORKLST;
2412 syncer_worklist_len++;
2415 if (delay > syncer_maxdelay - 2)
2416 delay = syncer_maxdelay - 2;
2417 slot = (syncer_delayno + delay) & syncer_mask;
2419 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2420 mtx_unlock(&sync_mtx);
2424 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2428 mtx_lock(&sync_mtx);
2429 len = syncer_worklist_len - sync_vnode_count;
2430 mtx_unlock(&sync_mtx);
2431 error = SYSCTL_OUT(req, &len, sizeof(len));
2435 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2436 CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2437 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2439 static struct proc *updateproc;
2440 static void sched_sync(void);
2441 static struct kproc_desc up_kp = {
2446 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2449 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2454 *bo = LIST_FIRST(slp);
2458 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2461 * We use vhold in case the vnode does not
2462 * successfully sync. vhold prevents the vnode from
2463 * going away when we unlock the sync_mtx so that
2464 * we can acquire the vnode interlock.
2467 mtx_unlock(&sync_mtx);
2469 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2471 mtx_lock(&sync_mtx);
2472 return (*bo == LIST_FIRST(slp));
2474 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2475 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2477 vn_finished_write(mp);
2479 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2481 * Put us back on the worklist. The worklist
2482 * routine will remove us from our current
2483 * position and then add us back in at a later
2486 vn_syncer_add_to_worklist(*bo, syncdelay);
2490 mtx_lock(&sync_mtx);
2494 static int first_printf = 1;
2497 * System filesystem synchronizer daemon.
2502 struct synclist *next, *slp;
2505 struct thread *td = curthread;
2507 int net_worklist_len;
2508 int syncer_final_iter;
2512 syncer_final_iter = 0;
2513 syncer_state = SYNCER_RUNNING;
2514 starttime = time_uptime;
2515 td->td_pflags |= TDP_NORUNNINGBUF;
2517 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2520 mtx_lock(&sync_mtx);
2522 if (syncer_state == SYNCER_FINAL_DELAY &&
2523 syncer_final_iter == 0) {
2524 mtx_unlock(&sync_mtx);
2525 kproc_suspend_check(td->td_proc);
2526 mtx_lock(&sync_mtx);
2528 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2529 if (syncer_state != SYNCER_RUNNING &&
2530 starttime != time_uptime) {
2532 printf("\nSyncing disks, vnodes remaining... ");
2535 printf("%d ", net_worklist_len);
2537 starttime = time_uptime;
2540 * Push files whose dirty time has expired. Be careful
2541 * of interrupt race on slp queue.
2543 * Skip over empty worklist slots when shutting down.
2546 slp = &syncer_workitem_pending[syncer_delayno];
2547 syncer_delayno += 1;
2548 if (syncer_delayno == syncer_maxdelay)
2550 next = &syncer_workitem_pending[syncer_delayno];
2552 * If the worklist has wrapped since the
2553 * it was emptied of all but syncer vnodes,
2554 * switch to the FINAL_DELAY state and run
2555 * for one more second.
2557 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2558 net_worklist_len == 0 &&
2559 last_work_seen == syncer_delayno) {
2560 syncer_state = SYNCER_FINAL_DELAY;
2561 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2563 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2564 syncer_worklist_len > 0);
2567 * Keep track of the last time there was anything
2568 * on the worklist other than syncer vnodes.
2569 * Return to the SHUTTING_DOWN state if any
2572 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2573 last_work_seen = syncer_delayno;
2574 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2575 syncer_state = SYNCER_SHUTTING_DOWN;
2576 while (!LIST_EMPTY(slp)) {
2577 error = sync_vnode(slp, &bo, td);
2579 LIST_REMOVE(bo, bo_synclist);
2580 LIST_INSERT_HEAD(next, bo, bo_synclist);
2584 if (first_printf == 0) {
2586 * Drop the sync mutex, because some watchdog
2587 * drivers need to sleep while patting
2589 mtx_unlock(&sync_mtx);
2590 wdog_kern_pat(WD_LASTVAL);
2591 mtx_lock(&sync_mtx);
2595 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2596 syncer_final_iter--;
2598 * The variable rushjob allows the kernel to speed up the
2599 * processing of the filesystem syncer process. A rushjob
2600 * value of N tells the filesystem syncer to process the next
2601 * N seconds worth of work on its queue ASAP. Currently rushjob
2602 * is used by the soft update code to speed up the filesystem
2603 * syncer process when the incore state is getting so far
2604 * ahead of the disk that the kernel memory pool is being
2605 * threatened with exhaustion.
2612 * Just sleep for a short period of time between
2613 * iterations when shutting down to allow some I/O
2616 * If it has taken us less than a second to process the
2617 * current work, then wait. Otherwise start right over
2618 * again. We can still lose time if any single round
2619 * takes more than two seconds, but it does not really
2620 * matter as we are just trying to generally pace the
2621 * filesystem activity.
2623 if (syncer_state != SYNCER_RUNNING ||
2624 time_uptime == starttime) {
2626 sched_prio(td, PPAUSE);
2629 if (syncer_state != SYNCER_RUNNING)
2630 cv_timedwait(&sync_wakeup, &sync_mtx,
2631 hz / SYNCER_SHUTDOWN_SPEEDUP);
2632 else if (time_uptime == starttime)
2633 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2638 * Request the syncer daemon to speed up its work.
2639 * We never push it to speed up more than half of its
2640 * normal turn time, otherwise it could take over the cpu.
2643 speedup_syncer(void)
2647 mtx_lock(&sync_mtx);
2648 if (rushjob < syncdelay / 2) {
2650 stat_rush_requests += 1;
2653 mtx_unlock(&sync_mtx);
2654 cv_broadcast(&sync_wakeup);
2659 * Tell the syncer to speed up its work and run though its work
2660 * list several times, then tell it to shut down.
2663 syncer_shutdown(void *arg, int howto)
2666 if (howto & RB_NOSYNC)
2668 mtx_lock(&sync_mtx);
2669 syncer_state = SYNCER_SHUTTING_DOWN;
2671 mtx_unlock(&sync_mtx);
2672 cv_broadcast(&sync_wakeup);
2673 kproc_shutdown(arg, howto);
2677 syncer_suspend(void)
2680 syncer_shutdown(updateproc, 0);
2687 mtx_lock(&sync_mtx);
2689 syncer_state = SYNCER_RUNNING;
2690 mtx_unlock(&sync_mtx);
2691 cv_broadcast(&sync_wakeup);
2692 kproc_resume(updateproc);
2696 * Reassign a buffer from one vnode to another.
2697 * Used to assign file specific control information
2698 * (indirect blocks) to the vnode to which they belong.
2701 reassignbuf(struct buf *bp)
2714 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2715 bp, bp->b_vp, bp->b_flags);
2717 * B_PAGING flagged buffers cannot be reassigned because their vp
2718 * is not fully linked in.
2720 if (bp->b_flags & B_PAGING)
2721 panic("cannot reassign paging buffer");
2724 * Delete from old vnode list, if on one.
2727 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2728 buf_vlist_remove(bp);
2730 panic("reassignbuf: Buffer %p not on queue.", bp);
2732 * If dirty, put on list of dirty buffers; otherwise insert onto list
2735 if (bp->b_flags & B_DELWRI) {
2736 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2737 switch (vp->v_type) {
2747 vn_syncer_add_to_worklist(bo, delay);
2749 buf_vlist_add(bp, bo, BX_VNDIRTY);
2751 buf_vlist_add(bp, bo, BX_VNCLEAN);
2753 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2754 mtx_lock(&sync_mtx);
2755 LIST_REMOVE(bo, bo_synclist);
2756 syncer_worklist_len--;
2757 mtx_unlock(&sync_mtx);
2758 bo->bo_flag &= ~BO_ONWORKLST;
2763 bp = TAILQ_FIRST(&bv->bv_hd);
2764 KASSERT(bp == NULL || bp->b_bufobj == bo,
2765 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2766 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2767 KASSERT(bp == NULL || bp->b_bufobj == bo,
2768 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2770 bp = TAILQ_FIRST(&bv->bv_hd);
2771 KASSERT(bp == NULL || bp->b_bufobj == bo,
2772 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2773 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2774 KASSERT(bp == NULL || bp->b_bufobj == bo,
2775 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2781 v_init_counters(struct vnode *vp)
2784 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2785 vp, ("%s called for an initialized vnode", __FUNCTION__));
2786 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2788 refcount_init(&vp->v_holdcnt, 1);
2789 refcount_init(&vp->v_usecount, 1);
2793 * Increment si_usecount of the associated device, if any.
2796 v_incr_devcount(struct vnode *vp)
2799 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2800 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2802 vp->v_rdev->si_usecount++;
2808 * Decrement si_usecount of the associated device, if any.
2811 v_decr_devcount(struct vnode *vp)
2814 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2815 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2817 vp->v_rdev->si_usecount--;
2823 * Grab a particular vnode from the free list, increment its
2824 * reference count and lock it. VIRF_DOOMED is set if the vnode
2825 * is being destroyed. Only callers who specify LK_RETRY will
2826 * see doomed vnodes. If inactive processing was delayed in
2827 * vput try to do it here.
2829 * usecount is manipulated using atomics without holding any locks,
2830 * except when transitioning 0->1 in which case the interlock is held.
2832 * holdcnt is manipulated using atomics without holding any locks,
2833 * except when transitioning 1->0 in which case the interlock is held.
2836 vget_prep(struct vnode *vp)
2840 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2850 vget(struct vnode *vp, int flags, struct thread *td)
2854 MPASS(td == curthread);
2857 return (vget_finish(vp, flags, vs));
2861 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
2863 int error, oweinact;
2865 VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2866 ("%s: invalid lock operation", __func__));
2868 if ((flags & LK_INTERLOCK) != 0)
2869 ASSERT_VI_LOCKED(vp, __func__);
2871 ASSERT_VI_UNLOCKED(vp, __func__);
2872 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
2873 if (vs == VGET_USECOUNT) {
2874 VNASSERT(vp->v_usecount > 0, vp,
2875 ("%s: vnode without usecount when VGET_USECOUNT was passed",
2879 if ((error = vn_lock(vp, flags)) != 0) {
2880 if (vs == VGET_USECOUNT)
2884 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2889 if (vs == VGET_USECOUNT) {
2890 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2891 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2896 * We hold the vnode. If the usecount is 0 it will be utilized to keep
2897 * the vnode around. Otherwise someone else lended their hold count and
2898 * we have to drop ours.
2900 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2902 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2903 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2905 refcount_release(&vp->v_holdcnt);
2907 VNODE_REFCOUNT_FENCE_ACQ();
2908 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2909 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2914 * We don't guarantee that any particular close will
2915 * trigger inactive processing so just make a best effort
2916 * here at preventing a reference to a removed file. If
2917 * we don't succeed no harm is done.
2919 * Upgrade our holdcnt to a usecount.
2923 * See the previous section. By the time we get here we may find
2924 * ourselves in the same spot.
2926 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2928 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2929 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2931 refcount_release(&vp->v_holdcnt);
2933 VNODE_REFCOUNT_FENCE_ACQ();
2934 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2935 ("%s: vnode with usecount and VI_OWEINACT set",
2940 if ((vp->v_iflag & VI_OWEINACT) == 0) {
2944 vp->v_iflag &= ~VI_OWEINACT;
2945 VNODE_REFCOUNT_FENCE_REL();
2947 v_incr_devcount(vp);
2948 refcount_acquire(&vp->v_usecount);
2949 if (oweinact && VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2950 (flags & LK_NOWAIT) == 0)
2957 * Increase the reference (use) and hold count of a vnode.
2958 * This will also remove the vnode from the free list if it is presently free.
2961 vref(struct vnode *vp)
2964 ASSERT_VI_UNLOCKED(vp, __func__);
2965 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2966 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2967 VNODE_REFCOUNT_FENCE_ACQ();
2968 VNASSERT(vp->v_holdcnt > 0, vp,
2969 ("%s: active vnode not held", __func__));
2970 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2971 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2980 vrefl(struct vnode *vp)
2983 ASSERT_VI_LOCKED(vp, __func__);
2984 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2985 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2986 VNODE_REFCOUNT_FENCE_ACQ();
2987 VNASSERT(vp->v_holdcnt > 0, vp,
2988 ("%s: active vnode not held", __func__));
2989 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2990 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2994 if ((vp->v_iflag & VI_OWEINACT) != 0) {
2995 vp->v_iflag &= ~VI_OWEINACT;
2996 VNODE_REFCOUNT_FENCE_REL();
2998 v_incr_devcount(vp);
2999 refcount_acquire(&vp->v_usecount);
3003 vrefact(struct vnode *vp)
3006 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3008 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
3009 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3011 refcount_acquire(&vp->v_usecount);
3016 * Return reference count of a vnode.
3018 * The results of this call are only guaranteed when some mechanism is used to
3019 * stop other processes from gaining references to the vnode. This may be the
3020 * case if the caller holds the only reference. This is also useful when stale
3021 * data is acceptable as race conditions may be accounted for by some other
3025 vrefcnt(struct vnode *vp)
3028 return (vp->v_usecount);
3032 vlazy(struct vnode *vp)
3036 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
3038 if ((vp->v_mflag & VMP_LAZYLIST) != 0)
3041 mtx_lock(&mp->mnt_listmtx);
3042 if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
3043 vp->v_mflag |= VMP_LAZYLIST;
3044 TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3045 mp->mnt_lazyvnodelistsize++;
3047 mtx_unlock(&mp->mnt_listmtx);
3051 vdefer_inactive(struct vnode *vp)
3054 ASSERT_VI_LOCKED(vp, __func__);
3055 VNASSERT(vp->v_iflag & VI_OWEINACT, vp,
3056 ("%s: vnode without VI_OWEINACT", __func__));
3057 if (VN_IS_DOOMED(vp)) {
3061 if (vp->v_iflag & VI_DEFINACT) {
3062 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3067 vp->v_iflag |= VI_DEFINACT;
3069 counter_u64_add(deferred_inact, 1);
3073 vdefer_inactive_cond(struct vnode *vp)
3077 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
3078 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3082 vdefer_inactive(vp);
3085 enum vputx_op { VPUTX_VRELE, VPUTX_VPUT, VPUTX_VUNREF };
3088 * Decrement the use and hold counts for a vnode.
3090 * See an explanation near vget() as to why atomic operation is safe.
3092 * XXX Some filesystems pass in an exclusively locked vnode and strongly depend
3093 * on the lock being held all the way until VOP_INACTIVE. This in particular
3094 * happens with UFS which adds half-constructed vnodes to the hash, where they
3095 * can be found by other code.
3098 vputx(struct vnode *vp, enum vputx_op func)
3102 KASSERT(vp != NULL, ("vputx: null vp"));
3103 if (func == VPUTX_VUNREF)
3104 ASSERT_VOP_LOCKED(vp, "vunref");
3105 else if (func == VPUTX_VPUT)
3106 ASSERT_VOP_LOCKED(vp, "vput");
3107 ASSERT_VI_UNLOCKED(vp, __func__);
3108 VNASSERT(vp->v_holdcnt > 0 && vp->v_usecount > 0, vp,
3109 ("%s: wrong ref counts", __func__));
3111 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3114 * We want to hold the vnode until the inactive finishes to
3115 * prevent vgone() races. We drop the use count here and the
3116 * hold count below when we're done.
3118 * If we release the last usecount we take ownership of the hold
3119 * count which provides liveness of the vnode, in which case we
3122 if (!refcount_release(&vp->v_usecount)) {
3123 if (func == VPUTX_VPUT)
3128 v_decr_devcount(vp);
3130 * By the time we got here someone else might have transitioned
3131 * the count back to > 0.
3133 if (vp->v_usecount > 0 || vp->v_iflag & VI_DOINGINACT)
3137 * Check if the fs wants to perform inactive processing. Note we
3138 * may be only holding the interlock, in which case it is possible
3139 * someone else called vgone on the vnode and ->v_data is now NULL.
3140 * Since vgone performs inactive on its own there is nothing to do
3141 * here but to drop our hold count.
3143 if (__predict_false(VN_IS_DOOMED(vp)) ||
3144 VOP_NEED_INACTIVE(vp) == 0)
3148 * We must call VOP_INACTIVE with the node locked. Mark
3149 * as VI_DOINGINACT to avoid recursion.
3151 vp->v_iflag |= VI_OWEINACT;
3154 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3159 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3160 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3167 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3168 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3173 VNASSERT(vp->v_usecount == 0 || (vp->v_iflag & VI_OWEINACT) == 0, vp,
3174 ("vnode with usecount and VI_OWEINACT set"));
3176 if (vp->v_iflag & VI_OWEINACT)
3178 if (func != VPUTX_VUNREF)
3181 } else if (vp->v_iflag & VI_OWEINACT) {
3182 vdefer_inactive(vp);
3188 if (func == VPUTX_VPUT)
3194 * Vnode put/release.
3195 * If count drops to zero, call inactive routine and return to freelist.
3198 vrele(struct vnode *vp)
3201 vputx(vp, VPUTX_VRELE);
3205 * Release an already locked vnode. This give the same effects as
3206 * unlock+vrele(), but takes less time and avoids releasing and
3207 * re-aquiring the lock (as vrele() acquires the lock internally.)
3210 vput(struct vnode *vp)
3213 vputx(vp, VPUTX_VPUT);
3217 * Release an exclusively locked vnode. Do not unlock the vnode lock.
3220 vunref(struct vnode *vp)
3223 vputx(vp, VPUTX_VUNREF);
3227 vhold(struct vnode *vp)
3232 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3233 old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3234 VNASSERT(old >= 0, vp, ("%s: wrong hold count %d", __func__, old));
3244 vholdl(struct vnode *vp)
3247 ASSERT_VI_LOCKED(vp, __func__);
3248 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3253 vholdnz(struct vnode *vp)
3256 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3258 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3259 VNASSERT(old > 0, vp, ("%s: wrong hold count %d", __func__, old));
3261 atomic_add_int(&vp->v_holdcnt, 1);
3265 static void __noinline
3266 vdbatch_process(struct vdbatch *vd)
3271 mtx_assert(&vd->lock, MA_OWNED);
3272 MPASS(curthread->td_pinned > 0);
3273 MPASS(vd->index == VDBATCH_SIZE);
3275 mtx_lock(&vnode_list_mtx);
3277 freevnodes += vd->freevnodes;
3278 for (i = 0; i < VDBATCH_SIZE; i++) {
3280 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3281 TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3282 MPASS(vp->v_dbatchcpu != NOCPU);
3283 vp->v_dbatchcpu = NOCPU;
3285 mtx_unlock(&vnode_list_mtx);
3288 bzero(vd->tab, sizeof(vd->tab));
3293 vdbatch_enqueue(struct vnode *vp)
3297 ASSERT_VI_LOCKED(vp, __func__);
3298 VNASSERT(!VN_IS_DOOMED(vp), vp,
3299 ("%s: deferring requeue of a doomed vnode", __func__));
3304 if (vp->v_dbatchcpu != NOCPU) {
3312 mtx_lock(&vd->lock);
3313 MPASS(vd->index < VDBATCH_SIZE);
3314 MPASS(vd->tab[vd->index] == NULL);
3316 * A hack: we depend on being pinned so that we know what to put in
3319 vp->v_dbatchcpu = curcpu;
3320 vd->tab[vd->index] = vp;
3323 if (vd->index == VDBATCH_SIZE)
3324 vdbatch_process(vd);
3325 mtx_unlock(&vd->lock);
3330 * This routine must only be called for vnodes which are about to be
3331 * deallocated. Supporting dequeue for arbitrary vndoes would require
3332 * validating that the locked batch matches.
3335 vdbatch_dequeue(struct vnode *vp)
3341 VNASSERT(vp->v_type == VBAD || vp->v_type == VNON, vp,
3342 ("%s: called for a used vnode\n", __func__));
3344 cpu = vp->v_dbatchcpu;
3348 vd = DPCPU_ID_PTR(cpu, vd);
3349 mtx_lock(&vd->lock);
3350 for (i = 0; i < vd->index; i++) {
3351 if (vd->tab[i] != vp)
3353 vp->v_dbatchcpu = NOCPU;
3355 vd->tab[i] = vd->tab[vd->index];
3356 vd->tab[vd->index] = NULL;
3359 mtx_unlock(&vd->lock);
3361 * Either we dequeued the vnode above or the target CPU beat us to it.
3363 MPASS(vp->v_dbatchcpu == NOCPU);
3367 * Drop the hold count of the vnode. If this is the last reference to
3368 * the vnode we place it on the free list unless it has been vgone'd
3369 * (marked VIRF_DOOMED) in which case we will free it.
3371 * Because the vnode vm object keeps a hold reference on the vnode if
3372 * there is at least one resident non-cached page, the vnode cannot
3373 * leave the active list without the page cleanup done.
3376 vdrop_deactivate(struct vnode *vp)
3380 ASSERT_VI_LOCKED(vp, __func__);
3382 * Mark a vnode as free: remove it from its active list
3383 * and put it up for recycling on the freelist.
3385 VNASSERT(!VN_IS_DOOMED(vp), vp,
3386 ("vdrop: returning doomed vnode"));
3387 VNASSERT(vp->v_op != NULL, vp,
3388 ("vdrop: vnode already reclaimed."));
3389 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
3390 ("vnode with VI_OWEINACT set"));
3391 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp,
3392 ("vnode with VI_DEFINACT set"));
3393 if (vp->v_mflag & VMP_LAZYLIST) {
3395 mtx_lock(&mp->mnt_listmtx);
3396 VNASSERT(vp->v_mflag & VMP_LAZYLIST, vp, ("lost VMP_LAZYLIST"));
3398 * Don't remove the vnode from the lazy list if another thread
3399 * has increased the hold count. It may have re-enqueued the
3400 * vnode to the lazy list and is now responsible for its
3403 if (vp->v_holdcnt == 0) {
3404 vp->v_mflag &= ~VMP_LAZYLIST;
3405 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3406 mp->mnt_lazyvnodelistsize--;
3408 mtx_unlock(&mp->mnt_listmtx);
3410 vdbatch_enqueue(vp);
3414 vdrop(struct vnode *vp)
3417 ASSERT_VI_UNLOCKED(vp, __func__);
3418 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3419 if (refcount_release_if_not_last(&vp->v_holdcnt))
3426 vdropl(struct vnode *vp)
3429 ASSERT_VI_LOCKED(vp, __func__);
3430 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3431 if (!refcount_release(&vp->v_holdcnt)) {
3435 if (VN_IS_DOOMED(vp)) {
3439 vdrop_deactivate(vp);
3443 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3444 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3445 * OWEINACT tracks whether a vnode missed a call to inactive due to a
3446 * failed lock upgrade.
3449 vinactive(struct vnode *vp)
3451 struct vm_object *obj;
3453 ASSERT_VOP_ELOCKED(vp, "vinactive");
3454 ASSERT_VI_LOCKED(vp, "vinactive");
3455 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3456 ("vinactive: recursed on VI_DOINGINACT"));
3457 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3458 vp->v_iflag |= VI_DOINGINACT;
3459 vp->v_iflag &= ~VI_OWEINACT;
3462 * Before moving off the active list, we must be sure that any
3463 * modified pages are converted into the vnode's dirty
3464 * buffers, since these will no longer be checked once the
3465 * vnode is on the inactive list.
3467 * The write-out of the dirty pages is asynchronous. At the
3468 * point that VOP_INACTIVE() is called, there could still be
3469 * pending I/O and dirty pages in the object.
3471 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3472 vm_object_mightbedirty(obj)) {
3473 VM_OBJECT_WLOCK(obj);
3474 vm_object_page_clean(obj, 0, 0, 0);
3475 VM_OBJECT_WUNLOCK(obj);
3477 VOP_INACTIVE(vp, curthread);
3479 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3480 ("vinactive: lost VI_DOINGINACT"));
3481 vp->v_iflag &= ~VI_DOINGINACT;
3485 * Remove any vnodes in the vnode table belonging to mount point mp.
3487 * If FORCECLOSE is not specified, there should not be any active ones,
3488 * return error if any are found (nb: this is a user error, not a
3489 * system error). If FORCECLOSE is specified, detach any active vnodes
3492 * If WRITECLOSE is set, only flush out regular file vnodes open for
3495 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3497 * `rootrefs' specifies the base reference count for the root vnode
3498 * of this filesystem. The root vnode is considered busy if its
3499 * v_usecount exceeds this value. On a successful return, vflush(, td)
3500 * will call vrele() on the root vnode exactly rootrefs times.
3501 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3505 static int busyprt = 0; /* print out busy vnodes */
3506 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3510 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3512 struct vnode *vp, *mvp, *rootvp = NULL;
3514 int busy = 0, error;
3516 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3519 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3520 ("vflush: bad args"));
3522 * Get the filesystem root vnode. We can vput() it
3523 * immediately, since with rootrefs > 0, it won't go away.
3525 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3526 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3533 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3535 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3538 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3542 * Skip over a vnodes marked VV_SYSTEM.
3544 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3550 * If WRITECLOSE is set, flush out unlinked but still open
3551 * files (even if open only for reading) and regular file
3552 * vnodes open for writing.
3554 if (flags & WRITECLOSE) {
3555 if (vp->v_object != NULL) {
3556 VM_OBJECT_WLOCK(vp->v_object);
3557 vm_object_page_clean(vp->v_object, 0, 0, 0);
3558 VM_OBJECT_WUNLOCK(vp->v_object);
3560 error = VOP_FSYNC(vp, MNT_WAIT, td);
3564 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3567 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3570 if ((vp->v_type == VNON ||
3571 (error == 0 && vattr.va_nlink > 0)) &&
3572 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3580 * With v_usecount == 0, all we need to do is clear out the
3581 * vnode data structures and we are done.
3583 * If FORCECLOSE is set, forcibly close the vnode.
3585 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3591 vn_printf(vp, "vflush: busy vnode ");
3597 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3599 * If just the root vnode is busy, and if its refcount
3600 * is equal to `rootrefs', then go ahead and kill it.
3603 KASSERT(busy > 0, ("vflush: not busy"));
3604 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3605 ("vflush: usecount %d < rootrefs %d",
3606 rootvp->v_usecount, rootrefs));
3607 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3608 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3616 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3620 for (; rootrefs > 0; rootrefs--)
3626 * Recycle an unused vnode to the front of the free list.
3629 vrecycle(struct vnode *vp)
3634 recycled = vrecyclel(vp);
3640 * vrecycle, with the vp interlock held.
3643 vrecyclel(struct vnode *vp)
3647 ASSERT_VOP_ELOCKED(vp, __func__);
3648 ASSERT_VI_LOCKED(vp, __func__);
3649 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3651 if (vp->v_usecount == 0) {
3659 * Eliminate all activity associated with a vnode
3660 * in preparation for reuse.
3663 vgone(struct vnode *vp)
3671 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3672 struct vnode *lowervp __unused)
3677 * Notify upper mounts about reclaimed or unlinked vnode.
3680 vfs_notify_upper(struct vnode *vp, int event)
3682 static struct vfsops vgonel_vfsops = {
3683 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3684 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3686 struct mount *mp, *ump, *mmp;
3691 if (TAILQ_EMPTY(&mp->mnt_uppers))
3694 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3695 mmp->mnt_op = &vgonel_vfsops;
3696 mmp->mnt_kern_flag |= MNTK_MARKER;
3698 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3699 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3700 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3701 ump = TAILQ_NEXT(ump, mnt_upper_link);
3704 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3707 case VFS_NOTIFY_UPPER_RECLAIM:
3708 VFS_RECLAIM_LOWERVP(ump, vp);
3710 case VFS_NOTIFY_UPPER_UNLINK:
3711 VFS_UNLINK_LOWERVP(ump, vp);
3714 KASSERT(0, ("invalid event %d", event));
3718 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3719 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3722 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3723 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3724 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3725 wakeup(&mp->mnt_uppers);
3731 * vgone, with the vp interlock held.
3734 vgonel(struct vnode *vp)
3739 bool active, oweinact;
3741 ASSERT_VOP_ELOCKED(vp, "vgonel");
3742 ASSERT_VI_LOCKED(vp, "vgonel");
3743 VNASSERT(vp->v_holdcnt, vp,
3744 ("vgonel: vp %p has no reference.", vp));
3745 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3749 * Don't vgonel if we're already doomed.
3751 if (vp->v_irflag & VIRF_DOOMED)
3753 vp->v_irflag |= VIRF_DOOMED;
3756 * Check to see if the vnode is in use. If so, we have to call
3757 * VOP_CLOSE() and VOP_INACTIVE().
3759 active = vp->v_usecount > 0;
3760 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
3762 * If we need to do inactive VI_OWEINACT will be set.
3764 if (vp->v_iflag & VI_DEFINACT) {
3765 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3766 vp->v_iflag &= ~VI_DEFINACT;
3769 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
3772 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
3775 * If purging an active vnode, it must be closed and
3776 * deactivated before being reclaimed.
3779 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
3780 if (oweinact || active) {
3782 if ((vp->v_iflag & VI_DOINGINACT) == 0)
3786 if (vp->v_type == VSOCK)
3787 vfs_unp_reclaim(vp);
3790 * Clean out any buffers associated with the vnode.
3791 * If the flush fails, just toss the buffers.
3794 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
3795 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
3796 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
3797 while (vinvalbuf(vp, 0, 0, 0) != 0)
3801 BO_LOCK(&vp->v_bufobj);
3802 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
3803 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
3804 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
3805 vp->v_bufobj.bo_clean.bv_cnt == 0,
3806 ("vp %p bufobj not invalidated", vp));
3809 * For VMIO bufobj, BO_DEAD is set later, or in
3810 * vm_object_terminate() after the object's page queue is
3813 object = vp->v_bufobj.bo_object;
3815 vp->v_bufobj.bo_flag |= BO_DEAD;
3816 BO_UNLOCK(&vp->v_bufobj);
3819 * Handle the VM part. Tmpfs handles v_object on its own (the
3820 * OBJT_VNODE check). Nullfs or other bypassing filesystems
3821 * should not touch the object borrowed from the lower vnode
3822 * (the handle check).
3824 if (object != NULL && object->type == OBJT_VNODE &&
3825 object->handle == vp)
3826 vnode_destroy_vobject(vp);
3829 * Reclaim the vnode.
3831 if (VOP_RECLAIM(vp, td))
3832 panic("vgone: cannot reclaim");
3834 vn_finished_secondary_write(mp);
3835 VNASSERT(vp->v_object == NULL, vp,
3836 ("vop_reclaim left v_object vp=%p", vp));
3838 * Clear the advisory locks and wake up waiting threads.
3840 (void)VOP_ADVLOCKPURGE(vp);
3843 * Delete from old mount point vnode list.
3848 * Done with purge, reset to the standard lock and invalidate
3852 vp->v_vnlock = &vp->v_lock;
3853 vp->v_op = &dead_vnodeops;
3858 * Calculate the total number of references to a special device.
3861 vcount(struct vnode *vp)
3866 count = vp->v_rdev->si_usecount;
3872 * Print out a description of a vnode.
3874 static char *typename[] =
3875 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
3879 vn_printf(struct vnode *vp, const char *fmt, ...)
3882 char buf[256], buf2[16];
3888 printf("%p: ", (void *)vp);
3889 printf("type %s\n", typename[vp->v_type]);
3890 printf(" usecount %d, writecount %d, refcount %d",
3891 vp->v_usecount, vp->v_writecount, vp->v_holdcnt);
3892 switch (vp->v_type) {
3894 printf(" mountedhere %p\n", vp->v_mountedhere);
3897 printf(" rdev %p\n", vp->v_rdev);
3900 printf(" socket %p\n", vp->v_unpcb);
3903 printf(" fifoinfo %p\n", vp->v_fifoinfo);
3911 if (vp->v_irflag & VIRF_DOOMED)
3912 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
3913 flags = vp->v_irflag & ~(VIRF_DOOMED);
3915 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
3916 strlcat(buf, buf2, sizeof(buf));
3918 if (vp->v_vflag & VV_ROOT)
3919 strlcat(buf, "|VV_ROOT", sizeof(buf));
3920 if (vp->v_vflag & VV_ISTTY)
3921 strlcat(buf, "|VV_ISTTY", sizeof(buf));
3922 if (vp->v_vflag & VV_NOSYNC)
3923 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
3924 if (vp->v_vflag & VV_ETERNALDEV)
3925 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
3926 if (vp->v_vflag & VV_CACHEDLABEL)
3927 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
3928 if (vp->v_vflag & VV_VMSIZEVNLOCK)
3929 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
3930 if (vp->v_vflag & VV_COPYONWRITE)
3931 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
3932 if (vp->v_vflag & VV_SYSTEM)
3933 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
3934 if (vp->v_vflag & VV_PROCDEP)
3935 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
3936 if (vp->v_vflag & VV_NOKNOTE)
3937 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
3938 if (vp->v_vflag & VV_DELETED)
3939 strlcat(buf, "|VV_DELETED", sizeof(buf));
3940 if (vp->v_vflag & VV_MD)
3941 strlcat(buf, "|VV_MD", sizeof(buf));
3942 if (vp->v_vflag & VV_FORCEINSMQ)
3943 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
3944 if (vp->v_vflag & VV_READLINK)
3945 strlcat(buf, "|VV_READLINK", sizeof(buf));
3946 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
3947 VV_CACHEDLABEL | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
3948 VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
3950 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
3951 strlcat(buf, buf2, sizeof(buf));
3953 if (vp->v_iflag & VI_TEXT_REF)
3954 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
3955 if (vp->v_iflag & VI_MOUNT)
3956 strlcat(buf, "|VI_MOUNT", sizeof(buf));
3957 if (vp->v_iflag & VI_DOINGINACT)
3958 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
3959 if (vp->v_iflag & VI_OWEINACT)
3960 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
3961 if (vp->v_iflag & VI_DEFINACT)
3962 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
3963 flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOINGINACT |
3964 VI_OWEINACT | VI_DEFINACT);
3966 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
3967 strlcat(buf, buf2, sizeof(buf));
3969 if (vp->v_mflag & VMP_LAZYLIST)
3970 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
3971 flags = vp->v_mflag & ~(VMP_LAZYLIST);
3973 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
3974 strlcat(buf, buf2, sizeof(buf));
3976 printf(" flags (%s)\n", buf + 1);
3977 if (mtx_owned(VI_MTX(vp)))
3978 printf(" VI_LOCKed");
3979 if (vp->v_object != NULL)
3980 printf(" v_object %p ref %d pages %d "
3981 "cleanbuf %d dirtybuf %d\n",
3982 vp->v_object, vp->v_object->ref_count,
3983 vp->v_object->resident_page_count,
3984 vp->v_bufobj.bo_clean.bv_cnt,
3985 vp->v_bufobj.bo_dirty.bv_cnt);
3987 lockmgr_printinfo(vp->v_vnlock);
3988 if (vp->v_data != NULL)
3994 * List all of the locked vnodes in the system.
3995 * Called when debugging the kernel.
3997 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
4003 * Note: because this is DDB, we can't obey the locking semantics
4004 * for these structures, which means we could catch an inconsistent
4005 * state and dereference a nasty pointer. Not much to be done
4008 db_printf("Locked vnodes\n");
4009 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4010 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4011 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4012 vn_printf(vp, "vnode ");
4018 * Show details about the given vnode.
4020 DB_SHOW_COMMAND(vnode, db_show_vnode)
4026 vp = (struct vnode *)addr;
4027 vn_printf(vp, "vnode ");
4031 * Show details about the given mount point.
4033 DB_SHOW_COMMAND(mount, db_show_mount)
4044 /* No address given, print short info about all mount points. */
4045 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4046 db_printf("%p %s on %s (%s)\n", mp,
4047 mp->mnt_stat.f_mntfromname,
4048 mp->mnt_stat.f_mntonname,
4049 mp->mnt_stat.f_fstypename);
4053 db_printf("\nMore info: show mount <addr>\n");
4057 mp = (struct mount *)addr;
4058 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4059 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4062 mflags = mp->mnt_flag;
4063 #define MNT_FLAG(flag) do { \
4064 if (mflags & (flag)) { \
4065 if (buf[0] != '\0') \
4066 strlcat(buf, ", ", sizeof(buf)); \
4067 strlcat(buf, (#flag) + 4, sizeof(buf)); \
4068 mflags &= ~(flag); \
4071 MNT_FLAG(MNT_RDONLY);
4072 MNT_FLAG(MNT_SYNCHRONOUS);
4073 MNT_FLAG(MNT_NOEXEC);
4074 MNT_FLAG(MNT_NOSUID);
4075 MNT_FLAG(MNT_NFS4ACLS);
4076 MNT_FLAG(MNT_UNION);
4077 MNT_FLAG(MNT_ASYNC);
4078 MNT_FLAG(MNT_SUIDDIR);
4079 MNT_FLAG(MNT_SOFTDEP);
4080 MNT_FLAG(MNT_NOSYMFOLLOW);
4081 MNT_FLAG(MNT_GJOURNAL);
4082 MNT_FLAG(MNT_MULTILABEL);
4084 MNT_FLAG(MNT_NOATIME);
4085 MNT_FLAG(MNT_NOCLUSTERR);
4086 MNT_FLAG(MNT_NOCLUSTERW);
4088 MNT_FLAG(MNT_EXRDONLY);
4089 MNT_FLAG(MNT_EXPORTED);
4090 MNT_FLAG(MNT_DEFEXPORTED);
4091 MNT_FLAG(MNT_EXPORTANON);
4092 MNT_FLAG(MNT_EXKERB);
4093 MNT_FLAG(MNT_EXPUBLIC);
4094 MNT_FLAG(MNT_LOCAL);
4095 MNT_FLAG(MNT_QUOTA);
4096 MNT_FLAG(MNT_ROOTFS);
4098 MNT_FLAG(MNT_IGNORE);
4099 MNT_FLAG(MNT_UPDATE);
4100 MNT_FLAG(MNT_DELEXPORT);
4101 MNT_FLAG(MNT_RELOAD);
4102 MNT_FLAG(MNT_FORCE);
4103 MNT_FLAG(MNT_SNAPSHOT);
4104 MNT_FLAG(MNT_BYFSID);
4108 strlcat(buf, ", ", sizeof(buf));
4109 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4110 "0x%016jx", mflags);
4112 db_printf(" mnt_flag = %s\n", buf);
4115 flags = mp->mnt_kern_flag;
4116 #define MNT_KERN_FLAG(flag) do { \
4117 if (flags & (flag)) { \
4118 if (buf[0] != '\0') \
4119 strlcat(buf, ", ", sizeof(buf)); \
4120 strlcat(buf, (#flag) + 5, sizeof(buf)); \
4124 MNT_KERN_FLAG(MNTK_UNMOUNTF);
4125 MNT_KERN_FLAG(MNTK_ASYNC);
4126 MNT_KERN_FLAG(MNTK_SOFTDEP);
4127 MNT_KERN_FLAG(MNTK_DRAINING);
4128 MNT_KERN_FLAG(MNTK_REFEXPIRE);
4129 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4130 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4131 MNT_KERN_FLAG(MNTK_NO_IOPF);
4132 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4133 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4134 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4135 MNT_KERN_FLAG(MNTK_MARKER);
4136 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4137 MNT_KERN_FLAG(MNTK_NOASYNC);
4138 MNT_KERN_FLAG(MNTK_UNMOUNT);
4139 MNT_KERN_FLAG(MNTK_MWAIT);
4140 MNT_KERN_FLAG(MNTK_SUSPEND);
4141 MNT_KERN_FLAG(MNTK_SUSPEND2);
4142 MNT_KERN_FLAG(MNTK_SUSPENDED);
4143 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4144 MNT_KERN_FLAG(MNTK_NOKNOTE);
4145 #undef MNT_KERN_FLAG
4148 strlcat(buf, ", ", sizeof(buf));
4149 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4152 db_printf(" mnt_kern_flag = %s\n", buf);
4154 db_printf(" mnt_opt = ");
4155 opt = TAILQ_FIRST(mp->mnt_opt);
4157 db_printf("%s", opt->name);
4158 opt = TAILQ_NEXT(opt, link);
4159 while (opt != NULL) {
4160 db_printf(", %s", opt->name);
4161 opt = TAILQ_NEXT(opt, link);
4167 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4168 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4169 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4170 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4171 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4172 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4173 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4174 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4175 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4176 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4177 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4178 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4180 db_printf(" mnt_cred = { uid=%u ruid=%u",
4181 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4182 if (jailed(mp->mnt_cred))
4183 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4185 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4186 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4187 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4188 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4189 db_printf(" mnt_lazyvnodelistsize = %d\n",
4190 mp->mnt_lazyvnodelistsize);
4191 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4192 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4193 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
4194 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4195 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4196 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4197 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4198 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4199 db_printf(" mnt_secondary_accwrites = %d\n",
4200 mp->mnt_secondary_accwrites);
4201 db_printf(" mnt_gjprovider = %s\n",
4202 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4203 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4205 db_printf("\n\nList of active vnodes\n");
4206 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4207 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4208 vn_printf(vp, "vnode ");
4213 db_printf("\n\nList of inactive vnodes\n");
4214 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4215 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4216 vn_printf(vp, "vnode ");
4225 * Fill in a struct xvfsconf based on a struct vfsconf.
4228 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4230 struct xvfsconf xvfsp;
4232 bzero(&xvfsp, sizeof(xvfsp));
4233 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4234 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4235 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4236 xvfsp.vfc_flags = vfsp->vfc_flags;
4238 * These are unused in userland, we keep them
4239 * to not break binary compatibility.
4241 xvfsp.vfc_vfsops = NULL;
4242 xvfsp.vfc_next = NULL;
4243 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4246 #ifdef COMPAT_FREEBSD32
4248 uint32_t vfc_vfsops;
4249 char vfc_name[MFSNAMELEN];
4250 int32_t vfc_typenum;
4251 int32_t vfc_refcount;
4257 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4259 struct xvfsconf32 xvfsp;
4261 bzero(&xvfsp, sizeof(xvfsp));
4262 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4263 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4264 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4265 xvfsp.vfc_flags = vfsp->vfc_flags;
4266 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4271 * Top level filesystem related information gathering.
4274 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4276 struct vfsconf *vfsp;
4281 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4282 #ifdef COMPAT_FREEBSD32
4283 if (req->flags & SCTL_MASK32)
4284 error = vfsconf2x32(req, vfsp);
4287 error = vfsconf2x(req, vfsp);
4295 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4296 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4297 "S,xvfsconf", "List of all configured filesystems");
4299 #ifndef BURN_BRIDGES
4300 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4303 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4305 int *name = (int *)arg1 - 1; /* XXX */
4306 u_int namelen = arg2 + 1; /* XXX */
4307 struct vfsconf *vfsp;
4309 log(LOG_WARNING, "userland calling deprecated sysctl, "
4310 "please rebuild world\n");
4312 #if 1 || defined(COMPAT_PRELITE2)
4313 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4315 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4319 case VFS_MAXTYPENUM:
4322 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4325 return (ENOTDIR); /* overloaded */
4327 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4328 if (vfsp->vfc_typenum == name[2])
4333 return (EOPNOTSUPP);
4334 #ifdef COMPAT_FREEBSD32
4335 if (req->flags & SCTL_MASK32)
4336 return (vfsconf2x32(req, vfsp));
4339 return (vfsconf2x(req, vfsp));
4341 return (EOPNOTSUPP);
4344 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4345 CTLFLAG_MPSAFE, vfs_sysctl,
4346 "Generic filesystem");
4348 #if 1 || defined(COMPAT_PRELITE2)
4351 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4354 struct vfsconf *vfsp;
4355 struct ovfsconf ovfs;
4358 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4359 bzero(&ovfs, sizeof(ovfs));
4360 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4361 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4362 ovfs.vfc_index = vfsp->vfc_typenum;
4363 ovfs.vfc_refcount = vfsp->vfc_refcount;
4364 ovfs.vfc_flags = vfsp->vfc_flags;
4365 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4375 #endif /* 1 || COMPAT_PRELITE2 */
4376 #endif /* !BURN_BRIDGES */
4378 #define KINFO_VNODESLOP 10
4381 * Dump vnode list (via sysctl).
4385 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4393 * Stale numvnodes access is not fatal here.
4396 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4398 /* Make an estimate */
4399 return (SYSCTL_OUT(req, 0, len));
4401 error = sysctl_wire_old_buffer(req, 0);
4404 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4406 mtx_lock(&mountlist_mtx);
4407 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4408 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4411 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4415 xvn[n].xv_size = sizeof *xvn;
4416 xvn[n].xv_vnode = vp;
4417 xvn[n].xv_id = 0; /* XXX compat */
4418 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4420 XV_COPY(writecount);
4426 xvn[n].xv_flag = vp->v_vflag;
4428 switch (vp->v_type) {
4435 if (vp->v_rdev == NULL) {
4439 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4442 xvn[n].xv_socket = vp->v_socket;
4445 xvn[n].xv_fifo = vp->v_fifoinfo;
4450 /* shouldn't happen? */
4458 mtx_lock(&mountlist_mtx);
4463 mtx_unlock(&mountlist_mtx);
4465 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4470 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4471 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4476 unmount_or_warn(struct mount *mp)
4480 error = dounmount(mp, MNT_FORCE, curthread);
4482 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4486 printf("%d)\n", error);
4491 * Unmount all filesystems. The list is traversed in reverse order
4492 * of mounting to avoid dependencies.
4495 vfs_unmountall(void)
4497 struct mount *mp, *tmp;
4499 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4502 * Since this only runs when rebooting, it is not interlocked.
4504 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4508 * Forcibly unmounting "/dev" before "/" would prevent clean
4509 * unmount of the latter.
4511 if (mp == rootdevmp)
4514 unmount_or_warn(mp);
4517 if (rootdevmp != NULL)
4518 unmount_or_warn(rootdevmp);
4522 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4525 ASSERT_VI_LOCKED(vp, __func__);
4526 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4527 if ((vp->v_iflag & VI_OWEINACT) == 0) {
4531 if (vn_lock(vp, lkflags) == 0) {
4533 if ((vp->v_iflag & (VI_OWEINACT | VI_DOINGINACT)) == VI_OWEINACT)
4539 vdefer_inactive_cond(vp);
4543 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4546 return (vp->v_iflag & VI_DEFINACT);
4549 static void __noinline
4550 vfs_periodic_inactive(struct mount *mp, int flags)
4552 struct vnode *vp, *mvp;
4555 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4556 if (flags != MNT_WAIT)
4557 lkflags |= LK_NOWAIT;
4559 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4560 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4564 vp->v_iflag &= ~VI_DEFINACT;
4565 vfs_deferred_inactive(vp, lkflags);
4570 vfs_want_msync(struct vnode *vp)
4572 struct vm_object *obj;
4575 * This test may be performed without any locks held.
4576 * We rely on vm_object's type stability.
4578 if (vp->v_vflag & VV_NOSYNC)
4581 return (obj != NULL && vm_object_mightbedirty(obj));
4585 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4588 if (vp->v_vflag & VV_NOSYNC)
4590 if (vp->v_iflag & VI_DEFINACT)
4592 return (vfs_want_msync(vp));
4595 static void __noinline
4596 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4598 struct vnode *vp, *mvp;
4599 struct vm_object *obj;
4601 int lkflags, objflags;
4606 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4607 if (flags != MNT_WAIT) {
4608 lkflags |= LK_NOWAIT;
4609 objflags = OBJPC_NOSYNC;
4611 objflags = OBJPC_SYNC;
4614 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4616 if (vp->v_iflag & VI_DEFINACT) {
4617 vp->v_iflag &= ~VI_DEFINACT;
4620 if (!vfs_want_msync(vp)) {
4622 vfs_deferred_inactive(vp, lkflags);
4627 if (vget(vp, lkflags, td) == 0) {
4629 if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4630 VM_OBJECT_WLOCK(obj);
4631 vm_object_page_clean(obj, 0, 0, objflags);
4632 VM_OBJECT_WUNLOCK(obj);
4639 vdefer_inactive_cond(vp);
4645 vfs_periodic(struct mount *mp, int flags)
4648 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4650 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4651 vfs_periodic_inactive(mp, flags);
4653 vfs_periodic_msync_inactive(mp, flags);
4657 destroy_vpollinfo_free(struct vpollinfo *vi)
4660 knlist_destroy(&vi->vpi_selinfo.si_note);
4661 mtx_destroy(&vi->vpi_lock);
4662 uma_zfree(vnodepoll_zone, vi);
4666 destroy_vpollinfo(struct vpollinfo *vi)
4669 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4670 seldrain(&vi->vpi_selinfo);
4671 destroy_vpollinfo_free(vi);
4675 * Initialize per-vnode helper structure to hold poll-related state.
4678 v_addpollinfo(struct vnode *vp)
4680 struct vpollinfo *vi;
4682 if (vp->v_pollinfo != NULL)
4684 vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4685 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4686 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4687 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4689 if (vp->v_pollinfo != NULL) {
4691 destroy_vpollinfo_free(vi);
4694 vp->v_pollinfo = vi;
4699 * Record a process's interest in events which might happen to
4700 * a vnode. Because poll uses the historic select-style interface
4701 * internally, this routine serves as both the ``check for any
4702 * pending events'' and the ``record my interest in future events''
4703 * functions. (These are done together, while the lock is held,
4704 * to avoid race conditions.)
4707 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4711 mtx_lock(&vp->v_pollinfo->vpi_lock);
4712 if (vp->v_pollinfo->vpi_revents & events) {
4714 * This leaves events we are not interested
4715 * in available for the other process which
4716 * which presumably had requested them
4717 * (otherwise they would never have been
4720 events &= vp->v_pollinfo->vpi_revents;
4721 vp->v_pollinfo->vpi_revents &= ~events;
4723 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4726 vp->v_pollinfo->vpi_events |= events;
4727 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4728 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4733 * Routine to create and manage a filesystem syncer vnode.
4735 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4736 static int sync_fsync(struct vop_fsync_args *);
4737 static int sync_inactive(struct vop_inactive_args *);
4738 static int sync_reclaim(struct vop_reclaim_args *);
4740 static struct vop_vector sync_vnodeops = {
4741 .vop_bypass = VOP_EOPNOTSUPP,
4742 .vop_close = sync_close, /* close */
4743 .vop_fsync = sync_fsync, /* fsync */
4744 .vop_inactive = sync_inactive, /* inactive */
4745 .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
4746 .vop_reclaim = sync_reclaim, /* reclaim */
4747 .vop_lock1 = vop_stdlock, /* lock */
4748 .vop_unlock = vop_stdunlock, /* unlock */
4749 .vop_islocked = vop_stdislocked, /* islocked */
4751 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
4754 * Create a new filesystem syncer vnode for the specified mount point.
4757 vfs_allocate_syncvnode(struct mount *mp)
4761 static long start, incr, next;
4764 /* Allocate a new vnode */
4765 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
4767 panic("vfs_allocate_syncvnode: getnewvnode() failed");
4769 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4770 vp->v_vflag |= VV_FORCEINSMQ;
4771 error = insmntque(vp, mp);
4773 panic("vfs_allocate_syncvnode: insmntque() failed");
4774 vp->v_vflag &= ~VV_FORCEINSMQ;
4777 * Place the vnode onto the syncer worklist. We attempt to
4778 * scatter them about on the list so that they will go off
4779 * at evenly distributed times even if all the filesystems
4780 * are mounted at once.
4783 if (next == 0 || next > syncer_maxdelay) {
4787 start = syncer_maxdelay / 2;
4788 incr = syncer_maxdelay;
4794 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
4795 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
4796 mtx_lock(&sync_mtx);
4798 if (mp->mnt_syncer == NULL) {
4799 mp->mnt_syncer = vp;
4802 mtx_unlock(&sync_mtx);
4805 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4812 vfs_deallocate_syncvnode(struct mount *mp)
4816 mtx_lock(&sync_mtx);
4817 vp = mp->mnt_syncer;
4819 mp->mnt_syncer = NULL;
4820 mtx_unlock(&sync_mtx);
4826 * Do a lazy sync of the filesystem.
4829 sync_fsync(struct vop_fsync_args *ap)
4831 struct vnode *syncvp = ap->a_vp;
4832 struct mount *mp = syncvp->v_mount;
4837 * We only need to do something if this is a lazy evaluation.
4839 if (ap->a_waitfor != MNT_LAZY)
4843 * Move ourselves to the back of the sync list.
4845 bo = &syncvp->v_bufobj;
4847 vn_syncer_add_to_worklist(bo, syncdelay);
4851 * Walk the list of vnodes pushing all that are dirty and
4852 * not already on the sync list.
4854 if (vfs_busy(mp, MBF_NOWAIT) != 0)
4856 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
4860 save = curthread_pflags_set(TDP_SYNCIO);
4862 * The filesystem at hand may be idle with free vnodes stored in the
4863 * batch. Return them instead of letting them stay there indefinitely.
4865 vfs_periodic(mp, MNT_NOWAIT);
4866 error = VFS_SYNC(mp, MNT_LAZY);
4867 curthread_pflags_restore(save);
4868 vn_finished_write(mp);
4874 * The syncer vnode is no referenced.
4877 sync_inactive(struct vop_inactive_args *ap)
4885 * The syncer vnode is no longer needed and is being decommissioned.
4887 * Modifications to the worklist must be protected by sync_mtx.
4890 sync_reclaim(struct vop_reclaim_args *ap)
4892 struct vnode *vp = ap->a_vp;
4897 mtx_lock(&sync_mtx);
4898 if (vp->v_mount->mnt_syncer == vp)
4899 vp->v_mount->mnt_syncer = NULL;
4900 if (bo->bo_flag & BO_ONWORKLST) {
4901 LIST_REMOVE(bo, bo_synclist);
4902 syncer_worklist_len--;
4904 bo->bo_flag &= ~BO_ONWORKLST;
4906 mtx_unlock(&sync_mtx);
4913 vn_need_pageq_flush(struct vnode *vp)
4915 struct vm_object *obj;
4918 MPASS(mtx_owned(VI_MTX(vp)));
4920 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
4921 vm_object_mightbedirty(obj))
4927 * Check if vnode represents a disk device
4930 vn_isdisk(struct vnode *vp, int *errp)
4934 if (vp->v_type != VCHR) {
4940 if (vp->v_rdev == NULL)
4942 else if (vp->v_rdev->si_devsw == NULL)
4944 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
4950 return (error == 0);
4954 * Common filesystem object access control check routine. Accepts a
4955 * vnode's type, "mode", uid and gid, requested access mode, credentials,
4956 * and optional call-by-reference privused argument allowing vaccess()
4957 * to indicate to the caller whether privilege was used to satisfy the
4958 * request (obsoleted). Returns 0 on success, or an errno on failure.
4961 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
4962 accmode_t accmode, struct ucred *cred, int *privused)
4964 accmode_t dac_granted;
4965 accmode_t priv_granted;
4967 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
4968 ("invalid bit in accmode"));
4969 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
4970 ("VAPPEND without VWRITE"));
4973 * Look for a normal, non-privileged way to access the file/directory
4974 * as requested. If it exists, go with that.
4977 if (privused != NULL)
4982 /* Check the owner. */
4983 if (cred->cr_uid == file_uid) {
4984 dac_granted |= VADMIN;
4985 if (file_mode & S_IXUSR)
4986 dac_granted |= VEXEC;
4987 if (file_mode & S_IRUSR)
4988 dac_granted |= VREAD;
4989 if (file_mode & S_IWUSR)
4990 dac_granted |= (VWRITE | VAPPEND);
4992 if ((accmode & dac_granted) == accmode)
4998 /* Otherwise, check the groups (first match) */
4999 if (groupmember(file_gid, cred)) {
5000 if (file_mode & S_IXGRP)
5001 dac_granted |= VEXEC;
5002 if (file_mode & S_IRGRP)
5003 dac_granted |= VREAD;
5004 if (file_mode & S_IWGRP)
5005 dac_granted |= (VWRITE | VAPPEND);
5007 if ((accmode & dac_granted) == accmode)
5013 /* Otherwise, check everyone else. */
5014 if (file_mode & S_IXOTH)
5015 dac_granted |= VEXEC;
5016 if (file_mode & S_IROTH)
5017 dac_granted |= VREAD;
5018 if (file_mode & S_IWOTH)
5019 dac_granted |= (VWRITE | VAPPEND);
5020 if ((accmode & dac_granted) == accmode)
5025 * Build a privilege mask to determine if the set of privileges
5026 * satisfies the requirements when combined with the granted mask
5027 * from above. For each privilege, if the privilege is required,
5028 * bitwise or the request type onto the priv_granted mask.
5034 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5035 * requests, instead of PRIV_VFS_EXEC.
5037 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5038 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5039 priv_granted |= VEXEC;
5042 * Ensure that at least one execute bit is on. Otherwise,
5043 * a privileged user will always succeed, and we don't want
5044 * this to happen unless the file really is executable.
5046 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5047 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5048 !priv_check_cred(cred, PRIV_VFS_EXEC))
5049 priv_granted |= VEXEC;
5052 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5053 !priv_check_cred(cred, PRIV_VFS_READ))
5054 priv_granted |= VREAD;
5056 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5057 !priv_check_cred(cred, PRIV_VFS_WRITE))
5058 priv_granted |= (VWRITE | VAPPEND);
5060 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5061 !priv_check_cred(cred, PRIV_VFS_ADMIN))
5062 priv_granted |= VADMIN;
5064 if ((accmode & (priv_granted | dac_granted)) == accmode) {
5065 /* XXX audit: privilege used */
5066 if (privused != NULL)
5071 return ((accmode & VADMIN) ? EPERM : EACCES);
5075 * Credential check based on process requesting service, and per-attribute
5079 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5080 struct thread *td, accmode_t accmode)
5084 * Kernel-invoked always succeeds.
5090 * Do not allow privileged processes in jail to directly manipulate
5091 * system attributes.
5093 switch (attrnamespace) {
5094 case EXTATTR_NAMESPACE_SYSTEM:
5095 /* Potentially should be: return (EPERM); */
5096 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5097 case EXTATTR_NAMESPACE_USER:
5098 return (VOP_ACCESS(vp, accmode, cred, td));
5104 #ifdef DEBUG_VFS_LOCKS
5106 * This only exists to suppress warnings from unlocked specfs accesses. It is
5107 * no longer ok to have an unlocked VFS.
5109 #define IGNORE_LOCK(vp) (KERNEL_PANICKED() || (vp) == NULL || \
5110 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
5112 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
5113 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5114 "Drop into debugger on lock violation");
5116 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
5117 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5118 0, "Check for interlock across VOPs");
5120 int vfs_badlock_print = 1; /* Print lock violations. */
5121 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5122 0, "Print lock violations");
5124 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
5125 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5126 0, "Print vnode details on lock violations");
5129 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
5130 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5131 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5135 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5139 if (vfs_badlock_backtrace)
5142 if (vfs_badlock_vnode)
5143 vn_printf(vp, "vnode ");
5144 if (vfs_badlock_print)
5145 printf("%s: %p %s\n", str, (void *)vp, msg);
5146 if (vfs_badlock_ddb)
5147 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5151 assert_vi_locked(struct vnode *vp, const char *str)
5154 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5155 vfs_badlock("interlock is not locked but should be", str, vp);
5159 assert_vi_unlocked(struct vnode *vp, const char *str)
5162 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5163 vfs_badlock("interlock is locked but should not be", str, vp);
5167 assert_vop_locked(struct vnode *vp, const char *str)
5171 if (!IGNORE_LOCK(vp)) {
5172 locked = VOP_ISLOCKED(vp);
5173 if (locked == 0 || locked == LK_EXCLOTHER)
5174 vfs_badlock("is not locked but should be", str, vp);
5179 assert_vop_unlocked(struct vnode *vp, const char *str)
5182 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5183 vfs_badlock("is locked but should not be", str, vp);
5187 assert_vop_elocked(struct vnode *vp, const char *str)
5190 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5191 vfs_badlock("is not exclusive locked but should be", str, vp);
5193 #endif /* DEBUG_VFS_LOCKS */
5196 vop_rename_fail(struct vop_rename_args *ap)
5199 if (ap->a_tvp != NULL)
5201 if (ap->a_tdvp == ap->a_tvp)
5210 vop_rename_pre(void *ap)
5212 struct vop_rename_args *a = ap;
5214 #ifdef DEBUG_VFS_LOCKS
5216 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5217 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5218 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5219 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5221 /* Check the source (from). */
5222 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5223 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5224 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5225 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5226 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5228 /* Check the target. */
5230 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5231 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5233 if (a->a_tdvp != a->a_fdvp)
5235 if (a->a_tvp != a->a_fvp)
5242 #ifdef DEBUG_VFS_LOCKS
5244 vop_strategy_pre(void *ap)
5246 struct vop_strategy_args *a;
5253 * Cluster ops lock their component buffers but not the IO container.
5255 if ((bp->b_flags & B_CLUSTER) != 0)
5258 if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5259 if (vfs_badlock_print)
5261 "VOP_STRATEGY: bp is not locked but should be\n");
5262 if (vfs_badlock_ddb)
5263 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5268 vop_lock_pre(void *ap)
5270 struct vop_lock1_args *a = ap;
5272 if ((a->a_flags & LK_INTERLOCK) == 0)
5273 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5275 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5279 vop_lock_post(void *ap, int rc)
5281 struct vop_lock1_args *a = ap;
5283 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5284 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5285 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5289 vop_unlock_pre(void *ap)
5291 struct vop_unlock_args *a = ap;
5293 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5297 vop_unlock_post(void *ap, int rc)
5303 vop_need_inactive_pre(void *ap)
5305 struct vop_need_inactive_args *a = ap;
5307 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5311 vop_need_inactive_post(void *ap, int rc)
5313 struct vop_need_inactive_args *a = ap;
5315 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5320 vop_create_post(void *ap, int rc)
5322 struct vop_create_args *a = ap;
5325 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5329 vop_deleteextattr_post(void *ap, int rc)
5331 struct vop_deleteextattr_args *a = ap;
5334 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5338 vop_link_post(void *ap, int rc)
5340 struct vop_link_args *a = ap;
5343 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
5344 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
5349 vop_mkdir_post(void *ap, int rc)
5351 struct vop_mkdir_args *a = ap;
5354 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5358 vop_mknod_post(void *ap, int rc)
5360 struct vop_mknod_args *a = ap;
5363 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5367 vop_reclaim_post(void *ap, int rc)
5369 struct vop_reclaim_args *a = ap;
5372 VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
5376 vop_remove_post(void *ap, int rc)
5378 struct vop_remove_args *a = ap;
5381 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5382 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5387 vop_rename_post(void *ap, int rc)
5389 struct vop_rename_args *a = ap;
5394 if (a->a_fdvp == a->a_tdvp) {
5395 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5397 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5398 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5400 hint |= NOTE_EXTEND;
5401 if (a->a_fvp->v_type == VDIR)
5403 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5405 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5406 a->a_tvp->v_type == VDIR)
5408 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5411 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5413 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5415 if (a->a_tdvp != a->a_fdvp)
5417 if (a->a_tvp != a->a_fvp)
5425 vop_rmdir_post(void *ap, int rc)
5427 struct vop_rmdir_args *a = ap;
5430 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5431 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5436 vop_setattr_post(void *ap, int rc)
5438 struct vop_setattr_args *a = ap;
5441 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5445 vop_setextattr_post(void *ap, int rc)
5447 struct vop_setextattr_args *a = ap;
5450 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5454 vop_symlink_post(void *ap, int rc)
5456 struct vop_symlink_args *a = ap;
5459 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5463 vop_open_post(void *ap, int rc)
5465 struct vop_open_args *a = ap;
5468 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
5472 vop_close_post(void *ap, int rc)
5474 struct vop_close_args *a = ap;
5476 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
5477 !VN_IS_DOOMED(a->a_vp))) {
5478 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
5479 NOTE_CLOSE_WRITE : NOTE_CLOSE);
5484 vop_read_post(void *ap, int rc)
5486 struct vop_read_args *a = ap;
5489 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5493 vop_readdir_post(void *ap, int rc)
5495 struct vop_readdir_args *a = ap;
5498 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5501 static struct knlist fs_knlist;
5504 vfs_event_init(void *arg)
5506 knlist_init_mtx(&fs_knlist, NULL);
5508 /* XXX - correct order? */
5509 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
5512 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
5515 KNOTE_UNLOCKED(&fs_knlist, event);
5518 static int filt_fsattach(struct knote *kn);
5519 static void filt_fsdetach(struct knote *kn);
5520 static int filt_fsevent(struct knote *kn, long hint);
5522 struct filterops fs_filtops = {
5524 .f_attach = filt_fsattach,
5525 .f_detach = filt_fsdetach,
5526 .f_event = filt_fsevent
5530 filt_fsattach(struct knote *kn)
5533 kn->kn_flags |= EV_CLEAR;
5534 knlist_add(&fs_knlist, kn, 0);
5539 filt_fsdetach(struct knote *kn)
5542 knlist_remove(&fs_knlist, kn, 0);
5546 filt_fsevent(struct knote *kn, long hint)
5549 kn->kn_fflags |= hint;
5550 return (kn->kn_fflags != 0);
5554 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
5560 error = SYSCTL_IN(req, &vc, sizeof(vc));
5563 if (vc.vc_vers != VFS_CTL_VERS1)
5565 mp = vfs_getvfs(&vc.vc_fsid);
5568 /* ensure that a specific sysctl goes to the right filesystem. */
5569 if (strcmp(vc.vc_fstypename, "*") != 0 &&
5570 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
5574 VCTLTOREQ(&vc, req);
5575 error = VFS_SYSCTL(mp, vc.vc_op, req);
5580 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
5581 NULL, 0, sysctl_vfs_ctl, "",
5585 * Function to initialize a va_filerev field sensibly.
5586 * XXX: Wouldn't a random number make a lot more sense ??
5589 init_va_filerev(void)
5594 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
5597 static int filt_vfsread(struct knote *kn, long hint);
5598 static int filt_vfswrite(struct knote *kn, long hint);
5599 static int filt_vfsvnode(struct knote *kn, long hint);
5600 static void filt_vfsdetach(struct knote *kn);
5601 static struct filterops vfsread_filtops = {
5603 .f_detach = filt_vfsdetach,
5604 .f_event = filt_vfsread
5606 static struct filterops vfswrite_filtops = {
5608 .f_detach = filt_vfsdetach,
5609 .f_event = filt_vfswrite
5611 static struct filterops vfsvnode_filtops = {
5613 .f_detach = filt_vfsdetach,
5614 .f_event = filt_vfsvnode
5618 vfs_knllock(void *arg)
5620 struct vnode *vp = arg;
5622 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5626 vfs_knlunlock(void *arg)
5628 struct vnode *vp = arg;
5634 vfs_knl_assert_locked(void *arg)
5636 #ifdef DEBUG_VFS_LOCKS
5637 struct vnode *vp = arg;
5639 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
5644 vfs_knl_assert_unlocked(void *arg)
5646 #ifdef DEBUG_VFS_LOCKS
5647 struct vnode *vp = arg;
5649 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
5654 vfs_kqfilter(struct vop_kqfilter_args *ap)
5656 struct vnode *vp = ap->a_vp;
5657 struct knote *kn = ap->a_kn;
5660 switch (kn->kn_filter) {
5662 kn->kn_fop = &vfsread_filtops;
5665 kn->kn_fop = &vfswrite_filtops;
5668 kn->kn_fop = &vfsvnode_filtops;
5674 kn->kn_hook = (caddr_t)vp;
5677 if (vp->v_pollinfo == NULL)
5679 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5681 knlist_add(knl, kn, 0);
5687 * Detach knote from vnode
5690 filt_vfsdetach(struct knote *kn)
5692 struct vnode *vp = (struct vnode *)kn->kn_hook;
5694 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
5695 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
5701 filt_vfsread(struct knote *kn, long hint)
5703 struct vnode *vp = (struct vnode *)kn->kn_hook;
5708 * filesystem is gone, so set the EOF flag and schedule
5709 * the knote for deletion.
5711 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5713 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5718 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
5722 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
5723 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
5730 filt_vfswrite(struct knote *kn, long hint)
5732 struct vnode *vp = (struct vnode *)kn->kn_hook;
5737 * filesystem is gone, so set the EOF flag and schedule
5738 * the knote for deletion.
5740 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
5741 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5749 filt_vfsvnode(struct knote *kn, long hint)
5751 struct vnode *vp = (struct vnode *)kn->kn_hook;
5755 if (kn->kn_sfflags & hint)
5756 kn->kn_fflags |= hint;
5757 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5758 kn->kn_flags |= EV_EOF;
5762 res = (kn->kn_fflags != 0);
5768 * Returns whether the directory is empty or not.
5769 * If it is empty, the return value is 0; otherwise
5770 * the return value is an error value (which may
5774 vfs_emptydir(struct vnode *vp)
5778 struct dirent *dirent, *dp, *endp;
5784 ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
5786 dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
5787 iov.iov_base = dirent;
5788 iov.iov_len = sizeof(struct dirent);
5793 uio.uio_resid = sizeof(struct dirent);
5794 uio.uio_segflg = UIO_SYSSPACE;
5795 uio.uio_rw = UIO_READ;
5796 uio.uio_td = curthread;
5798 while (eof == 0 && error == 0) {
5799 error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
5803 endp = (void *)((uint8_t *)dirent +
5804 sizeof(struct dirent) - uio.uio_resid);
5805 for (dp = dirent; dp < endp;
5806 dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
5807 if (dp->d_type == DT_WHT)
5809 if (dp->d_namlen == 0)
5811 if (dp->d_type != DT_DIR &&
5812 dp->d_type != DT_UNKNOWN) {
5816 if (dp->d_namlen > 2) {
5820 if (dp->d_namlen == 1 &&
5821 dp->d_name[0] != '.') {
5825 if (dp->d_namlen == 2 &&
5826 dp->d_name[1] != '.') {
5830 uio.uio_resid = sizeof(struct dirent);
5833 free(dirent, M_TEMP);
5838 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
5842 if (dp->d_reclen > ap->a_uio->uio_resid)
5843 return (ENAMETOOLONG);
5844 error = uiomove(dp, dp->d_reclen, ap->a_uio);
5846 if (ap->a_ncookies != NULL) {
5847 if (ap->a_cookies != NULL)
5848 free(ap->a_cookies, M_TEMP);
5849 ap->a_cookies = NULL;
5850 *ap->a_ncookies = 0;
5854 if (ap->a_ncookies == NULL)
5857 KASSERT(ap->a_cookies,
5858 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
5860 *ap->a_cookies = realloc(*ap->a_cookies,
5861 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
5862 (*ap->a_cookies)[*ap->a_ncookies] = off;
5863 *ap->a_ncookies += 1;
5868 * Mark for update the access time of the file if the filesystem
5869 * supports VOP_MARKATIME. This functionality is used by execve and
5870 * mmap, so we want to avoid the I/O implied by directly setting
5871 * va_atime for the sake of efficiency.
5874 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
5879 ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
5880 if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
5881 (void)VOP_MARKATIME(vp);
5885 * The purpose of this routine is to remove granularity from accmode_t,
5886 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
5887 * VADMIN and VAPPEND.
5889 * If it returns 0, the caller is supposed to continue with the usual
5890 * access checks using 'accmode' as modified by this routine. If it
5891 * returns nonzero value, the caller is supposed to return that value
5894 * Note that after this routine runs, accmode may be zero.
5897 vfs_unixify_accmode(accmode_t *accmode)
5900 * There is no way to specify explicit "deny" rule using
5901 * file mode or POSIX.1e ACLs.
5903 if (*accmode & VEXPLICIT_DENY) {
5909 * None of these can be translated into usual access bits.
5910 * Also, the common case for NFSv4 ACLs is to not contain
5911 * either of these bits. Caller should check for VWRITE
5912 * on the containing directory instead.
5914 if (*accmode & (VDELETE_CHILD | VDELETE))
5917 if (*accmode & VADMIN_PERMS) {
5918 *accmode &= ~VADMIN_PERMS;
5923 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
5924 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
5926 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
5932 * Clear out a doomed vnode (if any) and replace it with a new one as long
5933 * as the fs is not being unmounted. Return the root vnode to the caller.
5935 static int __noinline
5936 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
5942 if (mp->mnt_rootvnode != NULL) {
5944 vp = mp->mnt_rootvnode;
5946 if (!VN_IS_DOOMED(vp)) {
5949 error = vn_lock(vp, flags);
5958 * Clear the old one.
5960 mp->mnt_rootvnode = NULL;
5965 * Paired with a fence in vfs_op_thread_exit().
5967 atomic_thread_fence_acq();
5968 vfs_op_barrier_wait(mp);
5972 error = VFS_CACHEDROOT(mp, flags, vpp);
5975 if (mp->mnt_vfs_ops == 0) {
5977 if (mp->mnt_vfs_ops != 0) {
5981 if (mp->mnt_rootvnode == NULL) {
5983 mp->mnt_rootvnode = *vpp;
5985 if (mp->mnt_rootvnode != *vpp) {
5986 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
5987 panic("%s: mismatch between vnode returned "
5988 " by VFS_CACHEDROOT and the one cached "
5990 __func__, *vpp, mp->mnt_rootvnode);
6000 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6005 if (!vfs_op_thread_enter(mp))
6006 return (vfs_cache_root_fallback(mp, flags, vpp));
6007 vp = (struct vnode *)atomic_load_ptr(&mp->mnt_rootvnode);
6008 if (vp == NULL || VN_IS_DOOMED(vp)) {
6009 vfs_op_thread_exit(mp);
6010 return (vfs_cache_root_fallback(mp, flags, vpp));
6013 vfs_op_thread_exit(mp);
6014 error = vn_lock(vp, flags);
6017 return (vfs_cache_root_fallback(mp, flags, vpp));
6024 vfs_cache_root_clear(struct mount *mp)
6029 * ops > 0 guarantees there is nobody who can see this vnode
6031 MPASS(mp->mnt_vfs_ops > 0);
6032 vp = mp->mnt_rootvnode;
6033 mp->mnt_rootvnode = NULL;
6038 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6041 MPASS(mp->mnt_vfs_ops > 0);
6043 mp->mnt_rootvnode = vp;
6047 * These are helper functions for filesystems to traverse all
6048 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6050 * This interface replaces MNT_VNODE_FOREACH.
6055 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6060 kern_yield(PRI_USER);
6062 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6063 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6064 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6065 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6066 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6069 if (VN_IS_DOOMED(vp)) {
6076 __mnt_vnode_markerfree_all(mvp, mp);
6077 /* MNT_IUNLOCK(mp); -- done in above function */
6078 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6081 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6082 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6088 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6092 *mvp = vn_alloc_marker(mp);
6096 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6097 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6098 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6101 if (VN_IS_DOOMED(vp)) {
6110 vn_free_marker(*mvp);
6114 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6120 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6128 mtx_assert(MNT_MTX(mp), MA_OWNED);
6130 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6131 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6134 vn_free_marker(*mvp);
6139 * These are helper functions for filesystems to traverse their
6140 * lazy vnodes. See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6143 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6146 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6151 vn_free_marker(*mvp);
6156 * Relock the mp mount vnode list lock with the vp vnode interlock in the
6157 * conventional lock order during mnt_vnode_next_lazy iteration.
6159 * On entry, the mount vnode list lock is held and the vnode interlock is not.
6160 * The list lock is dropped and reacquired. On success, both locks are held.
6161 * On failure, the mount vnode list lock is held but the vnode interlock is
6162 * not, and the procedure may have yielded.
6165 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6168 const struct vnode *tmp;
6171 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6172 TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6173 ("%s: bad marker", __func__));
6174 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6175 ("%s: inappropriate vnode", __func__));
6176 ASSERT_VI_UNLOCKED(vp, __func__);
6177 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6181 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6182 TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6185 * Use a hold to prevent vp from disappearing while the mount vnode
6186 * list lock is dropped and reacquired. Normally a hold would be
6187 * acquired with vhold(), but that might try to acquire the vnode
6188 * interlock, which would be a LOR with the mount vnode list lock.
6190 held = refcount_acquire_if_not_zero(&vp->v_holdcnt);
6191 mtx_unlock(&mp->mnt_listmtx);
6195 if (!refcount_release_if_not_last(&vp->v_holdcnt)) {
6199 mtx_lock(&mp->mnt_listmtx);
6202 * Determine whether the vnode is still the next one after the marker,
6203 * excepting any other markers. If the vnode has not been doomed by
6204 * vgone() then the hold should have ensured that it remained on the
6205 * lazy list. If it has been doomed but is still on the lazy list,
6206 * don't abort, but rather skip over it (avoid spinning on doomed
6211 tmp = TAILQ_NEXT(tmp, v_lazylist);
6212 } while (tmp != NULL && tmp->v_type == VMARKER);
6214 mtx_unlock(&mp->mnt_listmtx);
6223 mtx_lock(&mp->mnt_listmtx);
6226 ASSERT_VI_LOCKED(vp, __func__);
6228 ASSERT_VI_UNLOCKED(vp, __func__);
6229 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6233 static struct vnode *
6234 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6237 struct vnode *vp, *nvp;
6239 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6240 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6242 vp = TAILQ_NEXT(*mvp, v_lazylist);
6243 while (vp != NULL) {
6244 if (vp->v_type == VMARKER) {
6245 vp = TAILQ_NEXT(vp, v_lazylist);
6249 * See if we want to process the vnode. Note we may encounter a
6250 * long string of vnodes we don't care about and hog the list
6251 * as a result. Check for it and requeue the marker.
6253 if (VN_IS_DOOMED(vp) || !cb(vp, cbarg)) {
6254 if (!should_yield()) {
6255 vp = TAILQ_NEXT(vp, v_lazylist);
6258 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6260 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6262 mtx_unlock(&mp->mnt_listmtx);
6263 kern_yield(PRI_USER);
6264 mtx_lock(&mp->mnt_listmtx);
6268 * Try-lock because this is the wrong lock order. If that does
6269 * not succeed, drop the mount vnode list lock and try to
6270 * reacquire it and the vnode interlock in the right order.
6272 if (!VI_TRYLOCK(vp) &&
6273 !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6275 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6276 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6277 ("alien vnode on the lazy list %p %p", vp, mp));
6278 if (vp->v_mount == mp && !VN_IS_DOOMED(vp))
6280 nvp = TAILQ_NEXT(vp, v_lazylist);
6284 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6286 /* Check if we are done */
6288 mtx_unlock(&mp->mnt_listmtx);
6289 mnt_vnode_markerfree_lazy(mvp, mp);
6292 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6293 mtx_unlock(&mp->mnt_listmtx);
6294 ASSERT_VI_LOCKED(vp, "lazy iter");
6299 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6304 kern_yield(PRI_USER);
6305 mtx_lock(&mp->mnt_listmtx);
6306 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6310 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6315 *mvp = vn_alloc_marker(mp);
6320 mtx_lock(&mp->mnt_listmtx);
6321 vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6323 mtx_unlock(&mp->mnt_listmtx);
6324 mnt_vnode_markerfree_lazy(mvp, mp);
6327 TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6328 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6332 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6338 mtx_lock(&mp->mnt_listmtx);
6339 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6340 mtx_unlock(&mp->mnt_listmtx);
6341 mnt_vnode_markerfree_lazy(mvp, mp);