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_usecount(struct vnode *);
111 static void v_incr_usecount_locked(struct vnode *);
112 static void v_incr_devcount(struct vnode *);
113 static void v_decr_devcount(struct vnode *);
114 static void vgonel(struct vnode *);
115 static void vfs_knllock(void *arg);
116 static void vfs_knlunlock(void *arg);
117 static void vfs_knl_assert_locked(void *arg);
118 static void vfs_knl_assert_unlocked(void *arg);
119 static void vnlru_return_batches(struct vfsops *mnt_op);
120 static void destroy_vpollinfo(struct vpollinfo *vi);
121 static int v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
122 daddr_t startlbn, daddr_t endlbn);
125 * These fences are intended for cases where some synchronization is
126 * needed between access of v_iflags and lockless vnode refcount (v_holdcnt
127 * and v_usecount) updates. Access to v_iflags is generally synchronized
128 * by the interlock, but we have some internal assertions that check vnode
129 * flags without acquiring the lock. Thus, these fences are INVARIANTS-only
133 #define VNODE_REFCOUNT_FENCE_ACQ() atomic_thread_fence_acq()
134 #define VNODE_REFCOUNT_FENCE_REL() atomic_thread_fence_rel()
136 #define VNODE_REFCOUNT_FENCE_ACQ()
137 #define VNODE_REFCOUNT_FENCE_REL()
141 * Number of vnodes in existence. Increased whenever getnewvnode()
142 * allocates a new vnode, decreased in vdropl() for VI_DOOMED vnode.
144 static unsigned long numvnodes;
146 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
147 "Number of vnodes in existence");
149 static counter_u64_t vnodes_created;
150 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
151 "Number of vnodes created by getnewvnode");
153 static u_long mnt_free_list_batch = 128;
154 SYSCTL_ULONG(_vfs, OID_AUTO, mnt_free_list_batch, CTLFLAG_RW,
155 &mnt_free_list_batch, 0, "Limit of vnodes held on mnt's free list");
158 * Conversion tables for conversion from vnode types to inode formats
161 enum vtype iftovt_tab[16] = {
162 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
163 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
165 int vttoif_tab[10] = {
166 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
167 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
171 * List of vnodes that are ready for recycling.
173 static TAILQ_HEAD(freelst, vnode) vnode_free_list;
176 * "Free" vnode target. Free vnodes are rarely completely free, but are
177 * just ones that are cheap to recycle. Usually they are for files which
178 * have been stat'd but not read; these usually have inode and namecache
179 * data attached to them. This target is the preferred minimum size of a
180 * sub-cache consisting mostly of such files. The system balances the size
181 * of this sub-cache with its complement to try to prevent either from
182 * thrashing while the other is relatively inactive. The targets express
183 * a preference for the best balance.
185 * "Above" this target there are 2 further targets (watermarks) related
186 * to recyling of free vnodes. In the best-operating case, the cache is
187 * exactly full, the free list has size between vlowat and vhiwat above the
188 * free target, and recycling from it and normal use maintains this state.
189 * Sometimes the free list is below vlowat or even empty, but this state
190 * is even better for immediate use provided the cache is not full.
191 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
192 * ones) to reach one of these states. The watermarks are currently hard-
193 * coded as 4% and 9% of the available space higher. These and the default
194 * of 25% for wantfreevnodes are too large if the memory size is large.
195 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
196 * whenever vnlru_proc() becomes active.
198 static u_long wantfreevnodes;
199 SYSCTL_ULONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW,
200 &wantfreevnodes, 0, "Target for minimum number of \"free\" vnodes");
201 static u_long freevnodes;
202 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
203 &freevnodes, 0, "Number of \"free\" vnodes");
205 static counter_u64_t recycles_count;
206 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
207 "Number of vnodes recycled to meet vnode cache targets");
210 * Various variables used for debugging the new implementation of
212 * XXX these are probably of (very) limited utility now.
214 static int reassignbufcalls;
215 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0,
216 "Number of calls to reassignbuf");
218 static counter_u64_t free_owe_inact;
219 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, free_owe_inact, CTLFLAG_RD, &free_owe_inact,
220 "Number of times free vnodes kept on active list due to VFS "
221 "owing inactivation");
223 /* To keep more than one thread at a time from running vfs_getnewfsid */
224 static struct mtx mntid_mtx;
227 * Lock for any access to the following:
232 static struct mtx vnode_free_list_mtx;
234 /* Publicly exported FS */
235 struct nfs_public nfs_pub;
237 static uma_zone_t buf_trie_zone;
239 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
240 static uma_zone_t vnode_zone;
241 static uma_zone_t vnodepoll_zone;
244 * The workitem queue.
246 * It is useful to delay writes of file data and filesystem metadata
247 * for tens of seconds so that quickly created and deleted files need
248 * not waste disk bandwidth being created and removed. To realize this,
249 * we append vnodes to a "workitem" queue. When running with a soft
250 * updates implementation, most pending metadata dependencies should
251 * not wait for more than a few seconds. Thus, mounted on block devices
252 * are delayed only about a half the time that file data is delayed.
253 * Similarly, directory updates are more critical, so are only delayed
254 * about a third the time that file data is delayed. Thus, there are
255 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
256 * one each second (driven off the filesystem syncer process). The
257 * syncer_delayno variable indicates the next queue that is to be processed.
258 * Items that need to be processed soon are placed in this queue:
260 * syncer_workitem_pending[syncer_delayno]
262 * A delay of fifteen seconds is done by placing the request fifteen
263 * entries later in the queue:
265 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
268 static int syncer_delayno;
269 static long syncer_mask;
270 LIST_HEAD(synclist, bufobj);
271 static struct synclist *syncer_workitem_pending;
273 * The sync_mtx protects:
278 * syncer_workitem_pending
279 * syncer_worklist_len
282 static struct mtx sync_mtx;
283 static struct cv sync_wakeup;
285 #define SYNCER_MAXDELAY 32
286 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
287 static int syncdelay = 30; /* max time to delay syncing data */
288 static int filedelay = 30; /* time to delay syncing files */
289 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
290 "Time to delay syncing files (in seconds)");
291 static int dirdelay = 29; /* time to delay syncing directories */
292 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
293 "Time to delay syncing directories (in seconds)");
294 static int metadelay = 28; /* time to delay syncing metadata */
295 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
296 "Time to delay syncing metadata (in seconds)");
297 static int rushjob; /* number of slots to run ASAP */
298 static int stat_rush_requests; /* number of times I/O speeded up */
299 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
300 "Number of times I/O speeded up (rush requests)");
303 * When shutting down the syncer, run it at four times normal speed.
305 #define SYNCER_SHUTDOWN_SPEEDUP 4
306 static int sync_vnode_count;
307 static int syncer_worklist_len;
308 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
311 /* Target for maximum number of vnodes. */
313 static int gapvnodes; /* gap between wanted and desired */
314 static int vhiwat; /* enough extras after expansion */
315 static int vlowat; /* minimal extras before expansion */
316 static int vstir; /* nonzero to stir non-free vnodes */
317 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
320 sysctl_update_desiredvnodes(SYSCTL_HANDLER_ARGS)
322 int error, old_desiredvnodes;
324 old_desiredvnodes = desiredvnodes;
325 if ((error = sysctl_handle_int(oidp, arg1, arg2, req)) != 0)
327 if (old_desiredvnodes != desiredvnodes) {
328 wantfreevnodes = desiredvnodes / 4;
329 /* XXX locking seems to be incomplete. */
330 vfs_hash_changesize(desiredvnodes);
331 cache_changesize(desiredvnodes);
336 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
337 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, &desiredvnodes, 0,
338 sysctl_update_desiredvnodes, "I", "Target for maximum number of vnodes");
339 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
340 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
341 static int vnlru_nowhere;
342 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
343 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
346 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
351 unsigned long ndflags;
354 if (req->newptr == NULL)
356 if (req->newlen > PATH_MAX)
359 buf = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
360 error = SYSCTL_IN(req, buf, req->newlen);
364 buf[req->newlen] = '\0';
366 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | NOCACHE | SAVENAME;
367 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
368 if ((error = namei(&nd)) != 0)
372 if ((vp->v_iflag & VI_DOOMED) != 0) {
374 * This vnode is being recycled. Return != 0 to let the caller
375 * know that the sysctl had no effect. Return EAGAIN because a
376 * subsequent call will likely succeed (since namei will create
377 * a new vnode if necessary)
383 counter_u64_add(recycles_count, 1);
393 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
395 struct thread *td = curthread;
401 if (req->newptr == NULL)
404 error = sysctl_handle_int(oidp, &fd, 0, req);
407 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
412 error = vn_lock(vp, LK_EXCLUSIVE);
416 counter_u64_add(recycles_count, 1);
424 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
425 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
426 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
427 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
428 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
429 sysctl_ftry_reclaim_vnode, "I",
430 "Try to reclaim a vnode by its file descriptor");
432 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
436 * Support for the bufobj clean & dirty pctrie.
439 buf_trie_alloc(struct pctrie *ptree)
442 return uma_zalloc(buf_trie_zone, M_NOWAIT);
446 buf_trie_free(struct pctrie *ptree, void *node)
449 uma_zfree(buf_trie_zone, node);
451 PCTRIE_DEFINE(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free);
454 * Initialize the vnode management data structures.
456 * Reevaluate the following cap on the number of vnodes after the physical
457 * memory size exceeds 512GB. In the limit, as the physical memory size
458 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
460 #ifndef MAXVNODES_MAX
461 #define MAXVNODES_MAX (512 * 1024 * 1024 / 64) /* 8M */
465 * Initialize a vnode as it first enters the zone.
468 vnode_init(void *mem, int size, int flags)
477 vp->v_vnlock = &vp->v_lock;
478 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
480 * By default, don't allow shared locks unless filesystems opt-in.
482 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
483 LK_NOSHARE | LK_IS_VNODE);
487 bufobj_init(&vp->v_bufobj, vp);
489 * Initialize namecache.
491 LIST_INIT(&vp->v_cache_src);
492 TAILQ_INIT(&vp->v_cache_dst);
494 * Initialize rangelocks.
496 rangelock_init(&vp->v_rl);
501 * Free a vnode when it is cleared from the zone.
504 vnode_fini(void *mem, int size)
510 rangelock_destroy(&vp->v_rl);
511 lockdestroy(vp->v_vnlock);
512 mtx_destroy(&vp->v_interlock);
514 rw_destroy(BO_LOCKPTR(bo));
518 * Provide the size of NFS nclnode and NFS fh for calculation of the
519 * vnode memory consumption. The size is specified directly to
520 * eliminate dependency on NFS-private header.
522 * Other filesystems may use bigger or smaller (like UFS and ZFS)
523 * private inode data, but the NFS-based estimation is ample enough.
524 * Still, we care about differences in the size between 64- and 32-bit
527 * Namecache structure size is heuristically
528 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
531 #define NFS_NCLNODE_SZ (528 + 64)
534 #define NFS_NCLNODE_SZ (360 + 32)
539 vntblinit(void *dummy __unused)
542 int physvnodes, virtvnodes;
545 * Desiredvnodes is a function of the physical memory size and the
546 * kernel's heap size. Generally speaking, it scales with the
547 * physical memory size. The ratio of desiredvnodes to the physical
548 * memory size is 1:16 until desiredvnodes exceeds 98,304.
550 * marginal ratio of desiredvnodes to the physical memory size is
551 * 1:64. However, desiredvnodes is limited by the kernel's heap
552 * size. The memory required by desiredvnodes vnodes and vm objects
553 * must not exceed 1/10th of the kernel's heap size.
555 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
556 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
557 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
558 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
559 desiredvnodes = min(physvnodes, virtvnodes);
560 if (desiredvnodes > MAXVNODES_MAX) {
562 printf("Reducing kern.maxvnodes %d -> %d\n",
563 desiredvnodes, MAXVNODES_MAX);
564 desiredvnodes = MAXVNODES_MAX;
566 wantfreevnodes = desiredvnodes / 4;
567 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
568 TAILQ_INIT(&vnode_free_list);
569 mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
570 vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
571 vnode_init, vnode_fini, UMA_ALIGN_PTR, 0);
572 vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
573 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
575 * Preallocate enough nodes to support one-per buf so that
576 * we can not fail an insert. reassignbuf() callers can not
577 * tolerate the insertion failure.
579 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
580 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
581 UMA_ZONE_NOFREE | UMA_ZONE_VM);
582 uma_prealloc(buf_trie_zone, nbuf);
584 vnodes_created = counter_u64_alloc(M_WAITOK);
585 recycles_count = counter_u64_alloc(M_WAITOK);
586 free_owe_inact = counter_u64_alloc(M_WAITOK);
589 * Initialize the filesystem syncer.
591 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
593 syncer_maxdelay = syncer_mask + 1;
594 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
595 cv_init(&sync_wakeup, "syncer");
596 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
600 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
604 * Mark a mount point as busy. Used to synchronize access and to delay
605 * unmounting. Eventually, mountlist_mtx is not released on failure.
607 * vfs_busy() is a custom lock, it can block the caller.
608 * vfs_busy() only sleeps if the unmount is active on the mount point.
609 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
610 * vnode belonging to mp.
612 * Lookup uses vfs_busy() to traverse mount points.
614 * / vnode lock A / vnode lock (/var) D
615 * /var vnode lock B /log vnode lock(/var/log) E
616 * vfs_busy lock C vfs_busy lock F
618 * Within each file system, the lock order is C->A->B and F->D->E.
620 * When traversing across mounts, the system follows that lock order:
626 * The lookup() process for namei("/var") illustrates the process:
627 * VOP_LOOKUP() obtains B while A is held
628 * vfs_busy() obtains a shared lock on F while A and B are held
629 * vput() releases lock on B
630 * vput() releases lock on A
631 * VFS_ROOT() obtains lock on D while shared lock on F is held
632 * vfs_unbusy() releases shared lock on F
633 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
634 * Attempt to lock A (instead of vp_crossmp) while D is held would
635 * violate the global order, causing deadlocks.
637 * dounmount() locks B while F is drained.
640 vfs_busy(struct mount *mp, int flags)
643 MPASS((flags & ~MBF_MASK) == 0);
644 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
649 * If mount point is currently being unmounted, sleep until the
650 * mount point fate is decided. If thread doing the unmounting fails,
651 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
652 * that this mount point has survived the unmount attempt and vfs_busy
653 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
654 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
655 * about to be really destroyed. vfs_busy needs to release its
656 * reference on the mount point in this case and return with ENOENT,
657 * telling the caller that mount mount it tried to busy is no longer
660 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
661 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
664 CTR1(KTR_VFS, "%s: failed busying before sleeping",
668 if (flags & MBF_MNTLSTLOCK)
669 mtx_unlock(&mountlist_mtx);
670 mp->mnt_kern_flag |= MNTK_MWAIT;
671 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
672 if (flags & MBF_MNTLSTLOCK)
673 mtx_lock(&mountlist_mtx);
676 if (flags & MBF_MNTLSTLOCK)
677 mtx_unlock(&mountlist_mtx);
684 * Free a busy filesystem.
687 vfs_unbusy(struct mount *mp)
690 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
693 KASSERT(mp->mnt_lockref > 0, ("negative mnt_lockref"));
695 if (mp->mnt_lockref == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
696 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
697 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
698 mp->mnt_kern_flag &= ~MNTK_DRAINING;
699 wakeup(&mp->mnt_lockref);
705 * Lookup a mount point by filesystem identifier.
708 vfs_getvfs(fsid_t *fsid)
712 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
713 mtx_lock(&mountlist_mtx);
714 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
715 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
716 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
718 mtx_unlock(&mountlist_mtx);
722 mtx_unlock(&mountlist_mtx);
723 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
724 return ((struct mount *) 0);
728 * Lookup a mount point by filesystem identifier, busying it before
731 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
732 * cache for popular filesystem identifiers. The cache is lockess, using
733 * the fact that struct mount's are never freed. In worst case we may
734 * get pointer to unmounted or even different filesystem, so we have to
735 * check what we got, and go slow way if so.
738 vfs_busyfs(fsid_t *fsid)
740 #define FSID_CACHE_SIZE 256
741 typedef struct mount * volatile vmp_t;
742 static vmp_t cache[FSID_CACHE_SIZE];
747 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
748 hash = fsid->val[0] ^ fsid->val[1];
749 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
752 mp->mnt_stat.f_fsid.val[0] != fsid->val[0] ||
753 mp->mnt_stat.f_fsid.val[1] != fsid->val[1])
755 if (vfs_busy(mp, 0) != 0) {
759 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
760 mp->mnt_stat.f_fsid.val[1] == fsid->val[1])
766 mtx_lock(&mountlist_mtx);
767 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
768 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
769 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
770 error = vfs_busy(mp, MBF_MNTLSTLOCK);
773 mtx_unlock(&mountlist_mtx);
780 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
781 mtx_unlock(&mountlist_mtx);
782 return ((struct mount *) 0);
786 * Check if a user can access privileged mount options.
789 vfs_suser(struct mount *mp, struct thread *td)
793 if (jailed(td->td_ucred)) {
795 * If the jail of the calling thread lacks permission for
796 * this type of file system, deny immediately.
798 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
802 * If the file system was mounted outside the jail of the
803 * calling thread, deny immediately.
805 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
810 * If file system supports delegated administration, we don't check
811 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
812 * by the file system itself.
813 * If this is not the user that did original mount, we check for
814 * the PRIV_VFS_MOUNT_OWNER privilege.
816 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
817 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
818 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
825 * Get a new unique fsid. Try to make its val[0] unique, since this value
826 * will be used to create fake device numbers for stat(). Also try (but
827 * not so hard) make its val[0] unique mod 2^16, since some emulators only
828 * support 16-bit device numbers. We end up with unique val[0]'s for the
829 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
831 * Keep in mind that several mounts may be running in parallel. Starting
832 * the search one past where the previous search terminated is both a
833 * micro-optimization and a defense against returning the same fsid to
837 vfs_getnewfsid(struct mount *mp)
839 static uint16_t mntid_base;
844 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
845 mtx_lock(&mntid_mtx);
846 mtype = mp->mnt_vfc->vfc_typenum;
847 tfsid.val[1] = mtype;
848 mtype = (mtype & 0xFF) << 24;
850 tfsid.val[0] = makedev(255,
851 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
853 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
857 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
858 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
859 mtx_unlock(&mntid_mtx);
863 * Knob to control the precision of file timestamps:
865 * 0 = seconds only; nanoseconds zeroed.
866 * 1 = seconds and nanoseconds, accurate within 1/HZ.
867 * 2 = seconds and nanoseconds, truncated to microseconds.
868 * >=3 = seconds and nanoseconds, maximum precision.
870 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
872 static int timestamp_precision = TSP_USEC;
873 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
874 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
875 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
876 "3+: sec + ns (max. precision))");
879 * Get a current timestamp.
882 vfs_timestamp(struct timespec *tsp)
886 switch (timestamp_precision) {
888 tsp->tv_sec = time_second;
896 TIMEVAL_TO_TIMESPEC(&tv, tsp);
906 * Set vnode attributes to VNOVAL
909 vattr_null(struct vattr *vap)
913 vap->va_size = VNOVAL;
914 vap->va_bytes = VNOVAL;
915 vap->va_mode = VNOVAL;
916 vap->va_nlink = VNOVAL;
917 vap->va_uid = VNOVAL;
918 vap->va_gid = VNOVAL;
919 vap->va_fsid = VNOVAL;
920 vap->va_fileid = VNOVAL;
921 vap->va_blocksize = VNOVAL;
922 vap->va_rdev = VNOVAL;
923 vap->va_atime.tv_sec = VNOVAL;
924 vap->va_atime.tv_nsec = VNOVAL;
925 vap->va_mtime.tv_sec = VNOVAL;
926 vap->va_mtime.tv_nsec = VNOVAL;
927 vap->va_ctime.tv_sec = VNOVAL;
928 vap->va_ctime.tv_nsec = VNOVAL;
929 vap->va_birthtime.tv_sec = VNOVAL;
930 vap->va_birthtime.tv_nsec = VNOVAL;
931 vap->va_flags = VNOVAL;
932 vap->va_gen = VNOVAL;
937 * This routine is called when we have too many vnodes. It attempts
938 * to free <count> vnodes and will potentially free vnodes that still
939 * have VM backing store (VM backing store is typically the cause
940 * of a vnode blowout so we want to do this). Therefore, this operation
941 * is not considered cheap.
943 * A number of conditions may prevent a vnode from being reclaimed.
944 * the buffer cache may have references on the vnode, a directory
945 * vnode may still have references due to the namei cache representing
946 * underlying files, or the vnode may be in active use. It is not
947 * desirable to reuse such vnodes. These conditions may cause the
948 * number of vnodes to reach some minimum value regardless of what
949 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
951 * @param mp Try to reclaim vnodes from this mountpoint
952 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
953 * entries if this argument is strue
954 * @param trigger Only reclaim vnodes with fewer than this many resident
956 * @return The number of vnodes that were reclaimed.
959 vlrureclaim(struct mount *mp, bool reclaim_nc_src, int trigger)
962 int count, done, target;
965 vn_start_write(NULL, &mp, V_WAIT);
967 count = mp->mnt_nvnodelistsize;
968 target = count * (int64_t)gapvnodes / imax(desiredvnodes, 1);
969 target = target / 10 + 1;
970 while (count != 0 && done < target) {
971 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
972 while (vp != NULL && vp->v_type == VMARKER)
973 vp = TAILQ_NEXT(vp, v_nmntvnodes);
977 * XXX LRU is completely broken for non-free vnodes. First
978 * by calling here in mountpoint order, then by moving
979 * unselected vnodes to the end here, and most grossly by
980 * removing the vlruvp() function that was supposed to
981 * maintain the order. (This function was born broken
982 * since syncer problems prevented it doing anything.) The
983 * order is closer to LRC (C = Created).
985 * LRU reclaiming of vnodes seems to have last worked in
986 * FreeBSD-3 where LRU wasn't mentioned under any spelling.
987 * Then there was no hold count, and inactive vnodes were
988 * simply put on the free list in LRU order. The separate
989 * lists also break LRU. We prefer to reclaim from the
990 * free list for technical reasons. This tends to thrash
991 * the free list to keep very unrecently used held vnodes.
992 * The problem is mitigated by keeping the free list large.
994 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
995 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1000 * If it's been deconstructed already, it's still
1001 * referenced, or it exceeds the trigger, skip it.
1002 * Also skip free vnodes. We are trying to make space
1003 * to expand the free list, not reduce it.
1005 if (vp->v_usecount ||
1006 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1007 ((vp->v_iflag & VI_FREE) != 0) ||
1008 (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
1009 vp->v_object->resident_page_count > trigger)) {
1015 if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT)) {
1017 goto next_iter_mntunlocked;
1021 * v_usecount may have been bumped after VOP_LOCK() dropped
1022 * the vnode interlock and before it was locked again.
1024 * It is not necessary to recheck VI_DOOMED because it can
1025 * only be set by another thread that holds both the vnode
1026 * lock and vnode interlock. If another thread has the
1027 * vnode lock before we get to VOP_LOCK() and obtains the
1028 * vnode interlock after VOP_LOCK() drops the vnode
1029 * interlock, the other thread will be unable to drop the
1030 * vnode lock before our VOP_LOCK() call fails.
1032 if (vp->v_usecount ||
1033 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1034 (vp->v_iflag & VI_FREE) != 0 ||
1035 (vp->v_object != NULL &&
1036 vp->v_object->resident_page_count > trigger)) {
1039 goto next_iter_mntunlocked;
1041 KASSERT((vp->v_iflag & VI_DOOMED) == 0,
1042 ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
1043 counter_u64_add(recycles_count, 1);
1048 next_iter_mntunlocked:
1049 if (!should_yield())
1053 if (!should_yield())
1057 kern_yield(PRI_USER);
1062 vn_finished_write(mp);
1066 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1067 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1069 "limit on vnode free requests per call to the vnlru_free routine");
1072 * Attempt to reduce the free list by the requested amount.
1075 vnlru_free_locked(int count, struct vfsops *mnt_op)
1081 tried_batches = false;
1082 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
1083 if (count > max_vnlru_free)
1084 count = max_vnlru_free;
1085 for (; count > 0; count--) {
1086 vp = TAILQ_FIRST(&vnode_free_list);
1088 * The list can be modified while the free_list_mtx
1089 * has been dropped and vp could be NULL here.
1094 mtx_unlock(&vnode_free_list_mtx);
1095 vnlru_return_batches(mnt_op);
1096 tried_batches = true;
1097 mtx_lock(&vnode_free_list_mtx);
1101 VNASSERT(vp->v_op != NULL, vp,
1102 ("vnlru_free: vnode already reclaimed."));
1103 KASSERT((vp->v_iflag & VI_FREE) != 0,
1104 ("Removing vnode not on freelist"));
1105 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1106 ("Mangling active vnode"));
1107 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
1110 * Don't recycle if our vnode is from different type
1111 * of mount point. Note that mp is type-safe, the
1112 * check does not reach unmapped address even if
1113 * vnode is reclaimed.
1114 * Don't recycle if we can't get the interlock without
1117 if ((mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1118 mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
1119 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_actfreelist);
1122 VNASSERT((vp->v_iflag & VI_FREE) != 0 && vp->v_holdcnt == 0,
1123 vp, ("vp inconsistent on freelist"));
1126 * The clear of VI_FREE prevents activation of the
1127 * vnode. There is no sense in putting the vnode on
1128 * the mount point active list, only to remove it
1129 * later during recycling. Inline the relevant part
1130 * of vholdl(), to avoid triggering assertions or
1134 vp->v_iflag &= ~VI_FREE;
1135 VNODE_REFCOUNT_FENCE_REL();
1136 refcount_acquire(&vp->v_holdcnt);
1138 mtx_unlock(&vnode_free_list_mtx);
1142 * If the recycled succeeded this vdrop will actually free
1143 * the vnode. If not it will simply place it back on
1147 mtx_lock(&vnode_free_list_mtx);
1152 vnlru_free(int count, struct vfsops *mnt_op)
1155 mtx_lock(&vnode_free_list_mtx);
1156 vnlru_free_locked(count, mnt_op);
1157 mtx_unlock(&vnode_free_list_mtx);
1161 /* XXX some names and initialization are bad for limits and watermarks. */
1167 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1168 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1169 vlowat = vhiwat / 2;
1170 if (numvnodes > desiredvnodes)
1172 space = desiredvnodes - numvnodes;
1173 if (freevnodes > wantfreevnodes)
1174 space += freevnodes - wantfreevnodes;
1179 vnlru_return_batch_locked(struct mount *mp)
1183 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
1185 if (mp->mnt_tmpfreevnodelistsize == 0)
1188 TAILQ_FOREACH(vp, &mp->mnt_tmpfreevnodelist, v_actfreelist) {
1189 VNASSERT((vp->v_mflag & VMP_TMPMNTFREELIST) != 0, vp,
1190 ("vnode without VMP_TMPMNTFREELIST on mnt_tmpfreevnodelist"));
1191 vp->v_mflag &= ~VMP_TMPMNTFREELIST;
1193 mtx_lock(&vnode_free_list_mtx);
1194 TAILQ_CONCAT(&vnode_free_list, &mp->mnt_tmpfreevnodelist, v_actfreelist);
1195 freevnodes += mp->mnt_tmpfreevnodelistsize;
1196 mtx_unlock(&vnode_free_list_mtx);
1197 mp->mnt_tmpfreevnodelistsize = 0;
1201 vnlru_return_batch(struct mount *mp)
1204 mtx_lock(&mp->mnt_listmtx);
1205 vnlru_return_batch_locked(mp);
1206 mtx_unlock(&mp->mnt_listmtx);
1210 vnlru_return_batches(struct vfsops *mnt_op)
1212 struct mount *mp, *nmp;
1215 mtx_lock(&mountlist_mtx);
1216 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1217 need_unbusy = false;
1218 if (mnt_op != NULL && mp->mnt_op != mnt_op)
1220 if (mp->mnt_tmpfreevnodelistsize == 0)
1222 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK) == 0) {
1223 vnlru_return_batch(mp);
1225 mtx_lock(&mountlist_mtx);
1228 nmp = TAILQ_NEXT(mp, mnt_list);
1232 mtx_unlock(&mountlist_mtx);
1236 * Attempt to recycle vnodes in a context that is always safe to block.
1237 * Calling vlrurecycle() from the bowels of filesystem code has some
1238 * interesting deadlock problems.
1240 static struct proc *vnlruproc;
1241 static int vnlruproc_sig;
1246 struct mount *mp, *nmp;
1247 unsigned long onumvnodes;
1248 int done, force, trigger, usevnodes;
1249 bool reclaim_nc_src;
1251 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1252 SHUTDOWN_PRI_FIRST);
1256 kproc_suspend_check(vnlruproc);
1257 mtx_lock(&vnode_free_list_mtx);
1259 * If numvnodes is too large (due to desiredvnodes being
1260 * adjusted using its sysctl, or emergency growth), first
1261 * try to reduce it by discarding from the free list.
1263 if (numvnodes > desiredvnodes)
1264 vnlru_free_locked(numvnodes - desiredvnodes, NULL);
1266 * Sleep if the vnode cache is in a good state. This is
1267 * when it is not over-full and has space for about a 4%
1268 * or 9% expansion (by growing its size or inexcessively
1269 * reducing its free list). Otherwise, try to reclaim
1270 * space for a 10% expansion.
1272 if (vstir && force == 0) {
1276 if (vspace() >= vlowat && force == 0) {
1278 wakeup(&vnlruproc_sig);
1279 msleep(vnlruproc, &vnode_free_list_mtx,
1280 PVFS|PDROP, "vlruwt", hz);
1283 mtx_unlock(&vnode_free_list_mtx);
1285 onumvnodes = numvnodes;
1287 * Calculate parameters for recycling. These are the same
1288 * throughout the loop to give some semblance of fairness.
1289 * The trigger point is to avoid recycling vnodes with lots
1290 * of resident pages. We aren't trying to free memory; we
1291 * are trying to recycle or at least free vnodes.
1293 if (numvnodes <= desiredvnodes)
1294 usevnodes = numvnodes - freevnodes;
1296 usevnodes = numvnodes;
1300 * The trigger value is is chosen to give a conservatively
1301 * large value to ensure that it alone doesn't prevent
1302 * making progress. The value can easily be so large that
1303 * it is effectively infinite in some congested and
1304 * misconfigured cases, and this is necessary. Normally
1305 * it is about 8 to 100 (pages), which is quite large.
1307 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1309 trigger = vsmalltrigger;
1310 reclaim_nc_src = force >= 3;
1311 mtx_lock(&mountlist_mtx);
1312 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1313 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK)) {
1314 nmp = TAILQ_NEXT(mp, mnt_list);
1317 done += vlrureclaim(mp, reclaim_nc_src, trigger);
1318 mtx_lock(&mountlist_mtx);
1319 nmp = TAILQ_NEXT(mp, mnt_list);
1322 mtx_unlock(&mountlist_mtx);
1323 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1326 if (force == 0 || force == 1) {
1336 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1338 kern_yield(PRI_USER);
1340 * After becoming active to expand above low water, keep
1341 * active until above high water.
1343 force = vspace() < vhiwat;
1347 static struct kproc_desc vnlru_kp = {
1352 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1356 * Routines having to do with the management of the vnode table.
1360 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1361 * before we actually vgone(). This function must be called with the vnode
1362 * held to prevent the vnode from being returned to the free list midway
1366 vtryrecycle(struct vnode *vp)
1370 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1371 VNASSERT(vp->v_holdcnt, vp,
1372 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1374 * This vnode may found and locked via some other list, if so we
1375 * can't recycle it yet.
1377 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1379 "%s: impossible to recycle, vp %p lock is already held",
1381 return (EWOULDBLOCK);
1384 * Don't recycle if its filesystem is being suspended.
1386 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1389 "%s: impossible to recycle, cannot start the write for %p",
1394 * If we got this far, we need to acquire the interlock and see if
1395 * anyone picked up this vnode from another list. If not, we will
1396 * mark it with DOOMED via vgonel() so that anyone who does find it
1397 * will skip over it.
1400 if (vp->v_usecount) {
1403 vn_finished_write(vnmp);
1405 "%s: impossible to recycle, %p is already referenced",
1409 if ((vp->v_iflag & VI_DOOMED) == 0) {
1410 counter_u64_add(recycles_count, 1);
1415 vn_finished_write(vnmp);
1423 if (vspace() < vlowat && vnlruproc_sig == 0) {
1430 * Wait if necessary for space for a new vnode.
1433 getnewvnode_wait(int suspended)
1436 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
1437 if (numvnodes >= desiredvnodes) {
1440 * The file system is being suspended. We cannot
1441 * risk a deadlock here, so allow allocation of
1442 * another vnode even if this would give too many.
1446 if (vnlruproc_sig == 0) {
1447 vnlruproc_sig = 1; /* avoid unnecessary wakeups */
1450 msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
1453 /* Post-adjust like the pre-adjust in getnewvnode(). */
1454 if (numvnodes + 1 > desiredvnodes && freevnodes > 1)
1455 vnlru_free_locked(1, NULL);
1456 return (numvnodes >= desiredvnodes ? ENFILE : 0);
1460 * This hack is fragile, and probably not needed any more now that the
1461 * watermark handling works.
1464 getnewvnode_reserve(u_int count)
1468 /* Pre-adjust like the pre-adjust in getnewvnode(), with any count. */
1469 /* XXX no longer so quick, but this part is not racy. */
1470 mtx_lock(&vnode_free_list_mtx);
1471 if (numvnodes + count > desiredvnodes && freevnodes > wantfreevnodes)
1472 vnlru_free_locked(ulmin(numvnodes + count - desiredvnodes,
1473 freevnodes - wantfreevnodes), NULL);
1474 mtx_unlock(&vnode_free_list_mtx);
1477 /* First try to be quick and racy. */
1478 if (atomic_fetchadd_long(&numvnodes, count) + count <= desiredvnodes) {
1479 td->td_vp_reserv += count;
1480 vcheckspace(); /* XXX no longer so quick, but more racy */
1483 atomic_subtract_long(&numvnodes, count);
1485 mtx_lock(&vnode_free_list_mtx);
1487 if (getnewvnode_wait(0) == 0) {
1490 atomic_add_long(&numvnodes, 1);
1494 mtx_unlock(&vnode_free_list_mtx);
1498 * This hack is fragile, especially if desiredvnodes or wantvnodes are
1499 * misconfgured or changed significantly. Reducing desiredvnodes below
1500 * the reserved amount should cause bizarre behaviour like reducing it
1501 * below the number of active vnodes -- the system will try to reduce
1502 * numvnodes to match, but should fail, so the subtraction below should
1506 getnewvnode_drop_reserve(void)
1511 atomic_subtract_long(&numvnodes, td->td_vp_reserv);
1512 td->td_vp_reserv = 0;
1516 * Return the next vnode from the free list.
1519 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1524 struct lock_object *lo;
1525 static int cyclecount;
1528 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1531 if (td->td_vp_reserv > 0) {
1532 td->td_vp_reserv -= 1;
1535 mtx_lock(&vnode_free_list_mtx);
1536 if (numvnodes < desiredvnodes)
1538 else if (cyclecount++ >= freevnodes) {
1543 * Grow the vnode cache if it will not be above its target max
1544 * after growing. Otherwise, if the free list is nonempty, try
1545 * to reclaim 1 item from it before growing the cache (possibly
1546 * above its target max if the reclamation failed or is delayed).
1547 * Otherwise, wait for some space. In all cases, schedule
1548 * vnlru_proc() if we are getting short of space. The watermarks
1549 * should be chosen so that we never wait or even reclaim from
1550 * the free list to below its target minimum.
1552 if (numvnodes + 1 <= desiredvnodes)
1554 else if (freevnodes > 0)
1555 vnlru_free_locked(1, NULL);
1557 error = getnewvnode_wait(mp != NULL && (mp->mnt_kern_flag &
1559 #if 0 /* XXX Not all VFS_VGET/ffs_vget callers check returns. */
1561 mtx_unlock(&vnode_free_list_mtx);
1567 atomic_add_long(&numvnodes, 1);
1568 mtx_unlock(&vnode_free_list_mtx);
1570 counter_u64_add(vnodes_created, 1);
1571 vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK);
1573 * Locks are given the generic name "vnode" when created.
1574 * Follow the historic practice of using the filesystem
1575 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1577 * Locks live in a witness group keyed on their name. Thus,
1578 * when a lock is renamed, it must also move from the witness
1579 * group of its old name to the witness group of its new name.
1581 * The change only needs to be made when the vnode moves
1582 * from one filesystem type to another. We ensure that each
1583 * filesystem use a single static name pointer for its tag so
1584 * that we can compare pointers rather than doing a strcmp().
1586 lo = &vp->v_vnlock->lock_object;
1587 if (lo->lo_name != tag) {
1589 WITNESS_DESTROY(lo);
1590 WITNESS_INIT(lo, tag);
1593 * By default, don't allow shared locks unless filesystems opt-in.
1595 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1597 * Finalize various vnode identity bits.
1599 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1600 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1601 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1605 v_init_counters(vp);
1606 vp->v_bufobj.bo_ops = &buf_ops_bio;
1608 if (mp == NULL && vops != &dead_vnodeops)
1609 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1613 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1614 mac_vnode_associate_singlelabel(mp, vp);
1617 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1618 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1619 vp->v_vflag |= VV_NOKNOTE;
1623 * For the filesystems which do not use vfs_hash_insert(),
1624 * still initialize v_hash to have vfs_hash_index() useful.
1625 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1628 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1635 * Delete from old mount point vnode list, if on one.
1638 delmntque(struct vnode *vp)
1648 KASSERT(mp->mnt_activevnodelistsize <= mp->mnt_nvnodelistsize,
1649 ("Active vnode list size %d > Vnode list size %d",
1650 mp->mnt_activevnodelistsize, mp->mnt_nvnodelistsize));
1651 active = vp->v_iflag & VI_ACTIVE;
1652 vp->v_iflag &= ~VI_ACTIVE;
1654 mtx_lock(&mp->mnt_listmtx);
1655 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp, v_actfreelist);
1656 mp->mnt_activevnodelistsize--;
1657 mtx_unlock(&mp->mnt_listmtx);
1661 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1662 ("bad mount point vnode list size"));
1663 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1664 mp->mnt_nvnodelistsize--;
1670 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1674 vp->v_op = &dead_vnodeops;
1680 * Insert into list of vnodes for the new mount point, if available.
1683 insmntque1(struct vnode *vp, struct mount *mp,
1684 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1687 KASSERT(vp->v_mount == NULL,
1688 ("insmntque: vnode already on per mount vnode list"));
1689 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1690 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1693 * We acquire the vnode interlock early to ensure that the
1694 * vnode cannot be recycled by another process releasing a
1695 * holdcnt on it before we get it on both the vnode list
1696 * and the active vnode list. The mount mutex protects only
1697 * manipulation of the vnode list and the vnode freelist
1698 * mutex protects only manipulation of the active vnode list.
1699 * Hence the need to hold the vnode interlock throughout.
1703 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1704 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1705 mp->mnt_nvnodelistsize == 0)) &&
1706 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1715 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1716 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1717 ("neg mount point vnode list size"));
1718 mp->mnt_nvnodelistsize++;
1719 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1720 ("Activating already active vnode"));
1721 vp->v_iflag |= VI_ACTIVE;
1722 mtx_lock(&mp->mnt_listmtx);
1723 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
1724 mp->mnt_activevnodelistsize++;
1725 mtx_unlock(&mp->mnt_listmtx);
1732 insmntque(struct vnode *vp, struct mount *mp)
1735 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1739 * Flush out and invalidate all buffers associated with a bufobj
1740 * Called with the underlying object locked.
1743 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1748 if (flags & V_SAVE) {
1749 error = bufobj_wwait(bo, slpflag, slptimeo);
1754 if (bo->bo_dirty.bv_cnt > 0) {
1756 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1759 * XXX We could save a lock/unlock if this was only
1760 * enabled under INVARIANTS
1763 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1764 panic("vinvalbuf: dirty bufs");
1768 * If you alter this loop please notice that interlock is dropped and
1769 * reacquired in flushbuflist. Special care is needed to ensure that
1770 * no race conditions occur from this.
1773 error = flushbuflist(&bo->bo_clean,
1774 flags, bo, slpflag, slptimeo);
1775 if (error == 0 && !(flags & V_CLEANONLY))
1776 error = flushbuflist(&bo->bo_dirty,
1777 flags, bo, slpflag, slptimeo);
1778 if (error != 0 && error != EAGAIN) {
1782 } while (error != 0);
1785 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1786 * have write I/O in-progress but if there is a VM object then the
1787 * VM object can also have read-I/O in-progress.
1790 bufobj_wwait(bo, 0, 0);
1791 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
1793 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
1796 } while (bo->bo_numoutput > 0);
1800 * Destroy the copy in the VM cache, too.
1802 if (bo->bo_object != NULL &&
1803 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1804 VM_OBJECT_WLOCK(bo->bo_object);
1805 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1806 OBJPR_CLEANONLY : 0);
1807 VM_OBJECT_WUNLOCK(bo->bo_object);
1812 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1813 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1814 bo->bo_clean.bv_cnt > 0))
1815 panic("vinvalbuf: flush failed");
1816 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1817 bo->bo_dirty.bv_cnt > 0)
1818 panic("vinvalbuf: flush dirty failed");
1825 * Flush out and invalidate all buffers associated with a vnode.
1826 * Called with the underlying object locked.
1829 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1832 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1833 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1834 if (vp->v_object != NULL && vp->v_object->handle != vp)
1836 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1840 * Flush out buffers on the specified list.
1844 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1847 struct buf *bp, *nbp;
1852 ASSERT_BO_WLOCKED(bo);
1855 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1857 * If we are flushing both V_NORMAL and V_ALT buffers then
1858 * do not skip any buffers. If we are flushing only V_NORMAL
1859 * buffers then skip buffers marked as BX_ALTDATA. If we are
1860 * flushing only V_ALT buffers then skip buffers not marked
1863 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
1864 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
1865 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
1869 lblkno = nbp->b_lblkno;
1870 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
1873 error = BUF_TIMELOCK(bp,
1874 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
1875 "flushbuf", slpflag, slptimeo);
1878 return (error != ENOLCK ? error : EAGAIN);
1880 KASSERT(bp->b_bufobj == bo,
1881 ("bp %p wrong b_bufobj %p should be %p",
1882 bp, bp->b_bufobj, bo));
1884 * XXX Since there are no node locks for NFS, I
1885 * believe there is a slight chance that a delayed
1886 * write will occur while sleeping just above, so
1889 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1892 bp->b_flags |= B_ASYNC;
1895 return (EAGAIN); /* XXX: why not loop ? */
1898 bp->b_flags |= (B_INVAL | B_RELBUF);
1899 bp->b_flags &= ~B_ASYNC;
1904 nbp = gbincore(bo, lblkno);
1905 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1907 break; /* nbp invalid */
1913 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
1919 ASSERT_BO_LOCKED(bo);
1921 for (lblkno = startn;;) {
1923 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
1924 if (bp == NULL || bp->b_lblkno >= endn ||
1925 bp->b_lblkno < startn)
1927 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
1928 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
1931 if (error == ENOLCK)
1935 KASSERT(bp->b_bufobj == bo,
1936 ("bp %p wrong b_bufobj %p should be %p",
1937 bp, bp->b_bufobj, bo));
1938 lblkno = bp->b_lblkno + 1;
1939 if ((bp->b_flags & B_MANAGED) == 0)
1941 bp->b_flags |= B_RELBUF;
1943 * In the VMIO case, use the B_NOREUSE flag to hint that the
1944 * pages backing each buffer in the range are unlikely to be
1945 * reused. Dirty buffers will have the hint applied once
1946 * they've been written.
1948 if ((bp->b_flags & B_VMIO) != 0)
1949 bp->b_flags |= B_NOREUSE;
1957 * Truncate a file's buffer and pages to a specified length. This
1958 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
1962 vtruncbuf(struct vnode *vp, off_t length, int blksize)
1964 struct buf *bp, *nbp;
1968 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
1969 vp, blksize, (uintmax_t)length);
1972 * Round up to the *next* lbn.
1974 startlbn = howmany(length, blksize);
1976 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
1982 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
1987 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1988 if (bp->b_lblkno > 0)
1991 * Since we hold the vnode lock this should only
1992 * fail if we're racing with the buf daemon.
1995 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1996 BO_LOCKPTR(bo)) == ENOLCK)
1997 goto restart_unlocked;
1999 VNASSERT((bp->b_flags & B_DELWRI), vp,
2000 ("buf(%p) on dirty queue without DELWRI", bp));
2009 bufobj_wwait(bo, 0, 0);
2011 vnode_pager_setsize(vp, length);
2017 * Invalidate the cached pages of a file's buffer within the range of block
2018 * numbers [startlbn, endlbn).
2021 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2027 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2029 start = blksize * startlbn;
2030 end = blksize * endlbn;
2034 MPASS(blksize == bo->bo_bsize);
2036 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2040 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2044 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2045 daddr_t startlbn, daddr_t endlbn)
2047 struct buf *bp, *nbp;
2050 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2051 ASSERT_BO_LOCKED(bo);
2055 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2056 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2059 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2060 BO_LOCKPTR(bo)) == ENOLCK) {
2066 bp->b_flags |= B_INVAL | B_RELBUF;
2067 bp->b_flags &= ~B_ASYNC;
2073 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2075 (nbp->b_flags & B_DELWRI) != 0))
2079 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2080 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2083 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2084 BO_LOCKPTR(bo)) == ENOLCK) {
2089 bp->b_flags |= B_INVAL | B_RELBUF;
2090 bp->b_flags &= ~B_ASYNC;
2096 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2097 (nbp->b_vp != vp) ||
2098 (nbp->b_flags & B_DELWRI) == 0))
2106 buf_vlist_remove(struct buf *bp)
2110 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2111 ASSERT_BO_WLOCKED(bp->b_bufobj);
2112 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
2113 (BX_VNDIRTY|BX_VNCLEAN),
2114 ("buf_vlist_remove: Buf %p is on two lists", bp));
2115 if (bp->b_xflags & BX_VNDIRTY)
2116 bv = &bp->b_bufobj->bo_dirty;
2118 bv = &bp->b_bufobj->bo_clean;
2119 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2120 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2122 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2126 * Add the buffer to the sorted clean or dirty block list.
2128 * NOTE: xflags is passed as a constant, optimizing this inline function!
2131 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2137 ASSERT_BO_WLOCKED(bo);
2138 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2139 ("dead bo %p", bo));
2140 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2141 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2142 bp->b_xflags |= xflags;
2143 if (xflags & BX_VNDIRTY)
2149 * Keep the list ordered. Optimize empty list insertion. Assume
2150 * we tend to grow at the tail so lookup_le should usually be cheaper
2153 if (bv->bv_cnt == 0 ||
2154 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2155 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2156 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2157 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2159 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2160 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2162 panic("buf_vlist_add: Preallocated nodes insufficient.");
2167 * Look up a buffer using the buffer tries.
2170 gbincore(struct bufobj *bo, daddr_t lblkno)
2174 ASSERT_BO_LOCKED(bo);
2175 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2178 return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
2182 * Associate a buffer with a vnode.
2185 bgetvp(struct vnode *vp, struct buf *bp)
2190 ASSERT_BO_WLOCKED(bo);
2191 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2193 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2194 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2195 ("bgetvp: bp already attached! %p", bp));
2201 * Insert onto list for new vnode.
2203 buf_vlist_add(bp, bo, BX_VNCLEAN);
2207 * Disassociate a buffer from a vnode.
2210 brelvp(struct buf *bp)
2215 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2216 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2219 * Delete from old vnode list, if on one.
2221 vp = bp->b_vp; /* XXX */
2224 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2225 buf_vlist_remove(bp);
2227 panic("brelvp: Buffer %p not on queue.", bp);
2228 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2229 bo->bo_flag &= ~BO_ONWORKLST;
2230 mtx_lock(&sync_mtx);
2231 LIST_REMOVE(bo, bo_synclist);
2232 syncer_worklist_len--;
2233 mtx_unlock(&sync_mtx);
2236 bp->b_bufobj = NULL;
2242 * Add an item to the syncer work queue.
2245 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2249 ASSERT_BO_WLOCKED(bo);
2251 mtx_lock(&sync_mtx);
2252 if (bo->bo_flag & BO_ONWORKLST)
2253 LIST_REMOVE(bo, bo_synclist);
2255 bo->bo_flag |= BO_ONWORKLST;
2256 syncer_worklist_len++;
2259 if (delay > syncer_maxdelay - 2)
2260 delay = syncer_maxdelay - 2;
2261 slot = (syncer_delayno + delay) & syncer_mask;
2263 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2264 mtx_unlock(&sync_mtx);
2268 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2272 mtx_lock(&sync_mtx);
2273 len = syncer_worklist_len - sync_vnode_count;
2274 mtx_unlock(&sync_mtx);
2275 error = SYSCTL_OUT(req, &len, sizeof(len));
2279 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
2280 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2282 static struct proc *updateproc;
2283 static void sched_sync(void);
2284 static struct kproc_desc up_kp = {
2289 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2292 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2297 *bo = LIST_FIRST(slp);
2301 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2304 * We use vhold in case the vnode does not
2305 * successfully sync. vhold prevents the vnode from
2306 * going away when we unlock the sync_mtx so that
2307 * we can acquire the vnode interlock.
2310 mtx_unlock(&sync_mtx);
2312 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2314 mtx_lock(&sync_mtx);
2315 return (*bo == LIST_FIRST(slp));
2317 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2318 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2320 vn_finished_write(mp);
2322 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2324 * Put us back on the worklist. The worklist
2325 * routine will remove us from our current
2326 * position and then add us back in at a later
2329 vn_syncer_add_to_worklist(*bo, syncdelay);
2333 mtx_lock(&sync_mtx);
2337 static int first_printf = 1;
2340 * System filesystem synchronizer daemon.
2345 struct synclist *next, *slp;
2348 struct thread *td = curthread;
2350 int net_worklist_len;
2351 int syncer_final_iter;
2355 syncer_final_iter = 0;
2356 syncer_state = SYNCER_RUNNING;
2357 starttime = time_uptime;
2358 td->td_pflags |= TDP_NORUNNINGBUF;
2360 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2363 mtx_lock(&sync_mtx);
2365 if (syncer_state == SYNCER_FINAL_DELAY &&
2366 syncer_final_iter == 0) {
2367 mtx_unlock(&sync_mtx);
2368 kproc_suspend_check(td->td_proc);
2369 mtx_lock(&sync_mtx);
2371 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2372 if (syncer_state != SYNCER_RUNNING &&
2373 starttime != time_uptime) {
2375 printf("\nSyncing disks, vnodes remaining... ");
2378 printf("%d ", net_worklist_len);
2380 starttime = time_uptime;
2383 * Push files whose dirty time has expired. Be careful
2384 * of interrupt race on slp queue.
2386 * Skip over empty worklist slots when shutting down.
2389 slp = &syncer_workitem_pending[syncer_delayno];
2390 syncer_delayno += 1;
2391 if (syncer_delayno == syncer_maxdelay)
2393 next = &syncer_workitem_pending[syncer_delayno];
2395 * If the worklist has wrapped since the
2396 * it was emptied of all but syncer vnodes,
2397 * switch to the FINAL_DELAY state and run
2398 * for one more second.
2400 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2401 net_worklist_len == 0 &&
2402 last_work_seen == syncer_delayno) {
2403 syncer_state = SYNCER_FINAL_DELAY;
2404 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2406 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2407 syncer_worklist_len > 0);
2410 * Keep track of the last time there was anything
2411 * on the worklist other than syncer vnodes.
2412 * Return to the SHUTTING_DOWN state if any
2415 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2416 last_work_seen = syncer_delayno;
2417 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2418 syncer_state = SYNCER_SHUTTING_DOWN;
2419 while (!LIST_EMPTY(slp)) {
2420 error = sync_vnode(slp, &bo, td);
2422 LIST_REMOVE(bo, bo_synclist);
2423 LIST_INSERT_HEAD(next, bo, bo_synclist);
2427 if (first_printf == 0) {
2429 * Drop the sync mutex, because some watchdog
2430 * drivers need to sleep while patting
2432 mtx_unlock(&sync_mtx);
2433 wdog_kern_pat(WD_LASTVAL);
2434 mtx_lock(&sync_mtx);
2438 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2439 syncer_final_iter--;
2441 * The variable rushjob allows the kernel to speed up the
2442 * processing of the filesystem syncer process. A rushjob
2443 * value of N tells the filesystem syncer to process the next
2444 * N seconds worth of work on its queue ASAP. Currently rushjob
2445 * is used by the soft update code to speed up the filesystem
2446 * syncer process when the incore state is getting so far
2447 * ahead of the disk that the kernel memory pool is being
2448 * threatened with exhaustion.
2455 * Just sleep for a short period of time between
2456 * iterations when shutting down to allow some I/O
2459 * If it has taken us less than a second to process the
2460 * current work, then wait. Otherwise start right over
2461 * again. We can still lose time if any single round
2462 * takes more than two seconds, but it does not really
2463 * matter as we are just trying to generally pace the
2464 * filesystem activity.
2466 if (syncer_state != SYNCER_RUNNING ||
2467 time_uptime == starttime) {
2469 sched_prio(td, PPAUSE);
2472 if (syncer_state != SYNCER_RUNNING)
2473 cv_timedwait(&sync_wakeup, &sync_mtx,
2474 hz / SYNCER_SHUTDOWN_SPEEDUP);
2475 else if (time_uptime == starttime)
2476 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2481 * Request the syncer daemon to speed up its work.
2482 * We never push it to speed up more than half of its
2483 * normal turn time, otherwise it could take over the cpu.
2486 speedup_syncer(void)
2490 mtx_lock(&sync_mtx);
2491 if (rushjob < syncdelay / 2) {
2493 stat_rush_requests += 1;
2496 mtx_unlock(&sync_mtx);
2497 cv_broadcast(&sync_wakeup);
2502 * Tell the syncer to speed up its work and run though its work
2503 * list several times, then tell it to shut down.
2506 syncer_shutdown(void *arg, int howto)
2509 if (howto & RB_NOSYNC)
2511 mtx_lock(&sync_mtx);
2512 syncer_state = SYNCER_SHUTTING_DOWN;
2514 mtx_unlock(&sync_mtx);
2515 cv_broadcast(&sync_wakeup);
2516 kproc_shutdown(arg, howto);
2520 syncer_suspend(void)
2523 syncer_shutdown(updateproc, 0);
2530 mtx_lock(&sync_mtx);
2532 syncer_state = SYNCER_RUNNING;
2533 mtx_unlock(&sync_mtx);
2534 cv_broadcast(&sync_wakeup);
2535 kproc_resume(updateproc);
2539 * Reassign a buffer from one vnode to another.
2540 * Used to assign file specific control information
2541 * (indirect blocks) to the vnode to which they belong.
2544 reassignbuf(struct buf *bp)
2557 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2558 bp, bp->b_vp, bp->b_flags);
2560 * B_PAGING flagged buffers cannot be reassigned because their vp
2561 * is not fully linked in.
2563 if (bp->b_flags & B_PAGING)
2564 panic("cannot reassign paging buffer");
2567 * Delete from old vnode list, if on one.
2570 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2571 buf_vlist_remove(bp);
2573 panic("reassignbuf: Buffer %p not on queue.", bp);
2575 * If dirty, put on list of dirty buffers; otherwise insert onto list
2578 if (bp->b_flags & B_DELWRI) {
2579 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2580 switch (vp->v_type) {
2590 vn_syncer_add_to_worklist(bo, delay);
2592 buf_vlist_add(bp, bo, BX_VNDIRTY);
2594 buf_vlist_add(bp, bo, BX_VNCLEAN);
2596 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2597 mtx_lock(&sync_mtx);
2598 LIST_REMOVE(bo, bo_synclist);
2599 syncer_worklist_len--;
2600 mtx_unlock(&sync_mtx);
2601 bo->bo_flag &= ~BO_ONWORKLST;
2606 bp = TAILQ_FIRST(&bv->bv_hd);
2607 KASSERT(bp == NULL || bp->b_bufobj == bo,
2608 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2609 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2610 KASSERT(bp == NULL || bp->b_bufobj == bo,
2611 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2613 bp = TAILQ_FIRST(&bv->bv_hd);
2614 KASSERT(bp == NULL || bp->b_bufobj == bo,
2615 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2616 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2617 KASSERT(bp == NULL || bp->b_bufobj == bo,
2618 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2624 v_init_counters(struct vnode *vp)
2627 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2628 vp, ("%s called for an initialized vnode", __FUNCTION__));
2629 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2631 refcount_init(&vp->v_holdcnt, 1);
2632 refcount_init(&vp->v_usecount, 1);
2636 v_incr_usecount_locked(struct vnode *vp)
2639 ASSERT_VI_LOCKED(vp, __func__);
2640 if ((vp->v_iflag & VI_OWEINACT) != 0) {
2641 VNASSERT(vp->v_usecount == 0, vp,
2642 ("vnode with usecount and VI_OWEINACT set"));
2643 vp->v_iflag &= ~VI_OWEINACT;
2645 refcount_acquire(&vp->v_usecount);
2646 v_incr_devcount(vp);
2650 * Increment the use count on the vnode, taking care to reference
2651 * the driver's usecount if this is a chardev.
2654 v_incr_usecount(struct vnode *vp)
2657 ASSERT_VI_UNLOCKED(vp, __func__);
2658 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2660 if (vp->v_type != VCHR &&
2661 refcount_acquire_if_not_zero(&vp->v_usecount)) {
2662 VNODE_REFCOUNT_FENCE_ACQ();
2663 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2664 ("vnode with usecount and VI_OWEINACT set"));
2667 v_incr_usecount_locked(vp);
2673 * Increment si_usecount of the associated device, if any.
2676 v_incr_devcount(struct vnode *vp)
2679 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2680 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2682 vp->v_rdev->si_usecount++;
2688 * Decrement si_usecount of the associated device, if any.
2691 v_decr_devcount(struct vnode *vp)
2694 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2695 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2697 vp->v_rdev->si_usecount--;
2703 * Grab a particular vnode from the free list, increment its
2704 * reference count and lock it. VI_DOOMED is set if the vnode
2705 * is being destroyed. Only callers who specify LK_RETRY will
2706 * see doomed vnodes. If inactive processing was delayed in
2707 * vput try to do it here.
2709 * Notes on lockless counter manipulation:
2710 * _vhold, vputx and other routines make various decisions based
2711 * on either holdcnt or usecount being 0. As long as either counter
2712 * is not transitioning 0->1 nor 1->0, the manipulation can be done
2713 * with atomic operations. Otherwise the interlock is taken covering
2714 * both the atomic and additional actions.
2717 vget(struct vnode *vp, int flags, struct thread *td)
2719 int error, oweinact;
2721 VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2722 ("vget: invalid lock operation"));
2724 if ((flags & LK_INTERLOCK) != 0)
2725 ASSERT_VI_LOCKED(vp, __func__);
2727 ASSERT_VI_UNLOCKED(vp, __func__);
2728 if ((flags & LK_VNHELD) != 0)
2729 VNASSERT((vp->v_holdcnt > 0), vp,
2730 ("vget: LK_VNHELD passed but vnode not held"));
2732 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2734 if ((flags & LK_VNHELD) == 0)
2735 _vhold(vp, (flags & LK_INTERLOCK) != 0);
2737 if ((error = vn_lock(vp, flags)) != 0) {
2739 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2743 if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0)
2744 panic("vget: vn_lock failed to return ENOENT\n");
2746 * We don't guarantee that any particular close will
2747 * trigger inactive processing so just make a best effort
2748 * here at preventing a reference to a removed file. If
2749 * we don't succeed no harm is done.
2751 * Upgrade our holdcnt to a usecount.
2753 if (vp->v_type == VCHR ||
2754 !refcount_acquire_if_not_zero(&vp->v_usecount)) {
2756 if ((vp->v_iflag & VI_OWEINACT) == 0) {
2760 vp->v_iflag &= ~VI_OWEINACT;
2761 VNODE_REFCOUNT_FENCE_REL();
2763 refcount_acquire(&vp->v_usecount);
2764 v_incr_devcount(vp);
2765 if (oweinact && VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2766 (flags & LK_NOWAIT) == 0)
2774 * Increase the reference (use) and hold count of a vnode.
2775 * This will also remove the vnode from the free list if it is presently free.
2778 vref(struct vnode *vp)
2781 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2783 v_incr_usecount(vp);
2787 vrefl(struct vnode *vp)
2790 ASSERT_VI_LOCKED(vp, __func__);
2791 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2793 v_incr_usecount_locked(vp);
2797 vrefact(struct vnode *vp)
2800 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2801 if (__predict_false(vp->v_type == VCHR)) {
2802 VNASSERT(vp->v_holdcnt > 0 && vp->v_usecount > 0, vp,
2803 ("%s: wrong ref counts", __func__));
2808 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
2809 VNASSERT(old > 0, vp, ("%s: wrong hold count", __func__));
2810 old = atomic_fetchadd_int(&vp->v_usecount, 1);
2811 VNASSERT(old > 0, vp, ("%s: wrong use count", __func__));
2813 refcount_acquire(&vp->v_holdcnt);
2814 refcount_acquire(&vp->v_usecount);
2819 * Return reference count of a vnode.
2821 * The results of this call are only guaranteed when some mechanism is used to
2822 * stop other processes from gaining references to the vnode. This may be the
2823 * case if the caller holds the only reference. This is also useful when stale
2824 * data is acceptable as race conditions may be accounted for by some other
2828 vrefcnt(struct vnode *vp)
2831 return (vp->v_usecount);
2834 #define VPUTX_VRELE 1
2835 #define VPUTX_VPUT 2
2836 #define VPUTX_VUNREF 3
2839 * Decrement the use and hold counts for a vnode.
2841 * See an explanation near vget() as to why atomic operation is safe.
2844 vputx(struct vnode *vp, int func)
2848 KASSERT(vp != NULL, ("vputx: null vp"));
2849 if (func == VPUTX_VUNREF)
2850 ASSERT_VOP_LOCKED(vp, "vunref");
2851 else if (func == VPUTX_VPUT)
2852 ASSERT_VOP_LOCKED(vp, "vput");
2854 KASSERT(func == VPUTX_VRELE, ("vputx: wrong func"));
2855 ASSERT_VI_UNLOCKED(vp, __func__);
2856 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2858 if (vp->v_type != VCHR &&
2859 refcount_release_if_not_last(&vp->v_usecount)) {
2860 if (func == VPUTX_VPUT)
2869 * We want to hold the vnode until the inactive finishes to
2870 * prevent vgone() races. We drop the use count here and the
2871 * hold count below when we're done.
2873 if (!refcount_release(&vp->v_usecount) ||
2874 (vp->v_iflag & VI_DOINGINACT)) {
2875 if (func == VPUTX_VPUT)
2877 v_decr_devcount(vp);
2882 v_decr_devcount(vp);
2886 if (vp->v_usecount != 0) {
2887 vn_printf(vp, "vputx: usecount not zero for vnode ");
2888 panic("vputx: usecount not zero");
2891 CTR2(KTR_VFS, "%s: return vnode %p to the freelist", __func__, vp);
2894 * We must call VOP_INACTIVE with the node locked. Mark
2895 * as VI_DOINGINACT to avoid recursion.
2897 vp->v_iflag |= VI_OWEINACT;
2900 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
2904 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2905 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
2911 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2912 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
2917 VNASSERT(vp->v_usecount == 0 || (vp->v_iflag & VI_OWEINACT) == 0, vp,
2918 ("vnode with usecount and VI_OWEINACT set"));
2920 if (vp->v_iflag & VI_OWEINACT)
2921 vinactive(vp, curthread);
2922 if (func != VPUTX_VUNREF)
2929 * Vnode put/release.
2930 * If count drops to zero, call inactive routine and return to freelist.
2933 vrele(struct vnode *vp)
2936 vputx(vp, VPUTX_VRELE);
2940 * Release an already locked vnode. This give the same effects as
2941 * unlock+vrele(), but takes less time and avoids releasing and
2942 * re-aquiring the lock (as vrele() acquires the lock internally.)
2945 vput(struct vnode *vp)
2948 vputx(vp, VPUTX_VPUT);
2952 * Release an exclusively locked vnode. Do not unlock the vnode lock.
2955 vunref(struct vnode *vp)
2958 vputx(vp, VPUTX_VUNREF);
2962 * Increase the hold count and activate if this is the first reference.
2965 _vhold(struct vnode *vp, bool locked)
2970 ASSERT_VI_LOCKED(vp, __func__);
2972 ASSERT_VI_UNLOCKED(vp, __func__);
2973 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2975 if (refcount_acquire_if_not_zero(&vp->v_holdcnt)) {
2976 VNODE_REFCOUNT_FENCE_ACQ();
2977 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2978 ("_vhold: vnode with holdcnt is free"));
2983 if ((vp->v_iflag & VI_FREE) == 0) {
2984 refcount_acquire(&vp->v_holdcnt);
2989 VNASSERT(vp->v_holdcnt == 0, vp,
2990 ("%s: wrong hold count", __func__));
2991 VNASSERT(vp->v_op != NULL, vp,
2992 ("%s: vnode already reclaimed.", __func__));
2994 * Remove a vnode from the free list, mark it as in use,
2995 * and put it on the active list.
2997 VNASSERT(vp->v_mount != NULL, vp,
2998 ("_vhold: vnode not on per mount vnode list"));
3000 mtx_lock(&mp->mnt_listmtx);
3001 if ((vp->v_mflag & VMP_TMPMNTFREELIST) != 0) {
3002 TAILQ_REMOVE(&mp->mnt_tmpfreevnodelist, vp, v_actfreelist);
3003 mp->mnt_tmpfreevnodelistsize--;
3004 vp->v_mflag &= ~VMP_TMPMNTFREELIST;
3006 mtx_lock(&vnode_free_list_mtx);
3007 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
3009 mtx_unlock(&vnode_free_list_mtx);
3011 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
3012 ("Activating already active vnode"));
3013 vp->v_iflag &= ~VI_FREE;
3014 vp->v_iflag |= VI_ACTIVE;
3015 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
3016 mp->mnt_activevnodelistsize++;
3017 mtx_unlock(&mp->mnt_listmtx);
3018 refcount_acquire(&vp->v_holdcnt);
3024 vholdnz(struct vnode *vp)
3027 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3029 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3030 VNASSERT(old > 0, vp, ("%s: wrong hold count", __func__));
3032 atomic_add_int(&vp->v_holdcnt, 1);
3037 * Drop the hold count of the vnode. If this is the last reference to
3038 * the vnode we place it on the free list unless it has been vgone'd
3039 * (marked VI_DOOMED) in which case we will free it.
3041 * Because the vnode vm object keeps a hold reference on the vnode if
3042 * there is at least one resident non-cached page, the vnode cannot
3043 * leave the active list without the page cleanup done.
3046 _vdrop(struct vnode *vp, bool locked)
3053 ASSERT_VI_LOCKED(vp, __func__);
3055 ASSERT_VI_UNLOCKED(vp, __func__);
3056 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3057 if ((int)vp->v_holdcnt <= 0)
3058 panic("vdrop: holdcnt %d", vp->v_holdcnt);
3060 if (refcount_release_if_not_last(&vp->v_holdcnt))
3064 if (refcount_release(&vp->v_holdcnt) == 0) {
3068 if ((vp->v_iflag & VI_DOOMED) == 0) {
3070 * Mark a vnode as free: remove it from its active list
3071 * and put it up for recycling on the freelist.
3073 VNASSERT(vp->v_op != NULL, vp,
3074 ("vdropl: vnode already reclaimed."));
3075 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
3076 ("vnode already free"));
3077 VNASSERT(vp->v_holdcnt == 0, vp,
3078 ("vdropl: freeing when we shouldn't"));
3079 active = vp->v_iflag & VI_ACTIVE;
3080 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3081 vp->v_iflag &= ~VI_ACTIVE;
3084 mtx_lock(&mp->mnt_listmtx);
3086 TAILQ_REMOVE(&mp->mnt_activevnodelist,
3088 mp->mnt_activevnodelistsize--;
3090 TAILQ_INSERT_TAIL(&mp->mnt_tmpfreevnodelist,
3092 mp->mnt_tmpfreevnodelistsize++;
3093 vp->v_iflag |= VI_FREE;
3094 vp->v_mflag |= VMP_TMPMNTFREELIST;
3096 if (mp->mnt_tmpfreevnodelistsize >=
3097 mnt_free_list_batch)
3098 vnlru_return_batch_locked(mp);
3099 mtx_unlock(&mp->mnt_listmtx);
3101 VNASSERT(active == 0, vp,
3102 ("vdropl: active vnode not on per mount "
3104 mtx_lock(&vnode_free_list_mtx);
3105 TAILQ_INSERT_TAIL(&vnode_free_list, vp,
3108 vp->v_iflag |= VI_FREE;
3110 mtx_unlock(&vnode_free_list_mtx);
3114 counter_u64_add(free_owe_inact, 1);
3119 * The vnode has been marked for destruction, so free it.
3121 * The vnode will be returned to the zone where it will
3122 * normally remain until it is needed for another vnode. We
3123 * need to cleanup (or verify that the cleanup has already
3124 * been done) any residual data left from its current use
3125 * so as not to contaminate the freshly allocated vnode.
3127 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
3128 atomic_subtract_long(&numvnodes, 1);
3130 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
3131 ("cleaned vnode still on the free list."));
3132 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
3133 VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
3134 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
3135 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
3136 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
3137 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
3138 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
3139 ("clean blk trie not empty"));
3140 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
3141 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
3142 ("dirty blk trie not empty"));
3143 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
3144 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
3145 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
3146 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
3147 ("Dangling rangelock waiters"));
3150 mac_vnode_destroy(vp);
3152 if (vp->v_pollinfo != NULL) {
3153 destroy_vpollinfo(vp->v_pollinfo);
3154 vp->v_pollinfo = NULL;
3157 /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
3160 vp->v_mountedhere = NULL;
3163 vp->v_fifoinfo = NULL;
3164 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
3168 uma_zfree(vnode_zone, vp);
3172 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3173 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3174 * OWEINACT tracks whether a vnode missed a call to inactive due to a
3175 * failed lock upgrade.
3178 vinactive(struct vnode *vp, struct thread *td)
3180 struct vm_object *obj;
3182 ASSERT_VOP_ELOCKED(vp, "vinactive");
3183 ASSERT_VI_LOCKED(vp, "vinactive");
3184 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3185 ("vinactive: recursed on VI_DOINGINACT"));
3186 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3187 vp->v_iflag |= VI_DOINGINACT;
3188 vp->v_iflag &= ~VI_OWEINACT;
3191 * Before moving off the active list, we must be sure that any
3192 * modified pages are converted into the vnode's dirty
3193 * buffers, since these will no longer be checked once the
3194 * vnode is on the inactive list.
3196 * The write-out of the dirty pages is asynchronous. At the
3197 * point that VOP_INACTIVE() is called, there could still be
3198 * pending I/O and dirty pages in the object.
3200 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3201 (obj->flags & OBJ_MIGHTBEDIRTY) != 0) {
3202 VM_OBJECT_WLOCK(obj);
3203 vm_object_page_clean(obj, 0, 0, 0);
3204 VM_OBJECT_WUNLOCK(obj);
3206 VOP_INACTIVE(vp, td);
3208 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3209 ("vinactive: lost VI_DOINGINACT"));
3210 vp->v_iflag &= ~VI_DOINGINACT;
3214 * Remove any vnodes in the vnode table belonging to mount point mp.
3216 * If FORCECLOSE is not specified, there should not be any active ones,
3217 * return error if any are found (nb: this is a user error, not a
3218 * system error). If FORCECLOSE is specified, detach any active vnodes
3221 * If WRITECLOSE is set, only flush out regular file vnodes open for
3224 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3226 * `rootrefs' specifies the base reference count for the root vnode
3227 * of this filesystem. The root vnode is considered busy if its
3228 * v_usecount exceeds this value. On a successful return, vflush(, td)
3229 * will call vrele() on the root vnode exactly rootrefs times.
3230 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3234 static int busyprt = 0; /* print out busy vnodes */
3235 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3239 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3241 struct vnode *vp, *mvp, *rootvp = NULL;
3243 int busy = 0, error;
3245 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3248 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3249 ("vflush: bad args"));
3251 * Get the filesystem root vnode. We can vput() it
3252 * immediately, since with rootrefs > 0, it won't go away.
3254 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3255 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3262 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3264 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3267 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3271 * Skip over a vnodes marked VV_SYSTEM.
3273 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3279 * If WRITECLOSE is set, flush out unlinked but still open
3280 * files (even if open only for reading) and regular file
3281 * vnodes open for writing.
3283 if (flags & WRITECLOSE) {
3284 if (vp->v_object != NULL) {
3285 VM_OBJECT_WLOCK(vp->v_object);
3286 vm_object_page_clean(vp->v_object, 0, 0, 0);
3287 VM_OBJECT_WUNLOCK(vp->v_object);
3289 error = VOP_FSYNC(vp, MNT_WAIT, td);
3293 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3296 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3299 if ((vp->v_type == VNON ||
3300 (error == 0 && vattr.va_nlink > 0)) &&
3301 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3309 * With v_usecount == 0, all we need to do is clear out the
3310 * vnode data structures and we are done.
3312 * If FORCECLOSE is set, forcibly close the vnode.
3314 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3320 vn_printf(vp, "vflush: busy vnode ");
3326 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3328 * If just the root vnode is busy, and if its refcount
3329 * is equal to `rootrefs', then go ahead and kill it.
3332 KASSERT(busy > 0, ("vflush: not busy"));
3333 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3334 ("vflush: usecount %d < rootrefs %d",
3335 rootvp->v_usecount, rootrefs));
3336 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3337 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3339 VOP_UNLOCK(rootvp, 0);
3345 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3349 for (; rootrefs > 0; rootrefs--)
3355 * Recycle an unused vnode to the front of the free list.
3358 vrecycle(struct vnode *vp)
3363 recycled = vrecyclel(vp);
3369 * vrecycle, with the vp interlock held.
3372 vrecyclel(struct vnode *vp)
3376 ASSERT_VOP_ELOCKED(vp, __func__);
3377 ASSERT_VI_LOCKED(vp, __func__);
3378 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3380 if (vp->v_usecount == 0) {
3388 * Eliminate all activity associated with a vnode
3389 * in preparation for reuse.
3392 vgone(struct vnode *vp)
3400 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3401 struct vnode *lowervp __unused)
3406 * Notify upper mounts about reclaimed or unlinked vnode.
3409 vfs_notify_upper(struct vnode *vp, int event)
3411 static struct vfsops vgonel_vfsops = {
3412 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3413 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3415 struct mount *mp, *ump, *mmp;
3422 if (TAILQ_EMPTY(&mp->mnt_uppers))
3425 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3426 mmp->mnt_op = &vgonel_vfsops;
3427 mmp->mnt_kern_flag |= MNTK_MARKER;
3429 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3430 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3431 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3432 ump = TAILQ_NEXT(ump, mnt_upper_link);
3435 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3438 case VFS_NOTIFY_UPPER_RECLAIM:
3439 VFS_RECLAIM_LOWERVP(ump, vp);
3441 case VFS_NOTIFY_UPPER_UNLINK:
3442 VFS_UNLINK_LOWERVP(ump, vp);
3445 KASSERT(0, ("invalid event %d", event));
3449 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3450 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3453 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3454 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3455 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3456 wakeup(&mp->mnt_uppers);
3463 * vgone, with the vp interlock held.
3466 vgonel(struct vnode *vp)
3473 ASSERT_VOP_ELOCKED(vp, "vgonel");
3474 ASSERT_VI_LOCKED(vp, "vgonel");
3475 VNASSERT(vp->v_holdcnt, vp,
3476 ("vgonel: vp %p has no reference.", vp));
3477 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3481 * Don't vgonel if we're already doomed.
3483 if (vp->v_iflag & VI_DOOMED)
3485 vp->v_iflag |= VI_DOOMED;
3488 * Check to see if the vnode is in use. If so, we have to call
3489 * VOP_CLOSE() and VOP_INACTIVE().
3491 active = vp->v_usecount;
3492 oweinact = (vp->v_iflag & VI_OWEINACT);
3494 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
3497 * If purging an active vnode, it must be closed and
3498 * deactivated before being reclaimed.
3501 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
3502 if (oweinact || active) {
3504 if ((vp->v_iflag & VI_DOINGINACT) == 0)
3508 if (vp->v_type == VSOCK)
3509 vfs_unp_reclaim(vp);
3512 * Clean out any buffers associated with the vnode.
3513 * If the flush fails, just toss the buffers.
3516 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
3517 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
3518 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
3519 while (vinvalbuf(vp, 0, 0, 0) != 0)
3523 BO_LOCK(&vp->v_bufobj);
3524 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
3525 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
3526 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
3527 vp->v_bufobj.bo_clean.bv_cnt == 0,
3528 ("vp %p bufobj not invalidated", vp));
3531 * For VMIO bufobj, BO_DEAD is set in vm_object_terminate()
3532 * after the object's page queue is flushed.
3534 if (vp->v_bufobj.bo_object == NULL)
3535 vp->v_bufobj.bo_flag |= BO_DEAD;
3536 BO_UNLOCK(&vp->v_bufobj);
3539 * Reclaim the vnode.
3541 if (VOP_RECLAIM(vp, td))
3542 panic("vgone: cannot reclaim");
3544 vn_finished_secondary_write(mp);
3545 VNASSERT(vp->v_object == NULL, vp,
3546 ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
3548 * Clear the advisory locks and wake up waiting threads.
3550 (void)VOP_ADVLOCKPURGE(vp);
3553 * Delete from old mount point vnode list.
3558 * Done with purge, reset to the standard lock and invalidate
3562 vp->v_vnlock = &vp->v_lock;
3563 vp->v_op = &dead_vnodeops;
3569 * Calculate the total number of references to a special device.
3572 vcount(struct vnode *vp)
3577 count = vp->v_rdev->si_usecount;
3583 * Same as above, but using the struct cdev *as argument
3586 count_dev(struct cdev *dev)
3591 count = dev->si_usecount;
3597 * Print out a description of a vnode.
3599 static char *typename[] =
3600 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
3604 vn_printf(struct vnode *vp, const char *fmt, ...)
3607 char buf[256], buf2[16];
3613 printf("%p: ", (void *)vp);
3614 printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
3615 printf(" usecount %d, writecount %d, refcount %d",
3616 vp->v_usecount, vp->v_writecount, vp->v_holdcnt);
3617 switch (vp->v_type) {
3619 printf(" mountedhere %p\n", vp->v_mountedhere);
3622 printf(" rdev %p\n", vp->v_rdev);
3625 printf(" socket %p\n", vp->v_unpcb);
3628 printf(" fifoinfo %p\n", vp->v_fifoinfo);
3636 if (vp->v_vflag & VV_ROOT)
3637 strlcat(buf, "|VV_ROOT", sizeof(buf));
3638 if (vp->v_vflag & VV_ISTTY)
3639 strlcat(buf, "|VV_ISTTY", sizeof(buf));
3640 if (vp->v_vflag & VV_NOSYNC)
3641 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
3642 if (vp->v_vflag & VV_ETERNALDEV)
3643 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
3644 if (vp->v_vflag & VV_CACHEDLABEL)
3645 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
3646 if (vp->v_vflag & VV_COPYONWRITE)
3647 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
3648 if (vp->v_vflag & VV_SYSTEM)
3649 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
3650 if (vp->v_vflag & VV_PROCDEP)
3651 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
3652 if (vp->v_vflag & VV_NOKNOTE)
3653 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
3654 if (vp->v_vflag & VV_DELETED)
3655 strlcat(buf, "|VV_DELETED", sizeof(buf));
3656 if (vp->v_vflag & VV_MD)
3657 strlcat(buf, "|VV_MD", sizeof(buf));
3658 if (vp->v_vflag & VV_FORCEINSMQ)
3659 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
3660 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
3661 VV_CACHEDLABEL | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
3662 VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
3664 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
3665 strlcat(buf, buf2, sizeof(buf));
3667 if (vp->v_iflag & VI_MOUNT)
3668 strlcat(buf, "|VI_MOUNT", sizeof(buf));
3669 if (vp->v_iflag & VI_DOOMED)
3670 strlcat(buf, "|VI_DOOMED", sizeof(buf));
3671 if (vp->v_iflag & VI_FREE)
3672 strlcat(buf, "|VI_FREE", sizeof(buf));
3673 if (vp->v_iflag & VI_ACTIVE)
3674 strlcat(buf, "|VI_ACTIVE", sizeof(buf));
3675 if (vp->v_iflag & VI_DOINGINACT)
3676 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
3677 if (vp->v_iflag & VI_OWEINACT)
3678 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
3679 flags = vp->v_iflag & ~(VI_MOUNT | VI_DOOMED | VI_FREE |
3680 VI_ACTIVE | VI_DOINGINACT | VI_OWEINACT);
3682 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
3683 strlcat(buf, buf2, sizeof(buf));
3685 printf(" flags (%s)\n", buf + 1);
3686 if (mtx_owned(VI_MTX(vp)))
3687 printf(" VI_LOCKed");
3688 if (vp->v_object != NULL)
3689 printf(" v_object %p ref %d pages %d "
3690 "cleanbuf %d dirtybuf %d\n",
3691 vp->v_object, vp->v_object->ref_count,
3692 vp->v_object->resident_page_count,
3693 vp->v_bufobj.bo_clean.bv_cnt,
3694 vp->v_bufobj.bo_dirty.bv_cnt);
3696 lockmgr_printinfo(vp->v_vnlock);
3697 if (vp->v_data != NULL)
3703 * List all of the locked vnodes in the system.
3704 * Called when debugging the kernel.
3706 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
3712 * Note: because this is DDB, we can't obey the locking semantics
3713 * for these structures, which means we could catch an inconsistent
3714 * state and dereference a nasty pointer. Not much to be done
3717 db_printf("Locked vnodes\n");
3718 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3719 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3720 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
3721 vn_printf(vp, "vnode ");
3727 * Show details about the given vnode.
3729 DB_SHOW_COMMAND(vnode, db_show_vnode)
3735 vp = (struct vnode *)addr;
3736 vn_printf(vp, "vnode ");
3740 * Show details about the given mount point.
3742 DB_SHOW_COMMAND(mount, db_show_mount)
3753 /* No address given, print short info about all mount points. */
3754 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3755 db_printf("%p %s on %s (%s)\n", mp,
3756 mp->mnt_stat.f_mntfromname,
3757 mp->mnt_stat.f_mntonname,
3758 mp->mnt_stat.f_fstypename);
3762 db_printf("\nMore info: show mount <addr>\n");
3766 mp = (struct mount *)addr;
3767 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
3768 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
3771 mflags = mp->mnt_flag;
3772 #define MNT_FLAG(flag) do { \
3773 if (mflags & (flag)) { \
3774 if (buf[0] != '\0') \
3775 strlcat(buf, ", ", sizeof(buf)); \
3776 strlcat(buf, (#flag) + 4, sizeof(buf)); \
3777 mflags &= ~(flag); \
3780 MNT_FLAG(MNT_RDONLY);
3781 MNT_FLAG(MNT_SYNCHRONOUS);
3782 MNT_FLAG(MNT_NOEXEC);
3783 MNT_FLAG(MNT_NOSUID);
3784 MNT_FLAG(MNT_NFS4ACLS);
3785 MNT_FLAG(MNT_UNION);
3786 MNT_FLAG(MNT_ASYNC);
3787 MNT_FLAG(MNT_SUIDDIR);
3788 MNT_FLAG(MNT_SOFTDEP);
3789 MNT_FLAG(MNT_NOSYMFOLLOW);
3790 MNT_FLAG(MNT_GJOURNAL);
3791 MNT_FLAG(MNT_MULTILABEL);
3793 MNT_FLAG(MNT_NOATIME);
3794 MNT_FLAG(MNT_NOCLUSTERR);
3795 MNT_FLAG(MNT_NOCLUSTERW);
3797 MNT_FLAG(MNT_EXRDONLY);
3798 MNT_FLAG(MNT_EXPORTED);
3799 MNT_FLAG(MNT_DEFEXPORTED);
3800 MNT_FLAG(MNT_EXPORTANON);
3801 MNT_FLAG(MNT_EXKERB);
3802 MNT_FLAG(MNT_EXPUBLIC);
3803 MNT_FLAG(MNT_LOCAL);
3804 MNT_FLAG(MNT_QUOTA);
3805 MNT_FLAG(MNT_ROOTFS);
3807 MNT_FLAG(MNT_IGNORE);
3808 MNT_FLAG(MNT_UPDATE);
3809 MNT_FLAG(MNT_DELEXPORT);
3810 MNT_FLAG(MNT_RELOAD);
3811 MNT_FLAG(MNT_FORCE);
3812 MNT_FLAG(MNT_SNAPSHOT);
3813 MNT_FLAG(MNT_BYFSID);
3817 strlcat(buf, ", ", sizeof(buf));
3818 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3819 "0x%016jx", mflags);
3821 db_printf(" mnt_flag = %s\n", buf);
3824 flags = mp->mnt_kern_flag;
3825 #define MNT_KERN_FLAG(flag) do { \
3826 if (flags & (flag)) { \
3827 if (buf[0] != '\0') \
3828 strlcat(buf, ", ", sizeof(buf)); \
3829 strlcat(buf, (#flag) + 5, sizeof(buf)); \
3833 MNT_KERN_FLAG(MNTK_UNMOUNTF);
3834 MNT_KERN_FLAG(MNTK_ASYNC);
3835 MNT_KERN_FLAG(MNTK_SOFTDEP);
3836 MNT_KERN_FLAG(MNTK_DRAINING);
3837 MNT_KERN_FLAG(MNTK_REFEXPIRE);
3838 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
3839 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
3840 MNT_KERN_FLAG(MNTK_NO_IOPF);
3841 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
3842 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
3843 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
3844 MNT_KERN_FLAG(MNTK_MARKER);
3845 MNT_KERN_FLAG(MNTK_USES_BCACHE);
3846 MNT_KERN_FLAG(MNTK_NOASYNC);
3847 MNT_KERN_FLAG(MNTK_UNMOUNT);
3848 MNT_KERN_FLAG(MNTK_MWAIT);
3849 MNT_KERN_FLAG(MNTK_SUSPEND);
3850 MNT_KERN_FLAG(MNTK_SUSPEND2);
3851 MNT_KERN_FLAG(MNTK_SUSPENDED);
3852 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
3853 MNT_KERN_FLAG(MNTK_NOKNOTE);
3854 #undef MNT_KERN_FLAG
3857 strlcat(buf, ", ", sizeof(buf));
3858 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3861 db_printf(" mnt_kern_flag = %s\n", buf);
3863 db_printf(" mnt_opt = ");
3864 opt = TAILQ_FIRST(mp->mnt_opt);
3866 db_printf("%s", opt->name);
3867 opt = TAILQ_NEXT(opt, link);
3868 while (opt != NULL) {
3869 db_printf(", %s", opt->name);
3870 opt = TAILQ_NEXT(opt, link);
3876 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
3877 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
3878 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
3879 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
3880 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
3881 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
3882 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
3883 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
3884 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
3885 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
3886 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
3887 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
3889 db_printf(" mnt_cred = { uid=%u ruid=%u",
3890 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
3891 if (jailed(mp->mnt_cred))
3892 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
3894 db_printf(" mnt_ref = %d\n", mp->mnt_ref);
3895 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
3896 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
3897 db_printf(" mnt_activevnodelistsize = %d\n",
3898 mp->mnt_activevnodelistsize);
3899 db_printf(" mnt_writeopcount = %d\n", mp->mnt_writeopcount);
3900 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
3901 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
3902 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
3903 db_printf(" mnt_lockref = %d\n", mp->mnt_lockref);
3904 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
3905 db_printf(" mnt_secondary_accwrites = %d\n",
3906 mp->mnt_secondary_accwrites);
3907 db_printf(" mnt_gjprovider = %s\n",
3908 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
3910 db_printf("\n\nList of active vnodes\n");
3911 TAILQ_FOREACH(vp, &mp->mnt_activevnodelist, v_actfreelist) {
3912 if (vp->v_type != VMARKER) {
3913 vn_printf(vp, "vnode ");
3918 db_printf("\n\nList of inactive vnodes\n");
3919 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3920 if (vp->v_type != VMARKER && (vp->v_iflag & VI_ACTIVE) == 0) {
3921 vn_printf(vp, "vnode ");
3930 * Fill in a struct xvfsconf based on a struct vfsconf.
3933 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
3935 struct xvfsconf xvfsp;
3937 bzero(&xvfsp, sizeof(xvfsp));
3938 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
3939 xvfsp.vfc_typenum = vfsp->vfc_typenum;
3940 xvfsp.vfc_refcount = vfsp->vfc_refcount;
3941 xvfsp.vfc_flags = vfsp->vfc_flags;
3943 * These are unused in userland, we keep them
3944 * to not break binary compatibility.
3946 xvfsp.vfc_vfsops = NULL;
3947 xvfsp.vfc_next = NULL;
3948 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3951 #ifdef COMPAT_FREEBSD32
3953 uint32_t vfc_vfsops;
3954 char vfc_name[MFSNAMELEN];
3955 int32_t vfc_typenum;
3956 int32_t vfc_refcount;
3962 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
3964 struct xvfsconf32 xvfsp;
3966 bzero(&xvfsp, sizeof(xvfsp));
3967 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
3968 xvfsp.vfc_typenum = vfsp->vfc_typenum;
3969 xvfsp.vfc_refcount = vfsp->vfc_refcount;
3970 xvfsp.vfc_flags = vfsp->vfc_flags;
3971 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3976 * Top level filesystem related information gathering.
3979 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
3981 struct vfsconf *vfsp;
3986 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3987 #ifdef COMPAT_FREEBSD32
3988 if (req->flags & SCTL_MASK32)
3989 error = vfsconf2x32(req, vfsp);
3992 error = vfsconf2x(req, vfsp);
4000 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4001 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4002 "S,xvfsconf", "List of all configured filesystems");
4004 #ifndef BURN_BRIDGES
4005 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4008 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4010 int *name = (int *)arg1 - 1; /* XXX */
4011 u_int namelen = arg2 + 1; /* XXX */
4012 struct vfsconf *vfsp;
4014 log(LOG_WARNING, "userland calling deprecated sysctl, "
4015 "please rebuild world\n");
4017 #if 1 || defined(COMPAT_PRELITE2)
4018 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4020 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4024 case VFS_MAXTYPENUM:
4027 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4030 return (ENOTDIR); /* overloaded */
4032 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4033 if (vfsp->vfc_typenum == name[2])
4038 return (EOPNOTSUPP);
4039 #ifdef COMPAT_FREEBSD32
4040 if (req->flags & SCTL_MASK32)
4041 return (vfsconf2x32(req, vfsp));
4044 return (vfsconf2x(req, vfsp));
4046 return (EOPNOTSUPP);
4049 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4050 CTLFLAG_MPSAFE, vfs_sysctl,
4051 "Generic filesystem");
4053 #if 1 || defined(COMPAT_PRELITE2)
4056 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4059 struct vfsconf *vfsp;
4060 struct ovfsconf ovfs;
4063 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4064 bzero(&ovfs, sizeof(ovfs));
4065 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4066 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4067 ovfs.vfc_index = vfsp->vfc_typenum;
4068 ovfs.vfc_refcount = vfsp->vfc_refcount;
4069 ovfs.vfc_flags = vfsp->vfc_flags;
4070 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4080 #endif /* 1 || COMPAT_PRELITE2 */
4081 #endif /* !BURN_BRIDGES */
4083 #define KINFO_VNODESLOP 10
4086 * Dump vnode list (via sysctl).
4090 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4098 * Stale numvnodes access is not fatal here.
4101 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4103 /* Make an estimate */
4104 return (SYSCTL_OUT(req, 0, len));
4106 error = sysctl_wire_old_buffer(req, 0);
4109 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4111 mtx_lock(&mountlist_mtx);
4112 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4113 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4116 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4120 xvn[n].xv_size = sizeof *xvn;
4121 xvn[n].xv_vnode = vp;
4122 xvn[n].xv_id = 0; /* XXX compat */
4123 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4125 XV_COPY(writecount);
4131 xvn[n].xv_flag = vp->v_vflag;
4133 switch (vp->v_type) {
4140 if (vp->v_rdev == NULL) {
4144 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4147 xvn[n].xv_socket = vp->v_socket;
4150 xvn[n].xv_fifo = vp->v_fifoinfo;
4155 /* shouldn't happen? */
4163 mtx_lock(&mountlist_mtx);
4168 mtx_unlock(&mountlist_mtx);
4170 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4175 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4176 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4181 unmount_or_warn(struct mount *mp)
4185 error = dounmount(mp, MNT_FORCE, curthread);
4187 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4191 printf("%d)\n", error);
4196 * Unmount all filesystems. The list is traversed in reverse order
4197 * of mounting to avoid dependencies.
4200 vfs_unmountall(void)
4202 struct mount *mp, *tmp;
4204 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4207 * Since this only runs when rebooting, it is not interlocked.
4209 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4213 * Forcibly unmounting "/dev" before "/" would prevent clean
4214 * unmount of the latter.
4216 if (mp == rootdevmp)
4219 unmount_or_warn(mp);
4222 if (rootdevmp != NULL)
4223 unmount_or_warn(rootdevmp);
4227 * perform msync on all vnodes under a mount point
4228 * the mount point must be locked.
4231 vfs_msync(struct mount *mp, int flags)
4233 struct vnode *vp, *mvp;
4234 struct vm_object *obj;
4236 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4238 vnlru_return_batch(mp);
4240 MNT_VNODE_FOREACH_ACTIVE(vp, mp, mvp) {
4242 if (obj != NULL && (obj->flags & OBJ_MIGHTBEDIRTY) != 0 &&
4243 (flags == MNT_WAIT || VOP_ISLOCKED(vp) == 0)) {
4245 LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
4247 if (vp->v_vflag & VV_NOSYNC) { /* unlinked */
4254 VM_OBJECT_WLOCK(obj);
4255 vm_object_page_clean(obj, 0, 0,
4257 OBJPC_SYNC : OBJPC_NOSYNC);
4258 VM_OBJECT_WUNLOCK(obj);
4268 destroy_vpollinfo_free(struct vpollinfo *vi)
4271 knlist_destroy(&vi->vpi_selinfo.si_note);
4272 mtx_destroy(&vi->vpi_lock);
4273 uma_zfree(vnodepoll_zone, vi);
4277 destroy_vpollinfo(struct vpollinfo *vi)
4280 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4281 seldrain(&vi->vpi_selinfo);
4282 destroy_vpollinfo_free(vi);
4286 * Initialize per-vnode helper structure to hold poll-related state.
4289 v_addpollinfo(struct vnode *vp)
4291 struct vpollinfo *vi;
4293 if (vp->v_pollinfo != NULL)
4295 vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4296 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4297 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4298 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4300 if (vp->v_pollinfo != NULL) {
4302 destroy_vpollinfo_free(vi);
4305 vp->v_pollinfo = vi;
4310 * Record a process's interest in events which might happen to
4311 * a vnode. Because poll uses the historic select-style interface
4312 * internally, this routine serves as both the ``check for any
4313 * pending events'' and the ``record my interest in future events''
4314 * functions. (These are done together, while the lock is held,
4315 * to avoid race conditions.)
4318 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4322 mtx_lock(&vp->v_pollinfo->vpi_lock);
4323 if (vp->v_pollinfo->vpi_revents & events) {
4325 * This leaves events we are not interested
4326 * in available for the other process which
4327 * which presumably had requested them
4328 * (otherwise they would never have been
4331 events &= vp->v_pollinfo->vpi_revents;
4332 vp->v_pollinfo->vpi_revents &= ~events;
4334 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4337 vp->v_pollinfo->vpi_events |= events;
4338 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4339 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4344 * Routine to create and manage a filesystem syncer vnode.
4346 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4347 static int sync_fsync(struct vop_fsync_args *);
4348 static int sync_inactive(struct vop_inactive_args *);
4349 static int sync_reclaim(struct vop_reclaim_args *);
4351 static struct vop_vector sync_vnodeops = {
4352 .vop_bypass = VOP_EOPNOTSUPP,
4353 .vop_close = sync_close, /* close */
4354 .vop_fsync = sync_fsync, /* fsync */
4355 .vop_inactive = sync_inactive, /* inactive */
4356 .vop_reclaim = sync_reclaim, /* reclaim */
4357 .vop_lock1 = vop_stdlock, /* lock */
4358 .vop_unlock = vop_stdunlock, /* unlock */
4359 .vop_islocked = vop_stdislocked, /* islocked */
4363 * Create a new filesystem syncer vnode for the specified mount point.
4366 vfs_allocate_syncvnode(struct mount *mp)
4370 static long start, incr, next;
4373 /* Allocate a new vnode */
4374 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
4376 panic("vfs_allocate_syncvnode: getnewvnode() failed");
4378 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4379 vp->v_vflag |= VV_FORCEINSMQ;
4380 error = insmntque(vp, mp);
4382 panic("vfs_allocate_syncvnode: insmntque() failed");
4383 vp->v_vflag &= ~VV_FORCEINSMQ;
4386 * Place the vnode onto the syncer worklist. We attempt to
4387 * scatter them about on the list so that they will go off
4388 * at evenly distributed times even if all the filesystems
4389 * are mounted at once.
4392 if (next == 0 || next > syncer_maxdelay) {
4396 start = syncer_maxdelay / 2;
4397 incr = syncer_maxdelay;
4403 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
4404 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
4405 mtx_lock(&sync_mtx);
4407 if (mp->mnt_syncer == NULL) {
4408 mp->mnt_syncer = vp;
4411 mtx_unlock(&sync_mtx);
4414 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4421 vfs_deallocate_syncvnode(struct mount *mp)
4425 mtx_lock(&sync_mtx);
4426 vp = mp->mnt_syncer;
4428 mp->mnt_syncer = NULL;
4429 mtx_unlock(&sync_mtx);
4435 * Do a lazy sync of the filesystem.
4438 sync_fsync(struct vop_fsync_args *ap)
4440 struct vnode *syncvp = ap->a_vp;
4441 struct mount *mp = syncvp->v_mount;
4446 * We only need to do something if this is a lazy evaluation.
4448 if (ap->a_waitfor != MNT_LAZY)
4452 * Move ourselves to the back of the sync list.
4454 bo = &syncvp->v_bufobj;
4456 vn_syncer_add_to_worklist(bo, syncdelay);
4460 * Walk the list of vnodes pushing all that are dirty and
4461 * not already on the sync list.
4463 if (vfs_busy(mp, MBF_NOWAIT) != 0)
4465 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
4469 save = curthread_pflags_set(TDP_SYNCIO);
4470 vfs_msync(mp, MNT_NOWAIT);
4471 error = VFS_SYNC(mp, MNT_LAZY);
4472 curthread_pflags_restore(save);
4473 vn_finished_write(mp);
4479 * The syncer vnode is no referenced.
4482 sync_inactive(struct vop_inactive_args *ap)
4490 * The syncer vnode is no longer needed and is being decommissioned.
4492 * Modifications to the worklist must be protected by sync_mtx.
4495 sync_reclaim(struct vop_reclaim_args *ap)
4497 struct vnode *vp = ap->a_vp;
4502 mtx_lock(&sync_mtx);
4503 if (vp->v_mount->mnt_syncer == vp)
4504 vp->v_mount->mnt_syncer = NULL;
4505 if (bo->bo_flag & BO_ONWORKLST) {
4506 LIST_REMOVE(bo, bo_synclist);
4507 syncer_worklist_len--;
4509 bo->bo_flag &= ~BO_ONWORKLST;
4511 mtx_unlock(&sync_mtx);
4518 * Check if vnode represents a disk device
4521 vn_isdisk(struct vnode *vp, int *errp)
4525 if (vp->v_type != VCHR) {
4531 if (vp->v_rdev == NULL)
4533 else if (vp->v_rdev->si_devsw == NULL)
4535 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
4541 return (error == 0);
4545 * Common filesystem object access control check routine. Accepts a
4546 * vnode's type, "mode", uid and gid, requested access mode, credentials,
4547 * and optional call-by-reference privused argument allowing vaccess()
4548 * to indicate to the caller whether privilege was used to satisfy the
4549 * request (obsoleted). Returns 0 on success, or an errno on failure.
4552 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
4553 accmode_t accmode, struct ucred *cred, int *privused)
4555 accmode_t dac_granted;
4556 accmode_t priv_granted;
4558 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
4559 ("invalid bit in accmode"));
4560 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
4561 ("VAPPEND without VWRITE"));
4564 * Look for a normal, non-privileged way to access the file/directory
4565 * as requested. If it exists, go with that.
4568 if (privused != NULL)
4573 /* Check the owner. */
4574 if (cred->cr_uid == file_uid) {
4575 dac_granted |= VADMIN;
4576 if (file_mode & S_IXUSR)
4577 dac_granted |= VEXEC;
4578 if (file_mode & S_IRUSR)
4579 dac_granted |= VREAD;
4580 if (file_mode & S_IWUSR)
4581 dac_granted |= (VWRITE | VAPPEND);
4583 if ((accmode & dac_granted) == accmode)
4589 /* Otherwise, check the groups (first match) */
4590 if (groupmember(file_gid, cred)) {
4591 if (file_mode & S_IXGRP)
4592 dac_granted |= VEXEC;
4593 if (file_mode & S_IRGRP)
4594 dac_granted |= VREAD;
4595 if (file_mode & S_IWGRP)
4596 dac_granted |= (VWRITE | VAPPEND);
4598 if ((accmode & dac_granted) == accmode)
4604 /* Otherwise, check everyone else. */
4605 if (file_mode & S_IXOTH)
4606 dac_granted |= VEXEC;
4607 if (file_mode & S_IROTH)
4608 dac_granted |= VREAD;
4609 if (file_mode & S_IWOTH)
4610 dac_granted |= (VWRITE | VAPPEND);
4611 if ((accmode & dac_granted) == accmode)
4616 * Build a privilege mask to determine if the set of privileges
4617 * satisfies the requirements when combined with the granted mask
4618 * from above. For each privilege, if the privilege is required,
4619 * bitwise or the request type onto the priv_granted mask.
4625 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
4626 * requests, instead of PRIV_VFS_EXEC.
4628 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4629 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
4630 priv_granted |= VEXEC;
4633 * Ensure that at least one execute bit is on. Otherwise,
4634 * a privileged user will always succeed, and we don't want
4635 * this to happen unless the file really is executable.
4637 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4638 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
4639 !priv_check_cred(cred, PRIV_VFS_EXEC))
4640 priv_granted |= VEXEC;
4643 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
4644 !priv_check_cred(cred, PRIV_VFS_READ))
4645 priv_granted |= VREAD;
4647 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
4648 !priv_check_cred(cred, PRIV_VFS_WRITE))
4649 priv_granted |= (VWRITE | VAPPEND);
4651 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
4652 !priv_check_cred(cred, PRIV_VFS_ADMIN))
4653 priv_granted |= VADMIN;
4655 if ((accmode & (priv_granted | dac_granted)) == accmode) {
4656 /* XXX audit: privilege used */
4657 if (privused != NULL)
4662 return ((accmode & VADMIN) ? EPERM : EACCES);
4666 * Credential check based on process requesting service, and per-attribute
4670 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
4671 struct thread *td, accmode_t accmode)
4675 * Kernel-invoked always succeeds.
4681 * Do not allow privileged processes in jail to directly manipulate
4682 * system attributes.
4684 switch (attrnamespace) {
4685 case EXTATTR_NAMESPACE_SYSTEM:
4686 /* Potentially should be: return (EPERM); */
4687 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
4688 case EXTATTR_NAMESPACE_USER:
4689 return (VOP_ACCESS(vp, accmode, cred, td));
4695 #ifdef DEBUG_VFS_LOCKS
4697 * This only exists to suppress warnings from unlocked specfs accesses. It is
4698 * no longer ok to have an unlocked VFS.
4700 #define IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL || \
4701 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
4703 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
4704 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
4705 "Drop into debugger on lock violation");
4707 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
4708 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
4709 0, "Check for interlock across VOPs");
4711 int vfs_badlock_print = 1; /* Print lock violations. */
4712 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
4713 0, "Print lock violations");
4715 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
4716 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
4717 0, "Print vnode details on lock violations");
4720 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
4721 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
4722 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
4726 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
4730 if (vfs_badlock_backtrace)
4733 if (vfs_badlock_vnode)
4734 vn_printf(vp, "vnode ");
4735 if (vfs_badlock_print)
4736 printf("%s: %p %s\n", str, (void *)vp, msg);
4737 if (vfs_badlock_ddb)
4738 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4742 assert_vi_locked(struct vnode *vp, const char *str)
4745 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
4746 vfs_badlock("interlock is not locked but should be", str, vp);
4750 assert_vi_unlocked(struct vnode *vp, const char *str)
4753 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
4754 vfs_badlock("interlock is locked but should not be", str, vp);
4758 assert_vop_locked(struct vnode *vp, const char *str)
4762 if (!IGNORE_LOCK(vp)) {
4763 locked = VOP_ISLOCKED(vp);
4764 if (locked == 0 || locked == LK_EXCLOTHER)
4765 vfs_badlock("is not locked but should be", str, vp);
4770 assert_vop_unlocked(struct vnode *vp, const char *str)
4773 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
4774 vfs_badlock("is locked but should not be", str, vp);
4778 assert_vop_elocked(struct vnode *vp, const char *str)
4781 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
4782 vfs_badlock("is not exclusive locked but should be", str, vp);
4784 #endif /* DEBUG_VFS_LOCKS */
4787 vop_rename_fail(struct vop_rename_args *ap)
4790 if (ap->a_tvp != NULL)
4792 if (ap->a_tdvp == ap->a_tvp)
4801 vop_rename_pre(void *ap)
4803 struct vop_rename_args *a = ap;
4805 #ifdef DEBUG_VFS_LOCKS
4807 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
4808 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
4809 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
4810 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
4812 /* Check the source (from). */
4813 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
4814 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
4815 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
4816 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
4817 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
4819 /* Check the target. */
4821 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
4822 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
4824 if (a->a_tdvp != a->a_fdvp)
4826 if (a->a_tvp != a->a_fvp)
4833 #ifdef DEBUG_VFS_LOCKS
4835 vop_strategy_pre(void *ap)
4837 struct vop_strategy_args *a;
4844 * Cluster ops lock their component buffers but not the IO container.
4846 if ((bp->b_flags & B_CLUSTER) != 0)
4849 if (panicstr == NULL && !BUF_ISLOCKED(bp)) {
4850 if (vfs_badlock_print)
4852 "VOP_STRATEGY: bp is not locked but should be\n");
4853 if (vfs_badlock_ddb)
4854 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4859 vop_lock_pre(void *ap)
4861 struct vop_lock1_args *a = ap;
4863 if ((a->a_flags & LK_INTERLOCK) == 0)
4864 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4866 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
4870 vop_lock_post(void *ap, int rc)
4872 struct vop_lock1_args *a = ap;
4874 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4875 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
4876 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
4880 vop_unlock_pre(void *ap)
4882 struct vop_unlock_args *a = ap;
4884 if (a->a_flags & LK_INTERLOCK)
4885 ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
4886 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
4890 vop_unlock_post(void *ap, int rc)
4892 struct vop_unlock_args *a = ap;
4894 if (a->a_flags & LK_INTERLOCK)
4895 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
4900 vop_create_post(void *ap, int rc)
4902 struct vop_create_args *a = ap;
4905 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4909 vop_deleteextattr_post(void *ap, int rc)
4911 struct vop_deleteextattr_args *a = ap;
4914 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4918 vop_link_post(void *ap, int rc)
4920 struct vop_link_args *a = ap;
4923 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
4924 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
4929 vop_mkdir_post(void *ap, int rc)
4931 struct vop_mkdir_args *a = ap;
4934 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4938 vop_mknod_post(void *ap, int rc)
4940 struct vop_mknod_args *a = ap;
4943 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4947 vop_reclaim_post(void *ap, int rc)
4949 struct vop_reclaim_args *a = ap;
4952 VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
4956 vop_remove_post(void *ap, int rc)
4958 struct vop_remove_args *a = ap;
4961 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4962 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4967 vop_rename_post(void *ap, int rc)
4969 struct vop_rename_args *a = ap;
4974 if (a->a_fdvp == a->a_tdvp) {
4975 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
4977 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
4978 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
4980 hint |= NOTE_EXTEND;
4981 if (a->a_fvp->v_type == VDIR)
4983 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
4985 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
4986 a->a_tvp->v_type == VDIR)
4988 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
4991 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
4993 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
4995 if (a->a_tdvp != a->a_fdvp)
4997 if (a->a_tvp != a->a_fvp)
5005 vop_rmdir_post(void *ap, int rc)
5007 struct vop_rmdir_args *a = ap;
5010 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5011 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5016 vop_setattr_post(void *ap, int rc)
5018 struct vop_setattr_args *a = ap;
5021 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5025 vop_setextattr_post(void *ap, int rc)
5027 struct vop_setextattr_args *a = ap;
5030 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5034 vop_symlink_post(void *ap, int rc)
5036 struct vop_symlink_args *a = ap;
5039 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5043 vop_open_post(void *ap, int rc)
5045 struct vop_open_args *a = ap;
5048 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
5052 vop_close_post(void *ap, int rc)
5054 struct vop_close_args *a = ap;
5056 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
5057 (a->a_vp->v_iflag & VI_DOOMED) == 0)) {
5058 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
5059 NOTE_CLOSE_WRITE : NOTE_CLOSE);
5064 vop_read_post(void *ap, int rc)
5066 struct vop_read_args *a = ap;
5069 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5073 vop_readdir_post(void *ap, int rc)
5075 struct vop_readdir_args *a = ap;
5078 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5081 static struct knlist fs_knlist;
5084 vfs_event_init(void *arg)
5086 knlist_init_mtx(&fs_knlist, NULL);
5088 /* XXX - correct order? */
5089 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
5092 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
5095 KNOTE_UNLOCKED(&fs_knlist, event);
5098 static int filt_fsattach(struct knote *kn);
5099 static void filt_fsdetach(struct knote *kn);
5100 static int filt_fsevent(struct knote *kn, long hint);
5102 struct filterops fs_filtops = {
5104 .f_attach = filt_fsattach,
5105 .f_detach = filt_fsdetach,
5106 .f_event = filt_fsevent
5110 filt_fsattach(struct knote *kn)
5113 kn->kn_flags |= EV_CLEAR;
5114 knlist_add(&fs_knlist, kn, 0);
5119 filt_fsdetach(struct knote *kn)
5122 knlist_remove(&fs_knlist, kn, 0);
5126 filt_fsevent(struct knote *kn, long hint)
5129 kn->kn_fflags |= hint;
5130 return (kn->kn_fflags != 0);
5134 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
5140 error = SYSCTL_IN(req, &vc, sizeof(vc));
5143 if (vc.vc_vers != VFS_CTL_VERS1)
5145 mp = vfs_getvfs(&vc.vc_fsid);
5148 /* ensure that a specific sysctl goes to the right filesystem. */
5149 if (strcmp(vc.vc_fstypename, "*") != 0 &&
5150 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
5154 VCTLTOREQ(&vc, req);
5155 error = VFS_SYSCTL(mp, vc.vc_op, req);
5160 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_WR,
5161 NULL, 0, sysctl_vfs_ctl, "",
5165 * Function to initialize a va_filerev field sensibly.
5166 * XXX: Wouldn't a random number make a lot more sense ??
5169 init_va_filerev(void)
5174 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
5177 static int filt_vfsread(struct knote *kn, long hint);
5178 static int filt_vfswrite(struct knote *kn, long hint);
5179 static int filt_vfsvnode(struct knote *kn, long hint);
5180 static void filt_vfsdetach(struct knote *kn);
5181 static struct filterops vfsread_filtops = {
5183 .f_detach = filt_vfsdetach,
5184 .f_event = filt_vfsread
5186 static struct filterops vfswrite_filtops = {
5188 .f_detach = filt_vfsdetach,
5189 .f_event = filt_vfswrite
5191 static struct filterops vfsvnode_filtops = {
5193 .f_detach = filt_vfsdetach,
5194 .f_event = filt_vfsvnode
5198 vfs_knllock(void *arg)
5200 struct vnode *vp = arg;
5202 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5206 vfs_knlunlock(void *arg)
5208 struct vnode *vp = arg;
5214 vfs_knl_assert_locked(void *arg)
5216 #ifdef DEBUG_VFS_LOCKS
5217 struct vnode *vp = arg;
5219 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
5224 vfs_knl_assert_unlocked(void *arg)
5226 #ifdef DEBUG_VFS_LOCKS
5227 struct vnode *vp = arg;
5229 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
5234 vfs_kqfilter(struct vop_kqfilter_args *ap)
5236 struct vnode *vp = ap->a_vp;
5237 struct knote *kn = ap->a_kn;
5240 switch (kn->kn_filter) {
5242 kn->kn_fop = &vfsread_filtops;
5245 kn->kn_fop = &vfswrite_filtops;
5248 kn->kn_fop = &vfsvnode_filtops;
5254 kn->kn_hook = (caddr_t)vp;
5257 if (vp->v_pollinfo == NULL)
5259 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5261 knlist_add(knl, kn, 0);
5267 * Detach knote from vnode
5270 filt_vfsdetach(struct knote *kn)
5272 struct vnode *vp = (struct vnode *)kn->kn_hook;
5274 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
5275 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
5281 filt_vfsread(struct knote *kn, long hint)
5283 struct vnode *vp = (struct vnode *)kn->kn_hook;
5288 * filesystem is gone, so set the EOF flag and schedule
5289 * the knote for deletion.
5291 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5293 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5298 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
5302 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
5303 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
5310 filt_vfswrite(struct knote *kn, long hint)
5312 struct vnode *vp = (struct vnode *)kn->kn_hook;
5317 * filesystem is gone, so set the EOF flag and schedule
5318 * the knote for deletion.
5320 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
5321 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5329 filt_vfsvnode(struct knote *kn, long hint)
5331 struct vnode *vp = (struct vnode *)kn->kn_hook;
5335 if (kn->kn_sfflags & hint)
5336 kn->kn_fflags |= hint;
5337 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5338 kn->kn_flags |= EV_EOF;
5342 res = (kn->kn_fflags != 0);
5348 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
5352 if (dp->d_reclen > ap->a_uio->uio_resid)
5353 return (ENAMETOOLONG);
5354 error = uiomove(dp, dp->d_reclen, ap->a_uio);
5356 if (ap->a_ncookies != NULL) {
5357 if (ap->a_cookies != NULL)
5358 free(ap->a_cookies, M_TEMP);
5359 ap->a_cookies = NULL;
5360 *ap->a_ncookies = 0;
5364 if (ap->a_ncookies == NULL)
5367 KASSERT(ap->a_cookies,
5368 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
5370 *ap->a_cookies = realloc(*ap->a_cookies,
5371 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
5372 (*ap->a_cookies)[*ap->a_ncookies] = off;
5373 *ap->a_ncookies += 1;
5378 * Mark for update the access time of the file if the filesystem
5379 * supports VOP_MARKATIME. This functionality is used by execve and
5380 * mmap, so we want to avoid the I/O implied by directly setting
5381 * va_atime for the sake of efficiency.
5384 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
5389 ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
5390 if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
5391 (void)VOP_MARKATIME(vp);
5395 * The purpose of this routine is to remove granularity from accmode_t,
5396 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
5397 * VADMIN and VAPPEND.
5399 * If it returns 0, the caller is supposed to continue with the usual
5400 * access checks using 'accmode' as modified by this routine. If it
5401 * returns nonzero value, the caller is supposed to return that value
5404 * Note that after this routine runs, accmode may be zero.
5407 vfs_unixify_accmode(accmode_t *accmode)
5410 * There is no way to specify explicit "deny" rule using
5411 * file mode or POSIX.1e ACLs.
5413 if (*accmode & VEXPLICIT_DENY) {
5419 * None of these can be translated into usual access bits.
5420 * Also, the common case for NFSv4 ACLs is to not contain
5421 * either of these bits. Caller should check for VWRITE
5422 * on the containing directory instead.
5424 if (*accmode & (VDELETE_CHILD | VDELETE))
5427 if (*accmode & VADMIN_PERMS) {
5428 *accmode &= ~VADMIN_PERMS;
5433 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
5434 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
5436 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
5442 * These are helper functions for filesystems to traverse all
5443 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
5445 * This interface replaces MNT_VNODE_FOREACH.
5448 MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
5451 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
5456 kern_yield(PRI_USER);
5458 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5459 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
5460 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
5461 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
5462 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
5465 if ((vp->v_iflag & VI_DOOMED) != 0) {
5472 __mnt_vnode_markerfree_all(mvp, mp);
5473 /* MNT_IUNLOCK(mp); -- done in above function */
5474 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
5477 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5478 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5484 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
5488 *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
5491 (*mvp)->v_mount = mp;
5492 (*mvp)->v_type = VMARKER;
5494 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
5495 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
5496 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
5499 if ((vp->v_iflag & VI_DOOMED) != 0) {
5508 free(*mvp, M_VNODE_MARKER);
5512 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5518 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
5526 mtx_assert(MNT_MTX(mp), MA_OWNED);
5528 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5529 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5532 free(*mvp, M_VNODE_MARKER);
5537 * These are helper functions for filesystems to traverse their
5538 * active vnodes. See MNT_VNODE_FOREACH_ACTIVE() in sys/mount.h
5541 mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
5544 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5549 free(*mvp, M_VNODE_MARKER);
5554 * Relock the mp mount vnode list lock with the vp vnode interlock in the
5555 * conventional lock order during mnt_vnode_next_active iteration.
5557 * On entry, the mount vnode list lock is held and the vnode interlock is not.
5558 * The list lock is dropped and reacquired. On success, both locks are held.
5559 * On failure, the mount vnode list lock is held but the vnode interlock is
5560 * not, and the procedure may have yielded.
5563 mnt_vnode_next_active_relock(struct vnode *mvp, struct mount *mp,
5566 const struct vnode *tmp;
5569 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
5570 TAILQ_NEXT(mvp, v_actfreelist) != NULL, mvp,
5571 ("%s: bad marker", __func__));
5572 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
5573 ("%s: inappropriate vnode", __func__));
5574 ASSERT_VI_UNLOCKED(vp, __func__);
5575 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5579 TAILQ_REMOVE(&mp->mnt_activevnodelist, mvp, v_actfreelist);
5580 TAILQ_INSERT_BEFORE(vp, mvp, v_actfreelist);
5583 * Use a hold to prevent vp from disappearing while the mount vnode
5584 * list lock is dropped and reacquired. Normally a hold would be
5585 * acquired with vhold(), but that might try to acquire the vnode
5586 * interlock, which would be a LOR with the mount vnode list lock.
5588 held = refcount_acquire_if_not_zero(&vp->v_holdcnt);
5589 mtx_unlock(&mp->mnt_listmtx);
5593 if (!refcount_release_if_not_last(&vp->v_holdcnt)) {
5597 mtx_lock(&mp->mnt_listmtx);
5600 * Determine whether the vnode is still the next one after the marker,
5601 * excepting any other markers. If the vnode has not been doomed by
5602 * vgone() then the hold should have ensured that it remained on the
5603 * active list. If it has been doomed but is still on the active list,
5604 * don't abort, but rather skip over it (avoid spinning on doomed
5609 tmp = TAILQ_NEXT(tmp, v_actfreelist);
5610 } while (tmp != NULL && tmp->v_type == VMARKER);
5612 mtx_unlock(&mp->mnt_listmtx);
5621 mtx_lock(&mp->mnt_listmtx);
5624 ASSERT_VI_LOCKED(vp, __func__);
5626 ASSERT_VI_UNLOCKED(vp, __func__);
5627 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5631 static struct vnode *
5632 mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
5634 struct vnode *vp, *nvp;
5636 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5637 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5639 vp = TAILQ_NEXT(*mvp, v_actfreelist);
5640 while (vp != NULL) {
5641 if (vp->v_type == VMARKER) {
5642 vp = TAILQ_NEXT(vp, v_actfreelist);
5646 * Try-lock because this is the wrong lock order. If that does
5647 * not succeed, drop the mount vnode list lock and try to
5648 * reacquire it and the vnode interlock in the right order.
5650 if (!VI_TRYLOCK(vp) &&
5651 !mnt_vnode_next_active_relock(*mvp, mp, vp))
5653 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
5654 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
5655 ("alien vnode on the active list %p %p", vp, mp));
5656 if (vp->v_mount == mp && (vp->v_iflag & VI_DOOMED) == 0)
5658 nvp = TAILQ_NEXT(vp, v_actfreelist);
5662 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
5664 /* Check if we are done */
5666 mtx_unlock(&mp->mnt_listmtx);
5667 mnt_vnode_markerfree_active(mvp, mp);
5670 TAILQ_INSERT_AFTER(&mp->mnt_activevnodelist, vp, *mvp, v_actfreelist);
5671 mtx_unlock(&mp->mnt_listmtx);
5672 ASSERT_VI_LOCKED(vp, "active iter");
5673 KASSERT((vp->v_iflag & VI_ACTIVE) != 0, ("Non-active vp %p", vp));
5678 __mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
5682 kern_yield(PRI_USER);
5683 mtx_lock(&mp->mnt_listmtx);
5684 return (mnt_vnode_next_active(mvp, mp));
5688 __mnt_vnode_first_active(struct vnode **mvp, struct mount *mp)
5692 *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
5696 (*mvp)->v_type = VMARKER;
5697 (*mvp)->v_mount = mp;
5699 mtx_lock(&mp->mnt_listmtx);
5700 vp = TAILQ_FIRST(&mp->mnt_activevnodelist);
5702 mtx_unlock(&mp->mnt_listmtx);
5703 mnt_vnode_markerfree_active(mvp, mp);
5706 TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
5707 return (mnt_vnode_next_active(mvp, mp));
5711 __mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
5717 mtx_lock(&mp->mnt_listmtx);
5718 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
5719 mtx_unlock(&mp->mnt_listmtx);
5720 mnt_vnode_markerfree_active(mvp, mp);