2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)vfs_subr.c 8.31 (Berkeley) 5/26/95
40 * External virtual filesystem routines
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
47 #include "opt_watchdog.h"
49 #include <sys/param.h>
50 #include <sys/systm.h>
53 #include <sys/capsicum.h>
54 #include <sys/condvar.h>
56 #include <sys/counter.h>
57 #include <sys/dirent.h>
58 #include <sys/event.h>
59 #include <sys/eventhandler.h>
60 #include <sys/extattr.h>
62 #include <sys/fcntl.h>
65 #include <sys/kernel.h>
66 #include <sys/kthread.h>
68 #include <sys/lockf.h>
69 #include <sys/malloc.h>
70 #include <sys/mount.h>
71 #include <sys/namei.h>
72 #include <sys/pctrie.h>
74 #include <sys/reboot.h>
75 #include <sys/refcount.h>
76 #include <sys/rwlock.h>
77 #include <sys/sched.h>
78 #include <sys/sleepqueue.h>
81 #include <sys/sysctl.h>
82 #include <sys/syslog.h>
83 #include <sys/vmmeter.h>
84 #include <sys/vnode.h>
85 #include <sys/watchdog.h>
87 #include <machine/stdarg.h>
89 #include <security/mac/mac_framework.h>
92 #include <vm/vm_object.h>
93 #include <vm/vm_extern.h>
95 #include <vm/vm_map.h>
96 #include <vm/vm_page.h>
97 #include <vm/vm_kern.h>
104 static void delmntque(struct vnode *vp);
105 static int flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
106 int slpflag, int slptimeo);
107 static void syncer_shutdown(void *arg, int howto);
108 static int vtryrecycle(struct vnode *vp);
109 static void v_init_counters(struct vnode *);
110 static void v_incr_devcount(struct vnode *);
111 static void v_decr_devcount(struct vnode *);
112 static void vgonel(struct vnode *);
113 static void vfs_knllock(void *arg);
114 static void vfs_knlunlock(void *arg);
115 static void vfs_knl_assert_locked(void *arg);
116 static void vfs_knl_assert_unlocked(void *arg);
117 static void vnlru_return_batches(struct vfsops *mnt_op);
118 static void destroy_vpollinfo(struct vpollinfo *vi);
119 static int v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
120 daddr_t startlbn, daddr_t endlbn);
123 * These fences are intended for cases where some synchronization is
124 * needed between access of v_iflags and lockless vnode refcount (v_holdcnt
125 * and v_usecount) updates. Access to v_iflags is generally synchronized
126 * by the interlock, but we have some internal assertions that check vnode
127 * flags without acquiring the lock. Thus, these fences are INVARIANTS-only
131 #define VNODE_REFCOUNT_FENCE_ACQ() atomic_thread_fence_acq()
132 #define VNODE_REFCOUNT_FENCE_REL() atomic_thread_fence_rel()
134 #define VNODE_REFCOUNT_FENCE_ACQ()
135 #define VNODE_REFCOUNT_FENCE_REL()
139 * Number of vnodes in existence. Increased whenever getnewvnode()
140 * allocates a new vnode, decreased in vdropl() for VI_DOOMED vnode.
142 static unsigned long numvnodes;
144 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
145 "Number of vnodes in existence");
147 static counter_u64_t vnodes_created;
148 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
149 "Number of vnodes created by getnewvnode");
151 static u_long mnt_free_list_batch = 128;
152 SYSCTL_ULONG(_vfs, OID_AUTO, mnt_free_list_batch, CTLFLAG_RW,
153 &mnt_free_list_batch, 0, "Limit of vnodes held on mnt's free list");
156 * Conversion tables for conversion from vnode types to inode formats
159 enum vtype iftovt_tab[16] = {
160 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
161 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
163 int vttoif_tab[10] = {
164 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
165 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
169 * List of vnodes that are ready for recycling.
171 static TAILQ_HEAD(freelst, vnode) vnode_free_list;
174 * "Free" vnode target. Free vnodes are rarely completely free, but are
175 * just ones that are cheap to recycle. Usually they are for files which
176 * have been stat'd but not read; these usually have inode and namecache
177 * data attached to them. This target is the preferred minimum size of a
178 * sub-cache consisting mostly of such files. The system balances the size
179 * of this sub-cache with its complement to try to prevent either from
180 * thrashing while the other is relatively inactive. The targets express
181 * a preference for the best balance.
183 * "Above" this target there are 2 further targets (watermarks) related
184 * to recyling of free vnodes. In the best-operating case, the cache is
185 * exactly full, the free list has size between vlowat and vhiwat above the
186 * free target, and recycling from it and normal use maintains this state.
187 * Sometimes the free list is below vlowat or even empty, but this state
188 * is even better for immediate use provided the cache is not full.
189 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
190 * ones) to reach one of these states. The watermarks are currently hard-
191 * coded as 4% and 9% of the available space higher. These and the default
192 * of 25% for wantfreevnodes are too large if the memory size is large.
193 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
194 * whenever vnlru_proc() becomes active.
196 static u_long wantfreevnodes;
197 SYSCTL_ULONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW,
198 &wantfreevnodes, 0, "Target for minimum number of \"free\" vnodes");
199 static u_long freevnodes;
200 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
201 &freevnodes, 0, "Number of \"free\" vnodes");
203 static counter_u64_t recycles_count;
204 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
205 "Number of vnodes recycled to meet vnode cache targets");
208 * Various variables used for debugging the new implementation of
210 * XXX these are probably of (very) limited utility now.
212 static int reassignbufcalls;
213 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW | CTLFLAG_STATS,
214 &reassignbufcalls, 0, "Number of calls to reassignbuf");
216 static counter_u64_t free_owe_inact;
217 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, free_owe_inact, CTLFLAG_RD, &free_owe_inact,
218 "Number of times free vnodes kept on active list due to VFS "
219 "owing inactivation");
221 /* To keep more than one thread at a time from running vfs_getnewfsid */
222 static struct mtx mntid_mtx;
225 * Lock for any access to the following:
230 static struct mtx vnode_free_list_mtx;
232 /* Publicly exported FS */
233 struct nfs_public nfs_pub;
235 static uma_zone_t buf_trie_zone;
237 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
238 static uma_zone_t vnode_zone;
239 static uma_zone_t vnodepoll_zone;
242 * The workitem queue.
244 * It is useful to delay writes of file data and filesystem metadata
245 * for tens of seconds so that quickly created and deleted files need
246 * not waste disk bandwidth being created and removed. To realize this,
247 * we append vnodes to a "workitem" queue. When running with a soft
248 * updates implementation, most pending metadata dependencies should
249 * not wait for more than a few seconds. Thus, mounted on block devices
250 * are delayed only about a half the time that file data is delayed.
251 * Similarly, directory updates are more critical, so are only delayed
252 * about a third the time that file data is delayed. Thus, there are
253 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
254 * one each second (driven off the filesystem syncer process). The
255 * syncer_delayno variable indicates the next queue that is to be processed.
256 * Items that need to be processed soon are placed in this queue:
258 * syncer_workitem_pending[syncer_delayno]
260 * A delay of fifteen seconds is done by placing the request fifteen
261 * entries later in the queue:
263 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
266 static int syncer_delayno;
267 static long syncer_mask;
268 LIST_HEAD(synclist, bufobj);
269 static struct synclist *syncer_workitem_pending;
271 * The sync_mtx protects:
276 * syncer_workitem_pending
277 * syncer_worklist_len
280 static struct mtx sync_mtx;
281 static struct cv sync_wakeup;
283 #define SYNCER_MAXDELAY 32
284 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
285 static int syncdelay = 30; /* max time to delay syncing data */
286 static int filedelay = 30; /* time to delay syncing files */
287 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
288 "Time to delay syncing files (in seconds)");
289 static int dirdelay = 29; /* time to delay syncing directories */
290 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
291 "Time to delay syncing directories (in seconds)");
292 static int metadelay = 28; /* time to delay syncing metadata */
293 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
294 "Time to delay syncing metadata (in seconds)");
295 static int rushjob; /* number of slots to run ASAP */
296 static int stat_rush_requests; /* number of times I/O speeded up */
297 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
298 "Number of times I/O speeded up (rush requests)");
301 * When shutting down the syncer, run it at four times normal speed.
303 #define SYNCER_SHUTDOWN_SPEEDUP 4
304 static int sync_vnode_count;
305 static int syncer_worklist_len;
306 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
309 /* Target for maximum number of vnodes. */
311 static int gapvnodes; /* gap between wanted and desired */
312 static int vhiwat; /* enough extras after expansion */
313 static int vlowat; /* minimal extras before expansion */
314 static int vstir; /* nonzero to stir non-free vnodes */
315 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
318 sysctl_update_desiredvnodes(SYSCTL_HANDLER_ARGS)
320 int error, old_desiredvnodes;
322 old_desiredvnodes = desiredvnodes;
323 if ((error = sysctl_handle_int(oidp, arg1, arg2, req)) != 0)
325 if (old_desiredvnodes != desiredvnodes) {
326 wantfreevnodes = desiredvnodes / 4;
327 /* XXX locking seems to be incomplete. */
328 vfs_hash_changesize(desiredvnodes);
329 cache_changesize(desiredvnodes);
334 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
335 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, &desiredvnodes, 0,
336 sysctl_update_desiredvnodes, "I", "Target for maximum number of vnodes");
337 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
338 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
339 static int vnlru_nowhere;
340 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
341 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
344 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
349 unsigned long ndflags;
352 if (req->newptr == NULL)
354 if (req->newlen >= PATH_MAX)
357 buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
358 error = SYSCTL_IN(req, buf, req->newlen);
362 buf[req->newlen] = '\0';
364 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | NOCACHE | SAVENAME;
365 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
366 if ((error = namei(&nd)) != 0)
370 if ((vp->v_iflag & VI_DOOMED) != 0) {
372 * This vnode is being recycled. Return != 0 to let the caller
373 * know that the sysctl had no effect. Return EAGAIN because a
374 * subsequent call will likely succeed (since namei will create
375 * a new vnode if necessary)
381 counter_u64_add(recycles_count, 1);
391 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
393 struct thread *td = curthread;
399 if (req->newptr == NULL)
402 error = sysctl_handle_int(oidp, &fd, 0, req);
405 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
410 error = vn_lock(vp, LK_EXCLUSIVE);
414 counter_u64_add(recycles_count, 1);
422 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
423 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
424 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
425 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
426 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
427 sysctl_ftry_reclaim_vnode, "I",
428 "Try to reclaim a vnode by its file descriptor");
430 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
434 * Support for the bufobj clean & dirty pctrie.
437 buf_trie_alloc(struct pctrie *ptree)
440 return uma_zalloc(buf_trie_zone, M_NOWAIT);
444 buf_trie_free(struct pctrie *ptree, void *node)
447 uma_zfree(buf_trie_zone, node);
449 PCTRIE_DEFINE(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free);
452 * Initialize the vnode management data structures.
454 * Reevaluate the following cap on the number of vnodes after the physical
455 * memory size exceeds 512GB. In the limit, as the physical memory size
456 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
458 #ifndef MAXVNODES_MAX
459 #define MAXVNODES_MAX (512 * 1024 * 1024 / 64) /* 8M */
463 * Initialize a vnode as it first enters the zone.
466 vnode_init(void *mem, int size, int flags)
475 vp->v_vnlock = &vp->v_lock;
476 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
478 * By default, don't allow shared locks unless filesystems opt-in.
480 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
481 LK_NOSHARE | LK_IS_VNODE);
485 bufobj_init(&vp->v_bufobj, vp);
487 * Initialize namecache.
489 LIST_INIT(&vp->v_cache_src);
490 TAILQ_INIT(&vp->v_cache_dst);
492 * Initialize rangelocks.
494 rangelock_init(&vp->v_rl);
499 * Free a vnode when it is cleared from the zone.
502 vnode_fini(void *mem, int size)
508 rangelock_destroy(&vp->v_rl);
509 lockdestroy(vp->v_vnlock);
510 mtx_destroy(&vp->v_interlock);
512 rw_destroy(BO_LOCKPTR(bo));
516 * Provide the size of NFS nclnode and NFS fh for calculation of the
517 * vnode memory consumption. The size is specified directly to
518 * eliminate dependency on NFS-private header.
520 * Other filesystems may use bigger or smaller (like UFS and ZFS)
521 * private inode data, but the NFS-based estimation is ample enough.
522 * Still, we care about differences in the size between 64- and 32-bit
525 * Namecache structure size is heuristically
526 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
529 #define NFS_NCLNODE_SZ (528 + 64)
532 #define NFS_NCLNODE_SZ (360 + 32)
537 vntblinit(void *dummy __unused)
540 int physvnodes, virtvnodes;
543 * Desiredvnodes is a function of the physical memory size and the
544 * kernel's heap size. Generally speaking, it scales with the
545 * physical memory size. The ratio of desiredvnodes to the physical
546 * memory size is 1:16 until desiredvnodes exceeds 98,304.
548 * marginal ratio of desiredvnodes to the physical memory size is
549 * 1:64. However, desiredvnodes is limited by the kernel's heap
550 * size. The memory required by desiredvnodes vnodes and vm objects
551 * must not exceed 1/10th of the kernel's heap size.
553 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
554 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
555 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
556 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
557 desiredvnodes = min(physvnodes, virtvnodes);
558 if (desiredvnodes > MAXVNODES_MAX) {
560 printf("Reducing kern.maxvnodes %d -> %d\n",
561 desiredvnodes, MAXVNODES_MAX);
562 desiredvnodes = MAXVNODES_MAX;
564 wantfreevnodes = desiredvnodes / 4;
565 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
566 TAILQ_INIT(&vnode_free_list);
567 mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
568 vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
569 vnode_init, vnode_fini, UMA_ALIGN_PTR, 0);
570 vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
571 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
573 * Preallocate enough nodes to support one-per buf so that
574 * we can not fail an insert. reassignbuf() callers can not
575 * tolerate the insertion failure.
577 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
578 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
579 UMA_ZONE_NOFREE | UMA_ZONE_VM);
580 uma_prealloc(buf_trie_zone, nbuf);
582 vnodes_created = counter_u64_alloc(M_WAITOK);
583 recycles_count = counter_u64_alloc(M_WAITOK);
584 free_owe_inact = counter_u64_alloc(M_WAITOK);
587 * Initialize the filesystem syncer.
589 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
591 syncer_maxdelay = syncer_mask + 1;
592 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
593 cv_init(&sync_wakeup, "syncer");
594 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
598 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
602 * Mark a mount point as busy. Used to synchronize access and to delay
603 * unmounting. Eventually, mountlist_mtx is not released on failure.
605 * vfs_busy() is a custom lock, it can block the caller.
606 * vfs_busy() only sleeps if the unmount is active on the mount point.
607 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
608 * vnode belonging to mp.
610 * Lookup uses vfs_busy() to traverse mount points.
612 * / vnode lock A / vnode lock (/var) D
613 * /var vnode lock B /log vnode lock(/var/log) E
614 * vfs_busy lock C vfs_busy lock F
616 * Within each file system, the lock order is C->A->B and F->D->E.
618 * When traversing across mounts, the system follows that lock order:
624 * The lookup() process for namei("/var") illustrates the process:
625 * VOP_LOOKUP() obtains B while A is held
626 * vfs_busy() obtains a shared lock on F while A and B are held
627 * vput() releases lock on B
628 * vput() releases lock on A
629 * VFS_ROOT() obtains lock on D while shared lock on F is held
630 * vfs_unbusy() releases shared lock on F
631 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
632 * Attempt to lock A (instead of vp_crossmp) while D is held would
633 * violate the global order, causing deadlocks.
635 * dounmount() locks B while F is drained.
638 vfs_busy(struct mount *mp, int flags)
641 MPASS((flags & ~MBF_MASK) == 0);
642 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
644 if (vfs_op_thread_enter(mp)) {
645 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
646 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
647 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
648 vfs_mp_count_add_pcpu(mp, ref, 1);
649 vfs_mp_count_add_pcpu(mp, lockref, 1);
650 vfs_op_thread_exit(mp);
651 if (flags & MBF_MNTLSTLOCK)
652 mtx_unlock(&mountlist_mtx);
657 vfs_assert_mount_counters(mp);
660 * If mount point is currently being unmounted, sleep until the
661 * mount point fate is decided. If thread doing the unmounting fails,
662 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
663 * that this mount point has survived the unmount attempt and vfs_busy
664 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
665 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
666 * about to be really destroyed. vfs_busy needs to release its
667 * reference on the mount point in this case and return with ENOENT,
668 * telling the caller that mount mount it tried to busy is no longer
671 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
672 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
675 CTR1(KTR_VFS, "%s: failed busying before sleeping",
679 if (flags & MBF_MNTLSTLOCK)
680 mtx_unlock(&mountlist_mtx);
681 mp->mnt_kern_flag |= MNTK_MWAIT;
682 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
683 if (flags & MBF_MNTLSTLOCK)
684 mtx_lock(&mountlist_mtx);
687 if (flags & MBF_MNTLSTLOCK)
688 mtx_unlock(&mountlist_mtx);
695 * Free a busy filesystem.
698 vfs_unbusy(struct mount *mp)
702 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
704 if (vfs_op_thread_enter(mp)) {
705 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
706 vfs_mp_count_sub_pcpu(mp, lockref, 1);
707 vfs_mp_count_sub_pcpu(mp, ref, 1);
708 vfs_op_thread_exit(mp);
713 vfs_assert_mount_counters(mp);
715 c = --mp->mnt_lockref;
716 if (mp->mnt_vfs_ops == 0) {
717 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
722 vfs_dump_mount_counters(mp);
723 if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
724 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
725 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
726 mp->mnt_kern_flag &= ~MNTK_DRAINING;
727 wakeup(&mp->mnt_lockref);
733 * Lookup a mount point by filesystem identifier.
736 vfs_getvfs(fsid_t *fsid)
740 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
741 mtx_lock(&mountlist_mtx);
742 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
743 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
744 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
746 mtx_unlock(&mountlist_mtx);
750 mtx_unlock(&mountlist_mtx);
751 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
752 return ((struct mount *) 0);
756 * Lookup a mount point by filesystem identifier, busying it before
759 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
760 * cache for popular filesystem identifiers. The cache is lockess, using
761 * the fact that struct mount's are never freed. In worst case we may
762 * get pointer to unmounted or even different filesystem, so we have to
763 * check what we got, and go slow way if so.
766 vfs_busyfs(fsid_t *fsid)
768 #define FSID_CACHE_SIZE 256
769 typedef struct mount * volatile vmp_t;
770 static vmp_t cache[FSID_CACHE_SIZE];
775 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
776 hash = fsid->val[0] ^ fsid->val[1];
777 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
780 mp->mnt_stat.f_fsid.val[0] != fsid->val[0] ||
781 mp->mnt_stat.f_fsid.val[1] != fsid->val[1])
783 if (vfs_busy(mp, 0) != 0) {
787 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
788 mp->mnt_stat.f_fsid.val[1] == fsid->val[1])
794 mtx_lock(&mountlist_mtx);
795 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
796 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
797 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
798 error = vfs_busy(mp, MBF_MNTLSTLOCK);
801 mtx_unlock(&mountlist_mtx);
808 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
809 mtx_unlock(&mountlist_mtx);
810 return ((struct mount *) 0);
814 * Check if a user can access privileged mount options.
817 vfs_suser(struct mount *mp, struct thread *td)
821 if (jailed(td->td_ucred)) {
823 * If the jail of the calling thread lacks permission for
824 * this type of file system, deny immediately.
826 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
830 * If the file system was mounted outside the jail of the
831 * calling thread, deny immediately.
833 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
838 * If file system supports delegated administration, we don't check
839 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
840 * by the file system itself.
841 * If this is not the user that did original mount, we check for
842 * the PRIV_VFS_MOUNT_OWNER privilege.
844 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
845 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
846 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
853 * Get a new unique fsid. Try to make its val[0] unique, since this value
854 * will be used to create fake device numbers for stat(). Also try (but
855 * not so hard) make its val[0] unique mod 2^16, since some emulators only
856 * support 16-bit device numbers. We end up with unique val[0]'s for the
857 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
859 * Keep in mind that several mounts may be running in parallel. Starting
860 * the search one past where the previous search terminated is both a
861 * micro-optimization and a defense against returning the same fsid to
865 vfs_getnewfsid(struct mount *mp)
867 static uint16_t mntid_base;
872 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
873 mtx_lock(&mntid_mtx);
874 mtype = mp->mnt_vfc->vfc_typenum;
875 tfsid.val[1] = mtype;
876 mtype = (mtype & 0xFF) << 24;
878 tfsid.val[0] = makedev(255,
879 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
881 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
885 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
886 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
887 mtx_unlock(&mntid_mtx);
891 * Knob to control the precision of file timestamps:
893 * 0 = seconds only; nanoseconds zeroed.
894 * 1 = seconds and nanoseconds, accurate within 1/HZ.
895 * 2 = seconds and nanoseconds, truncated to microseconds.
896 * >=3 = seconds and nanoseconds, maximum precision.
898 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
900 static int timestamp_precision = TSP_USEC;
901 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
902 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
903 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
904 "3+: sec + ns (max. precision))");
907 * Get a current timestamp.
910 vfs_timestamp(struct timespec *tsp)
914 switch (timestamp_precision) {
916 tsp->tv_sec = time_second;
924 TIMEVAL_TO_TIMESPEC(&tv, tsp);
934 * Set vnode attributes to VNOVAL
937 vattr_null(struct vattr *vap)
941 vap->va_size = VNOVAL;
942 vap->va_bytes = VNOVAL;
943 vap->va_mode = VNOVAL;
944 vap->va_nlink = VNOVAL;
945 vap->va_uid = VNOVAL;
946 vap->va_gid = VNOVAL;
947 vap->va_fsid = VNOVAL;
948 vap->va_fileid = VNOVAL;
949 vap->va_blocksize = VNOVAL;
950 vap->va_rdev = VNOVAL;
951 vap->va_atime.tv_sec = VNOVAL;
952 vap->va_atime.tv_nsec = VNOVAL;
953 vap->va_mtime.tv_sec = VNOVAL;
954 vap->va_mtime.tv_nsec = VNOVAL;
955 vap->va_ctime.tv_sec = VNOVAL;
956 vap->va_ctime.tv_nsec = VNOVAL;
957 vap->va_birthtime.tv_sec = VNOVAL;
958 vap->va_birthtime.tv_nsec = VNOVAL;
959 vap->va_flags = VNOVAL;
960 vap->va_gen = VNOVAL;
965 * This routine is called when we have too many vnodes. It attempts
966 * to free <count> vnodes and will potentially free vnodes that still
967 * have VM backing store (VM backing store is typically the cause
968 * of a vnode blowout so we want to do this). Therefore, this operation
969 * is not considered cheap.
971 * A number of conditions may prevent a vnode from being reclaimed.
972 * the buffer cache may have references on the vnode, a directory
973 * vnode may still have references due to the namei cache representing
974 * underlying files, or the vnode may be in active use. It is not
975 * desirable to reuse such vnodes. These conditions may cause the
976 * number of vnodes to reach some minimum value regardless of what
977 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
979 * @param mp Try to reclaim vnodes from this mountpoint
980 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
981 * entries if this argument is strue
982 * @param trigger Only reclaim vnodes with fewer than this many resident
984 * @return The number of vnodes that were reclaimed.
987 vlrureclaim(struct mount *mp, bool reclaim_nc_src, int trigger)
990 int count, done, target;
993 vn_start_write(NULL, &mp, V_WAIT);
995 count = mp->mnt_nvnodelistsize;
996 target = count * (int64_t)gapvnodes / imax(desiredvnodes, 1);
997 target = target / 10 + 1;
998 while (count != 0 && done < target) {
999 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
1000 while (vp != NULL && vp->v_type == VMARKER)
1001 vp = TAILQ_NEXT(vp, v_nmntvnodes);
1005 * XXX LRU is completely broken for non-free vnodes. First
1006 * by calling here in mountpoint order, then by moving
1007 * unselected vnodes to the end here, and most grossly by
1008 * removing the vlruvp() function that was supposed to
1009 * maintain the order. (This function was born broken
1010 * since syncer problems prevented it doing anything.) The
1011 * order is closer to LRC (C = Created).
1013 * LRU reclaiming of vnodes seems to have last worked in
1014 * FreeBSD-3 where LRU wasn't mentioned under any spelling.
1015 * Then there was no hold count, and inactive vnodes were
1016 * simply put on the free list in LRU order. The separate
1017 * lists also break LRU. We prefer to reclaim from the
1018 * free list for technical reasons. This tends to thrash
1019 * the free list to keep very unrecently used held vnodes.
1020 * The problem is mitigated by keeping the free list large.
1022 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1023 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1025 if (!VI_TRYLOCK(vp))
1028 * If it's been deconstructed already, it's still
1029 * referenced, or it exceeds the trigger, skip it.
1030 * Also skip free vnodes. We are trying to make space
1031 * to expand the free list, not reduce it.
1033 if (vp->v_usecount ||
1034 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1035 ((vp->v_iflag & VI_FREE) != 0) ||
1036 (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
1037 vp->v_object->resident_page_count > trigger)) {
1043 if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT)) {
1045 goto next_iter_mntunlocked;
1049 * v_usecount may have been bumped after VOP_LOCK() dropped
1050 * the vnode interlock and before it was locked again.
1052 * It is not necessary to recheck VI_DOOMED because it can
1053 * only be set by another thread that holds both the vnode
1054 * lock and vnode interlock. If another thread has the
1055 * vnode lock before we get to VOP_LOCK() and obtains the
1056 * vnode interlock after VOP_LOCK() drops the vnode
1057 * interlock, the other thread will be unable to drop the
1058 * vnode lock before our VOP_LOCK() call fails.
1060 if (vp->v_usecount ||
1061 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1062 (vp->v_iflag & VI_FREE) != 0 ||
1063 (vp->v_object != NULL &&
1064 vp->v_object->resident_page_count > trigger)) {
1067 goto next_iter_mntunlocked;
1069 KASSERT((vp->v_iflag & VI_DOOMED) == 0,
1070 ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
1071 counter_u64_add(recycles_count, 1);
1076 next_iter_mntunlocked:
1077 if (!should_yield())
1081 if (!should_yield())
1085 kern_yield(PRI_USER);
1090 vn_finished_write(mp);
1094 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1095 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1097 "limit on vnode free requests per call to the vnlru_free routine");
1100 * Attempt to reduce the free list by the requested amount.
1103 vnlru_free_locked(int count, struct vfsops *mnt_op)
1109 tried_batches = false;
1110 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
1111 if (count > max_vnlru_free)
1112 count = max_vnlru_free;
1113 for (; count > 0; count--) {
1114 vp = TAILQ_FIRST(&vnode_free_list);
1116 * The list can be modified while the free_list_mtx
1117 * has been dropped and vp could be NULL here.
1122 mtx_unlock(&vnode_free_list_mtx);
1123 vnlru_return_batches(mnt_op);
1124 tried_batches = true;
1125 mtx_lock(&vnode_free_list_mtx);
1129 VNASSERT(vp->v_op != NULL, vp,
1130 ("vnlru_free: vnode already reclaimed."));
1131 KASSERT((vp->v_iflag & VI_FREE) != 0,
1132 ("Removing vnode not on freelist"));
1133 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1134 ("Mangling active vnode"));
1135 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
1138 * Don't recycle if our vnode is from different type
1139 * of mount point. Note that mp is type-safe, the
1140 * check does not reach unmapped address even if
1141 * vnode is reclaimed.
1142 * Don't recycle if we can't get the interlock without
1145 if ((mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1146 mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
1147 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_actfreelist);
1150 VNASSERT((vp->v_iflag & VI_FREE) != 0 && vp->v_holdcnt == 0,
1151 vp, ("vp inconsistent on freelist"));
1154 * The clear of VI_FREE prevents activation of the
1155 * vnode. There is no sense in putting the vnode on
1156 * the mount point active list, only to remove it
1157 * later during recycling. Inline the relevant part
1158 * of vholdl(), to avoid triggering assertions or
1162 vp->v_iflag &= ~VI_FREE;
1163 VNODE_REFCOUNT_FENCE_REL();
1164 refcount_acquire(&vp->v_holdcnt);
1166 mtx_unlock(&vnode_free_list_mtx);
1170 * If the recycled succeeded this vdrop will actually free
1171 * the vnode. If not it will simply place it back on
1175 mtx_lock(&vnode_free_list_mtx);
1180 vnlru_free(int count, struct vfsops *mnt_op)
1183 mtx_lock(&vnode_free_list_mtx);
1184 vnlru_free_locked(count, mnt_op);
1185 mtx_unlock(&vnode_free_list_mtx);
1189 /* XXX some names and initialization are bad for limits and watermarks. */
1195 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1196 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1197 vlowat = vhiwat / 2;
1198 if (numvnodes > desiredvnodes)
1200 space = desiredvnodes - numvnodes;
1201 if (freevnodes > wantfreevnodes)
1202 space += freevnodes - wantfreevnodes;
1207 vnlru_return_batch_locked(struct mount *mp)
1211 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
1213 if (mp->mnt_tmpfreevnodelistsize == 0)
1216 TAILQ_FOREACH(vp, &mp->mnt_tmpfreevnodelist, v_actfreelist) {
1217 VNASSERT((vp->v_mflag & VMP_TMPMNTFREELIST) != 0, vp,
1218 ("vnode without VMP_TMPMNTFREELIST on mnt_tmpfreevnodelist"));
1219 vp->v_mflag &= ~VMP_TMPMNTFREELIST;
1221 mtx_lock(&vnode_free_list_mtx);
1222 TAILQ_CONCAT(&vnode_free_list, &mp->mnt_tmpfreevnodelist, v_actfreelist);
1223 freevnodes += mp->mnt_tmpfreevnodelistsize;
1224 mtx_unlock(&vnode_free_list_mtx);
1225 mp->mnt_tmpfreevnodelistsize = 0;
1229 vnlru_return_batch(struct mount *mp)
1232 mtx_lock(&mp->mnt_listmtx);
1233 vnlru_return_batch_locked(mp);
1234 mtx_unlock(&mp->mnt_listmtx);
1238 vnlru_return_batches(struct vfsops *mnt_op)
1240 struct mount *mp, *nmp;
1243 mtx_lock(&mountlist_mtx);
1244 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1245 need_unbusy = false;
1246 if (mnt_op != NULL && mp->mnt_op != mnt_op)
1248 if (mp->mnt_tmpfreevnodelistsize == 0)
1250 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK) == 0) {
1251 vnlru_return_batch(mp);
1253 mtx_lock(&mountlist_mtx);
1256 nmp = TAILQ_NEXT(mp, mnt_list);
1260 mtx_unlock(&mountlist_mtx);
1264 * Attempt to recycle vnodes in a context that is always safe to block.
1265 * Calling vlrurecycle() from the bowels of filesystem code has some
1266 * interesting deadlock problems.
1268 static struct proc *vnlruproc;
1269 static int vnlruproc_sig;
1274 struct mount *mp, *nmp;
1275 unsigned long onumvnodes;
1276 int done, force, trigger, usevnodes, vsp;
1277 bool reclaim_nc_src;
1279 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1280 SHUTDOWN_PRI_FIRST);
1284 kproc_suspend_check(vnlruproc);
1285 mtx_lock(&vnode_free_list_mtx);
1287 * If numvnodes is too large (due to desiredvnodes being
1288 * adjusted using its sysctl, or emergency growth), first
1289 * try to reduce it by discarding from the free list.
1291 if (numvnodes > desiredvnodes)
1292 vnlru_free_locked(numvnodes - desiredvnodes, NULL);
1294 * Sleep if the vnode cache is in a good state. This is
1295 * when it is not over-full and has space for about a 4%
1296 * or 9% expansion (by growing its size or inexcessively
1297 * reducing its free list). Otherwise, try to reclaim
1298 * space for a 10% expansion.
1300 if (vstir && force == 0) {
1305 if (vsp >= vlowat && force == 0) {
1307 wakeup(&vnlruproc_sig);
1308 msleep(vnlruproc, &vnode_free_list_mtx,
1309 PVFS|PDROP, "vlruwt", hz);
1312 mtx_unlock(&vnode_free_list_mtx);
1314 onumvnodes = numvnodes;
1316 * Calculate parameters for recycling. These are the same
1317 * throughout the loop to give some semblance of fairness.
1318 * The trigger point is to avoid recycling vnodes with lots
1319 * of resident pages. We aren't trying to free memory; we
1320 * are trying to recycle or at least free vnodes.
1322 if (numvnodes <= desiredvnodes)
1323 usevnodes = numvnodes - freevnodes;
1325 usevnodes = numvnodes;
1329 * The trigger value is is chosen to give a conservatively
1330 * large value to ensure that it alone doesn't prevent
1331 * making progress. The value can easily be so large that
1332 * it is effectively infinite in some congested and
1333 * misconfigured cases, and this is necessary. Normally
1334 * it is about 8 to 100 (pages), which is quite large.
1336 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1338 trigger = vsmalltrigger;
1339 reclaim_nc_src = force >= 3;
1340 mtx_lock(&mountlist_mtx);
1341 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1342 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK)) {
1343 nmp = TAILQ_NEXT(mp, mnt_list);
1346 done += vlrureclaim(mp, reclaim_nc_src, trigger);
1347 mtx_lock(&mountlist_mtx);
1348 nmp = TAILQ_NEXT(mp, mnt_list);
1351 mtx_unlock(&mountlist_mtx);
1352 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1353 uma_reclaim(UMA_RECLAIM_DRAIN);
1355 if (force == 0 || force == 1) {
1365 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1367 kern_yield(PRI_USER);
1369 * After becoming active to expand above low water, keep
1370 * active until above high water.
1373 force = vsp < vhiwat;
1377 static struct kproc_desc vnlru_kp = {
1382 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1386 * Routines having to do with the management of the vnode table.
1390 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1391 * before we actually vgone(). This function must be called with the vnode
1392 * held to prevent the vnode from being returned to the free list midway
1396 vtryrecycle(struct vnode *vp)
1400 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1401 VNASSERT(vp->v_holdcnt, vp,
1402 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1404 * This vnode may found and locked via some other list, if so we
1405 * can't recycle it yet.
1407 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1409 "%s: impossible to recycle, vp %p lock is already held",
1411 return (EWOULDBLOCK);
1414 * Don't recycle if its filesystem is being suspended.
1416 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1419 "%s: impossible to recycle, cannot start the write for %p",
1424 * If we got this far, we need to acquire the interlock and see if
1425 * anyone picked up this vnode from another list. If not, we will
1426 * mark it with DOOMED via vgonel() so that anyone who does find it
1427 * will skip over it.
1430 if (vp->v_usecount) {
1433 vn_finished_write(vnmp);
1435 "%s: impossible to recycle, %p is already referenced",
1439 if ((vp->v_iflag & VI_DOOMED) == 0) {
1440 counter_u64_add(recycles_count, 1);
1445 vn_finished_write(vnmp);
1455 if (vsp < vlowat && vnlruproc_sig == 0) {
1462 * Wait if necessary for space for a new vnode.
1465 getnewvnode_wait(int suspended)
1468 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
1469 if (numvnodes >= desiredvnodes) {
1472 * The file system is being suspended. We cannot
1473 * risk a deadlock here, so allow allocation of
1474 * another vnode even if this would give too many.
1478 if (vnlruproc_sig == 0) {
1479 vnlruproc_sig = 1; /* avoid unnecessary wakeups */
1482 msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
1485 /* Post-adjust like the pre-adjust in getnewvnode(). */
1486 if (numvnodes + 1 > desiredvnodes && freevnodes > 1)
1487 vnlru_free_locked(1, NULL);
1488 return (numvnodes >= desiredvnodes ? ENFILE : 0);
1492 * This hack is fragile, and probably not needed any more now that the
1493 * watermark handling works.
1496 getnewvnode_reserve(u_int count)
1500 /* Pre-adjust like the pre-adjust in getnewvnode(), with any count. */
1501 /* XXX no longer so quick, but this part is not racy. */
1502 mtx_lock(&vnode_free_list_mtx);
1503 if (numvnodes + count > desiredvnodes && freevnodes > wantfreevnodes)
1504 vnlru_free_locked(ulmin(numvnodes + count - desiredvnodes,
1505 freevnodes - wantfreevnodes), NULL);
1506 mtx_unlock(&vnode_free_list_mtx);
1509 /* First try to be quick and racy. */
1510 if (atomic_fetchadd_long(&numvnodes, count) + count <= desiredvnodes) {
1511 td->td_vp_reserv += count;
1512 vcheckspace(); /* XXX no longer so quick, but more racy */
1515 atomic_subtract_long(&numvnodes, count);
1517 mtx_lock(&vnode_free_list_mtx);
1519 if (getnewvnode_wait(0) == 0) {
1522 atomic_add_long(&numvnodes, 1);
1526 mtx_unlock(&vnode_free_list_mtx);
1530 * This hack is fragile, especially if desiredvnodes or wantvnodes are
1531 * misconfgured or changed significantly. Reducing desiredvnodes below
1532 * the reserved amount should cause bizarre behaviour like reducing it
1533 * below the number of active vnodes -- the system will try to reduce
1534 * numvnodes to match, but should fail, so the subtraction below should
1538 getnewvnode_drop_reserve(void)
1543 atomic_subtract_long(&numvnodes, td->td_vp_reserv);
1544 td->td_vp_reserv = 0;
1548 * Return the next vnode from the free list.
1551 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1556 struct lock_object *lo;
1557 static int cyclecount;
1560 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1563 if (td->td_vp_reserv > 0) {
1564 td->td_vp_reserv -= 1;
1567 mtx_lock(&vnode_free_list_mtx);
1568 if (numvnodes < desiredvnodes)
1570 else if (cyclecount++ >= freevnodes) {
1575 * Grow the vnode cache if it will not be above its target max
1576 * after growing. Otherwise, if the free list is nonempty, try
1577 * to reclaim 1 item from it before growing the cache (possibly
1578 * above its target max if the reclamation failed or is delayed).
1579 * Otherwise, wait for some space. In all cases, schedule
1580 * vnlru_proc() if we are getting short of space. The watermarks
1581 * should be chosen so that we never wait or even reclaim from
1582 * the free list to below its target minimum.
1584 if (numvnodes + 1 <= desiredvnodes)
1586 else if (freevnodes > 0)
1587 vnlru_free_locked(1, NULL);
1589 error = getnewvnode_wait(mp != NULL && (mp->mnt_kern_flag &
1591 #if 0 /* XXX Not all VFS_VGET/ffs_vget callers check returns. */
1593 mtx_unlock(&vnode_free_list_mtx);
1599 atomic_add_long(&numvnodes, 1);
1600 mtx_unlock(&vnode_free_list_mtx);
1602 counter_u64_add(vnodes_created, 1);
1603 vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK);
1605 * Locks are given the generic name "vnode" when created.
1606 * Follow the historic practice of using the filesystem
1607 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1609 * Locks live in a witness group keyed on their name. Thus,
1610 * when a lock is renamed, it must also move from the witness
1611 * group of its old name to the witness group of its new name.
1613 * The change only needs to be made when the vnode moves
1614 * from one filesystem type to another. We ensure that each
1615 * filesystem use a single static name pointer for its tag so
1616 * that we can compare pointers rather than doing a strcmp().
1618 lo = &vp->v_vnlock->lock_object;
1619 if (lo->lo_name != tag) {
1621 WITNESS_DESTROY(lo);
1622 WITNESS_INIT(lo, tag);
1625 * By default, don't allow shared locks unless filesystems opt-in.
1627 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1629 * Finalize various vnode identity bits.
1631 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1632 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1633 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1637 v_init_counters(vp);
1638 vp->v_bufobj.bo_ops = &buf_ops_bio;
1640 if (mp == NULL && vops != &dead_vnodeops)
1641 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1645 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1646 mac_vnode_associate_singlelabel(mp, vp);
1649 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1650 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1651 vp->v_vflag |= VV_NOKNOTE;
1655 * For the filesystems which do not use vfs_hash_insert(),
1656 * still initialize v_hash to have vfs_hash_index() useful.
1657 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1660 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1667 * Delete from old mount point vnode list, if on one.
1670 delmntque(struct vnode *vp)
1679 KASSERT(mp->mnt_activevnodelistsize <= mp->mnt_nvnodelistsize,
1680 ("Active vnode list size %d > Vnode list size %d",
1681 mp->mnt_activevnodelistsize, mp->mnt_nvnodelistsize));
1682 if (vp->v_iflag & VI_ACTIVE) {
1683 vp->v_iflag &= ~VI_ACTIVE;
1684 mtx_lock(&mp->mnt_listmtx);
1685 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp, v_actfreelist);
1686 mp->mnt_activevnodelistsize--;
1687 mtx_unlock(&mp->mnt_listmtx);
1691 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1692 ("bad mount point vnode list size"));
1693 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1694 mp->mnt_nvnodelistsize--;
1700 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1704 vp->v_op = &dead_vnodeops;
1710 * Insert into list of vnodes for the new mount point, if available.
1713 insmntque1(struct vnode *vp, struct mount *mp,
1714 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1717 KASSERT(vp->v_mount == NULL,
1718 ("insmntque: vnode already on per mount vnode list"));
1719 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1720 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1723 * We acquire the vnode interlock early to ensure that the
1724 * vnode cannot be recycled by another process releasing a
1725 * holdcnt on it before we get it on both the vnode list
1726 * and the active vnode list. The mount mutex protects only
1727 * manipulation of the vnode list and the vnode freelist
1728 * mutex protects only manipulation of the active vnode list.
1729 * Hence the need to hold the vnode interlock throughout.
1733 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1734 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1735 mp->mnt_nvnodelistsize == 0)) &&
1736 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1745 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1746 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1747 ("neg mount point vnode list size"));
1748 mp->mnt_nvnodelistsize++;
1749 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1750 ("Activating already active vnode"));
1751 vp->v_iflag |= VI_ACTIVE;
1752 mtx_lock(&mp->mnt_listmtx);
1753 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
1754 mp->mnt_activevnodelistsize++;
1755 mtx_unlock(&mp->mnt_listmtx);
1762 insmntque(struct vnode *vp, struct mount *mp)
1765 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1769 * Flush out and invalidate all buffers associated with a bufobj
1770 * Called with the underlying object locked.
1773 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1778 if (flags & V_SAVE) {
1779 error = bufobj_wwait(bo, slpflag, slptimeo);
1784 if (bo->bo_dirty.bv_cnt > 0) {
1786 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1789 * XXX We could save a lock/unlock if this was only
1790 * enabled under INVARIANTS
1793 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1794 panic("vinvalbuf: dirty bufs");
1798 * If you alter this loop please notice that interlock is dropped and
1799 * reacquired in flushbuflist. Special care is needed to ensure that
1800 * no race conditions occur from this.
1803 error = flushbuflist(&bo->bo_clean,
1804 flags, bo, slpflag, slptimeo);
1805 if (error == 0 && !(flags & V_CLEANONLY))
1806 error = flushbuflist(&bo->bo_dirty,
1807 flags, bo, slpflag, slptimeo);
1808 if (error != 0 && error != EAGAIN) {
1812 } while (error != 0);
1815 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1816 * have write I/O in-progress but if there is a VM object then the
1817 * VM object can also have read-I/O in-progress.
1820 bufobj_wwait(bo, 0, 0);
1821 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
1823 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
1826 } while (bo->bo_numoutput > 0);
1830 * Destroy the copy in the VM cache, too.
1832 if (bo->bo_object != NULL &&
1833 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1834 VM_OBJECT_WLOCK(bo->bo_object);
1835 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1836 OBJPR_CLEANONLY : 0);
1837 VM_OBJECT_WUNLOCK(bo->bo_object);
1842 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1843 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1844 bo->bo_clean.bv_cnt > 0))
1845 panic("vinvalbuf: flush failed");
1846 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1847 bo->bo_dirty.bv_cnt > 0)
1848 panic("vinvalbuf: flush dirty failed");
1855 * Flush out and invalidate all buffers associated with a vnode.
1856 * Called with the underlying object locked.
1859 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1862 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1863 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1864 if (vp->v_object != NULL && vp->v_object->handle != vp)
1866 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1870 * Flush out buffers on the specified list.
1874 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1877 struct buf *bp, *nbp;
1882 ASSERT_BO_WLOCKED(bo);
1885 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1887 * If we are flushing both V_NORMAL and V_ALT buffers then
1888 * do not skip any buffers. If we are flushing only V_NORMAL
1889 * buffers then skip buffers marked as BX_ALTDATA. If we are
1890 * flushing only V_ALT buffers then skip buffers not marked
1893 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
1894 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
1895 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
1899 lblkno = nbp->b_lblkno;
1900 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
1903 error = BUF_TIMELOCK(bp,
1904 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
1905 "flushbuf", slpflag, slptimeo);
1908 return (error != ENOLCK ? error : EAGAIN);
1910 KASSERT(bp->b_bufobj == bo,
1911 ("bp %p wrong b_bufobj %p should be %p",
1912 bp, bp->b_bufobj, bo));
1914 * XXX Since there are no node locks for NFS, I
1915 * believe there is a slight chance that a delayed
1916 * write will occur while sleeping just above, so
1919 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1922 bp->b_flags |= B_ASYNC;
1925 return (EAGAIN); /* XXX: why not loop ? */
1928 bp->b_flags |= (B_INVAL | B_RELBUF);
1929 bp->b_flags &= ~B_ASYNC;
1934 nbp = gbincore(bo, lblkno);
1935 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1937 break; /* nbp invalid */
1943 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
1949 ASSERT_BO_LOCKED(bo);
1951 for (lblkno = startn;;) {
1953 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
1954 if (bp == NULL || bp->b_lblkno >= endn ||
1955 bp->b_lblkno < startn)
1957 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
1958 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
1961 if (error == ENOLCK)
1965 KASSERT(bp->b_bufobj == bo,
1966 ("bp %p wrong b_bufobj %p should be %p",
1967 bp, bp->b_bufobj, bo));
1968 lblkno = bp->b_lblkno + 1;
1969 if ((bp->b_flags & B_MANAGED) == 0)
1971 bp->b_flags |= B_RELBUF;
1973 * In the VMIO case, use the B_NOREUSE flag to hint that the
1974 * pages backing each buffer in the range are unlikely to be
1975 * reused. Dirty buffers will have the hint applied once
1976 * they've been written.
1978 if ((bp->b_flags & B_VMIO) != 0)
1979 bp->b_flags |= B_NOREUSE;
1987 * Truncate a file's buffer and pages to a specified length. This
1988 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
1992 vtruncbuf(struct vnode *vp, off_t length, int blksize)
1994 struct buf *bp, *nbp;
1998 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
1999 vp, blksize, (uintmax_t)length);
2002 * Round up to the *next* lbn.
2004 startlbn = howmany(length, blksize);
2006 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2012 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2017 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2018 if (bp->b_lblkno > 0)
2021 * Since we hold the vnode lock this should only
2022 * fail if we're racing with the buf daemon.
2025 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2026 BO_LOCKPTR(bo)) == ENOLCK)
2027 goto restart_unlocked;
2029 VNASSERT((bp->b_flags & B_DELWRI), vp,
2030 ("buf(%p) on dirty queue without DELWRI", bp));
2039 bufobj_wwait(bo, 0, 0);
2041 vnode_pager_setsize(vp, length);
2047 * Invalidate the cached pages of a file's buffer within the range of block
2048 * numbers [startlbn, endlbn).
2051 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2057 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2059 start = blksize * startlbn;
2060 end = blksize * endlbn;
2064 MPASS(blksize == bo->bo_bsize);
2066 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2070 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2074 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2075 daddr_t startlbn, daddr_t endlbn)
2077 struct buf *bp, *nbp;
2080 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2081 ASSERT_BO_LOCKED(bo);
2085 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2086 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2089 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2090 BO_LOCKPTR(bo)) == ENOLCK) {
2096 bp->b_flags |= B_INVAL | B_RELBUF;
2097 bp->b_flags &= ~B_ASYNC;
2103 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2105 (nbp->b_flags & B_DELWRI) != 0))
2109 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2110 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2113 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2114 BO_LOCKPTR(bo)) == ENOLCK) {
2119 bp->b_flags |= B_INVAL | B_RELBUF;
2120 bp->b_flags &= ~B_ASYNC;
2126 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2127 (nbp->b_vp != vp) ||
2128 (nbp->b_flags & B_DELWRI) == 0))
2136 buf_vlist_remove(struct buf *bp)
2140 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2141 ASSERT_BO_WLOCKED(bp->b_bufobj);
2142 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
2143 (BX_VNDIRTY|BX_VNCLEAN),
2144 ("buf_vlist_remove: Buf %p is on two lists", bp));
2145 if (bp->b_xflags & BX_VNDIRTY)
2146 bv = &bp->b_bufobj->bo_dirty;
2148 bv = &bp->b_bufobj->bo_clean;
2149 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2150 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2152 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2156 * Add the buffer to the sorted clean or dirty block list.
2158 * NOTE: xflags is passed as a constant, optimizing this inline function!
2161 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2167 ASSERT_BO_WLOCKED(bo);
2168 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2169 ("dead bo %p", bo));
2170 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2171 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2172 bp->b_xflags |= xflags;
2173 if (xflags & BX_VNDIRTY)
2179 * Keep the list ordered. Optimize empty list insertion. Assume
2180 * we tend to grow at the tail so lookup_le should usually be cheaper
2183 if (bv->bv_cnt == 0 ||
2184 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2185 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2186 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2187 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2189 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2190 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2192 panic("buf_vlist_add: Preallocated nodes insufficient.");
2197 * Look up a buffer using the buffer tries.
2200 gbincore(struct bufobj *bo, daddr_t lblkno)
2204 ASSERT_BO_LOCKED(bo);
2205 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2208 return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
2212 * Associate a buffer with a vnode.
2215 bgetvp(struct vnode *vp, struct buf *bp)
2220 ASSERT_BO_WLOCKED(bo);
2221 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2223 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2224 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2225 ("bgetvp: bp already attached! %p", bp));
2231 * Insert onto list for new vnode.
2233 buf_vlist_add(bp, bo, BX_VNCLEAN);
2237 * Disassociate a buffer from a vnode.
2240 brelvp(struct buf *bp)
2245 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2246 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2249 * Delete from old vnode list, if on one.
2251 vp = bp->b_vp; /* XXX */
2254 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2255 buf_vlist_remove(bp);
2257 panic("brelvp: Buffer %p not on queue.", bp);
2258 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2259 bo->bo_flag &= ~BO_ONWORKLST;
2260 mtx_lock(&sync_mtx);
2261 LIST_REMOVE(bo, bo_synclist);
2262 syncer_worklist_len--;
2263 mtx_unlock(&sync_mtx);
2266 bp->b_bufobj = NULL;
2272 * Add an item to the syncer work queue.
2275 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2279 ASSERT_BO_WLOCKED(bo);
2281 mtx_lock(&sync_mtx);
2282 if (bo->bo_flag & BO_ONWORKLST)
2283 LIST_REMOVE(bo, bo_synclist);
2285 bo->bo_flag |= BO_ONWORKLST;
2286 syncer_worklist_len++;
2289 if (delay > syncer_maxdelay - 2)
2290 delay = syncer_maxdelay - 2;
2291 slot = (syncer_delayno + delay) & syncer_mask;
2293 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2294 mtx_unlock(&sync_mtx);
2298 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2302 mtx_lock(&sync_mtx);
2303 len = syncer_worklist_len - sync_vnode_count;
2304 mtx_unlock(&sync_mtx);
2305 error = SYSCTL_OUT(req, &len, sizeof(len));
2309 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
2310 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2312 static struct proc *updateproc;
2313 static void sched_sync(void);
2314 static struct kproc_desc up_kp = {
2319 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2322 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2327 *bo = LIST_FIRST(slp);
2331 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2334 * We use vhold in case the vnode does not
2335 * successfully sync. vhold prevents the vnode from
2336 * going away when we unlock the sync_mtx so that
2337 * we can acquire the vnode interlock.
2340 mtx_unlock(&sync_mtx);
2342 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2344 mtx_lock(&sync_mtx);
2345 return (*bo == LIST_FIRST(slp));
2347 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2348 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2350 vn_finished_write(mp);
2352 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2354 * Put us back on the worklist. The worklist
2355 * routine will remove us from our current
2356 * position and then add us back in at a later
2359 vn_syncer_add_to_worklist(*bo, syncdelay);
2363 mtx_lock(&sync_mtx);
2367 static int first_printf = 1;
2370 * System filesystem synchronizer daemon.
2375 struct synclist *next, *slp;
2378 struct thread *td = curthread;
2380 int net_worklist_len;
2381 int syncer_final_iter;
2385 syncer_final_iter = 0;
2386 syncer_state = SYNCER_RUNNING;
2387 starttime = time_uptime;
2388 td->td_pflags |= TDP_NORUNNINGBUF;
2390 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2393 mtx_lock(&sync_mtx);
2395 if (syncer_state == SYNCER_FINAL_DELAY &&
2396 syncer_final_iter == 0) {
2397 mtx_unlock(&sync_mtx);
2398 kproc_suspend_check(td->td_proc);
2399 mtx_lock(&sync_mtx);
2401 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2402 if (syncer_state != SYNCER_RUNNING &&
2403 starttime != time_uptime) {
2405 printf("\nSyncing disks, vnodes remaining... ");
2408 printf("%d ", net_worklist_len);
2410 starttime = time_uptime;
2413 * Push files whose dirty time has expired. Be careful
2414 * of interrupt race on slp queue.
2416 * Skip over empty worklist slots when shutting down.
2419 slp = &syncer_workitem_pending[syncer_delayno];
2420 syncer_delayno += 1;
2421 if (syncer_delayno == syncer_maxdelay)
2423 next = &syncer_workitem_pending[syncer_delayno];
2425 * If the worklist has wrapped since the
2426 * it was emptied of all but syncer vnodes,
2427 * switch to the FINAL_DELAY state and run
2428 * for one more second.
2430 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2431 net_worklist_len == 0 &&
2432 last_work_seen == syncer_delayno) {
2433 syncer_state = SYNCER_FINAL_DELAY;
2434 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2436 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2437 syncer_worklist_len > 0);
2440 * Keep track of the last time there was anything
2441 * on the worklist other than syncer vnodes.
2442 * Return to the SHUTTING_DOWN state if any
2445 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2446 last_work_seen = syncer_delayno;
2447 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2448 syncer_state = SYNCER_SHUTTING_DOWN;
2449 while (!LIST_EMPTY(slp)) {
2450 error = sync_vnode(slp, &bo, td);
2452 LIST_REMOVE(bo, bo_synclist);
2453 LIST_INSERT_HEAD(next, bo, bo_synclist);
2457 if (first_printf == 0) {
2459 * Drop the sync mutex, because some watchdog
2460 * drivers need to sleep while patting
2462 mtx_unlock(&sync_mtx);
2463 wdog_kern_pat(WD_LASTVAL);
2464 mtx_lock(&sync_mtx);
2468 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2469 syncer_final_iter--;
2471 * The variable rushjob allows the kernel to speed up the
2472 * processing of the filesystem syncer process. A rushjob
2473 * value of N tells the filesystem syncer to process the next
2474 * N seconds worth of work on its queue ASAP. Currently rushjob
2475 * is used by the soft update code to speed up the filesystem
2476 * syncer process when the incore state is getting so far
2477 * ahead of the disk that the kernel memory pool is being
2478 * threatened with exhaustion.
2485 * Just sleep for a short period of time between
2486 * iterations when shutting down to allow some I/O
2489 * If it has taken us less than a second to process the
2490 * current work, then wait. Otherwise start right over
2491 * again. We can still lose time if any single round
2492 * takes more than two seconds, but it does not really
2493 * matter as we are just trying to generally pace the
2494 * filesystem activity.
2496 if (syncer_state != SYNCER_RUNNING ||
2497 time_uptime == starttime) {
2499 sched_prio(td, PPAUSE);
2502 if (syncer_state != SYNCER_RUNNING)
2503 cv_timedwait(&sync_wakeup, &sync_mtx,
2504 hz / SYNCER_SHUTDOWN_SPEEDUP);
2505 else if (time_uptime == starttime)
2506 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2511 * Request the syncer daemon to speed up its work.
2512 * We never push it to speed up more than half of its
2513 * normal turn time, otherwise it could take over the cpu.
2516 speedup_syncer(void)
2520 mtx_lock(&sync_mtx);
2521 if (rushjob < syncdelay / 2) {
2523 stat_rush_requests += 1;
2526 mtx_unlock(&sync_mtx);
2527 cv_broadcast(&sync_wakeup);
2532 * Tell the syncer to speed up its work and run though its work
2533 * list several times, then tell it to shut down.
2536 syncer_shutdown(void *arg, int howto)
2539 if (howto & RB_NOSYNC)
2541 mtx_lock(&sync_mtx);
2542 syncer_state = SYNCER_SHUTTING_DOWN;
2544 mtx_unlock(&sync_mtx);
2545 cv_broadcast(&sync_wakeup);
2546 kproc_shutdown(arg, howto);
2550 syncer_suspend(void)
2553 syncer_shutdown(updateproc, 0);
2560 mtx_lock(&sync_mtx);
2562 syncer_state = SYNCER_RUNNING;
2563 mtx_unlock(&sync_mtx);
2564 cv_broadcast(&sync_wakeup);
2565 kproc_resume(updateproc);
2569 * Reassign a buffer from one vnode to another.
2570 * Used to assign file specific control information
2571 * (indirect blocks) to the vnode to which they belong.
2574 reassignbuf(struct buf *bp)
2587 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2588 bp, bp->b_vp, bp->b_flags);
2590 * B_PAGING flagged buffers cannot be reassigned because their vp
2591 * is not fully linked in.
2593 if (bp->b_flags & B_PAGING)
2594 panic("cannot reassign paging buffer");
2597 * Delete from old vnode list, if on one.
2600 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2601 buf_vlist_remove(bp);
2603 panic("reassignbuf: Buffer %p not on queue.", bp);
2605 * If dirty, put on list of dirty buffers; otherwise insert onto list
2608 if (bp->b_flags & B_DELWRI) {
2609 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2610 switch (vp->v_type) {
2620 vn_syncer_add_to_worklist(bo, delay);
2622 buf_vlist_add(bp, bo, BX_VNDIRTY);
2624 buf_vlist_add(bp, bo, BX_VNCLEAN);
2626 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2627 mtx_lock(&sync_mtx);
2628 LIST_REMOVE(bo, bo_synclist);
2629 syncer_worklist_len--;
2630 mtx_unlock(&sync_mtx);
2631 bo->bo_flag &= ~BO_ONWORKLST;
2636 bp = TAILQ_FIRST(&bv->bv_hd);
2637 KASSERT(bp == NULL || bp->b_bufobj == bo,
2638 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2639 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2640 KASSERT(bp == NULL || bp->b_bufobj == bo,
2641 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2643 bp = TAILQ_FIRST(&bv->bv_hd);
2644 KASSERT(bp == NULL || bp->b_bufobj == bo,
2645 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2646 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2647 KASSERT(bp == NULL || bp->b_bufobj == bo,
2648 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2654 v_init_counters(struct vnode *vp)
2657 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2658 vp, ("%s called for an initialized vnode", __FUNCTION__));
2659 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2661 refcount_init(&vp->v_holdcnt, 1);
2662 refcount_init(&vp->v_usecount, 1);
2666 * Increment si_usecount of the associated device, if any.
2669 v_incr_devcount(struct vnode *vp)
2672 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2673 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2675 vp->v_rdev->si_usecount++;
2681 * Decrement si_usecount of the associated device, if any.
2684 v_decr_devcount(struct vnode *vp)
2687 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2688 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2690 vp->v_rdev->si_usecount--;
2696 * Grab a particular vnode from the free list, increment its
2697 * reference count and lock it. VI_DOOMED is set if the vnode
2698 * is being destroyed. Only callers who specify LK_RETRY will
2699 * see doomed vnodes. If inactive processing was delayed in
2700 * vput try to do it here.
2702 * Both holdcnt and usecount can be manipulated using atomics without holding
2703 * any locks except in these cases which require the vnode interlock:
2704 * holdcnt: 1->0 and 0->1
2707 * usecount is permitted to transition 1->0 without the interlock because
2708 * vnode is kept live by holdcnt.
2710 static enum vgetstate
2711 _vget_prep(struct vnode *vp, bool interlock)
2715 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2718 _vhold(vp, interlock);
2725 vget_prep(struct vnode *vp)
2728 return (_vget_prep(vp, false));
2732 vget(struct vnode *vp, int flags, struct thread *td)
2736 MPASS(td == curthread);
2738 vs = _vget_prep(vp, (flags & LK_INTERLOCK) != 0);
2739 return (vget_finish(vp, flags, vs));
2743 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
2745 int error, oweinact;
2747 VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2748 ("%s: invalid lock operation", __func__));
2750 if ((flags & LK_INTERLOCK) != 0)
2751 ASSERT_VI_LOCKED(vp, __func__);
2753 ASSERT_VI_UNLOCKED(vp, __func__);
2754 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
2755 if (vs == VGET_USECOUNT) {
2756 VNASSERT(vp->v_usecount > 0, vp,
2757 ("%s: vnode without usecount when VGET_USECOUNT was passed",
2761 if ((error = vn_lock(vp, flags)) != 0) {
2762 if (vs == VGET_USECOUNT)
2766 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2771 if (vs == VGET_USECOUNT) {
2772 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2773 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2778 * We hold the vnode. If the usecount is 0 it will be utilized to keep
2779 * the vnode around. Otherwise someone else lended their hold count and
2780 * we have to drop ours.
2782 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2784 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1) - 1;
2785 VNASSERT(old > 0, vp, ("%s: wrong hold count", __func__));
2787 refcount_release(&vp->v_holdcnt);
2789 VNODE_REFCOUNT_FENCE_ACQ();
2790 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2791 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2796 * We don't guarantee that any particular close will
2797 * trigger inactive processing so just make a best effort
2798 * here at preventing a reference to a removed file. If
2799 * we don't succeed no harm is done.
2801 * Upgrade our holdcnt to a usecount.
2805 * See the previous section. By the time we get here we may find
2806 * ourselves in the same spot.
2808 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2810 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1) - 1;
2811 VNASSERT(old > 0, vp, ("%s: wrong hold count", __func__));
2813 refcount_release(&vp->v_holdcnt);
2815 VNODE_REFCOUNT_FENCE_ACQ();
2816 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2817 ("%s: vnode with usecount and VI_OWEINACT set",
2822 if ((vp->v_iflag & VI_OWEINACT) == 0) {
2826 vp->v_iflag &= ~VI_OWEINACT;
2827 VNODE_REFCOUNT_FENCE_REL();
2829 v_incr_devcount(vp);
2830 refcount_acquire(&vp->v_usecount);
2831 if (oweinact && VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2832 (flags & LK_NOWAIT) == 0)
2833 vinactive(vp, curthread);
2839 * Increase the reference (use) and hold count of a vnode.
2840 * This will also remove the vnode from the free list if it is presently free.
2843 vref(struct vnode *vp)
2846 ASSERT_VI_UNLOCKED(vp, __func__);
2847 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2848 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2849 VNODE_REFCOUNT_FENCE_ACQ();
2850 VNASSERT(vp->v_holdcnt > 0, vp,
2851 ("%s: active vnode not held", __func__));
2852 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2853 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2862 vrefl(struct vnode *vp)
2865 ASSERT_VI_LOCKED(vp, __func__);
2866 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2867 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2868 VNODE_REFCOUNT_FENCE_ACQ();
2869 VNASSERT(vp->v_holdcnt > 0, vp,
2870 ("%s: active vnode not held", __func__));
2871 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2872 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2876 if ((vp->v_iflag & VI_OWEINACT) != 0) {
2877 vp->v_iflag &= ~VI_OWEINACT;
2878 VNODE_REFCOUNT_FENCE_REL();
2880 v_incr_devcount(vp);
2881 refcount_acquire(&vp->v_usecount);
2885 vrefact(struct vnode *vp)
2888 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2890 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
2891 VNASSERT(old > 0, vp, ("%s: wrong use count", __func__));
2893 refcount_acquire(&vp->v_usecount);
2898 * Return reference count of a vnode.
2900 * The results of this call are only guaranteed when some mechanism is used to
2901 * stop other processes from gaining references to the vnode. This may be the
2902 * case if the caller holds the only reference. This is also useful when stale
2903 * data is acceptable as race conditions may be accounted for by some other
2907 vrefcnt(struct vnode *vp)
2910 return (vp->v_usecount);
2913 #define VPUTX_VRELE 1
2914 #define VPUTX_VPUT 2
2915 #define VPUTX_VUNREF 3
2918 * Decrement the use and hold counts for a vnode.
2920 * See an explanation near vget() as to why atomic operation is safe.
2923 vputx(struct vnode *vp, int func)
2927 KASSERT(vp != NULL, ("vputx: null vp"));
2928 if (func == VPUTX_VUNREF)
2929 ASSERT_VOP_LOCKED(vp, "vunref");
2930 else if (func == VPUTX_VPUT)
2931 ASSERT_VOP_LOCKED(vp, "vput");
2933 KASSERT(func == VPUTX_VRELE, ("vputx: wrong func"));
2934 ASSERT_VI_UNLOCKED(vp, __func__);
2935 VNASSERT(vp->v_holdcnt > 0 && vp->v_usecount > 0, vp,
2936 ("%s: wrong ref counts", __func__));
2938 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2941 * It is an invariant that all VOP_* calls operate on a held vnode.
2942 * We may be only having an implicit hold stemming from our usecount,
2943 * which we are about to release. If we unlock the vnode afterwards we
2944 * open a time window where someone else dropped the last usecount and
2945 * proceeded to free the vnode before our unlock finished. For this
2946 * reason we unlock the vnode early. This is a little bit wasteful as
2947 * it may be the vnode is exclusively locked and inactive processing is
2948 * needed, in which case we are adding work.
2950 if (func == VPUTX_VPUT)
2954 * We want to hold the vnode until the inactive finishes to
2955 * prevent vgone() races. We drop the use count here and the
2956 * hold count below when we're done.
2958 * If we release the last usecount we take ownership of the hold
2959 * count which provides liveness of the vnode, in which case we
2962 if (!refcount_release(&vp->v_usecount))
2965 v_decr_devcount(vp);
2967 * By the time we got here someone else might have transitioned
2968 * the count back to > 0.
2970 if (vp->v_usecount > 0) {
2974 if (vp->v_iflag & VI_DOINGINACT) {
2981 if (vp->v_usecount != 0) {
2982 vn_printf(vp, "vputx: usecount not zero for vnode ");
2983 panic("vputx: usecount not zero");
2986 CTR2(KTR_VFS, "%s: return vnode %p to the freelist", __func__, vp);
2989 * Check if the fs wants to perform inactive processing. Note we
2990 * may be only holding the interlock, in which case it is possible
2991 * someone else called vgone on the vnode and ->v_data is now NULL.
2992 * Since vgone performs inactive on its own there is nothing to do
2993 * here but to drop our hold count.
2995 if (__predict_false(vp->v_iflag & VI_DOOMED) ||
2996 VOP_NEED_INACTIVE(vp) == 0) {
3002 * We must call VOP_INACTIVE with the node locked. Mark
3003 * as VI_DOINGINACT to avoid recursion.
3005 vp->v_iflag |= VI_OWEINACT;
3008 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3012 error = VOP_LOCK(vp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT);
3016 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3017 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3022 VNASSERT(vp->v_usecount == 0 || (vp->v_iflag & VI_OWEINACT) == 0, vp,
3023 ("vnode with usecount and VI_OWEINACT set"));
3025 if (vp->v_iflag & VI_OWEINACT)
3026 vinactive(vp, curthread);
3027 if (func != VPUTX_VUNREF)
3034 * Vnode put/release.
3035 * If count drops to zero, call inactive routine and return to freelist.
3038 vrele(struct vnode *vp)
3041 vputx(vp, VPUTX_VRELE);
3045 * Release an already locked vnode. This give the same effects as
3046 * unlock+vrele(), but takes less time and avoids releasing and
3047 * re-aquiring the lock (as vrele() acquires the lock internally.)
3050 vput(struct vnode *vp)
3053 vputx(vp, VPUTX_VPUT);
3057 * Release an exclusively locked vnode. Do not unlock the vnode lock.
3060 vunref(struct vnode *vp)
3063 vputx(vp, VPUTX_VUNREF);
3067 * Increase the hold count and activate if this is the first reference.
3070 _vhold(struct vnode *vp, bool locked)
3075 ASSERT_VI_LOCKED(vp, __func__);
3077 ASSERT_VI_UNLOCKED(vp, __func__);
3078 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3080 if (refcount_acquire_if_not_zero(&vp->v_holdcnt)) {
3081 VNODE_REFCOUNT_FENCE_ACQ();
3082 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
3083 ("_vhold: vnode with holdcnt is free"));
3088 if ((vp->v_iflag & VI_FREE) == 0) {
3089 refcount_acquire(&vp->v_holdcnt);
3094 VNASSERT(vp->v_holdcnt == 0, vp,
3095 ("%s: wrong hold count", __func__));
3096 VNASSERT(vp->v_op != NULL, vp,
3097 ("%s: vnode already reclaimed.", __func__));
3099 * Remove a vnode from the free list, mark it as in use,
3100 * and put it on the active list.
3102 VNASSERT(vp->v_mount != NULL, vp,
3103 ("_vhold: vnode not on per mount vnode list"));
3105 mtx_lock(&mp->mnt_listmtx);
3106 if ((vp->v_mflag & VMP_TMPMNTFREELIST) != 0) {
3107 TAILQ_REMOVE(&mp->mnt_tmpfreevnodelist, vp, v_actfreelist);
3108 mp->mnt_tmpfreevnodelistsize--;
3109 vp->v_mflag &= ~VMP_TMPMNTFREELIST;
3111 mtx_lock(&vnode_free_list_mtx);
3112 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
3114 mtx_unlock(&vnode_free_list_mtx);
3116 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
3117 ("Activating already active vnode"));
3118 vp->v_iflag &= ~VI_FREE;
3119 vp->v_iflag |= VI_ACTIVE;
3120 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
3121 mp->mnt_activevnodelistsize++;
3122 mtx_unlock(&mp->mnt_listmtx);
3123 refcount_acquire(&vp->v_holdcnt);
3129 vholdnz(struct vnode *vp)
3132 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3134 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3135 VNASSERT(old > 0, vp, ("%s: wrong hold count", __func__));
3137 atomic_add_int(&vp->v_holdcnt, 1);
3142 * Drop the hold count of the vnode. If this is the last reference to
3143 * the vnode we place it on the free list unless it has been vgone'd
3144 * (marked VI_DOOMED) in which case we will free it.
3146 * Because the vnode vm object keeps a hold reference on the vnode if
3147 * there is at least one resident non-cached page, the vnode cannot
3148 * leave the active list without the page cleanup done.
3151 _vdrop(struct vnode *vp, bool locked)
3157 ASSERT_VI_LOCKED(vp, __func__);
3159 ASSERT_VI_UNLOCKED(vp, __func__);
3160 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3161 if (__predict_false((int)vp->v_holdcnt <= 0)) {
3162 vn_printf(vp, "vdrop: holdcnt %d", vp->v_holdcnt);
3163 panic("vdrop: wrong holdcnt");
3166 if (refcount_release_if_not_last(&vp->v_holdcnt))
3170 if (refcount_release(&vp->v_holdcnt) == 0) {
3174 if ((vp->v_iflag & VI_DOOMED) == 0) {
3176 * Mark a vnode as free: remove it from its active list
3177 * and put it up for recycling on the freelist.
3179 VNASSERT(vp->v_op != NULL, vp,
3180 ("vdropl: vnode already reclaimed."));
3181 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
3182 ("vnode already free"));
3183 VNASSERT(vp->v_holdcnt == 0, vp,
3184 ("vdropl: freeing when we shouldn't"));
3185 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3188 mtx_lock(&mp->mnt_listmtx);
3189 if (vp->v_iflag & VI_ACTIVE) {
3190 vp->v_iflag &= ~VI_ACTIVE;
3191 TAILQ_REMOVE(&mp->mnt_activevnodelist,
3193 mp->mnt_activevnodelistsize--;
3195 TAILQ_INSERT_TAIL(&mp->mnt_tmpfreevnodelist,
3197 mp->mnt_tmpfreevnodelistsize++;
3198 vp->v_iflag |= VI_FREE;
3199 vp->v_mflag |= VMP_TMPMNTFREELIST;
3201 if (mp->mnt_tmpfreevnodelistsize >=
3202 mnt_free_list_batch)
3203 vnlru_return_batch_locked(mp);
3204 mtx_unlock(&mp->mnt_listmtx);
3206 VNASSERT((vp->v_iflag & VI_ACTIVE) == 0, vp,
3207 ("vdropl: active vnode not on per mount "
3209 mtx_lock(&vnode_free_list_mtx);
3210 TAILQ_INSERT_TAIL(&vnode_free_list, vp,
3213 vp->v_iflag |= VI_FREE;
3215 mtx_unlock(&vnode_free_list_mtx);
3219 counter_u64_add(free_owe_inact, 1);
3224 * The vnode has been marked for destruction, so free it.
3226 * The vnode will be returned to the zone where it will
3227 * normally remain until it is needed for another vnode. We
3228 * need to cleanup (or verify that the cleanup has already
3229 * been done) any residual data left from its current use
3230 * so as not to contaminate the freshly allocated vnode.
3232 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
3233 atomic_subtract_long(&numvnodes, 1);
3235 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
3236 ("cleaned vnode still on the free list."));
3237 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
3238 VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
3239 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
3240 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
3241 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
3242 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
3243 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
3244 ("clean blk trie not empty"));
3245 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
3246 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
3247 ("dirty blk trie not empty"));
3248 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
3249 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
3250 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
3251 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
3252 ("Dangling rangelock waiters"));
3255 mac_vnode_destroy(vp);
3257 if (vp->v_pollinfo != NULL) {
3258 destroy_vpollinfo(vp->v_pollinfo);
3259 vp->v_pollinfo = NULL;
3262 /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
3265 vp->v_mountedhere = NULL;
3268 vp->v_fifoinfo = NULL;
3269 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
3273 uma_zfree(vnode_zone, vp);
3277 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3278 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3279 * OWEINACT tracks whether a vnode missed a call to inactive due to a
3280 * failed lock upgrade.
3283 vinactive(struct vnode *vp, struct thread *td)
3285 struct vm_object *obj;
3287 ASSERT_VOP_ELOCKED(vp, "vinactive");
3288 ASSERT_VI_LOCKED(vp, "vinactive");
3289 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3290 ("vinactive: recursed on VI_DOINGINACT"));
3291 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3292 vp->v_iflag |= VI_DOINGINACT;
3293 vp->v_iflag &= ~VI_OWEINACT;
3296 * Before moving off the active list, we must be sure that any
3297 * modified pages are converted into the vnode's dirty
3298 * buffers, since these will no longer be checked once the
3299 * vnode is on the inactive list.
3301 * The write-out of the dirty pages is asynchronous. At the
3302 * point that VOP_INACTIVE() is called, there could still be
3303 * pending I/O and dirty pages in the object.
3305 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3306 vm_object_mightbedirty(obj)) {
3307 VM_OBJECT_WLOCK(obj);
3308 vm_object_page_clean(obj, 0, 0, 0);
3309 VM_OBJECT_WUNLOCK(obj);
3311 VOP_INACTIVE(vp, td);
3313 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3314 ("vinactive: lost VI_DOINGINACT"));
3315 vp->v_iflag &= ~VI_DOINGINACT;
3319 * Remove any vnodes in the vnode table belonging to mount point mp.
3321 * If FORCECLOSE is not specified, there should not be any active ones,
3322 * return error if any are found (nb: this is a user error, not a
3323 * system error). If FORCECLOSE is specified, detach any active vnodes
3326 * If WRITECLOSE is set, only flush out regular file vnodes open for
3329 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3331 * `rootrefs' specifies the base reference count for the root vnode
3332 * of this filesystem. The root vnode is considered busy if its
3333 * v_usecount exceeds this value. On a successful return, vflush(, td)
3334 * will call vrele() on the root vnode exactly rootrefs times.
3335 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3339 static int busyprt = 0; /* print out busy vnodes */
3340 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3344 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3346 struct vnode *vp, *mvp, *rootvp = NULL;
3348 int busy = 0, error;
3350 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3353 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3354 ("vflush: bad args"));
3356 * Get the filesystem root vnode. We can vput() it
3357 * immediately, since with rootrefs > 0, it won't go away.
3359 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3360 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3367 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3369 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3372 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3376 * Skip over a vnodes marked VV_SYSTEM.
3378 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3384 * If WRITECLOSE is set, flush out unlinked but still open
3385 * files (even if open only for reading) and regular file
3386 * vnodes open for writing.
3388 if (flags & WRITECLOSE) {
3389 if (vp->v_object != NULL) {
3390 VM_OBJECT_WLOCK(vp->v_object);
3391 vm_object_page_clean(vp->v_object, 0, 0, 0);
3392 VM_OBJECT_WUNLOCK(vp->v_object);
3394 error = VOP_FSYNC(vp, MNT_WAIT, td);
3398 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3401 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3404 if ((vp->v_type == VNON ||
3405 (error == 0 && vattr.va_nlink > 0)) &&
3406 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3414 * With v_usecount == 0, all we need to do is clear out the
3415 * vnode data structures and we are done.
3417 * If FORCECLOSE is set, forcibly close the vnode.
3419 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3425 vn_printf(vp, "vflush: busy vnode ");
3431 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3433 * If just the root vnode is busy, and if its refcount
3434 * is equal to `rootrefs', then go ahead and kill it.
3437 KASSERT(busy > 0, ("vflush: not busy"));
3438 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3439 ("vflush: usecount %d < rootrefs %d",
3440 rootvp->v_usecount, rootrefs));
3441 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3442 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3444 VOP_UNLOCK(rootvp, 0);
3450 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3454 for (; rootrefs > 0; rootrefs--)
3460 * Recycle an unused vnode to the front of the free list.
3463 vrecycle(struct vnode *vp)
3468 recycled = vrecyclel(vp);
3474 * vrecycle, with the vp interlock held.
3477 vrecyclel(struct vnode *vp)
3481 ASSERT_VOP_ELOCKED(vp, __func__);
3482 ASSERT_VI_LOCKED(vp, __func__);
3483 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3485 if (vp->v_usecount == 0) {
3493 * Eliminate all activity associated with a vnode
3494 * in preparation for reuse.
3497 vgone(struct vnode *vp)
3505 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3506 struct vnode *lowervp __unused)
3511 * Notify upper mounts about reclaimed or unlinked vnode.
3514 vfs_notify_upper(struct vnode *vp, int event)
3516 static struct vfsops vgonel_vfsops = {
3517 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3518 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3520 struct mount *mp, *ump, *mmp;
3525 if (TAILQ_EMPTY(&mp->mnt_uppers))
3528 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3529 mmp->mnt_op = &vgonel_vfsops;
3530 mmp->mnt_kern_flag |= MNTK_MARKER;
3532 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3533 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3534 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3535 ump = TAILQ_NEXT(ump, mnt_upper_link);
3538 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3541 case VFS_NOTIFY_UPPER_RECLAIM:
3542 VFS_RECLAIM_LOWERVP(ump, vp);
3544 case VFS_NOTIFY_UPPER_UNLINK:
3545 VFS_UNLINK_LOWERVP(ump, vp);
3548 KASSERT(0, ("invalid event %d", event));
3552 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3553 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3556 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3557 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3558 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3559 wakeup(&mp->mnt_uppers);
3565 * vgone, with the vp interlock held.
3568 vgonel(struct vnode *vp)
3573 bool active, oweinact;
3575 ASSERT_VOP_ELOCKED(vp, "vgonel");
3576 ASSERT_VI_LOCKED(vp, "vgonel");
3577 VNASSERT(vp->v_holdcnt, vp,
3578 ("vgonel: vp %p has no reference.", vp));
3579 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3583 * Don't vgonel if we're already doomed.
3585 if (vp->v_iflag & VI_DOOMED)
3587 vp->v_iflag |= VI_DOOMED;
3590 * Check to see if the vnode is in use. If so, we have to call
3591 * VOP_CLOSE() and VOP_INACTIVE().
3593 active = vp->v_usecount > 0;
3594 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
3596 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
3599 * If purging an active vnode, it must be closed and
3600 * deactivated before being reclaimed.
3603 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
3604 if (oweinact || active) {
3606 if ((vp->v_iflag & VI_DOINGINACT) == 0)
3610 if (vp->v_type == VSOCK)
3611 vfs_unp_reclaim(vp);
3614 * Clean out any buffers associated with the vnode.
3615 * If the flush fails, just toss the buffers.
3618 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
3619 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
3620 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
3621 while (vinvalbuf(vp, 0, 0, 0) != 0)
3625 BO_LOCK(&vp->v_bufobj);
3626 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
3627 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
3628 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
3629 vp->v_bufobj.bo_clean.bv_cnt == 0,
3630 ("vp %p bufobj not invalidated", vp));
3633 * For VMIO bufobj, BO_DEAD is set later, or in
3634 * vm_object_terminate() after the object's page queue is
3637 object = vp->v_bufobj.bo_object;
3639 vp->v_bufobj.bo_flag |= BO_DEAD;
3640 BO_UNLOCK(&vp->v_bufobj);
3643 * Handle the VM part. Tmpfs handles v_object on its own (the
3644 * OBJT_VNODE check). Nullfs or other bypassing filesystems
3645 * should not touch the object borrowed from the lower vnode
3646 * (the handle check).
3648 if (object != NULL && object->type == OBJT_VNODE &&
3649 object->handle == vp)
3650 vnode_destroy_vobject(vp);
3653 * Reclaim the vnode.
3655 if (VOP_RECLAIM(vp, td))
3656 panic("vgone: cannot reclaim");
3658 vn_finished_secondary_write(mp);
3659 VNASSERT(vp->v_object == NULL, vp,
3660 ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
3662 * Clear the advisory locks and wake up waiting threads.
3664 (void)VOP_ADVLOCKPURGE(vp);
3667 * Delete from old mount point vnode list.
3672 * Done with purge, reset to the standard lock and invalidate
3676 vp->v_vnlock = &vp->v_lock;
3677 vp->v_op = &dead_vnodeops;
3683 * Calculate the total number of references to a special device.
3686 vcount(struct vnode *vp)
3691 count = vp->v_rdev->si_usecount;
3697 * Print out a description of a vnode.
3699 static char *typename[] =
3700 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
3704 vn_printf(struct vnode *vp, const char *fmt, ...)
3707 char buf[256], buf2[16];
3713 printf("%p: ", (void *)vp);
3714 printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
3715 printf(" usecount %d, writecount %d, refcount %d",
3716 vp->v_usecount, vp->v_writecount, vp->v_holdcnt);
3717 switch (vp->v_type) {
3719 printf(" mountedhere %p\n", vp->v_mountedhere);
3722 printf(" rdev %p\n", vp->v_rdev);
3725 printf(" socket %p\n", vp->v_unpcb);
3728 printf(" fifoinfo %p\n", vp->v_fifoinfo);
3736 if (vp->v_vflag & VV_ROOT)
3737 strlcat(buf, "|VV_ROOT", sizeof(buf));
3738 if (vp->v_vflag & VV_ISTTY)
3739 strlcat(buf, "|VV_ISTTY", sizeof(buf));
3740 if (vp->v_vflag & VV_NOSYNC)
3741 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
3742 if (vp->v_vflag & VV_ETERNALDEV)
3743 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
3744 if (vp->v_vflag & VV_CACHEDLABEL)
3745 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
3746 if (vp->v_vflag & VV_VMSIZEVNLOCK)
3747 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
3748 if (vp->v_vflag & VV_COPYONWRITE)
3749 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
3750 if (vp->v_vflag & VV_SYSTEM)
3751 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
3752 if (vp->v_vflag & VV_PROCDEP)
3753 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
3754 if (vp->v_vflag & VV_NOKNOTE)
3755 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
3756 if (vp->v_vflag & VV_DELETED)
3757 strlcat(buf, "|VV_DELETED", sizeof(buf));
3758 if (vp->v_vflag & VV_MD)
3759 strlcat(buf, "|VV_MD", sizeof(buf));
3760 if (vp->v_vflag & VV_FORCEINSMQ)
3761 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
3762 if (vp->v_vflag & VV_READLINK)
3763 strlcat(buf, "|VV_READLINK", sizeof(buf));
3764 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
3765 VV_CACHEDLABEL | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
3766 VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
3768 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
3769 strlcat(buf, buf2, sizeof(buf));
3771 if (vp->v_iflag & VI_TEXT_REF)
3772 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
3773 if (vp->v_iflag & VI_MOUNT)
3774 strlcat(buf, "|VI_MOUNT", sizeof(buf));
3775 if (vp->v_iflag & VI_DOOMED)
3776 strlcat(buf, "|VI_DOOMED", sizeof(buf));
3777 if (vp->v_iflag & VI_FREE)
3778 strlcat(buf, "|VI_FREE", sizeof(buf));
3779 if (vp->v_iflag & VI_ACTIVE)
3780 strlcat(buf, "|VI_ACTIVE", sizeof(buf));
3781 if (vp->v_iflag & VI_DOINGINACT)
3782 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
3783 if (vp->v_iflag & VI_OWEINACT)
3784 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
3785 flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOOMED | VI_FREE |
3786 VI_ACTIVE | VI_DOINGINACT | VI_OWEINACT);
3788 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
3789 strlcat(buf, buf2, sizeof(buf));
3791 if (vp->v_mflag & VMP_TMPMNTFREELIST)
3792 strlcat(buf, "|VMP_TMPMNTFREELIST", sizeof(buf));
3793 flags = vp->v_mflag & ~(VMP_TMPMNTFREELIST);
3795 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
3796 strlcat(buf, buf2, sizeof(buf));
3798 printf(" flags (%s)\n", buf + 1);
3799 if (mtx_owned(VI_MTX(vp)))
3800 printf(" VI_LOCKed");
3801 if (vp->v_object != NULL)
3802 printf(" v_object %p ref %d pages %d "
3803 "cleanbuf %d dirtybuf %d\n",
3804 vp->v_object, vp->v_object->ref_count,
3805 vp->v_object->resident_page_count,
3806 vp->v_bufobj.bo_clean.bv_cnt,
3807 vp->v_bufobj.bo_dirty.bv_cnt);
3809 lockmgr_printinfo(vp->v_vnlock);
3810 if (vp->v_data != NULL)
3816 * List all of the locked vnodes in the system.
3817 * Called when debugging the kernel.
3819 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
3825 * Note: because this is DDB, we can't obey the locking semantics
3826 * for these structures, which means we could catch an inconsistent
3827 * state and dereference a nasty pointer. Not much to be done
3830 db_printf("Locked vnodes\n");
3831 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3832 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3833 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
3834 vn_printf(vp, "vnode ");
3840 * Show details about the given vnode.
3842 DB_SHOW_COMMAND(vnode, db_show_vnode)
3848 vp = (struct vnode *)addr;
3849 vn_printf(vp, "vnode ");
3853 * Show details about the given mount point.
3855 DB_SHOW_COMMAND(mount, db_show_mount)
3866 /* No address given, print short info about all mount points. */
3867 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3868 db_printf("%p %s on %s (%s)\n", mp,
3869 mp->mnt_stat.f_mntfromname,
3870 mp->mnt_stat.f_mntonname,
3871 mp->mnt_stat.f_fstypename);
3875 db_printf("\nMore info: show mount <addr>\n");
3879 mp = (struct mount *)addr;
3880 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
3881 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
3884 mflags = mp->mnt_flag;
3885 #define MNT_FLAG(flag) do { \
3886 if (mflags & (flag)) { \
3887 if (buf[0] != '\0') \
3888 strlcat(buf, ", ", sizeof(buf)); \
3889 strlcat(buf, (#flag) + 4, sizeof(buf)); \
3890 mflags &= ~(flag); \
3893 MNT_FLAG(MNT_RDONLY);
3894 MNT_FLAG(MNT_SYNCHRONOUS);
3895 MNT_FLAG(MNT_NOEXEC);
3896 MNT_FLAG(MNT_NOSUID);
3897 MNT_FLAG(MNT_NFS4ACLS);
3898 MNT_FLAG(MNT_UNION);
3899 MNT_FLAG(MNT_ASYNC);
3900 MNT_FLAG(MNT_SUIDDIR);
3901 MNT_FLAG(MNT_SOFTDEP);
3902 MNT_FLAG(MNT_NOSYMFOLLOW);
3903 MNT_FLAG(MNT_GJOURNAL);
3904 MNT_FLAG(MNT_MULTILABEL);
3906 MNT_FLAG(MNT_NOATIME);
3907 MNT_FLAG(MNT_NOCLUSTERR);
3908 MNT_FLAG(MNT_NOCLUSTERW);
3910 MNT_FLAG(MNT_EXRDONLY);
3911 MNT_FLAG(MNT_EXPORTED);
3912 MNT_FLAG(MNT_DEFEXPORTED);
3913 MNT_FLAG(MNT_EXPORTANON);
3914 MNT_FLAG(MNT_EXKERB);
3915 MNT_FLAG(MNT_EXPUBLIC);
3916 MNT_FLAG(MNT_LOCAL);
3917 MNT_FLAG(MNT_QUOTA);
3918 MNT_FLAG(MNT_ROOTFS);
3920 MNT_FLAG(MNT_IGNORE);
3921 MNT_FLAG(MNT_UPDATE);
3922 MNT_FLAG(MNT_DELEXPORT);
3923 MNT_FLAG(MNT_RELOAD);
3924 MNT_FLAG(MNT_FORCE);
3925 MNT_FLAG(MNT_SNAPSHOT);
3926 MNT_FLAG(MNT_BYFSID);
3930 strlcat(buf, ", ", sizeof(buf));
3931 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3932 "0x%016jx", mflags);
3934 db_printf(" mnt_flag = %s\n", buf);
3937 flags = mp->mnt_kern_flag;
3938 #define MNT_KERN_FLAG(flag) do { \
3939 if (flags & (flag)) { \
3940 if (buf[0] != '\0') \
3941 strlcat(buf, ", ", sizeof(buf)); \
3942 strlcat(buf, (#flag) + 5, sizeof(buf)); \
3946 MNT_KERN_FLAG(MNTK_UNMOUNTF);
3947 MNT_KERN_FLAG(MNTK_ASYNC);
3948 MNT_KERN_FLAG(MNTK_SOFTDEP);
3949 MNT_KERN_FLAG(MNTK_DRAINING);
3950 MNT_KERN_FLAG(MNTK_REFEXPIRE);
3951 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
3952 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
3953 MNT_KERN_FLAG(MNTK_NO_IOPF);
3954 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
3955 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
3956 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
3957 MNT_KERN_FLAG(MNTK_MARKER);
3958 MNT_KERN_FLAG(MNTK_USES_BCACHE);
3959 MNT_KERN_FLAG(MNTK_NOASYNC);
3960 MNT_KERN_FLAG(MNTK_UNMOUNT);
3961 MNT_KERN_FLAG(MNTK_MWAIT);
3962 MNT_KERN_FLAG(MNTK_SUSPEND);
3963 MNT_KERN_FLAG(MNTK_SUSPEND2);
3964 MNT_KERN_FLAG(MNTK_SUSPENDED);
3965 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
3966 MNT_KERN_FLAG(MNTK_NOKNOTE);
3967 #undef MNT_KERN_FLAG
3970 strlcat(buf, ", ", sizeof(buf));
3971 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3974 db_printf(" mnt_kern_flag = %s\n", buf);
3976 db_printf(" mnt_opt = ");
3977 opt = TAILQ_FIRST(mp->mnt_opt);
3979 db_printf("%s", opt->name);
3980 opt = TAILQ_NEXT(opt, link);
3981 while (opt != NULL) {
3982 db_printf(", %s", opt->name);
3983 opt = TAILQ_NEXT(opt, link);
3989 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
3990 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
3991 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
3992 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
3993 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
3994 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
3995 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
3996 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
3997 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
3998 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
3999 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4000 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4002 db_printf(" mnt_cred = { uid=%u ruid=%u",
4003 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4004 if (jailed(mp->mnt_cred))
4005 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4007 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4008 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4009 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4010 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4011 db_printf(" mnt_activevnodelistsize = %d\n",
4012 mp->mnt_activevnodelistsize);
4013 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4014 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4015 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
4016 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4017 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4018 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4019 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4020 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4021 db_printf(" mnt_secondary_accwrites = %d\n",
4022 mp->mnt_secondary_accwrites);
4023 db_printf(" mnt_gjprovider = %s\n",
4024 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4025 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4027 db_printf("\n\nList of active vnodes\n");
4028 TAILQ_FOREACH(vp, &mp->mnt_activevnodelist, v_actfreelist) {
4029 if (vp->v_type != VMARKER) {
4030 vn_printf(vp, "vnode ");
4035 db_printf("\n\nList of inactive vnodes\n");
4036 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4037 if (vp->v_type != VMARKER && (vp->v_iflag & VI_ACTIVE) == 0) {
4038 vn_printf(vp, "vnode ");
4047 * Fill in a struct xvfsconf based on a struct vfsconf.
4050 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4052 struct xvfsconf xvfsp;
4054 bzero(&xvfsp, sizeof(xvfsp));
4055 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4056 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4057 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4058 xvfsp.vfc_flags = vfsp->vfc_flags;
4060 * These are unused in userland, we keep them
4061 * to not break binary compatibility.
4063 xvfsp.vfc_vfsops = NULL;
4064 xvfsp.vfc_next = NULL;
4065 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4068 #ifdef COMPAT_FREEBSD32
4070 uint32_t vfc_vfsops;
4071 char vfc_name[MFSNAMELEN];
4072 int32_t vfc_typenum;
4073 int32_t vfc_refcount;
4079 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4081 struct xvfsconf32 xvfsp;
4083 bzero(&xvfsp, sizeof(xvfsp));
4084 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4085 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4086 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4087 xvfsp.vfc_flags = vfsp->vfc_flags;
4088 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4093 * Top level filesystem related information gathering.
4096 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4098 struct vfsconf *vfsp;
4103 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4104 #ifdef COMPAT_FREEBSD32
4105 if (req->flags & SCTL_MASK32)
4106 error = vfsconf2x32(req, vfsp);
4109 error = vfsconf2x(req, vfsp);
4117 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4118 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4119 "S,xvfsconf", "List of all configured filesystems");
4121 #ifndef BURN_BRIDGES
4122 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4125 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4127 int *name = (int *)arg1 - 1; /* XXX */
4128 u_int namelen = arg2 + 1; /* XXX */
4129 struct vfsconf *vfsp;
4131 log(LOG_WARNING, "userland calling deprecated sysctl, "
4132 "please rebuild world\n");
4134 #if 1 || defined(COMPAT_PRELITE2)
4135 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4137 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4141 case VFS_MAXTYPENUM:
4144 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4147 return (ENOTDIR); /* overloaded */
4149 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4150 if (vfsp->vfc_typenum == name[2])
4155 return (EOPNOTSUPP);
4156 #ifdef COMPAT_FREEBSD32
4157 if (req->flags & SCTL_MASK32)
4158 return (vfsconf2x32(req, vfsp));
4161 return (vfsconf2x(req, vfsp));
4163 return (EOPNOTSUPP);
4166 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4167 CTLFLAG_MPSAFE, vfs_sysctl,
4168 "Generic filesystem");
4170 #if 1 || defined(COMPAT_PRELITE2)
4173 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4176 struct vfsconf *vfsp;
4177 struct ovfsconf ovfs;
4180 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4181 bzero(&ovfs, sizeof(ovfs));
4182 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4183 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4184 ovfs.vfc_index = vfsp->vfc_typenum;
4185 ovfs.vfc_refcount = vfsp->vfc_refcount;
4186 ovfs.vfc_flags = vfsp->vfc_flags;
4187 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4197 #endif /* 1 || COMPAT_PRELITE2 */
4198 #endif /* !BURN_BRIDGES */
4200 #define KINFO_VNODESLOP 10
4203 * Dump vnode list (via sysctl).
4207 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4215 * Stale numvnodes access is not fatal here.
4218 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4220 /* Make an estimate */
4221 return (SYSCTL_OUT(req, 0, len));
4223 error = sysctl_wire_old_buffer(req, 0);
4226 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4228 mtx_lock(&mountlist_mtx);
4229 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4230 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4233 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4237 xvn[n].xv_size = sizeof *xvn;
4238 xvn[n].xv_vnode = vp;
4239 xvn[n].xv_id = 0; /* XXX compat */
4240 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4242 XV_COPY(writecount);
4248 xvn[n].xv_flag = vp->v_vflag;
4250 switch (vp->v_type) {
4257 if (vp->v_rdev == NULL) {
4261 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4264 xvn[n].xv_socket = vp->v_socket;
4267 xvn[n].xv_fifo = vp->v_fifoinfo;
4272 /* shouldn't happen? */
4280 mtx_lock(&mountlist_mtx);
4285 mtx_unlock(&mountlist_mtx);
4287 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4292 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4293 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4298 unmount_or_warn(struct mount *mp)
4302 error = dounmount(mp, MNT_FORCE, curthread);
4304 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4308 printf("%d)\n", error);
4313 * Unmount all filesystems. The list is traversed in reverse order
4314 * of mounting to avoid dependencies.
4317 vfs_unmountall(void)
4319 struct mount *mp, *tmp;
4321 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4324 * Since this only runs when rebooting, it is not interlocked.
4326 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4330 * Forcibly unmounting "/dev" before "/" would prevent clean
4331 * unmount of the latter.
4333 if (mp == rootdevmp)
4336 unmount_or_warn(mp);
4339 if (rootdevmp != NULL)
4340 unmount_or_warn(rootdevmp);
4344 * perform msync on all vnodes under a mount point
4345 * the mount point must be locked.
4348 vfs_msync(struct mount *mp, int flags)
4350 struct vnode *vp, *mvp;
4351 struct vm_object *obj;
4353 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4355 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4358 MNT_VNODE_FOREACH_ACTIVE(vp, mp, mvp) {
4360 if (obj != NULL && vm_object_mightbedirty(obj) &&
4361 (flags == MNT_WAIT || VOP_ISLOCKED(vp) == 0)) {
4363 LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
4365 if (vp->v_vflag & VV_NOSYNC) { /* unlinked */
4372 VM_OBJECT_WLOCK(obj);
4373 vm_object_page_clean(obj, 0, 0,
4375 OBJPC_SYNC : OBJPC_NOSYNC);
4376 VM_OBJECT_WUNLOCK(obj);
4386 destroy_vpollinfo_free(struct vpollinfo *vi)
4389 knlist_destroy(&vi->vpi_selinfo.si_note);
4390 mtx_destroy(&vi->vpi_lock);
4391 uma_zfree(vnodepoll_zone, vi);
4395 destroy_vpollinfo(struct vpollinfo *vi)
4398 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4399 seldrain(&vi->vpi_selinfo);
4400 destroy_vpollinfo_free(vi);
4404 * Initialize per-vnode helper structure to hold poll-related state.
4407 v_addpollinfo(struct vnode *vp)
4409 struct vpollinfo *vi;
4411 if (vp->v_pollinfo != NULL)
4413 vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4414 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4415 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4416 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4418 if (vp->v_pollinfo != NULL) {
4420 destroy_vpollinfo_free(vi);
4423 vp->v_pollinfo = vi;
4428 * Record a process's interest in events which might happen to
4429 * a vnode. Because poll uses the historic select-style interface
4430 * internally, this routine serves as both the ``check for any
4431 * pending events'' and the ``record my interest in future events''
4432 * functions. (These are done together, while the lock is held,
4433 * to avoid race conditions.)
4436 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4440 mtx_lock(&vp->v_pollinfo->vpi_lock);
4441 if (vp->v_pollinfo->vpi_revents & events) {
4443 * This leaves events we are not interested
4444 * in available for the other process which
4445 * which presumably had requested them
4446 * (otherwise they would never have been
4449 events &= vp->v_pollinfo->vpi_revents;
4450 vp->v_pollinfo->vpi_revents &= ~events;
4452 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4455 vp->v_pollinfo->vpi_events |= events;
4456 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4457 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4462 * Routine to create and manage a filesystem syncer vnode.
4464 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4465 static int sync_fsync(struct vop_fsync_args *);
4466 static int sync_inactive(struct vop_inactive_args *);
4467 static int sync_reclaim(struct vop_reclaim_args *);
4469 static struct vop_vector sync_vnodeops = {
4470 .vop_bypass = VOP_EOPNOTSUPP,
4471 .vop_close = sync_close, /* close */
4472 .vop_fsync = sync_fsync, /* fsync */
4473 .vop_inactive = sync_inactive, /* inactive */
4474 .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
4475 .vop_reclaim = sync_reclaim, /* reclaim */
4476 .vop_lock1 = vop_stdlock, /* lock */
4477 .vop_unlock = vop_stdunlock, /* unlock */
4478 .vop_islocked = vop_stdislocked, /* islocked */
4482 * Create a new filesystem syncer vnode for the specified mount point.
4485 vfs_allocate_syncvnode(struct mount *mp)
4489 static long start, incr, next;
4492 /* Allocate a new vnode */
4493 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
4495 panic("vfs_allocate_syncvnode: getnewvnode() failed");
4497 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4498 vp->v_vflag |= VV_FORCEINSMQ;
4499 error = insmntque(vp, mp);
4501 panic("vfs_allocate_syncvnode: insmntque() failed");
4502 vp->v_vflag &= ~VV_FORCEINSMQ;
4505 * Place the vnode onto the syncer worklist. We attempt to
4506 * scatter them about on the list so that they will go off
4507 * at evenly distributed times even if all the filesystems
4508 * are mounted at once.
4511 if (next == 0 || next > syncer_maxdelay) {
4515 start = syncer_maxdelay / 2;
4516 incr = syncer_maxdelay;
4522 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
4523 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
4524 mtx_lock(&sync_mtx);
4526 if (mp->mnt_syncer == NULL) {
4527 mp->mnt_syncer = vp;
4530 mtx_unlock(&sync_mtx);
4533 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4540 vfs_deallocate_syncvnode(struct mount *mp)
4544 mtx_lock(&sync_mtx);
4545 vp = mp->mnt_syncer;
4547 mp->mnt_syncer = NULL;
4548 mtx_unlock(&sync_mtx);
4554 * Do a lazy sync of the filesystem.
4557 sync_fsync(struct vop_fsync_args *ap)
4559 struct vnode *syncvp = ap->a_vp;
4560 struct mount *mp = syncvp->v_mount;
4565 * We only need to do something if this is a lazy evaluation.
4567 if (ap->a_waitfor != MNT_LAZY)
4571 * Move ourselves to the back of the sync list.
4573 bo = &syncvp->v_bufobj;
4575 vn_syncer_add_to_worklist(bo, syncdelay);
4579 * Walk the list of vnodes pushing all that are dirty and
4580 * not already on the sync list.
4582 if (vfs_busy(mp, MBF_NOWAIT) != 0)
4584 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
4588 save = curthread_pflags_set(TDP_SYNCIO);
4590 * The filesystem at hand may be idle with free vnodes stored in the
4591 * batch. Return them instead of letting them stay there indefinitely.
4593 vnlru_return_batch(mp);
4594 vfs_msync(mp, MNT_NOWAIT);
4595 error = VFS_SYNC(mp, MNT_LAZY);
4596 curthread_pflags_restore(save);
4597 vn_finished_write(mp);
4603 * The syncer vnode is no referenced.
4606 sync_inactive(struct vop_inactive_args *ap)
4614 * The syncer vnode is no longer needed and is being decommissioned.
4616 * Modifications to the worklist must be protected by sync_mtx.
4619 sync_reclaim(struct vop_reclaim_args *ap)
4621 struct vnode *vp = ap->a_vp;
4626 mtx_lock(&sync_mtx);
4627 if (vp->v_mount->mnt_syncer == vp)
4628 vp->v_mount->mnt_syncer = NULL;
4629 if (bo->bo_flag & BO_ONWORKLST) {
4630 LIST_REMOVE(bo, bo_synclist);
4631 syncer_worklist_len--;
4633 bo->bo_flag &= ~BO_ONWORKLST;
4635 mtx_unlock(&sync_mtx);
4642 vn_need_pageq_flush(struct vnode *vp)
4644 struct vm_object *obj;
4647 MPASS(mtx_owned(VI_MTX(vp)));
4649 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
4650 vm_object_mightbedirty(obj))
4656 * Check if vnode represents a disk device
4659 vn_isdisk(struct vnode *vp, int *errp)
4663 if (vp->v_type != VCHR) {
4669 if (vp->v_rdev == NULL)
4671 else if (vp->v_rdev->si_devsw == NULL)
4673 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
4679 return (error == 0);
4683 * Common filesystem object access control check routine. Accepts a
4684 * vnode's type, "mode", uid and gid, requested access mode, credentials,
4685 * and optional call-by-reference privused argument allowing vaccess()
4686 * to indicate to the caller whether privilege was used to satisfy the
4687 * request (obsoleted). Returns 0 on success, or an errno on failure.
4690 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
4691 accmode_t accmode, struct ucred *cred, int *privused)
4693 accmode_t dac_granted;
4694 accmode_t priv_granted;
4696 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
4697 ("invalid bit in accmode"));
4698 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
4699 ("VAPPEND without VWRITE"));
4702 * Look for a normal, non-privileged way to access the file/directory
4703 * as requested. If it exists, go with that.
4706 if (privused != NULL)
4711 /* Check the owner. */
4712 if (cred->cr_uid == file_uid) {
4713 dac_granted |= VADMIN;
4714 if (file_mode & S_IXUSR)
4715 dac_granted |= VEXEC;
4716 if (file_mode & S_IRUSR)
4717 dac_granted |= VREAD;
4718 if (file_mode & S_IWUSR)
4719 dac_granted |= (VWRITE | VAPPEND);
4721 if ((accmode & dac_granted) == accmode)
4727 /* Otherwise, check the groups (first match) */
4728 if (groupmember(file_gid, cred)) {
4729 if (file_mode & S_IXGRP)
4730 dac_granted |= VEXEC;
4731 if (file_mode & S_IRGRP)
4732 dac_granted |= VREAD;
4733 if (file_mode & S_IWGRP)
4734 dac_granted |= (VWRITE | VAPPEND);
4736 if ((accmode & dac_granted) == accmode)
4742 /* Otherwise, check everyone else. */
4743 if (file_mode & S_IXOTH)
4744 dac_granted |= VEXEC;
4745 if (file_mode & S_IROTH)
4746 dac_granted |= VREAD;
4747 if (file_mode & S_IWOTH)
4748 dac_granted |= (VWRITE | VAPPEND);
4749 if ((accmode & dac_granted) == accmode)
4754 * Build a privilege mask to determine if the set of privileges
4755 * satisfies the requirements when combined with the granted mask
4756 * from above. For each privilege, if the privilege is required,
4757 * bitwise or the request type onto the priv_granted mask.
4763 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
4764 * requests, instead of PRIV_VFS_EXEC.
4766 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4767 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
4768 priv_granted |= VEXEC;
4771 * Ensure that at least one execute bit is on. Otherwise,
4772 * a privileged user will always succeed, and we don't want
4773 * this to happen unless the file really is executable.
4775 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4776 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
4777 !priv_check_cred(cred, PRIV_VFS_EXEC))
4778 priv_granted |= VEXEC;
4781 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
4782 !priv_check_cred(cred, PRIV_VFS_READ))
4783 priv_granted |= VREAD;
4785 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
4786 !priv_check_cred(cred, PRIV_VFS_WRITE))
4787 priv_granted |= (VWRITE | VAPPEND);
4789 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
4790 !priv_check_cred(cred, PRIV_VFS_ADMIN))
4791 priv_granted |= VADMIN;
4793 if ((accmode & (priv_granted | dac_granted)) == accmode) {
4794 /* XXX audit: privilege used */
4795 if (privused != NULL)
4800 return ((accmode & VADMIN) ? EPERM : EACCES);
4804 * Credential check based on process requesting service, and per-attribute
4808 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
4809 struct thread *td, accmode_t accmode)
4813 * Kernel-invoked always succeeds.
4819 * Do not allow privileged processes in jail to directly manipulate
4820 * system attributes.
4822 switch (attrnamespace) {
4823 case EXTATTR_NAMESPACE_SYSTEM:
4824 /* Potentially should be: return (EPERM); */
4825 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
4826 case EXTATTR_NAMESPACE_USER:
4827 return (VOP_ACCESS(vp, accmode, cred, td));
4833 #ifdef DEBUG_VFS_LOCKS
4835 * This only exists to suppress warnings from unlocked specfs accesses. It is
4836 * no longer ok to have an unlocked VFS.
4838 #define IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL || \
4839 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
4841 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
4842 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
4843 "Drop into debugger on lock violation");
4845 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
4846 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
4847 0, "Check for interlock across VOPs");
4849 int vfs_badlock_print = 1; /* Print lock violations. */
4850 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
4851 0, "Print lock violations");
4853 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
4854 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
4855 0, "Print vnode details on lock violations");
4858 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
4859 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
4860 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
4864 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
4868 if (vfs_badlock_backtrace)
4871 if (vfs_badlock_vnode)
4872 vn_printf(vp, "vnode ");
4873 if (vfs_badlock_print)
4874 printf("%s: %p %s\n", str, (void *)vp, msg);
4875 if (vfs_badlock_ddb)
4876 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4880 assert_vi_locked(struct vnode *vp, const char *str)
4883 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
4884 vfs_badlock("interlock is not locked but should be", str, vp);
4888 assert_vi_unlocked(struct vnode *vp, const char *str)
4891 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
4892 vfs_badlock("interlock is locked but should not be", str, vp);
4896 assert_vop_locked(struct vnode *vp, const char *str)
4900 if (!IGNORE_LOCK(vp)) {
4901 locked = VOP_ISLOCKED(vp);
4902 if (locked == 0 || locked == LK_EXCLOTHER)
4903 vfs_badlock("is not locked but should be", str, vp);
4908 assert_vop_unlocked(struct vnode *vp, const char *str)
4911 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
4912 vfs_badlock("is locked but should not be", str, vp);
4916 assert_vop_elocked(struct vnode *vp, const char *str)
4919 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
4920 vfs_badlock("is not exclusive locked but should be", str, vp);
4922 #endif /* DEBUG_VFS_LOCKS */
4925 vop_rename_fail(struct vop_rename_args *ap)
4928 if (ap->a_tvp != NULL)
4930 if (ap->a_tdvp == ap->a_tvp)
4939 vop_rename_pre(void *ap)
4941 struct vop_rename_args *a = ap;
4943 #ifdef DEBUG_VFS_LOCKS
4945 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
4946 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
4947 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
4948 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
4950 /* Check the source (from). */
4951 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
4952 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
4953 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
4954 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
4955 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
4957 /* Check the target. */
4959 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
4960 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
4962 if (a->a_tdvp != a->a_fdvp)
4964 if (a->a_tvp != a->a_fvp)
4971 #ifdef DEBUG_VFS_LOCKS
4973 vop_strategy_pre(void *ap)
4975 struct vop_strategy_args *a;
4982 * Cluster ops lock their component buffers but not the IO container.
4984 if ((bp->b_flags & B_CLUSTER) != 0)
4987 if (panicstr == NULL && !BUF_ISLOCKED(bp)) {
4988 if (vfs_badlock_print)
4990 "VOP_STRATEGY: bp is not locked but should be\n");
4991 if (vfs_badlock_ddb)
4992 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4997 vop_lock_pre(void *ap)
4999 struct vop_lock1_args *a = ap;
5001 if ((a->a_flags & LK_INTERLOCK) == 0)
5002 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5004 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5008 vop_lock_post(void *ap, int rc)
5010 struct vop_lock1_args *a = ap;
5012 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5013 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5014 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5018 vop_unlock_pre(void *ap)
5020 struct vop_unlock_args *a = ap;
5022 if (a->a_flags & LK_INTERLOCK)
5023 ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
5024 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5028 vop_unlock_post(void *ap, int rc)
5030 struct vop_unlock_args *a = ap;
5032 if (a->a_flags & LK_INTERLOCK)
5033 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
5037 vop_need_inactive_pre(void *ap)
5039 struct vop_need_inactive_args *a = ap;
5041 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5045 vop_need_inactive_post(void *ap, int rc)
5047 struct vop_need_inactive_args *a = ap;
5049 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5054 vop_create_post(void *ap, int rc)
5056 struct vop_create_args *a = ap;
5059 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5063 vop_deleteextattr_post(void *ap, int rc)
5065 struct vop_deleteextattr_args *a = ap;
5068 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5072 vop_link_post(void *ap, int rc)
5074 struct vop_link_args *a = ap;
5077 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
5078 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
5083 vop_mkdir_post(void *ap, int rc)
5085 struct vop_mkdir_args *a = ap;
5088 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5092 vop_mknod_post(void *ap, int rc)
5094 struct vop_mknod_args *a = ap;
5097 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5101 vop_reclaim_post(void *ap, int rc)
5103 struct vop_reclaim_args *a = ap;
5106 VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
5110 vop_remove_post(void *ap, int rc)
5112 struct vop_remove_args *a = ap;
5115 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5116 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5121 vop_rename_post(void *ap, int rc)
5123 struct vop_rename_args *a = ap;
5128 if (a->a_fdvp == a->a_tdvp) {
5129 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5131 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5132 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5134 hint |= NOTE_EXTEND;
5135 if (a->a_fvp->v_type == VDIR)
5137 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5139 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5140 a->a_tvp->v_type == VDIR)
5142 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5145 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5147 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5149 if (a->a_tdvp != a->a_fdvp)
5151 if (a->a_tvp != a->a_fvp)
5159 vop_rmdir_post(void *ap, int rc)
5161 struct vop_rmdir_args *a = ap;
5164 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5165 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5170 vop_setattr_post(void *ap, int rc)
5172 struct vop_setattr_args *a = ap;
5175 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5179 vop_setextattr_post(void *ap, int rc)
5181 struct vop_setextattr_args *a = ap;
5184 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5188 vop_symlink_post(void *ap, int rc)
5190 struct vop_symlink_args *a = ap;
5193 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5197 vop_open_post(void *ap, int rc)
5199 struct vop_open_args *a = ap;
5202 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
5206 vop_close_post(void *ap, int rc)
5208 struct vop_close_args *a = ap;
5210 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
5211 (a->a_vp->v_iflag & VI_DOOMED) == 0)) {
5212 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
5213 NOTE_CLOSE_WRITE : NOTE_CLOSE);
5218 vop_read_post(void *ap, int rc)
5220 struct vop_read_args *a = ap;
5223 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5227 vop_readdir_post(void *ap, int rc)
5229 struct vop_readdir_args *a = ap;
5232 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5235 static struct knlist fs_knlist;
5238 vfs_event_init(void *arg)
5240 knlist_init_mtx(&fs_knlist, NULL);
5242 /* XXX - correct order? */
5243 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
5246 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
5249 KNOTE_UNLOCKED(&fs_knlist, event);
5252 static int filt_fsattach(struct knote *kn);
5253 static void filt_fsdetach(struct knote *kn);
5254 static int filt_fsevent(struct knote *kn, long hint);
5256 struct filterops fs_filtops = {
5258 .f_attach = filt_fsattach,
5259 .f_detach = filt_fsdetach,
5260 .f_event = filt_fsevent
5264 filt_fsattach(struct knote *kn)
5267 kn->kn_flags |= EV_CLEAR;
5268 knlist_add(&fs_knlist, kn, 0);
5273 filt_fsdetach(struct knote *kn)
5276 knlist_remove(&fs_knlist, kn, 0);
5280 filt_fsevent(struct knote *kn, long hint)
5283 kn->kn_fflags |= hint;
5284 return (kn->kn_fflags != 0);
5288 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
5294 error = SYSCTL_IN(req, &vc, sizeof(vc));
5297 if (vc.vc_vers != VFS_CTL_VERS1)
5299 mp = vfs_getvfs(&vc.vc_fsid);
5302 /* ensure that a specific sysctl goes to the right filesystem. */
5303 if (strcmp(vc.vc_fstypename, "*") != 0 &&
5304 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
5308 VCTLTOREQ(&vc, req);
5309 error = VFS_SYSCTL(mp, vc.vc_op, req);
5314 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_WR,
5315 NULL, 0, sysctl_vfs_ctl, "",
5319 * Function to initialize a va_filerev field sensibly.
5320 * XXX: Wouldn't a random number make a lot more sense ??
5323 init_va_filerev(void)
5328 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
5331 static int filt_vfsread(struct knote *kn, long hint);
5332 static int filt_vfswrite(struct knote *kn, long hint);
5333 static int filt_vfsvnode(struct knote *kn, long hint);
5334 static void filt_vfsdetach(struct knote *kn);
5335 static struct filterops vfsread_filtops = {
5337 .f_detach = filt_vfsdetach,
5338 .f_event = filt_vfsread
5340 static struct filterops vfswrite_filtops = {
5342 .f_detach = filt_vfsdetach,
5343 .f_event = filt_vfswrite
5345 static struct filterops vfsvnode_filtops = {
5347 .f_detach = filt_vfsdetach,
5348 .f_event = filt_vfsvnode
5352 vfs_knllock(void *arg)
5354 struct vnode *vp = arg;
5356 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5360 vfs_knlunlock(void *arg)
5362 struct vnode *vp = arg;
5368 vfs_knl_assert_locked(void *arg)
5370 #ifdef DEBUG_VFS_LOCKS
5371 struct vnode *vp = arg;
5373 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
5378 vfs_knl_assert_unlocked(void *arg)
5380 #ifdef DEBUG_VFS_LOCKS
5381 struct vnode *vp = arg;
5383 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
5388 vfs_kqfilter(struct vop_kqfilter_args *ap)
5390 struct vnode *vp = ap->a_vp;
5391 struct knote *kn = ap->a_kn;
5394 switch (kn->kn_filter) {
5396 kn->kn_fop = &vfsread_filtops;
5399 kn->kn_fop = &vfswrite_filtops;
5402 kn->kn_fop = &vfsvnode_filtops;
5408 kn->kn_hook = (caddr_t)vp;
5411 if (vp->v_pollinfo == NULL)
5413 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5415 knlist_add(knl, kn, 0);
5421 * Detach knote from vnode
5424 filt_vfsdetach(struct knote *kn)
5426 struct vnode *vp = (struct vnode *)kn->kn_hook;
5428 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
5429 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
5435 filt_vfsread(struct knote *kn, long hint)
5437 struct vnode *vp = (struct vnode *)kn->kn_hook;
5442 * filesystem is gone, so set the EOF flag and schedule
5443 * the knote for deletion.
5445 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5447 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5452 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
5456 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
5457 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
5464 filt_vfswrite(struct knote *kn, long hint)
5466 struct vnode *vp = (struct vnode *)kn->kn_hook;
5471 * filesystem is gone, so set the EOF flag and schedule
5472 * the knote for deletion.
5474 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
5475 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5483 filt_vfsvnode(struct knote *kn, long hint)
5485 struct vnode *vp = (struct vnode *)kn->kn_hook;
5489 if (kn->kn_sfflags & hint)
5490 kn->kn_fflags |= hint;
5491 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5492 kn->kn_flags |= EV_EOF;
5496 res = (kn->kn_fflags != 0);
5502 * Returns whether the directory is empty or not.
5503 * If it is empty, the return value is 0; otherwise
5504 * the return value is an error value (which may
5508 vfs_emptydir(struct vnode *vp)
5512 struct dirent *dirent, *dp, *endp;
5518 ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
5520 dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
5521 iov.iov_base = dirent;
5522 iov.iov_len = sizeof(struct dirent);
5527 uio.uio_resid = sizeof(struct dirent);
5528 uio.uio_segflg = UIO_SYSSPACE;
5529 uio.uio_rw = UIO_READ;
5530 uio.uio_td = curthread;
5532 while (eof == 0 && error == 0) {
5533 error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
5537 endp = (void *)((uint8_t *)dirent +
5538 sizeof(struct dirent) - uio.uio_resid);
5539 for (dp = dirent; dp < endp;
5540 dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
5541 if (dp->d_type == DT_WHT)
5543 if (dp->d_namlen == 0)
5545 if (dp->d_type != DT_DIR &&
5546 dp->d_type != DT_UNKNOWN) {
5550 if (dp->d_namlen > 2) {
5554 if (dp->d_namlen == 1 &&
5555 dp->d_name[0] != '.') {
5559 if (dp->d_namlen == 2 &&
5560 dp->d_name[1] != '.') {
5564 uio.uio_resid = sizeof(struct dirent);
5567 free(dirent, M_TEMP);
5572 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
5576 if (dp->d_reclen > ap->a_uio->uio_resid)
5577 return (ENAMETOOLONG);
5578 error = uiomove(dp, dp->d_reclen, ap->a_uio);
5580 if (ap->a_ncookies != NULL) {
5581 if (ap->a_cookies != NULL)
5582 free(ap->a_cookies, M_TEMP);
5583 ap->a_cookies = NULL;
5584 *ap->a_ncookies = 0;
5588 if (ap->a_ncookies == NULL)
5591 KASSERT(ap->a_cookies,
5592 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
5594 *ap->a_cookies = realloc(*ap->a_cookies,
5595 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
5596 (*ap->a_cookies)[*ap->a_ncookies] = off;
5597 *ap->a_ncookies += 1;
5602 * Mark for update the access time of the file if the filesystem
5603 * supports VOP_MARKATIME. This functionality is used by execve and
5604 * mmap, so we want to avoid the I/O implied by directly setting
5605 * va_atime for the sake of efficiency.
5608 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
5613 ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
5614 if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
5615 (void)VOP_MARKATIME(vp);
5619 * The purpose of this routine is to remove granularity from accmode_t,
5620 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
5621 * VADMIN and VAPPEND.
5623 * If it returns 0, the caller is supposed to continue with the usual
5624 * access checks using 'accmode' as modified by this routine. If it
5625 * returns nonzero value, the caller is supposed to return that value
5628 * Note that after this routine runs, accmode may be zero.
5631 vfs_unixify_accmode(accmode_t *accmode)
5634 * There is no way to specify explicit "deny" rule using
5635 * file mode or POSIX.1e ACLs.
5637 if (*accmode & VEXPLICIT_DENY) {
5643 * None of these can be translated into usual access bits.
5644 * Also, the common case for NFSv4 ACLs is to not contain
5645 * either of these bits. Caller should check for VWRITE
5646 * on the containing directory instead.
5648 if (*accmode & (VDELETE_CHILD | VDELETE))
5651 if (*accmode & VADMIN_PERMS) {
5652 *accmode &= ~VADMIN_PERMS;
5657 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
5658 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
5660 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
5666 * Clear out a doomed vnode (if any) and replace it with a new one as long
5667 * as the fs is not being unmounted. Return the root vnode to the caller.
5669 static int __noinline
5670 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
5676 if (mp->mnt_rootvnode != NULL) {
5678 vp = mp->mnt_rootvnode;
5680 if ((vp->v_iflag & VI_DOOMED) == 0) {
5683 error = vn_lock(vp, flags);
5692 * Clear the old one.
5694 mp->mnt_rootvnode = NULL;
5699 * Paired with a fence in vfs_op_thread_exit().
5701 atomic_thread_fence_acq();
5702 vfs_op_barrier_wait(mp);
5706 error = VFS_CACHEDROOT(mp, flags, vpp);
5709 if (mp->mnt_vfs_ops == 0) {
5711 if (mp->mnt_vfs_ops != 0) {
5715 if (mp->mnt_rootvnode == NULL) {
5717 mp->mnt_rootvnode = *vpp;
5719 if (mp->mnt_rootvnode != *vpp) {
5720 if ((mp->mnt_rootvnode->v_iflag & VI_DOOMED) == 0) {
5721 panic("%s: mismatch between vnode returned "
5722 " by VFS_CACHEDROOT and the one cached "
5724 __func__, *vpp, mp->mnt_rootvnode);
5734 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
5739 if (!vfs_op_thread_enter(mp))
5740 return (vfs_cache_root_fallback(mp, flags, vpp));
5741 vp = (struct vnode *)atomic_load_ptr(&mp->mnt_rootvnode);
5742 if (vp == NULL || (vp->v_iflag & VI_DOOMED)) {
5743 vfs_op_thread_exit(mp);
5744 return (vfs_cache_root_fallback(mp, flags, vpp));
5747 vfs_op_thread_exit(mp);
5748 error = vn_lock(vp, flags);
5751 return (vfs_cache_root_fallback(mp, flags, vpp));
5758 vfs_cache_root_clear(struct mount *mp)
5763 * ops > 0 guarantees there is nobody who can see this vnode
5765 MPASS(mp->mnt_vfs_ops > 0);
5766 vp = mp->mnt_rootvnode;
5767 mp->mnt_rootvnode = NULL;
5772 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
5775 MPASS(mp->mnt_vfs_ops > 0);
5777 mp->mnt_rootvnode = vp;
5781 * These are helper functions for filesystems to traverse all
5782 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
5784 * This interface replaces MNT_VNODE_FOREACH.
5787 MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
5790 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
5795 kern_yield(PRI_USER);
5797 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5798 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
5799 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
5800 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
5801 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
5804 if ((vp->v_iflag & VI_DOOMED) != 0) {
5811 __mnt_vnode_markerfree_all(mvp, mp);
5812 /* MNT_IUNLOCK(mp); -- done in above function */
5813 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
5816 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5817 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5823 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
5827 *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
5830 (*mvp)->v_mount = mp;
5831 (*mvp)->v_type = VMARKER;
5833 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
5834 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
5835 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
5838 if ((vp->v_iflag & VI_DOOMED) != 0) {
5847 free(*mvp, M_VNODE_MARKER);
5851 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5857 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
5865 mtx_assert(MNT_MTX(mp), MA_OWNED);
5867 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5868 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5871 free(*mvp, M_VNODE_MARKER);
5876 * These are helper functions for filesystems to traverse their
5877 * active vnodes. See MNT_VNODE_FOREACH_ACTIVE() in sys/mount.h
5880 mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
5883 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5888 free(*mvp, M_VNODE_MARKER);
5893 * Relock the mp mount vnode list lock with the vp vnode interlock in the
5894 * conventional lock order during mnt_vnode_next_active iteration.
5896 * On entry, the mount vnode list lock is held and the vnode interlock is not.
5897 * The list lock is dropped and reacquired. On success, both locks are held.
5898 * On failure, the mount vnode list lock is held but the vnode interlock is
5899 * not, and the procedure may have yielded.
5902 mnt_vnode_next_active_relock(struct vnode *mvp, struct mount *mp,
5905 const struct vnode *tmp;
5908 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
5909 TAILQ_NEXT(mvp, v_actfreelist) != NULL, mvp,
5910 ("%s: bad marker", __func__));
5911 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
5912 ("%s: inappropriate vnode", __func__));
5913 ASSERT_VI_UNLOCKED(vp, __func__);
5914 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5918 TAILQ_REMOVE(&mp->mnt_activevnodelist, mvp, v_actfreelist);
5919 TAILQ_INSERT_BEFORE(vp, mvp, v_actfreelist);
5922 * Use a hold to prevent vp from disappearing while the mount vnode
5923 * list lock is dropped and reacquired. Normally a hold would be
5924 * acquired with vhold(), but that might try to acquire the vnode
5925 * interlock, which would be a LOR with the mount vnode list lock.
5927 held = refcount_acquire_if_not_zero(&vp->v_holdcnt);
5928 mtx_unlock(&mp->mnt_listmtx);
5932 if (!refcount_release_if_not_last(&vp->v_holdcnt)) {
5936 mtx_lock(&mp->mnt_listmtx);
5939 * Determine whether the vnode is still the next one after the marker,
5940 * excepting any other markers. If the vnode has not been doomed by
5941 * vgone() then the hold should have ensured that it remained on the
5942 * active list. If it has been doomed but is still on the active list,
5943 * don't abort, but rather skip over it (avoid spinning on doomed
5948 tmp = TAILQ_NEXT(tmp, v_actfreelist);
5949 } while (tmp != NULL && tmp->v_type == VMARKER);
5951 mtx_unlock(&mp->mnt_listmtx);
5960 mtx_lock(&mp->mnt_listmtx);
5963 ASSERT_VI_LOCKED(vp, __func__);
5965 ASSERT_VI_UNLOCKED(vp, __func__);
5966 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5970 static struct vnode *
5971 mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
5973 struct vnode *vp, *nvp;
5975 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5976 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5978 vp = TAILQ_NEXT(*mvp, v_actfreelist);
5979 while (vp != NULL) {
5980 if (vp->v_type == VMARKER) {
5981 vp = TAILQ_NEXT(vp, v_actfreelist);
5985 * Try-lock because this is the wrong lock order. If that does
5986 * not succeed, drop the mount vnode list lock and try to
5987 * reacquire it and the vnode interlock in the right order.
5989 if (!VI_TRYLOCK(vp) &&
5990 !mnt_vnode_next_active_relock(*mvp, mp, vp))
5992 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
5993 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
5994 ("alien vnode on the active list %p %p", vp, mp));
5995 if (vp->v_mount == mp && (vp->v_iflag & VI_DOOMED) == 0)
5997 nvp = TAILQ_NEXT(vp, v_actfreelist);
6001 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
6003 /* Check if we are done */
6005 mtx_unlock(&mp->mnt_listmtx);
6006 mnt_vnode_markerfree_active(mvp, mp);
6009 TAILQ_INSERT_AFTER(&mp->mnt_activevnodelist, vp, *mvp, v_actfreelist);
6010 mtx_unlock(&mp->mnt_listmtx);
6011 ASSERT_VI_LOCKED(vp, "active iter");
6012 KASSERT((vp->v_iflag & VI_ACTIVE) != 0, ("Non-active vp %p", vp));
6017 __mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
6021 kern_yield(PRI_USER);
6022 mtx_lock(&mp->mnt_listmtx);
6023 return (mnt_vnode_next_active(mvp, mp));
6027 __mnt_vnode_first_active(struct vnode **mvp, struct mount *mp)
6031 *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
6035 (*mvp)->v_type = VMARKER;
6036 (*mvp)->v_mount = mp;
6038 mtx_lock(&mp->mnt_listmtx);
6039 vp = TAILQ_FIRST(&mp->mnt_activevnodelist);
6041 mtx_unlock(&mp->mnt_listmtx);
6042 mnt_vnode_markerfree_active(mvp, mp);
6045 TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
6046 return (mnt_vnode_next_active(mvp, mp));
6050 __mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
6056 mtx_lock(&mp->mnt_listmtx);
6057 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
6058 mtx_unlock(&mp->mnt_listmtx);
6059 mnt_vnode_markerfree_active(mvp, mp);