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 VIRF_DOOMED vnode.
142 static u_long __exclusive_cache_line numvnodes;
144 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
145 "Number of vnodes in existence");
147 static counter_u64_t vnodes_created;
148 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
149 "Number of vnodes created by getnewvnode");
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");
207 static counter_u64_t recycles_free_count;
208 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD, &recycles_free_count,
209 "Number of free vnodes recycled to meet vnode cache targets");
212 * Various variables used for debugging the new implementation of
214 * XXX these are probably of (very) limited utility now.
216 static int reassignbufcalls;
217 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW | CTLFLAG_STATS,
218 &reassignbufcalls, 0, "Number of calls to reassignbuf");
220 static counter_u64_t free_owe_inact;
221 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, free_owe_inact, CTLFLAG_RD, &free_owe_inact,
222 "Number of times free vnodes kept on active list due to VFS "
223 "owing inactivation");
225 /* To keep more than one thread at a time from running vfs_getnewfsid */
226 static struct mtx mntid_mtx;
229 * Lock for any access to the following:
234 static struct mtx __exclusive_cache_line vnode_free_list_mtx;
236 /* Publicly exported FS */
237 struct nfs_public nfs_pub;
239 static uma_zone_t buf_trie_zone;
241 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
242 static uma_zone_t vnode_zone;
243 static uma_zone_t vnodepoll_zone;
246 * The workitem queue.
248 * It is useful to delay writes of file data and filesystem metadata
249 * for tens of seconds so that quickly created and deleted files need
250 * not waste disk bandwidth being created and removed. To realize this,
251 * we append vnodes to a "workitem" queue. When running with a soft
252 * updates implementation, most pending metadata dependencies should
253 * not wait for more than a few seconds. Thus, mounted on block devices
254 * are delayed only about a half the time that file data is delayed.
255 * Similarly, directory updates are more critical, so are only delayed
256 * about a third the time that file data is delayed. Thus, there are
257 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
258 * one each second (driven off the filesystem syncer process). The
259 * syncer_delayno variable indicates the next queue that is to be processed.
260 * Items that need to be processed soon are placed in this queue:
262 * syncer_workitem_pending[syncer_delayno]
264 * A delay of fifteen seconds is done by placing the request fifteen
265 * entries later in the queue:
267 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
270 static int syncer_delayno;
271 static long syncer_mask;
272 LIST_HEAD(synclist, bufobj);
273 static struct synclist *syncer_workitem_pending;
275 * The sync_mtx protects:
280 * syncer_workitem_pending
281 * syncer_worklist_len
284 static struct mtx sync_mtx;
285 static struct cv sync_wakeup;
287 #define SYNCER_MAXDELAY 32
288 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
289 static int syncdelay = 30; /* max time to delay syncing data */
290 static int filedelay = 30; /* time to delay syncing files */
291 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
292 "Time to delay syncing files (in seconds)");
293 static int dirdelay = 29; /* time to delay syncing directories */
294 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
295 "Time to delay syncing directories (in seconds)");
296 static int metadelay = 28; /* time to delay syncing metadata */
297 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
298 "Time to delay syncing metadata (in seconds)");
299 static int rushjob; /* number of slots to run ASAP */
300 static int stat_rush_requests; /* number of times I/O speeded up */
301 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
302 "Number of times I/O speeded up (rush requests)");
305 * When shutting down the syncer, run it at four times normal speed.
307 #define SYNCER_SHUTDOWN_SPEEDUP 4
308 static int sync_vnode_count;
309 static int syncer_worklist_len;
310 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
313 /* Target for maximum number of vnodes. */
315 static int gapvnodes; /* gap between wanted and desired */
316 static int vhiwat; /* enough extras after expansion */
317 static int vlowat; /* minimal extras before expansion */
318 static int vstir; /* nonzero to stir non-free vnodes */
319 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
322 sysctl_update_desiredvnodes(SYSCTL_HANDLER_ARGS)
324 int error, old_desiredvnodes;
326 old_desiredvnodes = desiredvnodes;
327 if ((error = sysctl_handle_int(oidp, arg1, arg2, req)) != 0)
329 if (old_desiredvnodes != desiredvnodes) {
330 wantfreevnodes = desiredvnodes / 4;
331 /* XXX locking seems to be incomplete. */
332 vfs_hash_changesize(desiredvnodes);
333 cache_changesize(desiredvnodes);
338 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
339 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, &desiredvnodes, 0,
340 sysctl_update_desiredvnodes, "I", "Target for maximum number of vnodes");
341 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
342 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
343 static int vnlru_nowhere;
344 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
345 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
348 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
353 unsigned long ndflags;
356 if (req->newptr == NULL)
358 if (req->newlen >= PATH_MAX)
361 buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
362 error = SYSCTL_IN(req, buf, req->newlen);
366 buf[req->newlen] = '\0';
368 ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | NOCACHE | SAVENAME;
369 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
370 if ((error = namei(&nd)) != 0)
374 if (VN_IS_DOOMED(vp)) {
376 * This vnode is being recycled. Return != 0 to let the caller
377 * know that the sysctl had no effect. Return EAGAIN because a
378 * subsequent call will likely succeed (since namei will create
379 * a new vnode if necessary)
385 counter_u64_add(recycles_count, 1);
395 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
397 struct thread *td = curthread;
403 if (req->newptr == NULL)
406 error = sysctl_handle_int(oidp, &fd, 0, req);
409 error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
414 error = vn_lock(vp, LK_EXCLUSIVE);
418 counter_u64_add(recycles_count, 1);
426 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
427 CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
428 sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
429 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
430 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
431 sysctl_ftry_reclaim_vnode, "I",
432 "Try to reclaim a vnode by its file descriptor");
434 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
438 * Support for the bufobj clean & dirty pctrie.
441 buf_trie_alloc(struct pctrie *ptree)
444 return uma_zalloc(buf_trie_zone, M_NOWAIT);
448 buf_trie_free(struct pctrie *ptree, void *node)
451 uma_zfree(buf_trie_zone, node);
453 PCTRIE_DEFINE(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free);
456 * Initialize the vnode management data structures.
458 * Reevaluate the following cap on the number of vnodes after the physical
459 * memory size exceeds 512GB. In the limit, as the physical memory size
460 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
462 #ifndef MAXVNODES_MAX
463 #define MAXVNODES_MAX (512 * 1024 * 1024 / 64) /* 8M */
466 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
468 static struct vnode *
469 vn_alloc_marker(struct mount *mp)
473 vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
474 vp->v_type = VMARKER;
481 vn_free_marker(struct vnode *vp)
484 MPASS(vp->v_type == VMARKER);
485 free(vp, M_VNODE_MARKER);
489 * Initialize a vnode as it first enters the zone.
492 vnode_init(void *mem, int size, int flags)
501 vp->v_vnlock = &vp->v_lock;
502 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
504 * By default, don't allow shared locks unless filesystems opt-in.
506 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
507 LK_NOSHARE | LK_IS_VNODE);
511 bufobj_init(&vp->v_bufobj, vp);
513 * Initialize namecache.
515 LIST_INIT(&vp->v_cache_src);
516 TAILQ_INIT(&vp->v_cache_dst);
518 * Initialize rangelocks.
520 rangelock_init(&vp->v_rl);
525 * Free a vnode when it is cleared from the zone.
528 vnode_fini(void *mem, int size)
534 rangelock_destroy(&vp->v_rl);
535 lockdestroy(vp->v_vnlock);
536 mtx_destroy(&vp->v_interlock);
538 rw_destroy(BO_LOCKPTR(bo));
542 * Provide the size of NFS nclnode and NFS fh for calculation of the
543 * vnode memory consumption. The size is specified directly to
544 * eliminate dependency on NFS-private header.
546 * Other filesystems may use bigger or smaller (like UFS and ZFS)
547 * private inode data, but the NFS-based estimation is ample enough.
548 * Still, we care about differences in the size between 64- and 32-bit
551 * Namecache structure size is heuristically
552 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
555 #define NFS_NCLNODE_SZ (528 + 64)
558 #define NFS_NCLNODE_SZ (360 + 32)
563 vntblinit(void *dummy __unused)
566 int physvnodes, virtvnodes;
569 * Desiredvnodes is a function of the physical memory size and the
570 * kernel's heap size. Generally speaking, it scales with the
571 * physical memory size. The ratio of desiredvnodes to the physical
572 * memory size is 1:16 until desiredvnodes exceeds 98,304.
574 * marginal ratio of desiredvnodes to the physical memory size is
575 * 1:64. However, desiredvnodes is limited by the kernel's heap
576 * size. The memory required by desiredvnodes vnodes and vm objects
577 * must not exceed 1/10th of the kernel's heap size.
579 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
580 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
581 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
582 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
583 desiredvnodes = min(physvnodes, virtvnodes);
584 if (desiredvnodes > MAXVNODES_MAX) {
586 printf("Reducing kern.maxvnodes %d -> %d\n",
587 desiredvnodes, MAXVNODES_MAX);
588 desiredvnodes = MAXVNODES_MAX;
590 wantfreevnodes = desiredvnodes / 4;
591 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
592 TAILQ_INIT(&vnode_free_list);
593 mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
594 vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
595 vnode_init, vnode_fini, UMA_ALIGN_PTR, 0);
596 vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
597 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
599 * Preallocate enough nodes to support one-per buf so that
600 * we can not fail an insert. reassignbuf() callers can not
601 * tolerate the insertion failure.
603 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
604 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
605 UMA_ZONE_NOFREE | UMA_ZONE_VM);
606 uma_prealloc(buf_trie_zone, nbuf);
608 vnodes_created = counter_u64_alloc(M_WAITOK);
609 recycles_count = counter_u64_alloc(M_WAITOK);
610 recycles_free_count = counter_u64_alloc(M_WAITOK);
611 free_owe_inact = counter_u64_alloc(M_WAITOK);
614 * Initialize the filesystem syncer.
616 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
618 syncer_maxdelay = syncer_mask + 1;
619 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
620 cv_init(&sync_wakeup, "syncer");
621 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
625 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
629 * Mark a mount point as busy. Used to synchronize access and to delay
630 * unmounting. Eventually, mountlist_mtx is not released on failure.
632 * vfs_busy() is a custom lock, it can block the caller.
633 * vfs_busy() only sleeps if the unmount is active on the mount point.
634 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
635 * vnode belonging to mp.
637 * Lookup uses vfs_busy() to traverse mount points.
639 * / vnode lock A / vnode lock (/var) D
640 * /var vnode lock B /log vnode lock(/var/log) E
641 * vfs_busy lock C vfs_busy lock F
643 * Within each file system, the lock order is C->A->B and F->D->E.
645 * When traversing across mounts, the system follows that lock order:
651 * The lookup() process for namei("/var") illustrates the process:
652 * VOP_LOOKUP() obtains B while A is held
653 * vfs_busy() obtains a shared lock on F while A and B are held
654 * vput() releases lock on B
655 * vput() releases lock on A
656 * VFS_ROOT() obtains lock on D while shared lock on F is held
657 * vfs_unbusy() releases shared lock on F
658 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
659 * Attempt to lock A (instead of vp_crossmp) while D is held would
660 * violate the global order, causing deadlocks.
662 * dounmount() locks B while F is drained.
665 vfs_busy(struct mount *mp, int flags)
668 MPASS((flags & ~MBF_MASK) == 0);
669 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
671 if (vfs_op_thread_enter(mp)) {
672 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
673 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
674 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
675 vfs_mp_count_add_pcpu(mp, ref, 1);
676 vfs_mp_count_add_pcpu(mp, lockref, 1);
677 vfs_op_thread_exit(mp);
678 if (flags & MBF_MNTLSTLOCK)
679 mtx_unlock(&mountlist_mtx);
684 vfs_assert_mount_counters(mp);
687 * If mount point is currently being unmounted, sleep until the
688 * mount point fate is decided. If thread doing the unmounting fails,
689 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
690 * that this mount point has survived the unmount attempt and vfs_busy
691 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
692 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
693 * about to be really destroyed. vfs_busy needs to release its
694 * reference on the mount point in this case and return with ENOENT,
695 * telling the caller that mount mount it tried to busy is no longer
698 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
699 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
702 CTR1(KTR_VFS, "%s: failed busying before sleeping",
706 if (flags & MBF_MNTLSTLOCK)
707 mtx_unlock(&mountlist_mtx);
708 mp->mnt_kern_flag |= MNTK_MWAIT;
709 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
710 if (flags & MBF_MNTLSTLOCK)
711 mtx_lock(&mountlist_mtx);
714 if (flags & MBF_MNTLSTLOCK)
715 mtx_unlock(&mountlist_mtx);
722 * Free a busy filesystem.
725 vfs_unbusy(struct mount *mp)
729 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
731 if (vfs_op_thread_enter(mp)) {
732 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
733 vfs_mp_count_sub_pcpu(mp, lockref, 1);
734 vfs_mp_count_sub_pcpu(mp, ref, 1);
735 vfs_op_thread_exit(mp);
740 vfs_assert_mount_counters(mp);
742 c = --mp->mnt_lockref;
743 if (mp->mnt_vfs_ops == 0) {
744 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
749 vfs_dump_mount_counters(mp);
750 if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
751 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
752 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
753 mp->mnt_kern_flag &= ~MNTK_DRAINING;
754 wakeup(&mp->mnt_lockref);
760 * Lookup a mount point by filesystem identifier.
763 vfs_getvfs(fsid_t *fsid)
767 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
768 mtx_lock(&mountlist_mtx);
769 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
770 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
771 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
773 mtx_unlock(&mountlist_mtx);
777 mtx_unlock(&mountlist_mtx);
778 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
779 return ((struct mount *) 0);
783 * Lookup a mount point by filesystem identifier, busying it before
786 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
787 * cache for popular filesystem identifiers. The cache is lockess, using
788 * the fact that struct mount's are never freed. In worst case we may
789 * get pointer to unmounted or even different filesystem, so we have to
790 * check what we got, and go slow way if so.
793 vfs_busyfs(fsid_t *fsid)
795 #define FSID_CACHE_SIZE 256
796 typedef struct mount * volatile vmp_t;
797 static vmp_t cache[FSID_CACHE_SIZE];
802 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
803 hash = fsid->val[0] ^ fsid->val[1];
804 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
807 mp->mnt_stat.f_fsid.val[0] != fsid->val[0] ||
808 mp->mnt_stat.f_fsid.val[1] != fsid->val[1])
810 if (vfs_busy(mp, 0) != 0) {
814 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
815 mp->mnt_stat.f_fsid.val[1] == fsid->val[1])
821 mtx_lock(&mountlist_mtx);
822 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
823 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
824 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
825 error = vfs_busy(mp, MBF_MNTLSTLOCK);
828 mtx_unlock(&mountlist_mtx);
835 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
836 mtx_unlock(&mountlist_mtx);
837 return ((struct mount *) 0);
841 * Check if a user can access privileged mount options.
844 vfs_suser(struct mount *mp, struct thread *td)
848 if (jailed(td->td_ucred)) {
850 * If the jail of the calling thread lacks permission for
851 * this type of file system, deny immediately.
853 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
857 * If the file system was mounted outside the jail of the
858 * calling thread, deny immediately.
860 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
865 * If file system supports delegated administration, we don't check
866 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
867 * by the file system itself.
868 * If this is not the user that did original mount, we check for
869 * the PRIV_VFS_MOUNT_OWNER privilege.
871 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
872 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
873 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
880 * Get a new unique fsid. Try to make its val[0] unique, since this value
881 * will be used to create fake device numbers for stat(). Also try (but
882 * not so hard) make its val[0] unique mod 2^16, since some emulators only
883 * support 16-bit device numbers. We end up with unique val[0]'s for the
884 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
886 * Keep in mind that several mounts may be running in parallel. Starting
887 * the search one past where the previous search terminated is both a
888 * micro-optimization and a defense against returning the same fsid to
892 vfs_getnewfsid(struct mount *mp)
894 static uint16_t mntid_base;
899 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
900 mtx_lock(&mntid_mtx);
901 mtype = mp->mnt_vfc->vfc_typenum;
902 tfsid.val[1] = mtype;
903 mtype = (mtype & 0xFF) << 24;
905 tfsid.val[0] = makedev(255,
906 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
908 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
912 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
913 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
914 mtx_unlock(&mntid_mtx);
918 * Knob to control the precision of file timestamps:
920 * 0 = seconds only; nanoseconds zeroed.
921 * 1 = seconds and nanoseconds, accurate within 1/HZ.
922 * 2 = seconds and nanoseconds, truncated to microseconds.
923 * >=3 = seconds and nanoseconds, maximum precision.
925 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
927 static int timestamp_precision = TSP_USEC;
928 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
929 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
930 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
931 "3+: sec + ns (max. precision))");
934 * Get a current timestamp.
937 vfs_timestamp(struct timespec *tsp)
941 switch (timestamp_precision) {
943 tsp->tv_sec = time_second;
951 TIMEVAL_TO_TIMESPEC(&tv, tsp);
961 * Set vnode attributes to VNOVAL
964 vattr_null(struct vattr *vap)
968 vap->va_size = VNOVAL;
969 vap->va_bytes = VNOVAL;
970 vap->va_mode = VNOVAL;
971 vap->va_nlink = VNOVAL;
972 vap->va_uid = VNOVAL;
973 vap->va_gid = VNOVAL;
974 vap->va_fsid = VNOVAL;
975 vap->va_fileid = VNOVAL;
976 vap->va_blocksize = VNOVAL;
977 vap->va_rdev = VNOVAL;
978 vap->va_atime.tv_sec = VNOVAL;
979 vap->va_atime.tv_nsec = VNOVAL;
980 vap->va_mtime.tv_sec = VNOVAL;
981 vap->va_mtime.tv_nsec = VNOVAL;
982 vap->va_ctime.tv_sec = VNOVAL;
983 vap->va_ctime.tv_nsec = VNOVAL;
984 vap->va_birthtime.tv_sec = VNOVAL;
985 vap->va_birthtime.tv_nsec = VNOVAL;
986 vap->va_flags = VNOVAL;
987 vap->va_gen = VNOVAL;
992 * This routine is called when we have too many vnodes. It attempts
993 * to free <count> vnodes and will potentially free vnodes that still
994 * have VM backing store (VM backing store is typically the cause
995 * of a vnode blowout so we want to do this). Therefore, this operation
996 * is not considered cheap.
998 * A number of conditions may prevent a vnode from being reclaimed.
999 * the buffer cache may have references on the vnode, a directory
1000 * vnode may still have references due to the namei cache representing
1001 * underlying files, or the vnode may be in active use. It is not
1002 * desirable to reuse such vnodes. These conditions may cause the
1003 * number of vnodes to reach some minimum value regardless of what
1004 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
1006 * @param mp Try to reclaim vnodes from this mountpoint
1007 * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1008 * entries if this argument is strue
1009 * @param trigger Only reclaim vnodes with fewer than this many resident
1011 * @return The number of vnodes that were reclaimed.
1014 vlrureclaim(struct mount *mp, bool reclaim_nc_src, int trigger)
1017 int count, done, target;
1020 vn_start_write(NULL, &mp, V_WAIT);
1022 count = mp->mnt_nvnodelistsize;
1023 target = count * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1024 target = target / 10 + 1;
1025 while (count != 0 && done < target) {
1026 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
1027 while (vp != NULL && vp->v_type == VMARKER)
1028 vp = TAILQ_NEXT(vp, v_nmntvnodes);
1032 * XXX LRU is completely broken for non-free vnodes. First
1033 * by calling here in mountpoint order, then by moving
1034 * unselected vnodes to the end here, and most grossly by
1035 * removing the vlruvp() function that was supposed to
1036 * maintain the order. (This function was born broken
1037 * since syncer problems prevented it doing anything.) The
1038 * order is closer to LRC (C = Created).
1040 * LRU reclaiming of vnodes seems to have last worked in
1041 * FreeBSD-3 where LRU wasn't mentioned under any spelling.
1042 * Then there was no hold count, and inactive vnodes were
1043 * simply put on the free list in LRU order. The separate
1044 * lists also break LRU. We prefer to reclaim from the
1045 * free list for technical reasons. This tends to thrash
1046 * the free list to keep very unrecently used held vnodes.
1047 * The problem is mitigated by keeping the free list large.
1049 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1050 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1052 if (!VI_TRYLOCK(vp))
1055 * If it's been deconstructed already, it's still
1056 * referenced, or it exceeds the trigger, skip it.
1057 * Also skip free vnodes. We are trying to make space
1058 * to expand the free list, not reduce it.
1060 if (vp->v_usecount ||
1061 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1062 ((vp->v_iflag & VI_FREE) != 0) ||
1063 VN_IS_DOOMED(vp) || (vp->v_object != NULL &&
1064 vp->v_object->resident_page_count > trigger)) {
1070 if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT)) {
1072 goto next_iter_mntunlocked;
1076 * v_usecount may have been bumped after VOP_LOCK() dropped
1077 * the vnode interlock and before it was locked again.
1079 * It is not necessary to recheck VIRF_DOOMED because it can
1080 * only be set by another thread that holds both the vnode
1081 * lock and vnode interlock. If another thread has the
1082 * vnode lock before we get to VOP_LOCK() and obtains the
1083 * vnode interlock after VOP_LOCK() drops the vnode
1084 * interlock, the other thread will be unable to drop the
1085 * vnode lock before our VOP_LOCK() call fails.
1087 if (vp->v_usecount ||
1088 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1089 (vp->v_object != NULL &&
1090 vp->v_object->resident_page_count > trigger)) {
1093 goto next_iter_mntunlocked;
1095 KASSERT(!VN_IS_DOOMED(vp),
1096 ("VIRF_DOOMED unexpectedly detected in vlrureclaim()"));
1097 counter_u64_add(recycles_count, 1);
1102 next_iter_mntunlocked:
1103 if (!should_yield())
1107 if (!should_yield())
1111 kern_yield(PRI_USER);
1116 vn_finished_write(mp);
1120 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1121 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1123 "limit on vnode free requests per call to the vnlru_free routine");
1126 * Attempt to reduce the free list by the requested amount.
1129 vnlru_free_locked(int count, struct vfsops *mnt_op)
1135 tried_batches = false;
1136 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
1137 if (count > max_vnlru_free)
1138 count = max_vnlru_free;
1139 for (; count > 0; count--) {
1140 vp = TAILQ_FIRST(&vnode_free_list);
1142 * The list can be modified while the free_list_mtx
1143 * has been dropped and vp could be NULL here.
1148 mtx_unlock(&vnode_free_list_mtx);
1149 vnlru_return_batches(mnt_op);
1150 tried_batches = true;
1151 mtx_lock(&vnode_free_list_mtx);
1155 VNASSERT(vp->v_op != NULL, vp,
1156 ("vnlru_free: vnode already reclaimed."));
1157 KASSERT((vp->v_iflag & VI_FREE) != 0,
1158 ("Removing vnode not on freelist"));
1159 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1160 ("Mangling active vnode"));
1161 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
1164 * Don't recycle if our vnode is from different type
1165 * of mount point. Note that mp is type-safe, the
1166 * check does not reach unmapped address even if
1167 * vnode is reclaimed.
1168 * Don't recycle if we can't get the interlock without
1171 if ((mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1172 mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
1173 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_actfreelist);
1176 VNASSERT((vp->v_iflag & VI_FREE) != 0 && vp->v_holdcnt == 0,
1177 vp, ("vp inconsistent on freelist"));
1180 * The clear of VI_FREE prevents activation of the
1181 * vnode. There is no sense in putting the vnode on
1182 * the mount point active list, only to remove it
1183 * later during recycling. Inline the relevant part
1184 * of vholdl(), to avoid triggering assertions or
1188 vp->v_iflag &= ~VI_FREE;
1189 VNODE_REFCOUNT_FENCE_REL();
1190 refcount_acquire(&vp->v_holdcnt);
1192 mtx_unlock(&vnode_free_list_mtx);
1196 * If the recycled succeeded this vdrop will actually free
1197 * the vnode. If not it will simply place it back on
1201 mtx_lock(&vnode_free_list_mtx);
1206 vnlru_free(int count, struct vfsops *mnt_op)
1209 mtx_lock(&vnode_free_list_mtx);
1210 vnlru_free_locked(count, mnt_op);
1211 mtx_unlock(&vnode_free_list_mtx);
1215 /* XXX some names and initialization are bad for limits and watermarks. */
1219 u_long rnumvnodes, rfreevnodes;
1222 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1223 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1224 vlowat = vhiwat / 2;
1225 rnumvnodes = atomic_load_long(&numvnodes);
1226 rfreevnodes = atomic_load_long(&freevnodes);
1227 if (rnumvnodes > desiredvnodes)
1229 space = desiredvnodes - rnumvnodes;
1230 if (freevnodes > wantfreevnodes)
1231 space += rfreevnodes - wantfreevnodes;
1236 vnlru_return_batch_locked(struct mount *mp)
1240 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
1242 if (mp->mnt_tmpfreevnodelistsize == 0)
1245 TAILQ_FOREACH(vp, &mp->mnt_tmpfreevnodelist, v_actfreelist) {
1246 VNASSERT((vp->v_mflag & VMP_TMPMNTFREELIST) != 0, vp,
1247 ("vnode without VMP_TMPMNTFREELIST on mnt_tmpfreevnodelist"));
1248 vp->v_mflag &= ~VMP_TMPMNTFREELIST;
1250 mtx_lock(&vnode_free_list_mtx);
1251 TAILQ_CONCAT(&vnode_free_list, &mp->mnt_tmpfreevnodelist, v_actfreelist);
1252 freevnodes += mp->mnt_tmpfreevnodelistsize;
1253 mtx_unlock(&vnode_free_list_mtx);
1254 mp->mnt_tmpfreevnodelistsize = 0;
1258 vnlru_return_batch(struct mount *mp)
1261 mtx_lock(&mp->mnt_listmtx);
1262 vnlru_return_batch_locked(mp);
1263 mtx_unlock(&mp->mnt_listmtx);
1267 vnlru_return_batches(struct vfsops *mnt_op)
1269 struct mount *mp, *nmp;
1272 mtx_lock(&mountlist_mtx);
1273 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1274 need_unbusy = false;
1275 if (mnt_op != NULL && mp->mnt_op != mnt_op)
1277 if (mp->mnt_tmpfreevnodelistsize == 0)
1279 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK) == 0) {
1280 vnlru_return_batch(mp);
1282 mtx_lock(&mountlist_mtx);
1285 nmp = TAILQ_NEXT(mp, mnt_list);
1289 mtx_unlock(&mountlist_mtx);
1293 * Attempt to recycle vnodes in a context that is always safe to block.
1294 * Calling vlrurecycle() from the bowels of filesystem code has some
1295 * interesting deadlock problems.
1297 static struct proc *vnlruproc;
1298 static int vnlruproc_sig;
1303 u_long rnumvnodes, rfreevnodes;
1304 struct mount *mp, *nmp;
1305 unsigned long onumvnodes;
1306 int done, force, trigger, usevnodes, vsp;
1307 bool reclaim_nc_src;
1309 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1310 SHUTDOWN_PRI_FIRST);
1314 kproc_suspend_check(vnlruproc);
1315 mtx_lock(&vnode_free_list_mtx);
1316 rnumvnodes = atomic_load_long(&numvnodes);
1318 * If numvnodes is too large (due to desiredvnodes being
1319 * adjusted using its sysctl, or emergency growth), first
1320 * try to reduce it by discarding from the free list.
1322 if (rnumvnodes > desiredvnodes)
1323 vnlru_free_locked(rnumvnodes - desiredvnodes, NULL);
1325 * Sleep if the vnode cache is in a good state. This is
1326 * when it is not over-full and has space for about a 4%
1327 * or 9% expansion (by growing its size or inexcessively
1328 * reducing its free list). Otherwise, try to reclaim
1329 * space for a 10% expansion.
1331 if (vstir && force == 0) {
1336 if (vsp >= vlowat && force == 0) {
1338 wakeup(&vnlruproc_sig);
1339 msleep(vnlruproc, &vnode_free_list_mtx,
1340 PVFS|PDROP, "vlruwt", hz);
1343 mtx_unlock(&vnode_free_list_mtx);
1345 rnumvnodes = atomic_load_long(&numvnodes);
1346 rfreevnodes = atomic_load_long(&freevnodes);
1348 onumvnodes = rnumvnodes;
1350 * Calculate parameters for recycling. These are the same
1351 * throughout the loop to give some semblance of fairness.
1352 * The trigger point is to avoid recycling vnodes with lots
1353 * of resident pages. We aren't trying to free memory; we
1354 * are trying to recycle or at least free vnodes.
1356 if (rnumvnodes <= desiredvnodes)
1357 usevnodes = rnumvnodes - rfreevnodes;
1359 usevnodes = rnumvnodes;
1363 * The trigger value is is chosen to give a conservatively
1364 * large value to ensure that it alone doesn't prevent
1365 * making progress. The value can easily be so large that
1366 * it is effectively infinite in some congested and
1367 * misconfigured cases, and this is necessary. Normally
1368 * it is about 8 to 100 (pages), which is quite large.
1370 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1372 trigger = vsmalltrigger;
1373 reclaim_nc_src = force >= 3;
1374 mtx_lock(&mountlist_mtx);
1375 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1376 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK)) {
1377 nmp = TAILQ_NEXT(mp, mnt_list);
1380 done += vlrureclaim(mp, reclaim_nc_src, trigger);
1381 mtx_lock(&mountlist_mtx);
1382 nmp = TAILQ_NEXT(mp, mnt_list);
1385 mtx_unlock(&mountlist_mtx);
1386 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1387 uma_reclaim(UMA_RECLAIM_DRAIN);
1389 if (force == 0 || force == 1) {
1399 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1401 kern_yield(PRI_USER);
1403 * After becoming active to expand above low water, keep
1404 * active until above high water.
1407 force = vsp < vhiwat;
1411 static struct kproc_desc vnlru_kp = {
1416 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1420 * Routines having to do with the management of the vnode table.
1424 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1425 * before we actually vgone(). This function must be called with the vnode
1426 * held to prevent the vnode from being returned to the free list midway
1430 vtryrecycle(struct vnode *vp)
1434 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1435 VNASSERT(vp->v_holdcnt, vp,
1436 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1438 * This vnode may found and locked via some other list, if so we
1439 * can't recycle it yet.
1441 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1443 "%s: impossible to recycle, vp %p lock is already held",
1445 return (EWOULDBLOCK);
1448 * Don't recycle if its filesystem is being suspended.
1450 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1453 "%s: impossible to recycle, cannot start the write for %p",
1458 * If we got this far, we need to acquire the interlock and see if
1459 * anyone picked up this vnode from another list. If not, we will
1460 * mark it with DOOMED via vgonel() so that anyone who does find it
1461 * will skip over it.
1464 if (vp->v_usecount) {
1467 vn_finished_write(vnmp);
1469 "%s: impossible to recycle, %p is already referenced",
1473 if (!VN_IS_DOOMED(vp)) {
1474 counter_u64_add(recycles_free_count, 1);
1479 vn_finished_write(vnmp);
1489 if (vsp < vlowat && vnlruproc_sig == 0) {
1496 * Wait if necessary for space for a new vnode.
1499 getnewvnode_wait(int suspended)
1502 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
1503 if (numvnodes >= desiredvnodes) {
1506 * The file system is being suspended. We cannot
1507 * risk a deadlock here, so allow allocation of
1508 * another vnode even if this would give too many.
1512 if (vnlruproc_sig == 0) {
1513 vnlruproc_sig = 1; /* avoid unnecessary wakeups */
1516 msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
1519 /* Post-adjust like the pre-adjust in getnewvnode(). */
1520 if (numvnodes + 1 > desiredvnodes && freevnodes > 1)
1521 vnlru_free_locked(1, NULL);
1522 return (numvnodes >= desiredvnodes ? ENFILE : 0);
1526 * This hack is fragile, and probably not needed any more now that the
1527 * watermark handling works.
1530 getnewvnode_reserve(u_int count)
1532 u_long rnumvnodes, rfreevnodes;
1535 /* Pre-adjust like the pre-adjust in getnewvnode(), with any count. */
1536 /* XXX no longer so quick, but this part is not racy. */
1537 mtx_lock(&vnode_free_list_mtx);
1538 rnumvnodes = atomic_load_long(&numvnodes);
1539 rfreevnodes = atomic_load_long(&freevnodes);
1540 if (rnumvnodes + count > desiredvnodes && rfreevnodes > wantfreevnodes)
1541 vnlru_free_locked(ulmin(rnumvnodes + count - desiredvnodes,
1542 rfreevnodes - wantfreevnodes), NULL);
1543 mtx_unlock(&vnode_free_list_mtx);
1546 /* First try to be quick and racy. */
1547 if (atomic_fetchadd_long(&numvnodes, count) + count <= desiredvnodes) {
1548 td->td_vp_reserv += count;
1549 vcheckspace(); /* XXX no longer so quick, but more racy */
1552 atomic_subtract_long(&numvnodes, count);
1554 mtx_lock(&vnode_free_list_mtx);
1556 if (getnewvnode_wait(0) == 0) {
1559 atomic_add_long(&numvnodes, 1);
1563 mtx_unlock(&vnode_free_list_mtx);
1567 * This hack is fragile, especially if desiredvnodes or wantvnodes are
1568 * misconfgured or changed significantly. Reducing desiredvnodes below
1569 * the reserved amount should cause bizarre behaviour like reducing it
1570 * below the number of active vnodes -- the system will try to reduce
1571 * numvnodes to match, but should fail, so the subtraction below should
1575 getnewvnode_drop_reserve(void)
1580 atomic_subtract_long(&numvnodes, td->td_vp_reserv);
1581 td->td_vp_reserv = 0;
1585 * Return the next vnode from the free list.
1588 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1593 struct lock_object *lo;
1594 static int cyclecount;
1597 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1599 KASSERT(vops->registered,
1600 ("%s: not registered vector op %p\n", __func__, vops));
1604 if (td->td_vp_reserv > 0) {
1605 td->td_vp_reserv -= 1;
1608 mtx_lock(&vnode_free_list_mtx);
1609 if (numvnodes < desiredvnodes)
1611 else if (cyclecount++ >= freevnodes) {
1616 * Grow the vnode cache if it will not be above its target max
1617 * after growing. Otherwise, if the free list is nonempty, try
1618 * to reclaim 1 item from it before growing the cache (possibly
1619 * above its target max if the reclamation failed or is delayed).
1620 * Otherwise, wait for some space. In all cases, schedule
1621 * vnlru_proc() if we are getting short of space. The watermarks
1622 * should be chosen so that we never wait or even reclaim from
1623 * the free list to below its target minimum.
1625 if (numvnodes + 1 <= desiredvnodes)
1627 else if (freevnodes > 0)
1628 vnlru_free_locked(1, NULL);
1630 error = getnewvnode_wait(mp != NULL && (mp->mnt_kern_flag &
1632 #if 0 /* XXX Not all VFS_VGET/ffs_vget callers check returns. */
1634 mtx_unlock(&vnode_free_list_mtx);
1640 atomic_add_long(&numvnodes, 1);
1641 mtx_unlock(&vnode_free_list_mtx);
1643 counter_u64_add(vnodes_created, 1);
1644 vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK);
1646 * Locks are given the generic name "vnode" when created.
1647 * Follow the historic practice of using the filesystem
1648 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1650 * Locks live in a witness group keyed on their name. Thus,
1651 * when a lock is renamed, it must also move from the witness
1652 * group of its old name to the witness group of its new name.
1654 * The change only needs to be made when the vnode moves
1655 * from one filesystem type to another. We ensure that each
1656 * filesystem use a single static name pointer for its tag so
1657 * that we can compare pointers rather than doing a strcmp().
1659 lo = &vp->v_vnlock->lock_object;
1660 if (lo->lo_name != tag) {
1662 WITNESS_DESTROY(lo);
1663 WITNESS_INIT(lo, tag);
1666 * By default, don't allow shared locks unless filesystems opt-in.
1668 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1670 * Finalize various vnode identity bits.
1672 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1673 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1674 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1677 v_init_counters(vp);
1678 vp->v_bufobj.bo_ops = &buf_ops_bio;
1680 if (mp == NULL && vops != &dead_vnodeops)
1681 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1685 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1686 mac_vnode_associate_singlelabel(mp, vp);
1689 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1690 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1691 vp->v_vflag |= VV_NOKNOTE;
1695 * For the filesystems which do not use vfs_hash_insert(),
1696 * still initialize v_hash to have vfs_hash_index() useful.
1697 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1700 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1707 freevnode(struct vnode *vp)
1712 * The vnode has been marked for destruction, so free it.
1714 * The vnode will be returned to the zone where it will
1715 * normally remain until it is needed for another vnode. We
1716 * need to cleanup (or verify that the cleanup has already
1717 * been done) any residual data left from its current use
1718 * so as not to contaminate the freshly allocated vnode.
1720 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1721 atomic_subtract_long(&numvnodes, 1);
1723 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
1724 ("cleaned vnode still on the free list."));
1725 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1726 VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
1727 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1728 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1729 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1730 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1731 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1732 ("clean blk trie not empty"));
1733 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1734 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1735 ("dirty blk trie not empty"));
1736 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1737 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1738 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1739 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1740 ("Dangling rangelock waiters"));
1743 mac_vnode_destroy(vp);
1745 if (vp->v_pollinfo != NULL) {
1746 destroy_vpollinfo(vp->v_pollinfo);
1747 vp->v_pollinfo = NULL;
1750 /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
1753 vp->v_mountedhere = NULL;
1756 vp->v_fifoinfo = NULL;
1757 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
1762 uma_zfree(vnode_zone, vp);
1766 * Delete from old mount point vnode list, if on one.
1769 delmntque(struct vnode *vp)
1778 KASSERT(mp->mnt_activevnodelistsize <= mp->mnt_nvnodelistsize,
1779 ("Active vnode list size %d > Vnode list size %d",
1780 mp->mnt_activevnodelistsize, mp->mnt_nvnodelistsize));
1781 if (vp->v_iflag & VI_ACTIVE) {
1782 vp->v_iflag &= ~VI_ACTIVE;
1783 mtx_lock(&mp->mnt_listmtx);
1784 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp, v_actfreelist);
1785 mp->mnt_activevnodelistsize--;
1786 mtx_unlock(&mp->mnt_listmtx);
1790 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1791 ("bad mount point vnode list size"));
1792 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1793 mp->mnt_nvnodelistsize--;
1799 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1803 vp->v_op = &dead_vnodeops;
1809 * Insert into list of vnodes for the new mount point, if available.
1812 insmntque1(struct vnode *vp, struct mount *mp,
1813 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1816 KASSERT(vp->v_mount == NULL,
1817 ("insmntque: vnode already on per mount vnode list"));
1818 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1819 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1822 * We acquire the vnode interlock early to ensure that the
1823 * vnode cannot be recycled by another process releasing a
1824 * holdcnt on it before we get it on both the vnode list
1825 * and the active vnode list. The mount mutex protects only
1826 * manipulation of the vnode list and the vnode freelist
1827 * mutex protects only manipulation of the active vnode list.
1828 * Hence the need to hold the vnode interlock throughout.
1832 if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1833 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1834 mp->mnt_nvnodelistsize == 0)) &&
1835 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1844 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1845 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1846 ("neg mount point vnode list size"));
1847 mp->mnt_nvnodelistsize++;
1848 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1849 ("Activating already active vnode"));
1850 vp->v_iflag |= VI_ACTIVE;
1851 mtx_lock(&mp->mnt_listmtx);
1852 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
1853 mp->mnt_activevnodelistsize++;
1854 mtx_unlock(&mp->mnt_listmtx);
1861 insmntque(struct vnode *vp, struct mount *mp)
1864 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1868 * Flush out and invalidate all buffers associated with a bufobj
1869 * Called with the underlying object locked.
1872 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1877 if (flags & V_SAVE) {
1878 error = bufobj_wwait(bo, slpflag, slptimeo);
1883 if (bo->bo_dirty.bv_cnt > 0) {
1885 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1888 * XXX We could save a lock/unlock if this was only
1889 * enabled under INVARIANTS
1892 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1893 panic("vinvalbuf: dirty bufs");
1897 * If you alter this loop please notice that interlock is dropped and
1898 * reacquired in flushbuflist. Special care is needed to ensure that
1899 * no race conditions occur from this.
1902 error = flushbuflist(&bo->bo_clean,
1903 flags, bo, slpflag, slptimeo);
1904 if (error == 0 && !(flags & V_CLEANONLY))
1905 error = flushbuflist(&bo->bo_dirty,
1906 flags, bo, slpflag, slptimeo);
1907 if (error != 0 && error != EAGAIN) {
1911 } while (error != 0);
1914 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1915 * have write I/O in-progress but if there is a VM object then the
1916 * VM object can also have read-I/O in-progress.
1919 bufobj_wwait(bo, 0, 0);
1920 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
1922 vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
1925 } while (bo->bo_numoutput > 0);
1929 * Destroy the copy in the VM cache, too.
1931 if (bo->bo_object != NULL &&
1932 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1933 VM_OBJECT_WLOCK(bo->bo_object);
1934 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1935 OBJPR_CLEANONLY : 0);
1936 VM_OBJECT_WUNLOCK(bo->bo_object);
1941 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1942 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1943 bo->bo_clean.bv_cnt > 0))
1944 panic("vinvalbuf: flush failed");
1945 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1946 bo->bo_dirty.bv_cnt > 0)
1947 panic("vinvalbuf: flush dirty failed");
1954 * Flush out and invalidate all buffers associated with a vnode.
1955 * Called with the underlying object locked.
1958 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1961 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1962 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1963 if (vp->v_object != NULL && vp->v_object->handle != vp)
1965 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1969 * Flush out buffers on the specified list.
1973 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1976 struct buf *bp, *nbp;
1981 ASSERT_BO_WLOCKED(bo);
1984 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1986 * If we are flushing both V_NORMAL and V_ALT buffers then
1987 * do not skip any buffers. If we are flushing only V_NORMAL
1988 * buffers then skip buffers marked as BX_ALTDATA. If we are
1989 * flushing only V_ALT buffers then skip buffers not marked
1992 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
1993 (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
1994 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
1998 lblkno = nbp->b_lblkno;
1999 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2002 error = BUF_TIMELOCK(bp,
2003 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2004 "flushbuf", slpflag, slptimeo);
2007 return (error != ENOLCK ? error : EAGAIN);
2009 KASSERT(bp->b_bufobj == bo,
2010 ("bp %p wrong b_bufobj %p should be %p",
2011 bp, bp->b_bufobj, bo));
2013 * XXX Since there are no node locks for NFS, I
2014 * believe there is a slight chance that a delayed
2015 * write will occur while sleeping just above, so
2018 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2021 bp->b_flags |= B_ASYNC;
2024 return (EAGAIN); /* XXX: why not loop ? */
2027 bp->b_flags |= (B_INVAL | B_RELBUF);
2028 bp->b_flags &= ~B_ASYNC;
2033 nbp = gbincore(bo, lblkno);
2034 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2036 break; /* nbp invalid */
2042 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2048 ASSERT_BO_LOCKED(bo);
2050 for (lblkno = startn;;) {
2052 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2053 if (bp == NULL || bp->b_lblkno >= endn ||
2054 bp->b_lblkno < startn)
2056 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2057 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2060 if (error == ENOLCK)
2064 KASSERT(bp->b_bufobj == bo,
2065 ("bp %p wrong b_bufobj %p should be %p",
2066 bp, bp->b_bufobj, bo));
2067 lblkno = bp->b_lblkno + 1;
2068 if ((bp->b_flags & B_MANAGED) == 0)
2070 bp->b_flags |= B_RELBUF;
2072 * In the VMIO case, use the B_NOREUSE flag to hint that the
2073 * pages backing each buffer in the range are unlikely to be
2074 * reused. Dirty buffers will have the hint applied once
2075 * they've been written.
2077 if ((bp->b_flags & B_VMIO) != 0)
2078 bp->b_flags |= B_NOREUSE;
2086 * Truncate a file's buffer and pages to a specified length. This
2087 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2091 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2093 struct buf *bp, *nbp;
2097 CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2098 vp, blksize, (uintmax_t)length);
2101 * Round up to the *next* lbn.
2103 startlbn = howmany(length, blksize);
2105 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2111 while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2116 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2117 if (bp->b_lblkno > 0)
2120 * Since we hold the vnode lock this should only
2121 * fail if we're racing with the buf daemon.
2124 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2125 BO_LOCKPTR(bo)) == ENOLCK)
2126 goto restart_unlocked;
2128 VNASSERT((bp->b_flags & B_DELWRI), vp,
2129 ("buf(%p) on dirty queue without DELWRI", bp));
2138 bufobj_wwait(bo, 0, 0);
2140 vnode_pager_setsize(vp, length);
2146 * Invalidate the cached pages of a file's buffer within the range of block
2147 * numbers [startlbn, endlbn).
2150 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2156 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2158 start = blksize * startlbn;
2159 end = blksize * endlbn;
2163 MPASS(blksize == bo->bo_bsize);
2165 while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2169 vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2173 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2174 daddr_t startlbn, daddr_t endlbn)
2176 struct buf *bp, *nbp;
2179 ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2180 ASSERT_BO_LOCKED(bo);
2184 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2185 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2188 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2189 BO_LOCKPTR(bo)) == ENOLCK) {
2195 bp->b_flags |= B_INVAL | B_RELBUF;
2196 bp->b_flags &= ~B_ASYNC;
2202 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2204 (nbp->b_flags & B_DELWRI) != 0))
2208 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2209 if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2212 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2213 BO_LOCKPTR(bo)) == ENOLCK) {
2218 bp->b_flags |= B_INVAL | B_RELBUF;
2219 bp->b_flags &= ~B_ASYNC;
2225 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2226 (nbp->b_vp != vp) ||
2227 (nbp->b_flags & B_DELWRI) == 0))
2235 buf_vlist_remove(struct buf *bp)
2239 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2240 ASSERT_BO_WLOCKED(bp->b_bufobj);
2241 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
2242 (BX_VNDIRTY|BX_VNCLEAN),
2243 ("buf_vlist_remove: Buf %p is on two lists", bp));
2244 if (bp->b_xflags & BX_VNDIRTY)
2245 bv = &bp->b_bufobj->bo_dirty;
2247 bv = &bp->b_bufobj->bo_clean;
2248 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2249 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2251 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2255 * Add the buffer to the sorted clean or dirty block list.
2257 * NOTE: xflags is passed as a constant, optimizing this inline function!
2260 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2266 ASSERT_BO_WLOCKED(bo);
2267 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2268 ("dead bo %p", bo));
2269 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2270 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2271 bp->b_xflags |= xflags;
2272 if (xflags & BX_VNDIRTY)
2278 * Keep the list ordered. Optimize empty list insertion. Assume
2279 * we tend to grow at the tail so lookup_le should usually be cheaper
2282 if (bv->bv_cnt == 0 ||
2283 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2284 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2285 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2286 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2288 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2289 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2291 panic("buf_vlist_add: Preallocated nodes insufficient.");
2296 * Look up a buffer using the buffer tries.
2299 gbincore(struct bufobj *bo, daddr_t lblkno)
2303 ASSERT_BO_LOCKED(bo);
2304 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2307 return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
2311 * Associate a buffer with a vnode.
2314 bgetvp(struct vnode *vp, struct buf *bp)
2319 ASSERT_BO_WLOCKED(bo);
2320 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2322 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2323 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2324 ("bgetvp: bp already attached! %p", bp));
2330 * Insert onto list for new vnode.
2332 buf_vlist_add(bp, bo, BX_VNCLEAN);
2336 * Disassociate a buffer from a vnode.
2339 brelvp(struct buf *bp)
2344 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2345 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2348 * Delete from old vnode list, if on one.
2350 vp = bp->b_vp; /* XXX */
2353 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2354 buf_vlist_remove(bp);
2356 panic("brelvp: Buffer %p not on queue.", bp);
2357 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2358 bo->bo_flag &= ~BO_ONWORKLST;
2359 mtx_lock(&sync_mtx);
2360 LIST_REMOVE(bo, bo_synclist);
2361 syncer_worklist_len--;
2362 mtx_unlock(&sync_mtx);
2365 bp->b_bufobj = NULL;
2371 * Add an item to the syncer work queue.
2374 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2378 ASSERT_BO_WLOCKED(bo);
2380 mtx_lock(&sync_mtx);
2381 if (bo->bo_flag & BO_ONWORKLST)
2382 LIST_REMOVE(bo, bo_synclist);
2384 bo->bo_flag |= BO_ONWORKLST;
2385 syncer_worklist_len++;
2388 if (delay > syncer_maxdelay - 2)
2389 delay = syncer_maxdelay - 2;
2390 slot = (syncer_delayno + delay) & syncer_mask;
2392 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2393 mtx_unlock(&sync_mtx);
2397 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2401 mtx_lock(&sync_mtx);
2402 len = syncer_worklist_len - sync_vnode_count;
2403 mtx_unlock(&sync_mtx);
2404 error = SYSCTL_OUT(req, &len, sizeof(len));
2408 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
2409 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2411 static struct proc *updateproc;
2412 static void sched_sync(void);
2413 static struct kproc_desc up_kp = {
2418 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2421 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2426 *bo = LIST_FIRST(slp);
2430 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2433 * We use vhold in case the vnode does not
2434 * successfully sync. vhold prevents the vnode from
2435 * going away when we unlock the sync_mtx so that
2436 * we can acquire the vnode interlock.
2439 mtx_unlock(&sync_mtx);
2441 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2443 mtx_lock(&sync_mtx);
2444 return (*bo == LIST_FIRST(slp));
2446 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2447 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2449 vn_finished_write(mp);
2451 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2453 * Put us back on the worklist. The worklist
2454 * routine will remove us from our current
2455 * position and then add us back in at a later
2458 vn_syncer_add_to_worklist(*bo, syncdelay);
2462 mtx_lock(&sync_mtx);
2466 static int first_printf = 1;
2469 * System filesystem synchronizer daemon.
2474 struct synclist *next, *slp;
2477 struct thread *td = curthread;
2479 int net_worklist_len;
2480 int syncer_final_iter;
2484 syncer_final_iter = 0;
2485 syncer_state = SYNCER_RUNNING;
2486 starttime = time_uptime;
2487 td->td_pflags |= TDP_NORUNNINGBUF;
2489 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2492 mtx_lock(&sync_mtx);
2494 if (syncer_state == SYNCER_FINAL_DELAY &&
2495 syncer_final_iter == 0) {
2496 mtx_unlock(&sync_mtx);
2497 kproc_suspend_check(td->td_proc);
2498 mtx_lock(&sync_mtx);
2500 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2501 if (syncer_state != SYNCER_RUNNING &&
2502 starttime != time_uptime) {
2504 printf("\nSyncing disks, vnodes remaining... ");
2507 printf("%d ", net_worklist_len);
2509 starttime = time_uptime;
2512 * Push files whose dirty time has expired. Be careful
2513 * of interrupt race on slp queue.
2515 * Skip over empty worklist slots when shutting down.
2518 slp = &syncer_workitem_pending[syncer_delayno];
2519 syncer_delayno += 1;
2520 if (syncer_delayno == syncer_maxdelay)
2522 next = &syncer_workitem_pending[syncer_delayno];
2524 * If the worklist has wrapped since the
2525 * it was emptied of all but syncer vnodes,
2526 * switch to the FINAL_DELAY state and run
2527 * for one more second.
2529 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2530 net_worklist_len == 0 &&
2531 last_work_seen == syncer_delayno) {
2532 syncer_state = SYNCER_FINAL_DELAY;
2533 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2535 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2536 syncer_worklist_len > 0);
2539 * Keep track of the last time there was anything
2540 * on the worklist other than syncer vnodes.
2541 * Return to the SHUTTING_DOWN state if any
2544 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2545 last_work_seen = syncer_delayno;
2546 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2547 syncer_state = SYNCER_SHUTTING_DOWN;
2548 while (!LIST_EMPTY(slp)) {
2549 error = sync_vnode(slp, &bo, td);
2551 LIST_REMOVE(bo, bo_synclist);
2552 LIST_INSERT_HEAD(next, bo, bo_synclist);
2556 if (first_printf == 0) {
2558 * Drop the sync mutex, because some watchdog
2559 * drivers need to sleep while patting
2561 mtx_unlock(&sync_mtx);
2562 wdog_kern_pat(WD_LASTVAL);
2563 mtx_lock(&sync_mtx);
2567 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2568 syncer_final_iter--;
2570 * The variable rushjob allows the kernel to speed up the
2571 * processing of the filesystem syncer process. A rushjob
2572 * value of N tells the filesystem syncer to process the next
2573 * N seconds worth of work on its queue ASAP. Currently rushjob
2574 * is used by the soft update code to speed up the filesystem
2575 * syncer process when the incore state is getting so far
2576 * ahead of the disk that the kernel memory pool is being
2577 * threatened with exhaustion.
2584 * Just sleep for a short period of time between
2585 * iterations when shutting down to allow some I/O
2588 * If it has taken us less than a second to process the
2589 * current work, then wait. Otherwise start right over
2590 * again. We can still lose time if any single round
2591 * takes more than two seconds, but it does not really
2592 * matter as we are just trying to generally pace the
2593 * filesystem activity.
2595 if (syncer_state != SYNCER_RUNNING ||
2596 time_uptime == starttime) {
2598 sched_prio(td, PPAUSE);
2601 if (syncer_state != SYNCER_RUNNING)
2602 cv_timedwait(&sync_wakeup, &sync_mtx,
2603 hz / SYNCER_SHUTDOWN_SPEEDUP);
2604 else if (time_uptime == starttime)
2605 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2610 * Request the syncer daemon to speed up its work.
2611 * We never push it to speed up more than half of its
2612 * normal turn time, otherwise it could take over the cpu.
2615 speedup_syncer(void)
2619 mtx_lock(&sync_mtx);
2620 if (rushjob < syncdelay / 2) {
2622 stat_rush_requests += 1;
2625 mtx_unlock(&sync_mtx);
2626 cv_broadcast(&sync_wakeup);
2631 * Tell the syncer to speed up its work and run though its work
2632 * list several times, then tell it to shut down.
2635 syncer_shutdown(void *arg, int howto)
2638 if (howto & RB_NOSYNC)
2640 mtx_lock(&sync_mtx);
2641 syncer_state = SYNCER_SHUTTING_DOWN;
2643 mtx_unlock(&sync_mtx);
2644 cv_broadcast(&sync_wakeup);
2645 kproc_shutdown(arg, howto);
2649 syncer_suspend(void)
2652 syncer_shutdown(updateproc, 0);
2659 mtx_lock(&sync_mtx);
2661 syncer_state = SYNCER_RUNNING;
2662 mtx_unlock(&sync_mtx);
2663 cv_broadcast(&sync_wakeup);
2664 kproc_resume(updateproc);
2668 * Reassign a buffer from one vnode to another.
2669 * Used to assign file specific control information
2670 * (indirect blocks) to the vnode to which they belong.
2673 reassignbuf(struct buf *bp)
2686 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2687 bp, bp->b_vp, bp->b_flags);
2689 * B_PAGING flagged buffers cannot be reassigned because their vp
2690 * is not fully linked in.
2692 if (bp->b_flags & B_PAGING)
2693 panic("cannot reassign paging buffer");
2696 * Delete from old vnode list, if on one.
2699 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2700 buf_vlist_remove(bp);
2702 panic("reassignbuf: Buffer %p not on queue.", bp);
2704 * If dirty, put on list of dirty buffers; otherwise insert onto list
2707 if (bp->b_flags & B_DELWRI) {
2708 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2709 switch (vp->v_type) {
2719 vn_syncer_add_to_worklist(bo, delay);
2721 buf_vlist_add(bp, bo, BX_VNDIRTY);
2723 buf_vlist_add(bp, bo, BX_VNCLEAN);
2725 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2726 mtx_lock(&sync_mtx);
2727 LIST_REMOVE(bo, bo_synclist);
2728 syncer_worklist_len--;
2729 mtx_unlock(&sync_mtx);
2730 bo->bo_flag &= ~BO_ONWORKLST;
2735 bp = TAILQ_FIRST(&bv->bv_hd);
2736 KASSERT(bp == NULL || bp->b_bufobj == bo,
2737 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2738 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2739 KASSERT(bp == NULL || bp->b_bufobj == bo,
2740 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2742 bp = TAILQ_FIRST(&bv->bv_hd);
2743 KASSERT(bp == NULL || bp->b_bufobj == bo,
2744 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2745 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2746 KASSERT(bp == NULL || bp->b_bufobj == bo,
2747 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2753 v_init_counters(struct vnode *vp)
2756 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2757 vp, ("%s called for an initialized vnode", __FUNCTION__));
2758 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2760 refcount_init(&vp->v_holdcnt, 1);
2761 refcount_init(&vp->v_usecount, 1);
2765 * Increment si_usecount of the associated device, if any.
2768 v_incr_devcount(struct vnode *vp)
2771 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2772 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2774 vp->v_rdev->si_usecount++;
2780 * Decrement si_usecount of the associated device, if any.
2783 v_decr_devcount(struct vnode *vp)
2786 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2787 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2789 vp->v_rdev->si_usecount--;
2795 * Grab a particular vnode from the free list, increment its
2796 * reference count and lock it. VIRF_DOOMED is set if the vnode
2797 * is being destroyed. Only callers who specify LK_RETRY will
2798 * see doomed vnodes. If inactive processing was delayed in
2799 * vput try to do it here.
2801 * Both holdcnt and usecount can be manipulated using atomics without holding
2802 * any locks except in these cases which require the vnode interlock:
2803 * holdcnt: 1->0 and 0->1
2806 * usecount is permitted to transition 1->0 without the interlock because
2807 * vnode is kept live by holdcnt.
2809 static enum vgetstate __always_inline
2810 _vget_prep(struct vnode *vp, bool interlock)
2814 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2827 vget_prep(struct vnode *vp)
2830 return (_vget_prep(vp, false));
2834 vget(struct vnode *vp, int flags, struct thread *td)
2838 MPASS(td == curthread);
2840 vs = _vget_prep(vp, (flags & LK_INTERLOCK) != 0);
2841 return (vget_finish(vp, flags, vs));
2845 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
2847 int error, oweinact;
2849 VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2850 ("%s: invalid lock operation", __func__));
2852 if ((flags & LK_INTERLOCK) != 0)
2853 ASSERT_VI_LOCKED(vp, __func__);
2855 ASSERT_VI_UNLOCKED(vp, __func__);
2856 VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
2857 if (vs == VGET_USECOUNT) {
2858 VNASSERT(vp->v_usecount > 0, vp,
2859 ("%s: vnode without usecount when VGET_USECOUNT was passed",
2863 if ((error = vn_lock(vp, flags)) != 0) {
2864 if (vs == VGET_USECOUNT)
2868 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2873 if (vs == VGET_USECOUNT) {
2874 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2875 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2880 * We hold the vnode. If the usecount is 0 it will be utilized to keep
2881 * the vnode around. Otherwise someone else lended their hold count and
2882 * we have to drop ours.
2884 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2886 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2887 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2889 refcount_release(&vp->v_holdcnt);
2891 VNODE_REFCOUNT_FENCE_ACQ();
2892 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2893 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2898 * We don't guarantee that any particular close will
2899 * trigger inactive processing so just make a best effort
2900 * here at preventing a reference to a removed file. If
2901 * we don't succeed no harm is done.
2903 * Upgrade our holdcnt to a usecount.
2907 * See the previous section. By the time we get here we may find
2908 * ourselves in the same spot.
2910 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2912 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2913 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2915 refcount_release(&vp->v_holdcnt);
2917 VNODE_REFCOUNT_FENCE_ACQ();
2918 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2919 ("%s: vnode with usecount and VI_OWEINACT set",
2924 if ((vp->v_iflag & VI_OWEINACT) == 0) {
2928 vp->v_iflag &= ~VI_OWEINACT;
2929 VNODE_REFCOUNT_FENCE_REL();
2931 v_incr_devcount(vp);
2932 refcount_acquire(&vp->v_usecount);
2933 if (oweinact && VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2934 (flags & LK_NOWAIT) == 0)
2941 * Increase the reference (use) and hold count of a vnode.
2942 * This will also remove the vnode from the free list if it is presently free.
2945 vref(struct vnode *vp)
2948 ASSERT_VI_UNLOCKED(vp, __func__);
2949 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2950 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2951 VNODE_REFCOUNT_FENCE_ACQ();
2952 VNASSERT(vp->v_holdcnt > 0, vp,
2953 ("%s: active vnode not held", __func__));
2954 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2955 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2964 vrefl(struct vnode *vp)
2967 ASSERT_VI_LOCKED(vp, __func__);
2968 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2969 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2970 VNODE_REFCOUNT_FENCE_ACQ();
2971 VNASSERT(vp->v_holdcnt > 0, vp,
2972 ("%s: active vnode not held", __func__));
2973 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2974 ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2978 if ((vp->v_iflag & VI_OWEINACT) != 0) {
2979 vp->v_iflag &= ~VI_OWEINACT;
2980 VNODE_REFCOUNT_FENCE_REL();
2982 v_incr_devcount(vp);
2983 refcount_acquire(&vp->v_usecount);
2987 vrefact(struct vnode *vp)
2990 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2992 int old = atomic_fetchadd_int(&vp->v_usecount, 1);
2993 VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
2995 refcount_acquire(&vp->v_usecount);
3000 * Return reference count of a vnode.
3002 * The results of this call are only guaranteed when some mechanism is used to
3003 * stop other processes from gaining references to the vnode. This may be the
3004 * case if the caller holds the only reference. This is also useful when stale
3005 * data is acceptable as race conditions may be accounted for by some other
3009 vrefcnt(struct vnode *vp)
3012 return (vp->v_usecount);
3015 enum vputx_op { VPUTX_VRELE, VPUTX_VPUT, VPUTX_VUNREF };
3018 * Decrement the use and hold counts for a vnode.
3020 * See an explanation near vget() as to why atomic operation is safe.
3023 vputx(struct vnode *vp, enum vputx_op func)
3027 KASSERT(vp != NULL, ("vputx: null vp"));
3028 if (func == VPUTX_VUNREF)
3029 ASSERT_VOP_LOCKED(vp, "vunref");
3030 ASSERT_VI_UNLOCKED(vp, __func__);
3031 VNASSERT(vp->v_holdcnt > 0 && vp->v_usecount > 0, vp,
3032 ("%s: wrong ref counts", __func__));
3034 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3037 * We want to hold the vnode until the inactive finishes to
3038 * prevent vgone() races. We drop the use count here and the
3039 * hold count below when we're done.
3041 * If we release the last usecount we take ownership of the hold
3042 * count which provides liveness of the vnode, in which case we
3045 if (!refcount_release(&vp->v_usecount))
3048 v_decr_devcount(vp);
3050 * By the time we got here someone else might have transitioned
3051 * the count back to > 0.
3053 if (vp->v_usecount > 0) {
3057 if (vp->v_iflag & VI_DOINGINACT) {
3063 * Check if the fs wants to perform inactive processing. Note we
3064 * may be only holding the interlock, in which case it is possible
3065 * someone else called vgone on the vnode and ->v_data is now NULL.
3066 * Since vgone performs inactive on its own there is nothing to do
3067 * here but to drop our hold count.
3069 if (__predict_false(VN_IS_DOOMED(vp)) ||
3070 VOP_NEED_INACTIVE(vp) == 0) {
3076 * We must call VOP_INACTIVE with the node locked. Mark
3077 * as VI_DOINGINACT to avoid recursion.
3079 vp->v_iflag |= VI_OWEINACT;
3082 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3086 error = VOP_LOCK(vp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT);
3091 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3092 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3097 VNASSERT(vp->v_usecount == 0 || (vp->v_iflag & VI_OWEINACT) == 0, vp,
3098 ("vnode with usecount and VI_OWEINACT set"));
3100 if (vp->v_iflag & VI_OWEINACT)
3102 if (func != VPUTX_VUNREF)
3109 * Vnode put/release.
3110 * If count drops to zero, call inactive routine and return to freelist.
3113 vrele(struct vnode *vp)
3116 vputx(vp, VPUTX_VRELE);
3120 * Release an already locked vnode. This give the same effects as
3121 * unlock+vrele(), but takes less time and avoids releasing and
3122 * re-aquiring the lock (as vrele() acquires the lock internally.)
3124 * It is an invariant that all VOP_* calls operate on a held vnode.
3125 * We may be only having an implicit hold stemming from our usecount,
3126 * which we are about to release. If we unlock the vnode afterwards we
3127 * open a time window where someone else dropped the last usecount and
3128 * proceeded to free the vnode before our unlock finished. For this
3129 * reason we unlock the vnode early. This is a little bit wasteful as
3130 * it may be the vnode is exclusively locked and inactive processing is
3131 * needed, in which case we are adding work.
3134 vput(struct vnode *vp)
3138 vputx(vp, VPUTX_VPUT);
3142 * Release an exclusively locked vnode. Do not unlock the vnode lock.
3145 vunref(struct vnode *vp)
3148 vputx(vp, VPUTX_VUNREF);
3152 * Increase the hold count and activate if this is the first reference.
3155 vhold_activate(struct vnode *vp)
3159 ASSERT_VI_LOCKED(vp, __func__);
3160 VNASSERT(vp->v_holdcnt == 0, vp,
3161 ("%s: wrong hold count", __func__));
3162 VNASSERT(vp->v_op != NULL, vp,
3163 ("%s: vnode already reclaimed.", __func__));
3165 * Remove a vnode from the free list, mark it as in use,
3166 * and put it on the active list.
3168 VNASSERT(vp->v_mount != NULL, vp,
3169 ("_vhold: vnode not on per mount vnode list"));
3171 mtx_lock(&mp->mnt_listmtx);
3172 if ((vp->v_mflag & VMP_TMPMNTFREELIST) != 0) {
3173 TAILQ_REMOVE(&mp->mnt_tmpfreevnodelist, vp, v_actfreelist);
3174 mp->mnt_tmpfreevnodelistsize--;
3175 vp->v_mflag &= ~VMP_TMPMNTFREELIST;
3177 mtx_lock(&vnode_free_list_mtx);
3178 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
3180 mtx_unlock(&vnode_free_list_mtx);
3182 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
3183 ("Activating already active vnode"));
3184 vp->v_iflag &= ~VI_FREE;
3185 vp->v_iflag |= VI_ACTIVE;
3186 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
3187 mp->mnt_activevnodelistsize++;
3188 mtx_unlock(&mp->mnt_listmtx);
3189 refcount_acquire(&vp->v_holdcnt);
3193 vhold(struct vnode *vp)
3196 ASSERT_VI_UNLOCKED(vp, __func__);
3197 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3198 if (refcount_acquire_if_not_zero(&vp->v_holdcnt)) {
3199 VNODE_REFCOUNT_FENCE_ACQ();
3200 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
3201 ("vhold: vnode with holdcnt is free"));
3210 vholdl(struct vnode *vp)
3213 ASSERT_VI_LOCKED(vp, __func__);
3214 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3215 if ((vp->v_iflag & VI_FREE) == 0) {
3216 refcount_acquire(&vp->v_holdcnt);
3223 vholdnz(struct vnode *vp)
3226 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3228 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3229 VNASSERT(old > 0, vp, ("%s: wrong hold count %d", __func__, old));
3231 atomic_add_int(&vp->v_holdcnt, 1);
3236 * Drop the hold count of the vnode. If this is the last reference to
3237 * the vnode we place it on the free list unless it has been vgone'd
3238 * (marked VIRF_DOOMED) in which case we will free it.
3240 * Because the vnode vm object keeps a hold reference on the vnode if
3241 * there is at least one resident non-cached page, the vnode cannot
3242 * leave the active list without the page cleanup done.
3245 vdrop_deactivate(struct vnode *vp)
3249 ASSERT_VI_LOCKED(vp, __func__);
3251 * Mark a vnode as free: remove it from its active list
3252 * and put it up for recycling on the freelist.
3254 VNASSERT(!VN_IS_DOOMED(vp), vp,
3255 ("vdrop: returning doomed vnode"));
3256 VNASSERT(vp->v_op != NULL, vp,
3257 ("vdrop: vnode already reclaimed."));
3258 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
3259 ("vnode already free"));
3260 VNASSERT(vp->v_holdcnt == 0, vp,
3261 ("vdrop: freeing when we shouldn't"));
3262 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3264 mtx_lock(&mp->mnt_listmtx);
3265 if (vp->v_iflag & VI_ACTIVE) {
3266 vp->v_iflag &= ~VI_ACTIVE;
3267 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp, v_actfreelist);
3268 mp->mnt_activevnodelistsize--;
3270 TAILQ_INSERT_TAIL(&mp->mnt_tmpfreevnodelist, vp, v_actfreelist);
3271 mp->mnt_tmpfreevnodelistsize++;
3272 vp->v_iflag |= VI_FREE;
3273 vp->v_mflag |= VMP_TMPMNTFREELIST;
3275 if (mp->mnt_tmpfreevnodelistsize >= mnt_free_list_batch)
3276 vnlru_return_batch_locked(mp);
3277 mtx_unlock(&mp->mnt_listmtx);
3280 counter_u64_add(free_owe_inact, 1);
3285 vdrop(struct vnode *vp)
3288 ASSERT_VI_UNLOCKED(vp, __func__);
3289 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3290 if (refcount_release_if_not_last(&vp->v_holdcnt))
3297 vdropl(struct vnode *vp)
3300 ASSERT_VI_LOCKED(vp, __func__);
3301 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3302 if (!refcount_release(&vp->v_holdcnt)) {
3306 if (VN_IS_DOOMED(vp)) {
3310 vdrop_deactivate(vp);
3314 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3315 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
3316 * OWEINACT tracks whether a vnode missed a call to inactive due to a
3317 * failed lock upgrade.
3320 vinactive(struct vnode *vp)
3322 struct vm_object *obj;
3324 ASSERT_VOP_ELOCKED(vp, "vinactive");
3325 ASSERT_VI_LOCKED(vp, "vinactive");
3326 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3327 ("vinactive: recursed on VI_DOINGINACT"));
3328 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3329 vp->v_iflag |= VI_DOINGINACT;
3330 vp->v_iflag &= ~VI_OWEINACT;
3333 * Before moving off the active list, we must be sure that any
3334 * modified pages are converted into the vnode's dirty
3335 * buffers, since these will no longer be checked once the
3336 * vnode is on the inactive list.
3338 * The write-out of the dirty pages is asynchronous. At the
3339 * point that VOP_INACTIVE() is called, there could still be
3340 * pending I/O and dirty pages in the object.
3342 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3343 vm_object_mightbedirty(obj)) {
3344 VM_OBJECT_WLOCK(obj);
3345 vm_object_page_clean(obj, 0, 0, 0);
3346 VM_OBJECT_WUNLOCK(obj);
3348 VOP_INACTIVE(vp, curthread);
3350 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3351 ("vinactive: lost VI_DOINGINACT"));
3352 vp->v_iflag &= ~VI_DOINGINACT;
3356 * Remove any vnodes in the vnode table belonging to mount point mp.
3358 * If FORCECLOSE is not specified, there should not be any active ones,
3359 * return error if any are found (nb: this is a user error, not a
3360 * system error). If FORCECLOSE is specified, detach any active vnodes
3363 * If WRITECLOSE is set, only flush out regular file vnodes open for
3366 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3368 * `rootrefs' specifies the base reference count for the root vnode
3369 * of this filesystem. The root vnode is considered busy if its
3370 * v_usecount exceeds this value. On a successful return, vflush(, td)
3371 * will call vrele() on the root vnode exactly rootrefs times.
3372 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3376 static int busyprt = 0; /* print out busy vnodes */
3377 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3381 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3383 struct vnode *vp, *mvp, *rootvp = NULL;
3385 int busy = 0, error;
3387 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3390 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3391 ("vflush: bad args"));
3393 * Get the filesystem root vnode. We can vput() it
3394 * immediately, since with rootrefs > 0, it won't go away.
3396 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3397 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3404 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3406 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3409 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3413 * Skip over a vnodes marked VV_SYSTEM.
3415 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3421 * If WRITECLOSE is set, flush out unlinked but still open
3422 * files (even if open only for reading) and regular file
3423 * vnodes open for writing.
3425 if (flags & WRITECLOSE) {
3426 if (vp->v_object != NULL) {
3427 VM_OBJECT_WLOCK(vp->v_object);
3428 vm_object_page_clean(vp->v_object, 0, 0, 0);
3429 VM_OBJECT_WUNLOCK(vp->v_object);
3431 error = VOP_FSYNC(vp, MNT_WAIT, td);
3435 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3438 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3441 if ((vp->v_type == VNON ||
3442 (error == 0 && vattr.va_nlink > 0)) &&
3443 (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3451 * With v_usecount == 0, all we need to do is clear out the
3452 * vnode data structures and we are done.
3454 * If FORCECLOSE is set, forcibly close the vnode.
3456 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3462 vn_printf(vp, "vflush: busy vnode ");
3468 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3470 * If just the root vnode is busy, and if its refcount
3471 * is equal to `rootrefs', then go ahead and kill it.
3474 KASSERT(busy > 0, ("vflush: not busy"));
3475 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3476 ("vflush: usecount %d < rootrefs %d",
3477 rootvp->v_usecount, rootrefs));
3478 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3479 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3487 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3491 for (; rootrefs > 0; rootrefs--)
3497 * Recycle an unused vnode to the front of the free list.
3500 vrecycle(struct vnode *vp)
3505 recycled = vrecyclel(vp);
3511 * vrecycle, with the vp interlock held.
3514 vrecyclel(struct vnode *vp)
3518 ASSERT_VOP_ELOCKED(vp, __func__);
3519 ASSERT_VI_LOCKED(vp, __func__);
3520 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3522 if (vp->v_usecount == 0) {
3530 * Eliminate all activity associated with a vnode
3531 * in preparation for reuse.
3534 vgone(struct vnode *vp)
3542 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3543 struct vnode *lowervp __unused)
3548 * Notify upper mounts about reclaimed or unlinked vnode.
3551 vfs_notify_upper(struct vnode *vp, int event)
3553 static struct vfsops vgonel_vfsops = {
3554 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3555 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3557 struct mount *mp, *ump, *mmp;
3562 if (TAILQ_EMPTY(&mp->mnt_uppers))
3565 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3566 mmp->mnt_op = &vgonel_vfsops;
3567 mmp->mnt_kern_flag |= MNTK_MARKER;
3569 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3570 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3571 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3572 ump = TAILQ_NEXT(ump, mnt_upper_link);
3575 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3578 case VFS_NOTIFY_UPPER_RECLAIM:
3579 VFS_RECLAIM_LOWERVP(ump, vp);
3581 case VFS_NOTIFY_UPPER_UNLINK:
3582 VFS_UNLINK_LOWERVP(ump, vp);
3585 KASSERT(0, ("invalid event %d", event));
3589 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3590 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3593 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3594 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3595 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3596 wakeup(&mp->mnt_uppers);
3602 * vgone, with the vp interlock held.
3605 vgonel(struct vnode *vp)
3610 bool active, oweinact;
3612 ASSERT_VOP_ELOCKED(vp, "vgonel");
3613 ASSERT_VI_LOCKED(vp, "vgonel");
3614 VNASSERT(vp->v_holdcnt, vp,
3615 ("vgonel: vp %p has no reference.", vp));
3616 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3620 * Don't vgonel if we're already doomed.
3622 if (vp->v_irflag & VIRF_DOOMED)
3624 vp->v_irflag |= VIRF_DOOMED;
3627 * Check to see if the vnode is in use. If so, we have to call
3628 * VOP_CLOSE() and VOP_INACTIVE().
3630 active = vp->v_usecount > 0;
3631 oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
3633 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
3636 * If purging an active vnode, it must be closed and
3637 * deactivated before being reclaimed.
3640 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
3641 if (oweinact || active) {
3643 if ((vp->v_iflag & VI_DOINGINACT) == 0)
3647 if (vp->v_type == VSOCK)
3648 vfs_unp_reclaim(vp);
3651 * Clean out any buffers associated with the vnode.
3652 * If the flush fails, just toss the buffers.
3655 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
3656 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
3657 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
3658 while (vinvalbuf(vp, 0, 0, 0) != 0)
3662 BO_LOCK(&vp->v_bufobj);
3663 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
3664 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
3665 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
3666 vp->v_bufobj.bo_clean.bv_cnt == 0,
3667 ("vp %p bufobj not invalidated", vp));
3670 * For VMIO bufobj, BO_DEAD is set later, or in
3671 * vm_object_terminate() after the object's page queue is
3674 object = vp->v_bufobj.bo_object;
3676 vp->v_bufobj.bo_flag |= BO_DEAD;
3677 BO_UNLOCK(&vp->v_bufobj);
3680 * Handle the VM part. Tmpfs handles v_object on its own (the
3681 * OBJT_VNODE check). Nullfs or other bypassing filesystems
3682 * should not touch the object borrowed from the lower vnode
3683 * (the handle check).
3685 if (object != NULL && object->type == OBJT_VNODE &&
3686 object->handle == vp)
3687 vnode_destroy_vobject(vp);
3690 * Reclaim the vnode.
3692 if (VOP_RECLAIM(vp, td))
3693 panic("vgone: cannot reclaim");
3695 vn_finished_secondary_write(mp);
3696 VNASSERT(vp->v_object == NULL, vp,
3697 ("vop_reclaim left v_object vp=%p", vp));
3699 * Clear the advisory locks and wake up waiting threads.
3701 (void)VOP_ADVLOCKPURGE(vp);
3704 * Delete from old mount point vnode list.
3709 * Done with purge, reset to the standard lock and invalidate
3713 vp->v_vnlock = &vp->v_lock;
3714 vp->v_op = &dead_vnodeops;
3719 * Calculate the total number of references to a special device.
3722 vcount(struct vnode *vp)
3727 count = vp->v_rdev->si_usecount;
3733 * Print out a description of a vnode.
3735 static char *typename[] =
3736 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
3740 vn_printf(struct vnode *vp, const char *fmt, ...)
3743 char buf[256], buf2[16];
3749 printf("%p: ", (void *)vp);
3750 printf("type %s\n", typename[vp->v_type]);
3751 printf(" usecount %d, writecount %d, refcount %d",
3752 vp->v_usecount, vp->v_writecount, vp->v_holdcnt);
3753 switch (vp->v_type) {
3755 printf(" mountedhere %p\n", vp->v_mountedhere);
3758 printf(" rdev %p\n", vp->v_rdev);
3761 printf(" socket %p\n", vp->v_unpcb);
3764 printf(" fifoinfo %p\n", vp->v_fifoinfo);
3772 if (vp->v_irflag & VIRF_DOOMED)
3773 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
3774 flags = vp->v_irflag & ~(VIRF_DOOMED);
3776 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
3777 strlcat(buf, buf2, sizeof(buf));
3779 if (vp->v_vflag & VV_ROOT)
3780 strlcat(buf, "|VV_ROOT", sizeof(buf));
3781 if (vp->v_vflag & VV_ISTTY)
3782 strlcat(buf, "|VV_ISTTY", sizeof(buf));
3783 if (vp->v_vflag & VV_NOSYNC)
3784 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
3785 if (vp->v_vflag & VV_ETERNALDEV)
3786 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
3787 if (vp->v_vflag & VV_CACHEDLABEL)
3788 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
3789 if (vp->v_vflag & VV_VMSIZEVNLOCK)
3790 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
3791 if (vp->v_vflag & VV_COPYONWRITE)
3792 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
3793 if (vp->v_vflag & VV_SYSTEM)
3794 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
3795 if (vp->v_vflag & VV_PROCDEP)
3796 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
3797 if (vp->v_vflag & VV_NOKNOTE)
3798 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
3799 if (vp->v_vflag & VV_DELETED)
3800 strlcat(buf, "|VV_DELETED", sizeof(buf));
3801 if (vp->v_vflag & VV_MD)
3802 strlcat(buf, "|VV_MD", sizeof(buf));
3803 if (vp->v_vflag & VV_FORCEINSMQ)
3804 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
3805 if (vp->v_vflag & VV_READLINK)
3806 strlcat(buf, "|VV_READLINK", sizeof(buf));
3807 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
3808 VV_CACHEDLABEL | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
3809 VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
3811 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
3812 strlcat(buf, buf2, sizeof(buf));
3814 if (vp->v_iflag & VI_TEXT_REF)
3815 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
3816 if (vp->v_iflag & VI_MOUNT)
3817 strlcat(buf, "|VI_MOUNT", sizeof(buf));
3818 if (vp->v_iflag & VI_FREE)
3819 strlcat(buf, "|VI_FREE", sizeof(buf));
3820 if (vp->v_iflag & VI_ACTIVE)
3821 strlcat(buf, "|VI_ACTIVE", sizeof(buf));
3822 if (vp->v_iflag & VI_DOINGINACT)
3823 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
3824 if (vp->v_iflag & VI_OWEINACT)
3825 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
3826 flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_FREE | VI_ACTIVE |
3827 VI_DOINGINACT | VI_OWEINACT);
3829 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
3830 strlcat(buf, buf2, sizeof(buf));
3832 if (vp->v_mflag & VMP_TMPMNTFREELIST)
3833 strlcat(buf, "|VMP_TMPMNTFREELIST", sizeof(buf));
3834 flags = vp->v_mflag & ~(VMP_TMPMNTFREELIST);
3836 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
3837 strlcat(buf, buf2, sizeof(buf));
3839 printf(" flags (%s)\n", buf + 1);
3840 if (mtx_owned(VI_MTX(vp)))
3841 printf(" VI_LOCKed");
3842 if (vp->v_object != NULL)
3843 printf(" v_object %p ref %d pages %d "
3844 "cleanbuf %d dirtybuf %d\n",
3845 vp->v_object, vp->v_object->ref_count,
3846 vp->v_object->resident_page_count,
3847 vp->v_bufobj.bo_clean.bv_cnt,
3848 vp->v_bufobj.bo_dirty.bv_cnt);
3850 lockmgr_printinfo(vp->v_vnlock);
3851 if (vp->v_data != NULL)
3857 * List all of the locked vnodes in the system.
3858 * Called when debugging the kernel.
3860 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
3866 * Note: because this is DDB, we can't obey the locking semantics
3867 * for these structures, which means we could catch an inconsistent
3868 * state and dereference a nasty pointer. Not much to be done
3871 db_printf("Locked vnodes\n");
3872 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3873 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3874 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
3875 vn_printf(vp, "vnode ");
3881 * Show details about the given vnode.
3883 DB_SHOW_COMMAND(vnode, db_show_vnode)
3889 vp = (struct vnode *)addr;
3890 vn_printf(vp, "vnode ");
3894 * Show details about the given mount point.
3896 DB_SHOW_COMMAND(mount, db_show_mount)
3907 /* No address given, print short info about all mount points. */
3908 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3909 db_printf("%p %s on %s (%s)\n", mp,
3910 mp->mnt_stat.f_mntfromname,
3911 mp->mnt_stat.f_mntonname,
3912 mp->mnt_stat.f_fstypename);
3916 db_printf("\nMore info: show mount <addr>\n");
3920 mp = (struct mount *)addr;
3921 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
3922 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
3925 mflags = mp->mnt_flag;
3926 #define MNT_FLAG(flag) do { \
3927 if (mflags & (flag)) { \
3928 if (buf[0] != '\0') \
3929 strlcat(buf, ", ", sizeof(buf)); \
3930 strlcat(buf, (#flag) + 4, sizeof(buf)); \
3931 mflags &= ~(flag); \
3934 MNT_FLAG(MNT_RDONLY);
3935 MNT_FLAG(MNT_SYNCHRONOUS);
3936 MNT_FLAG(MNT_NOEXEC);
3937 MNT_FLAG(MNT_NOSUID);
3938 MNT_FLAG(MNT_NFS4ACLS);
3939 MNT_FLAG(MNT_UNION);
3940 MNT_FLAG(MNT_ASYNC);
3941 MNT_FLAG(MNT_SUIDDIR);
3942 MNT_FLAG(MNT_SOFTDEP);
3943 MNT_FLAG(MNT_NOSYMFOLLOW);
3944 MNT_FLAG(MNT_GJOURNAL);
3945 MNT_FLAG(MNT_MULTILABEL);
3947 MNT_FLAG(MNT_NOATIME);
3948 MNT_FLAG(MNT_NOCLUSTERR);
3949 MNT_FLAG(MNT_NOCLUSTERW);
3951 MNT_FLAG(MNT_EXRDONLY);
3952 MNT_FLAG(MNT_EXPORTED);
3953 MNT_FLAG(MNT_DEFEXPORTED);
3954 MNT_FLAG(MNT_EXPORTANON);
3955 MNT_FLAG(MNT_EXKERB);
3956 MNT_FLAG(MNT_EXPUBLIC);
3957 MNT_FLAG(MNT_LOCAL);
3958 MNT_FLAG(MNT_QUOTA);
3959 MNT_FLAG(MNT_ROOTFS);
3961 MNT_FLAG(MNT_IGNORE);
3962 MNT_FLAG(MNT_UPDATE);
3963 MNT_FLAG(MNT_DELEXPORT);
3964 MNT_FLAG(MNT_RELOAD);
3965 MNT_FLAG(MNT_FORCE);
3966 MNT_FLAG(MNT_SNAPSHOT);
3967 MNT_FLAG(MNT_BYFSID);
3971 strlcat(buf, ", ", sizeof(buf));
3972 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3973 "0x%016jx", mflags);
3975 db_printf(" mnt_flag = %s\n", buf);
3978 flags = mp->mnt_kern_flag;
3979 #define MNT_KERN_FLAG(flag) do { \
3980 if (flags & (flag)) { \
3981 if (buf[0] != '\0') \
3982 strlcat(buf, ", ", sizeof(buf)); \
3983 strlcat(buf, (#flag) + 5, sizeof(buf)); \
3987 MNT_KERN_FLAG(MNTK_UNMOUNTF);
3988 MNT_KERN_FLAG(MNTK_ASYNC);
3989 MNT_KERN_FLAG(MNTK_SOFTDEP);
3990 MNT_KERN_FLAG(MNTK_DRAINING);
3991 MNT_KERN_FLAG(MNTK_REFEXPIRE);
3992 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
3993 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
3994 MNT_KERN_FLAG(MNTK_NO_IOPF);
3995 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
3996 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
3997 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
3998 MNT_KERN_FLAG(MNTK_MARKER);
3999 MNT_KERN_FLAG(MNTK_USES_BCACHE);
4000 MNT_KERN_FLAG(MNTK_NOASYNC);
4001 MNT_KERN_FLAG(MNTK_UNMOUNT);
4002 MNT_KERN_FLAG(MNTK_MWAIT);
4003 MNT_KERN_FLAG(MNTK_SUSPEND);
4004 MNT_KERN_FLAG(MNTK_SUSPEND2);
4005 MNT_KERN_FLAG(MNTK_SUSPENDED);
4006 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4007 MNT_KERN_FLAG(MNTK_NOKNOTE);
4008 #undef MNT_KERN_FLAG
4011 strlcat(buf, ", ", sizeof(buf));
4012 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4015 db_printf(" mnt_kern_flag = %s\n", buf);
4017 db_printf(" mnt_opt = ");
4018 opt = TAILQ_FIRST(mp->mnt_opt);
4020 db_printf("%s", opt->name);
4021 opt = TAILQ_NEXT(opt, link);
4022 while (opt != NULL) {
4023 db_printf(", %s", opt->name);
4024 opt = TAILQ_NEXT(opt, link);
4030 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
4031 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4032 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4033 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4034 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4035 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4036 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4037 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4038 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4039 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4040 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4041 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4043 db_printf(" mnt_cred = { uid=%u ruid=%u",
4044 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4045 if (jailed(mp->mnt_cred))
4046 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4048 db_printf(" mnt_ref = %d (with %d in the struct)\n",
4049 vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4050 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
4051 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4052 db_printf(" mnt_activevnodelistsize = %d\n",
4053 mp->mnt_activevnodelistsize);
4054 db_printf(" mnt_writeopcount = %d (with %d in the struct)\n",
4055 vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4056 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
4057 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4058 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
4059 db_printf(" mnt_lockref = %d (with %d in the struct)\n",
4060 vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4061 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4062 db_printf(" mnt_secondary_accwrites = %d\n",
4063 mp->mnt_secondary_accwrites);
4064 db_printf(" mnt_gjprovider = %s\n",
4065 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4066 db_printf(" mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4068 db_printf("\n\nList of active vnodes\n");
4069 TAILQ_FOREACH(vp, &mp->mnt_activevnodelist, v_actfreelist) {
4070 if (vp->v_type != VMARKER) {
4071 vn_printf(vp, "vnode ");
4076 db_printf("\n\nList of inactive vnodes\n");
4077 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4078 if (vp->v_type != VMARKER && (vp->v_iflag & VI_ACTIVE) == 0) {
4079 vn_printf(vp, "vnode ");
4088 * Fill in a struct xvfsconf based on a struct vfsconf.
4091 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4093 struct xvfsconf xvfsp;
4095 bzero(&xvfsp, sizeof(xvfsp));
4096 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4097 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4098 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4099 xvfsp.vfc_flags = vfsp->vfc_flags;
4101 * These are unused in userland, we keep them
4102 * to not break binary compatibility.
4104 xvfsp.vfc_vfsops = NULL;
4105 xvfsp.vfc_next = NULL;
4106 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4109 #ifdef COMPAT_FREEBSD32
4111 uint32_t vfc_vfsops;
4112 char vfc_name[MFSNAMELEN];
4113 int32_t vfc_typenum;
4114 int32_t vfc_refcount;
4120 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4122 struct xvfsconf32 xvfsp;
4124 bzero(&xvfsp, sizeof(xvfsp));
4125 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4126 xvfsp.vfc_typenum = vfsp->vfc_typenum;
4127 xvfsp.vfc_refcount = vfsp->vfc_refcount;
4128 xvfsp.vfc_flags = vfsp->vfc_flags;
4129 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4134 * Top level filesystem related information gathering.
4137 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4139 struct vfsconf *vfsp;
4144 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4145 #ifdef COMPAT_FREEBSD32
4146 if (req->flags & SCTL_MASK32)
4147 error = vfsconf2x32(req, vfsp);
4150 error = vfsconf2x(req, vfsp);
4158 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4159 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4160 "S,xvfsconf", "List of all configured filesystems");
4162 #ifndef BURN_BRIDGES
4163 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4166 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4168 int *name = (int *)arg1 - 1; /* XXX */
4169 u_int namelen = arg2 + 1; /* XXX */
4170 struct vfsconf *vfsp;
4172 log(LOG_WARNING, "userland calling deprecated sysctl, "
4173 "please rebuild world\n");
4175 #if 1 || defined(COMPAT_PRELITE2)
4176 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4178 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4182 case VFS_MAXTYPENUM:
4185 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4188 return (ENOTDIR); /* overloaded */
4190 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4191 if (vfsp->vfc_typenum == name[2])
4196 return (EOPNOTSUPP);
4197 #ifdef COMPAT_FREEBSD32
4198 if (req->flags & SCTL_MASK32)
4199 return (vfsconf2x32(req, vfsp));
4202 return (vfsconf2x(req, vfsp));
4204 return (EOPNOTSUPP);
4207 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4208 CTLFLAG_MPSAFE, vfs_sysctl,
4209 "Generic filesystem");
4211 #if 1 || defined(COMPAT_PRELITE2)
4214 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4217 struct vfsconf *vfsp;
4218 struct ovfsconf ovfs;
4221 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4222 bzero(&ovfs, sizeof(ovfs));
4223 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
4224 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4225 ovfs.vfc_index = vfsp->vfc_typenum;
4226 ovfs.vfc_refcount = vfsp->vfc_refcount;
4227 ovfs.vfc_flags = vfsp->vfc_flags;
4228 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4238 #endif /* 1 || COMPAT_PRELITE2 */
4239 #endif /* !BURN_BRIDGES */
4241 #define KINFO_VNODESLOP 10
4244 * Dump vnode list (via sysctl).
4248 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4256 * Stale numvnodes access is not fatal here.
4259 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4261 /* Make an estimate */
4262 return (SYSCTL_OUT(req, 0, len));
4264 error = sysctl_wire_old_buffer(req, 0);
4267 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4269 mtx_lock(&mountlist_mtx);
4270 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4271 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4274 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4278 xvn[n].xv_size = sizeof *xvn;
4279 xvn[n].xv_vnode = vp;
4280 xvn[n].xv_id = 0; /* XXX compat */
4281 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4283 XV_COPY(writecount);
4289 xvn[n].xv_flag = vp->v_vflag;
4291 switch (vp->v_type) {
4298 if (vp->v_rdev == NULL) {
4302 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4305 xvn[n].xv_socket = vp->v_socket;
4308 xvn[n].xv_fifo = vp->v_fifoinfo;
4313 /* shouldn't happen? */
4321 mtx_lock(&mountlist_mtx);
4326 mtx_unlock(&mountlist_mtx);
4328 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4333 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4334 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4339 unmount_or_warn(struct mount *mp)
4343 error = dounmount(mp, MNT_FORCE, curthread);
4345 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4349 printf("%d)\n", error);
4354 * Unmount all filesystems. The list is traversed in reverse order
4355 * of mounting to avoid dependencies.
4358 vfs_unmountall(void)
4360 struct mount *mp, *tmp;
4362 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4365 * Since this only runs when rebooting, it is not interlocked.
4367 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4371 * Forcibly unmounting "/dev" before "/" would prevent clean
4372 * unmount of the latter.
4374 if (mp == rootdevmp)
4377 unmount_or_warn(mp);
4380 if (rootdevmp != NULL)
4381 unmount_or_warn(rootdevmp);
4385 * perform msync on all vnodes under a mount point
4386 * the mount point must be locked.
4389 vfs_msync(struct mount *mp, int flags)
4391 struct vnode *vp, *mvp;
4392 struct vm_object *obj;
4394 int lkflags, objflags;
4396 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4398 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4403 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4404 if (flags != MNT_WAIT) {
4405 lkflags |= LK_NOWAIT;
4406 objflags = OBJPC_NOSYNC;
4408 objflags = OBJPC_SYNC;
4411 MNT_VNODE_FOREACH_ACTIVE(vp, mp, mvp) {
4413 if (obj == NULL || !vm_object_mightbedirty(obj)) {
4417 if (vget(vp, lkflags, td) == 0) {
4419 if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4420 VM_OBJECT_WLOCK(obj);
4421 vm_object_page_clean(obj, 0, 0, objflags);
4422 VM_OBJECT_WUNLOCK(obj);
4430 destroy_vpollinfo_free(struct vpollinfo *vi)
4433 knlist_destroy(&vi->vpi_selinfo.si_note);
4434 mtx_destroy(&vi->vpi_lock);
4435 uma_zfree(vnodepoll_zone, vi);
4439 destroy_vpollinfo(struct vpollinfo *vi)
4442 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4443 seldrain(&vi->vpi_selinfo);
4444 destroy_vpollinfo_free(vi);
4448 * Initialize per-vnode helper structure to hold poll-related state.
4451 v_addpollinfo(struct vnode *vp)
4453 struct vpollinfo *vi;
4455 if (vp->v_pollinfo != NULL)
4457 vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4458 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4459 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4460 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4462 if (vp->v_pollinfo != NULL) {
4464 destroy_vpollinfo_free(vi);
4467 vp->v_pollinfo = vi;
4472 * Record a process's interest in events which might happen to
4473 * a vnode. Because poll uses the historic select-style interface
4474 * internally, this routine serves as both the ``check for any
4475 * pending events'' and the ``record my interest in future events''
4476 * functions. (These are done together, while the lock is held,
4477 * to avoid race conditions.)
4480 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4484 mtx_lock(&vp->v_pollinfo->vpi_lock);
4485 if (vp->v_pollinfo->vpi_revents & events) {
4487 * This leaves events we are not interested
4488 * in available for the other process which
4489 * which presumably had requested them
4490 * (otherwise they would never have been
4493 events &= vp->v_pollinfo->vpi_revents;
4494 vp->v_pollinfo->vpi_revents &= ~events;
4496 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4499 vp->v_pollinfo->vpi_events |= events;
4500 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4501 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4506 * Routine to create and manage a filesystem syncer vnode.
4508 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4509 static int sync_fsync(struct vop_fsync_args *);
4510 static int sync_inactive(struct vop_inactive_args *);
4511 static int sync_reclaim(struct vop_reclaim_args *);
4513 static struct vop_vector sync_vnodeops = {
4514 .vop_bypass = VOP_EOPNOTSUPP,
4515 .vop_close = sync_close, /* close */
4516 .vop_fsync = sync_fsync, /* fsync */
4517 .vop_inactive = sync_inactive, /* inactive */
4518 .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
4519 .vop_reclaim = sync_reclaim, /* reclaim */
4520 .vop_lock1 = vop_stdlock, /* lock */
4521 .vop_unlock = vop_stdunlock, /* unlock */
4522 .vop_islocked = vop_stdislocked, /* islocked */
4524 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
4527 * Create a new filesystem syncer vnode for the specified mount point.
4530 vfs_allocate_syncvnode(struct mount *mp)
4534 static long start, incr, next;
4537 /* Allocate a new vnode */
4538 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
4540 panic("vfs_allocate_syncvnode: getnewvnode() failed");
4542 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4543 vp->v_vflag |= VV_FORCEINSMQ;
4544 error = insmntque(vp, mp);
4546 panic("vfs_allocate_syncvnode: insmntque() failed");
4547 vp->v_vflag &= ~VV_FORCEINSMQ;
4550 * Place the vnode onto the syncer worklist. We attempt to
4551 * scatter them about on the list so that they will go off
4552 * at evenly distributed times even if all the filesystems
4553 * are mounted at once.
4556 if (next == 0 || next > syncer_maxdelay) {
4560 start = syncer_maxdelay / 2;
4561 incr = syncer_maxdelay;
4567 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
4568 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
4569 mtx_lock(&sync_mtx);
4571 if (mp->mnt_syncer == NULL) {
4572 mp->mnt_syncer = vp;
4575 mtx_unlock(&sync_mtx);
4578 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4585 vfs_deallocate_syncvnode(struct mount *mp)
4589 mtx_lock(&sync_mtx);
4590 vp = mp->mnt_syncer;
4592 mp->mnt_syncer = NULL;
4593 mtx_unlock(&sync_mtx);
4599 * Do a lazy sync of the filesystem.
4602 sync_fsync(struct vop_fsync_args *ap)
4604 struct vnode *syncvp = ap->a_vp;
4605 struct mount *mp = syncvp->v_mount;
4610 * We only need to do something if this is a lazy evaluation.
4612 if (ap->a_waitfor != MNT_LAZY)
4616 * Move ourselves to the back of the sync list.
4618 bo = &syncvp->v_bufobj;
4620 vn_syncer_add_to_worklist(bo, syncdelay);
4624 * Walk the list of vnodes pushing all that are dirty and
4625 * not already on the sync list.
4627 if (vfs_busy(mp, MBF_NOWAIT) != 0)
4629 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
4633 save = curthread_pflags_set(TDP_SYNCIO);
4635 * The filesystem at hand may be idle with free vnodes stored in the
4636 * batch. Return them instead of letting them stay there indefinitely.
4638 vnlru_return_batch(mp);
4639 vfs_msync(mp, MNT_NOWAIT);
4640 error = VFS_SYNC(mp, MNT_LAZY);
4641 curthread_pflags_restore(save);
4642 vn_finished_write(mp);
4648 * The syncer vnode is no referenced.
4651 sync_inactive(struct vop_inactive_args *ap)
4659 * The syncer vnode is no longer needed and is being decommissioned.
4661 * Modifications to the worklist must be protected by sync_mtx.
4664 sync_reclaim(struct vop_reclaim_args *ap)
4666 struct vnode *vp = ap->a_vp;
4671 mtx_lock(&sync_mtx);
4672 if (vp->v_mount->mnt_syncer == vp)
4673 vp->v_mount->mnt_syncer = NULL;
4674 if (bo->bo_flag & BO_ONWORKLST) {
4675 LIST_REMOVE(bo, bo_synclist);
4676 syncer_worklist_len--;
4678 bo->bo_flag &= ~BO_ONWORKLST;
4680 mtx_unlock(&sync_mtx);
4687 vn_need_pageq_flush(struct vnode *vp)
4689 struct vm_object *obj;
4692 MPASS(mtx_owned(VI_MTX(vp)));
4694 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
4695 vm_object_mightbedirty(obj))
4701 * Check if vnode represents a disk device
4704 vn_isdisk(struct vnode *vp, int *errp)
4708 if (vp->v_type != VCHR) {
4714 if (vp->v_rdev == NULL)
4716 else if (vp->v_rdev->si_devsw == NULL)
4718 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
4724 return (error == 0);
4728 * Common filesystem object access control check routine. Accepts a
4729 * vnode's type, "mode", uid and gid, requested access mode, credentials,
4730 * and optional call-by-reference privused argument allowing vaccess()
4731 * to indicate to the caller whether privilege was used to satisfy the
4732 * request (obsoleted). Returns 0 on success, or an errno on failure.
4735 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
4736 accmode_t accmode, struct ucred *cred, int *privused)
4738 accmode_t dac_granted;
4739 accmode_t priv_granted;
4741 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
4742 ("invalid bit in accmode"));
4743 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
4744 ("VAPPEND without VWRITE"));
4747 * Look for a normal, non-privileged way to access the file/directory
4748 * as requested. If it exists, go with that.
4751 if (privused != NULL)
4756 /* Check the owner. */
4757 if (cred->cr_uid == file_uid) {
4758 dac_granted |= VADMIN;
4759 if (file_mode & S_IXUSR)
4760 dac_granted |= VEXEC;
4761 if (file_mode & S_IRUSR)
4762 dac_granted |= VREAD;
4763 if (file_mode & S_IWUSR)
4764 dac_granted |= (VWRITE | VAPPEND);
4766 if ((accmode & dac_granted) == accmode)
4772 /* Otherwise, check the groups (first match) */
4773 if (groupmember(file_gid, cred)) {
4774 if (file_mode & S_IXGRP)
4775 dac_granted |= VEXEC;
4776 if (file_mode & S_IRGRP)
4777 dac_granted |= VREAD;
4778 if (file_mode & S_IWGRP)
4779 dac_granted |= (VWRITE | VAPPEND);
4781 if ((accmode & dac_granted) == accmode)
4787 /* Otherwise, check everyone else. */
4788 if (file_mode & S_IXOTH)
4789 dac_granted |= VEXEC;
4790 if (file_mode & S_IROTH)
4791 dac_granted |= VREAD;
4792 if (file_mode & S_IWOTH)
4793 dac_granted |= (VWRITE | VAPPEND);
4794 if ((accmode & dac_granted) == accmode)
4799 * Build a privilege mask to determine if the set of privileges
4800 * satisfies the requirements when combined with the granted mask
4801 * from above. For each privilege, if the privilege is required,
4802 * bitwise or the request type onto the priv_granted mask.
4808 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
4809 * requests, instead of PRIV_VFS_EXEC.
4811 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4812 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
4813 priv_granted |= VEXEC;
4816 * Ensure that at least one execute bit is on. Otherwise,
4817 * a privileged user will always succeed, and we don't want
4818 * this to happen unless the file really is executable.
4820 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4821 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
4822 !priv_check_cred(cred, PRIV_VFS_EXEC))
4823 priv_granted |= VEXEC;
4826 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
4827 !priv_check_cred(cred, PRIV_VFS_READ))
4828 priv_granted |= VREAD;
4830 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
4831 !priv_check_cred(cred, PRIV_VFS_WRITE))
4832 priv_granted |= (VWRITE | VAPPEND);
4834 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
4835 !priv_check_cred(cred, PRIV_VFS_ADMIN))
4836 priv_granted |= VADMIN;
4838 if ((accmode & (priv_granted | dac_granted)) == accmode) {
4839 /* XXX audit: privilege used */
4840 if (privused != NULL)
4845 return ((accmode & VADMIN) ? EPERM : EACCES);
4849 * Credential check based on process requesting service, and per-attribute
4853 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
4854 struct thread *td, accmode_t accmode)
4858 * Kernel-invoked always succeeds.
4864 * Do not allow privileged processes in jail to directly manipulate
4865 * system attributes.
4867 switch (attrnamespace) {
4868 case EXTATTR_NAMESPACE_SYSTEM:
4869 /* Potentially should be: return (EPERM); */
4870 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
4871 case EXTATTR_NAMESPACE_USER:
4872 return (VOP_ACCESS(vp, accmode, cred, td));
4878 #ifdef DEBUG_VFS_LOCKS
4880 * This only exists to suppress warnings from unlocked specfs accesses. It is
4881 * no longer ok to have an unlocked VFS.
4883 #define IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL || \
4884 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
4886 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
4887 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
4888 "Drop into debugger on lock violation");
4890 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
4891 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
4892 0, "Check for interlock across VOPs");
4894 int vfs_badlock_print = 1; /* Print lock violations. */
4895 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
4896 0, "Print lock violations");
4898 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
4899 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
4900 0, "Print vnode details on lock violations");
4903 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
4904 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
4905 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
4909 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
4913 if (vfs_badlock_backtrace)
4916 if (vfs_badlock_vnode)
4917 vn_printf(vp, "vnode ");
4918 if (vfs_badlock_print)
4919 printf("%s: %p %s\n", str, (void *)vp, msg);
4920 if (vfs_badlock_ddb)
4921 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4925 assert_vi_locked(struct vnode *vp, const char *str)
4928 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
4929 vfs_badlock("interlock is not locked but should be", str, vp);
4933 assert_vi_unlocked(struct vnode *vp, const char *str)
4936 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
4937 vfs_badlock("interlock is locked but should not be", str, vp);
4941 assert_vop_locked(struct vnode *vp, const char *str)
4945 if (!IGNORE_LOCK(vp)) {
4946 locked = VOP_ISLOCKED(vp);
4947 if (locked == 0 || locked == LK_EXCLOTHER)
4948 vfs_badlock("is not locked but should be", str, vp);
4953 assert_vop_unlocked(struct vnode *vp, const char *str)
4956 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
4957 vfs_badlock("is locked but should not be", str, vp);
4961 assert_vop_elocked(struct vnode *vp, const char *str)
4964 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
4965 vfs_badlock("is not exclusive locked but should be", str, vp);
4967 #endif /* DEBUG_VFS_LOCKS */
4970 vop_rename_fail(struct vop_rename_args *ap)
4973 if (ap->a_tvp != NULL)
4975 if (ap->a_tdvp == ap->a_tvp)
4984 vop_rename_pre(void *ap)
4986 struct vop_rename_args *a = ap;
4988 #ifdef DEBUG_VFS_LOCKS
4990 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
4991 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
4992 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
4993 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
4995 /* Check the source (from). */
4996 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
4997 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
4998 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
4999 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5000 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5002 /* Check the target. */
5004 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5005 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5007 if (a->a_tdvp != a->a_fdvp)
5009 if (a->a_tvp != a->a_fvp)
5016 #ifdef DEBUG_VFS_LOCKS
5018 vop_strategy_pre(void *ap)
5020 struct vop_strategy_args *a;
5027 * Cluster ops lock their component buffers but not the IO container.
5029 if ((bp->b_flags & B_CLUSTER) != 0)
5032 if (panicstr == NULL && !BUF_ISLOCKED(bp)) {
5033 if (vfs_badlock_print)
5035 "VOP_STRATEGY: bp is not locked but should be\n");
5036 if (vfs_badlock_ddb)
5037 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5042 vop_lock_pre(void *ap)
5044 struct vop_lock1_args *a = ap;
5046 if ((a->a_flags & LK_INTERLOCK) == 0)
5047 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5049 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5053 vop_lock_post(void *ap, int rc)
5055 struct vop_lock1_args *a = ap;
5057 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5058 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5059 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5063 vop_unlock_pre(void *ap)
5065 struct vop_unlock_args *a = ap;
5067 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5071 vop_unlock_post(void *ap, int rc)
5077 vop_need_inactive_pre(void *ap)
5079 struct vop_need_inactive_args *a = ap;
5081 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5085 vop_need_inactive_post(void *ap, int rc)
5087 struct vop_need_inactive_args *a = ap;
5089 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5094 vop_create_post(void *ap, int rc)
5096 struct vop_create_args *a = ap;
5099 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5103 vop_deleteextattr_post(void *ap, int rc)
5105 struct vop_deleteextattr_args *a = ap;
5108 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5112 vop_link_post(void *ap, int rc)
5114 struct vop_link_args *a = ap;
5117 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
5118 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
5123 vop_mkdir_post(void *ap, int rc)
5125 struct vop_mkdir_args *a = ap;
5128 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5132 vop_mknod_post(void *ap, int rc)
5134 struct vop_mknod_args *a = ap;
5137 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5141 vop_reclaim_post(void *ap, int rc)
5143 struct vop_reclaim_args *a = ap;
5146 VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
5150 vop_remove_post(void *ap, int rc)
5152 struct vop_remove_args *a = ap;
5155 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5156 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5161 vop_rename_post(void *ap, int rc)
5163 struct vop_rename_args *a = ap;
5168 if (a->a_fdvp == a->a_tdvp) {
5169 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5171 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5172 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5174 hint |= NOTE_EXTEND;
5175 if (a->a_fvp->v_type == VDIR)
5177 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5179 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5180 a->a_tvp->v_type == VDIR)
5182 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5185 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5187 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5189 if (a->a_tdvp != a->a_fdvp)
5191 if (a->a_tvp != a->a_fvp)
5199 vop_rmdir_post(void *ap, int rc)
5201 struct vop_rmdir_args *a = ap;
5204 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5205 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5210 vop_setattr_post(void *ap, int rc)
5212 struct vop_setattr_args *a = ap;
5215 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5219 vop_setextattr_post(void *ap, int rc)
5221 struct vop_setextattr_args *a = ap;
5224 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5228 vop_symlink_post(void *ap, int rc)
5230 struct vop_symlink_args *a = ap;
5233 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5237 vop_open_post(void *ap, int rc)
5239 struct vop_open_args *a = ap;
5242 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
5246 vop_close_post(void *ap, int rc)
5248 struct vop_close_args *a = ap;
5250 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
5251 !VN_IS_DOOMED(a->a_vp))) {
5252 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
5253 NOTE_CLOSE_WRITE : NOTE_CLOSE);
5258 vop_read_post(void *ap, int rc)
5260 struct vop_read_args *a = ap;
5263 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5267 vop_readdir_post(void *ap, int rc)
5269 struct vop_readdir_args *a = ap;
5272 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5275 static struct knlist fs_knlist;
5278 vfs_event_init(void *arg)
5280 knlist_init_mtx(&fs_knlist, NULL);
5282 /* XXX - correct order? */
5283 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
5286 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
5289 KNOTE_UNLOCKED(&fs_knlist, event);
5292 static int filt_fsattach(struct knote *kn);
5293 static void filt_fsdetach(struct knote *kn);
5294 static int filt_fsevent(struct knote *kn, long hint);
5296 struct filterops fs_filtops = {
5298 .f_attach = filt_fsattach,
5299 .f_detach = filt_fsdetach,
5300 .f_event = filt_fsevent
5304 filt_fsattach(struct knote *kn)
5307 kn->kn_flags |= EV_CLEAR;
5308 knlist_add(&fs_knlist, kn, 0);
5313 filt_fsdetach(struct knote *kn)
5316 knlist_remove(&fs_knlist, kn, 0);
5320 filt_fsevent(struct knote *kn, long hint)
5323 kn->kn_fflags |= hint;
5324 return (kn->kn_fflags != 0);
5328 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
5334 error = SYSCTL_IN(req, &vc, sizeof(vc));
5337 if (vc.vc_vers != VFS_CTL_VERS1)
5339 mp = vfs_getvfs(&vc.vc_fsid);
5342 /* ensure that a specific sysctl goes to the right filesystem. */
5343 if (strcmp(vc.vc_fstypename, "*") != 0 &&
5344 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
5348 VCTLTOREQ(&vc, req);
5349 error = VFS_SYSCTL(mp, vc.vc_op, req);
5354 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_WR,
5355 NULL, 0, sysctl_vfs_ctl, "",
5359 * Function to initialize a va_filerev field sensibly.
5360 * XXX: Wouldn't a random number make a lot more sense ??
5363 init_va_filerev(void)
5368 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
5371 static int filt_vfsread(struct knote *kn, long hint);
5372 static int filt_vfswrite(struct knote *kn, long hint);
5373 static int filt_vfsvnode(struct knote *kn, long hint);
5374 static void filt_vfsdetach(struct knote *kn);
5375 static struct filterops vfsread_filtops = {
5377 .f_detach = filt_vfsdetach,
5378 .f_event = filt_vfsread
5380 static struct filterops vfswrite_filtops = {
5382 .f_detach = filt_vfsdetach,
5383 .f_event = filt_vfswrite
5385 static struct filterops vfsvnode_filtops = {
5387 .f_detach = filt_vfsdetach,
5388 .f_event = filt_vfsvnode
5392 vfs_knllock(void *arg)
5394 struct vnode *vp = arg;
5396 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5400 vfs_knlunlock(void *arg)
5402 struct vnode *vp = arg;
5408 vfs_knl_assert_locked(void *arg)
5410 #ifdef DEBUG_VFS_LOCKS
5411 struct vnode *vp = arg;
5413 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
5418 vfs_knl_assert_unlocked(void *arg)
5420 #ifdef DEBUG_VFS_LOCKS
5421 struct vnode *vp = arg;
5423 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
5428 vfs_kqfilter(struct vop_kqfilter_args *ap)
5430 struct vnode *vp = ap->a_vp;
5431 struct knote *kn = ap->a_kn;
5434 switch (kn->kn_filter) {
5436 kn->kn_fop = &vfsread_filtops;
5439 kn->kn_fop = &vfswrite_filtops;
5442 kn->kn_fop = &vfsvnode_filtops;
5448 kn->kn_hook = (caddr_t)vp;
5451 if (vp->v_pollinfo == NULL)
5453 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5455 knlist_add(knl, kn, 0);
5461 * Detach knote from vnode
5464 filt_vfsdetach(struct knote *kn)
5466 struct vnode *vp = (struct vnode *)kn->kn_hook;
5468 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
5469 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
5475 filt_vfsread(struct knote *kn, long hint)
5477 struct vnode *vp = (struct vnode *)kn->kn_hook;
5482 * filesystem is gone, so set the EOF flag and schedule
5483 * the knote for deletion.
5485 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5487 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5492 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
5496 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
5497 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
5504 filt_vfswrite(struct knote *kn, long hint)
5506 struct vnode *vp = (struct vnode *)kn->kn_hook;
5511 * filesystem is gone, so set the EOF flag and schedule
5512 * the knote for deletion.
5514 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
5515 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5523 filt_vfsvnode(struct knote *kn, long hint)
5525 struct vnode *vp = (struct vnode *)kn->kn_hook;
5529 if (kn->kn_sfflags & hint)
5530 kn->kn_fflags |= hint;
5531 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5532 kn->kn_flags |= EV_EOF;
5536 res = (kn->kn_fflags != 0);
5542 * Returns whether the directory is empty or not.
5543 * If it is empty, the return value is 0; otherwise
5544 * the return value is an error value (which may
5548 vfs_emptydir(struct vnode *vp)
5552 struct dirent *dirent, *dp, *endp;
5558 ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
5560 dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
5561 iov.iov_base = dirent;
5562 iov.iov_len = sizeof(struct dirent);
5567 uio.uio_resid = sizeof(struct dirent);
5568 uio.uio_segflg = UIO_SYSSPACE;
5569 uio.uio_rw = UIO_READ;
5570 uio.uio_td = curthread;
5572 while (eof == 0 && error == 0) {
5573 error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
5577 endp = (void *)((uint8_t *)dirent +
5578 sizeof(struct dirent) - uio.uio_resid);
5579 for (dp = dirent; dp < endp;
5580 dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
5581 if (dp->d_type == DT_WHT)
5583 if (dp->d_namlen == 0)
5585 if (dp->d_type != DT_DIR &&
5586 dp->d_type != DT_UNKNOWN) {
5590 if (dp->d_namlen > 2) {
5594 if (dp->d_namlen == 1 &&
5595 dp->d_name[0] != '.') {
5599 if (dp->d_namlen == 2 &&
5600 dp->d_name[1] != '.') {
5604 uio.uio_resid = sizeof(struct dirent);
5607 free(dirent, M_TEMP);
5612 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
5616 if (dp->d_reclen > ap->a_uio->uio_resid)
5617 return (ENAMETOOLONG);
5618 error = uiomove(dp, dp->d_reclen, ap->a_uio);
5620 if (ap->a_ncookies != NULL) {
5621 if (ap->a_cookies != NULL)
5622 free(ap->a_cookies, M_TEMP);
5623 ap->a_cookies = NULL;
5624 *ap->a_ncookies = 0;
5628 if (ap->a_ncookies == NULL)
5631 KASSERT(ap->a_cookies,
5632 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
5634 *ap->a_cookies = realloc(*ap->a_cookies,
5635 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
5636 (*ap->a_cookies)[*ap->a_ncookies] = off;
5637 *ap->a_ncookies += 1;
5642 * Mark for update the access time of the file if the filesystem
5643 * supports VOP_MARKATIME. This functionality is used by execve and
5644 * mmap, so we want to avoid the I/O implied by directly setting
5645 * va_atime for the sake of efficiency.
5648 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
5653 ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
5654 if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
5655 (void)VOP_MARKATIME(vp);
5659 * The purpose of this routine is to remove granularity from accmode_t,
5660 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
5661 * VADMIN and VAPPEND.
5663 * If it returns 0, the caller is supposed to continue with the usual
5664 * access checks using 'accmode' as modified by this routine. If it
5665 * returns nonzero value, the caller is supposed to return that value
5668 * Note that after this routine runs, accmode may be zero.
5671 vfs_unixify_accmode(accmode_t *accmode)
5674 * There is no way to specify explicit "deny" rule using
5675 * file mode or POSIX.1e ACLs.
5677 if (*accmode & VEXPLICIT_DENY) {
5683 * None of these can be translated into usual access bits.
5684 * Also, the common case for NFSv4 ACLs is to not contain
5685 * either of these bits. Caller should check for VWRITE
5686 * on the containing directory instead.
5688 if (*accmode & (VDELETE_CHILD | VDELETE))
5691 if (*accmode & VADMIN_PERMS) {
5692 *accmode &= ~VADMIN_PERMS;
5697 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
5698 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
5700 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
5706 * Clear out a doomed vnode (if any) and replace it with a new one as long
5707 * as the fs is not being unmounted. Return the root vnode to the caller.
5709 static int __noinline
5710 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
5716 if (mp->mnt_rootvnode != NULL) {
5718 vp = mp->mnt_rootvnode;
5720 if (!VN_IS_DOOMED(vp)) {
5723 error = vn_lock(vp, flags);
5732 * Clear the old one.
5734 mp->mnt_rootvnode = NULL;
5739 * Paired with a fence in vfs_op_thread_exit().
5741 atomic_thread_fence_acq();
5742 vfs_op_barrier_wait(mp);
5746 error = VFS_CACHEDROOT(mp, flags, vpp);
5749 if (mp->mnt_vfs_ops == 0) {
5751 if (mp->mnt_vfs_ops != 0) {
5755 if (mp->mnt_rootvnode == NULL) {
5757 mp->mnt_rootvnode = *vpp;
5759 if (mp->mnt_rootvnode != *vpp) {
5760 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
5761 panic("%s: mismatch between vnode returned "
5762 " by VFS_CACHEDROOT and the one cached "
5764 __func__, *vpp, mp->mnt_rootvnode);
5774 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
5779 if (!vfs_op_thread_enter(mp))
5780 return (vfs_cache_root_fallback(mp, flags, vpp));
5781 vp = (struct vnode *)atomic_load_ptr(&mp->mnt_rootvnode);
5782 if (vp == NULL || VN_IS_DOOMED(vp)) {
5783 vfs_op_thread_exit(mp);
5784 return (vfs_cache_root_fallback(mp, flags, vpp));
5787 vfs_op_thread_exit(mp);
5788 error = vn_lock(vp, flags);
5791 return (vfs_cache_root_fallback(mp, flags, vpp));
5798 vfs_cache_root_clear(struct mount *mp)
5803 * ops > 0 guarantees there is nobody who can see this vnode
5805 MPASS(mp->mnt_vfs_ops > 0);
5806 vp = mp->mnt_rootvnode;
5807 mp->mnt_rootvnode = NULL;
5812 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
5815 MPASS(mp->mnt_vfs_ops > 0);
5817 mp->mnt_rootvnode = vp;
5821 * These are helper functions for filesystems to traverse all
5822 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
5824 * This interface replaces MNT_VNODE_FOREACH.
5829 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
5834 kern_yield(PRI_USER);
5836 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5837 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
5838 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
5839 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
5840 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
5843 if (VN_IS_DOOMED(vp)) {
5850 __mnt_vnode_markerfree_all(mvp, mp);
5851 /* MNT_IUNLOCK(mp); -- done in above function */
5852 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
5855 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5856 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5862 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
5866 *mvp = vn_alloc_marker(mp);
5870 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
5871 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
5872 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
5875 if (VN_IS_DOOMED(vp)) {
5884 vn_free_marker(*mvp);
5888 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5894 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
5902 mtx_assert(MNT_MTX(mp), MA_OWNED);
5904 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5905 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5908 vn_free_marker(*mvp);
5913 * These are helper functions for filesystems to traverse their
5914 * active vnodes. See MNT_VNODE_FOREACH_ACTIVE() in sys/mount.h
5917 mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
5920 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5925 vn_free_marker(*mvp);
5930 * Relock the mp mount vnode list lock with the vp vnode interlock in the
5931 * conventional lock order during mnt_vnode_next_active iteration.
5933 * On entry, the mount vnode list lock is held and the vnode interlock is not.
5934 * The list lock is dropped and reacquired. On success, both locks are held.
5935 * On failure, the mount vnode list lock is held but the vnode interlock is
5936 * not, and the procedure may have yielded.
5939 mnt_vnode_next_active_relock(struct vnode *mvp, struct mount *mp,
5942 const struct vnode *tmp;
5945 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
5946 TAILQ_NEXT(mvp, v_actfreelist) != NULL, mvp,
5947 ("%s: bad marker", __func__));
5948 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
5949 ("%s: inappropriate vnode", __func__));
5950 ASSERT_VI_UNLOCKED(vp, __func__);
5951 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5955 TAILQ_REMOVE(&mp->mnt_activevnodelist, mvp, v_actfreelist);
5956 TAILQ_INSERT_BEFORE(vp, mvp, v_actfreelist);
5959 * Use a hold to prevent vp from disappearing while the mount vnode
5960 * list lock is dropped and reacquired. Normally a hold would be
5961 * acquired with vhold(), but that might try to acquire the vnode
5962 * interlock, which would be a LOR with the mount vnode list lock.
5964 held = refcount_acquire_if_not_zero(&vp->v_holdcnt);
5965 mtx_unlock(&mp->mnt_listmtx);
5969 if (!refcount_release_if_not_last(&vp->v_holdcnt)) {
5973 mtx_lock(&mp->mnt_listmtx);
5976 * Determine whether the vnode is still the next one after the marker,
5977 * excepting any other markers. If the vnode has not been doomed by
5978 * vgone() then the hold should have ensured that it remained on the
5979 * active list. If it has been doomed but is still on the active list,
5980 * don't abort, but rather skip over it (avoid spinning on doomed
5985 tmp = TAILQ_NEXT(tmp, v_actfreelist);
5986 } while (tmp != NULL && tmp->v_type == VMARKER);
5988 mtx_unlock(&mp->mnt_listmtx);
5997 mtx_lock(&mp->mnt_listmtx);
6000 ASSERT_VI_LOCKED(vp, __func__);
6002 ASSERT_VI_UNLOCKED(vp, __func__);
6003 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6007 static struct vnode *
6008 mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
6010 struct vnode *vp, *nvp;
6012 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6013 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6015 vp = TAILQ_NEXT(*mvp, v_actfreelist);
6016 while (vp != NULL) {
6017 if (vp->v_type == VMARKER) {
6018 vp = TAILQ_NEXT(vp, v_actfreelist);
6022 * Try-lock because this is the wrong lock order. If that does
6023 * not succeed, drop the mount vnode list lock and try to
6024 * reacquire it and the vnode interlock in the right order.
6026 if (!VI_TRYLOCK(vp) &&
6027 !mnt_vnode_next_active_relock(*mvp, mp, vp))
6029 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6030 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6031 ("alien vnode on the active list %p %p", vp, mp));
6032 if (vp->v_mount == mp && !VN_IS_DOOMED(vp))
6034 nvp = TAILQ_NEXT(vp, v_actfreelist);
6038 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
6040 /* Check if we are done */
6042 mtx_unlock(&mp->mnt_listmtx);
6043 mnt_vnode_markerfree_active(mvp, mp);
6046 TAILQ_INSERT_AFTER(&mp->mnt_activevnodelist, vp, *mvp, v_actfreelist);
6047 mtx_unlock(&mp->mnt_listmtx);
6048 ASSERT_VI_LOCKED(vp, "active iter");
6049 KASSERT((vp->v_iflag & VI_ACTIVE) != 0, ("Non-active vp %p", vp));
6054 __mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
6058 kern_yield(PRI_USER);
6059 mtx_lock(&mp->mnt_listmtx);
6060 return (mnt_vnode_next_active(mvp, mp));
6064 __mnt_vnode_first_active(struct vnode **mvp, struct mount *mp)
6068 *mvp = vn_alloc_marker(mp);
6073 mtx_lock(&mp->mnt_listmtx);
6074 vp = TAILQ_FIRST(&mp->mnt_activevnodelist);
6076 mtx_unlock(&mp->mnt_listmtx);
6077 mnt_vnode_markerfree_active(mvp, mp);
6080 TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
6081 return (mnt_vnode_next_active(mvp, mp));
6085 __mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
6091 mtx_lock(&mp->mnt_listmtx);
6092 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
6093 mtx_unlock(&mp->mnt_listmtx);
6094 mnt_vnode_markerfree_active(mvp, mp);