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 u_long wantfreevnodes;
195 static u_long __exclusive_cache_line freevnodes;
196 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
197 &freevnodes, 0, "Number of \"free\" vnodes");
199 static counter_u64_t recycles_count;
200 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
201 "Number of vnodes recycled to meet vnode cache targets");
203 static counter_u64_t recycles_free_count;
204 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD, &recycles_free_count,
205 "Number of free vnodes recycled to meet vnode cache targets");
208 * Various variables used for debugging the new implementation of
210 * XXX these are probably of (very) limited utility now.
212 static int reassignbufcalls;
213 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW | CTLFLAG_STATS,
214 &reassignbufcalls, 0, "Number of calls to reassignbuf");
216 static counter_u64_t deferred_inact;
217 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, deferred_inact, CTLFLAG_RD, &deferred_inact,
218 "Number of times inactive processing was deferred");
220 /* To keep more than one thread at a time from running vfs_getnewfsid */
221 static struct mtx mntid_mtx;
224 * Lock for any access to the following:
229 static struct mtx __exclusive_cache_line vnode_list_mtx;
231 /* Publicly exported FS */
232 struct nfs_public nfs_pub;
234 static uma_zone_t buf_trie_zone;
236 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
237 static uma_zone_t vnode_zone;
238 static uma_zone_t vnodepoll_zone;
241 * The workitem queue.
243 * It is useful to delay writes of file data and filesystem metadata
244 * for tens of seconds so that quickly created and deleted files need
245 * not waste disk bandwidth being created and removed. To realize this,
246 * we append vnodes to a "workitem" queue. When running with a soft
247 * updates implementation, most pending metadata dependencies should
248 * not wait for more than a few seconds. Thus, mounted on block devices
249 * are delayed only about a half the time that file data is delayed.
250 * Similarly, directory updates are more critical, so are only delayed
251 * about a third the time that file data is delayed. Thus, there are
252 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
253 * one each second (driven off the filesystem syncer process). The
254 * syncer_delayno variable indicates the next queue that is to be processed.
255 * Items that need to be processed soon are placed in this queue:
257 * syncer_workitem_pending[syncer_delayno]
259 * A delay of fifteen seconds is done by placing the request fifteen
260 * entries later in the queue:
262 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
265 static int syncer_delayno;
266 static long syncer_mask;
267 LIST_HEAD(synclist, bufobj);
268 static struct synclist *syncer_workitem_pending;
270 * The sync_mtx protects:
275 * syncer_workitem_pending
276 * syncer_worklist_len
279 static struct mtx sync_mtx;
280 static struct cv sync_wakeup;
282 #define SYNCER_MAXDELAY 32
283 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
284 static int syncdelay = 30; /* max time to delay syncing data */
285 static int filedelay = 30; /* time to delay syncing files */
286 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
287 "Time to delay syncing files (in seconds)");
288 static int dirdelay = 29; /* time to delay syncing directories */
289 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
290 "Time to delay syncing directories (in seconds)");
291 static int metadelay = 28; /* time to delay syncing metadata */
292 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
293 "Time to delay syncing metadata (in seconds)");
294 static int rushjob; /* number of slots to run ASAP */
295 static int stat_rush_requests; /* number of times I/O speeded up */
296 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
297 "Number of times I/O speeded up (rush requests)");
299 #define VDBATCH_SIZE 8
303 struct vnode *tab[VDBATCH_SIZE];
305 DPCPU_DEFINE_STATIC(struct vdbatch, vd);
307 static void vdbatch_dequeue(struct vnode *vp);
310 * When shutting down the syncer, run it at four times normal speed.
312 #define SYNCER_SHUTDOWN_SPEEDUP 4
313 static int sync_vnode_count;
314 static int syncer_worklist_len;
315 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
318 /* Target for maximum number of vnodes. */
319 u_long desiredvnodes;
320 static u_long gapvnodes; /* gap between wanted and desired */
321 static u_long vhiwat; /* enough extras after expansion */
322 static u_long vlowat; /* minimal extras before expansion */
323 static u_long vstir; /* nonzero to stir non-free vnodes */
324 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
327 * Note that no attempt is made to sanitize these parameters.
330 sysctl_maxvnodes(SYSCTL_HANDLER_ARGS)
336 error = sysctl_handle_long(oidp, &val, 0, req);
337 if (error != 0 || req->newptr == NULL)
340 if (val == desiredvnodes)
342 mtx_lock(&vnode_list_mtx);
344 wantfreevnodes = desiredvnodes / 4;
346 mtx_unlock(&vnode_list_mtx);
348 * XXX There is no protection against multiple threads changing
349 * desiredvnodes at the same time. Locking above only helps vnlru and
352 vfs_hash_changesize(desiredvnodes);
353 cache_changesize(desiredvnodes);
357 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
358 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
359 "UL", "Target for maximum number of vnodes");
362 sysctl_wantfreevnodes(SYSCTL_HANDLER_ARGS)
367 val = wantfreevnodes;
368 error = sysctl_handle_long(oidp, &val, 0, req);
369 if (error != 0 || req->newptr == NULL)
372 if (val == wantfreevnodes)
374 mtx_lock(&vnode_list_mtx);
375 wantfreevnodes = val;
377 mtx_unlock(&vnode_list_mtx);
381 SYSCTL_PROC(_vfs, OID_AUTO, wantfreevnodes,
382 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
383 "UL", "Target for minimum number of \"free\" vnodes");
385 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
386 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
387 static int vnlru_nowhere;
388 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
389 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
392 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
397 unsigned long ndflags;
400 if (req->newptr == NULL)
402 if (req->newlen >= PATH_MAX)
405 buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
406 error = SYSCTL_IN(req, buf, req->newlen);
410 buf[req->newlen] = '\0';
412 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | NOCACHE | SAVENAME;
413 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
414 if ((error = namei(&nd)) != 0)
418 if (VN_IS_DOOMED(vp)) {
420 * This vnode is being recycled. Return != 0 to let the caller
421 * know that the sysctl had no effect. Return EAGAIN because a
422 * subsequent call will likely succeed (since namei will create
423 * a new vnode if necessary)
429 counter_u64_add(recycles_count, 1);
439 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
441 struct thread *td = curthread;
447 if (req->newptr == NULL)
450 error = sysctl_handle_int(oidp, &fd, 0, req);
453 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
458 error = vn_lock(vp, LK_EXCLUSIVE);
462 counter_u64_add(recycles_count, 1);
470 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
471 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
472 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
473 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
474 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
475 sysctl_ftry_reclaim_vnode, "I",
476 "Try to reclaim a vnode by its file descriptor");
478 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
482 * Support for the bufobj clean & dirty pctrie.
485 buf_trie_alloc(struct pctrie *ptree)
488 return uma_zalloc(buf_trie_zone, M_NOWAIT);
492 buf_trie_free(struct pctrie *ptree, void *node)
495 uma_zfree(buf_trie_zone, node);
497 PCTRIE_DEFINE(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free);
500 * Initialize the vnode management data structures.
502 * Reevaluate the following cap on the number of vnodes after the physical
503 * memory size exceeds 512GB. In the limit, as the physical memory size
504 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
506 #ifndef MAXVNODES_MAX
507 #define MAXVNODES_MAX (512UL * 1024 * 1024 / 64) /* 8M */
510 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
512 static struct vnode *
513 vn_alloc_marker(struct mount *mp)
517 vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
518 vp->v_type = VMARKER;
525 vn_free_marker(struct vnode *vp)
528 MPASS(vp->v_type == VMARKER);
529 free(vp, M_VNODE_MARKER);
533 * Initialize a vnode as it first enters the zone.
536 vnode_init(void *mem, int size, int flags)
545 vp->v_vnlock = &vp->v_lock;
546 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
548 * By default, don't allow shared locks unless filesystems opt-in.
550 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
551 LK_NOSHARE | LK_IS_VNODE);
555 bufobj_init(&vp->v_bufobj, vp);
557 * Initialize namecache.
559 LIST_INIT(&vp->v_cache_src);
560 TAILQ_INIT(&vp->v_cache_dst);
562 * Initialize rangelocks.
564 rangelock_init(&vp->v_rl);
566 vp->v_dbatchcpu = NOCPU;
568 mtx_lock(&vnode_list_mtx);
569 TAILQ_INSERT_BEFORE(vnode_list_free_marker, vp, v_vnodelist);
570 mtx_unlock(&vnode_list_mtx);
575 * Free a vnode when it is cleared from the zone.
578 vnode_fini(void *mem, int size)
585 mtx_lock(&vnode_list_mtx);
586 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
587 mtx_unlock(&vnode_list_mtx);
588 rangelock_destroy(&vp->v_rl);
589 lockdestroy(vp->v_vnlock);
590 mtx_destroy(&vp->v_interlock);
592 rw_destroy(BO_LOCKPTR(bo));
596 * Provide the size of NFS nclnode and NFS fh for calculation of the
597 * vnode memory consumption. The size is specified directly to
598 * eliminate dependency on NFS-private header.
600 * Other filesystems may use bigger or smaller (like UFS and ZFS)
601 * private inode data, but the NFS-based estimation is ample enough.
602 * Still, we care about differences in the size between 64- and 32-bit
605 * Namecache structure size is heuristically
606 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
609 #define NFS_NCLNODE_SZ (528 + 64)
612 #define NFS_NCLNODE_SZ (360 + 32)
617 vntblinit(void *dummy __unused)
620 int cpu, physvnodes, virtvnodes;
624 * Desiredvnodes is a function of the physical memory size and the
625 * kernel's heap size. Generally speaking, it scales with the
626 * physical memory size. The ratio of desiredvnodes to the physical
627 * memory size is 1:16 until desiredvnodes exceeds 98,304.
629 * marginal ratio of desiredvnodes to the physical memory size is
630 * 1:64. However, desiredvnodes is limited by the kernel's heap
631 * size. The memory required by desiredvnodes vnodes and vm objects
632 * must not exceed 1/10th of the kernel's heap size.
634 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
635 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
636 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
637 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
638 desiredvnodes = min(physvnodes, virtvnodes);
639 if (desiredvnodes > MAXVNODES_MAX) {
641 printf("Reducing kern.maxvnodes %lu -> %lu\n",
642 desiredvnodes, MAXVNODES_MAX);
643 desiredvnodes = MAXVNODES_MAX;
645 wantfreevnodes = desiredvnodes / 4;
646 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
647 TAILQ_INIT(&vnode_list);
648 mtx_init(&vnode_list_mtx, "vnode_list", NULL, MTX_DEF);
650 * The lock is taken to appease WITNESS.
652 mtx_lock(&vnode_list_mtx);
654 mtx_unlock(&vnode_list_mtx);
655 vnode_list_free_marker = vn_alloc_marker(NULL);
656 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_free_marker, v_vnodelist);
657 vnode_list_reclaim_marker = vn_alloc_marker(NULL);
658 TAILQ_INSERT_HEAD(&vnode_list, vnode_list_reclaim_marker, v_vnodelist);
659 vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
660 vnode_init, vnode_fini, UMA_ALIGN_PTR, 0);
661 vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
662 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
664 * Preallocate enough nodes to support one-per buf so that
665 * we can not fail an insert. reassignbuf() callers can not
666 * tolerate the insertion failure.
668 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
669 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
670 UMA_ZONE_NOFREE | UMA_ZONE_VM);
671 uma_prealloc(buf_trie_zone, nbuf);
673 vnodes_created = counter_u64_alloc(M_WAITOK);
674 recycles_count = counter_u64_alloc(M_WAITOK);
675 recycles_free_count = counter_u64_alloc(M_WAITOK);
676 deferred_inact = counter_u64_alloc(M_WAITOK);
679 * Initialize the filesystem syncer.
681 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
683 syncer_maxdelay = syncer_mask + 1;
684 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
685 cv_init(&sync_wakeup, "syncer");
686 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
691 vd = DPCPU_ID_PTR((cpu), vd);
692 bzero(vd, sizeof(*vd));
693 mtx_init(&vd->lock, "vdbatch", NULL, MTX_DEF);
696 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
700 * Mark a mount point as busy. Used to synchronize access and to delay
701 * unmounting. Eventually, mountlist_mtx is not released on failure.
703 * vfs_busy() is a custom lock, it can block the caller.
704 * vfs_busy() only sleeps if the unmount is active on the mount point.
705 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
706 * vnode belonging to mp.
708 * Lookup uses vfs_busy() to traverse mount points.
710 * / vnode lock A / vnode lock (/var) D
711 * /var vnode lock B /log vnode lock(/var/log) E
712 * vfs_busy lock C vfs_busy lock F
714 * Within each file system, the lock order is C->A->B and F->D->E.
716 * When traversing across mounts, the system follows that lock order:
722 * The lookup() process for namei("/var") illustrates the process:
723 * VOP_LOOKUP() obtains B while A is held
724 * vfs_busy() obtains a shared lock on F while A and B are held
725 * vput() releases lock on B
726 * vput() releases lock on A
727 * VFS_ROOT() obtains lock on D while shared lock on F is held
728 * vfs_unbusy() releases shared lock on F
729 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
730 * Attempt to lock A (instead of vp_crossmp) while D is held would
731 * violate the global order, causing deadlocks.
733 * dounmount() locks B while F is drained.
736 vfs_busy(struct mount *mp, int flags)
739 MPASS((flags & ~MBF_MASK) == 0);
740 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
742 if (vfs_op_thread_enter(mp)) {
743 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
744 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
745 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
746 vfs_mp_count_add_pcpu(mp, ref, 1);
747 vfs_mp_count_add_pcpu(mp, lockref, 1);
748 vfs_op_thread_exit(mp);
749 if (flags & MBF_MNTLSTLOCK)
750 mtx_unlock(&mountlist_mtx);
755 vfs_assert_mount_counters(mp);
758 * If mount point is currently being unmounted, sleep until the
759 * mount point fate is decided. If thread doing the unmounting fails,
760 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
761 * that this mount point has survived the unmount attempt and vfs_busy
762 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
763 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
764 * about to be really destroyed. vfs_busy needs to release its
765 * reference on the mount point in this case and return with ENOENT,
766 * telling the caller that mount mount it tried to busy is no longer
769 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
770 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
773 CTR1(KTR_VFS, "%s: failed busying before sleeping",
777 if (flags & MBF_MNTLSTLOCK)
778 mtx_unlock(&mountlist_mtx);
779 mp->mnt_kern_flag |= MNTK_MWAIT;
780 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
781 if (flags & MBF_MNTLSTLOCK)
782 mtx_lock(&mountlist_mtx);
785 if (flags & MBF_MNTLSTLOCK)
786 mtx_unlock(&mountlist_mtx);
793 * Free a busy filesystem.
796 vfs_unbusy(struct mount *mp)
800 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
802 if (vfs_op_thread_enter(mp)) {
803 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
804 vfs_mp_count_sub_pcpu(mp, lockref, 1);
805 vfs_mp_count_sub_pcpu(mp, ref, 1);
806 vfs_op_thread_exit(mp);
811 vfs_assert_mount_counters(mp);
813 c = --mp->mnt_lockref;
814 if (mp->mnt_vfs_ops == 0) {
815 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
820 vfs_dump_mount_counters(mp);
821 if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
822 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
823 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
824 mp->mnt_kern_flag &= ~MNTK_DRAINING;
825 wakeup(&mp->mnt_lockref);
831 * Lookup a mount point by filesystem identifier.
834 vfs_getvfs(fsid_t *fsid)
838 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
839 mtx_lock(&mountlist_mtx);
840 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
841 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
842 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
844 mtx_unlock(&mountlist_mtx);
848 mtx_unlock(&mountlist_mtx);
849 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
850 return ((struct mount *) 0);
854 * Lookup a mount point by filesystem identifier, busying it before
857 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
858 * cache for popular filesystem identifiers. The cache is lockess, using
859 * the fact that struct mount's are never freed. In worst case we may
860 * get pointer to unmounted or even different filesystem, so we have to
861 * check what we got, and go slow way if so.
864 vfs_busyfs(fsid_t *fsid)
866 #define FSID_CACHE_SIZE 256
867 typedef struct mount * volatile vmp_t;
868 static vmp_t cache[FSID_CACHE_SIZE];
873 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
874 hash = fsid->val[0] ^ fsid->val[1];
875 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
878 mp->mnt_stat.f_fsid.val[0] != fsid->val[0] ||
879 mp->mnt_stat.f_fsid.val[1] != fsid->val[1])
881 if (vfs_busy(mp, 0) != 0) {
885 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
886 mp->mnt_stat.f_fsid.val[1] == fsid->val[1])
892 mtx_lock(&mountlist_mtx);
893 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
894 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
895 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
896 error = vfs_busy(mp, MBF_MNTLSTLOCK);
899 mtx_unlock(&mountlist_mtx);
906 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
907 mtx_unlock(&mountlist_mtx);
908 return ((struct mount *) 0);
912 * Check if a user can access privileged mount options.
915 vfs_suser(struct mount *mp, struct thread *td)
919 if (jailed(td->td_ucred)) {
921 * If the jail of the calling thread lacks permission for
922 * this type of file system, deny immediately.
924 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
928 * If the file system was mounted outside the jail of the
929 * calling thread, deny immediately.
931 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
936 * If file system supports delegated administration, we don't check
937 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
938 * by the file system itself.
939 * If this is not the user that did original mount, we check for
940 * the PRIV_VFS_MOUNT_OWNER privilege.
942 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
943 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
944 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
951 * Get a new unique fsid. Try to make its val[0] unique, since this value
952 * will be used to create fake device numbers for stat(). Also try (but
953 * not so hard) make its val[0] unique mod 2^16, since some emulators only
954 * support 16-bit device numbers. We end up with unique val[0]'s for the
955 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
957 * Keep in mind that several mounts may be running in parallel. Starting
958 * the search one past where the previous search terminated is both a
959 * micro-optimization and a defense against returning the same fsid to
963 vfs_getnewfsid(struct mount *mp)
965 static uint16_t mntid_base;
970 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
971 mtx_lock(&mntid_mtx);
972 mtype = mp->mnt_vfc->vfc_typenum;
973 tfsid.val[1] = mtype;
974 mtype = (mtype & 0xFF) << 24;
976 tfsid.val[0] = makedev(255,
977 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
979 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
983 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
984 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
985 mtx_unlock(&mntid_mtx);
989 * Knob to control the precision of file timestamps:
991 * 0 = seconds only; nanoseconds zeroed.
992 * 1 = seconds and nanoseconds, accurate within 1/HZ.
993 * 2 = seconds and nanoseconds, truncated to microseconds.
994 * >=3 = seconds and nanoseconds, maximum precision.
996 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
998 static int timestamp_precision = TSP_USEC;
999 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
1000 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
1001 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
1002 "3+: sec + ns (max. precision))");
1005 * Get a current timestamp.
1008 vfs_timestamp(struct timespec *tsp)
1012 switch (timestamp_precision) {
1014 tsp->tv_sec = time_second;
1022 TIMEVAL_TO_TIMESPEC(&tv, tsp);
1032 * Set vnode attributes to VNOVAL
1035 vattr_null(struct vattr *vap)
1038 vap->va_type = VNON;
1039 vap->va_size = VNOVAL;
1040 vap->va_bytes = VNOVAL;
1041 vap->va_mode = VNOVAL;
1042 vap->va_nlink = VNOVAL;
1043 vap->va_uid = VNOVAL;
1044 vap->va_gid = VNOVAL;
1045 vap->va_fsid = VNOVAL;
1046 vap->va_fileid = VNOVAL;
1047 vap->va_blocksize = VNOVAL;
1048 vap->va_rdev = VNOVAL;
1049 vap->va_atime.tv_sec = VNOVAL;
1050 vap->va_atime.tv_nsec = VNOVAL;
1051 vap->va_mtime.tv_sec = VNOVAL;
1052 vap->va_mtime.tv_nsec = VNOVAL;
1053 vap->va_ctime.tv_sec = VNOVAL;
1054 vap->va_ctime.tv_nsec = VNOVAL;
1055 vap->va_birthtime.tv_sec = VNOVAL;
1056 vap->va_birthtime.tv_nsec = VNOVAL;
1057 vap->va_flags = VNOVAL;
1058 vap->va_gen = VNOVAL;
1059 vap->va_vaflags = 0;
1063 * Try to reduce the total number of vnodes.
1065 * This routine (and its user) are buggy in at least the following ways:
1066 * - all parameters were picked years ago when RAM sizes were significantly
1068 * - it can pick vnodes based on pages used by the vm object, but filesystems
1069 * like ZFS don't use it making the pick broken
1070 * - since ZFS has its own aging policy it gets partially combated by this one
1071 * - a dedicated method should be provided for filesystems to let them decide
1072 * whether the vnode should be recycled
1074 * This routine is called when we have too many vnodes. It attempts
1075 * to free <count> vnodes and will potentially free vnodes that still
1076 * have VM backing store (VM backing store is typically the cause
1077 * of a vnode blowout so we want to do this). Therefore, this operation
1078 * is not considered cheap.
1080 * A number of conditions may prevent a vnode from being reclaimed.
1081 * the buffer cache may have references on the vnode, a directory
1082 * vnode may still have references due to the namei cache representing
1083 * underlying files, or the vnode may be in active use. It is not
1084 * desirable to reuse such vnodes. These conditions may cause the
1085 * number of vnodes to reach some minimum value regardless of what
1086 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
1088 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1089 * entries if this argument is strue
1090 * @param trigger Only reclaim vnodes with fewer than this many resident
1092 * @param target How many vnodes to reclaim.
1093 * @return The number of vnodes that were reclaimed.
1096 vlrureclaim(bool reclaim_nc_src, int trigger, u_long target)
1098 struct vnode *vp, *mvp;
1103 mtx_assert(&vnode_list_mtx, MA_OWNED);
1108 mvp = vnode_list_reclaim_marker;
1111 while (done < target) {
1112 vp = TAILQ_NEXT(vp, v_vnodelist);
1113 if (__predict_false(vp == NULL))
1116 if (__predict_false(vp->v_type == VMARKER))
1120 * If it's been deconstructed already, it's still
1121 * referenced, or it exceeds the trigger, skip it.
1122 * Also skip free vnodes. We are trying to make space
1123 * to expand the free list, not reduce it.
1125 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1126 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)))
1129 if (vp->v_type == VBAD || vp->v_type == VNON)
1132 if (!VI_TRYLOCK(vp))
1135 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1136 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1137 vp->v_type == VBAD || vp->v_type == VNON ||
1138 (vp->v_object != NULL &&
1139 vp->v_object->resident_page_count > trigger)) {
1145 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1146 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1147 mtx_unlock(&vnode_list_mtx);
1149 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1151 goto next_iter_unlocked;
1153 if (VOP_LOCK(vp, LK_EXCLUSIVE|LK_NOWAIT) != 0) {
1155 vn_finished_write(mp);
1156 goto next_iter_unlocked;
1160 if (vp->v_usecount > 0 ||
1161 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1162 (vp->v_object != NULL &&
1163 vp->v_object->resident_page_count > trigger)) {
1166 vn_finished_write(mp);
1167 goto next_iter_unlocked;
1169 counter_u64_add(recycles_count, 1);
1173 vn_finished_write(mp);
1177 kern_yield(PRI_USER);
1178 mtx_lock(&vnode_list_mtx);
1181 MPASS(vp->v_type != VMARKER);
1182 if (!should_yield())
1184 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1185 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1186 mtx_unlock(&vnode_list_mtx);
1187 kern_yield(PRI_USER);
1188 mtx_lock(&vnode_list_mtx);
1191 if (done == 0 && !retried) {
1192 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1193 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1200 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1201 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1203 "limit on vnode free requests per call to the vnlru_free routine");
1206 * Attempt to reduce the free list by the requested amount.
1209 vnlru_free_locked(int count, struct vfsops *mnt_op)
1211 struct vnode *vp, *mvp;
1214 mtx_assert(&vnode_list_mtx, MA_OWNED);
1215 if (count > max_vnlru_free)
1216 count = max_vnlru_free;
1217 mvp = vnode_list_free_marker;
1221 vp = TAILQ_NEXT(vp, v_vnodelist);
1222 if (__predict_false(vp == NULL)) {
1223 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1224 TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1227 if (__predict_false(vp->v_type == VMARKER))
1231 * Don't recycle if our vnode is from different type
1232 * of mount point. Note that mp is type-safe, the
1233 * check does not reach unmapped address even if
1234 * vnode is reclaimed.
1235 * Don't recycle if we can't get the interlock without
1238 if (vp->v_holdcnt > 0 || (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1239 mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
1242 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1243 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1244 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1250 mtx_unlock(&vnode_list_mtx);
1254 mtx_lock(&vnode_list_mtx);
1260 vnlru_free(int count, struct vfsops *mnt_op)
1263 mtx_lock(&vnode_list_mtx);
1264 vnlru_free_locked(count, mnt_op);
1265 mtx_unlock(&vnode_list_mtx);
1272 mtx_assert(&vnode_list_mtx, MA_OWNED);
1273 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1274 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1275 vlowat = vhiwat / 2;
1279 * Attempt to recycle vnodes in a context that is always safe to block.
1280 * Calling vlrurecycle() from the bowels of filesystem code has some
1281 * interesting deadlock problems.
1283 static struct proc *vnlruproc;
1284 static int vnlruproc_sig;
1287 vnlru_under(u_long rnumvnodes, u_long limit)
1289 u_long rfreevnodes, space;
1291 if (__predict_false(rnumvnodes > desiredvnodes))
1294 space = desiredvnodes - rnumvnodes;
1295 if (space < limit) {
1296 rfreevnodes = atomic_load_long(&freevnodes);
1297 if (rfreevnodes > wantfreevnodes)
1298 space += rfreevnodes - wantfreevnodes;
1300 return (space < limit);
1307 mtx_assert(&vnode_list_mtx, MA_OWNED);
1308 if (vnlruproc_sig == 0) {
1317 u_long rnumvnodes, rfreevnodes, target;
1318 unsigned long onumvnodes;
1319 int done, force, trigger, usevnodes;
1320 bool reclaim_nc_src;
1322 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1323 SHUTDOWN_PRI_FIRST);
1327 kproc_suspend_check(vnlruproc);
1328 mtx_lock(&vnode_list_mtx);
1329 rnumvnodes = atomic_load_long(&numvnodes);
1331 * If numvnodes is too large (due to desiredvnodes being
1332 * adjusted using its sysctl, or emergency growth), first
1333 * try to reduce it by discarding from the free list.
1335 if (rnumvnodes > desiredvnodes) {
1336 vnlru_free_locked(rnumvnodes - desiredvnodes, NULL);
1337 rnumvnodes = atomic_load_long(&numvnodes);
1340 * Sleep if the vnode cache is in a good state. This is
1341 * when it is not over-full and has space for about a 4%
1342 * or 9% expansion (by growing its size or inexcessively
1343 * reducing its free list). Otherwise, try to reclaim
1344 * space for a 10% expansion.
1346 if (vstir && force == 0) {
1350 if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1352 wakeup(&vnlruproc_sig);
1353 msleep(vnlruproc, &vnode_list_mtx,
1354 PVFS|PDROP, "vlruwt", hz);
1357 rfreevnodes = atomic_load_long(&freevnodes);
1359 onumvnodes = rnumvnodes;
1361 * Calculate parameters for recycling. These are the same
1362 * throughout the loop to give some semblance of fairness.
1363 * The trigger point is to avoid recycling vnodes with lots
1364 * of resident pages. We aren't trying to free memory; we
1365 * are trying to recycle or at least free vnodes.
1367 if (rnumvnodes <= desiredvnodes)
1368 usevnodes = rnumvnodes - rfreevnodes;
1370 usevnodes = rnumvnodes;
1374 * The trigger value is is chosen to give a conservatively
1375 * large value to ensure that it alone doesn't prevent
1376 * making progress. The value can easily be so large that
1377 * it is effectively infinite in some congested and
1378 * misconfigured cases, and this is necessary. Normally
1379 * it is about 8 to 100 (pages), which is quite large.
1381 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1383 trigger = vsmalltrigger;
1384 reclaim_nc_src = force >= 3;
1385 target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1386 target = target / 10 + 1;
1387 done = vlrureclaim(reclaim_nc_src, trigger, target);
1388 mtx_unlock(&vnode_list_mtx);
1389 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1390 uma_reclaim(UMA_RECLAIM_DRAIN);
1392 if (force == 0 || force == 1) {
1402 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1404 kern_yield(PRI_USER);
1406 * After becoming active to expand above low water, keep
1407 * active until above high water.
1409 force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1413 static struct kproc_desc vnlru_kp = {
1418 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1422 * Routines having to do with the management of the vnode table.
1426 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1427 * before we actually vgone(). This function must be called with the vnode
1428 * held to prevent the vnode from being returned to the free list midway
1432 vtryrecycle(struct vnode *vp)
1436 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1437 VNASSERT(vp->v_holdcnt, vp,
1438 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1440 * This vnode may found and locked via some other list, if so we
1441 * can't recycle it yet.
1443 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1445 "%s: impossible to recycle, vp %p lock is already held",
1447 return (EWOULDBLOCK);
1450 * Don't recycle if its filesystem is being suspended.
1452 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1455 "%s: impossible to recycle, cannot start the write for %p",
1460 * If we got this far, we need to acquire the interlock and see if
1461 * anyone picked up this vnode from another list. If not, we will
1462 * mark it with DOOMED via vgonel() so that anyone who does find it
1463 * will skip over it.
1466 if (vp->v_usecount) {
1469 vn_finished_write(vnmp);
1471 "%s: impossible to recycle, %p is already referenced",
1475 if (!VN_IS_DOOMED(vp)) {
1476 counter_u64_add(recycles_free_count, 1);
1481 vn_finished_write(vnmp);
1486 * Allocate a new vnode.
1488 * The operation never returns an error. Returning an error was disabled
1489 * in r145385 (dated 2005) with the following comment:
1491 * XXX Not all VFS_VGET/ffs_vget callers check returns.
1493 * Given the age of this commit (almost 15 years at the time of writing this
1494 * comment) restoring the ability to fail requires a significant audit of
1497 * The routine can try to free a vnode or stall for up to 1 second waiting for
1498 * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1500 static u_long vn_alloc_cyclecount;
1502 static struct vnode * __noinline
1503 vn_alloc_hard(struct mount *mp)
1505 u_long rnumvnodes, rfreevnodes;
1507 mtx_lock(&vnode_list_mtx);
1508 rnumvnodes = atomic_load_long(&numvnodes);
1509 if (rnumvnodes + 1 < desiredvnodes) {
1510 vn_alloc_cyclecount = 0;
1513 rfreevnodes = atomic_load_long(&freevnodes);
1514 if (vn_alloc_cyclecount++ >= rfreevnodes) {
1515 vn_alloc_cyclecount = 0;
1519 * Grow the vnode cache if it will not be above its target max
1520 * after growing. Otherwise, if the free list is nonempty, try
1521 * to reclaim 1 item from it before growing the cache (possibly
1522 * above its target max if the reclamation failed or is delayed).
1523 * Otherwise, wait for some space. In all cases, schedule
1524 * vnlru_proc() if we are getting short of space. The watermarks
1525 * should be chosen so that we never wait or even reclaim from
1526 * the free list to below its target minimum.
1528 if (rfreevnodes > 0) {
1529 vnlru_free_locked(1, NULL);
1532 if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1534 * Wait for space for a new vnode.
1537 msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1538 if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1539 atomic_load_long(&freevnodes) > 1)
1540 vnlru_free_locked(1, NULL);
1543 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1544 if (vnlru_under(rnumvnodes, vlowat))
1546 mtx_unlock(&vnode_list_mtx);
1547 return (uma_zalloc(vnode_zone, M_WAITOK));
1550 static struct vnode *
1551 vn_alloc(struct mount *mp)
1555 if (__predict_false(vn_alloc_cyclecount != 0))
1556 return (vn_alloc_hard(mp));
1557 rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1558 if (__predict_false(vnlru_under(rnumvnodes, vlowat))) {
1559 atomic_subtract_long(&numvnodes, 1);
1560 return (vn_alloc_hard(mp));
1563 return (uma_zalloc(vnode_zone, M_WAITOK));
1567 vn_free(struct vnode *vp)
1570 atomic_subtract_long(&numvnodes, 1);
1571 uma_zfree(vnode_zone, vp);
1575 * Return the next vnode from the free list.
1578 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1583 struct lock_object *lo;
1585 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1587 KASSERT(vops->registered,
1588 ("%s: not registered vector op %p\n", __func__, vops));
1591 if (td->td_vp_reserved != NULL) {
1592 vp = td->td_vp_reserved;
1593 td->td_vp_reserved = NULL;
1597 counter_u64_add(vnodes_created, 1);
1599 * Locks are given the generic name "vnode" when created.
1600 * Follow the historic practice of using the filesystem
1601 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1603 * Locks live in a witness group keyed on their name. Thus,
1604 * when a lock is renamed, it must also move from the witness
1605 * group of its old name to the witness group of its new name.
1607 * The change only needs to be made when the vnode moves
1608 * from one filesystem type to another. We ensure that each
1609 * filesystem use a single static name pointer for its tag so
1610 * that we can compare pointers rather than doing a strcmp().
1612 lo = &vp->v_vnlock->lock_object;
1613 if (lo->lo_name != tag) {
1615 WITNESS_DESTROY(lo);
1616 WITNESS_INIT(lo, tag);
1619 * By default, don't allow shared locks unless filesystems opt-in.
1621 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1623 * Finalize various vnode identity bits.
1625 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1626 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1627 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1630 v_init_counters(vp);
1631 vp->v_bufobj.bo_ops = &buf_ops_bio;
1633 if (mp == NULL && vops != &dead_vnodeops)
1634 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1638 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1639 mac_vnode_associate_singlelabel(mp, vp);
1642 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1643 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1644 vp->v_vflag |= VV_NOKNOTE;
1648 * For the filesystems which do not use vfs_hash_insert(),
1649 * still initialize v_hash to have vfs_hash_index() useful.
1650 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1653 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1660 getnewvnode_reserve(void)
1665 MPASS(td->td_vp_reserved == NULL);
1666 td->td_vp_reserved = vn_alloc(NULL);
1670 getnewvnode_drop_reserve(void)
1675 if (td->td_vp_reserved != NULL) {
1676 vn_free(td->td_vp_reserved);
1677 td->td_vp_reserved = NULL;
1682 freevnode(struct vnode *vp)
1687 * The vnode has been marked for destruction, so free it.
1689 * The vnode will be returned to the zone where it will
1690 * normally remain until it is needed for another vnode. We
1691 * need to cleanup (or verify that the cleanup has already
1692 * been done) any residual data left from its current use
1693 * so as not to contaminate the freshly allocated vnode.
1695 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1697 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1698 VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
1699 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1700 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1701 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1702 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1703 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1704 ("clean blk trie not empty"));
1705 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1706 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1707 ("dirty blk trie not empty"));
1708 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1709 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1710 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1711 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1712 ("Dangling rangelock waiters"));
1715 mac_vnode_destroy(vp);
1717 if (vp->v_pollinfo != NULL) {
1718 destroy_vpollinfo(vp->v_pollinfo);
1719 vp->v_pollinfo = NULL;
1722 /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
1725 vp->v_mountedhere = NULL;
1728 vp->v_fifoinfo = NULL;
1729 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
1738 * Delete from old mount point vnode list, if on one.
1741 delmntque(struct vnode *vp)
1750 if (vp->v_mflag & VMP_LAZYLIST) {
1751 mtx_lock(&mp->mnt_listmtx);
1752 if (vp->v_mflag & VMP_LAZYLIST) {
1753 vp->v_mflag &= ~VMP_LAZYLIST;
1754 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
1755 mp->mnt_lazyvnodelistsize--;
1757 mtx_unlock(&mp->mnt_listmtx);
1761 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1762 ("bad mount point vnode list size"));
1763 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1764 mp->mnt_nvnodelistsize--;
1770 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1774 vp->v_op = &dead_vnodeops;
1780 * Insert into list of vnodes for the new mount point, if available.
1783 insmntque1(struct vnode *vp, struct mount *mp,
1784 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1787 KASSERT(vp->v_mount == NULL,
1788 ("insmntque: vnode already on per mount vnode list"));
1789 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1790 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1793 * We acquire the vnode interlock early to ensure that the
1794 * vnode cannot be recycled by another process releasing a
1795 * holdcnt on it before we get it on both the vnode list
1796 * and the active vnode list. The mount mutex protects only
1797 * manipulation of the vnode list and the vnode freelist
1798 * mutex protects only manipulation of the active vnode list.
1799 * Hence the need to hold the vnode interlock throughout.
1803 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1804 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1805 mp->mnt_nvnodelistsize == 0)) &&
1806 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1815 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1816 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1817 ("neg mount point vnode list size"));
1818 mp->mnt_nvnodelistsize++;
1825 insmntque(struct vnode *vp, struct mount *mp)
1828 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1832 * Flush out and invalidate all buffers associated with a bufobj
1833 * Called with the underlying object locked.
1836 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1841 if (flags & V_SAVE) {
1842 error = bufobj_wwait(bo, slpflag, slptimeo);
1847 if (bo->bo_dirty.bv_cnt > 0) {
1849 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1852 * XXX We could save a lock/unlock if this was only
1853 * enabled under INVARIANTS
1856 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1857 panic("vinvalbuf: dirty bufs");
1861 * If you alter this loop please notice that interlock is dropped and
1862 * reacquired in flushbuflist. Special care is needed to ensure that
1863 * no race conditions occur from this.
1866 error = flushbuflist(&bo->bo_clean,
1867 flags, bo, slpflag, slptimeo);
1868 if (error == 0 && !(flags & V_CLEANONLY))
1869 error = flushbuflist(&bo->bo_dirty,
1870 flags, bo, slpflag, slptimeo);
1871 if (error != 0 && error != EAGAIN) {
1875 } while (error != 0);
1878 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1879 * have write I/O in-progress but if there is a VM object then the
1880 * VM object can also have read-I/O in-progress.
1883 bufobj_wwait(bo, 0, 0);
1884 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
1886 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
1889 } while (bo->bo_numoutput > 0);
1893 * Destroy the copy in the VM cache, too.
1895 if (bo->bo_object != NULL &&
1896 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1897 VM_OBJECT_WLOCK(bo->bo_object);
1898 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1899 OBJPR_CLEANONLY : 0);
1900 VM_OBJECT_WUNLOCK(bo->bo_object);
1905 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1906 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1907 bo->bo_clean.bv_cnt > 0))
1908 panic("vinvalbuf: flush failed");
1909 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1910 bo->bo_dirty.bv_cnt > 0)
1911 panic("vinvalbuf: flush dirty failed");
1918 * Flush out and invalidate all buffers associated with a vnode.
1919 * Called with the underlying object locked.
1922 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1925 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1926 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1927 if (vp->v_object != NULL && vp->v_object->handle != vp)
1929 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1933 * Flush out buffers on the specified list.
1937 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1940 struct buf *bp, *nbp;
1945 ASSERT_BO_WLOCKED(bo);
1948 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1950 * If we are flushing both V_NORMAL and V_ALT buffers then
1951 * do not skip any buffers. If we are flushing only V_NORMAL
1952 * buffers then skip buffers marked as BX_ALTDATA. If we are
1953 * flushing only V_ALT buffers then skip buffers not marked
1956 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
1957 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
1958 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
1962 lblkno = nbp->b_lblkno;
1963 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
1966 error = BUF_TIMELOCK(bp,
1967 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
1968 "flushbuf", slpflag, slptimeo);
1971 return (error != ENOLCK ? error : EAGAIN);
1973 KASSERT(bp->b_bufobj == bo,
1974 ("bp %p wrong b_bufobj %p should be %p",
1975 bp, bp->b_bufobj, bo));
1977 * XXX Since there are no node locks for NFS, I
1978 * believe there is a slight chance that a delayed
1979 * write will occur while sleeping just above, so
1982 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1985 bp->b_flags |= B_ASYNC;
1988 return (EAGAIN); /* XXX: why not loop ? */
1991 bp->b_flags |= (B_INVAL | B_RELBUF);
1992 bp->b_flags &= ~B_ASYNC;
1997 nbp = gbincore(bo, lblkno);
1998 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2000 break; /* nbp invalid */
2006 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2012 ASSERT_BO_LOCKED(bo);
2014 for (lblkno = startn;;) {
2016 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2017 if (bp == NULL || bp->b_lblkno >= endn ||
2018 bp->b_lblkno < startn)
2020 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2021 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2024 if (error == ENOLCK)
2028 KASSERT(bp->b_bufobj == bo,
2029 ("bp %p wrong b_bufobj %p should be %p",
2030 bp, bp->b_bufobj, bo));
2031 lblkno = bp->b_lblkno + 1;
2032 if ((bp->b_flags & B_MANAGED) == 0)
2034 bp->b_flags |= B_RELBUF;
2036 * In the VMIO case, use the B_NOREUSE flag to hint that the
2037 * pages backing each buffer in the range are unlikely to be
2038 * reused. Dirty buffers will have the hint applied once
2039 * they've been written.
2041 if ((bp->b_flags & B_VMIO) != 0)
2042 bp->b_flags |= B_NOREUSE;
2050 * Truncate a file's buffer and pages to a specified length. This
2051 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2055 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2057 struct buf *bp, *nbp;
2061 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2062 vp, blksize, (uintmax_t)length);
2065 * Round up to the *next* lbn.
2067 startlbn = howmany(length, blksize);
2069 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2075 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2080 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2081 if (bp->b_lblkno > 0)
2084 * Since we hold the vnode lock this should only
2085 * fail if we're racing with the buf daemon.
2088 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2089 BO_LOCKPTR(bo)) == ENOLCK)
2090 goto restart_unlocked;
2092 VNASSERT((bp->b_flags & B_DELWRI), vp,
2093 ("buf(%p) on dirty queue without DELWRI", bp));
2102 bufobj_wwait(bo, 0, 0);
2104 vnode_pager_setsize(vp, length);
2110 * Invalidate the cached pages of a file's buffer within the range of block
2111 * numbers [startlbn, endlbn).
2114 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2120 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2122 start = blksize * startlbn;
2123 end = blksize * endlbn;
2127 MPASS(blksize == bo->bo_bsize);
2129 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2133 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2137 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2138 daddr_t startlbn, daddr_t endlbn)
2140 struct buf *bp, *nbp;
2143 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2144 ASSERT_BO_LOCKED(bo);
2148 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2149 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2152 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2153 BO_LOCKPTR(bo)) == ENOLCK) {
2159 bp->b_flags |= B_INVAL | B_RELBUF;
2160 bp->b_flags &= ~B_ASYNC;
2166 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2168 (nbp->b_flags & B_DELWRI) != 0))
2172 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2173 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2176 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2177 BO_LOCKPTR(bo)) == ENOLCK) {
2182 bp->b_flags |= B_INVAL | B_RELBUF;
2183 bp->b_flags &= ~B_ASYNC;
2189 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2190 (nbp->b_vp != vp) ||
2191 (nbp->b_flags & B_DELWRI) == 0))
2199 buf_vlist_remove(struct buf *bp)
2203 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2204 ASSERT_BO_WLOCKED(bp->b_bufobj);
2205 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
2206 (BX_VNDIRTY|BX_VNCLEAN),
2207 ("buf_vlist_remove: Buf %p is on two lists", bp));
2208 if (bp->b_xflags & BX_VNDIRTY)
2209 bv = &bp->b_bufobj->bo_dirty;
2211 bv = &bp->b_bufobj->bo_clean;
2212 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2213 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2215 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2219 * Add the buffer to the sorted clean or dirty block list.
2221 * NOTE: xflags is passed as a constant, optimizing this inline function!
2224 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2230 ASSERT_BO_WLOCKED(bo);
2231 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2232 ("dead bo %p", bo));
2233 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2234 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2235 bp->b_xflags |= xflags;
2236 if (xflags & BX_VNDIRTY)
2242 * Keep the list ordered. Optimize empty list insertion. Assume
2243 * we tend to grow at the tail so lookup_le should usually be cheaper
2246 if (bv->bv_cnt == 0 ||
2247 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2248 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2249 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2250 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2252 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2253 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2255 panic("buf_vlist_add: Preallocated nodes insufficient.");
2260 * Look up a buffer using the buffer tries.
2263 gbincore(struct bufobj *bo, daddr_t lblkno)
2267 ASSERT_BO_LOCKED(bo);
2268 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2271 return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
2275 * Associate a buffer with a vnode.
2278 bgetvp(struct vnode *vp, struct buf *bp)
2283 ASSERT_BO_WLOCKED(bo);
2284 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2286 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2287 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2288 ("bgetvp: bp already attached! %p", bp));
2294 * Insert onto list for new vnode.
2296 buf_vlist_add(bp, bo, BX_VNCLEAN);
2300 * Disassociate a buffer from a vnode.
2303 brelvp(struct buf *bp)
2308 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2309 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2312 * Delete from old vnode list, if on one.
2314 vp = bp->b_vp; /* XXX */
2317 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2318 buf_vlist_remove(bp);
2320 panic("brelvp: Buffer %p not on queue.", bp);
2321 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2322 bo->bo_flag &= ~BO_ONWORKLST;
2323 mtx_lock(&sync_mtx);
2324 LIST_REMOVE(bo, bo_synclist);
2325 syncer_worklist_len--;
2326 mtx_unlock(&sync_mtx);
2329 bp->b_bufobj = NULL;
2335 * Add an item to the syncer work queue.
2338 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2342 ASSERT_BO_WLOCKED(bo);
2344 mtx_lock(&sync_mtx);
2345 if (bo->bo_flag & BO_ONWORKLST)
2346 LIST_REMOVE(bo, bo_synclist);
2348 bo->bo_flag |= BO_ONWORKLST;
2349 syncer_worklist_len++;
2352 if (delay > syncer_maxdelay - 2)
2353 delay = syncer_maxdelay - 2;
2354 slot = (syncer_delayno + delay) & syncer_mask;
2356 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2357 mtx_unlock(&sync_mtx);
2361 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2365 mtx_lock(&sync_mtx);
2366 len = syncer_worklist_len - sync_vnode_count;
2367 mtx_unlock(&sync_mtx);
2368 error = SYSCTL_OUT(req, &len, sizeof(len));
2372 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2373 CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2374 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2376 static struct proc *updateproc;
2377 static void sched_sync(void);
2378 static struct kproc_desc up_kp = {
2383 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2386 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2391 *bo = LIST_FIRST(slp);
2395 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2398 * We use vhold in case the vnode does not
2399 * successfully sync. vhold prevents the vnode from
2400 * going away when we unlock the sync_mtx so that
2401 * we can acquire the vnode interlock.
2404 mtx_unlock(&sync_mtx);
2406 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2408 mtx_lock(&sync_mtx);
2409 return (*bo == LIST_FIRST(slp));
2411 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2412 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2414 vn_finished_write(mp);
2416 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2418 * Put us back on the worklist. The worklist
2419 * routine will remove us from our current
2420 * position and then add us back in at a later
2423 vn_syncer_add_to_worklist(*bo, syncdelay);
2427 mtx_lock(&sync_mtx);
2431 static int first_printf = 1;
2434 * System filesystem synchronizer daemon.
2439 struct synclist *next, *slp;
2442 struct thread *td = curthread;
2444 int net_worklist_len;
2445 int syncer_final_iter;
2449 syncer_final_iter = 0;
2450 syncer_state = SYNCER_RUNNING;
2451 starttime = time_uptime;
2452 td->td_pflags |= TDP_NORUNNINGBUF;
2454 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2457 mtx_lock(&sync_mtx);
2459 if (syncer_state == SYNCER_FINAL_DELAY &&
2460 syncer_final_iter == 0) {
2461 mtx_unlock(&sync_mtx);
2462 kproc_suspend_check(td->td_proc);
2463 mtx_lock(&sync_mtx);
2465 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2466 if (syncer_state != SYNCER_RUNNING &&
2467 starttime != time_uptime) {
2469 printf("\nSyncing disks, vnodes remaining... ");
2472 printf("%d ", net_worklist_len);
2474 starttime = time_uptime;
2477 * Push files whose dirty time has expired. Be careful
2478 * of interrupt race on slp queue.
2480 * Skip over empty worklist slots when shutting down.
2483 slp = &syncer_workitem_pending[syncer_delayno];
2484 syncer_delayno += 1;
2485 if (syncer_delayno == syncer_maxdelay)
2487 next = &syncer_workitem_pending[syncer_delayno];
2489 * If the worklist has wrapped since the
2490 * it was emptied of all but syncer vnodes,
2491 * switch to the FINAL_DELAY state and run
2492 * for one more second.
2494 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2495 net_worklist_len == 0 &&
2496 last_work_seen == syncer_delayno) {
2497 syncer_state = SYNCER_FINAL_DELAY;
2498 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2500 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2501 syncer_worklist_len > 0);
2504 * Keep track of the last time there was anything
2505 * on the worklist other than syncer vnodes.
2506 * Return to the SHUTTING_DOWN state if any
2509 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2510 last_work_seen = syncer_delayno;
2511 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2512 syncer_state = SYNCER_SHUTTING_DOWN;
2513 while (!LIST_EMPTY(slp)) {
2514 error = sync_vnode(slp, &bo, td);
2516 LIST_REMOVE(bo, bo_synclist);
2517 LIST_INSERT_HEAD(next, bo, bo_synclist);
2521 if (first_printf == 0) {
2523 * Drop the sync mutex, because some watchdog
2524 * drivers need to sleep while patting
2526 mtx_unlock(&sync_mtx);
2527 wdog_kern_pat(WD_LASTVAL);
2528 mtx_lock(&sync_mtx);
2532 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2533 syncer_final_iter--;
2535 * The variable rushjob allows the kernel to speed up the
2536 * processing of the filesystem syncer process. A rushjob
2537 * value of N tells the filesystem syncer to process the next
2538 * N seconds worth of work on its queue ASAP. Currently rushjob
2539 * is used by the soft update code to speed up the filesystem
2540 * syncer process when the incore state is getting so far
2541 * ahead of the disk that the kernel memory pool is being
2542 * threatened with exhaustion.
2549 * Just sleep for a short period of time between
2550 * iterations when shutting down to allow some I/O
2553 * If it has taken us less than a second to process the
2554 * current work, then wait. Otherwise start right over
2555 * again. We can still lose time if any single round
2556 * takes more than two seconds, but it does not really
2557 * matter as we are just trying to generally pace the
2558 * filesystem activity.
2560 if (syncer_state != SYNCER_RUNNING ||
2561 time_uptime == starttime) {
2563 sched_prio(td, PPAUSE);
2566 if (syncer_state != SYNCER_RUNNING)
2567 cv_timedwait(&sync_wakeup, &sync_mtx,
2568 hz / SYNCER_SHUTDOWN_SPEEDUP);
2569 else if (time_uptime == starttime)
2570 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2575 * Request the syncer daemon to speed up its work.
2576 * We never push it to speed up more than half of its
2577 * normal turn time, otherwise it could take over the cpu.
2580 speedup_syncer(void)
2584 mtx_lock(&sync_mtx);
2585 if (rushjob < syncdelay / 2) {
2587 stat_rush_requests += 1;
2590 mtx_unlock(&sync_mtx);
2591 cv_broadcast(&sync_wakeup);
2596 * Tell the syncer to speed up its work and run though its work
2597 * list several times, then tell it to shut down.
2600 syncer_shutdown(void *arg, int howto)
2603 if (howto & RB_NOSYNC)
2605 mtx_lock(&sync_mtx);
2606 syncer_state = SYNCER_SHUTTING_DOWN;
2608 mtx_unlock(&sync_mtx);
2609 cv_broadcast(&sync_wakeup);
2610 kproc_shutdown(arg, howto);
2614 syncer_suspend(void)
2617 syncer_shutdown(updateproc, 0);
2624 mtx_lock(&sync_mtx);
2626 syncer_state = SYNCER_RUNNING;
2627 mtx_unlock(&sync_mtx);
2628 cv_broadcast(&sync_wakeup);
2629 kproc_resume(updateproc);
2633 * Reassign a buffer from one vnode to another.
2634 * Used to assign file specific control information
2635 * (indirect blocks) to the vnode to which they belong.
2638 reassignbuf(struct buf *bp)
2651 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2652 bp, bp->b_vp, bp->b_flags);
2654 * B_PAGING flagged buffers cannot be reassigned because their vp
2655 * is not fully linked in.
2657 if (bp->b_flags & B_PAGING)
2658 panic("cannot reassign paging buffer");
2661 * Delete from old vnode list, if on one.
2664 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2665 buf_vlist_remove(bp);
2667 panic("reassignbuf: Buffer %p not on queue.", bp);
2669 * If dirty, put on list of dirty buffers; otherwise insert onto list
2672 if (bp->b_flags & B_DELWRI) {
2673 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2674 switch (vp->v_type) {
2684 vn_syncer_add_to_worklist(bo, delay);
2686 buf_vlist_add(bp, bo, BX_VNDIRTY);
2688 buf_vlist_add(bp, bo, BX_VNCLEAN);
2690 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2691 mtx_lock(&sync_mtx);
2692 LIST_REMOVE(bo, bo_synclist);
2693 syncer_worklist_len--;
2694 mtx_unlock(&sync_mtx);
2695 bo->bo_flag &= ~BO_ONWORKLST;
2700 bp = TAILQ_FIRST(&bv->bv_hd);
2701 KASSERT(bp == NULL || bp->b_bufobj == bo,
2702 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2703 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2704 KASSERT(bp == NULL || bp->b_bufobj == bo,
2705 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2707 bp = TAILQ_FIRST(&bv->bv_hd);
2708 KASSERT(bp == NULL || bp->b_bufobj == bo,
2709 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2710 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2711 KASSERT(bp == NULL || bp->b_bufobj == bo,
2712 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2718 v_init_counters(struct vnode *vp)
2721 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2722 vp, ("%s called for an initialized vnode", __FUNCTION__));
2723 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2725 refcount_init(&vp->v_holdcnt, 1);
2726 refcount_init(&vp->v_usecount, 1);
2730 * Increment si_usecount of the associated device, if any.
2733 v_incr_devcount(struct vnode *vp)
2736 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2737 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2739 vp->v_rdev->si_usecount++;
2745 * Decrement si_usecount of the associated device, if any.
2748 v_decr_devcount(struct vnode *vp)
2751 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2752 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2754 vp->v_rdev->si_usecount--;
2760 * Grab a particular vnode from the free list, increment its
2761 * reference count and lock it. VIRF_DOOMED is set if the vnode
2762 * is being destroyed. Only callers who specify LK_RETRY will
2763 * see doomed vnodes. If inactive processing was delayed in
2764 * vput try to do it here.
2766 * Both holdcnt and usecount can be manipulated using atomics without holding
2767 * any locks except in these cases which require the vnode interlock:
2768 * holdcnt: 1->0 and 0->1
2771 * usecount is permitted to transition 1->0 without the interlock because
2772 * vnode is kept live by holdcnt.
2774 static enum vgetstate __always_inline
2775 _vget_prep(struct vnode *vp, bool interlock)
2779 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2792 vget_prep(struct vnode *vp)
2795 return (_vget_prep(vp, false));
2799 vget(struct vnode *vp, int flags, struct thread *td)
2803 MPASS(td == curthread);
2805 vs = _vget_prep(vp, (flags & LK_INTERLOCK) != 0);
2806 return (vget_finish(vp, flags, vs));
2810 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
2812 int error, oweinact;
2814 VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2815 ("%s: invalid lock operation", __func__));
2817 if ((flags & LK_INTERLOCK) != 0)
2818 ASSERT_VI_LOCKED(vp, __func__);
2820 ASSERT_VI_UNLOCKED(vp, __func__);
2821 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
2822 if (vs == VGET_USECOUNT) {
2823 VNASSERT(vp->v_usecount > 0, vp,
2824 ("%s: vnode without usecount when VGET_USECOUNT was passed",
2828 if ((error = vn_lock(vp, flags)) != 0) {
2829 if (vs == VGET_USECOUNT)
2833 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2838 if (vs == VGET_USECOUNT) {
2839 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2840 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2845 * We hold the vnode. If the usecount is 0 it will be utilized to keep
2846 * the vnode around. Otherwise someone else lended their hold count and
2847 * we have to drop ours.
2849 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2851 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2852 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2854 refcount_release(&vp->v_holdcnt);
2856 VNODE_REFCOUNT_FENCE_ACQ();
2857 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2858 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2863 * We don't guarantee that any particular close will
2864 * trigger inactive processing so just make a best effort
2865 * here at preventing a reference to a removed file. If
2866 * we don't succeed no harm is done.
2868 * Upgrade our holdcnt to a usecount.
2872 * See the previous section. By the time we get here we may find
2873 * ourselves in the same spot.
2875 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2877 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2878 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2880 refcount_release(&vp->v_holdcnt);
2882 VNODE_REFCOUNT_FENCE_ACQ();
2883 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2884 ("%s: vnode with usecount and VI_OWEINACT set",
2889 if ((vp->v_iflag & VI_OWEINACT) == 0) {
2893 vp->v_iflag &= ~VI_OWEINACT;
2894 VNODE_REFCOUNT_FENCE_REL();
2896 v_incr_devcount(vp);
2897 refcount_acquire(&vp->v_usecount);
2898 if (oweinact && VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2899 (flags & LK_NOWAIT) == 0)
2906 * Increase the reference (use) and hold count of a vnode.
2907 * This will also remove the vnode from the free list if it is presently free.
2910 vref(struct vnode *vp)
2913 ASSERT_VI_UNLOCKED(vp, __func__);
2914 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2915 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2916 VNODE_REFCOUNT_FENCE_ACQ();
2917 VNASSERT(vp->v_holdcnt > 0, vp,
2918 ("%s: active vnode not held", __func__));
2919 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2920 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2929 vrefl(struct vnode *vp)
2932 ASSERT_VI_LOCKED(vp, __func__);
2933 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2934 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2935 VNODE_REFCOUNT_FENCE_ACQ();
2936 VNASSERT(vp->v_holdcnt > 0, vp,
2937 ("%s: active vnode not held", __func__));
2938 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2939 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2943 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);
2952 vrefact(struct vnode *vp)
2955 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2957 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
2958 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
2960 refcount_acquire(&vp->v_usecount);
2965 * Return reference count of a vnode.
2967 * The results of this call are only guaranteed when some mechanism is used to
2968 * stop other processes from gaining references to the vnode. This may be the
2969 * case if the caller holds the only reference. This is also useful when stale
2970 * data is acceptable as race conditions may be accounted for by some other
2974 vrefcnt(struct vnode *vp)
2977 return (vp->v_usecount);
2981 vlazy(struct vnode *vp)
2985 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
2987 if ((vp->v_mflag & VMP_LAZYLIST) != 0)
2990 mtx_lock(&mp->mnt_listmtx);
2991 if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
2992 vp->v_mflag |= VMP_LAZYLIST;
2993 TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
2994 mp->mnt_lazyvnodelistsize++;
2996 mtx_unlock(&mp->mnt_listmtx);
3000 vdefer_inactive(struct vnode *vp)
3003 ASSERT_VI_LOCKED(vp, __func__);
3004 VNASSERT(vp->v_iflag & VI_OWEINACT, vp,
3005 ("%s: vnode without VI_OWEINACT", __func__));
3006 if (VN_IS_DOOMED(vp)) {
3010 if (vp->v_iflag & VI_DEFINACT) {
3011 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3016 vp->v_iflag |= VI_DEFINACT;
3018 counter_u64_add(deferred_inact, 1);
3022 vdefer_inactive_cond(struct vnode *vp)
3026 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
3027 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3031 vdefer_inactive(vp);
3034 enum vputx_op { VPUTX_VRELE, VPUTX_VPUT, VPUTX_VUNREF };
3037 * Decrement the use and hold counts for a vnode.
3039 * See an explanation near vget() as to why atomic operation is safe.
3042 vputx(struct vnode *vp, enum vputx_op func)
3046 KASSERT(vp != NULL, ("vputx: null vp"));
3047 if (func == VPUTX_VUNREF)
3048 ASSERT_VOP_LOCKED(vp, "vunref");
3049 ASSERT_VI_UNLOCKED(vp, __func__);
3050 VNASSERT(vp->v_holdcnt > 0 && vp->v_usecount > 0, vp,
3051 ("%s: wrong ref counts", __func__));
3053 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3056 * We want to hold the vnode until the inactive finishes to
3057 * prevent vgone() races. We drop the use count here and the
3058 * hold count below when we're done.
3060 * If we release the last usecount we take ownership of the hold
3061 * count which provides liveness of the vnode, in which case we
3064 if (!refcount_release(&vp->v_usecount))
3067 v_decr_devcount(vp);
3069 * By the time we got here someone else might have transitioned
3070 * the count back to > 0.
3072 if (vp->v_usecount > 0) {
3076 if (vp->v_iflag & VI_DOINGINACT) {
3082 * Check if the fs wants to perform inactive processing. Note we
3083 * may be only holding the interlock, in which case it is possible
3084 * someone else called vgone on the vnode and ->v_data is now NULL.
3085 * Since vgone performs inactive on its own there is nothing to do
3086 * here but to drop our hold count.
3088 if (__predict_false(VN_IS_DOOMED(vp)) ||
3089 VOP_NEED_INACTIVE(vp) == 0) {
3095 * We must call VOP_INACTIVE with the node locked. Mark
3096 * as VI_DOINGINACT to avoid recursion.
3098 vp->v_iflag |= VI_OWEINACT;
3101 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3105 error = VOP_LOCK(vp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT);
3110 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3111 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3116 VNASSERT(vp->v_usecount == 0 || (vp->v_iflag & VI_OWEINACT) == 0, vp,
3117 ("vnode with usecount and VI_OWEINACT set"));
3119 if (vp->v_iflag & VI_OWEINACT)
3121 if (func != VPUTX_VUNREF)
3124 } else if (vp->v_iflag & VI_OWEINACT) {
3125 vdefer_inactive(vp);
3132 * Vnode put/release.
3133 * If count drops to zero, call inactive routine and return to freelist.
3136 vrele(struct vnode *vp)
3139 vputx(vp, VPUTX_VRELE);
3143 * Release an already locked vnode. This give the same effects as
3144 * unlock+vrele(), but takes less time and avoids releasing and
3145 * re-aquiring the lock (as vrele() acquires the lock internally.)
3147 * It is an invariant that all VOP_* calls operate on a held vnode.
3148 * We may be only having an implicit hold stemming from our usecount,
3149 * which we are about to release. If we unlock the vnode afterwards we
3150 * open a time window where someone else dropped the last usecount and
3151 * proceeded to free the vnode before our unlock finished. For this
3152 * reason we unlock the vnode early. This is a little bit wasteful as
3153 * it may be the vnode is exclusively locked and inactive processing is
3154 * needed, in which case we are adding work.
3157 vput(struct vnode *vp)
3161 vputx(vp, VPUTX_VPUT);
3165 * Release an exclusively locked vnode. Do not unlock the vnode lock.
3168 vunref(struct vnode *vp)
3171 vputx(vp, VPUTX_VUNREF);
3175 * Increase the hold count and activate if this is the first reference.
3178 vhold_activate(struct vnode *vp)
3181 ASSERT_VI_LOCKED(vp, __func__);
3182 VNASSERT(vp->v_holdcnt == 0, vp,
3183 ("%s: wrong hold count", __func__));
3184 VNASSERT(vp->v_op != NULL, vp,
3185 ("%s: vnode already reclaimed.", __func__));
3186 atomic_subtract_long(&freevnodes, 1);
3187 refcount_acquire(&vp->v_holdcnt);
3191 vhold(struct vnode *vp)
3194 ASSERT_VI_UNLOCKED(vp, __func__);
3195 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3196 if (refcount_acquire_if_not_zero(&vp->v_holdcnt))
3204 vholdl(struct vnode *vp)
3207 ASSERT_VI_LOCKED(vp, __func__);
3208 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3209 if (vp->v_holdcnt > 0) {
3210 refcount_acquire(&vp->v_holdcnt);
3217 vholdnz(struct vnode *vp)
3220 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3222 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3223 VNASSERT(old > 0, vp, ("%s: wrong hold count %d", __func__, old));
3225 atomic_add_int(&vp->v_holdcnt, 1);
3229 static void __noinline
3230 vdbatch_process(struct vdbatch *vd)
3235 mtx_assert(&vd->lock, MA_OWNED);
3236 MPASS(vd->index == VDBATCH_SIZE);
3238 mtx_lock(&vnode_list_mtx);
3239 for (i = 0; i < VDBATCH_SIZE; i++) {
3241 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3242 TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3243 MPASS(vp->v_dbatchcpu != NOCPU);
3244 vp->v_dbatchcpu = NOCPU;
3246 bzero(vd->tab, sizeof(vd->tab));
3248 mtx_unlock(&vnode_list_mtx);
3252 vdbatch_enqueue(struct vnode *vp)
3256 ASSERT_VI_LOCKED(vp, __func__);
3257 VNASSERT(!VN_IS_DOOMED(vp), vp,
3258 ("%s: deferring requeue of a doomed vnode", __func__));
3260 if (vp->v_dbatchcpu != NOCPU) {
3266 * A hack: pin us to the current CPU so that we know what to put in
3271 mtx_lock(&vd->lock);
3272 MPASS(vd->index < VDBATCH_SIZE);
3273 MPASS(vd->tab[vd->index] == NULL);
3274 vp->v_dbatchcpu = curcpu;
3275 vd->tab[vd->index] = vp;
3278 if (vd->index == VDBATCH_SIZE)
3279 vdbatch_process(vd);
3280 mtx_unlock(&vd->lock);
3285 * This routine must only be called for vnodes which are about to be
3286 * deallocated. Supporting dequeue for arbitrary vndoes would require
3287 * validating that the locked batch matches.
3290 vdbatch_dequeue(struct vnode *vp)
3296 VNASSERT(vp->v_type == VBAD || vp->v_type == VNON, vp,
3297 ("%s: called for a used vnode\n", __func__));
3299 cpu = vp->v_dbatchcpu;
3303 vd = DPCPU_ID_PTR(cpu, vd);
3304 mtx_lock(&vd->lock);
3305 for (i = 0; i < vd->index; i++) {
3306 if (vd->tab[i] != vp)
3308 vp->v_dbatchcpu = NOCPU;
3310 vd->tab[i] = vd->tab[vd->index];
3311 vd->tab[vd->index] = NULL;
3314 mtx_unlock(&vd->lock);
3316 * Either we dequeued the vnode above or the target CPU beat us to it.
3318 MPASS(vp->v_dbatchcpu == NOCPU);
3322 * Drop the hold count of the vnode. If this is the last reference to
3323 * the vnode we place it on the free list unless it has been vgone'd
3324 * (marked VIRF_DOOMED) in which case we will free it.
3326 * Because the vnode vm object keeps a hold reference on the vnode if
3327 * there is at least one resident non-cached page, the vnode cannot
3328 * leave the active list without the page cleanup done.
3331 vdrop_deactivate(struct vnode *vp)
3335 ASSERT_VI_LOCKED(vp, __func__);
3337 * Mark a vnode as free: remove it from its active list
3338 * and put it up for recycling on the freelist.
3340 VNASSERT(!VN_IS_DOOMED(vp), vp,
3341 ("vdrop: returning doomed vnode"));
3342 VNASSERT(vp->v_op != NULL, vp,
3343 ("vdrop: vnode already reclaimed."));
3344 VNASSERT(vp->v_holdcnt == 0, vp,
3345 ("vdrop: freeing when we shouldn't"));
3346 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
3347 ("vnode with VI_OWEINACT set"));
3348 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp,
3349 ("vnode with VI_DEFINACT set"));
3350 if (vp->v_mflag & VMP_LAZYLIST) {
3352 mtx_lock(&mp->mnt_listmtx);
3353 vp->v_mflag &= ~VMP_LAZYLIST;
3354 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3355 mp->mnt_lazyvnodelistsize--;
3356 mtx_unlock(&mp->mnt_listmtx);
3358 atomic_add_long(&freevnodes, 1);
3359 vdbatch_enqueue(vp);
3363 vdrop(struct vnode *vp)
3366 ASSERT_VI_UNLOCKED(vp, __func__);
3367 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3368 if (refcount_release_if_not_last(&vp->v_holdcnt))
3375 vdropl(struct vnode *vp)
3378 ASSERT_VI_LOCKED(vp, __func__);
3379 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3380 if (!refcount_release(&vp->v_holdcnt)) {
3384 if (VN_IS_DOOMED(vp)) {
3388 vdrop_deactivate(vp);
3392 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3393 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3394 * OWEINACT tracks whether a vnode missed a call to inactive due to a
3395 * failed lock upgrade.
3398 vinactive(struct vnode *vp)
3400 struct vm_object *obj;
3402 ASSERT_VOP_ELOCKED(vp, "vinactive");
3403 ASSERT_VI_LOCKED(vp, "vinactive");
3404 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3405 ("vinactive: recursed on VI_DOINGINACT"));
3406 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3407 vp->v_iflag |= VI_DOINGINACT;
3408 vp->v_iflag &= ~VI_OWEINACT;
3411 * Before moving off the active list, we must be sure that any
3412 * modified pages are converted into the vnode's dirty
3413 * buffers, since these will no longer be checked once the
3414 * vnode is on the inactive list.
3416 * The write-out of the dirty pages is asynchronous. At the
3417 * point that VOP_INACTIVE() is called, there could still be
3418 * pending I/O and dirty pages in the object.
3420 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3421 vm_object_mightbedirty(obj)) {
3422 VM_OBJECT_WLOCK(obj);
3423 vm_object_page_clean(obj, 0, 0, 0);
3424 VM_OBJECT_WUNLOCK(obj);
3426 VOP_INACTIVE(vp, curthread);
3428 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3429 ("vinactive: lost VI_DOINGINACT"));
3430 vp->v_iflag &= ~VI_DOINGINACT;
3434 * Remove any vnodes in the vnode table belonging to mount point mp.
3436 * If FORCECLOSE is not specified, there should not be any active ones,
3437 * return error if any are found (nb: this is a user error, not a
3438 * system error). If FORCECLOSE is specified, detach any active vnodes
3441 * If WRITECLOSE is set, only flush out regular file vnodes open for
3444 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3446 * `rootrefs' specifies the base reference count for the root vnode
3447 * of this filesystem. The root vnode is considered busy if its
3448 * v_usecount exceeds this value. On a successful return, vflush(, td)
3449 * will call vrele() on the root vnode exactly rootrefs times.
3450 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3454 static int busyprt = 0; /* print out busy vnodes */
3455 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3459 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3461 struct vnode *vp, *mvp, *rootvp = NULL;
3463 int busy = 0, error;
3465 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3468 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3469 ("vflush: bad args"));
3471 * Get the filesystem root vnode. We can vput() it
3472 * immediately, since with rootrefs > 0, it won't go away.
3474 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3475 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3482 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3484 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3487 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3491 * Skip over a vnodes marked VV_SYSTEM.
3493 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3499 * If WRITECLOSE is set, flush out unlinked but still open
3500 * files (even if open only for reading) and regular file
3501 * vnodes open for writing.
3503 if (flags & WRITECLOSE) {
3504 if (vp->v_object != NULL) {
3505 VM_OBJECT_WLOCK(vp->v_object);
3506 vm_object_page_clean(vp->v_object, 0, 0, 0);
3507 VM_OBJECT_WUNLOCK(vp->v_object);
3509 error = VOP_FSYNC(vp, MNT_WAIT, td);
3513 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3516 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3519 if ((vp->v_type == VNON ||
3520 (error == 0 && vattr.va_nlink > 0)) &&
3521 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3529 * With v_usecount == 0, all we need to do is clear out the
3530 * vnode data structures and we are done.
3532 * If FORCECLOSE is set, forcibly close the vnode.
3534 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3540 vn_printf(vp, "vflush: busy vnode ");
3546 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3548 * If just the root vnode is busy, and if its refcount
3549 * is equal to `rootrefs', then go ahead and kill it.
3552 KASSERT(busy > 0, ("vflush: not busy"));
3553 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3554 ("vflush: usecount %d < rootrefs %d",
3555 rootvp->v_usecount, rootrefs));
3556 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3557 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3565 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3569 for (; rootrefs > 0; rootrefs--)
3575 * Recycle an unused vnode to the front of the free list.
3578 vrecycle(struct vnode *vp)
3583 recycled = vrecyclel(vp);
3589 * vrecycle, with the vp interlock held.
3592 vrecyclel(struct vnode *vp)
3596 ASSERT_VOP_ELOCKED(vp, __func__);
3597 ASSERT_VI_LOCKED(vp, __func__);
3598 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3600 if (vp->v_usecount == 0) {
3608 * Eliminate all activity associated with a vnode
3609 * in preparation for reuse.
3612 vgone(struct vnode *vp)
3620 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3621 struct vnode *lowervp __unused)
3626 * Notify upper mounts about reclaimed or unlinked vnode.
3629 vfs_notify_upper(struct vnode *vp, int event)
3631 static struct vfsops vgonel_vfsops = {
3632 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3633 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3635 struct mount *mp, *ump, *mmp;
3640 if (TAILQ_EMPTY(&mp->mnt_uppers))
3643 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3644 mmp->mnt_op = &vgonel_vfsops;
3645 mmp->mnt_kern_flag |= MNTK_MARKER;
3647 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3648 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3649 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3650 ump = TAILQ_NEXT(ump, mnt_upper_link);
3653 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3656 case VFS_NOTIFY_UPPER_RECLAIM:
3657 VFS_RECLAIM_LOWERVP(ump, vp);
3659 case VFS_NOTIFY_UPPER_UNLINK:
3660 VFS_UNLINK_LOWERVP(ump, vp);
3663 KASSERT(0, ("invalid event %d", event));
3667 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3668 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3671 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3672 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3673 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3674 wakeup(&mp->mnt_uppers);
3680 * vgone, with the vp interlock held.
3683 vgonel(struct vnode *vp)
3688 bool active, oweinact;
3690 ASSERT_VOP_ELOCKED(vp, "vgonel");
3691 ASSERT_VI_LOCKED(vp, "vgonel");
3692 VNASSERT(vp->v_holdcnt, vp,
3693 ("vgonel: vp %p has no reference.", vp));
3694 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3698 * Don't vgonel if we're already doomed.
3700 if (vp->v_irflag & VIRF_DOOMED)
3702 vp->v_irflag |= VIRF_DOOMED;
3705 * Check to see if the vnode is in use. If so, we have to call
3706 * VOP_CLOSE() and VOP_INACTIVE().
3708 active = vp->v_usecount > 0;
3709 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
3711 * If we need to do inactive VI_OWEINACT will be set.
3713 if (vp->v_iflag & VI_DEFINACT) {
3714 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3715 vp->v_iflag &= ~VI_DEFINACT;
3718 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
3721 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
3724 * If purging an active vnode, it must be closed and
3725 * deactivated before being reclaimed.
3728 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
3729 if (oweinact || active) {
3731 if ((vp->v_iflag & VI_DOINGINACT) == 0)
3735 if (vp->v_type == VSOCK)
3736 vfs_unp_reclaim(vp);
3739 * Clean out any buffers associated with the vnode.
3740 * If the flush fails, just toss the buffers.
3743 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
3744 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
3745 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
3746 while (vinvalbuf(vp, 0, 0, 0) != 0)
3750 BO_LOCK(&vp->v_bufobj);
3751 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
3752 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
3753 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
3754 vp->v_bufobj.bo_clean.bv_cnt == 0,
3755 ("vp %p bufobj not invalidated", vp));
3758 * For VMIO bufobj, BO_DEAD is set later, or in
3759 * vm_object_terminate() after the object's page queue is
3762 object = vp->v_bufobj.bo_object;
3764 vp->v_bufobj.bo_flag |= BO_DEAD;
3765 BO_UNLOCK(&vp->v_bufobj);
3768 * Handle the VM part. Tmpfs handles v_object on its own (the
3769 * OBJT_VNODE check). Nullfs or other bypassing filesystems
3770 * should not touch the object borrowed from the lower vnode
3771 * (the handle check).
3773 if (object != NULL && object->type == OBJT_VNODE &&
3774 object->handle == vp)
3775 vnode_destroy_vobject(vp);
3778 * Reclaim the vnode.
3780 if (VOP_RECLAIM(vp, td))
3781 panic("vgone: cannot reclaim");
3783 vn_finished_secondary_write(mp);
3784 VNASSERT(vp->v_object == NULL, vp,
3785 ("vop_reclaim left v_object vp=%p", vp));
3787 * Clear the advisory locks and wake up waiting threads.
3789 (void)VOP_ADVLOCKPURGE(vp);
3792 * Delete from old mount point vnode list.
3797 * Done with purge, reset to the standard lock and invalidate
3801 vp->v_vnlock = &vp->v_lock;
3802 vp->v_op = &dead_vnodeops;
3807 * Calculate the total number of references to a special device.
3810 vcount(struct vnode *vp)
3815 count = vp->v_rdev->si_usecount;
3821 * Print out a description of a vnode.
3823 static char *typename[] =
3824 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
3828 vn_printf(struct vnode *vp, const char *fmt, ...)
3831 char buf[256], buf2[16];
3837 printf("%p: ", (void *)vp);
3838 printf("type %s\n", typename[vp->v_type]);
3839 printf(" usecount %d, writecount %d, refcount %d",
3840 vp->v_usecount, vp->v_writecount, vp->v_holdcnt);
3841 switch (vp->v_type) {
3843 printf(" mountedhere %p\n", vp->v_mountedhere);
3846 printf(" rdev %p\n", vp->v_rdev);
3849 printf(" socket %p\n", vp->v_unpcb);
3852 printf(" fifoinfo %p\n", vp->v_fifoinfo);
3860 if (vp->v_irflag & VIRF_DOOMED)
3861 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
3862 flags = vp->v_irflag & ~(VIRF_DOOMED);
3864 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
3865 strlcat(buf, buf2, sizeof(buf));
3867 if (vp->v_vflag & VV_ROOT)
3868 strlcat(buf, "|VV_ROOT", sizeof(buf));
3869 if (vp->v_vflag & VV_ISTTY)
3870 strlcat(buf, "|VV_ISTTY", sizeof(buf));
3871 if (vp->v_vflag & VV_NOSYNC)
3872 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
3873 if (vp->v_vflag & VV_ETERNALDEV)
3874 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
3875 if (vp->v_vflag & VV_CACHEDLABEL)
3876 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
3877 if (vp->v_vflag & VV_VMSIZEVNLOCK)
3878 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
3879 if (vp->v_vflag & VV_COPYONWRITE)
3880 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
3881 if (vp->v_vflag & VV_SYSTEM)
3882 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
3883 if (vp->v_vflag & VV_PROCDEP)
3884 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
3885 if (vp->v_vflag & VV_NOKNOTE)
3886 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
3887 if (vp->v_vflag & VV_DELETED)
3888 strlcat(buf, "|VV_DELETED", sizeof(buf));
3889 if (vp->v_vflag & VV_MD)
3890 strlcat(buf, "|VV_MD", sizeof(buf));
3891 if (vp->v_vflag & VV_FORCEINSMQ)
3892 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
3893 if (vp->v_vflag & VV_READLINK)
3894 strlcat(buf, "|VV_READLINK", sizeof(buf));
3895 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
3896 VV_CACHEDLABEL | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
3897 VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
3899 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
3900 strlcat(buf, buf2, sizeof(buf));
3902 if (vp->v_iflag & VI_TEXT_REF)
3903 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
3904 if (vp->v_iflag & VI_MOUNT)
3905 strlcat(buf, "|VI_MOUNT", sizeof(buf));
3906 if (vp->v_iflag & VI_DOINGINACT)
3907 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
3908 if (vp->v_iflag & VI_OWEINACT)
3909 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
3910 if (vp->v_iflag & VI_DEFINACT)
3911 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
3912 flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOINGINACT |
3913 VI_OWEINACT | VI_DEFINACT);
3915 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
3916 strlcat(buf, buf2, sizeof(buf));
3918 if (vp->v_mflag & VMP_LAZYLIST)
3919 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
3920 flags = vp->v_mflag & ~(VMP_LAZYLIST);
3922 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
3923 strlcat(buf, buf2, sizeof(buf));
3925 printf(" flags (%s)\n", buf + 1);
3926 if (mtx_owned(VI_MTX(vp)))
3927 printf(" VI_LOCKed");
3928 if (vp->v_object != NULL)
3929 printf(" v_object %p ref %d pages %d "
3930 "cleanbuf %d dirtybuf %d\n",
3931 vp->v_object, vp->v_object->ref_count,
3932 vp->v_object->resident_page_count,
3933 vp->v_bufobj.bo_clean.bv_cnt,
3934 vp->v_bufobj.bo_dirty.bv_cnt);
3936 lockmgr_printinfo(vp->v_vnlock);
3937 if (vp->v_data != NULL)
3943 * List all of the locked vnodes in the system.
3944 * Called when debugging the kernel.
3946 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
3952 * Note: because this is DDB, we can't obey the locking semantics
3953 * for these structures, which means we could catch an inconsistent
3954 * state and dereference a nasty pointer. Not much to be done
3957 db_printf("Locked vnodes\n");
3958 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3959 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3960 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
3961 vn_printf(vp, "vnode ");
3967 * Show details about the given vnode.
3969 DB_SHOW_COMMAND(vnode, db_show_vnode)
3975 vp = (struct vnode *)addr;
3976 vn_printf(vp, "vnode ");
3980 * Show details about the given mount point.
3982 DB_SHOW_COMMAND(mount, db_show_mount)
3993 /* No address given, print short info about all mount points. */
3994 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3995 db_printf("%p %s on %s (%s)\n", mp,
3996 mp->mnt_stat.f_mntfromname,
3997 mp->mnt_stat.f_mntonname,
3998 mp->mnt_stat.f_fstypename);
4002 db_printf("\nMore info: show mount <addr>\n");
4006 mp = (struct mount *)addr;
4007 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4008 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4011 mflags = mp->mnt_flag;
4012 #define MNT_FLAG(flag) do { \
4013 if (mflags & (flag)) { \
4014 if (buf[0] != '\0') \
4015 strlcat(buf, ", ", sizeof(buf)); \
4016 strlcat(buf, (#flag) + 4, sizeof(buf)); \
4017 mflags &= ~(flag); \
4020 MNT_FLAG(MNT_RDONLY);
4021 MNT_FLAG(MNT_SYNCHRONOUS);
4022 MNT_FLAG(MNT_NOEXEC);
4023 MNT_FLAG(MNT_NOSUID);
4024 MNT_FLAG(MNT_NFS4ACLS);
4025 MNT_FLAG(MNT_UNION);
4026 MNT_FLAG(MNT_ASYNC);
4027 MNT_FLAG(MNT_SUIDDIR);
4028 MNT_FLAG(MNT_SOFTDEP);
4029 MNT_FLAG(MNT_NOSYMFOLLOW);
4030 MNT_FLAG(MNT_GJOURNAL);
4031 MNT_FLAG(MNT_MULTILABEL);
4033 MNT_FLAG(MNT_NOATIME);
4034 MNT_FLAG(MNT_NOCLUSTERR);
4035 MNT_FLAG(MNT_NOCLUSTERW);
4037 MNT_FLAG(MNT_EXRDONLY);
4038 MNT_FLAG(MNT_EXPORTED);
4039 MNT_FLAG(MNT_DEFEXPORTED);
4040 MNT_FLAG(MNT_EXPORTANON);
4041 MNT_FLAG(MNT_EXKERB);
4042 MNT_FLAG(MNT_EXPUBLIC);
4043 MNT_FLAG(MNT_LOCAL);
4044 MNT_FLAG(MNT_QUOTA);
4045 MNT_FLAG(MNT_ROOTFS);
4047 MNT_FLAG(MNT_IGNORE);
4048 MNT_FLAG(MNT_UPDATE);
4049 MNT_FLAG(MNT_DELEXPORT);
4050 MNT_FLAG(MNT_RELOAD);
4051 MNT_FLAG(MNT_FORCE);
4052 MNT_FLAG(MNT_SNAPSHOT);
4053 MNT_FLAG(MNT_BYFSID);
4057 strlcat(buf, ", ", sizeof(buf));
4058 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4059 "0x%016jx", mflags);
4061 db_printf(" mnt_flag = %s\n", buf);
4064 flags = mp->mnt_kern_flag;
4065 #define MNT_KERN_FLAG(flag) do { \
4066 if (flags & (flag)) { \
4067 if (buf[0] != '\0') \
4068 strlcat(buf, ", ", sizeof(buf)); \
4069 strlcat(buf, (#flag) + 5, sizeof(buf)); \
4073 MNT_KERN_FLAG(MNTK_UNMOUNTF);
4074 MNT_KERN_FLAG(MNTK_ASYNC);
4075 MNT_KERN_FLAG(MNTK_SOFTDEP);
4076 MNT_KERN_FLAG(MNTK_DRAINING);
4077 MNT_KERN_FLAG(MNTK_REFEXPIRE);
4078 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4079 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4080 MNT_KERN_FLAG(MNTK_NO_IOPF);
4081 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4082 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4083 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4084 MNT_KERN_FLAG(MNTK_MARKER);
4085 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4086 MNT_KERN_FLAG(MNTK_NOASYNC);
4087 MNT_KERN_FLAG(MNTK_UNMOUNT);
4088 MNT_KERN_FLAG(MNTK_MWAIT);
4089 MNT_KERN_FLAG(MNTK_SUSPEND);
4090 MNT_KERN_FLAG(MNTK_SUSPEND2);
4091 MNT_KERN_FLAG(MNTK_SUSPENDED);
4092 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4093 MNT_KERN_FLAG(MNTK_NOKNOTE);
4094 #undef MNT_KERN_FLAG
4097 strlcat(buf, ", ", sizeof(buf));
4098 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4101 db_printf(" mnt_kern_flag = %s\n", buf);
4103 db_printf(" mnt_opt = ");
4104 opt = TAILQ_FIRST(mp->mnt_opt);
4106 db_printf("%s", opt->name);
4107 opt = TAILQ_NEXT(opt, link);
4108 while (opt != NULL) {
4109 db_printf(", %s", opt->name);
4110 opt = TAILQ_NEXT(opt, link);
4116 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4117 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4118 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4119 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4120 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4121 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4122 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4123 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4124 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4125 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4126 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4127 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4129 db_printf(" mnt_cred = { uid=%u ruid=%u",
4130 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4131 if (jailed(mp->mnt_cred))
4132 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4134 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4135 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4136 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4137 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4138 db_printf(" mnt_lazyvnodelistsize = %d\n",
4139 mp->mnt_lazyvnodelistsize);
4140 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4141 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4142 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
4143 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4144 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4145 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4146 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4147 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4148 db_printf(" mnt_secondary_accwrites = %d\n",
4149 mp->mnt_secondary_accwrites);
4150 db_printf(" mnt_gjprovider = %s\n",
4151 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4152 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4154 db_printf("\n\nList of active vnodes\n");
4155 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4156 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4157 vn_printf(vp, "vnode ");
4162 db_printf("\n\nList of inactive vnodes\n");
4163 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4164 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4165 vn_printf(vp, "vnode ");
4174 * Fill in a struct xvfsconf based on a struct vfsconf.
4177 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4179 struct xvfsconf xvfsp;
4181 bzero(&xvfsp, sizeof(xvfsp));
4182 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4183 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4184 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4185 xvfsp.vfc_flags = vfsp->vfc_flags;
4187 * These are unused in userland, we keep them
4188 * to not break binary compatibility.
4190 xvfsp.vfc_vfsops = NULL;
4191 xvfsp.vfc_next = NULL;
4192 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4195 #ifdef COMPAT_FREEBSD32
4197 uint32_t vfc_vfsops;
4198 char vfc_name[MFSNAMELEN];
4199 int32_t vfc_typenum;
4200 int32_t vfc_refcount;
4206 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4208 struct xvfsconf32 xvfsp;
4210 bzero(&xvfsp, sizeof(xvfsp));
4211 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4212 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4213 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4214 xvfsp.vfc_flags = vfsp->vfc_flags;
4215 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4220 * Top level filesystem related information gathering.
4223 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4225 struct vfsconf *vfsp;
4230 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4231 #ifdef COMPAT_FREEBSD32
4232 if (req->flags & SCTL_MASK32)
4233 error = vfsconf2x32(req, vfsp);
4236 error = vfsconf2x(req, vfsp);
4244 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4245 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4246 "S,xvfsconf", "List of all configured filesystems");
4248 #ifndef BURN_BRIDGES
4249 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4252 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4254 int *name = (int *)arg1 - 1; /* XXX */
4255 u_int namelen = arg2 + 1; /* XXX */
4256 struct vfsconf *vfsp;
4258 log(LOG_WARNING, "userland calling deprecated sysctl, "
4259 "please rebuild world\n");
4261 #if 1 || defined(COMPAT_PRELITE2)
4262 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4264 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4268 case VFS_MAXTYPENUM:
4271 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4274 return (ENOTDIR); /* overloaded */
4276 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4277 if (vfsp->vfc_typenum == name[2])
4282 return (EOPNOTSUPP);
4283 #ifdef COMPAT_FREEBSD32
4284 if (req->flags & SCTL_MASK32)
4285 return (vfsconf2x32(req, vfsp));
4288 return (vfsconf2x(req, vfsp));
4290 return (EOPNOTSUPP);
4293 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4294 CTLFLAG_MPSAFE, vfs_sysctl,
4295 "Generic filesystem");
4297 #if 1 || defined(COMPAT_PRELITE2)
4300 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4303 struct vfsconf *vfsp;
4304 struct ovfsconf ovfs;
4307 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4308 bzero(&ovfs, sizeof(ovfs));
4309 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4310 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4311 ovfs.vfc_index = vfsp->vfc_typenum;
4312 ovfs.vfc_refcount = vfsp->vfc_refcount;
4313 ovfs.vfc_flags = vfsp->vfc_flags;
4314 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4324 #endif /* 1 || COMPAT_PRELITE2 */
4325 #endif /* !BURN_BRIDGES */
4327 #define KINFO_VNODESLOP 10
4330 * Dump vnode list (via sysctl).
4334 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4342 * Stale numvnodes access is not fatal here.
4345 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4347 /* Make an estimate */
4348 return (SYSCTL_OUT(req, 0, len));
4350 error = sysctl_wire_old_buffer(req, 0);
4353 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4355 mtx_lock(&mountlist_mtx);
4356 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4357 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4360 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4364 xvn[n].xv_size = sizeof *xvn;
4365 xvn[n].xv_vnode = vp;
4366 xvn[n].xv_id = 0; /* XXX compat */
4367 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4369 XV_COPY(writecount);
4375 xvn[n].xv_flag = vp->v_vflag;
4377 switch (vp->v_type) {
4384 if (vp->v_rdev == NULL) {
4388 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4391 xvn[n].xv_socket = vp->v_socket;
4394 xvn[n].xv_fifo = vp->v_fifoinfo;
4399 /* shouldn't happen? */
4407 mtx_lock(&mountlist_mtx);
4412 mtx_unlock(&mountlist_mtx);
4414 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4419 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4420 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4425 unmount_or_warn(struct mount *mp)
4429 error = dounmount(mp, MNT_FORCE, curthread);
4431 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4435 printf("%d)\n", error);
4440 * Unmount all filesystems. The list is traversed in reverse order
4441 * of mounting to avoid dependencies.
4444 vfs_unmountall(void)
4446 struct mount *mp, *tmp;
4448 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4451 * Since this only runs when rebooting, it is not interlocked.
4453 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4457 * Forcibly unmounting "/dev" before "/" would prevent clean
4458 * unmount of the latter.
4460 if (mp == rootdevmp)
4463 unmount_or_warn(mp);
4466 if (rootdevmp != NULL)
4467 unmount_or_warn(rootdevmp);
4471 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4474 ASSERT_VI_LOCKED(vp, __func__);
4475 VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4476 if ((vp->v_iflag & VI_OWEINACT) == 0) {
4480 if (vn_lock(vp, lkflags) == 0) {
4482 if ((vp->v_iflag & (VI_OWEINACT | VI_DOINGINACT)) == VI_OWEINACT)
4488 vdefer_inactive_cond(vp);
4492 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4495 return (vp->v_iflag & VI_DEFINACT);
4498 static void __noinline
4499 vfs_periodic_inactive(struct mount *mp, int flags)
4501 struct vnode *vp, *mvp;
4504 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4505 if (flags != MNT_WAIT)
4506 lkflags |= LK_NOWAIT;
4508 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4509 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4513 vp->v_iflag &= ~VI_DEFINACT;
4514 vfs_deferred_inactive(vp, lkflags);
4519 vfs_want_msync(struct vnode *vp)
4521 struct vm_object *obj;
4524 * This test may be performed without any locks held.
4525 * We rely on vm_object's type stability.
4527 if (vp->v_vflag & VV_NOSYNC)
4530 return (obj != NULL && vm_object_mightbedirty(obj));
4534 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4537 if (vp->v_vflag & VV_NOSYNC)
4539 if (vp->v_iflag & VI_DEFINACT)
4541 return (vfs_want_msync(vp));
4544 static void __noinline
4545 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4547 struct vnode *vp, *mvp;
4548 struct vm_object *obj;
4550 int lkflags, objflags;
4555 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4556 if (flags != MNT_WAIT) {
4557 lkflags |= LK_NOWAIT;
4558 objflags = OBJPC_NOSYNC;
4560 objflags = OBJPC_SYNC;
4563 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4565 if (vp->v_iflag & VI_DEFINACT) {
4566 vp->v_iflag &= ~VI_DEFINACT;
4569 if (!vfs_want_msync(vp)) {
4571 vfs_deferred_inactive(vp, lkflags);
4576 if (vget(vp, lkflags, td) == 0) {
4578 if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4579 VM_OBJECT_WLOCK(obj);
4580 vm_object_page_clean(obj, 0, 0, objflags);
4581 VM_OBJECT_WUNLOCK(obj);
4588 vdefer_inactive_cond(vp);
4594 vfs_periodic(struct mount *mp, int flags)
4597 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4599 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4600 vfs_periodic_inactive(mp, flags);
4602 vfs_periodic_msync_inactive(mp, flags);
4606 destroy_vpollinfo_free(struct vpollinfo *vi)
4609 knlist_destroy(&vi->vpi_selinfo.si_note);
4610 mtx_destroy(&vi->vpi_lock);
4611 uma_zfree(vnodepoll_zone, vi);
4615 destroy_vpollinfo(struct vpollinfo *vi)
4618 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4619 seldrain(&vi->vpi_selinfo);
4620 destroy_vpollinfo_free(vi);
4624 * Initialize per-vnode helper structure to hold poll-related state.
4627 v_addpollinfo(struct vnode *vp)
4629 struct vpollinfo *vi;
4631 if (vp->v_pollinfo != NULL)
4633 vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4634 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4635 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4636 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4638 if (vp->v_pollinfo != NULL) {
4640 destroy_vpollinfo_free(vi);
4643 vp->v_pollinfo = vi;
4648 * Record a process's interest in events which might happen to
4649 * a vnode. Because poll uses the historic select-style interface
4650 * internally, this routine serves as both the ``check for any
4651 * pending events'' and the ``record my interest in future events''
4652 * functions. (These are done together, while the lock is held,
4653 * to avoid race conditions.)
4656 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4660 mtx_lock(&vp->v_pollinfo->vpi_lock);
4661 if (vp->v_pollinfo->vpi_revents & events) {
4663 * This leaves events we are not interested
4664 * in available for the other process which
4665 * which presumably had requested them
4666 * (otherwise they would never have been
4669 events &= vp->v_pollinfo->vpi_revents;
4670 vp->v_pollinfo->vpi_revents &= ~events;
4672 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4675 vp->v_pollinfo->vpi_events |= events;
4676 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4677 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4682 * Routine to create and manage a filesystem syncer vnode.
4684 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4685 static int sync_fsync(struct vop_fsync_args *);
4686 static int sync_inactive(struct vop_inactive_args *);
4687 static int sync_reclaim(struct vop_reclaim_args *);
4689 static struct vop_vector sync_vnodeops = {
4690 .vop_bypass = VOP_EOPNOTSUPP,
4691 .vop_close = sync_close, /* close */
4692 .vop_fsync = sync_fsync, /* fsync */
4693 .vop_inactive = sync_inactive, /* inactive */
4694 .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
4695 .vop_reclaim = sync_reclaim, /* reclaim */
4696 .vop_lock1 = vop_stdlock, /* lock */
4697 .vop_unlock = vop_stdunlock, /* unlock */
4698 .vop_islocked = vop_stdislocked, /* islocked */
4700 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
4703 * Create a new filesystem syncer vnode for the specified mount point.
4706 vfs_allocate_syncvnode(struct mount *mp)
4710 static long start, incr, next;
4713 /* Allocate a new vnode */
4714 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
4716 panic("vfs_allocate_syncvnode: getnewvnode() failed");
4718 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4719 vp->v_vflag |= VV_FORCEINSMQ;
4720 error = insmntque(vp, mp);
4722 panic("vfs_allocate_syncvnode: insmntque() failed");
4723 vp->v_vflag &= ~VV_FORCEINSMQ;
4726 * Place the vnode onto the syncer worklist. We attempt to
4727 * scatter them about on the list so that they will go off
4728 * at evenly distributed times even if all the filesystems
4729 * are mounted at once.
4732 if (next == 0 || next > syncer_maxdelay) {
4736 start = syncer_maxdelay / 2;
4737 incr = syncer_maxdelay;
4743 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
4744 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
4745 mtx_lock(&sync_mtx);
4747 if (mp->mnt_syncer == NULL) {
4748 mp->mnt_syncer = vp;
4751 mtx_unlock(&sync_mtx);
4754 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4761 vfs_deallocate_syncvnode(struct mount *mp)
4765 mtx_lock(&sync_mtx);
4766 vp = mp->mnt_syncer;
4768 mp->mnt_syncer = NULL;
4769 mtx_unlock(&sync_mtx);
4775 * Do a lazy sync of the filesystem.
4778 sync_fsync(struct vop_fsync_args *ap)
4780 struct vnode *syncvp = ap->a_vp;
4781 struct mount *mp = syncvp->v_mount;
4786 * We only need to do something if this is a lazy evaluation.
4788 if (ap->a_waitfor != MNT_LAZY)
4792 * Move ourselves to the back of the sync list.
4794 bo = &syncvp->v_bufobj;
4796 vn_syncer_add_to_worklist(bo, syncdelay);
4800 * Walk the list of vnodes pushing all that are dirty and
4801 * not already on the sync list.
4803 if (vfs_busy(mp, MBF_NOWAIT) != 0)
4805 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
4809 save = curthread_pflags_set(TDP_SYNCIO);
4811 * The filesystem at hand may be idle with free vnodes stored in the
4812 * batch. Return them instead of letting them stay there indefinitely.
4814 vfs_periodic(mp, MNT_NOWAIT);
4815 error = VFS_SYNC(mp, MNT_LAZY);
4816 curthread_pflags_restore(save);
4817 vn_finished_write(mp);
4823 * The syncer vnode is no referenced.
4826 sync_inactive(struct vop_inactive_args *ap)
4834 * The syncer vnode is no longer needed and is being decommissioned.
4836 * Modifications to the worklist must be protected by sync_mtx.
4839 sync_reclaim(struct vop_reclaim_args *ap)
4841 struct vnode *vp = ap->a_vp;
4846 mtx_lock(&sync_mtx);
4847 if (vp->v_mount->mnt_syncer == vp)
4848 vp->v_mount->mnt_syncer = NULL;
4849 if (bo->bo_flag & BO_ONWORKLST) {
4850 LIST_REMOVE(bo, bo_synclist);
4851 syncer_worklist_len--;
4853 bo->bo_flag &= ~BO_ONWORKLST;
4855 mtx_unlock(&sync_mtx);
4862 vn_need_pageq_flush(struct vnode *vp)
4864 struct vm_object *obj;
4867 MPASS(mtx_owned(VI_MTX(vp)));
4869 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
4870 vm_object_mightbedirty(obj))
4876 * Check if vnode represents a disk device
4879 vn_isdisk(struct vnode *vp, int *errp)
4883 if (vp->v_type != VCHR) {
4889 if (vp->v_rdev == NULL)
4891 else if (vp->v_rdev->si_devsw == NULL)
4893 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
4899 return (error == 0);
4903 * Common filesystem object access control check routine. Accepts a
4904 * vnode's type, "mode", uid and gid, requested access mode, credentials,
4905 * and optional call-by-reference privused argument allowing vaccess()
4906 * to indicate to the caller whether privilege was used to satisfy the
4907 * request (obsoleted). Returns 0 on success, or an errno on failure.
4910 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
4911 accmode_t accmode, struct ucred *cred, int *privused)
4913 accmode_t dac_granted;
4914 accmode_t priv_granted;
4916 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
4917 ("invalid bit in accmode"));
4918 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
4919 ("VAPPEND without VWRITE"));
4922 * Look for a normal, non-privileged way to access the file/directory
4923 * as requested. If it exists, go with that.
4926 if (privused != NULL)
4931 /* Check the owner. */
4932 if (cred->cr_uid == file_uid) {
4933 dac_granted |= VADMIN;
4934 if (file_mode & S_IXUSR)
4935 dac_granted |= VEXEC;
4936 if (file_mode & S_IRUSR)
4937 dac_granted |= VREAD;
4938 if (file_mode & S_IWUSR)
4939 dac_granted |= (VWRITE | VAPPEND);
4941 if ((accmode & dac_granted) == accmode)
4947 /* Otherwise, check the groups (first match) */
4948 if (groupmember(file_gid, cred)) {
4949 if (file_mode & S_IXGRP)
4950 dac_granted |= VEXEC;
4951 if (file_mode & S_IRGRP)
4952 dac_granted |= VREAD;
4953 if (file_mode & S_IWGRP)
4954 dac_granted |= (VWRITE | VAPPEND);
4956 if ((accmode & dac_granted) == accmode)
4962 /* Otherwise, check everyone else. */
4963 if (file_mode & S_IXOTH)
4964 dac_granted |= VEXEC;
4965 if (file_mode & S_IROTH)
4966 dac_granted |= VREAD;
4967 if (file_mode & S_IWOTH)
4968 dac_granted |= (VWRITE | VAPPEND);
4969 if ((accmode & dac_granted) == accmode)
4974 * Build a privilege mask to determine if the set of privileges
4975 * satisfies the requirements when combined with the granted mask
4976 * from above. For each privilege, if the privilege is required,
4977 * bitwise or the request type onto the priv_granted mask.
4983 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
4984 * requests, instead of PRIV_VFS_EXEC.
4986 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4987 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
4988 priv_granted |= VEXEC;
4991 * Ensure that at least one execute bit is on. Otherwise,
4992 * a privileged user will always succeed, and we don't want
4993 * this to happen unless the file really is executable.
4995 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4996 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
4997 !priv_check_cred(cred, PRIV_VFS_EXEC))
4998 priv_granted |= VEXEC;
5001 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5002 !priv_check_cred(cred, PRIV_VFS_READ))
5003 priv_granted |= VREAD;
5005 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5006 !priv_check_cred(cred, PRIV_VFS_WRITE))
5007 priv_granted |= (VWRITE | VAPPEND);
5009 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5010 !priv_check_cred(cred, PRIV_VFS_ADMIN))
5011 priv_granted |= VADMIN;
5013 if ((accmode & (priv_granted | dac_granted)) == accmode) {
5014 /* XXX audit: privilege used */
5015 if (privused != NULL)
5020 return ((accmode & VADMIN) ? EPERM : EACCES);
5024 * Credential check based on process requesting service, and per-attribute
5028 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5029 struct thread *td, accmode_t accmode)
5033 * Kernel-invoked always succeeds.
5039 * Do not allow privileged processes in jail to directly manipulate
5040 * system attributes.
5042 switch (attrnamespace) {
5043 case EXTATTR_NAMESPACE_SYSTEM:
5044 /* Potentially should be: return (EPERM); */
5045 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5046 case EXTATTR_NAMESPACE_USER:
5047 return (VOP_ACCESS(vp, accmode, cred, td));
5053 #ifdef DEBUG_VFS_LOCKS
5055 * This only exists to suppress warnings from unlocked specfs accesses. It is
5056 * no longer ok to have an unlocked VFS.
5058 #define IGNORE_LOCK(vp) (KERNEL_PANICKED() || (vp) == NULL || \
5059 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
5061 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
5062 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5063 "Drop into debugger on lock violation");
5065 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
5066 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5067 0, "Check for interlock across VOPs");
5069 int vfs_badlock_print = 1; /* Print lock violations. */
5070 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5071 0, "Print lock violations");
5073 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
5074 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5075 0, "Print vnode details on lock violations");
5078 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
5079 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5080 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5084 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5088 if (vfs_badlock_backtrace)
5091 if (vfs_badlock_vnode)
5092 vn_printf(vp, "vnode ");
5093 if (vfs_badlock_print)
5094 printf("%s: %p %s\n", str, (void *)vp, msg);
5095 if (vfs_badlock_ddb)
5096 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5100 assert_vi_locked(struct vnode *vp, const char *str)
5103 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5104 vfs_badlock("interlock is not locked but should be", str, vp);
5108 assert_vi_unlocked(struct vnode *vp, const char *str)
5111 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5112 vfs_badlock("interlock is locked but should not be", str, vp);
5116 assert_vop_locked(struct vnode *vp, const char *str)
5120 if (!IGNORE_LOCK(vp)) {
5121 locked = VOP_ISLOCKED(vp);
5122 if (locked == 0 || locked == LK_EXCLOTHER)
5123 vfs_badlock("is not locked but should be", str, vp);
5128 assert_vop_unlocked(struct vnode *vp, const char *str)
5131 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5132 vfs_badlock("is locked but should not be", str, vp);
5136 assert_vop_elocked(struct vnode *vp, const char *str)
5139 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5140 vfs_badlock("is not exclusive locked but should be", str, vp);
5142 #endif /* DEBUG_VFS_LOCKS */
5145 vop_rename_fail(struct vop_rename_args *ap)
5148 if (ap->a_tvp != NULL)
5150 if (ap->a_tdvp == ap->a_tvp)
5159 vop_rename_pre(void *ap)
5161 struct vop_rename_args *a = ap;
5163 #ifdef DEBUG_VFS_LOCKS
5165 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5166 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5167 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5168 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5170 /* Check the source (from). */
5171 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5172 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5173 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5174 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5175 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5177 /* Check the target. */
5179 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5180 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5182 if (a->a_tdvp != a->a_fdvp)
5184 if (a->a_tvp != a->a_fvp)
5191 #ifdef DEBUG_VFS_LOCKS
5193 vop_strategy_pre(void *ap)
5195 struct vop_strategy_args *a;
5202 * Cluster ops lock their component buffers but not the IO container.
5204 if ((bp->b_flags & B_CLUSTER) != 0)
5207 if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5208 if (vfs_badlock_print)
5210 "VOP_STRATEGY: bp is not locked but should be\n");
5211 if (vfs_badlock_ddb)
5212 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5217 vop_lock_pre(void *ap)
5219 struct vop_lock1_args *a = ap;
5221 if ((a->a_flags & LK_INTERLOCK) == 0)
5222 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5224 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5228 vop_lock_post(void *ap, int rc)
5230 struct vop_lock1_args *a = ap;
5232 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5233 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5234 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5238 vop_unlock_pre(void *ap)
5240 struct vop_unlock_args *a = ap;
5242 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5246 vop_unlock_post(void *ap, int rc)
5252 vop_need_inactive_pre(void *ap)
5254 struct vop_need_inactive_args *a = ap;
5256 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5260 vop_need_inactive_post(void *ap, int rc)
5262 struct vop_need_inactive_args *a = ap;
5264 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5269 vop_create_post(void *ap, int rc)
5271 struct vop_create_args *a = ap;
5274 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5278 vop_deleteextattr_post(void *ap, int rc)
5280 struct vop_deleteextattr_args *a = ap;
5283 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5287 vop_link_post(void *ap, int rc)
5289 struct vop_link_args *a = ap;
5292 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
5293 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
5298 vop_mkdir_post(void *ap, int rc)
5300 struct vop_mkdir_args *a = ap;
5303 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5307 vop_mknod_post(void *ap, int rc)
5309 struct vop_mknod_args *a = ap;
5312 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5316 vop_reclaim_post(void *ap, int rc)
5318 struct vop_reclaim_args *a = ap;
5321 VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
5325 vop_remove_post(void *ap, int rc)
5327 struct vop_remove_args *a = ap;
5330 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5331 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5336 vop_rename_post(void *ap, int rc)
5338 struct vop_rename_args *a = ap;
5343 if (a->a_fdvp == a->a_tdvp) {
5344 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5346 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5347 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5349 hint |= NOTE_EXTEND;
5350 if (a->a_fvp->v_type == VDIR)
5352 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5354 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5355 a->a_tvp->v_type == VDIR)
5357 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5360 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5362 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5364 if (a->a_tdvp != a->a_fdvp)
5366 if (a->a_tvp != a->a_fvp)
5374 vop_rmdir_post(void *ap, int rc)
5376 struct vop_rmdir_args *a = ap;
5379 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5380 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5385 vop_setattr_post(void *ap, int rc)
5387 struct vop_setattr_args *a = ap;
5390 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5394 vop_setextattr_post(void *ap, int rc)
5396 struct vop_setextattr_args *a = ap;
5399 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5403 vop_symlink_post(void *ap, int rc)
5405 struct vop_symlink_args *a = ap;
5408 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5412 vop_open_post(void *ap, int rc)
5414 struct vop_open_args *a = ap;
5417 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
5421 vop_close_post(void *ap, int rc)
5423 struct vop_close_args *a = ap;
5425 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
5426 !VN_IS_DOOMED(a->a_vp))) {
5427 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
5428 NOTE_CLOSE_WRITE : NOTE_CLOSE);
5433 vop_read_post(void *ap, int rc)
5435 struct vop_read_args *a = ap;
5438 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5442 vop_readdir_post(void *ap, int rc)
5444 struct vop_readdir_args *a = ap;
5447 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5450 static struct knlist fs_knlist;
5453 vfs_event_init(void *arg)
5455 knlist_init_mtx(&fs_knlist, NULL);
5457 /* XXX - correct order? */
5458 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
5461 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
5464 KNOTE_UNLOCKED(&fs_knlist, event);
5467 static int filt_fsattach(struct knote *kn);
5468 static void filt_fsdetach(struct knote *kn);
5469 static int filt_fsevent(struct knote *kn, long hint);
5471 struct filterops fs_filtops = {
5473 .f_attach = filt_fsattach,
5474 .f_detach = filt_fsdetach,
5475 .f_event = filt_fsevent
5479 filt_fsattach(struct knote *kn)
5482 kn->kn_flags |= EV_CLEAR;
5483 knlist_add(&fs_knlist, kn, 0);
5488 filt_fsdetach(struct knote *kn)
5491 knlist_remove(&fs_knlist, kn, 0);
5495 filt_fsevent(struct knote *kn, long hint)
5498 kn->kn_fflags |= hint;
5499 return (kn->kn_fflags != 0);
5503 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
5509 error = SYSCTL_IN(req, &vc, sizeof(vc));
5512 if (vc.vc_vers != VFS_CTL_VERS1)
5514 mp = vfs_getvfs(&vc.vc_fsid);
5517 /* ensure that a specific sysctl goes to the right filesystem. */
5518 if (strcmp(vc.vc_fstypename, "*") != 0 &&
5519 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
5523 VCTLTOREQ(&vc, req);
5524 error = VFS_SYSCTL(mp, vc.vc_op, req);
5529 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
5530 NULL, 0, sysctl_vfs_ctl, "",
5534 * Function to initialize a va_filerev field sensibly.
5535 * XXX: Wouldn't a random number make a lot more sense ??
5538 init_va_filerev(void)
5543 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
5546 static int filt_vfsread(struct knote *kn, long hint);
5547 static int filt_vfswrite(struct knote *kn, long hint);
5548 static int filt_vfsvnode(struct knote *kn, long hint);
5549 static void filt_vfsdetach(struct knote *kn);
5550 static struct filterops vfsread_filtops = {
5552 .f_detach = filt_vfsdetach,
5553 .f_event = filt_vfsread
5555 static struct filterops vfswrite_filtops = {
5557 .f_detach = filt_vfsdetach,
5558 .f_event = filt_vfswrite
5560 static struct filterops vfsvnode_filtops = {
5562 .f_detach = filt_vfsdetach,
5563 .f_event = filt_vfsvnode
5567 vfs_knllock(void *arg)
5569 struct vnode *vp = arg;
5571 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5575 vfs_knlunlock(void *arg)
5577 struct vnode *vp = arg;
5583 vfs_knl_assert_locked(void *arg)
5585 #ifdef DEBUG_VFS_LOCKS
5586 struct vnode *vp = arg;
5588 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
5593 vfs_knl_assert_unlocked(void *arg)
5595 #ifdef DEBUG_VFS_LOCKS
5596 struct vnode *vp = arg;
5598 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
5603 vfs_kqfilter(struct vop_kqfilter_args *ap)
5605 struct vnode *vp = ap->a_vp;
5606 struct knote *kn = ap->a_kn;
5609 switch (kn->kn_filter) {
5611 kn->kn_fop = &vfsread_filtops;
5614 kn->kn_fop = &vfswrite_filtops;
5617 kn->kn_fop = &vfsvnode_filtops;
5623 kn->kn_hook = (caddr_t)vp;
5626 if (vp->v_pollinfo == NULL)
5628 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5630 knlist_add(knl, kn, 0);
5636 * Detach knote from vnode
5639 filt_vfsdetach(struct knote *kn)
5641 struct vnode *vp = (struct vnode *)kn->kn_hook;
5643 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
5644 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
5650 filt_vfsread(struct knote *kn, long hint)
5652 struct vnode *vp = (struct vnode *)kn->kn_hook;
5657 * filesystem is gone, so set the EOF flag and schedule
5658 * the knote for deletion.
5660 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5662 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5667 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
5671 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
5672 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
5679 filt_vfswrite(struct knote *kn, long hint)
5681 struct vnode *vp = (struct vnode *)kn->kn_hook;
5686 * filesystem is gone, so set the EOF flag and schedule
5687 * the knote for deletion.
5689 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
5690 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5698 filt_vfsvnode(struct knote *kn, long hint)
5700 struct vnode *vp = (struct vnode *)kn->kn_hook;
5704 if (kn->kn_sfflags & hint)
5705 kn->kn_fflags |= hint;
5706 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5707 kn->kn_flags |= EV_EOF;
5711 res = (kn->kn_fflags != 0);
5717 * Returns whether the directory is empty or not.
5718 * If it is empty, the return value is 0; otherwise
5719 * the return value is an error value (which may
5723 vfs_emptydir(struct vnode *vp)
5727 struct dirent *dirent, *dp, *endp;
5733 ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
5735 dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
5736 iov.iov_base = dirent;
5737 iov.iov_len = sizeof(struct dirent);
5742 uio.uio_resid = sizeof(struct dirent);
5743 uio.uio_segflg = UIO_SYSSPACE;
5744 uio.uio_rw = UIO_READ;
5745 uio.uio_td = curthread;
5747 while (eof == 0 && error == 0) {
5748 error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
5752 endp = (void *)((uint8_t *)dirent +
5753 sizeof(struct dirent) - uio.uio_resid);
5754 for (dp = dirent; dp < endp;
5755 dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
5756 if (dp->d_type == DT_WHT)
5758 if (dp->d_namlen == 0)
5760 if (dp->d_type != DT_DIR &&
5761 dp->d_type != DT_UNKNOWN) {
5765 if (dp->d_namlen > 2) {
5769 if (dp->d_namlen == 1 &&
5770 dp->d_name[0] != '.') {
5774 if (dp->d_namlen == 2 &&
5775 dp->d_name[1] != '.') {
5779 uio.uio_resid = sizeof(struct dirent);
5782 free(dirent, M_TEMP);
5787 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
5791 if (dp->d_reclen > ap->a_uio->uio_resid)
5792 return (ENAMETOOLONG);
5793 error = uiomove(dp, dp->d_reclen, ap->a_uio);
5795 if (ap->a_ncookies != NULL) {
5796 if (ap->a_cookies != NULL)
5797 free(ap->a_cookies, M_TEMP);
5798 ap->a_cookies = NULL;
5799 *ap->a_ncookies = 0;
5803 if (ap->a_ncookies == NULL)
5806 KASSERT(ap->a_cookies,
5807 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
5809 *ap->a_cookies = realloc(*ap->a_cookies,
5810 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
5811 (*ap->a_cookies)[*ap->a_ncookies] = off;
5812 *ap->a_ncookies += 1;
5817 * Mark for update the access time of the file if the filesystem
5818 * supports VOP_MARKATIME. This functionality is used by execve and
5819 * mmap, so we want to avoid the I/O implied by directly setting
5820 * va_atime for the sake of efficiency.
5823 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
5828 ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
5829 if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
5830 (void)VOP_MARKATIME(vp);
5834 * The purpose of this routine is to remove granularity from accmode_t,
5835 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
5836 * VADMIN and VAPPEND.
5838 * If it returns 0, the caller is supposed to continue with the usual
5839 * access checks using 'accmode' as modified by this routine. If it
5840 * returns nonzero value, the caller is supposed to return that value
5843 * Note that after this routine runs, accmode may be zero.
5846 vfs_unixify_accmode(accmode_t *accmode)
5849 * There is no way to specify explicit "deny" rule using
5850 * file mode or POSIX.1e ACLs.
5852 if (*accmode & VEXPLICIT_DENY) {
5858 * None of these can be translated into usual access bits.
5859 * Also, the common case for NFSv4 ACLs is to not contain
5860 * either of these bits. Caller should check for VWRITE
5861 * on the containing directory instead.
5863 if (*accmode & (VDELETE_CHILD | VDELETE))
5866 if (*accmode & VADMIN_PERMS) {
5867 *accmode &= ~VADMIN_PERMS;
5872 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
5873 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
5875 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
5881 * Clear out a doomed vnode (if any) and replace it with a new one as long
5882 * as the fs is not being unmounted. Return the root vnode to the caller.
5884 static int __noinline
5885 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
5891 if (mp->mnt_rootvnode != NULL) {
5893 vp = mp->mnt_rootvnode;
5895 if (!VN_IS_DOOMED(vp)) {
5898 error = vn_lock(vp, flags);
5907 * Clear the old one.
5909 mp->mnt_rootvnode = NULL;
5914 * Paired with a fence in vfs_op_thread_exit().
5916 atomic_thread_fence_acq();
5917 vfs_op_barrier_wait(mp);
5921 error = VFS_CACHEDROOT(mp, flags, vpp);
5924 if (mp->mnt_vfs_ops == 0) {
5926 if (mp->mnt_vfs_ops != 0) {
5930 if (mp->mnt_rootvnode == NULL) {
5932 mp->mnt_rootvnode = *vpp;
5934 if (mp->mnt_rootvnode != *vpp) {
5935 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
5936 panic("%s: mismatch between vnode returned "
5937 " by VFS_CACHEDROOT and the one cached "
5939 __func__, *vpp, mp->mnt_rootvnode);
5949 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
5954 if (!vfs_op_thread_enter(mp))
5955 return (vfs_cache_root_fallback(mp, flags, vpp));
5956 vp = (struct vnode *)atomic_load_ptr(&mp->mnt_rootvnode);
5957 if (vp == NULL || VN_IS_DOOMED(vp)) {
5958 vfs_op_thread_exit(mp);
5959 return (vfs_cache_root_fallback(mp, flags, vpp));
5962 vfs_op_thread_exit(mp);
5963 error = vn_lock(vp, flags);
5966 return (vfs_cache_root_fallback(mp, flags, vpp));
5973 vfs_cache_root_clear(struct mount *mp)
5978 * ops > 0 guarantees there is nobody who can see this vnode
5980 MPASS(mp->mnt_vfs_ops > 0);
5981 vp = mp->mnt_rootvnode;
5982 mp->mnt_rootvnode = NULL;
5987 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
5990 MPASS(mp->mnt_vfs_ops > 0);
5992 mp->mnt_rootvnode = vp;
5996 * These are helper functions for filesystems to traverse all
5997 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
5999 * This interface replaces MNT_VNODE_FOREACH.
6004 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6009 kern_yield(PRI_USER);
6011 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6012 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6013 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6014 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6015 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6018 if (VN_IS_DOOMED(vp)) {
6025 __mnt_vnode_markerfree_all(mvp, mp);
6026 /* MNT_IUNLOCK(mp); -- done in above function */
6027 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6030 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6031 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6037 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6041 *mvp = vn_alloc_marker(mp);
6045 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6046 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6047 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6050 if (VN_IS_DOOMED(vp)) {
6059 vn_free_marker(*mvp);
6063 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6069 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6077 mtx_assert(MNT_MTX(mp), MA_OWNED);
6079 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6080 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6083 vn_free_marker(*mvp);
6088 * These are helper functions for filesystems to traverse their
6089 * lazy vnodes. See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6092 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6095 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6100 vn_free_marker(*mvp);
6105 * Relock the mp mount vnode list lock with the vp vnode interlock in the
6106 * conventional lock order during mnt_vnode_next_lazy iteration.
6108 * On entry, the mount vnode list lock is held and the vnode interlock is not.
6109 * The list lock is dropped and reacquired. On success, both locks are held.
6110 * On failure, the mount vnode list lock is held but the vnode interlock is
6111 * not, and the procedure may have yielded.
6114 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6117 const struct vnode *tmp;
6120 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6121 TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6122 ("%s: bad marker", __func__));
6123 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6124 ("%s: inappropriate vnode", __func__));
6125 ASSERT_VI_UNLOCKED(vp, __func__);
6126 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6130 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6131 TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6134 * Use a hold to prevent vp from disappearing while the mount vnode
6135 * list lock is dropped and reacquired. Normally a hold would be
6136 * acquired with vhold(), but that might try to acquire the vnode
6137 * interlock, which would be a LOR with the mount vnode list lock.
6139 held = refcount_acquire_if_not_zero(&vp->v_holdcnt);
6140 mtx_unlock(&mp->mnt_listmtx);
6144 if (!refcount_release_if_not_last(&vp->v_holdcnt)) {
6148 mtx_lock(&mp->mnt_listmtx);
6151 * Determine whether the vnode is still the next one after the marker,
6152 * excepting any other markers. If the vnode has not been doomed by
6153 * vgone() then the hold should have ensured that it remained on the
6154 * lazy list. If it has been doomed but is still on the lazy list,
6155 * don't abort, but rather skip over it (avoid spinning on doomed
6160 tmp = TAILQ_NEXT(tmp, v_lazylist);
6161 } while (tmp != NULL && tmp->v_type == VMARKER);
6163 mtx_unlock(&mp->mnt_listmtx);
6172 mtx_lock(&mp->mnt_listmtx);
6175 ASSERT_VI_LOCKED(vp, __func__);
6177 ASSERT_VI_UNLOCKED(vp, __func__);
6178 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6182 static struct vnode *
6183 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6186 struct vnode *vp, *nvp;
6188 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6189 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6191 vp = TAILQ_NEXT(*mvp, v_lazylist);
6192 while (vp != NULL) {
6193 if (vp->v_type == VMARKER) {
6194 vp = TAILQ_NEXT(vp, v_lazylist);
6198 * See if we want to process the vnode. Note we may encounter a
6199 * long string of vnodes we don't care about and hog the list
6200 * as a result. Check for it and requeue the marker.
6202 if (VN_IS_DOOMED(vp) || !cb(vp, cbarg)) {
6203 if (!should_yield()) {
6204 vp = TAILQ_NEXT(vp, v_lazylist);
6207 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6209 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6211 mtx_unlock(&mp->mnt_listmtx);
6212 kern_yield(PRI_USER);
6213 mtx_lock(&mp->mnt_listmtx);
6217 * Try-lock because this is the wrong lock order. If that does
6218 * not succeed, drop the mount vnode list lock and try to
6219 * reacquire it and the vnode interlock in the right order.
6221 if (!VI_TRYLOCK(vp) &&
6222 !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6224 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6225 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6226 ("alien vnode on the lazy list %p %p", vp, mp));
6227 if (vp->v_mount == mp && !VN_IS_DOOMED(vp))
6229 nvp = TAILQ_NEXT(vp, v_lazylist);
6233 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6235 /* Check if we are done */
6237 mtx_unlock(&mp->mnt_listmtx);
6238 mnt_vnode_markerfree_lazy(mvp, mp);
6241 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6242 mtx_unlock(&mp->mnt_listmtx);
6243 ASSERT_VI_LOCKED(vp, "lazy iter");
6248 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6253 kern_yield(PRI_USER);
6254 mtx_lock(&mp->mnt_listmtx);
6255 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6259 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6264 *mvp = vn_alloc_marker(mp);
6269 mtx_lock(&mp->mnt_listmtx);
6270 vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6272 mtx_unlock(&mp->mnt_listmtx);
6273 mnt_vnode_markerfree_lazy(mvp, mp);
6276 TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6277 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6281 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6287 mtx_lock(&mp->mnt_listmtx);
6288 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6289 mtx_unlock(&mp->mnt_listmtx);
6290 mnt_vnode_markerfree_lazy(mvp, mp);