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_range1(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 reclaim_free Only reclaim free vnodes if this is set.
955 * @return The number of vnodes that were reclaimed.
958 vlrureclaim(struct mount *mp, int reclaim_nc_src, int trigger)
961 int count, done, target;
964 vn_start_write(NULL, &mp, V_WAIT);
966 count = mp->mnt_nvnodelistsize;
967 target = count * (int64_t)gapvnodes / imax(desiredvnodes, 1);
968 target = target / 10 + 1;
969 while (count != 0 && done < target) {
970 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
971 while (vp != NULL && vp->v_type == VMARKER)
972 vp = TAILQ_NEXT(vp, v_nmntvnodes);
976 * XXX LRU is completely broken for non-free vnodes. First
977 * by calling here in mountpoint order, then by moving
978 * unselected vnodes to the end here, and most grossly by
979 * removing the vlruvp() function that was supposed to
980 * maintain the order. (This function was born broken
981 * since syncer problems prevented it doing anything.) The
982 * order is closer to LRC (C = Created).
984 * LRU reclaiming of vnodes seems to have last worked in
985 * FreeBSD-3 where LRU wasn't mentioned under any spelling.
986 * Then there was no hold count, and inactive vnodes were
987 * simply put on the free list in LRU order. The separate
988 * lists also break LRU. We prefer to reclaim from the
989 * free list for technical reasons. This tends to thrash
990 * the free list to keep very unrecently used held vnodes.
991 * The problem is mitigated by keeping the free list large.
993 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
994 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
999 * If it's been deconstructed already, it's still
1000 * referenced, or it exceeds the trigger, skip it.
1001 * Also skip free vnodes. We are trying to make space
1002 * to expand the free list, not reduce it.
1004 if (vp->v_usecount ||
1005 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1006 ((vp->v_iflag & VI_FREE) != 0) ||
1007 (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
1008 vp->v_object->resident_page_count > trigger)) {
1014 if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT)) {
1016 goto next_iter_mntunlocked;
1020 * v_usecount may have been bumped after VOP_LOCK() dropped
1021 * the vnode interlock and before it was locked again.
1023 * It is not necessary to recheck VI_DOOMED because it can
1024 * only be set by another thread that holds both the vnode
1025 * lock and vnode interlock. If another thread has the
1026 * vnode lock before we get to VOP_LOCK() and obtains the
1027 * vnode interlock after VOP_LOCK() drops the vnode
1028 * interlock, the other thread will be unable to drop the
1029 * vnode lock before our VOP_LOCK() call fails.
1031 if (vp->v_usecount ||
1032 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1033 (vp->v_iflag & VI_FREE) != 0 ||
1034 (vp->v_object != NULL &&
1035 vp->v_object->resident_page_count > trigger)) {
1036 VOP_UNLOCK(vp, LK_INTERLOCK);
1038 goto next_iter_mntunlocked;
1040 KASSERT((vp->v_iflag & VI_DOOMED) == 0,
1041 ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
1042 counter_u64_add(recycles_count, 1);
1047 next_iter_mntunlocked:
1048 if (!should_yield())
1052 if (!should_yield())
1056 kern_yield(PRI_USER);
1061 vn_finished_write(mp);
1065 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1066 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1068 "limit on vnode free requests per call to the vnlru_free routine");
1071 * Attempt to reduce the free list by the requested amount.
1074 vnlru_free_locked(int count, struct vfsops *mnt_op)
1080 tried_batches = false;
1081 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
1082 if (count > max_vnlru_free)
1083 count = max_vnlru_free;
1084 for (; count > 0; count--) {
1085 vp = TAILQ_FIRST(&vnode_free_list);
1087 * The list can be modified while the free_list_mtx
1088 * has been dropped and vp could be NULL here.
1093 mtx_unlock(&vnode_free_list_mtx);
1094 vnlru_return_batches(mnt_op);
1095 tried_batches = true;
1096 mtx_lock(&vnode_free_list_mtx);
1100 VNASSERT(vp->v_op != NULL, vp,
1101 ("vnlru_free: vnode already reclaimed."));
1102 KASSERT((vp->v_iflag & VI_FREE) != 0,
1103 ("Removing vnode not on freelist"));
1104 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1105 ("Mangling active vnode"));
1106 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
1109 * Don't recycle if our vnode is from different type
1110 * of mount point. Note that mp is type-safe, the
1111 * check does not reach unmapped address even if
1112 * vnode is reclaimed.
1113 * Don't recycle if we can't get the interlock without
1116 if ((mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1117 mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
1118 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_actfreelist);
1121 VNASSERT((vp->v_iflag & VI_FREE) != 0 && vp->v_holdcnt == 0,
1122 vp, ("vp inconsistent on freelist"));
1125 * The clear of VI_FREE prevents activation of the
1126 * vnode. There is no sense in putting the vnode on
1127 * the mount point active list, only to remove it
1128 * later during recycling. Inline the relevant part
1129 * of vholdl(), to avoid triggering assertions or
1133 vp->v_iflag &= ~VI_FREE;
1134 VNODE_REFCOUNT_FENCE_REL();
1135 refcount_acquire(&vp->v_holdcnt);
1137 mtx_unlock(&vnode_free_list_mtx);
1141 * If the recycled succeeded this vdrop will actually free
1142 * the vnode. If not it will simply place it back on
1146 mtx_lock(&vnode_free_list_mtx);
1151 vnlru_free(int count, struct vfsops *mnt_op)
1154 mtx_lock(&vnode_free_list_mtx);
1155 vnlru_free_locked(count, mnt_op);
1156 mtx_unlock(&vnode_free_list_mtx);
1160 /* XXX some names and initialization are bad for limits and watermarks. */
1166 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1167 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1168 vlowat = vhiwat / 2;
1169 if (numvnodes > desiredvnodes)
1171 space = desiredvnodes - numvnodes;
1172 if (freevnodes > wantfreevnodes)
1173 space += freevnodes - wantfreevnodes;
1178 vnlru_return_batch_locked(struct mount *mp)
1182 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
1184 if (mp->mnt_tmpfreevnodelistsize == 0)
1187 TAILQ_FOREACH(vp, &mp->mnt_tmpfreevnodelist, v_actfreelist) {
1188 VNASSERT((vp->v_mflag & VMP_TMPMNTFREELIST) != 0, vp,
1189 ("vnode without VMP_TMPMNTFREELIST on mnt_tmpfreevnodelist"));
1190 vp->v_mflag &= ~VMP_TMPMNTFREELIST;
1192 mtx_lock(&vnode_free_list_mtx);
1193 TAILQ_CONCAT(&vnode_free_list, &mp->mnt_tmpfreevnodelist, v_actfreelist);
1194 freevnodes += mp->mnt_tmpfreevnodelistsize;
1195 mtx_unlock(&vnode_free_list_mtx);
1196 mp->mnt_tmpfreevnodelistsize = 0;
1200 vnlru_return_batch(struct mount *mp)
1203 mtx_lock(&mp->mnt_listmtx);
1204 vnlru_return_batch_locked(mp);
1205 mtx_unlock(&mp->mnt_listmtx);
1209 vnlru_return_batches(struct vfsops *mnt_op)
1211 struct mount *mp, *nmp;
1214 mtx_lock(&mountlist_mtx);
1215 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1216 need_unbusy = false;
1217 if (mnt_op != NULL && mp->mnt_op != mnt_op)
1219 if (mp->mnt_tmpfreevnodelistsize == 0)
1221 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK) == 0) {
1222 vnlru_return_batch(mp);
1224 mtx_lock(&mountlist_mtx);
1227 nmp = TAILQ_NEXT(mp, mnt_list);
1231 mtx_unlock(&mountlist_mtx);
1235 * Attempt to recycle vnodes in a context that is always safe to block.
1236 * Calling vlrurecycle() from the bowels of filesystem code has some
1237 * interesting deadlock problems.
1239 static struct proc *vnlruproc;
1240 static int vnlruproc_sig;
1245 struct mount *mp, *nmp;
1246 unsigned long onumvnodes;
1247 int done, force, reclaim_nc_src, trigger, usevnodes;
1249 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1250 SHUTDOWN_PRI_FIRST);
1254 kproc_suspend_check(vnlruproc);
1255 mtx_lock(&vnode_free_list_mtx);
1257 * If numvnodes is too large (due to desiredvnodes being
1258 * adjusted using its sysctl, or emergency growth), first
1259 * try to reduce it by discarding from the free list.
1261 if (numvnodes > desiredvnodes)
1262 vnlru_free_locked(numvnodes - desiredvnodes, NULL);
1264 * Sleep if the vnode cache is in a good state. This is
1265 * when it is not over-full and has space for about a 4%
1266 * or 9% expansion (by growing its size or inexcessively
1267 * reducing its free list). Otherwise, try to reclaim
1268 * space for a 10% expansion.
1270 if (vstir && force == 0) {
1274 if (vspace() >= vlowat && force == 0) {
1276 wakeup(&vnlruproc_sig);
1277 msleep(vnlruproc, &vnode_free_list_mtx,
1278 PVFS|PDROP, "vlruwt", hz);
1281 mtx_unlock(&vnode_free_list_mtx);
1283 onumvnodes = numvnodes;
1285 * Calculate parameters for recycling. These are the same
1286 * throughout the loop to give some semblance of fairness.
1287 * The trigger point is to avoid recycling vnodes with lots
1288 * of resident pages. We aren't trying to free memory; we
1289 * are trying to recycle or at least free vnodes.
1291 if (numvnodes <= desiredvnodes)
1292 usevnodes = numvnodes - freevnodes;
1294 usevnodes = numvnodes;
1298 * The trigger value is is chosen to give a conservatively
1299 * large value to ensure that it alone doesn't prevent
1300 * making progress. The value can easily be so large that
1301 * it is effectively infinite in some congested and
1302 * misconfigured cases, and this is necessary. Normally
1303 * it is about 8 to 100 (pages), which is quite large.
1305 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1307 trigger = vsmalltrigger;
1308 reclaim_nc_src = force >= 3;
1309 mtx_lock(&mountlist_mtx);
1310 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1311 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK)) {
1312 nmp = TAILQ_NEXT(mp, mnt_list);
1315 done += vlrureclaim(mp, reclaim_nc_src, trigger);
1316 mtx_lock(&mountlist_mtx);
1317 nmp = TAILQ_NEXT(mp, mnt_list);
1320 mtx_unlock(&mountlist_mtx);
1321 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1324 if (force == 0 || force == 1) {
1334 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1336 kern_yield(PRI_USER);
1338 * After becoming active to expand above low water, keep
1339 * active until above high water.
1341 force = vspace() < vhiwat;
1345 static struct kproc_desc vnlru_kp = {
1350 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1354 * Routines having to do with the management of the vnode table.
1358 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1359 * before we actually vgone(). This function must be called with the vnode
1360 * held to prevent the vnode from being returned to the free list midway
1364 vtryrecycle(struct vnode *vp)
1368 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1369 VNASSERT(vp->v_holdcnt, vp,
1370 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1372 * This vnode may found and locked via some other list, if so we
1373 * can't recycle it yet.
1375 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1377 "%s: impossible to recycle, vp %p lock is already held",
1379 return (EWOULDBLOCK);
1382 * Don't recycle if its filesystem is being suspended.
1384 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1387 "%s: impossible to recycle, cannot start the write for %p",
1392 * If we got this far, we need to acquire the interlock and see if
1393 * anyone picked up this vnode from another list. If not, we will
1394 * mark it with DOOMED via vgonel() so that anyone who does find it
1395 * will skip over it.
1398 if (vp->v_usecount) {
1399 VOP_UNLOCK(vp, LK_INTERLOCK);
1400 vn_finished_write(vnmp);
1402 "%s: impossible to recycle, %p is already referenced",
1406 if ((vp->v_iflag & VI_DOOMED) == 0) {
1407 counter_u64_add(recycles_count, 1);
1410 VOP_UNLOCK(vp, LK_INTERLOCK);
1411 vn_finished_write(vnmp);
1419 if (vspace() < vlowat && vnlruproc_sig == 0) {
1426 * Wait if necessary for space for a new vnode.
1429 getnewvnode_wait(int suspended)
1432 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
1433 if (numvnodes >= desiredvnodes) {
1436 * The file system is being suspended. We cannot
1437 * risk a deadlock here, so allow allocation of
1438 * another vnode even if this would give too many.
1442 if (vnlruproc_sig == 0) {
1443 vnlruproc_sig = 1; /* avoid unnecessary wakeups */
1446 msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
1449 /* Post-adjust like the pre-adjust in getnewvnode(). */
1450 if (numvnodes + 1 > desiredvnodes && freevnodes > 1)
1451 vnlru_free_locked(1, NULL);
1452 return (numvnodes >= desiredvnodes ? ENFILE : 0);
1456 * This hack is fragile, and probably not needed any more now that the
1457 * watermark handling works.
1460 getnewvnode_reserve(u_int count)
1464 /* Pre-adjust like the pre-adjust in getnewvnode(), with any count. */
1465 /* XXX no longer so quick, but this part is not racy. */
1466 mtx_lock(&vnode_free_list_mtx);
1467 if (numvnodes + count > desiredvnodes && freevnodes > wantfreevnodes)
1468 vnlru_free_locked(ulmin(numvnodes + count - desiredvnodes,
1469 freevnodes - wantfreevnodes), NULL);
1470 mtx_unlock(&vnode_free_list_mtx);
1473 /* First try to be quick and racy. */
1474 if (atomic_fetchadd_long(&numvnodes, count) + count <= desiredvnodes) {
1475 td->td_vp_reserv += count;
1476 vcheckspace(); /* XXX no longer so quick, but more racy */
1479 atomic_subtract_long(&numvnodes, count);
1481 mtx_lock(&vnode_free_list_mtx);
1483 if (getnewvnode_wait(0) == 0) {
1486 atomic_add_long(&numvnodes, 1);
1490 mtx_unlock(&vnode_free_list_mtx);
1494 * This hack is fragile, especially if desiredvnodes or wantvnodes are
1495 * misconfgured or changed significantly. Reducing desiredvnodes below
1496 * the reserved amount should cause bizarre behaviour like reducing it
1497 * below the number of active vnodes -- the system will try to reduce
1498 * numvnodes to match, but should fail, so the subtraction below should
1502 getnewvnode_drop_reserve(void)
1507 atomic_subtract_long(&numvnodes, td->td_vp_reserv);
1508 td->td_vp_reserv = 0;
1512 * Return the next vnode from the free list.
1515 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1520 struct lock_object *lo;
1521 static int cyclecount;
1524 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1527 if (td->td_vp_reserv > 0) {
1528 td->td_vp_reserv -= 1;
1531 mtx_lock(&vnode_free_list_mtx);
1532 if (numvnodes < desiredvnodes)
1534 else if (cyclecount++ >= freevnodes) {
1539 * Grow the vnode cache if it will not be above its target max
1540 * after growing. Otherwise, if the free list is nonempty, try
1541 * to reclaim 1 item from it before growing the cache (possibly
1542 * above its target max if the reclamation failed or is delayed).
1543 * Otherwise, wait for some space. In all cases, schedule
1544 * vnlru_proc() if we are getting short of space. The watermarks
1545 * should be chosen so that we never wait or even reclaim from
1546 * the free list to below its target minimum.
1548 if (numvnodes + 1 <= desiredvnodes)
1550 else if (freevnodes > 0)
1551 vnlru_free_locked(1, NULL);
1553 error = getnewvnode_wait(mp != NULL && (mp->mnt_kern_flag &
1555 #if 0 /* XXX Not all VFS_VGET/ffs_vget callers check returns. */
1557 mtx_unlock(&vnode_free_list_mtx);
1563 atomic_add_long(&numvnodes, 1);
1564 mtx_unlock(&vnode_free_list_mtx);
1566 counter_u64_add(vnodes_created, 1);
1567 vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK);
1569 * Locks are given the generic name "vnode" when created.
1570 * Follow the historic practice of using the filesystem
1571 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1573 * Locks live in a witness group keyed on their name. Thus,
1574 * when a lock is renamed, it must also move from the witness
1575 * group of its old name to the witness group of its new name.
1577 * The change only needs to be made when the vnode moves
1578 * from one filesystem type to another. We ensure that each
1579 * filesystem use a single static name pointer for its tag so
1580 * that we can compare pointers rather than doing a strcmp().
1582 lo = &vp->v_vnlock->lock_object;
1583 if (lo->lo_name != tag) {
1585 WITNESS_DESTROY(lo);
1586 WITNESS_INIT(lo, tag);
1589 * By default, don't allow shared locks unless filesystems opt-in.
1591 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1593 * Finalize various vnode identity bits.
1595 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1596 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1597 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1601 v_init_counters(vp);
1602 vp->v_bufobj.bo_ops = &buf_ops_bio;
1604 if (mp == NULL && vops != &dead_vnodeops)
1605 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1609 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1610 mac_vnode_associate_singlelabel(mp, vp);
1613 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1614 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1615 vp->v_vflag |= VV_NOKNOTE;
1619 * For the filesystems which do not use vfs_hash_insert(),
1620 * still initialize v_hash to have vfs_hash_index() useful.
1621 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1624 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1631 * Delete from old mount point vnode list, if on one.
1634 delmntque(struct vnode *vp)
1644 KASSERT(mp->mnt_activevnodelistsize <= mp->mnt_nvnodelistsize,
1645 ("Active vnode list size %d > Vnode list size %d",
1646 mp->mnt_activevnodelistsize, mp->mnt_nvnodelistsize));
1647 active = vp->v_iflag & VI_ACTIVE;
1648 vp->v_iflag &= ~VI_ACTIVE;
1650 mtx_lock(&mp->mnt_listmtx);
1651 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp, v_actfreelist);
1652 mp->mnt_activevnodelistsize--;
1653 mtx_unlock(&mp->mnt_listmtx);
1657 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1658 ("bad mount point vnode list size"));
1659 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1660 mp->mnt_nvnodelistsize--;
1666 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1670 vp->v_op = &dead_vnodeops;
1676 * Insert into list of vnodes for the new mount point, if available.
1679 insmntque1(struct vnode *vp, struct mount *mp,
1680 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1683 KASSERT(vp->v_mount == NULL,
1684 ("insmntque: vnode already on per mount vnode list"));
1685 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1686 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1689 * We acquire the vnode interlock early to ensure that the
1690 * vnode cannot be recycled by another process releasing a
1691 * holdcnt on it before we get it on both the vnode list
1692 * and the active vnode list. The mount mutex protects only
1693 * manipulation of the vnode list and the vnode freelist
1694 * mutex protects only manipulation of the active vnode list.
1695 * Hence the need to hold the vnode interlock throughout.
1699 if (((mp->mnt_kern_flag & MNTK_NOINSMNTQ) != 0 &&
1700 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1701 mp->mnt_nvnodelistsize == 0)) &&
1702 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1711 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1712 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1713 ("neg mount point vnode list size"));
1714 mp->mnt_nvnodelistsize++;
1715 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1716 ("Activating already active vnode"));
1717 vp->v_iflag |= VI_ACTIVE;
1718 mtx_lock(&mp->mnt_listmtx);
1719 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
1720 mp->mnt_activevnodelistsize++;
1721 mtx_unlock(&mp->mnt_listmtx);
1728 insmntque(struct vnode *vp, struct mount *mp)
1731 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1735 * Flush out and invalidate all buffers associated with a bufobj
1736 * Called with the underlying object locked.
1739 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1744 if (flags & V_SAVE) {
1745 error = bufobj_wwait(bo, slpflag, slptimeo);
1750 if (bo->bo_dirty.bv_cnt > 0) {
1752 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1755 * XXX We could save a lock/unlock if this was only
1756 * enabled under INVARIANTS
1759 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1760 panic("vinvalbuf: dirty bufs");
1764 * If you alter this loop please notice that interlock is dropped and
1765 * reacquired in flushbuflist. Special care is needed to ensure that
1766 * no race conditions occur from this.
1769 error = flushbuflist(&bo->bo_clean,
1770 flags, bo, slpflag, slptimeo);
1771 if (error == 0 && !(flags & V_CLEANONLY))
1772 error = flushbuflist(&bo->bo_dirty,
1773 flags, bo, slpflag, slptimeo);
1774 if (error != 0 && error != EAGAIN) {
1778 } while (error != 0);
1781 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1782 * have write I/O in-progress but if there is a VM object then the
1783 * VM object can also have read-I/O in-progress.
1786 bufobj_wwait(bo, 0, 0);
1787 if ((flags & V_VMIO) == 0) {
1789 if (bo->bo_object != NULL) {
1790 VM_OBJECT_WLOCK(bo->bo_object);
1791 vm_object_pip_wait(bo->bo_object, "bovlbx");
1792 VM_OBJECT_WUNLOCK(bo->bo_object);
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");
1981 if (v_inval_buf_range1(vp, bo, startlbn, INT64_MAX) == EAGAIN)
1986 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1987 if (bp->b_lblkno > 0)
1990 * Since we hold the vnode lock this should only
1991 * fail if we're racing with the buf daemon.
1994 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1995 BO_LOCKPTR(bo)) == ENOLCK) {
1998 VNASSERT((bp->b_flags & B_DELWRI), vp,
1999 ("buf(%p) on dirty queue without DELWRI", bp));
2008 bufobj_wwait(bo, 0, 0);
2010 vnode_pager_setsize(vp, length);
2016 * Invalidate the cached pages of a file's buffer within the range of block
2017 * numbers [startlbn, endlbn). Every buffer that overlaps that range will be
2018 * invalidated. This must not result in any dirty data being lost.
2021 v_inval_buf_range(struct vnode *vp, off_t start, off_t end, int blksize)
2024 daddr_t startlbn, endlbn;
2025 vm_pindex_t startp, endp;
2027 /* Round "outwards" */
2028 startlbn = start / blksize;
2029 endlbn = howmany(end, blksize);
2030 startp = OFF_TO_IDX(start);
2031 endp = OFF_TO_IDX(end + PAGE_SIZE - 1);
2033 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2040 struct buf *bp, *nbp;
2042 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2044 * Disallow invalidating dirty data outside of the requested
2045 * offsets. Assume that data within the requested offsets is
2046 * being invalidated for a good reason.
2048 off_t blkstart, blkend;
2050 blkstart = bp->b_offset;
2051 blkend = bp->b_offset + bp->b_bcount;
2052 KASSERT(blkstart >= start && blkend <= end,
2053 ("Invalidating extra dirty data!"));
2057 if (v_inval_buf_range1(vp, bo, startlbn, endlbn) == EAGAIN)
2061 vn_pages_remove(vp, startp, endp);
2064 /* Like v_inval_buf_range, but operates on whole buffers instead of offsets */
2066 v_inval_buf_range1(struct vnode *vp, struct bufobj *bo,
2067 daddr_t startlbn, daddr_t endlbn)
2069 struct buf *bp, *nbp;
2075 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2076 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2079 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2080 BO_LOCKPTR(bo)) == ENOLCK)
2084 bp->b_flags |= (B_INVAL | B_RELBUF);
2085 bp->b_flags &= ~B_ASYNC;
2091 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2092 (nbp->b_vp != vp) ||
2093 (nbp->b_flags & B_DELWRI))) {
2099 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2100 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2103 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2104 BO_LOCKPTR(bo)) == ENOLCK)
2107 bp->b_flags |= (B_INVAL | B_RELBUF);
2108 bp->b_flags &= ~B_ASYNC;
2114 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2115 (nbp->b_vp != vp) ||
2116 (nbp->b_flags & B_DELWRI) == 0)) {
2126 buf_vlist_remove(struct buf *bp)
2130 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2131 ASSERT_BO_WLOCKED(bp->b_bufobj);
2132 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
2133 (BX_VNDIRTY|BX_VNCLEAN),
2134 ("buf_vlist_remove: Buf %p is on two lists", bp));
2135 if (bp->b_xflags & BX_VNDIRTY)
2136 bv = &bp->b_bufobj->bo_dirty;
2138 bv = &bp->b_bufobj->bo_clean;
2139 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2140 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2142 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2146 * Add the buffer to the sorted clean or dirty block list.
2148 * NOTE: xflags is passed as a constant, optimizing this inline function!
2151 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2157 ASSERT_BO_WLOCKED(bo);
2158 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2159 ("dead bo %p", bo));
2160 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2161 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2162 bp->b_xflags |= xflags;
2163 if (xflags & BX_VNDIRTY)
2169 * Keep the list ordered. Optimize empty list insertion. Assume
2170 * we tend to grow at the tail so lookup_le should usually be cheaper
2173 if (bv->bv_cnt == 0 ||
2174 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2175 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2176 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2177 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2179 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2180 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2182 panic("buf_vlist_add: Preallocated nodes insufficient.");
2187 * Look up a buffer using the buffer tries.
2190 gbincore(struct bufobj *bo, daddr_t lblkno)
2194 ASSERT_BO_LOCKED(bo);
2195 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2198 return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
2202 * Associate a buffer with a vnode.
2205 bgetvp(struct vnode *vp, struct buf *bp)
2210 ASSERT_BO_WLOCKED(bo);
2211 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2213 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2214 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2215 ("bgetvp: bp already attached! %p", bp));
2221 * Insert onto list for new vnode.
2223 buf_vlist_add(bp, bo, BX_VNCLEAN);
2227 * Disassociate a buffer from a vnode.
2230 brelvp(struct buf *bp)
2235 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2236 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2239 * Delete from old vnode list, if on one.
2241 vp = bp->b_vp; /* XXX */
2244 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2245 buf_vlist_remove(bp);
2247 panic("brelvp: Buffer %p not on queue.", bp);
2248 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2249 bo->bo_flag &= ~BO_ONWORKLST;
2250 mtx_lock(&sync_mtx);
2251 LIST_REMOVE(bo, bo_synclist);
2252 syncer_worklist_len--;
2253 mtx_unlock(&sync_mtx);
2256 bp->b_bufobj = NULL;
2262 * Add an item to the syncer work queue.
2265 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2269 ASSERT_BO_WLOCKED(bo);
2271 mtx_lock(&sync_mtx);
2272 if (bo->bo_flag & BO_ONWORKLST)
2273 LIST_REMOVE(bo, bo_synclist);
2275 bo->bo_flag |= BO_ONWORKLST;
2276 syncer_worklist_len++;
2279 if (delay > syncer_maxdelay - 2)
2280 delay = syncer_maxdelay - 2;
2281 slot = (syncer_delayno + delay) & syncer_mask;
2283 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2284 mtx_unlock(&sync_mtx);
2288 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2292 mtx_lock(&sync_mtx);
2293 len = syncer_worklist_len - sync_vnode_count;
2294 mtx_unlock(&sync_mtx);
2295 error = SYSCTL_OUT(req, &len, sizeof(len));
2299 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
2300 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2302 static struct proc *updateproc;
2303 static void sched_sync(void);
2304 static struct kproc_desc up_kp = {
2309 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2312 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2317 *bo = LIST_FIRST(slp);
2321 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2324 * We use vhold in case the vnode does not
2325 * successfully sync. vhold prevents the vnode from
2326 * going away when we unlock the sync_mtx so that
2327 * we can acquire the vnode interlock.
2330 mtx_unlock(&sync_mtx);
2332 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2334 mtx_lock(&sync_mtx);
2335 return (*bo == LIST_FIRST(slp));
2337 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2338 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2340 vn_finished_write(mp);
2342 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2344 * Put us back on the worklist. The worklist
2345 * routine will remove us from our current
2346 * position and then add us back in at a later
2349 vn_syncer_add_to_worklist(*bo, syncdelay);
2353 mtx_lock(&sync_mtx);
2357 static int first_printf = 1;
2360 * System filesystem synchronizer daemon.
2365 struct synclist *next, *slp;
2368 struct thread *td = curthread;
2370 int net_worklist_len;
2371 int syncer_final_iter;
2375 syncer_final_iter = 0;
2376 syncer_state = SYNCER_RUNNING;
2377 starttime = time_uptime;
2378 td->td_pflags |= TDP_NORUNNINGBUF;
2380 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2383 mtx_lock(&sync_mtx);
2385 if (syncer_state == SYNCER_FINAL_DELAY &&
2386 syncer_final_iter == 0) {
2387 mtx_unlock(&sync_mtx);
2388 kproc_suspend_check(td->td_proc);
2389 mtx_lock(&sync_mtx);
2391 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2392 if (syncer_state != SYNCER_RUNNING &&
2393 starttime != time_uptime) {
2395 printf("\nSyncing disks, vnodes remaining... ");
2398 printf("%d ", net_worklist_len);
2400 starttime = time_uptime;
2403 * Push files whose dirty time has expired. Be careful
2404 * of interrupt race on slp queue.
2406 * Skip over empty worklist slots when shutting down.
2409 slp = &syncer_workitem_pending[syncer_delayno];
2410 syncer_delayno += 1;
2411 if (syncer_delayno == syncer_maxdelay)
2413 next = &syncer_workitem_pending[syncer_delayno];
2415 * If the worklist has wrapped since the
2416 * it was emptied of all but syncer vnodes,
2417 * switch to the FINAL_DELAY state and run
2418 * for one more second.
2420 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2421 net_worklist_len == 0 &&
2422 last_work_seen == syncer_delayno) {
2423 syncer_state = SYNCER_FINAL_DELAY;
2424 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2426 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2427 syncer_worklist_len > 0);
2430 * Keep track of the last time there was anything
2431 * on the worklist other than syncer vnodes.
2432 * Return to the SHUTTING_DOWN state if any
2435 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2436 last_work_seen = syncer_delayno;
2437 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2438 syncer_state = SYNCER_SHUTTING_DOWN;
2439 while (!LIST_EMPTY(slp)) {
2440 error = sync_vnode(slp, &bo, td);
2442 LIST_REMOVE(bo, bo_synclist);
2443 LIST_INSERT_HEAD(next, bo, bo_synclist);
2447 if (first_printf == 0) {
2449 * Drop the sync mutex, because some watchdog
2450 * drivers need to sleep while patting
2452 mtx_unlock(&sync_mtx);
2453 wdog_kern_pat(WD_LASTVAL);
2454 mtx_lock(&sync_mtx);
2458 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2459 syncer_final_iter--;
2461 * The variable rushjob allows the kernel to speed up the
2462 * processing of the filesystem syncer process. A rushjob
2463 * value of N tells the filesystem syncer to process the next
2464 * N seconds worth of work on its queue ASAP. Currently rushjob
2465 * is used by the soft update code to speed up the filesystem
2466 * syncer process when the incore state is getting so far
2467 * ahead of the disk that the kernel memory pool is being
2468 * threatened with exhaustion.
2475 * Just sleep for a short period of time between
2476 * iterations when shutting down to allow some I/O
2479 * If it has taken us less than a second to process the
2480 * current work, then wait. Otherwise start right over
2481 * again. We can still lose time if any single round
2482 * takes more than two seconds, but it does not really
2483 * matter as we are just trying to generally pace the
2484 * filesystem activity.
2486 if (syncer_state != SYNCER_RUNNING ||
2487 time_uptime == starttime) {
2489 sched_prio(td, PPAUSE);
2492 if (syncer_state != SYNCER_RUNNING)
2493 cv_timedwait(&sync_wakeup, &sync_mtx,
2494 hz / SYNCER_SHUTDOWN_SPEEDUP);
2495 else if (time_uptime == starttime)
2496 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2501 * Request the syncer daemon to speed up its work.
2502 * We never push it to speed up more than half of its
2503 * normal turn time, otherwise it could take over the cpu.
2506 speedup_syncer(void)
2510 mtx_lock(&sync_mtx);
2511 if (rushjob < syncdelay / 2) {
2513 stat_rush_requests += 1;
2516 mtx_unlock(&sync_mtx);
2517 cv_broadcast(&sync_wakeup);
2522 * Tell the syncer to speed up its work and run though its work
2523 * list several times, then tell it to shut down.
2526 syncer_shutdown(void *arg, int howto)
2529 if (howto & RB_NOSYNC)
2531 mtx_lock(&sync_mtx);
2532 syncer_state = SYNCER_SHUTTING_DOWN;
2534 mtx_unlock(&sync_mtx);
2535 cv_broadcast(&sync_wakeup);
2536 kproc_shutdown(arg, howto);
2540 syncer_suspend(void)
2543 syncer_shutdown(updateproc, 0);
2550 mtx_lock(&sync_mtx);
2552 syncer_state = SYNCER_RUNNING;
2553 mtx_unlock(&sync_mtx);
2554 cv_broadcast(&sync_wakeup);
2555 kproc_resume(updateproc);
2559 * Reassign a buffer from one vnode to another.
2560 * Used to assign file specific control information
2561 * (indirect blocks) to the vnode to which they belong.
2564 reassignbuf(struct buf *bp)
2577 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2578 bp, bp->b_vp, bp->b_flags);
2580 * B_PAGING flagged buffers cannot be reassigned because their vp
2581 * is not fully linked in.
2583 if (bp->b_flags & B_PAGING)
2584 panic("cannot reassign paging buffer");
2587 * Delete from old vnode list, if on one.
2590 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2591 buf_vlist_remove(bp);
2593 panic("reassignbuf: Buffer %p not on queue.", bp);
2595 * If dirty, put on list of dirty buffers; otherwise insert onto list
2598 if (bp->b_flags & B_DELWRI) {
2599 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2600 switch (vp->v_type) {
2610 vn_syncer_add_to_worklist(bo, delay);
2612 buf_vlist_add(bp, bo, BX_VNDIRTY);
2614 buf_vlist_add(bp, bo, BX_VNCLEAN);
2616 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2617 mtx_lock(&sync_mtx);
2618 LIST_REMOVE(bo, bo_synclist);
2619 syncer_worklist_len--;
2620 mtx_unlock(&sync_mtx);
2621 bo->bo_flag &= ~BO_ONWORKLST;
2626 bp = TAILQ_FIRST(&bv->bv_hd);
2627 KASSERT(bp == NULL || bp->b_bufobj == bo,
2628 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2629 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2630 KASSERT(bp == NULL || bp->b_bufobj == bo,
2631 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2633 bp = TAILQ_FIRST(&bv->bv_hd);
2634 KASSERT(bp == NULL || bp->b_bufobj == bo,
2635 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2636 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2637 KASSERT(bp == NULL || bp->b_bufobj == bo,
2638 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2644 v_init_counters(struct vnode *vp)
2647 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2648 vp, ("%s called for an initialized vnode", __FUNCTION__));
2649 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2651 refcount_init(&vp->v_holdcnt, 1);
2652 refcount_init(&vp->v_usecount, 1);
2656 v_incr_usecount_locked(struct vnode *vp)
2659 ASSERT_VI_LOCKED(vp, __func__);
2660 if ((vp->v_iflag & VI_OWEINACT) != 0) {
2661 VNASSERT(vp->v_usecount == 0, vp,
2662 ("vnode with usecount and VI_OWEINACT set"));
2663 vp->v_iflag &= ~VI_OWEINACT;
2665 refcount_acquire(&vp->v_usecount);
2666 v_incr_devcount(vp);
2670 * Increment the use count on the vnode, taking care to reference
2671 * the driver's usecount if this is a chardev.
2674 v_incr_usecount(struct vnode *vp)
2677 ASSERT_VI_UNLOCKED(vp, __func__);
2678 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2680 if (vp->v_type != VCHR &&
2681 refcount_acquire_if_not_zero(&vp->v_usecount)) {
2682 VNODE_REFCOUNT_FENCE_ACQ();
2683 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2684 ("vnode with usecount and VI_OWEINACT set"));
2687 v_incr_usecount_locked(vp);
2693 * Increment si_usecount of the associated device, if any.
2696 v_incr_devcount(struct vnode *vp)
2699 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2700 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2702 vp->v_rdev->si_usecount++;
2708 * Decrement si_usecount of the associated device, if any.
2711 v_decr_devcount(struct vnode *vp)
2714 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2715 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2717 vp->v_rdev->si_usecount--;
2723 * Grab a particular vnode from the free list, increment its
2724 * reference count and lock it. VI_DOOMED is set if the vnode
2725 * is being destroyed. Only callers who specify LK_RETRY will
2726 * see doomed vnodes. If inactive processing was delayed in
2727 * vput try to do it here.
2729 * Notes on lockless counter manipulation:
2730 * _vhold, vputx and other routines make various decisions based
2731 * on either holdcnt or usecount being 0. As long as either counter
2732 * is not transitioning 0->1 nor 1->0, the manipulation can be done
2733 * with atomic operations. Otherwise the interlock is taken covering
2734 * both the atomic and additional actions.
2737 vget(struct vnode *vp, int flags, struct thread *td)
2739 int error, oweinact;
2741 VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2742 ("vget: invalid lock operation"));
2744 if ((flags & LK_INTERLOCK) != 0)
2745 ASSERT_VI_LOCKED(vp, __func__);
2747 ASSERT_VI_UNLOCKED(vp, __func__);
2748 if ((flags & LK_VNHELD) != 0)
2749 VNASSERT((vp->v_holdcnt > 0), vp,
2750 ("vget: LK_VNHELD passed but vnode not held"));
2752 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2754 if ((flags & LK_VNHELD) == 0)
2755 _vhold(vp, (flags & LK_INTERLOCK) != 0);
2757 if ((error = vn_lock(vp, flags)) != 0) {
2759 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2763 if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0)
2764 panic("vget: vn_lock failed to return ENOENT\n");
2766 * We don't guarantee that any particular close will
2767 * trigger inactive processing so just make a best effort
2768 * here at preventing a reference to a removed file. If
2769 * we don't succeed no harm is done.
2771 * Upgrade our holdcnt to a usecount.
2773 if (vp->v_type == VCHR ||
2774 !refcount_acquire_if_not_zero(&vp->v_usecount)) {
2776 if ((vp->v_iflag & VI_OWEINACT) == 0) {
2780 vp->v_iflag &= ~VI_OWEINACT;
2781 VNODE_REFCOUNT_FENCE_REL();
2783 refcount_acquire(&vp->v_usecount);
2784 v_incr_devcount(vp);
2785 if (oweinact && VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2786 (flags & LK_NOWAIT) == 0)
2794 * Increase the reference (use) and hold count of a vnode.
2795 * This will also remove the vnode from the free list if it is presently free.
2798 vref(struct vnode *vp)
2801 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2803 v_incr_usecount(vp);
2807 vrefl(struct vnode *vp)
2810 ASSERT_VI_LOCKED(vp, __func__);
2811 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2813 v_incr_usecount_locked(vp);
2817 vrefact(struct vnode *vp)
2820 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2821 if (__predict_false(vp->v_type == VCHR)) {
2822 VNASSERT(vp->v_holdcnt > 0 && vp->v_usecount > 0, vp,
2823 ("%s: wrong ref counts", __func__));
2828 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
2829 VNASSERT(old > 0, vp, ("%s: wrong hold count", __func__));
2830 old = atomic_fetchadd_int(&vp->v_usecount, 1);
2831 VNASSERT(old > 0, vp, ("%s: wrong use count", __func__));
2833 refcount_acquire(&vp->v_holdcnt);
2834 refcount_acquire(&vp->v_usecount);
2839 * Return reference count of a vnode.
2841 * The results of this call are only guaranteed when some mechanism is used to
2842 * stop other processes from gaining references to the vnode. This may be the
2843 * case if the caller holds the only reference. This is also useful when stale
2844 * data is acceptable as race conditions may be accounted for by some other
2848 vrefcnt(struct vnode *vp)
2851 return (vp->v_usecount);
2854 #define VPUTX_VRELE 1
2855 #define VPUTX_VPUT 2
2856 #define VPUTX_VUNREF 3
2859 * Decrement the use and hold counts for a vnode.
2861 * See an explanation near vget() as to why atomic operation is safe.
2864 vputx(struct vnode *vp, int func)
2868 KASSERT(vp != NULL, ("vputx: null vp"));
2869 if (func == VPUTX_VUNREF)
2870 ASSERT_VOP_LOCKED(vp, "vunref");
2871 else if (func == VPUTX_VPUT)
2872 ASSERT_VOP_LOCKED(vp, "vput");
2874 KASSERT(func == VPUTX_VRELE, ("vputx: wrong func"));
2875 ASSERT_VI_UNLOCKED(vp, __func__);
2876 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2878 if (vp->v_type != VCHR &&
2879 refcount_release_if_not_last(&vp->v_usecount)) {
2880 if (func == VPUTX_VPUT)
2889 * We want to hold the vnode until the inactive finishes to
2890 * prevent vgone() races. We drop the use count here and the
2891 * hold count below when we're done.
2893 if (!refcount_release(&vp->v_usecount) ||
2894 (vp->v_iflag & VI_DOINGINACT)) {
2895 if (func == VPUTX_VPUT)
2897 v_decr_devcount(vp);
2902 v_decr_devcount(vp);
2906 if (vp->v_usecount != 0) {
2907 vn_printf(vp, "vputx: usecount not zero for vnode ");
2908 panic("vputx: usecount not zero");
2911 CTR2(KTR_VFS, "%s: return vnode %p to the freelist", __func__, vp);
2914 * We must call VOP_INACTIVE with the node locked. Mark
2915 * as VI_DOINGINACT to avoid recursion.
2917 vp->v_iflag |= VI_OWEINACT;
2920 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
2924 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2925 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
2931 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2932 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
2937 VNASSERT(vp->v_usecount == 0 || (vp->v_iflag & VI_OWEINACT) == 0, vp,
2938 ("vnode with usecount and VI_OWEINACT set"));
2940 if (vp->v_iflag & VI_OWEINACT)
2941 vinactive(vp, curthread);
2942 if (func != VPUTX_VUNREF)
2949 * Vnode put/release.
2950 * If count drops to zero, call inactive routine and return to freelist.
2953 vrele(struct vnode *vp)
2956 vputx(vp, VPUTX_VRELE);
2960 * Release an already locked vnode. This give the same effects as
2961 * unlock+vrele(), but takes less time and avoids releasing and
2962 * re-aquiring the lock (as vrele() acquires the lock internally.)
2965 vput(struct vnode *vp)
2968 vputx(vp, VPUTX_VPUT);
2972 * Release an exclusively locked vnode. Do not unlock the vnode lock.
2975 vunref(struct vnode *vp)
2978 vputx(vp, VPUTX_VUNREF);
2982 * Increase the hold count and activate if this is the first reference.
2985 _vhold(struct vnode *vp, bool locked)
2990 ASSERT_VI_LOCKED(vp, __func__);
2992 ASSERT_VI_UNLOCKED(vp, __func__);
2993 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2995 if (refcount_acquire_if_not_zero(&vp->v_holdcnt)) {
2996 VNODE_REFCOUNT_FENCE_ACQ();
2997 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2998 ("_vhold: vnode with holdcnt is free"));
3003 if ((vp->v_iflag & VI_FREE) == 0) {
3004 refcount_acquire(&vp->v_holdcnt);
3009 VNASSERT(vp->v_holdcnt == 0, vp,
3010 ("%s: wrong hold count", __func__));
3011 VNASSERT(vp->v_op != NULL, vp,
3012 ("%s: vnode already reclaimed.", __func__));
3014 * Remove a vnode from the free list, mark it as in use,
3015 * and put it on the active list.
3017 VNASSERT(vp->v_mount != NULL, vp,
3018 ("_vhold: vnode not on per mount vnode list"));
3020 mtx_lock(&mp->mnt_listmtx);
3021 if ((vp->v_mflag & VMP_TMPMNTFREELIST) != 0) {
3022 TAILQ_REMOVE(&mp->mnt_tmpfreevnodelist, vp, v_actfreelist);
3023 mp->mnt_tmpfreevnodelistsize--;
3024 vp->v_mflag &= ~VMP_TMPMNTFREELIST;
3026 mtx_lock(&vnode_free_list_mtx);
3027 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
3029 mtx_unlock(&vnode_free_list_mtx);
3031 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
3032 ("Activating already active vnode"));
3033 vp->v_iflag &= ~VI_FREE;
3034 vp->v_iflag |= VI_ACTIVE;
3035 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
3036 mp->mnt_activevnodelistsize++;
3037 mtx_unlock(&mp->mnt_listmtx);
3038 refcount_acquire(&vp->v_holdcnt);
3044 * Drop the hold count of the vnode. If this is the last reference to
3045 * the vnode we place it on the free list unless it has been vgone'd
3046 * (marked VI_DOOMED) in which case we will free it.
3048 * Because the vnode vm object keeps a hold reference on the vnode if
3049 * there is at least one resident non-cached page, the vnode cannot
3050 * leave the active list without the page cleanup done.
3053 _vdrop(struct vnode *vp, bool locked)
3060 ASSERT_VI_LOCKED(vp, __func__);
3062 ASSERT_VI_UNLOCKED(vp, __func__);
3063 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3064 if ((int)vp->v_holdcnt <= 0)
3065 panic("vdrop: holdcnt %d", vp->v_holdcnt);
3067 if (refcount_release_if_not_last(&vp->v_holdcnt))
3071 if (refcount_release(&vp->v_holdcnt) == 0) {
3075 if ((vp->v_iflag & VI_DOOMED) == 0) {
3077 * Mark a vnode as free: remove it from its active list
3078 * and put it up for recycling on the freelist.
3080 VNASSERT(vp->v_op != NULL, vp,
3081 ("vdropl: vnode already reclaimed."));
3082 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
3083 ("vnode already free"));
3084 VNASSERT(vp->v_holdcnt == 0, vp,
3085 ("vdropl: freeing when we shouldn't"));
3086 active = vp->v_iflag & VI_ACTIVE;
3087 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3088 vp->v_iflag &= ~VI_ACTIVE;
3091 mtx_lock(&mp->mnt_listmtx);
3093 TAILQ_REMOVE(&mp->mnt_activevnodelist,
3095 mp->mnt_activevnodelistsize--;
3097 TAILQ_INSERT_TAIL(&mp->mnt_tmpfreevnodelist,
3099 mp->mnt_tmpfreevnodelistsize++;
3100 vp->v_iflag |= VI_FREE;
3101 vp->v_mflag |= VMP_TMPMNTFREELIST;
3103 if (mp->mnt_tmpfreevnodelistsize >=
3104 mnt_free_list_batch)
3105 vnlru_return_batch_locked(mp);
3106 mtx_unlock(&mp->mnt_listmtx);
3108 VNASSERT(active == 0, vp,
3109 ("vdropl: active vnode not on per mount "
3111 mtx_lock(&vnode_free_list_mtx);
3112 TAILQ_INSERT_TAIL(&vnode_free_list, vp,
3115 vp->v_iflag |= VI_FREE;
3117 mtx_unlock(&vnode_free_list_mtx);
3121 counter_u64_add(free_owe_inact, 1);
3126 * The vnode has been marked for destruction, so free it.
3128 * The vnode will be returned to the zone where it will
3129 * normally remain until it is needed for another vnode. We
3130 * need to cleanup (or verify that the cleanup has already
3131 * been done) any residual data left from its current use
3132 * so as not to contaminate the freshly allocated vnode.
3134 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
3135 atomic_subtract_long(&numvnodes, 1);
3137 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
3138 ("cleaned vnode still on the free list."));
3139 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
3140 VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
3141 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
3142 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
3143 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
3144 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
3145 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
3146 ("clean blk trie not empty"));
3147 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
3148 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
3149 ("dirty blk trie not empty"));
3150 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
3151 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
3152 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
3153 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
3154 ("Dangling rangelock waiters"));
3157 mac_vnode_destroy(vp);
3159 if (vp->v_pollinfo != NULL) {
3160 destroy_vpollinfo(vp->v_pollinfo);
3161 vp->v_pollinfo = NULL;
3164 /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
3167 vp->v_mountedhere = NULL;
3170 vp->v_fifoinfo = NULL;
3171 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
3175 uma_zfree(vnode_zone, vp);
3179 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3180 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3181 * OWEINACT tracks whether a vnode missed a call to inactive due to a
3182 * failed lock upgrade.
3185 vinactive(struct vnode *vp, struct thread *td)
3187 struct vm_object *obj;
3189 ASSERT_VOP_ELOCKED(vp, "vinactive");
3190 ASSERT_VI_LOCKED(vp, "vinactive");
3191 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3192 ("vinactive: recursed on VI_DOINGINACT"));
3193 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3194 vp->v_iflag |= VI_DOINGINACT;
3195 vp->v_iflag &= ~VI_OWEINACT;
3198 * Before moving off the active list, we must be sure that any
3199 * modified pages are converted into the vnode's dirty
3200 * buffers, since these will no longer be checked once the
3201 * vnode is on the inactive list.
3203 * The write-out of the dirty pages is asynchronous. At the
3204 * point that VOP_INACTIVE() is called, there could still be
3205 * pending I/O and dirty pages in the object.
3207 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3208 (obj->flags & OBJ_MIGHTBEDIRTY) != 0) {
3209 VM_OBJECT_WLOCK(obj);
3210 vm_object_page_clean(obj, 0, 0, 0);
3211 VM_OBJECT_WUNLOCK(obj);
3213 VOP_INACTIVE(vp, td);
3215 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3216 ("vinactive: lost VI_DOINGINACT"));
3217 vp->v_iflag &= ~VI_DOINGINACT;
3221 * Remove any vnodes in the vnode table belonging to mount point mp.
3223 * If FORCECLOSE is not specified, there should not be any active ones,
3224 * return error if any are found (nb: this is a user error, not a
3225 * system error). If FORCECLOSE is specified, detach any active vnodes
3228 * If WRITECLOSE is set, only flush out regular file vnodes open for
3231 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3233 * `rootrefs' specifies the base reference count for the root vnode
3234 * of this filesystem. The root vnode is considered busy if its
3235 * v_usecount exceeds this value. On a successful return, vflush(, td)
3236 * will call vrele() on the root vnode exactly rootrefs times.
3237 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3241 static int busyprt = 0; /* print out busy vnodes */
3242 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3246 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3248 struct vnode *vp, *mvp, *rootvp = NULL;
3250 int busy = 0, error;
3252 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3255 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3256 ("vflush: bad args"));
3258 * Get the filesystem root vnode. We can vput() it
3259 * immediately, since with rootrefs > 0, it won't go away.
3261 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3262 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3269 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3271 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3274 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3278 * Skip over a vnodes marked VV_SYSTEM.
3280 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3286 * If WRITECLOSE is set, flush out unlinked but still open
3287 * files (even if open only for reading) and regular file
3288 * vnodes open for writing.
3290 if (flags & WRITECLOSE) {
3291 if (vp->v_object != NULL) {
3292 VM_OBJECT_WLOCK(vp->v_object);
3293 vm_object_page_clean(vp->v_object, 0, 0, 0);
3294 VM_OBJECT_WUNLOCK(vp->v_object);
3296 error = VOP_FSYNC(vp, MNT_WAIT, td);
3300 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3303 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3306 if ((vp->v_type == VNON ||
3307 (error == 0 && vattr.va_nlink > 0)) &&
3308 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3316 * With v_usecount == 0, all we need to do is clear out the
3317 * vnode data structures and we are done.
3319 * If FORCECLOSE is set, forcibly close the vnode.
3321 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3327 vn_printf(vp, "vflush: busy vnode ");
3333 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3335 * If just the root vnode is busy, and if its refcount
3336 * is equal to `rootrefs', then go ahead and kill it.
3339 KASSERT(busy > 0, ("vflush: not busy"));
3340 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3341 ("vflush: usecount %d < rootrefs %d",
3342 rootvp->v_usecount, rootrefs));
3343 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3344 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3346 VOP_UNLOCK(rootvp, 0);
3352 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3356 for (; rootrefs > 0; rootrefs--)
3362 * Recycle an unused vnode to the front of the free list.
3365 vrecycle(struct vnode *vp)
3370 recycled = vrecyclel(vp);
3376 * vrecycle, with the vp interlock held.
3379 vrecyclel(struct vnode *vp)
3383 ASSERT_VOP_ELOCKED(vp, __func__);
3384 ASSERT_VI_LOCKED(vp, __func__);
3385 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3387 if (vp->v_usecount == 0) {
3395 * Eliminate all activity associated with a vnode
3396 * in preparation for reuse.
3399 vgone(struct vnode *vp)
3407 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3408 struct vnode *lowervp __unused)
3413 * Notify upper mounts about reclaimed or unlinked vnode.
3416 vfs_notify_upper(struct vnode *vp, int event)
3418 static struct vfsops vgonel_vfsops = {
3419 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3420 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3422 struct mount *mp, *ump, *mmp;
3429 if (TAILQ_EMPTY(&mp->mnt_uppers))
3432 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3433 mmp->mnt_op = &vgonel_vfsops;
3434 mmp->mnt_kern_flag |= MNTK_MARKER;
3436 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3437 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3438 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3439 ump = TAILQ_NEXT(ump, mnt_upper_link);
3442 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3445 case VFS_NOTIFY_UPPER_RECLAIM:
3446 VFS_RECLAIM_LOWERVP(ump, vp);
3448 case VFS_NOTIFY_UPPER_UNLINK:
3449 VFS_UNLINK_LOWERVP(ump, vp);
3452 KASSERT(0, ("invalid event %d", event));
3456 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3457 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3460 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3461 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3462 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3463 wakeup(&mp->mnt_uppers);
3470 * vgone, with the vp interlock held.
3473 vgonel(struct vnode *vp)
3480 ASSERT_VOP_ELOCKED(vp, "vgonel");
3481 ASSERT_VI_LOCKED(vp, "vgonel");
3482 VNASSERT(vp->v_holdcnt, vp,
3483 ("vgonel: vp %p has no reference.", vp));
3484 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3488 * Don't vgonel if we're already doomed.
3490 if (vp->v_iflag & VI_DOOMED)
3492 vp->v_iflag |= VI_DOOMED;
3495 * Check to see if the vnode is in use. If so, we have to call
3496 * VOP_CLOSE() and VOP_INACTIVE().
3498 active = vp->v_usecount;
3499 oweinact = (vp->v_iflag & VI_OWEINACT);
3501 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
3504 * If purging an active vnode, it must be closed and
3505 * deactivated before being reclaimed.
3508 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
3509 if (oweinact || active) {
3511 if ((vp->v_iflag & VI_DOINGINACT) == 0)
3515 if (vp->v_type == VSOCK)
3516 vfs_unp_reclaim(vp);
3519 * Clean out any buffers associated with the vnode.
3520 * If the flush fails, just toss the buffers.
3523 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
3524 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
3525 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
3526 while (vinvalbuf(vp, 0, 0, 0) != 0)
3530 BO_LOCK(&vp->v_bufobj);
3531 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
3532 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
3533 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
3534 vp->v_bufobj.bo_clean.bv_cnt == 0,
3535 ("vp %p bufobj not invalidated", vp));
3538 * For VMIO bufobj, BO_DEAD is set in vm_object_terminate()
3539 * after the object's page queue is flushed.
3541 if (vp->v_bufobj.bo_object == NULL)
3542 vp->v_bufobj.bo_flag |= BO_DEAD;
3543 BO_UNLOCK(&vp->v_bufobj);
3546 * Reclaim the vnode.
3548 if (VOP_RECLAIM(vp, td))
3549 panic("vgone: cannot reclaim");
3551 vn_finished_secondary_write(mp);
3552 VNASSERT(vp->v_object == NULL, vp,
3553 ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
3555 * Clear the advisory locks and wake up waiting threads.
3557 (void)VOP_ADVLOCKPURGE(vp);
3560 * Delete from old mount point vnode list.
3565 * Done with purge, reset to the standard lock and invalidate
3569 vp->v_vnlock = &vp->v_lock;
3570 vp->v_op = &dead_vnodeops;
3576 * Calculate the total number of references to a special device.
3579 vcount(struct vnode *vp)
3584 count = vp->v_rdev->si_usecount;
3590 * Same as above, but using the struct cdev *as argument
3593 count_dev(struct cdev *dev)
3598 count = dev->si_usecount;
3604 * Print out a description of a vnode.
3606 static char *typename[] =
3607 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
3611 vn_printf(struct vnode *vp, const char *fmt, ...)
3614 char buf[256], buf2[16];
3620 printf("%p: ", (void *)vp);
3621 printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
3622 printf(" usecount %d, writecount %d, refcount %d",
3623 vp->v_usecount, vp->v_writecount, vp->v_holdcnt);
3624 switch (vp->v_type) {
3626 printf(" mountedhere %p\n", vp->v_mountedhere);
3629 printf(" rdev %p\n", vp->v_rdev);
3632 printf(" socket %p\n", vp->v_unpcb);
3635 printf(" fifoinfo %p\n", vp->v_fifoinfo);
3643 if (vp->v_vflag & VV_ROOT)
3644 strlcat(buf, "|VV_ROOT", sizeof(buf));
3645 if (vp->v_vflag & VV_ISTTY)
3646 strlcat(buf, "|VV_ISTTY", sizeof(buf));
3647 if (vp->v_vflag & VV_NOSYNC)
3648 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
3649 if (vp->v_vflag & VV_ETERNALDEV)
3650 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
3651 if (vp->v_vflag & VV_CACHEDLABEL)
3652 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
3653 if (vp->v_vflag & VV_COPYONWRITE)
3654 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
3655 if (vp->v_vflag & VV_SYSTEM)
3656 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
3657 if (vp->v_vflag & VV_PROCDEP)
3658 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
3659 if (vp->v_vflag & VV_NOKNOTE)
3660 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
3661 if (vp->v_vflag & VV_DELETED)
3662 strlcat(buf, "|VV_DELETED", sizeof(buf));
3663 if (vp->v_vflag & VV_MD)
3664 strlcat(buf, "|VV_MD", sizeof(buf));
3665 if (vp->v_vflag & VV_FORCEINSMQ)
3666 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
3667 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
3668 VV_CACHEDLABEL | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
3669 VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
3671 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
3672 strlcat(buf, buf2, sizeof(buf));
3674 if (vp->v_iflag & VI_MOUNT)
3675 strlcat(buf, "|VI_MOUNT", sizeof(buf));
3676 if (vp->v_iflag & VI_DOOMED)
3677 strlcat(buf, "|VI_DOOMED", sizeof(buf));
3678 if (vp->v_iflag & VI_FREE)
3679 strlcat(buf, "|VI_FREE", sizeof(buf));
3680 if (vp->v_iflag & VI_ACTIVE)
3681 strlcat(buf, "|VI_ACTIVE", sizeof(buf));
3682 if (vp->v_iflag & VI_DOINGINACT)
3683 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
3684 if (vp->v_iflag & VI_OWEINACT)
3685 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
3686 flags = vp->v_iflag & ~(VI_MOUNT | VI_DOOMED | VI_FREE |
3687 VI_ACTIVE | VI_DOINGINACT | VI_OWEINACT);
3689 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
3690 strlcat(buf, buf2, sizeof(buf));
3692 printf(" flags (%s)\n", buf + 1);
3693 if (mtx_owned(VI_MTX(vp)))
3694 printf(" VI_LOCKed");
3695 if (vp->v_object != NULL)
3696 printf(" v_object %p ref %d pages %d "
3697 "cleanbuf %d dirtybuf %d\n",
3698 vp->v_object, vp->v_object->ref_count,
3699 vp->v_object->resident_page_count,
3700 vp->v_bufobj.bo_clean.bv_cnt,
3701 vp->v_bufobj.bo_dirty.bv_cnt);
3703 lockmgr_printinfo(vp->v_vnlock);
3704 if (vp->v_data != NULL)
3710 * List all of the locked vnodes in the system.
3711 * Called when debugging the kernel.
3713 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
3719 * Note: because this is DDB, we can't obey the locking semantics
3720 * for these structures, which means we could catch an inconsistent
3721 * state and dereference a nasty pointer. Not much to be done
3724 db_printf("Locked vnodes\n");
3725 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3726 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3727 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
3728 vn_printf(vp, "vnode ");
3734 * Show details about the given vnode.
3736 DB_SHOW_COMMAND(vnode, db_show_vnode)
3742 vp = (struct vnode *)addr;
3743 vn_printf(vp, "vnode ");
3747 * Show details about the given mount point.
3749 DB_SHOW_COMMAND(mount, db_show_mount)
3760 /* No address given, print short info about all mount points. */
3761 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3762 db_printf("%p %s on %s (%s)\n", mp,
3763 mp->mnt_stat.f_mntfromname,
3764 mp->mnt_stat.f_mntonname,
3765 mp->mnt_stat.f_fstypename);
3769 db_printf("\nMore info: show mount <addr>\n");
3773 mp = (struct mount *)addr;
3774 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
3775 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
3778 mflags = mp->mnt_flag;
3779 #define MNT_FLAG(flag) do { \
3780 if (mflags & (flag)) { \
3781 if (buf[0] != '\0') \
3782 strlcat(buf, ", ", sizeof(buf)); \
3783 strlcat(buf, (#flag) + 4, sizeof(buf)); \
3784 mflags &= ~(flag); \
3787 MNT_FLAG(MNT_RDONLY);
3788 MNT_FLAG(MNT_SYNCHRONOUS);
3789 MNT_FLAG(MNT_NOEXEC);
3790 MNT_FLAG(MNT_NOSUID);
3791 MNT_FLAG(MNT_NFS4ACLS);
3792 MNT_FLAG(MNT_UNION);
3793 MNT_FLAG(MNT_ASYNC);
3794 MNT_FLAG(MNT_SUIDDIR);
3795 MNT_FLAG(MNT_SOFTDEP);
3796 MNT_FLAG(MNT_NOSYMFOLLOW);
3797 MNT_FLAG(MNT_GJOURNAL);
3798 MNT_FLAG(MNT_MULTILABEL);
3800 MNT_FLAG(MNT_NOATIME);
3801 MNT_FLAG(MNT_NOCLUSTERR);
3802 MNT_FLAG(MNT_NOCLUSTERW);
3804 MNT_FLAG(MNT_EXRDONLY);
3805 MNT_FLAG(MNT_EXPORTED);
3806 MNT_FLAG(MNT_DEFEXPORTED);
3807 MNT_FLAG(MNT_EXPORTANON);
3808 MNT_FLAG(MNT_EXKERB);
3809 MNT_FLAG(MNT_EXPUBLIC);
3810 MNT_FLAG(MNT_LOCAL);
3811 MNT_FLAG(MNT_QUOTA);
3812 MNT_FLAG(MNT_ROOTFS);
3814 MNT_FLAG(MNT_IGNORE);
3815 MNT_FLAG(MNT_UPDATE);
3816 MNT_FLAG(MNT_DELEXPORT);
3817 MNT_FLAG(MNT_RELOAD);
3818 MNT_FLAG(MNT_FORCE);
3819 MNT_FLAG(MNT_SNAPSHOT);
3820 MNT_FLAG(MNT_BYFSID);
3824 strlcat(buf, ", ", sizeof(buf));
3825 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3826 "0x%016jx", mflags);
3828 db_printf(" mnt_flag = %s\n", buf);
3831 flags = mp->mnt_kern_flag;
3832 #define MNT_KERN_FLAG(flag) do { \
3833 if (flags & (flag)) { \
3834 if (buf[0] != '\0') \
3835 strlcat(buf, ", ", sizeof(buf)); \
3836 strlcat(buf, (#flag) + 5, sizeof(buf)); \
3840 MNT_KERN_FLAG(MNTK_UNMOUNTF);
3841 MNT_KERN_FLAG(MNTK_ASYNC);
3842 MNT_KERN_FLAG(MNTK_SOFTDEP);
3843 MNT_KERN_FLAG(MNTK_NOINSMNTQ);
3844 MNT_KERN_FLAG(MNTK_DRAINING);
3845 MNT_KERN_FLAG(MNTK_REFEXPIRE);
3846 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
3847 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
3848 MNT_KERN_FLAG(MNTK_NO_IOPF);
3849 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
3850 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
3851 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
3852 MNT_KERN_FLAG(MNTK_MARKER);
3853 MNT_KERN_FLAG(MNTK_USES_BCACHE);
3854 MNT_KERN_FLAG(MNTK_NOASYNC);
3855 MNT_KERN_FLAG(MNTK_UNMOUNT);
3856 MNT_KERN_FLAG(MNTK_MWAIT);
3857 MNT_KERN_FLAG(MNTK_SUSPEND);
3858 MNT_KERN_FLAG(MNTK_SUSPEND2);
3859 MNT_KERN_FLAG(MNTK_SUSPENDED);
3860 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
3861 MNT_KERN_FLAG(MNTK_NOKNOTE);
3862 #undef MNT_KERN_FLAG
3865 strlcat(buf, ", ", sizeof(buf));
3866 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3869 db_printf(" mnt_kern_flag = %s\n", buf);
3871 db_printf(" mnt_opt = ");
3872 opt = TAILQ_FIRST(mp->mnt_opt);
3874 db_printf("%s", opt->name);
3875 opt = TAILQ_NEXT(opt, link);
3876 while (opt != NULL) {
3877 db_printf(", %s", opt->name);
3878 opt = TAILQ_NEXT(opt, link);
3884 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
3885 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
3886 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
3887 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
3888 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
3889 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
3890 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
3891 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
3892 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
3893 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
3894 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
3895 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
3897 db_printf(" mnt_cred = { uid=%u ruid=%u",
3898 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
3899 if (jailed(mp->mnt_cred))
3900 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
3902 db_printf(" mnt_ref = %d\n", mp->mnt_ref);
3903 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
3904 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
3905 db_printf(" mnt_activevnodelistsize = %d\n",
3906 mp->mnt_activevnodelistsize);
3907 db_printf(" mnt_writeopcount = %d\n", mp->mnt_writeopcount);
3908 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
3909 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
3910 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
3911 db_printf(" mnt_lockref = %d\n", mp->mnt_lockref);
3912 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
3913 db_printf(" mnt_secondary_accwrites = %d\n",
3914 mp->mnt_secondary_accwrites);
3915 db_printf(" mnt_gjprovider = %s\n",
3916 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
3918 db_printf("\n\nList of active vnodes\n");
3919 TAILQ_FOREACH(vp, &mp->mnt_activevnodelist, v_actfreelist) {
3920 if (vp->v_type != VMARKER) {
3921 vn_printf(vp, "vnode ");
3926 db_printf("\n\nList of inactive vnodes\n");
3927 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3928 if (vp->v_type != VMARKER && (vp->v_iflag & VI_ACTIVE) == 0) {
3929 vn_printf(vp, "vnode ");
3938 * Fill in a struct xvfsconf based on a struct vfsconf.
3941 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
3943 struct xvfsconf xvfsp;
3945 bzero(&xvfsp, sizeof(xvfsp));
3946 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
3947 xvfsp.vfc_typenum = vfsp->vfc_typenum;
3948 xvfsp.vfc_refcount = vfsp->vfc_refcount;
3949 xvfsp.vfc_flags = vfsp->vfc_flags;
3951 * These are unused in userland, we keep them
3952 * to not break binary compatibility.
3954 xvfsp.vfc_vfsops = NULL;
3955 xvfsp.vfc_next = NULL;
3956 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3959 #ifdef COMPAT_FREEBSD32
3961 uint32_t vfc_vfsops;
3962 char vfc_name[MFSNAMELEN];
3963 int32_t vfc_typenum;
3964 int32_t vfc_refcount;
3970 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
3972 struct xvfsconf32 xvfsp;
3974 bzero(&xvfsp, sizeof(xvfsp));
3975 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
3976 xvfsp.vfc_typenum = vfsp->vfc_typenum;
3977 xvfsp.vfc_refcount = vfsp->vfc_refcount;
3978 xvfsp.vfc_flags = vfsp->vfc_flags;
3979 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3984 * Top level filesystem related information gathering.
3987 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
3989 struct vfsconf *vfsp;
3994 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3995 #ifdef COMPAT_FREEBSD32
3996 if (req->flags & SCTL_MASK32)
3997 error = vfsconf2x32(req, vfsp);
4000 error = vfsconf2x(req, vfsp);
4008 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4009 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4010 "S,xvfsconf", "List of all configured filesystems");
4012 #ifndef BURN_BRIDGES
4013 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4016 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4018 int *name = (int *)arg1 - 1; /* XXX */
4019 u_int namelen = arg2 + 1; /* XXX */
4020 struct vfsconf *vfsp;
4022 log(LOG_WARNING, "userland calling deprecated sysctl, "
4023 "please rebuild world\n");
4025 #if 1 || defined(COMPAT_PRELITE2)
4026 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4028 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4032 case VFS_MAXTYPENUM:
4035 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4038 return (ENOTDIR); /* overloaded */
4040 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4041 if (vfsp->vfc_typenum == name[2])
4046 return (EOPNOTSUPP);
4047 #ifdef COMPAT_FREEBSD32
4048 if (req->flags & SCTL_MASK32)
4049 return (vfsconf2x32(req, vfsp));
4052 return (vfsconf2x(req, vfsp));
4054 return (EOPNOTSUPP);
4057 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4058 CTLFLAG_MPSAFE, vfs_sysctl,
4059 "Generic filesystem");
4061 #if 1 || defined(COMPAT_PRELITE2)
4064 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4067 struct vfsconf *vfsp;
4068 struct ovfsconf ovfs;
4071 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4072 bzero(&ovfs, sizeof(ovfs));
4073 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4074 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4075 ovfs.vfc_index = vfsp->vfc_typenum;
4076 ovfs.vfc_refcount = vfsp->vfc_refcount;
4077 ovfs.vfc_flags = vfsp->vfc_flags;
4078 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4088 #endif /* 1 || COMPAT_PRELITE2 */
4089 #endif /* !BURN_BRIDGES */
4091 #define KINFO_VNODESLOP 10
4094 * Dump vnode list (via sysctl).
4098 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4106 * Stale numvnodes access is not fatal here.
4109 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4111 /* Make an estimate */
4112 return (SYSCTL_OUT(req, 0, len));
4114 error = sysctl_wire_old_buffer(req, 0);
4117 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4119 mtx_lock(&mountlist_mtx);
4120 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4121 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4124 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4128 xvn[n].xv_size = sizeof *xvn;
4129 xvn[n].xv_vnode = vp;
4130 xvn[n].xv_id = 0; /* XXX compat */
4131 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4133 XV_COPY(writecount);
4139 xvn[n].xv_flag = vp->v_vflag;
4141 switch (vp->v_type) {
4148 if (vp->v_rdev == NULL) {
4152 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4155 xvn[n].xv_socket = vp->v_socket;
4158 xvn[n].xv_fifo = vp->v_fifoinfo;
4163 /* shouldn't happen? */
4171 mtx_lock(&mountlist_mtx);
4176 mtx_unlock(&mountlist_mtx);
4178 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4183 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4184 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4189 unmount_or_warn(struct mount *mp)
4193 error = dounmount(mp, MNT_FORCE, curthread);
4195 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4199 printf("%d)\n", error);
4204 * Unmount all filesystems. The list is traversed in reverse order
4205 * of mounting to avoid dependencies.
4208 vfs_unmountall(void)
4210 struct mount *mp, *tmp;
4212 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4215 * Since this only runs when rebooting, it is not interlocked.
4217 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4221 * Forcibly unmounting "/dev" before "/" would prevent clean
4222 * unmount of the latter.
4224 if (mp == rootdevmp)
4227 unmount_or_warn(mp);
4230 if (rootdevmp != NULL)
4231 unmount_or_warn(rootdevmp);
4235 * perform msync on all vnodes under a mount point
4236 * the mount point must be locked.
4239 vfs_msync(struct mount *mp, int flags)
4241 struct vnode *vp, *mvp;
4242 struct vm_object *obj;
4244 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4246 vnlru_return_batch(mp);
4248 MNT_VNODE_FOREACH_ACTIVE(vp, mp, mvp) {
4250 if (obj != NULL && (obj->flags & OBJ_MIGHTBEDIRTY) != 0 &&
4251 (flags == MNT_WAIT || VOP_ISLOCKED(vp) == 0)) {
4253 LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
4255 if (vp->v_vflag & VV_NOSYNC) { /* unlinked */
4262 VM_OBJECT_WLOCK(obj);
4263 vm_object_page_clean(obj, 0, 0,
4265 OBJPC_SYNC : OBJPC_NOSYNC);
4266 VM_OBJECT_WUNLOCK(obj);
4276 destroy_vpollinfo_free(struct vpollinfo *vi)
4279 knlist_destroy(&vi->vpi_selinfo.si_note);
4280 mtx_destroy(&vi->vpi_lock);
4281 uma_zfree(vnodepoll_zone, vi);
4285 destroy_vpollinfo(struct vpollinfo *vi)
4288 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4289 seldrain(&vi->vpi_selinfo);
4290 destroy_vpollinfo_free(vi);
4294 * Initialize per-vnode helper structure to hold poll-related state.
4297 v_addpollinfo(struct vnode *vp)
4299 struct vpollinfo *vi;
4301 if (vp->v_pollinfo != NULL)
4303 vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4304 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4305 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4306 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4308 if (vp->v_pollinfo != NULL) {
4310 destroy_vpollinfo_free(vi);
4313 vp->v_pollinfo = vi;
4318 * Record a process's interest in events which might happen to
4319 * a vnode. Because poll uses the historic select-style interface
4320 * internally, this routine serves as both the ``check for any
4321 * pending events'' and the ``record my interest in future events''
4322 * functions. (These are done together, while the lock is held,
4323 * to avoid race conditions.)
4326 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4330 mtx_lock(&vp->v_pollinfo->vpi_lock);
4331 if (vp->v_pollinfo->vpi_revents & events) {
4333 * This leaves events we are not interested
4334 * in available for the other process which
4335 * which presumably had requested them
4336 * (otherwise they would never have been
4339 events &= vp->v_pollinfo->vpi_revents;
4340 vp->v_pollinfo->vpi_revents &= ~events;
4342 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4345 vp->v_pollinfo->vpi_events |= events;
4346 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4347 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4352 * Routine to create and manage a filesystem syncer vnode.
4354 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4355 static int sync_fsync(struct vop_fsync_args *);
4356 static int sync_inactive(struct vop_inactive_args *);
4357 static int sync_reclaim(struct vop_reclaim_args *);
4359 static struct vop_vector sync_vnodeops = {
4360 .vop_bypass = VOP_EOPNOTSUPP,
4361 .vop_close = sync_close, /* close */
4362 .vop_fsync = sync_fsync, /* fsync */
4363 .vop_inactive = sync_inactive, /* inactive */
4364 .vop_reclaim = sync_reclaim, /* reclaim */
4365 .vop_lock1 = vop_stdlock, /* lock */
4366 .vop_unlock = vop_stdunlock, /* unlock */
4367 .vop_islocked = vop_stdislocked, /* islocked */
4371 * Create a new filesystem syncer vnode for the specified mount point.
4374 vfs_allocate_syncvnode(struct mount *mp)
4378 static long start, incr, next;
4381 /* Allocate a new vnode */
4382 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
4384 panic("vfs_allocate_syncvnode: getnewvnode() failed");
4386 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4387 vp->v_vflag |= VV_FORCEINSMQ;
4388 error = insmntque(vp, mp);
4390 panic("vfs_allocate_syncvnode: insmntque() failed");
4391 vp->v_vflag &= ~VV_FORCEINSMQ;
4394 * Place the vnode onto the syncer worklist. We attempt to
4395 * scatter them about on the list so that they will go off
4396 * at evenly distributed times even if all the filesystems
4397 * are mounted at once.
4400 if (next == 0 || next > syncer_maxdelay) {
4404 start = syncer_maxdelay / 2;
4405 incr = syncer_maxdelay;
4411 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
4412 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
4413 mtx_lock(&sync_mtx);
4415 if (mp->mnt_syncer == NULL) {
4416 mp->mnt_syncer = vp;
4419 mtx_unlock(&sync_mtx);
4422 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4429 vfs_deallocate_syncvnode(struct mount *mp)
4433 mtx_lock(&sync_mtx);
4434 vp = mp->mnt_syncer;
4436 mp->mnt_syncer = NULL;
4437 mtx_unlock(&sync_mtx);
4443 * Do a lazy sync of the filesystem.
4446 sync_fsync(struct vop_fsync_args *ap)
4448 struct vnode *syncvp = ap->a_vp;
4449 struct mount *mp = syncvp->v_mount;
4454 * We only need to do something if this is a lazy evaluation.
4456 if (ap->a_waitfor != MNT_LAZY)
4460 * Move ourselves to the back of the sync list.
4462 bo = &syncvp->v_bufobj;
4464 vn_syncer_add_to_worklist(bo, syncdelay);
4468 * Walk the list of vnodes pushing all that are dirty and
4469 * not already on the sync list.
4471 if (vfs_busy(mp, MBF_NOWAIT) != 0)
4473 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
4477 save = curthread_pflags_set(TDP_SYNCIO);
4478 vfs_msync(mp, MNT_NOWAIT);
4479 error = VFS_SYNC(mp, MNT_LAZY);
4480 curthread_pflags_restore(save);
4481 vn_finished_write(mp);
4487 * The syncer vnode is no referenced.
4490 sync_inactive(struct vop_inactive_args *ap)
4498 * The syncer vnode is no longer needed and is being decommissioned.
4500 * Modifications to the worklist must be protected by sync_mtx.
4503 sync_reclaim(struct vop_reclaim_args *ap)
4505 struct vnode *vp = ap->a_vp;
4510 mtx_lock(&sync_mtx);
4511 if (vp->v_mount->mnt_syncer == vp)
4512 vp->v_mount->mnt_syncer = NULL;
4513 if (bo->bo_flag & BO_ONWORKLST) {
4514 LIST_REMOVE(bo, bo_synclist);
4515 syncer_worklist_len--;
4517 bo->bo_flag &= ~BO_ONWORKLST;
4519 mtx_unlock(&sync_mtx);
4526 * Check if vnode represents a disk device
4529 vn_isdisk(struct vnode *vp, int *errp)
4533 if (vp->v_type != VCHR) {
4539 if (vp->v_rdev == NULL)
4541 else if (vp->v_rdev->si_devsw == NULL)
4543 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
4549 return (error == 0);
4553 * Common filesystem object access control check routine. Accepts a
4554 * vnode's type, "mode", uid and gid, requested access mode, credentials,
4555 * and optional call-by-reference privused argument allowing vaccess()
4556 * to indicate to the caller whether privilege was used to satisfy the
4557 * request (obsoleted). Returns 0 on success, or an errno on failure.
4560 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
4561 accmode_t accmode, struct ucred *cred, int *privused)
4563 accmode_t dac_granted;
4564 accmode_t priv_granted;
4566 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
4567 ("invalid bit in accmode"));
4568 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
4569 ("VAPPEND without VWRITE"));
4572 * Look for a normal, non-privileged way to access the file/directory
4573 * as requested. If it exists, go with that.
4576 if (privused != NULL)
4581 /* Check the owner. */
4582 if (cred->cr_uid == file_uid) {
4583 dac_granted |= VADMIN;
4584 if (file_mode & S_IXUSR)
4585 dac_granted |= VEXEC;
4586 if (file_mode & S_IRUSR)
4587 dac_granted |= VREAD;
4588 if (file_mode & S_IWUSR)
4589 dac_granted |= (VWRITE | VAPPEND);
4591 if ((accmode & dac_granted) == accmode)
4597 /* Otherwise, check the groups (first match) */
4598 if (groupmember(file_gid, cred)) {
4599 if (file_mode & S_IXGRP)
4600 dac_granted |= VEXEC;
4601 if (file_mode & S_IRGRP)
4602 dac_granted |= VREAD;
4603 if (file_mode & S_IWGRP)
4604 dac_granted |= (VWRITE | VAPPEND);
4606 if ((accmode & dac_granted) == accmode)
4612 /* Otherwise, check everyone else. */
4613 if (file_mode & S_IXOTH)
4614 dac_granted |= VEXEC;
4615 if (file_mode & S_IROTH)
4616 dac_granted |= VREAD;
4617 if (file_mode & S_IWOTH)
4618 dac_granted |= (VWRITE | VAPPEND);
4619 if ((accmode & dac_granted) == accmode)
4624 * Build a privilege mask to determine if the set of privileges
4625 * satisfies the requirements when combined with the granted mask
4626 * from above. For each privilege, if the privilege is required,
4627 * bitwise or the request type onto the priv_granted mask.
4633 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
4634 * requests, instead of PRIV_VFS_EXEC.
4636 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4637 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
4638 priv_granted |= VEXEC;
4641 * Ensure that at least one execute bit is on. Otherwise,
4642 * a privileged user will always succeed, and we don't want
4643 * this to happen unless the file really is executable.
4645 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4646 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
4647 !priv_check_cred(cred, PRIV_VFS_EXEC))
4648 priv_granted |= VEXEC;
4651 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
4652 !priv_check_cred(cred, PRIV_VFS_READ))
4653 priv_granted |= VREAD;
4655 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
4656 !priv_check_cred(cred, PRIV_VFS_WRITE))
4657 priv_granted |= (VWRITE | VAPPEND);
4659 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
4660 !priv_check_cred(cred, PRIV_VFS_ADMIN))
4661 priv_granted |= VADMIN;
4663 if ((accmode & (priv_granted | dac_granted)) == accmode) {
4664 /* XXX audit: privilege used */
4665 if (privused != NULL)
4670 return ((accmode & VADMIN) ? EPERM : EACCES);
4674 * Credential check based on process requesting service, and per-attribute
4678 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
4679 struct thread *td, accmode_t accmode)
4683 * Kernel-invoked always succeeds.
4689 * Do not allow privileged processes in jail to directly manipulate
4690 * system attributes.
4692 switch (attrnamespace) {
4693 case EXTATTR_NAMESPACE_SYSTEM:
4694 /* Potentially should be: return (EPERM); */
4695 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
4696 case EXTATTR_NAMESPACE_USER:
4697 return (VOP_ACCESS(vp, accmode, cred, td));
4703 #ifdef DEBUG_VFS_LOCKS
4705 * This only exists to suppress warnings from unlocked specfs accesses. It is
4706 * no longer ok to have an unlocked VFS.
4708 #define IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL || \
4709 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
4711 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
4712 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
4713 "Drop into debugger on lock violation");
4715 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
4716 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
4717 0, "Check for interlock across VOPs");
4719 int vfs_badlock_print = 1; /* Print lock violations. */
4720 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
4721 0, "Print lock violations");
4723 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
4724 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
4725 0, "Print vnode details on lock violations");
4728 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
4729 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
4730 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
4734 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
4738 if (vfs_badlock_backtrace)
4741 if (vfs_badlock_vnode)
4742 vn_printf(vp, "vnode ");
4743 if (vfs_badlock_print)
4744 printf("%s: %p %s\n", str, (void *)vp, msg);
4745 if (vfs_badlock_ddb)
4746 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4750 assert_vi_locked(struct vnode *vp, const char *str)
4753 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
4754 vfs_badlock("interlock is not locked but should be", str, vp);
4758 assert_vi_unlocked(struct vnode *vp, const char *str)
4761 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
4762 vfs_badlock("interlock is locked but should not be", str, vp);
4766 assert_vop_locked(struct vnode *vp, const char *str)
4770 if (!IGNORE_LOCK(vp)) {
4771 locked = VOP_ISLOCKED(vp);
4772 if (locked == 0 || locked == LK_EXCLOTHER)
4773 vfs_badlock("is not locked but should be", str, vp);
4778 assert_vop_unlocked(struct vnode *vp, const char *str)
4781 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
4782 vfs_badlock("is locked but should not be", str, vp);
4786 assert_vop_elocked(struct vnode *vp, const char *str)
4789 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
4790 vfs_badlock("is not exclusive locked but should be", str, vp);
4792 #endif /* DEBUG_VFS_LOCKS */
4795 vop_rename_fail(struct vop_rename_args *ap)
4798 if (ap->a_tvp != NULL)
4800 if (ap->a_tdvp == ap->a_tvp)
4809 vop_rename_pre(void *ap)
4811 struct vop_rename_args *a = ap;
4813 #ifdef DEBUG_VFS_LOCKS
4815 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
4816 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
4817 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
4818 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
4820 /* Check the source (from). */
4821 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
4822 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
4823 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
4824 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
4825 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
4827 /* Check the target. */
4829 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
4830 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
4832 if (a->a_tdvp != a->a_fdvp)
4834 if (a->a_tvp != a->a_fvp)
4841 #ifdef DEBUG_VFS_LOCKS
4843 vop_strategy_pre(void *ap)
4845 struct vop_strategy_args *a;
4852 * Cluster ops lock their component buffers but not the IO container.
4854 if ((bp->b_flags & B_CLUSTER) != 0)
4857 if (panicstr == NULL && !BUF_ISLOCKED(bp)) {
4858 if (vfs_badlock_print)
4860 "VOP_STRATEGY: bp is not locked but should be\n");
4861 if (vfs_badlock_ddb)
4862 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4867 vop_lock_pre(void *ap)
4869 struct vop_lock1_args *a = ap;
4871 if ((a->a_flags & LK_INTERLOCK) == 0)
4872 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4874 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
4878 vop_lock_post(void *ap, int rc)
4880 struct vop_lock1_args *a = ap;
4882 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4883 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
4884 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
4888 vop_unlock_pre(void *ap)
4890 struct vop_unlock_args *a = ap;
4892 if (a->a_flags & LK_INTERLOCK)
4893 ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
4894 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
4898 vop_unlock_post(void *ap, int rc)
4900 struct vop_unlock_args *a = ap;
4902 if (a->a_flags & LK_INTERLOCK)
4903 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
4908 vop_create_post(void *ap, int rc)
4910 struct vop_create_args *a = ap;
4913 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4917 vop_deleteextattr_post(void *ap, int rc)
4919 struct vop_deleteextattr_args *a = ap;
4922 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4926 vop_link_post(void *ap, int rc)
4928 struct vop_link_args *a = ap;
4931 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
4932 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
4937 vop_mkdir_post(void *ap, int rc)
4939 struct vop_mkdir_args *a = ap;
4942 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4946 vop_mknod_post(void *ap, int rc)
4948 struct vop_mknod_args *a = ap;
4951 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4955 vop_reclaim_post(void *ap, int rc)
4957 struct vop_reclaim_args *a = ap;
4960 VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
4964 vop_remove_post(void *ap, int rc)
4966 struct vop_remove_args *a = ap;
4969 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4970 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4975 vop_rename_post(void *ap, int rc)
4977 struct vop_rename_args *a = ap;
4982 if (a->a_fdvp == a->a_tdvp) {
4983 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
4985 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
4986 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
4988 hint |= NOTE_EXTEND;
4989 if (a->a_fvp->v_type == VDIR)
4991 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
4993 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
4994 a->a_tvp->v_type == VDIR)
4996 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
4999 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5001 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5003 if (a->a_tdvp != a->a_fdvp)
5005 if (a->a_tvp != a->a_fvp)
5013 vop_rmdir_post(void *ap, int rc)
5015 struct vop_rmdir_args *a = ap;
5018 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5019 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5024 vop_setattr_post(void *ap, int rc)
5026 struct vop_setattr_args *a = ap;
5029 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5033 vop_setextattr_post(void *ap, int rc)
5035 struct vop_setextattr_args *a = ap;
5038 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5042 vop_symlink_post(void *ap, int rc)
5044 struct vop_symlink_args *a = ap;
5047 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5051 vop_open_post(void *ap, int rc)
5053 struct vop_open_args *a = ap;
5056 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
5060 vop_close_post(void *ap, int rc)
5062 struct vop_close_args *a = ap;
5064 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
5065 (a->a_vp->v_iflag & VI_DOOMED) == 0)) {
5066 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
5067 NOTE_CLOSE_WRITE : NOTE_CLOSE);
5072 vop_read_post(void *ap, int rc)
5074 struct vop_read_args *a = ap;
5077 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5081 vop_readdir_post(void *ap, int rc)
5083 struct vop_readdir_args *a = ap;
5086 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5089 static struct knlist fs_knlist;
5092 vfs_event_init(void *arg)
5094 knlist_init_mtx(&fs_knlist, NULL);
5096 /* XXX - correct order? */
5097 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
5100 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
5103 KNOTE_UNLOCKED(&fs_knlist, event);
5106 static int filt_fsattach(struct knote *kn);
5107 static void filt_fsdetach(struct knote *kn);
5108 static int filt_fsevent(struct knote *kn, long hint);
5110 struct filterops fs_filtops = {
5112 .f_attach = filt_fsattach,
5113 .f_detach = filt_fsdetach,
5114 .f_event = filt_fsevent
5118 filt_fsattach(struct knote *kn)
5121 kn->kn_flags |= EV_CLEAR;
5122 knlist_add(&fs_knlist, kn, 0);
5127 filt_fsdetach(struct knote *kn)
5130 knlist_remove(&fs_knlist, kn, 0);
5134 filt_fsevent(struct knote *kn, long hint)
5137 kn->kn_fflags |= hint;
5138 return (kn->kn_fflags != 0);
5142 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
5148 error = SYSCTL_IN(req, &vc, sizeof(vc));
5151 if (vc.vc_vers != VFS_CTL_VERS1)
5153 mp = vfs_getvfs(&vc.vc_fsid);
5156 /* ensure that a specific sysctl goes to the right filesystem. */
5157 if (strcmp(vc.vc_fstypename, "*") != 0 &&
5158 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
5162 VCTLTOREQ(&vc, req);
5163 error = VFS_SYSCTL(mp, vc.vc_op, req);
5168 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_WR,
5169 NULL, 0, sysctl_vfs_ctl, "",
5173 * Function to initialize a va_filerev field sensibly.
5174 * XXX: Wouldn't a random number make a lot more sense ??
5177 init_va_filerev(void)
5182 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
5185 static int filt_vfsread(struct knote *kn, long hint);
5186 static int filt_vfswrite(struct knote *kn, long hint);
5187 static int filt_vfsvnode(struct knote *kn, long hint);
5188 static void filt_vfsdetach(struct knote *kn);
5189 static struct filterops vfsread_filtops = {
5191 .f_detach = filt_vfsdetach,
5192 .f_event = filt_vfsread
5194 static struct filterops vfswrite_filtops = {
5196 .f_detach = filt_vfsdetach,
5197 .f_event = filt_vfswrite
5199 static struct filterops vfsvnode_filtops = {
5201 .f_detach = filt_vfsdetach,
5202 .f_event = filt_vfsvnode
5206 vfs_knllock(void *arg)
5208 struct vnode *vp = arg;
5210 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5214 vfs_knlunlock(void *arg)
5216 struct vnode *vp = arg;
5222 vfs_knl_assert_locked(void *arg)
5224 #ifdef DEBUG_VFS_LOCKS
5225 struct vnode *vp = arg;
5227 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
5232 vfs_knl_assert_unlocked(void *arg)
5234 #ifdef DEBUG_VFS_LOCKS
5235 struct vnode *vp = arg;
5237 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
5242 vfs_kqfilter(struct vop_kqfilter_args *ap)
5244 struct vnode *vp = ap->a_vp;
5245 struct knote *kn = ap->a_kn;
5248 switch (kn->kn_filter) {
5250 kn->kn_fop = &vfsread_filtops;
5253 kn->kn_fop = &vfswrite_filtops;
5256 kn->kn_fop = &vfsvnode_filtops;
5262 kn->kn_hook = (caddr_t)vp;
5265 if (vp->v_pollinfo == NULL)
5267 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5269 knlist_add(knl, kn, 0);
5275 * Detach knote from vnode
5278 filt_vfsdetach(struct knote *kn)
5280 struct vnode *vp = (struct vnode *)kn->kn_hook;
5282 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
5283 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
5289 filt_vfsread(struct knote *kn, long hint)
5291 struct vnode *vp = (struct vnode *)kn->kn_hook;
5296 * filesystem is gone, so set the EOF flag and schedule
5297 * the knote for deletion.
5299 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5301 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5306 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
5310 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
5311 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
5318 filt_vfswrite(struct knote *kn, long hint)
5320 struct vnode *vp = (struct vnode *)kn->kn_hook;
5325 * filesystem is gone, so set the EOF flag and schedule
5326 * the knote for deletion.
5328 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
5329 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5337 filt_vfsvnode(struct knote *kn, long hint)
5339 struct vnode *vp = (struct vnode *)kn->kn_hook;
5343 if (kn->kn_sfflags & hint)
5344 kn->kn_fflags |= hint;
5345 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5346 kn->kn_flags |= EV_EOF;
5350 res = (kn->kn_fflags != 0);
5356 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
5360 if (dp->d_reclen > ap->a_uio->uio_resid)
5361 return (ENAMETOOLONG);
5362 error = uiomove(dp, dp->d_reclen, ap->a_uio);
5364 if (ap->a_ncookies != NULL) {
5365 if (ap->a_cookies != NULL)
5366 free(ap->a_cookies, M_TEMP);
5367 ap->a_cookies = NULL;
5368 *ap->a_ncookies = 0;
5372 if (ap->a_ncookies == NULL)
5375 KASSERT(ap->a_cookies,
5376 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
5378 *ap->a_cookies = realloc(*ap->a_cookies,
5379 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
5380 (*ap->a_cookies)[*ap->a_ncookies] = off;
5381 *ap->a_ncookies += 1;
5386 * Mark for update the access time of the file if the filesystem
5387 * supports VOP_MARKATIME. This functionality is used by execve and
5388 * mmap, so we want to avoid the I/O implied by directly setting
5389 * va_atime for the sake of efficiency.
5392 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
5397 ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
5398 if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
5399 (void)VOP_MARKATIME(vp);
5403 * The purpose of this routine is to remove granularity from accmode_t,
5404 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
5405 * VADMIN and VAPPEND.
5407 * If it returns 0, the caller is supposed to continue with the usual
5408 * access checks using 'accmode' as modified by this routine. If it
5409 * returns nonzero value, the caller is supposed to return that value
5412 * Note that after this routine runs, accmode may be zero.
5415 vfs_unixify_accmode(accmode_t *accmode)
5418 * There is no way to specify explicit "deny" rule using
5419 * file mode or POSIX.1e ACLs.
5421 if (*accmode & VEXPLICIT_DENY) {
5427 * None of these can be translated into usual access bits.
5428 * Also, the common case for NFSv4 ACLs is to not contain
5429 * either of these bits. Caller should check for VWRITE
5430 * on the containing directory instead.
5432 if (*accmode & (VDELETE_CHILD | VDELETE))
5435 if (*accmode & VADMIN_PERMS) {
5436 *accmode &= ~VADMIN_PERMS;
5441 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
5442 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
5444 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
5450 * These are helper functions for filesystems to traverse all
5451 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
5453 * This interface replaces MNT_VNODE_FOREACH.
5456 MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
5459 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
5464 kern_yield(PRI_USER);
5466 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5467 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
5468 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
5469 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
5470 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
5473 if ((vp->v_iflag & VI_DOOMED) != 0) {
5480 __mnt_vnode_markerfree_all(mvp, mp);
5481 /* MNT_IUNLOCK(mp); -- done in above function */
5482 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
5485 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5486 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5492 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
5496 *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
5499 (*mvp)->v_mount = mp;
5500 (*mvp)->v_type = VMARKER;
5502 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
5503 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
5504 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
5507 if ((vp->v_iflag & VI_DOOMED) != 0) {
5516 free(*mvp, M_VNODE_MARKER);
5520 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5526 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
5534 mtx_assert(MNT_MTX(mp), MA_OWNED);
5536 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5537 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5540 free(*mvp, M_VNODE_MARKER);
5545 * These are helper functions for filesystems to traverse their
5546 * active vnodes. See MNT_VNODE_FOREACH_ACTIVE() in sys/mount.h
5549 mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
5552 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5557 free(*mvp, M_VNODE_MARKER);
5562 * Relock the mp mount vnode list lock with the vp vnode interlock in the
5563 * conventional lock order during mnt_vnode_next_active iteration.
5565 * On entry, the mount vnode list lock is held and the vnode interlock is not.
5566 * The list lock is dropped and reacquired. On success, both locks are held.
5567 * On failure, the mount vnode list lock is held but the vnode interlock is
5568 * not, and the procedure may have yielded.
5571 mnt_vnode_next_active_relock(struct vnode *mvp, struct mount *mp,
5574 const struct vnode *tmp;
5577 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
5578 TAILQ_NEXT(mvp, v_actfreelist) != NULL, mvp,
5579 ("%s: bad marker", __func__));
5580 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
5581 ("%s: inappropriate vnode", __func__));
5582 ASSERT_VI_UNLOCKED(vp, __func__);
5583 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5587 TAILQ_REMOVE(&mp->mnt_activevnodelist, mvp, v_actfreelist);
5588 TAILQ_INSERT_BEFORE(vp, mvp, v_actfreelist);
5591 * Use a hold to prevent vp from disappearing while the mount vnode
5592 * list lock is dropped and reacquired. Normally a hold would be
5593 * acquired with vhold(), but that might try to acquire the vnode
5594 * interlock, which would be a LOR with the mount vnode list lock.
5596 held = refcount_acquire_if_not_zero(&vp->v_holdcnt);
5597 mtx_unlock(&mp->mnt_listmtx);
5601 if (!refcount_release_if_not_last(&vp->v_holdcnt)) {
5605 mtx_lock(&mp->mnt_listmtx);
5608 * Determine whether the vnode is still the next one after the marker,
5609 * excepting any other markers. If the vnode has not been doomed by
5610 * vgone() then the hold should have ensured that it remained on the
5611 * active list. If it has been doomed but is still on the active list,
5612 * don't abort, but rather skip over it (avoid spinning on doomed
5617 tmp = TAILQ_NEXT(tmp, v_actfreelist);
5618 } while (tmp != NULL && tmp->v_type == VMARKER);
5620 mtx_unlock(&mp->mnt_listmtx);
5629 mtx_lock(&mp->mnt_listmtx);
5632 ASSERT_VI_LOCKED(vp, __func__);
5634 ASSERT_VI_UNLOCKED(vp, __func__);
5635 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5639 static struct vnode *
5640 mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
5642 struct vnode *vp, *nvp;
5644 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5645 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5647 vp = TAILQ_NEXT(*mvp, v_actfreelist);
5648 while (vp != NULL) {
5649 if (vp->v_type == VMARKER) {
5650 vp = TAILQ_NEXT(vp, v_actfreelist);
5654 * Try-lock because this is the wrong lock order. If that does
5655 * not succeed, drop the mount vnode list lock and try to
5656 * reacquire it and the vnode interlock in the right order.
5658 if (!VI_TRYLOCK(vp) &&
5659 !mnt_vnode_next_active_relock(*mvp, mp, vp))
5661 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
5662 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
5663 ("alien vnode on the active list %p %p", vp, mp));
5664 if (vp->v_mount == mp && (vp->v_iflag & VI_DOOMED) == 0)
5666 nvp = TAILQ_NEXT(vp, v_actfreelist);
5670 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
5672 /* Check if we are done */
5674 mtx_unlock(&mp->mnt_listmtx);
5675 mnt_vnode_markerfree_active(mvp, mp);
5678 TAILQ_INSERT_AFTER(&mp->mnt_activevnodelist, vp, *mvp, v_actfreelist);
5679 mtx_unlock(&mp->mnt_listmtx);
5680 ASSERT_VI_LOCKED(vp, "active iter");
5681 KASSERT((vp->v_iflag & VI_ACTIVE) != 0, ("Non-active vp %p", vp));
5686 __mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
5690 kern_yield(PRI_USER);
5691 mtx_lock(&mp->mnt_listmtx);
5692 return (mnt_vnode_next_active(mvp, mp));
5696 __mnt_vnode_first_active(struct vnode **mvp, struct mount *mp)
5700 *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
5704 (*mvp)->v_type = VMARKER;
5705 (*mvp)->v_mount = mp;
5707 mtx_lock(&mp->mnt_listmtx);
5708 vp = TAILQ_FIRST(&mp->mnt_activevnodelist);
5710 mtx_unlock(&mp->mnt_listmtx);
5711 mnt_vnode_markerfree_active(mvp, mp);
5714 TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
5715 return (mnt_vnode_next_active(mvp, mp));
5719 __mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
5725 mtx_lock(&mp->mnt_listmtx);
5726 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
5727 mtx_unlock(&mp->mnt_listmtx);
5728 mnt_vnode_markerfree_active(mvp, mp);