2 * Copyright (c) 1989, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)vfs_subr.c 8.31 (Berkeley) 5/26/95
38 * External virtual filesystem routines
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
44 #include "opt_compat.h"
46 #include "opt_watchdog.h"
48 #include <sys/param.h>
49 #include <sys/systm.h>
52 #include <sys/condvar.h>
54 #include <sys/counter.h>
55 #include <sys/dirent.h>
56 #include <sys/event.h>
57 #include <sys/eventhandler.h>
58 #include <sys/extattr.h>
60 #include <sys/fcntl.h>
63 #include <sys/kernel.h>
64 #include <sys/kthread.h>
65 #include <sys/lockf.h>
66 #include <sys/malloc.h>
67 #include <sys/mount.h>
68 #include <sys/namei.h>
69 #include <sys/pctrie.h>
71 #include <sys/reboot.h>
72 #include <sys/refcount.h>
73 #include <sys/rwlock.h>
74 #include <sys/sched.h>
75 #include <sys/sleepqueue.h>
78 #include <sys/sysctl.h>
79 #include <sys/syslog.h>
80 #include <sys/vmmeter.h>
81 #include <sys/vnode.h>
82 #include <sys/watchdog.h>
84 #include <machine/stdarg.h>
86 #include <security/mac/mac_framework.h>
89 #include <vm/vm_object.h>
90 #include <vm/vm_extern.h>
92 #include <vm/vm_map.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_kern.h>
101 static void delmntque(struct vnode *vp);
102 static int flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
103 int slpflag, int slptimeo);
104 static void syncer_shutdown(void *arg, int howto);
105 static int vtryrecycle(struct vnode *vp);
106 static void v_init_counters(struct vnode *);
107 static void v_incr_usecount(struct vnode *);
108 static void v_incr_usecount_locked(struct vnode *);
109 static void v_incr_devcount(struct vnode *);
110 static void v_decr_devcount(struct vnode *);
111 static void vgonel(struct vnode *);
112 static void vfs_knllock(void *arg);
113 static void vfs_knlunlock(void *arg);
114 static void vfs_knl_assert_locked(void *arg);
115 static void vfs_knl_assert_unlocked(void *arg);
116 static void destroy_vpollinfo(struct vpollinfo *vi);
119 * Number of vnodes in existence. Increased whenever getnewvnode()
120 * allocates a new vnode, decreased in vdropl() for VI_DOOMED vnode.
122 static unsigned long numvnodes;
124 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
125 "Number of vnodes in existence");
127 static counter_u64_t vnodes_created;
128 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
129 "Number of vnodes created by getnewvnode");
132 * Conversion tables for conversion from vnode types to inode formats
135 enum vtype iftovt_tab[16] = {
136 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
137 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
139 int vttoif_tab[10] = {
140 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
141 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
145 * List of vnodes that are ready for recycling.
147 static TAILQ_HEAD(freelst, vnode) vnode_free_list;
150 * "Free" vnode target. Free vnodes are rarely completely free, but are
151 * just ones that are cheap to recycle. Usually they are for files which
152 * have been stat'd but not read; these usually have inode and namecache
153 * data attached to them. This target is the preferred minimum size of a
154 * sub-cache consisting mostly of such files. The system balances the size
155 * of this sub-cache with its complement to try to prevent either from
156 * thrashing while the other is relatively inactive. The targets express
157 * a preference for the best balance.
159 * "Above" this target there are 2 further targets (watermarks) related
160 * to recyling of free vnodes. In the best-operating case, the cache is
161 * exactly full, the free list has size between vlowat and vhiwat above the
162 * free target, and recycling from it and normal use maintains this state.
163 * Sometimes the free list is below vlowat or even empty, but this state
164 * is even better for immediate use provided the cache is not full.
165 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
166 * ones) to reach one of these states. The watermarks are currently hard-
167 * coded as 4% and 9% of the available space higher. These and the default
168 * of 25% for wantfreevnodes are too large if the memory size is large.
169 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
170 * whenever vnlru_proc() becomes active.
172 static u_long wantfreevnodes;
173 SYSCTL_ULONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW,
174 &wantfreevnodes, 0, "Target for minimum number of \"free\" vnodes");
175 static u_long freevnodes;
176 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
177 &freevnodes, 0, "Number of \"free\" vnodes");
179 static counter_u64_t recycles_count;
180 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
181 "Number of vnodes recycled to meet vnode cache targets");
184 * Various variables used for debugging the new implementation of
186 * XXX these are probably of (very) limited utility now.
188 static int reassignbufcalls;
189 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0,
190 "Number of calls to reassignbuf");
192 static counter_u64_t free_owe_inact;
193 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, free_owe_inact, CTLFLAG_RD, &free_owe_inact,
194 "Number of times free vnodes kept on active list due to VFS "
195 "owing inactivation");
197 /* To keep more than one thread at a time from running vfs_getnewfsid */
198 static struct mtx mntid_mtx;
201 * Lock for any access to the following:
206 static struct mtx vnode_free_list_mtx;
208 /* Publicly exported FS */
209 struct nfs_public nfs_pub;
211 static uma_zone_t buf_trie_zone;
213 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
214 static uma_zone_t vnode_zone;
215 static uma_zone_t vnodepoll_zone;
218 * The workitem queue.
220 * It is useful to delay writes of file data and filesystem metadata
221 * for tens of seconds so that quickly created and deleted files need
222 * not waste disk bandwidth being created and removed. To realize this,
223 * we append vnodes to a "workitem" queue. When running with a soft
224 * updates implementation, most pending metadata dependencies should
225 * not wait for more than a few seconds. Thus, mounted on block devices
226 * are delayed only about a half the time that file data is delayed.
227 * Similarly, directory updates are more critical, so are only delayed
228 * about a third the time that file data is delayed. Thus, there are
229 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
230 * one each second (driven off the filesystem syncer process). The
231 * syncer_delayno variable indicates the next queue that is to be processed.
232 * Items that need to be processed soon are placed in this queue:
234 * syncer_workitem_pending[syncer_delayno]
236 * A delay of fifteen seconds is done by placing the request fifteen
237 * entries later in the queue:
239 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
242 static int syncer_delayno;
243 static long syncer_mask;
244 LIST_HEAD(synclist, bufobj);
245 static struct synclist *syncer_workitem_pending;
247 * The sync_mtx protects:
252 * syncer_workitem_pending
253 * syncer_worklist_len
256 static struct mtx sync_mtx;
257 static struct cv sync_wakeup;
259 #define SYNCER_MAXDELAY 32
260 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
261 static int syncdelay = 30; /* max time to delay syncing data */
262 static int filedelay = 30; /* time to delay syncing files */
263 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
264 "Time to delay syncing files (in seconds)");
265 static int dirdelay = 29; /* time to delay syncing directories */
266 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
267 "Time to delay syncing directories (in seconds)");
268 static int metadelay = 28; /* time to delay syncing metadata */
269 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
270 "Time to delay syncing metadata (in seconds)");
271 static int rushjob; /* number of slots to run ASAP */
272 static int stat_rush_requests; /* number of times I/O speeded up */
273 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
274 "Number of times I/O speeded up (rush requests)");
277 * When shutting down the syncer, run it at four times normal speed.
279 #define SYNCER_SHUTDOWN_SPEEDUP 4
280 static int sync_vnode_count;
281 static int syncer_worklist_len;
282 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
285 /* Target for maximum number of vnodes. */
287 static int gapvnodes; /* gap between wanted and desired */
288 static int vhiwat; /* enough extras after expansion */
289 static int vlowat; /* minimal extras before expansion */
290 static int vstir; /* nonzero to stir non-free vnodes */
291 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
294 sysctl_update_desiredvnodes(SYSCTL_HANDLER_ARGS)
296 int error, old_desiredvnodes;
298 old_desiredvnodes = desiredvnodes;
299 if ((error = sysctl_handle_int(oidp, arg1, arg2, req)) != 0)
301 if (old_desiredvnodes != desiredvnodes) {
302 wantfreevnodes = desiredvnodes / 4;
303 /* XXX locking seems to be incomplete. */
304 vfs_hash_changesize(desiredvnodes);
305 cache_changesize(desiredvnodes);
310 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
311 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, &desiredvnodes, 0,
312 sysctl_update_desiredvnodes, "I", "Target for maximum number of vnodes");
313 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
314 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
315 static int vnlru_nowhere;
316 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
317 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
319 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
323 * Support for the bufobj clean & dirty pctrie.
326 buf_trie_alloc(struct pctrie *ptree)
329 return uma_zalloc(buf_trie_zone, M_NOWAIT);
333 buf_trie_free(struct pctrie *ptree, void *node)
336 uma_zfree(buf_trie_zone, node);
338 PCTRIE_DEFINE(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free);
341 * Initialize the vnode management data structures.
343 * Reevaluate the following cap on the number of vnodes after the physical
344 * memory size exceeds 512GB. In the limit, as the physical memory size
345 * grows, the ratio of the memory size in KB to to vnodes approaches 64:1.
347 #ifndef MAXVNODES_MAX
348 #define MAXVNODES_MAX (512 * 1024 * 1024 / 64) /* 8M */
352 * Initialize a vnode as it first enters the zone.
355 vnode_init(void *mem, int size, int flags)
365 vp->v_vnlock = &vp->v_lock;
366 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
368 * By default, don't allow shared locks unless filesystems opt-in.
370 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
371 LK_NOSHARE | LK_IS_VNODE);
377 rw_init(BO_LOCKPTR(bo), "bufobj interlock");
379 TAILQ_INIT(&bo->bo_clean.bv_hd);
380 TAILQ_INIT(&bo->bo_dirty.bv_hd);
382 * Initialize namecache.
384 LIST_INIT(&vp->v_cache_src);
385 TAILQ_INIT(&vp->v_cache_dst);
387 * Initialize rangelocks.
389 rangelock_init(&vp->v_rl);
394 * Free a vnode when it is cleared from the zone.
397 vnode_fini(void *mem, int size)
403 rangelock_destroy(&vp->v_rl);
404 lockdestroy(vp->v_vnlock);
405 mtx_destroy(&vp->v_interlock);
407 rw_destroy(BO_LOCKPTR(bo));
411 * Provide the size of NFS nclnode and NFS fh for calculation of the
412 * vnode memory consumption. The size is specified directly to
413 * eliminate dependency on NFS-private header.
415 * Other filesystems may use bigger or smaller (like UFS and ZFS)
416 * private inode data, but the NFS-based estimation is ample enough.
417 * Still, we care about differences in the size between 64- and 32-bit
420 * Namecache structure size is heuristically
421 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
424 #define NFS_NCLNODE_SZ (528 + 64)
427 #define NFS_NCLNODE_SZ (360 + 32)
432 vntblinit(void *dummy __unused)
435 int physvnodes, virtvnodes;
438 * Desiredvnodes is a function of the physical memory size and the
439 * kernel's heap size. Generally speaking, it scales with the
440 * physical memory size. The ratio of desiredvnodes to the physical
441 * memory size is 1:16 until desiredvnodes exceeds 98,304.
443 * marginal ratio of desiredvnodes to the physical memory size is
444 * 1:64. However, desiredvnodes is limited by the kernel's heap
445 * size. The memory required by desiredvnodes vnodes and vm objects
446 * must not exceed 1/10th of the kernel's heap size.
448 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
449 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
450 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
451 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
452 desiredvnodes = min(physvnodes, virtvnodes);
453 if (desiredvnodes > MAXVNODES_MAX) {
455 printf("Reducing kern.maxvnodes %d -> %d\n",
456 desiredvnodes, MAXVNODES_MAX);
457 desiredvnodes = MAXVNODES_MAX;
459 wantfreevnodes = desiredvnodes / 4;
460 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
461 TAILQ_INIT(&vnode_free_list);
462 mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
463 vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
464 vnode_init, vnode_fini, UMA_ALIGN_PTR, 0);
465 vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
466 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
468 * Preallocate enough nodes to support one-per buf so that
469 * we can not fail an insert. reassignbuf() callers can not
470 * tolerate the insertion failure.
472 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
473 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
474 UMA_ZONE_NOFREE | UMA_ZONE_VM);
475 uma_prealloc(buf_trie_zone, nbuf);
477 vnodes_created = counter_u64_alloc(M_WAITOK);
478 recycles_count = counter_u64_alloc(M_WAITOK);
479 free_owe_inact = counter_u64_alloc(M_WAITOK);
482 * Initialize the filesystem syncer.
484 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
486 syncer_maxdelay = syncer_mask + 1;
487 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
488 cv_init(&sync_wakeup, "syncer");
489 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
493 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
497 * Mark a mount point as busy. Used to synchronize access and to delay
498 * unmounting. Eventually, mountlist_mtx is not released on failure.
500 * vfs_busy() is a custom lock, it can block the caller.
501 * vfs_busy() only sleeps if the unmount is active on the mount point.
502 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
503 * vnode belonging to mp.
505 * Lookup uses vfs_busy() to traverse mount points.
507 * / vnode lock A / vnode lock (/var) D
508 * /var vnode lock B /log vnode lock(/var/log) E
509 * vfs_busy lock C vfs_busy lock F
511 * Within each file system, the lock order is C->A->B and F->D->E.
513 * When traversing across mounts, the system follows that lock order:
519 * The lookup() process for namei("/var") illustrates the process:
520 * VOP_LOOKUP() obtains B while A is held
521 * vfs_busy() obtains a shared lock on F while A and B are held
522 * vput() releases lock on B
523 * vput() releases lock on A
524 * VFS_ROOT() obtains lock on D while shared lock on F is held
525 * vfs_unbusy() releases shared lock on F
526 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
527 * Attempt to lock A (instead of vp_crossmp) while D is held would
528 * violate the global order, causing deadlocks.
530 * dounmount() locks B while F is drained.
533 vfs_busy(struct mount *mp, int flags)
536 MPASS((flags & ~MBF_MASK) == 0);
537 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
542 * If mount point is currently being unmounted, sleep until the
543 * mount point fate is decided. If thread doing the unmounting fails,
544 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
545 * that this mount point has survived the unmount attempt and vfs_busy
546 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
547 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
548 * about to be really destroyed. vfs_busy needs to release its
549 * reference on the mount point in this case and return with ENOENT,
550 * telling the caller that mount mount it tried to busy is no longer
553 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
554 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
557 CTR1(KTR_VFS, "%s: failed busying before sleeping",
561 if (flags & MBF_MNTLSTLOCK)
562 mtx_unlock(&mountlist_mtx);
563 mp->mnt_kern_flag |= MNTK_MWAIT;
564 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
565 if (flags & MBF_MNTLSTLOCK)
566 mtx_lock(&mountlist_mtx);
569 if (flags & MBF_MNTLSTLOCK)
570 mtx_unlock(&mountlist_mtx);
577 * Free a busy filesystem.
580 vfs_unbusy(struct mount *mp)
583 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
586 KASSERT(mp->mnt_lockref > 0, ("negative mnt_lockref"));
588 if (mp->mnt_lockref == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
589 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
590 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
591 mp->mnt_kern_flag &= ~MNTK_DRAINING;
592 wakeup(&mp->mnt_lockref);
598 * Lookup a mount point by filesystem identifier.
601 vfs_getvfs(fsid_t *fsid)
605 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
606 mtx_lock(&mountlist_mtx);
607 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
608 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
609 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
611 mtx_unlock(&mountlist_mtx);
615 mtx_unlock(&mountlist_mtx);
616 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
617 return ((struct mount *) 0);
621 * Lookup a mount point by filesystem identifier, busying it before
624 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
625 * cache for popular filesystem identifiers. The cache is lockess, using
626 * the fact that struct mount's are never freed. In worst case we may
627 * get pointer to unmounted or even different filesystem, so we have to
628 * check what we got, and go slow way if so.
631 vfs_busyfs(fsid_t *fsid)
633 #define FSID_CACHE_SIZE 256
634 typedef struct mount * volatile vmp_t;
635 static vmp_t cache[FSID_CACHE_SIZE];
640 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
641 hash = fsid->val[0] ^ fsid->val[1];
642 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
645 mp->mnt_stat.f_fsid.val[0] != fsid->val[0] ||
646 mp->mnt_stat.f_fsid.val[1] != fsid->val[1])
648 if (vfs_busy(mp, 0) != 0) {
652 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
653 mp->mnt_stat.f_fsid.val[1] == fsid->val[1])
659 mtx_lock(&mountlist_mtx);
660 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
661 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
662 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
663 error = vfs_busy(mp, MBF_MNTLSTLOCK);
666 mtx_unlock(&mountlist_mtx);
673 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
674 mtx_unlock(&mountlist_mtx);
675 return ((struct mount *) 0);
679 * Check if a user can access privileged mount options.
682 vfs_suser(struct mount *mp, struct thread *td)
687 * If the thread is jailed, but this is not a jail-friendly file
688 * system, deny immediately.
690 if (!(mp->mnt_vfc->vfc_flags & VFCF_JAIL) && jailed(td->td_ucred))
694 * If the file system was mounted outside the jail of the calling
695 * thread, deny immediately.
697 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
701 * If file system supports delegated administration, we don't check
702 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
703 * by the file system itself.
704 * If this is not the user that did original mount, we check for
705 * the PRIV_VFS_MOUNT_OWNER privilege.
707 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
708 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
709 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
716 * Get a new unique fsid. Try to make its val[0] unique, since this value
717 * will be used to create fake device numbers for stat(). Also try (but
718 * not so hard) make its val[0] unique mod 2^16, since some emulators only
719 * support 16-bit device numbers. We end up with unique val[0]'s for the
720 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
722 * Keep in mind that several mounts may be running in parallel. Starting
723 * the search one past where the previous search terminated is both a
724 * micro-optimization and a defense against returning the same fsid to
728 vfs_getnewfsid(struct mount *mp)
730 static uint16_t mntid_base;
735 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
736 mtx_lock(&mntid_mtx);
737 mtype = mp->mnt_vfc->vfc_typenum;
738 tfsid.val[1] = mtype;
739 mtype = (mtype & 0xFF) << 24;
741 tfsid.val[0] = makedev(255,
742 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
744 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
748 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
749 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
750 mtx_unlock(&mntid_mtx);
754 * Knob to control the precision of file timestamps:
756 * 0 = seconds only; nanoseconds zeroed.
757 * 1 = seconds and nanoseconds, accurate within 1/HZ.
758 * 2 = seconds and nanoseconds, truncated to microseconds.
759 * >=3 = seconds and nanoseconds, maximum precision.
761 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
763 static int timestamp_precision = TSP_USEC;
764 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
765 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
766 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
767 "3+: sec + ns (max. precision))");
770 * Get a current timestamp.
773 vfs_timestamp(struct timespec *tsp)
777 switch (timestamp_precision) {
779 tsp->tv_sec = time_second;
787 TIMEVAL_TO_TIMESPEC(&tv, tsp);
797 * Set vnode attributes to VNOVAL
800 vattr_null(struct vattr *vap)
804 vap->va_size = VNOVAL;
805 vap->va_bytes = VNOVAL;
806 vap->va_mode = VNOVAL;
807 vap->va_nlink = VNOVAL;
808 vap->va_uid = VNOVAL;
809 vap->va_gid = VNOVAL;
810 vap->va_fsid = VNOVAL;
811 vap->va_fileid = VNOVAL;
812 vap->va_blocksize = VNOVAL;
813 vap->va_rdev = VNOVAL;
814 vap->va_atime.tv_sec = VNOVAL;
815 vap->va_atime.tv_nsec = VNOVAL;
816 vap->va_mtime.tv_sec = VNOVAL;
817 vap->va_mtime.tv_nsec = VNOVAL;
818 vap->va_ctime.tv_sec = VNOVAL;
819 vap->va_ctime.tv_nsec = VNOVAL;
820 vap->va_birthtime.tv_sec = VNOVAL;
821 vap->va_birthtime.tv_nsec = VNOVAL;
822 vap->va_flags = VNOVAL;
823 vap->va_gen = VNOVAL;
828 * This routine is called when we have too many vnodes. It attempts
829 * to free <count> vnodes and will potentially free vnodes that still
830 * have VM backing store (VM backing store is typically the cause
831 * of a vnode blowout so we want to do this). Therefore, this operation
832 * is not considered cheap.
834 * A number of conditions may prevent a vnode from being reclaimed.
835 * the buffer cache may have references on the vnode, a directory
836 * vnode may still have references due to the namei cache representing
837 * underlying files, or the vnode may be in active use. It is not
838 * desirable to reuse such vnodes. These conditions may cause the
839 * number of vnodes to reach some minimum value regardless of what
840 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
843 vlrureclaim(struct mount *mp, int reclaim_nc_src, int trigger)
846 int count, done, target;
849 vn_start_write(NULL, &mp, V_WAIT);
851 count = mp->mnt_nvnodelistsize;
852 target = count * (int64_t)gapvnodes / imax(desiredvnodes, 1);
853 target = target / 10 + 1;
854 while (count != 0 && done < target) {
855 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
856 while (vp != NULL && vp->v_type == VMARKER)
857 vp = TAILQ_NEXT(vp, v_nmntvnodes);
861 * XXX LRU is completely broken for non-free vnodes. First
862 * by calling here in mountpoint order, then by moving
863 * unselected vnodes to the end here, and most grossly by
864 * removing the vlruvp() function that was supposed to
865 * maintain the order. (This function was born broken
866 * since syncer problems prevented it doing anything.) The
867 * order is closer to LRC (C = Created).
869 * LRU reclaiming of vnodes seems to have last worked in
870 * FreeBSD-3 where LRU wasn't mentioned under any spelling.
871 * Then there was no hold count, and inactive vnodes were
872 * simply put on the free list in LRU order. The separate
873 * lists also break LRU. We prefer to reclaim from the
874 * free list for technical reasons. This tends to thrash
875 * the free list to keep very unrecently used held vnodes.
876 * The problem is mitigated by keeping the free list large.
878 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
879 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
884 * If it's been deconstructed already, it's still
885 * referenced, or it exceeds the trigger, skip it.
886 * Also skip free vnodes. We are trying to make space
887 * to expand the free list, not reduce it.
889 if (vp->v_usecount ||
890 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
891 ((vp->v_iflag & VI_FREE) != 0) ||
892 (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
893 vp->v_object->resident_page_count > trigger)) {
899 if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT)) {
901 goto next_iter_mntunlocked;
905 * v_usecount may have been bumped after VOP_LOCK() dropped
906 * the vnode interlock and before it was locked again.
908 * It is not necessary to recheck VI_DOOMED because it can
909 * only be set by another thread that holds both the vnode
910 * lock and vnode interlock. If another thread has the
911 * vnode lock before we get to VOP_LOCK() and obtains the
912 * vnode interlock after VOP_LOCK() drops the vnode
913 * interlock, the other thread will be unable to drop the
914 * vnode lock before our VOP_LOCK() call fails.
916 if (vp->v_usecount ||
917 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
918 (vp->v_iflag & VI_FREE) != 0 ||
919 (vp->v_object != NULL &&
920 vp->v_object->resident_page_count > trigger)) {
921 VOP_UNLOCK(vp, LK_INTERLOCK);
923 goto next_iter_mntunlocked;
925 KASSERT((vp->v_iflag & VI_DOOMED) == 0,
926 ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
927 counter_u64_add(recycles_count, 1);
932 next_iter_mntunlocked:
941 kern_yield(PRI_USER);
946 vn_finished_write(mp);
950 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
951 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
953 "limit on vnode free requests per call to the vnlru_free routine");
956 * Attempt to reduce the free list by the requested amount.
959 vnlru_free_locked(int count, struct vfsops *mnt_op)
964 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
965 if (count > max_vnlru_free)
966 count = max_vnlru_free;
967 for (; count > 0; count--) {
968 vp = TAILQ_FIRST(&vnode_free_list);
970 * The list can be modified while the free_list_mtx
971 * has been dropped and vp could be NULL here.
975 VNASSERT(vp->v_op != NULL, vp,
976 ("vnlru_free: vnode already reclaimed."));
977 KASSERT((vp->v_iflag & VI_FREE) != 0,
978 ("Removing vnode not on freelist"));
979 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
980 ("Mangling active vnode"));
981 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
984 * Don't recycle if our vnode is from different type
985 * of mount point. Note that mp is type-safe, the
986 * check does not reach unmapped address even if
987 * vnode is reclaimed.
988 * Don't recycle if we can't get the interlock without
991 if ((mnt_op != NULL && (mp = vp->v_mount) != NULL &&
992 mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
993 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_actfreelist);
996 VNASSERT((vp->v_iflag & VI_FREE) != 0 && vp->v_holdcnt == 0,
997 vp, ("vp inconsistent on freelist"));
1000 * The clear of VI_FREE prevents activation of the
1001 * vnode. There is no sense in putting the vnode on
1002 * the mount point active list, only to remove it
1003 * later during recycling. Inline the relevant part
1004 * of vholdl(), to avoid triggering assertions or
1008 vp->v_iflag &= ~VI_FREE;
1009 refcount_acquire(&vp->v_holdcnt);
1011 mtx_unlock(&vnode_free_list_mtx);
1015 * If the recycled succeeded this vdrop will actually free
1016 * the vnode. If not it will simply place it back on
1020 mtx_lock(&vnode_free_list_mtx);
1025 vnlru_free(int count, struct vfsops *mnt_op)
1028 mtx_lock(&vnode_free_list_mtx);
1029 vnlru_free_locked(count, mnt_op);
1030 mtx_unlock(&vnode_free_list_mtx);
1034 /* XXX some names and initialization are bad for limits and watermarks. */
1040 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1041 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1042 vlowat = vhiwat / 2;
1043 if (numvnodes > desiredvnodes)
1045 space = desiredvnodes - numvnodes;
1046 if (freevnodes > wantfreevnodes)
1047 space += freevnodes - wantfreevnodes;
1052 * Attempt to recycle vnodes in a context that is always safe to block.
1053 * Calling vlrurecycle() from the bowels of filesystem code has some
1054 * interesting deadlock problems.
1056 static struct proc *vnlruproc;
1057 static int vnlruproc_sig;
1062 struct mount *mp, *nmp;
1063 unsigned long ofreevnodes, onumvnodes;
1064 int done, force, reclaim_nc_src, trigger, usevnodes;
1066 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1067 SHUTDOWN_PRI_FIRST);
1071 kproc_suspend_check(vnlruproc);
1072 mtx_lock(&vnode_free_list_mtx);
1074 * If numvnodes is too large (due to desiredvnodes being
1075 * adjusted using its sysctl, or emergency growth), first
1076 * try to reduce it by discarding from the free list.
1078 if (numvnodes > desiredvnodes && freevnodes > 0)
1079 vnlru_free_locked(ulmin(numvnodes - desiredvnodes,
1082 * Sleep if the vnode cache is in a good state. This is
1083 * when it is not over-full and has space for about a 4%
1084 * or 9% expansion (by growing its size or inexcessively
1085 * reducing its free list). Otherwise, try to reclaim
1086 * space for a 10% expansion.
1088 if (vstir && force == 0) {
1092 if (vspace() >= vlowat && force == 0) {
1094 wakeup(&vnlruproc_sig);
1095 msleep(vnlruproc, &vnode_free_list_mtx,
1096 PVFS|PDROP, "vlruwt", hz);
1099 mtx_unlock(&vnode_free_list_mtx);
1101 ofreevnodes = freevnodes;
1102 onumvnodes = numvnodes;
1104 * Calculate parameters for recycling. These are the same
1105 * throughout the loop to give some semblance of fairness.
1106 * The trigger point is to avoid recycling vnodes with lots
1107 * of resident pages. We aren't trying to free memory; we
1108 * are trying to recycle or at least free vnodes.
1110 if (numvnodes <= desiredvnodes)
1111 usevnodes = numvnodes - freevnodes;
1113 usevnodes = numvnodes;
1117 * The trigger value is is chosen to give a conservatively
1118 * large value to ensure that it alone doesn't prevent
1119 * making progress. The value can easily be so large that
1120 * it is effectively infinite in some congested and
1121 * misconfigured cases, and this is necessary. Normally
1122 * it is about 8 to 100 (pages), which is quite large.
1124 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1126 trigger = vsmalltrigger;
1127 reclaim_nc_src = force >= 3;
1128 mtx_lock(&mountlist_mtx);
1129 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1130 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK)) {
1131 nmp = TAILQ_NEXT(mp, mnt_list);
1134 done += vlrureclaim(mp, reclaim_nc_src, trigger);
1135 mtx_lock(&mountlist_mtx);
1136 nmp = TAILQ_NEXT(mp, mnt_list);
1139 mtx_unlock(&mountlist_mtx);
1140 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1143 if (force == 0 || force == 1) {
1153 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1155 kern_yield(PRI_USER);
1157 * After becoming active to expand above low water, keep
1158 * active until above high water.
1160 force = vspace() < vhiwat;
1164 static struct kproc_desc vnlru_kp = {
1169 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1173 * Routines having to do with the management of the vnode table.
1177 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1178 * before we actually vgone(). This function must be called with the vnode
1179 * held to prevent the vnode from being returned to the free list midway
1183 vtryrecycle(struct vnode *vp)
1187 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1188 VNASSERT(vp->v_holdcnt, vp,
1189 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1191 * This vnode may found and locked via some other list, if so we
1192 * can't recycle it yet.
1194 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1196 "%s: impossible to recycle, vp %p lock is already held",
1198 return (EWOULDBLOCK);
1201 * Don't recycle if its filesystem is being suspended.
1203 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1206 "%s: impossible to recycle, cannot start the write for %p",
1211 * If we got this far, we need to acquire the interlock and see if
1212 * anyone picked up this vnode from another list. If not, we will
1213 * mark it with DOOMED via vgonel() so that anyone who does find it
1214 * will skip over it.
1217 if (vp->v_usecount) {
1218 VOP_UNLOCK(vp, LK_INTERLOCK);
1219 vn_finished_write(vnmp);
1221 "%s: impossible to recycle, %p is already referenced",
1225 if ((vp->v_iflag & VI_DOOMED) == 0) {
1226 counter_u64_add(recycles_count, 1);
1229 VOP_UNLOCK(vp, LK_INTERLOCK);
1230 vn_finished_write(vnmp);
1238 if (vspace() < vlowat && vnlruproc_sig == 0) {
1245 * Wait if necessary for space for a new vnode.
1248 getnewvnode_wait(int suspended)
1251 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
1252 if (numvnodes >= desiredvnodes) {
1255 * The file system is being suspended. We cannot
1256 * risk a deadlock here, so allow allocation of
1257 * another vnode even if this would give too many.
1261 if (vnlruproc_sig == 0) {
1262 vnlruproc_sig = 1; /* avoid unnecessary wakeups */
1265 msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
1268 /* Post-adjust like the pre-adjust in getnewvnode(). */
1269 if (numvnodes + 1 > desiredvnodes && freevnodes > 1)
1270 vnlru_free_locked(1, NULL);
1271 return (numvnodes >= desiredvnodes ? ENFILE : 0);
1275 * This hack is fragile, and probably not needed any more now that the
1276 * watermark handling works.
1279 getnewvnode_reserve(u_int count)
1283 /* Pre-adjust like the pre-adjust in getnewvnode(), with any count. */
1284 /* XXX no longer so quick, but this part is not racy. */
1285 mtx_lock(&vnode_free_list_mtx);
1286 if (numvnodes + count > desiredvnodes && freevnodes > wantfreevnodes)
1287 vnlru_free_locked(ulmin(numvnodes + count - desiredvnodes,
1288 freevnodes - wantfreevnodes), NULL);
1289 mtx_unlock(&vnode_free_list_mtx);
1292 /* First try to be quick and racy. */
1293 if (atomic_fetchadd_long(&numvnodes, count) + count <= desiredvnodes) {
1294 td->td_vp_reserv += count;
1295 vcheckspace(); /* XXX no longer so quick, but more racy */
1298 atomic_subtract_long(&numvnodes, count);
1300 mtx_lock(&vnode_free_list_mtx);
1302 if (getnewvnode_wait(0) == 0) {
1305 atomic_add_long(&numvnodes, 1);
1309 mtx_unlock(&vnode_free_list_mtx);
1313 * This hack is fragile, especially if desiredvnodes or wantvnodes are
1314 * misconfgured or changed significantly. Reducing desiredvnodes below
1315 * the reserved amount should cause bizarre behaviour like reducing it
1316 * below the number of active vnodes -- the system will try to reduce
1317 * numvnodes to match, but should fail, so the subtraction below should
1321 getnewvnode_drop_reserve(void)
1326 atomic_subtract_long(&numvnodes, td->td_vp_reserv);
1327 td->td_vp_reserv = 0;
1331 * Return the next vnode from the free list.
1334 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1339 struct lock_object *lo;
1340 static int cyclecount;
1343 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1346 if (td->td_vp_reserv > 0) {
1347 td->td_vp_reserv -= 1;
1350 mtx_lock(&vnode_free_list_mtx);
1351 if (numvnodes < desiredvnodes)
1353 else if (cyclecount++ >= freevnodes) {
1358 * Grow the vnode cache if it will not be above its target max
1359 * after growing. Otherwise, if the free list is nonempty, try
1360 * to reclaim 1 item from it before growing the cache (possibly
1361 * above its target max if the reclamation failed or is delayed).
1362 * Otherwise, wait for some space. In all cases, schedule
1363 * vnlru_proc() if we are getting short of space. The watermarks
1364 * should be chosen so that we never wait or even reclaim from
1365 * the free list to below its target minimum.
1367 if (numvnodes + 1 <= desiredvnodes)
1369 else if (freevnodes > 0)
1370 vnlru_free_locked(1, NULL);
1372 error = getnewvnode_wait(mp != NULL && (mp->mnt_kern_flag &
1374 #if 0 /* XXX Not all VFS_VGET/ffs_vget callers check returns. */
1376 mtx_unlock(&vnode_free_list_mtx);
1382 atomic_add_long(&numvnodes, 1);
1383 mtx_unlock(&vnode_free_list_mtx);
1385 counter_u64_add(vnodes_created, 1);
1386 vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK);
1388 * Locks are given the generic name "vnode" when created.
1389 * Follow the historic practice of using the filesystem
1390 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1392 * Locks live in a witness group keyed on their name. Thus,
1393 * when a lock is renamed, it must also move from the witness
1394 * group of its old name to the witness group of its new name.
1396 * The change only needs to be made when the vnode moves
1397 * from one filesystem type to another. We ensure that each
1398 * filesystem use a single static name pointer for its tag so
1399 * that we can compare pointers rather than doing a strcmp().
1401 lo = &vp->v_vnlock->lock_object;
1402 if (lo->lo_name != tag) {
1404 WITNESS_DESTROY(lo);
1405 WITNESS_INIT(lo, tag);
1408 * By default, don't allow shared locks unless filesystems opt-in.
1410 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1412 * Finalize various vnode identity bits.
1414 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1415 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1416 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1420 v_init_counters(vp);
1421 vp->v_bufobj.bo_ops = &buf_ops_bio;
1423 if (mp == NULL && vops != &dead_vnodeops)
1424 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1428 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1429 mac_vnode_associate_singlelabel(mp, vp);
1432 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1433 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1434 vp->v_vflag |= VV_NOKNOTE;
1438 * For the filesystems which do not use vfs_hash_insert(),
1439 * still initialize v_hash to have vfs_hash_index() useful.
1440 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1443 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1450 * Delete from old mount point vnode list, if on one.
1453 delmntque(struct vnode *vp)
1463 KASSERT(mp->mnt_activevnodelistsize <= mp->mnt_nvnodelistsize,
1464 ("Active vnode list size %d > Vnode list size %d",
1465 mp->mnt_activevnodelistsize, mp->mnt_nvnodelistsize));
1466 active = vp->v_iflag & VI_ACTIVE;
1467 vp->v_iflag &= ~VI_ACTIVE;
1469 mtx_lock(&vnode_free_list_mtx);
1470 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp, v_actfreelist);
1471 mp->mnt_activevnodelistsize--;
1472 mtx_unlock(&vnode_free_list_mtx);
1476 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1477 ("bad mount point vnode list size"));
1478 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1479 mp->mnt_nvnodelistsize--;
1485 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1489 vp->v_op = &dead_vnodeops;
1495 * Insert into list of vnodes for the new mount point, if available.
1498 insmntque1(struct vnode *vp, struct mount *mp,
1499 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1502 KASSERT(vp->v_mount == NULL,
1503 ("insmntque: vnode already on per mount vnode list"));
1504 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1505 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1508 * We acquire the vnode interlock early to ensure that the
1509 * vnode cannot be recycled by another process releasing a
1510 * holdcnt on it before we get it on both the vnode list
1511 * and the active vnode list. The mount mutex protects only
1512 * manipulation of the vnode list and the vnode freelist
1513 * mutex protects only manipulation of the active vnode list.
1514 * Hence the need to hold the vnode interlock throughout.
1518 if (((mp->mnt_kern_flag & MNTK_NOINSMNTQ) != 0 &&
1519 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1520 mp->mnt_nvnodelistsize == 0)) &&
1521 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1530 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1531 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1532 ("neg mount point vnode list size"));
1533 mp->mnt_nvnodelistsize++;
1534 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1535 ("Activating already active vnode"));
1536 vp->v_iflag |= VI_ACTIVE;
1537 mtx_lock(&vnode_free_list_mtx);
1538 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
1539 mp->mnt_activevnodelistsize++;
1540 mtx_unlock(&vnode_free_list_mtx);
1547 insmntque(struct vnode *vp, struct mount *mp)
1550 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1554 * Flush out and invalidate all buffers associated with a bufobj
1555 * Called with the underlying object locked.
1558 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1563 if (flags & V_SAVE) {
1564 error = bufobj_wwait(bo, slpflag, slptimeo);
1569 if (bo->bo_dirty.bv_cnt > 0) {
1571 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1574 * XXX We could save a lock/unlock if this was only
1575 * enabled under INVARIANTS
1578 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1579 panic("vinvalbuf: dirty bufs");
1583 * If you alter this loop please notice that interlock is dropped and
1584 * reacquired in flushbuflist. Special care is needed to ensure that
1585 * no race conditions occur from this.
1588 error = flushbuflist(&bo->bo_clean,
1589 flags, bo, slpflag, slptimeo);
1590 if (error == 0 && !(flags & V_CLEANONLY))
1591 error = flushbuflist(&bo->bo_dirty,
1592 flags, bo, slpflag, slptimeo);
1593 if (error != 0 && error != EAGAIN) {
1597 } while (error != 0);
1600 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1601 * have write I/O in-progress but if there is a VM object then the
1602 * VM object can also have read-I/O in-progress.
1605 bufobj_wwait(bo, 0, 0);
1606 if ((flags & V_VMIO) == 0) {
1608 if (bo->bo_object != NULL) {
1609 VM_OBJECT_WLOCK(bo->bo_object);
1610 vm_object_pip_wait(bo->bo_object, "bovlbx");
1611 VM_OBJECT_WUNLOCK(bo->bo_object);
1615 } while (bo->bo_numoutput > 0);
1619 * Destroy the copy in the VM cache, too.
1621 if (bo->bo_object != NULL &&
1622 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1623 VM_OBJECT_WLOCK(bo->bo_object);
1624 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1625 OBJPR_CLEANONLY : 0);
1626 VM_OBJECT_WUNLOCK(bo->bo_object);
1631 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1632 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1633 bo->bo_clean.bv_cnt > 0))
1634 panic("vinvalbuf: flush failed");
1635 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1636 bo->bo_dirty.bv_cnt > 0)
1637 panic("vinvalbuf: flush dirty failed");
1644 * Flush out and invalidate all buffers associated with a vnode.
1645 * Called with the underlying object locked.
1648 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1651 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1652 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1653 if (vp->v_object != NULL && vp->v_object->handle != vp)
1655 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1659 * Flush out buffers on the specified list.
1663 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1666 struct buf *bp, *nbp;
1671 ASSERT_BO_WLOCKED(bo);
1674 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1675 if (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA)) ||
1676 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0)) {
1682 lblkno = nbp->b_lblkno;
1683 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
1686 error = BUF_TIMELOCK(bp,
1687 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
1688 "flushbuf", slpflag, slptimeo);
1691 return (error != ENOLCK ? error : EAGAIN);
1693 KASSERT(bp->b_bufobj == bo,
1694 ("bp %p wrong b_bufobj %p should be %p",
1695 bp, bp->b_bufobj, bo));
1697 * XXX Since there are no node locks for NFS, I
1698 * believe there is a slight chance that a delayed
1699 * write will occur while sleeping just above, so
1702 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1705 bp->b_flags |= B_ASYNC;
1708 return (EAGAIN); /* XXX: why not loop ? */
1711 bp->b_flags |= (B_INVAL | B_RELBUF);
1712 bp->b_flags &= ~B_ASYNC;
1715 nbp = gbincore(bo, lblkno);
1716 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1718 break; /* nbp invalid */
1724 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
1730 ASSERT_BO_LOCKED(bo);
1732 for (lblkno = startn;;) {
1734 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
1735 if (bp == NULL || bp->b_lblkno >= endn ||
1736 bp->b_lblkno < startn)
1738 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
1739 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
1742 if (error == ENOLCK)
1746 KASSERT(bp->b_bufobj == bo,
1747 ("bp %p wrong b_bufobj %p should be %p",
1748 bp, bp->b_bufobj, bo));
1749 lblkno = bp->b_lblkno + 1;
1750 if ((bp->b_flags & B_MANAGED) == 0)
1752 bp->b_flags |= B_RELBUF;
1754 * In the VMIO case, use the B_NOREUSE flag to hint that the
1755 * pages backing each buffer in the range are unlikely to be
1756 * reused. Dirty buffers will have the hint applied once
1757 * they've been written.
1759 if (bp->b_vp->v_object != NULL)
1760 bp->b_flags |= B_NOREUSE;
1768 * Truncate a file's buffer and pages to a specified length. This
1769 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
1773 vtruncbuf(struct vnode *vp, struct ucred *cred, off_t length, int blksize)
1775 struct buf *bp, *nbp;
1780 CTR5(KTR_VFS, "%s: vp %p with cred %p and block %d:%ju", __func__,
1781 vp, cred, blksize, (uintmax_t)length);
1784 * Round up to the *next* lbn.
1786 trunclbn = howmany(length, blksize);
1788 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
1795 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
1796 if (bp->b_lblkno < trunclbn)
1799 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1800 BO_LOCKPTR(bo)) == ENOLCK)
1804 bp->b_flags |= (B_INVAL | B_RELBUF);
1805 bp->b_flags &= ~B_ASYNC;
1811 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
1812 (nbp->b_vp != vp) ||
1813 (nbp->b_flags & B_DELWRI))) {
1819 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1820 if (bp->b_lblkno < trunclbn)
1823 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1824 BO_LOCKPTR(bo)) == ENOLCK)
1827 bp->b_flags |= (B_INVAL | B_RELBUF);
1828 bp->b_flags &= ~B_ASYNC;
1834 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
1835 (nbp->b_vp != vp) ||
1836 (nbp->b_flags & B_DELWRI) == 0)) {
1845 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1846 if (bp->b_lblkno > 0)
1849 * Since we hold the vnode lock this should only
1850 * fail if we're racing with the buf daemon.
1853 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1854 BO_LOCKPTR(bo)) == ENOLCK) {
1857 VNASSERT((bp->b_flags & B_DELWRI), vp,
1858 ("buf(%p) on dirty queue without DELWRI", bp));
1867 bufobj_wwait(bo, 0, 0);
1869 vnode_pager_setsize(vp, length);
1875 buf_vlist_remove(struct buf *bp)
1879 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1880 ASSERT_BO_WLOCKED(bp->b_bufobj);
1881 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
1882 (BX_VNDIRTY|BX_VNCLEAN),
1883 ("buf_vlist_remove: Buf %p is on two lists", bp));
1884 if (bp->b_xflags & BX_VNDIRTY)
1885 bv = &bp->b_bufobj->bo_dirty;
1887 bv = &bp->b_bufobj->bo_clean;
1888 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
1889 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
1891 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1895 * Add the buffer to the sorted clean or dirty block list.
1897 * NOTE: xflags is passed as a constant, optimizing this inline function!
1900 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
1906 ASSERT_BO_WLOCKED(bo);
1907 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
1908 ("dead bo %p", bo));
1909 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
1910 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
1911 bp->b_xflags |= xflags;
1912 if (xflags & BX_VNDIRTY)
1918 * Keep the list ordered. Optimize empty list insertion. Assume
1919 * we tend to grow at the tail so lookup_le should usually be cheaper
1922 if (bv->bv_cnt == 0 ||
1923 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
1924 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
1925 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
1926 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
1928 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
1929 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
1931 panic("buf_vlist_add: Preallocated nodes insufficient.");
1936 * Look up a buffer using the buffer tries.
1939 gbincore(struct bufobj *bo, daddr_t lblkno)
1943 ASSERT_BO_LOCKED(bo);
1944 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
1947 return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
1951 * Associate a buffer with a vnode.
1954 bgetvp(struct vnode *vp, struct buf *bp)
1959 ASSERT_BO_WLOCKED(bo);
1960 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
1962 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
1963 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
1964 ("bgetvp: bp already attached! %p", bp));
1970 * Insert onto list for new vnode.
1972 buf_vlist_add(bp, bo, BX_VNCLEAN);
1976 * Disassociate a buffer from a vnode.
1979 brelvp(struct buf *bp)
1984 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1985 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1988 * Delete from old vnode list, if on one.
1990 vp = bp->b_vp; /* XXX */
1993 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1994 buf_vlist_remove(bp);
1996 panic("brelvp: Buffer %p not on queue.", bp);
1997 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1998 bo->bo_flag &= ~BO_ONWORKLST;
1999 mtx_lock(&sync_mtx);
2000 LIST_REMOVE(bo, bo_synclist);
2001 syncer_worklist_len--;
2002 mtx_unlock(&sync_mtx);
2005 bp->b_bufobj = NULL;
2011 * Add an item to the syncer work queue.
2014 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2018 ASSERT_BO_WLOCKED(bo);
2020 mtx_lock(&sync_mtx);
2021 if (bo->bo_flag & BO_ONWORKLST)
2022 LIST_REMOVE(bo, bo_synclist);
2024 bo->bo_flag |= BO_ONWORKLST;
2025 syncer_worklist_len++;
2028 if (delay > syncer_maxdelay - 2)
2029 delay = syncer_maxdelay - 2;
2030 slot = (syncer_delayno + delay) & syncer_mask;
2032 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2033 mtx_unlock(&sync_mtx);
2037 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2041 mtx_lock(&sync_mtx);
2042 len = syncer_worklist_len - sync_vnode_count;
2043 mtx_unlock(&sync_mtx);
2044 error = SYSCTL_OUT(req, &len, sizeof(len));
2048 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
2049 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2051 static struct proc *updateproc;
2052 static void sched_sync(void);
2053 static struct kproc_desc up_kp = {
2058 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2061 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2066 *bo = LIST_FIRST(slp);
2069 vp = (*bo)->__bo_vnode; /* XXX */
2070 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2073 * We use vhold in case the vnode does not
2074 * successfully sync. vhold prevents the vnode from
2075 * going away when we unlock the sync_mtx so that
2076 * we can acquire the vnode interlock.
2079 mtx_unlock(&sync_mtx);
2081 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2083 mtx_lock(&sync_mtx);
2084 return (*bo == LIST_FIRST(slp));
2086 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2087 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2089 vn_finished_write(mp);
2091 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2093 * Put us back on the worklist. The worklist
2094 * routine will remove us from our current
2095 * position and then add us back in at a later
2098 vn_syncer_add_to_worklist(*bo, syncdelay);
2102 mtx_lock(&sync_mtx);
2106 static int first_printf = 1;
2109 * System filesystem synchronizer daemon.
2114 struct synclist *next, *slp;
2117 struct thread *td = curthread;
2119 int net_worklist_len;
2120 int syncer_final_iter;
2124 syncer_final_iter = 0;
2125 syncer_state = SYNCER_RUNNING;
2126 starttime = time_uptime;
2127 td->td_pflags |= TDP_NORUNNINGBUF;
2129 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2132 mtx_lock(&sync_mtx);
2134 if (syncer_state == SYNCER_FINAL_DELAY &&
2135 syncer_final_iter == 0) {
2136 mtx_unlock(&sync_mtx);
2137 kproc_suspend_check(td->td_proc);
2138 mtx_lock(&sync_mtx);
2140 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2141 if (syncer_state != SYNCER_RUNNING &&
2142 starttime != time_uptime) {
2144 printf("\nSyncing disks, vnodes remaining... ");
2147 printf("%d ", net_worklist_len);
2149 starttime = time_uptime;
2152 * Push files whose dirty time has expired. Be careful
2153 * of interrupt race on slp queue.
2155 * Skip over empty worklist slots when shutting down.
2158 slp = &syncer_workitem_pending[syncer_delayno];
2159 syncer_delayno += 1;
2160 if (syncer_delayno == syncer_maxdelay)
2162 next = &syncer_workitem_pending[syncer_delayno];
2164 * If the worklist has wrapped since the
2165 * it was emptied of all but syncer vnodes,
2166 * switch to the FINAL_DELAY state and run
2167 * for one more second.
2169 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2170 net_worklist_len == 0 &&
2171 last_work_seen == syncer_delayno) {
2172 syncer_state = SYNCER_FINAL_DELAY;
2173 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2175 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2176 syncer_worklist_len > 0);
2179 * Keep track of the last time there was anything
2180 * on the worklist other than syncer vnodes.
2181 * Return to the SHUTTING_DOWN state if any
2184 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2185 last_work_seen = syncer_delayno;
2186 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2187 syncer_state = SYNCER_SHUTTING_DOWN;
2188 while (!LIST_EMPTY(slp)) {
2189 error = sync_vnode(slp, &bo, td);
2191 LIST_REMOVE(bo, bo_synclist);
2192 LIST_INSERT_HEAD(next, bo, bo_synclist);
2196 if (first_printf == 0) {
2198 * Drop the sync mutex, because some watchdog
2199 * drivers need to sleep while patting
2201 mtx_unlock(&sync_mtx);
2202 wdog_kern_pat(WD_LASTVAL);
2203 mtx_lock(&sync_mtx);
2207 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2208 syncer_final_iter--;
2210 * The variable rushjob allows the kernel to speed up the
2211 * processing of the filesystem syncer process. A rushjob
2212 * value of N tells the filesystem syncer to process the next
2213 * N seconds worth of work on its queue ASAP. Currently rushjob
2214 * is used by the soft update code to speed up the filesystem
2215 * syncer process when the incore state is getting so far
2216 * ahead of the disk that the kernel memory pool is being
2217 * threatened with exhaustion.
2224 * Just sleep for a short period of time between
2225 * iterations when shutting down to allow some I/O
2228 * If it has taken us less than a second to process the
2229 * current work, then wait. Otherwise start right over
2230 * again. We can still lose time if any single round
2231 * takes more than two seconds, but it does not really
2232 * matter as we are just trying to generally pace the
2233 * filesystem activity.
2235 if (syncer_state != SYNCER_RUNNING ||
2236 time_uptime == starttime) {
2238 sched_prio(td, PPAUSE);
2241 if (syncer_state != SYNCER_RUNNING)
2242 cv_timedwait(&sync_wakeup, &sync_mtx,
2243 hz / SYNCER_SHUTDOWN_SPEEDUP);
2244 else if (time_uptime == starttime)
2245 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2250 * Request the syncer daemon to speed up its work.
2251 * We never push it to speed up more than half of its
2252 * normal turn time, otherwise it could take over the cpu.
2255 speedup_syncer(void)
2259 mtx_lock(&sync_mtx);
2260 if (rushjob < syncdelay / 2) {
2262 stat_rush_requests += 1;
2265 mtx_unlock(&sync_mtx);
2266 cv_broadcast(&sync_wakeup);
2271 * Tell the syncer to speed up its work and run though its work
2272 * list several times, then tell it to shut down.
2275 syncer_shutdown(void *arg, int howto)
2278 if (howto & RB_NOSYNC)
2280 mtx_lock(&sync_mtx);
2281 syncer_state = SYNCER_SHUTTING_DOWN;
2283 mtx_unlock(&sync_mtx);
2284 cv_broadcast(&sync_wakeup);
2285 kproc_shutdown(arg, howto);
2289 syncer_suspend(void)
2292 syncer_shutdown(updateproc, 0);
2299 mtx_lock(&sync_mtx);
2301 syncer_state = SYNCER_RUNNING;
2302 mtx_unlock(&sync_mtx);
2303 cv_broadcast(&sync_wakeup);
2304 kproc_resume(updateproc);
2308 * Reassign a buffer from one vnode to another.
2309 * Used to assign file specific control information
2310 * (indirect blocks) to the vnode to which they belong.
2313 reassignbuf(struct buf *bp)
2326 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2327 bp, bp->b_vp, bp->b_flags);
2329 * B_PAGING flagged buffers cannot be reassigned because their vp
2330 * is not fully linked in.
2332 if (bp->b_flags & B_PAGING)
2333 panic("cannot reassign paging buffer");
2336 * Delete from old vnode list, if on one.
2339 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2340 buf_vlist_remove(bp);
2342 panic("reassignbuf: Buffer %p not on queue.", bp);
2344 * If dirty, put on list of dirty buffers; otherwise insert onto list
2347 if (bp->b_flags & B_DELWRI) {
2348 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2349 switch (vp->v_type) {
2359 vn_syncer_add_to_worklist(bo, delay);
2361 buf_vlist_add(bp, bo, BX_VNDIRTY);
2363 buf_vlist_add(bp, bo, BX_VNCLEAN);
2365 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2366 mtx_lock(&sync_mtx);
2367 LIST_REMOVE(bo, bo_synclist);
2368 syncer_worklist_len--;
2369 mtx_unlock(&sync_mtx);
2370 bo->bo_flag &= ~BO_ONWORKLST;
2375 bp = TAILQ_FIRST(&bv->bv_hd);
2376 KASSERT(bp == NULL || bp->b_bufobj == bo,
2377 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2378 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2379 KASSERT(bp == NULL || bp->b_bufobj == bo,
2380 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2382 bp = TAILQ_FIRST(&bv->bv_hd);
2383 KASSERT(bp == NULL || bp->b_bufobj == bo,
2384 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2385 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2386 KASSERT(bp == NULL || bp->b_bufobj == bo,
2387 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2393 * A temporary hack until refcount_* APIs are sorted out.
2396 vfs_refcount_acquire_if_not_zero(volatile u_int *count)
2404 if (atomic_fcmpset_int(count, &old, old + 1))
2410 vfs_refcount_release_if_not_last(volatile u_int *count)
2418 if (atomic_fcmpset_int(count, &old, old - 1))
2424 v_init_counters(struct vnode *vp)
2427 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2428 vp, ("%s called for an initialized vnode", __FUNCTION__));
2429 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2431 refcount_init(&vp->v_holdcnt, 1);
2432 refcount_init(&vp->v_usecount, 1);
2436 v_incr_usecount_locked(struct vnode *vp)
2439 ASSERT_VI_LOCKED(vp, __func__);
2440 if ((vp->v_iflag & VI_OWEINACT) != 0) {
2441 VNASSERT(vp->v_usecount == 0, vp,
2442 ("vnode with usecount and VI_OWEINACT set"));
2443 vp->v_iflag &= ~VI_OWEINACT;
2445 refcount_acquire(&vp->v_usecount);
2446 v_incr_devcount(vp);
2450 * Increment the use and hold counts on the vnode, taking care to reference
2451 * the driver's usecount if this is a chardev. The _vhold() will remove
2452 * the vnode from the free list if it is presently free.
2455 v_incr_usecount(struct vnode *vp)
2458 ASSERT_VI_UNLOCKED(vp, __func__);
2459 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2461 if (vp->v_type != VCHR &&
2462 vfs_refcount_acquire_if_not_zero(&vp->v_usecount)) {
2463 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2464 ("vnode with usecount and VI_OWEINACT set"));
2467 v_incr_usecount_locked(vp);
2473 * Increment si_usecount of the associated device, if any.
2476 v_incr_devcount(struct vnode *vp)
2479 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2480 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2482 vp->v_rdev->si_usecount++;
2488 * Decrement si_usecount of the associated device, if any.
2491 v_decr_devcount(struct vnode *vp)
2494 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2495 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2497 vp->v_rdev->si_usecount--;
2503 * Grab a particular vnode from the free list, increment its
2504 * reference count and lock it. VI_DOOMED is set if the vnode
2505 * is being destroyed. Only callers who specify LK_RETRY will
2506 * see doomed vnodes. If inactive processing was delayed in
2507 * vput try to do it here.
2509 * Notes on lockless counter manipulation:
2510 * _vhold, vputx and other routines make various decisions based
2511 * on either holdcnt or usecount being 0. As long as either counter
2512 * is not transitioning 0->1 nor 1->0, the manipulation can be done
2513 * with atomic operations. Otherwise the interlock is taken covering
2514 * both the atomic and additional actions.
2517 vget(struct vnode *vp, int flags, struct thread *td)
2519 int error, oweinact;
2521 VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2522 ("vget: invalid lock operation"));
2524 if ((flags & LK_INTERLOCK) != 0)
2525 ASSERT_VI_LOCKED(vp, __func__);
2527 ASSERT_VI_UNLOCKED(vp, __func__);
2528 if ((flags & LK_VNHELD) != 0)
2529 VNASSERT((vp->v_holdcnt > 0), vp,
2530 ("vget: LK_VNHELD passed but vnode not held"));
2532 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2534 if ((flags & LK_VNHELD) == 0)
2535 _vhold(vp, (flags & LK_INTERLOCK) != 0);
2537 if ((error = vn_lock(vp, flags)) != 0) {
2539 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2543 if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0)
2544 panic("vget: vn_lock failed to return ENOENT\n");
2546 * We don't guarantee that any particular close will
2547 * trigger inactive processing so just make a best effort
2548 * here at preventing a reference to a removed file. If
2549 * we don't succeed no harm is done.
2551 * Upgrade our holdcnt to a usecount.
2553 if (vp->v_type == VCHR ||
2554 !vfs_refcount_acquire_if_not_zero(&vp->v_usecount)) {
2556 if ((vp->v_iflag & VI_OWEINACT) == 0) {
2560 vp->v_iflag &= ~VI_OWEINACT;
2562 refcount_acquire(&vp->v_usecount);
2563 v_incr_devcount(vp);
2564 if (oweinact && VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2565 (flags & LK_NOWAIT) == 0)
2573 * Increase the reference count of a vnode.
2576 vref(struct vnode *vp)
2579 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2581 v_incr_usecount(vp);
2585 vrefl(struct vnode *vp)
2588 ASSERT_VI_LOCKED(vp, __func__);
2589 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2591 v_incr_usecount_locked(vp);
2595 vrefact(struct vnode *vp)
2598 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2599 if (__predict_false(vp->v_type == VCHR)) {
2600 VNASSERT(vp->v_holdcnt > 0 && vp->v_usecount > 0, vp,
2601 ("%s: wrong ref counts", __func__));
2606 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
2607 VNASSERT(old > 0, vp, ("%s: wrong hold count", __func__));
2608 old = atomic_fetchadd_int(&vp->v_usecount, 1);
2609 VNASSERT(old > 0, vp, ("%s: wrong use count", __func__));
2611 refcount_acquire(&vp->v_holdcnt);
2612 refcount_acquire(&vp->v_usecount);
2617 * Return reference count of a vnode.
2619 * The results of this call are only guaranteed when some mechanism is used to
2620 * stop other processes from gaining references to the vnode. This may be the
2621 * case if the caller holds the only reference. This is also useful when stale
2622 * data is acceptable as race conditions may be accounted for by some other
2626 vrefcnt(struct vnode *vp)
2629 return (vp->v_usecount);
2632 #define VPUTX_VRELE 1
2633 #define VPUTX_VPUT 2
2634 #define VPUTX_VUNREF 3
2637 * Decrement the use and hold counts for a vnode.
2639 * See an explanation near vget() as to why atomic operation is safe.
2642 vputx(struct vnode *vp, int func)
2646 KASSERT(vp != NULL, ("vputx: null vp"));
2647 if (func == VPUTX_VUNREF)
2648 ASSERT_VOP_LOCKED(vp, "vunref");
2649 else if (func == VPUTX_VPUT)
2650 ASSERT_VOP_LOCKED(vp, "vput");
2652 KASSERT(func == VPUTX_VRELE, ("vputx: wrong func"));
2653 ASSERT_VI_UNLOCKED(vp, __func__);
2654 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2656 if (vp->v_type != VCHR &&
2657 vfs_refcount_release_if_not_last(&vp->v_usecount)) {
2658 if (func == VPUTX_VPUT)
2667 * We want to hold the vnode until the inactive finishes to
2668 * prevent vgone() races. We drop the use count here and the
2669 * hold count below when we're done.
2671 if (!refcount_release(&vp->v_usecount) ||
2672 (vp->v_iflag & VI_DOINGINACT)) {
2673 if (func == VPUTX_VPUT)
2675 v_decr_devcount(vp);
2680 v_decr_devcount(vp);
2684 if (vp->v_usecount != 0) {
2685 vn_printf(vp, "vputx: usecount not zero for vnode ");
2686 panic("vputx: usecount not zero");
2689 CTR2(KTR_VFS, "%s: return vnode %p to the freelist", __func__, vp);
2692 * We must call VOP_INACTIVE with the node locked. Mark
2693 * as VI_DOINGINACT to avoid recursion.
2695 vp->v_iflag |= VI_OWEINACT;
2698 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
2702 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2703 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
2709 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2710 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
2715 VNASSERT(vp->v_usecount == 0 || (vp->v_iflag & VI_OWEINACT) == 0, vp,
2716 ("vnode with usecount and VI_OWEINACT set"));
2718 if (vp->v_iflag & VI_OWEINACT)
2719 vinactive(vp, curthread);
2720 if (func != VPUTX_VUNREF)
2727 * Vnode put/release.
2728 * If count drops to zero, call inactive routine and return to freelist.
2731 vrele(struct vnode *vp)
2734 vputx(vp, VPUTX_VRELE);
2738 * Release an already locked vnode. This give the same effects as
2739 * unlock+vrele(), but takes less time and avoids releasing and
2740 * re-aquiring the lock (as vrele() acquires the lock internally.)
2743 vput(struct vnode *vp)
2746 vputx(vp, VPUTX_VPUT);
2750 * Release an exclusively locked vnode. Do not unlock the vnode lock.
2753 vunref(struct vnode *vp)
2756 vputx(vp, VPUTX_VUNREF);
2760 * Increase the hold count and activate if this is the first reference.
2763 _vhold(struct vnode *vp, bool locked)
2768 ASSERT_VI_LOCKED(vp, __func__);
2770 ASSERT_VI_UNLOCKED(vp, __func__);
2771 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2772 if (!locked && vfs_refcount_acquire_if_not_zero(&vp->v_holdcnt)) {
2773 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2774 ("_vhold: vnode with holdcnt is free"));
2780 if ((vp->v_iflag & VI_FREE) == 0) {
2781 refcount_acquire(&vp->v_holdcnt);
2786 VNASSERT(vp->v_holdcnt == 0, vp,
2787 ("%s: wrong hold count", __func__));
2788 VNASSERT(vp->v_op != NULL, vp,
2789 ("%s: vnode already reclaimed.", __func__));
2791 * Remove a vnode from the free list, mark it as in use,
2792 * and put it on the active list.
2794 mtx_lock(&vnode_free_list_mtx);
2795 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
2797 vp->v_iflag &= ~VI_FREE;
2798 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
2799 ("Activating already active vnode"));
2800 vp->v_iflag |= VI_ACTIVE;
2802 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
2803 mp->mnt_activevnodelistsize++;
2804 mtx_unlock(&vnode_free_list_mtx);
2805 refcount_acquire(&vp->v_holdcnt);
2811 * Drop the hold count of the vnode. If this is the last reference to
2812 * the vnode we place it on the free list unless it has been vgone'd
2813 * (marked VI_DOOMED) in which case we will free it.
2815 * Because the vnode vm object keeps a hold reference on the vnode if
2816 * there is at least one resident non-cached page, the vnode cannot
2817 * leave the active list without the page cleanup done.
2820 _vdrop(struct vnode *vp, bool locked)
2827 ASSERT_VI_LOCKED(vp, __func__);
2829 ASSERT_VI_UNLOCKED(vp, __func__);
2830 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2831 if ((int)vp->v_holdcnt <= 0)
2832 panic("vdrop: holdcnt %d", vp->v_holdcnt);
2833 if (vfs_refcount_release_if_not_last(&vp->v_holdcnt)) {
2841 if (refcount_release(&vp->v_holdcnt) == 0) {
2845 if ((vp->v_iflag & VI_DOOMED) == 0) {
2847 * Mark a vnode as free: remove it from its active list
2848 * and put it up for recycling on the freelist.
2850 VNASSERT(vp->v_op != NULL, vp,
2851 ("vdropl: vnode already reclaimed."));
2852 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2853 ("vnode already free"));
2854 VNASSERT(vp->v_holdcnt == 0, vp,
2855 ("vdropl: freeing when we shouldn't"));
2856 active = vp->v_iflag & VI_ACTIVE;
2857 if ((vp->v_iflag & VI_OWEINACT) == 0) {
2858 vp->v_iflag &= ~VI_ACTIVE;
2860 mtx_lock(&vnode_free_list_mtx);
2862 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp,
2864 mp->mnt_activevnodelistsize--;
2866 TAILQ_INSERT_TAIL(&vnode_free_list, vp,
2869 vp->v_iflag |= VI_FREE;
2870 mtx_unlock(&vnode_free_list_mtx);
2872 counter_u64_add(free_owe_inact, 1);
2878 * The vnode has been marked for destruction, so free it.
2880 * The vnode will be returned to the zone where it will
2881 * normally remain until it is needed for another vnode. We
2882 * need to cleanup (or verify that the cleanup has already
2883 * been done) any residual data left from its current use
2884 * so as not to contaminate the freshly allocated vnode.
2886 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
2887 atomic_subtract_long(&numvnodes, 1);
2889 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2890 ("cleaned vnode still on the free list."));
2891 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
2892 VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
2893 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
2894 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
2895 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
2896 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
2897 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
2898 ("clean blk trie not empty"));
2899 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
2900 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
2901 ("dirty blk trie not empty"));
2902 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
2903 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
2904 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
2905 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
2906 ("Dangling rangelock waiters"));
2909 mac_vnode_destroy(vp);
2911 if (vp->v_pollinfo != NULL) {
2912 destroy_vpollinfo(vp->v_pollinfo);
2913 vp->v_pollinfo = NULL;
2916 /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
2919 bzero(&vp->v_un, sizeof(vp->v_un));
2920 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
2924 uma_zfree(vnode_zone, vp);
2928 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
2929 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
2930 * OWEINACT tracks whether a vnode missed a call to inactive due to a
2931 * failed lock upgrade.
2934 vinactive(struct vnode *vp, struct thread *td)
2936 struct vm_object *obj;
2938 ASSERT_VOP_ELOCKED(vp, "vinactive");
2939 ASSERT_VI_LOCKED(vp, "vinactive");
2940 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
2941 ("vinactive: recursed on VI_DOINGINACT"));
2942 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2943 vp->v_iflag |= VI_DOINGINACT;
2944 vp->v_iflag &= ~VI_OWEINACT;
2947 * Before moving off the active list, we must be sure that any
2948 * modified pages are converted into the vnode's dirty
2949 * buffers, since these will no longer be checked once the
2950 * vnode is on the inactive list.
2952 * The write-out of the dirty pages is asynchronous. At the
2953 * point that VOP_INACTIVE() is called, there could still be
2954 * pending I/O and dirty pages in the object.
2956 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
2957 (obj->flags & OBJ_MIGHTBEDIRTY) != 0) {
2958 VM_OBJECT_WLOCK(obj);
2959 vm_object_page_clean(obj, 0, 0, 0);
2960 VM_OBJECT_WUNLOCK(obj);
2962 VOP_INACTIVE(vp, td);
2964 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
2965 ("vinactive: lost VI_DOINGINACT"));
2966 vp->v_iflag &= ~VI_DOINGINACT;
2970 * Remove any vnodes in the vnode table belonging to mount point mp.
2972 * If FORCECLOSE is not specified, there should not be any active ones,
2973 * return error if any are found (nb: this is a user error, not a
2974 * system error). If FORCECLOSE is specified, detach any active vnodes
2977 * If WRITECLOSE is set, only flush out regular file vnodes open for
2980 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
2982 * `rootrefs' specifies the base reference count for the root vnode
2983 * of this filesystem. The root vnode is considered busy if its
2984 * v_usecount exceeds this value. On a successful return, vflush(, td)
2985 * will call vrele() on the root vnode exactly rootrefs times.
2986 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
2990 static int busyprt = 0; /* print out busy vnodes */
2991 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
2995 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
2997 struct vnode *vp, *mvp, *rootvp = NULL;
2999 int busy = 0, error;
3001 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3004 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3005 ("vflush: bad args"));
3007 * Get the filesystem root vnode. We can vput() it
3008 * immediately, since with rootrefs > 0, it won't go away.
3010 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3011 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3018 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3020 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3023 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3027 * Skip over a vnodes marked VV_SYSTEM.
3029 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3035 * If WRITECLOSE is set, flush out unlinked but still open
3036 * files (even if open only for reading) and regular file
3037 * vnodes open for writing.
3039 if (flags & WRITECLOSE) {
3040 if (vp->v_object != NULL) {
3041 VM_OBJECT_WLOCK(vp->v_object);
3042 vm_object_page_clean(vp->v_object, 0, 0, 0);
3043 VM_OBJECT_WUNLOCK(vp->v_object);
3045 error = VOP_FSYNC(vp, MNT_WAIT, td);
3049 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3052 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3055 if ((vp->v_type == VNON ||
3056 (error == 0 && vattr.va_nlink > 0)) &&
3057 (vp->v_writecount == 0 || vp->v_type != VREG)) {
3065 * With v_usecount == 0, all we need to do is clear out the
3066 * vnode data structures and we are done.
3068 * If FORCECLOSE is set, forcibly close the vnode.
3070 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3076 vn_printf(vp, "vflush: busy vnode ");
3082 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3084 * If just the root vnode is busy, and if its refcount
3085 * is equal to `rootrefs', then go ahead and kill it.
3088 KASSERT(busy > 0, ("vflush: not busy"));
3089 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3090 ("vflush: usecount %d < rootrefs %d",
3091 rootvp->v_usecount, rootrefs));
3092 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3093 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3095 VOP_UNLOCK(rootvp, 0);
3101 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3105 for (; rootrefs > 0; rootrefs--)
3111 * Recycle an unused vnode to the front of the free list.
3114 vrecycle(struct vnode *vp)
3118 ASSERT_VOP_ELOCKED(vp, "vrecycle");
3119 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3122 if (vp->v_usecount == 0) {
3131 * Eliminate all activity associated with a vnode
3132 * in preparation for reuse.
3135 vgone(struct vnode *vp)
3143 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3144 struct vnode *lowervp __unused)
3149 * Notify upper mounts about reclaimed or unlinked vnode.
3152 vfs_notify_upper(struct vnode *vp, int event)
3154 static struct vfsops vgonel_vfsops = {
3155 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3156 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3158 struct mount *mp, *ump, *mmp;
3165 if (TAILQ_EMPTY(&mp->mnt_uppers))
3168 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3169 mmp->mnt_op = &vgonel_vfsops;
3170 mmp->mnt_kern_flag |= MNTK_MARKER;
3172 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3173 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3174 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3175 ump = TAILQ_NEXT(ump, mnt_upper_link);
3178 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3181 case VFS_NOTIFY_UPPER_RECLAIM:
3182 VFS_RECLAIM_LOWERVP(ump, vp);
3184 case VFS_NOTIFY_UPPER_UNLINK:
3185 VFS_UNLINK_LOWERVP(ump, vp);
3188 KASSERT(0, ("invalid event %d", event));
3192 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3193 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3196 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3197 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3198 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3199 wakeup(&mp->mnt_uppers);
3206 * vgone, with the vp interlock held.
3209 vgonel(struct vnode *vp)
3216 ASSERT_VOP_ELOCKED(vp, "vgonel");
3217 ASSERT_VI_LOCKED(vp, "vgonel");
3218 VNASSERT(vp->v_holdcnt, vp,
3219 ("vgonel: vp %p has no reference.", vp));
3220 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3224 * Don't vgonel if we're already doomed.
3226 if (vp->v_iflag & VI_DOOMED)
3228 vp->v_iflag |= VI_DOOMED;
3231 * Check to see if the vnode is in use. If so, we have to call
3232 * VOP_CLOSE() and VOP_INACTIVE().
3234 active = vp->v_usecount;
3235 oweinact = (vp->v_iflag & VI_OWEINACT);
3237 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
3240 * If purging an active vnode, it must be closed and
3241 * deactivated before being reclaimed.
3244 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
3245 if (oweinact || active) {
3247 if ((vp->v_iflag & VI_DOINGINACT) == 0)
3251 if (vp->v_type == VSOCK)
3252 vfs_unp_reclaim(vp);
3255 * Clean out any buffers associated with the vnode.
3256 * If the flush fails, just toss the buffers.
3259 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
3260 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
3261 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
3262 while (vinvalbuf(vp, 0, 0, 0) != 0)
3266 BO_LOCK(&vp->v_bufobj);
3267 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
3268 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
3269 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
3270 vp->v_bufobj.bo_clean.bv_cnt == 0,
3271 ("vp %p bufobj not invalidated", vp));
3274 * For VMIO bufobj, BO_DEAD is set in vm_object_terminate()
3275 * after the object's page queue is flushed.
3277 if (vp->v_bufobj.bo_object == NULL)
3278 vp->v_bufobj.bo_flag |= BO_DEAD;
3279 BO_UNLOCK(&vp->v_bufobj);
3282 * Reclaim the vnode.
3284 if (VOP_RECLAIM(vp, td))
3285 panic("vgone: cannot reclaim");
3287 vn_finished_secondary_write(mp);
3288 VNASSERT(vp->v_object == NULL, vp,
3289 ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
3291 * Clear the advisory locks and wake up waiting threads.
3293 (void)VOP_ADVLOCKPURGE(vp);
3296 * Delete from old mount point vnode list.
3301 * Done with purge, reset to the standard lock and invalidate
3305 vp->v_vnlock = &vp->v_lock;
3306 vp->v_op = &dead_vnodeops;
3312 * Calculate the total number of references to a special device.
3315 vcount(struct vnode *vp)
3320 count = vp->v_rdev->si_usecount;
3326 * Same as above, but using the struct cdev *as argument
3329 count_dev(struct cdev *dev)
3334 count = dev->si_usecount;
3340 * Print out a description of a vnode.
3342 static char *typename[] =
3343 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
3347 vn_printf(struct vnode *vp, const char *fmt, ...)
3350 char buf[256], buf2[16];
3356 printf("%p: ", (void *)vp);
3357 printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
3358 printf(" usecount %d, writecount %d, refcount %d mountedhere %p\n",
3359 vp->v_usecount, vp->v_writecount, vp->v_holdcnt, vp->v_mountedhere);
3362 if (vp->v_vflag & VV_ROOT)
3363 strlcat(buf, "|VV_ROOT", sizeof(buf));
3364 if (vp->v_vflag & VV_ISTTY)
3365 strlcat(buf, "|VV_ISTTY", sizeof(buf));
3366 if (vp->v_vflag & VV_NOSYNC)
3367 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
3368 if (vp->v_vflag & VV_ETERNALDEV)
3369 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
3370 if (vp->v_vflag & VV_CACHEDLABEL)
3371 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
3372 if (vp->v_vflag & VV_TEXT)
3373 strlcat(buf, "|VV_TEXT", sizeof(buf));
3374 if (vp->v_vflag & VV_COPYONWRITE)
3375 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
3376 if (vp->v_vflag & VV_SYSTEM)
3377 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
3378 if (vp->v_vflag & VV_PROCDEP)
3379 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
3380 if (vp->v_vflag & VV_NOKNOTE)
3381 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
3382 if (vp->v_vflag & VV_DELETED)
3383 strlcat(buf, "|VV_DELETED", sizeof(buf));
3384 if (vp->v_vflag & VV_MD)
3385 strlcat(buf, "|VV_MD", sizeof(buf));
3386 if (vp->v_vflag & VV_FORCEINSMQ)
3387 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
3388 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
3389 VV_CACHEDLABEL | VV_TEXT | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
3390 VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
3392 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
3393 strlcat(buf, buf2, sizeof(buf));
3395 if (vp->v_iflag & VI_MOUNT)
3396 strlcat(buf, "|VI_MOUNT", sizeof(buf));
3397 if (vp->v_iflag & VI_DOOMED)
3398 strlcat(buf, "|VI_DOOMED", sizeof(buf));
3399 if (vp->v_iflag & VI_FREE)
3400 strlcat(buf, "|VI_FREE", sizeof(buf));
3401 if (vp->v_iflag & VI_ACTIVE)
3402 strlcat(buf, "|VI_ACTIVE", sizeof(buf));
3403 if (vp->v_iflag & VI_DOINGINACT)
3404 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
3405 if (vp->v_iflag & VI_OWEINACT)
3406 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
3407 flags = vp->v_iflag & ~(VI_MOUNT | VI_DOOMED | VI_FREE |
3408 VI_ACTIVE | VI_DOINGINACT | VI_OWEINACT);
3410 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
3411 strlcat(buf, buf2, sizeof(buf));
3413 printf(" flags (%s)\n", buf + 1);
3414 if (mtx_owned(VI_MTX(vp)))
3415 printf(" VI_LOCKed");
3416 if (vp->v_object != NULL)
3417 printf(" v_object %p ref %d pages %d "
3418 "cleanbuf %d dirtybuf %d\n",
3419 vp->v_object, vp->v_object->ref_count,
3420 vp->v_object->resident_page_count,
3421 vp->v_bufobj.bo_clean.bv_cnt,
3422 vp->v_bufobj.bo_dirty.bv_cnt);
3424 lockmgr_printinfo(vp->v_vnlock);
3425 if (vp->v_data != NULL)
3431 * List all of the locked vnodes in the system.
3432 * Called when debugging the kernel.
3434 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
3440 * Note: because this is DDB, we can't obey the locking semantics
3441 * for these structures, which means we could catch an inconsistent
3442 * state and dereference a nasty pointer. Not much to be done
3445 db_printf("Locked vnodes\n");
3446 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3447 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3448 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
3449 vn_printf(vp, "vnode ");
3455 * Show details about the given vnode.
3457 DB_SHOW_COMMAND(vnode, db_show_vnode)
3463 vp = (struct vnode *)addr;
3464 vn_printf(vp, "vnode ");
3468 * Show details about the given mount point.
3470 DB_SHOW_COMMAND(mount, db_show_mount)
3481 /* No address given, print short info about all mount points. */
3482 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3483 db_printf("%p %s on %s (%s)\n", mp,
3484 mp->mnt_stat.f_mntfromname,
3485 mp->mnt_stat.f_mntonname,
3486 mp->mnt_stat.f_fstypename);
3490 db_printf("\nMore info: show mount <addr>\n");
3494 mp = (struct mount *)addr;
3495 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
3496 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
3499 mflags = mp->mnt_flag;
3500 #define MNT_FLAG(flag) do { \
3501 if (mflags & (flag)) { \
3502 if (buf[0] != '\0') \
3503 strlcat(buf, ", ", sizeof(buf)); \
3504 strlcat(buf, (#flag) + 4, sizeof(buf)); \
3505 mflags &= ~(flag); \
3508 MNT_FLAG(MNT_RDONLY);
3509 MNT_FLAG(MNT_SYNCHRONOUS);
3510 MNT_FLAG(MNT_NOEXEC);
3511 MNT_FLAG(MNT_NOSUID);
3512 MNT_FLAG(MNT_NFS4ACLS);
3513 MNT_FLAG(MNT_UNION);
3514 MNT_FLAG(MNT_ASYNC);
3515 MNT_FLAG(MNT_SUIDDIR);
3516 MNT_FLAG(MNT_SOFTDEP);
3517 MNT_FLAG(MNT_NOSYMFOLLOW);
3518 MNT_FLAG(MNT_GJOURNAL);
3519 MNT_FLAG(MNT_MULTILABEL);
3521 MNT_FLAG(MNT_NOATIME);
3522 MNT_FLAG(MNT_NOCLUSTERR);
3523 MNT_FLAG(MNT_NOCLUSTERW);
3525 MNT_FLAG(MNT_EXRDONLY);
3526 MNT_FLAG(MNT_EXPORTED);
3527 MNT_FLAG(MNT_DEFEXPORTED);
3528 MNT_FLAG(MNT_EXPORTANON);
3529 MNT_FLAG(MNT_EXKERB);
3530 MNT_FLAG(MNT_EXPUBLIC);
3531 MNT_FLAG(MNT_LOCAL);
3532 MNT_FLAG(MNT_QUOTA);
3533 MNT_FLAG(MNT_ROOTFS);
3535 MNT_FLAG(MNT_IGNORE);
3536 MNT_FLAG(MNT_UPDATE);
3537 MNT_FLAG(MNT_DELEXPORT);
3538 MNT_FLAG(MNT_RELOAD);
3539 MNT_FLAG(MNT_FORCE);
3540 MNT_FLAG(MNT_SNAPSHOT);
3541 MNT_FLAG(MNT_BYFSID);
3545 strlcat(buf, ", ", sizeof(buf));
3546 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3547 "0x%016jx", mflags);
3549 db_printf(" mnt_flag = %s\n", buf);
3552 flags = mp->mnt_kern_flag;
3553 #define MNT_KERN_FLAG(flag) do { \
3554 if (flags & (flag)) { \
3555 if (buf[0] != '\0') \
3556 strlcat(buf, ", ", sizeof(buf)); \
3557 strlcat(buf, (#flag) + 5, sizeof(buf)); \
3561 MNT_KERN_FLAG(MNTK_UNMOUNTF);
3562 MNT_KERN_FLAG(MNTK_ASYNC);
3563 MNT_KERN_FLAG(MNTK_SOFTDEP);
3564 MNT_KERN_FLAG(MNTK_NOINSMNTQ);
3565 MNT_KERN_FLAG(MNTK_DRAINING);
3566 MNT_KERN_FLAG(MNTK_REFEXPIRE);
3567 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
3568 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
3569 MNT_KERN_FLAG(MNTK_NO_IOPF);
3570 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
3571 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
3572 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
3573 MNT_KERN_FLAG(MNTK_MARKER);
3574 MNT_KERN_FLAG(MNTK_USES_BCACHE);
3575 MNT_KERN_FLAG(MNTK_NOASYNC);
3576 MNT_KERN_FLAG(MNTK_UNMOUNT);
3577 MNT_KERN_FLAG(MNTK_MWAIT);
3578 MNT_KERN_FLAG(MNTK_SUSPEND);
3579 MNT_KERN_FLAG(MNTK_SUSPEND2);
3580 MNT_KERN_FLAG(MNTK_SUSPENDED);
3581 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
3582 MNT_KERN_FLAG(MNTK_NOKNOTE);
3583 #undef MNT_KERN_FLAG
3586 strlcat(buf, ", ", sizeof(buf));
3587 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3590 db_printf(" mnt_kern_flag = %s\n", buf);
3592 db_printf(" mnt_opt = ");
3593 opt = TAILQ_FIRST(mp->mnt_opt);
3595 db_printf("%s", opt->name);
3596 opt = TAILQ_NEXT(opt, link);
3597 while (opt != NULL) {
3598 db_printf(", %s", opt->name);
3599 opt = TAILQ_NEXT(opt, link);
3605 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
3606 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
3607 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
3608 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
3609 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
3610 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
3611 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
3612 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
3613 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
3614 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
3615 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
3616 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
3618 db_printf(" mnt_cred = { uid=%u ruid=%u",
3619 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
3620 if (jailed(mp->mnt_cred))
3621 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
3623 db_printf(" mnt_ref = %d\n", mp->mnt_ref);
3624 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
3625 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
3626 db_printf(" mnt_activevnodelistsize = %d\n",
3627 mp->mnt_activevnodelistsize);
3628 db_printf(" mnt_writeopcount = %d\n", mp->mnt_writeopcount);
3629 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
3630 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
3631 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
3632 db_printf(" mnt_lockref = %d\n", mp->mnt_lockref);
3633 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
3634 db_printf(" mnt_secondary_accwrites = %d\n",
3635 mp->mnt_secondary_accwrites);
3636 db_printf(" mnt_gjprovider = %s\n",
3637 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
3639 db_printf("\n\nList of active vnodes\n");
3640 TAILQ_FOREACH(vp, &mp->mnt_activevnodelist, v_actfreelist) {
3641 if (vp->v_type != VMARKER) {
3642 vn_printf(vp, "vnode ");
3647 db_printf("\n\nList of inactive vnodes\n");
3648 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3649 if (vp->v_type != VMARKER && (vp->v_iflag & VI_ACTIVE) == 0) {
3650 vn_printf(vp, "vnode ");
3659 * Fill in a struct xvfsconf based on a struct vfsconf.
3662 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
3664 struct xvfsconf xvfsp;
3666 bzero(&xvfsp, sizeof(xvfsp));
3667 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
3668 xvfsp.vfc_typenum = vfsp->vfc_typenum;
3669 xvfsp.vfc_refcount = vfsp->vfc_refcount;
3670 xvfsp.vfc_flags = vfsp->vfc_flags;
3672 * These are unused in userland, we keep them
3673 * to not break binary compatibility.
3675 xvfsp.vfc_vfsops = NULL;
3676 xvfsp.vfc_next = NULL;
3677 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3680 #ifdef COMPAT_FREEBSD32
3682 uint32_t vfc_vfsops;
3683 char vfc_name[MFSNAMELEN];
3684 int32_t vfc_typenum;
3685 int32_t vfc_refcount;
3691 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
3693 struct xvfsconf32 xvfsp;
3695 bzero(&xvfsp, sizeof(xvfsp));
3696 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
3697 xvfsp.vfc_typenum = vfsp->vfc_typenum;
3698 xvfsp.vfc_refcount = vfsp->vfc_refcount;
3699 xvfsp.vfc_flags = vfsp->vfc_flags;
3700 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3705 * Top level filesystem related information gathering.
3708 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
3710 struct vfsconf *vfsp;
3715 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3716 #ifdef COMPAT_FREEBSD32
3717 if (req->flags & SCTL_MASK32)
3718 error = vfsconf2x32(req, vfsp);
3721 error = vfsconf2x(req, vfsp);
3729 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
3730 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
3731 "S,xvfsconf", "List of all configured filesystems");
3733 #ifndef BURN_BRIDGES
3734 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
3737 vfs_sysctl(SYSCTL_HANDLER_ARGS)
3739 int *name = (int *)arg1 - 1; /* XXX */
3740 u_int namelen = arg2 + 1; /* XXX */
3741 struct vfsconf *vfsp;
3743 log(LOG_WARNING, "userland calling deprecated sysctl, "
3744 "please rebuild world\n");
3746 #if 1 || defined(COMPAT_PRELITE2)
3747 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
3749 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
3753 case VFS_MAXTYPENUM:
3756 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
3759 return (ENOTDIR); /* overloaded */
3761 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3762 if (vfsp->vfc_typenum == name[2])
3767 return (EOPNOTSUPP);
3768 #ifdef COMPAT_FREEBSD32
3769 if (req->flags & SCTL_MASK32)
3770 return (vfsconf2x32(req, vfsp));
3773 return (vfsconf2x(req, vfsp));
3775 return (EOPNOTSUPP);
3778 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
3779 CTLFLAG_MPSAFE, vfs_sysctl,
3780 "Generic filesystem");
3782 #if 1 || defined(COMPAT_PRELITE2)
3785 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
3788 struct vfsconf *vfsp;
3789 struct ovfsconf ovfs;
3792 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3793 bzero(&ovfs, sizeof(ovfs));
3794 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
3795 strcpy(ovfs.vfc_name, vfsp->vfc_name);
3796 ovfs.vfc_index = vfsp->vfc_typenum;
3797 ovfs.vfc_refcount = vfsp->vfc_refcount;
3798 ovfs.vfc_flags = vfsp->vfc_flags;
3799 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
3809 #endif /* 1 || COMPAT_PRELITE2 */
3810 #endif /* !BURN_BRIDGES */
3812 #define KINFO_VNODESLOP 10
3815 * Dump vnode list (via sysctl).
3819 sysctl_vnode(SYSCTL_HANDLER_ARGS)
3827 * Stale numvnodes access is not fatal here.
3830 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
3832 /* Make an estimate */
3833 return (SYSCTL_OUT(req, 0, len));
3835 error = sysctl_wire_old_buffer(req, 0);
3838 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
3840 mtx_lock(&mountlist_mtx);
3841 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3842 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
3845 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3849 xvn[n].xv_size = sizeof *xvn;
3850 xvn[n].xv_vnode = vp;
3851 xvn[n].xv_id = 0; /* XXX compat */
3852 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
3854 XV_COPY(writecount);
3860 xvn[n].xv_flag = vp->v_vflag;
3862 switch (vp->v_type) {
3869 if (vp->v_rdev == NULL) {
3873 xvn[n].xv_dev = dev2udev(vp->v_rdev);
3876 xvn[n].xv_socket = vp->v_socket;
3879 xvn[n].xv_fifo = vp->v_fifoinfo;
3884 /* shouldn't happen? */
3892 mtx_lock(&mountlist_mtx);
3897 mtx_unlock(&mountlist_mtx);
3899 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
3904 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
3905 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
3910 unmount_or_warn(struct mount *mp)
3914 error = dounmount(mp, MNT_FORCE, curthread);
3916 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
3920 printf("%d)\n", error);
3925 * Unmount all filesystems. The list is traversed in reverse order
3926 * of mounting to avoid dependencies.
3929 vfs_unmountall(void)
3931 struct mount *mp, *tmp;
3933 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
3936 * Since this only runs when rebooting, it is not interlocked.
3938 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
3942 * Forcibly unmounting "/dev" before "/" would prevent clean
3943 * unmount of the latter.
3945 if (mp == rootdevmp)
3948 unmount_or_warn(mp);
3951 if (rootdevmp != NULL)
3952 unmount_or_warn(rootdevmp);
3956 * perform msync on all vnodes under a mount point
3957 * the mount point must be locked.
3960 vfs_msync(struct mount *mp, int flags)
3962 struct vnode *vp, *mvp;
3963 struct vm_object *obj;
3965 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
3966 MNT_VNODE_FOREACH_ACTIVE(vp, mp, mvp) {
3968 if (obj != NULL && (obj->flags & OBJ_MIGHTBEDIRTY) != 0 &&
3969 (flags == MNT_WAIT || VOP_ISLOCKED(vp) == 0)) {
3971 LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
3973 if (vp->v_vflag & VV_NOSYNC) { /* unlinked */
3980 VM_OBJECT_WLOCK(obj);
3981 vm_object_page_clean(obj, 0, 0,
3983 OBJPC_SYNC : OBJPC_NOSYNC);
3984 VM_OBJECT_WUNLOCK(obj);
3994 destroy_vpollinfo_free(struct vpollinfo *vi)
3997 knlist_destroy(&vi->vpi_selinfo.si_note);
3998 mtx_destroy(&vi->vpi_lock);
3999 uma_zfree(vnodepoll_zone, vi);
4003 destroy_vpollinfo(struct vpollinfo *vi)
4006 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4007 seldrain(&vi->vpi_selinfo);
4008 destroy_vpollinfo_free(vi);
4012 * Initialize per-vnode helper structure to hold poll-related state.
4015 v_addpollinfo(struct vnode *vp)
4017 struct vpollinfo *vi;
4019 if (vp->v_pollinfo != NULL)
4021 vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4022 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4023 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4024 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4026 if (vp->v_pollinfo != NULL) {
4028 destroy_vpollinfo_free(vi);
4031 vp->v_pollinfo = vi;
4036 * Record a process's interest in events which might happen to
4037 * a vnode. Because poll uses the historic select-style interface
4038 * internally, this routine serves as both the ``check for any
4039 * pending events'' and the ``record my interest in future events''
4040 * functions. (These are done together, while the lock is held,
4041 * to avoid race conditions.)
4044 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4048 mtx_lock(&vp->v_pollinfo->vpi_lock);
4049 if (vp->v_pollinfo->vpi_revents & events) {
4051 * This leaves events we are not interested
4052 * in available for the other process which
4053 * which presumably had requested them
4054 * (otherwise they would never have been
4057 events &= vp->v_pollinfo->vpi_revents;
4058 vp->v_pollinfo->vpi_revents &= ~events;
4060 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4063 vp->v_pollinfo->vpi_events |= events;
4064 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4065 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4070 * Routine to create and manage a filesystem syncer vnode.
4072 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4073 static int sync_fsync(struct vop_fsync_args *);
4074 static int sync_inactive(struct vop_inactive_args *);
4075 static int sync_reclaim(struct vop_reclaim_args *);
4077 static struct vop_vector sync_vnodeops = {
4078 .vop_bypass = VOP_EOPNOTSUPP,
4079 .vop_close = sync_close, /* close */
4080 .vop_fsync = sync_fsync, /* fsync */
4081 .vop_inactive = sync_inactive, /* inactive */
4082 .vop_reclaim = sync_reclaim, /* reclaim */
4083 .vop_lock1 = vop_stdlock, /* lock */
4084 .vop_unlock = vop_stdunlock, /* unlock */
4085 .vop_islocked = vop_stdislocked, /* islocked */
4089 * Create a new filesystem syncer vnode for the specified mount point.
4092 vfs_allocate_syncvnode(struct mount *mp)
4096 static long start, incr, next;
4099 /* Allocate a new vnode */
4100 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
4102 panic("vfs_allocate_syncvnode: getnewvnode() failed");
4104 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4105 vp->v_vflag |= VV_FORCEINSMQ;
4106 error = insmntque(vp, mp);
4108 panic("vfs_allocate_syncvnode: insmntque() failed");
4109 vp->v_vflag &= ~VV_FORCEINSMQ;
4112 * Place the vnode onto the syncer worklist. We attempt to
4113 * scatter them about on the list so that they will go off
4114 * at evenly distributed times even if all the filesystems
4115 * are mounted at once.
4118 if (next == 0 || next > syncer_maxdelay) {
4122 start = syncer_maxdelay / 2;
4123 incr = syncer_maxdelay;
4129 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
4130 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
4131 mtx_lock(&sync_mtx);
4133 if (mp->mnt_syncer == NULL) {
4134 mp->mnt_syncer = vp;
4137 mtx_unlock(&sync_mtx);
4140 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4147 vfs_deallocate_syncvnode(struct mount *mp)
4151 mtx_lock(&sync_mtx);
4152 vp = mp->mnt_syncer;
4154 mp->mnt_syncer = NULL;
4155 mtx_unlock(&sync_mtx);
4161 * Do a lazy sync of the filesystem.
4164 sync_fsync(struct vop_fsync_args *ap)
4166 struct vnode *syncvp = ap->a_vp;
4167 struct mount *mp = syncvp->v_mount;
4172 * We only need to do something if this is a lazy evaluation.
4174 if (ap->a_waitfor != MNT_LAZY)
4178 * Move ourselves to the back of the sync list.
4180 bo = &syncvp->v_bufobj;
4182 vn_syncer_add_to_worklist(bo, syncdelay);
4186 * Walk the list of vnodes pushing all that are dirty and
4187 * not already on the sync list.
4189 if (vfs_busy(mp, MBF_NOWAIT) != 0)
4191 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
4195 save = curthread_pflags_set(TDP_SYNCIO);
4196 vfs_msync(mp, MNT_NOWAIT);
4197 error = VFS_SYNC(mp, MNT_LAZY);
4198 curthread_pflags_restore(save);
4199 vn_finished_write(mp);
4205 * The syncer vnode is no referenced.
4208 sync_inactive(struct vop_inactive_args *ap)
4216 * The syncer vnode is no longer needed and is being decommissioned.
4218 * Modifications to the worklist must be protected by sync_mtx.
4221 sync_reclaim(struct vop_reclaim_args *ap)
4223 struct vnode *vp = ap->a_vp;
4228 mtx_lock(&sync_mtx);
4229 if (vp->v_mount->mnt_syncer == vp)
4230 vp->v_mount->mnt_syncer = NULL;
4231 if (bo->bo_flag & BO_ONWORKLST) {
4232 LIST_REMOVE(bo, bo_synclist);
4233 syncer_worklist_len--;
4235 bo->bo_flag &= ~BO_ONWORKLST;
4237 mtx_unlock(&sync_mtx);
4244 * Check if vnode represents a disk device
4247 vn_isdisk(struct vnode *vp, int *errp)
4251 if (vp->v_type != VCHR) {
4257 if (vp->v_rdev == NULL)
4259 else if (vp->v_rdev->si_devsw == NULL)
4261 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
4267 return (error == 0);
4271 * Common filesystem object access control check routine. Accepts a
4272 * vnode's type, "mode", uid and gid, requested access mode, credentials,
4273 * and optional call-by-reference privused argument allowing vaccess()
4274 * to indicate to the caller whether privilege was used to satisfy the
4275 * request (obsoleted). Returns 0 on success, or an errno on failure.
4278 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
4279 accmode_t accmode, struct ucred *cred, int *privused)
4281 accmode_t dac_granted;
4282 accmode_t priv_granted;
4284 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
4285 ("invalid bit in accmode"));
4286 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
4287 ("VAPPEND without VWRITE"));
4290 * Look for a normal, non-privileged way to access the file/directory
4291 * as requested. If it exists, go with that.
4294 if (privused != NULL)
4299 /* Check the owner. */
4300 if (cred->cr_uid == file_uid) {
4301 dac_granted |= VADMIN;
4302 if (file_mode & S_IXUSR)
4303 dac_granted |= VEXEC;
4304 if (file_mode & S_IRUSR)
4305 dac_granted |= VREAD;
4306 if (file_mode & S_IWUSR)
4307 dac_granted |= (VWRITE | VAPPEND);
4309 if ((accmode & dac_granted) == accmode)
4315 /* Otherwise, check the groups (first match) */
4316 if (groupmember(file_gid, cred)) {
4317 if (file_mode & S_IXGRP)
4318 dac_granted |= VEXEC;
4319 if (file_mode & S_IRGRP)
4320 dac_granted |= VREAD;
4321 if (file_mode & S_IWGRP)
4322 dac_granted |= (VWRITE | VAPPEND);
4324 if ((accmode & dac_granted) == accmode)
4330 /* Otherwise, check everyone else. */
4331 if (file_mode & S_IXOTH)
4332 dac_granted |= VEXEC;
4333 if (file_mode & S_IROTH)
4334 dac_granted |= VREAD;
4335 if (file_mode & S_IWOTH)
4336 dac_granted |= (VWRITE | VAPPEND);
4337 if ((accmode & dac_granted) == accmode)
4342 * Build a privilege mask to determine if the set of privileges
4343 * satisfies the requirements when combined with the granted mask
4344 * from above. For each privilege, if the privilege is required,
4345 * bitwise or the request type onto the priv_granted mask.
4351 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
4352 * requests, instead of PRIV_VFS_EXEC.
4354 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4355 !priv_check_cred(cred, PRIV_VFS_LOOKUP, 0))
4356 priv_granted |= VEXEC;
4359 * Ensure that at least one execute bit is on. Otherwise,
4360 * a privileged user will always succeed, and we don't want
4361 * this to happen unless the file really is executable.
4363 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4364 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
4365 !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
4366 priv_granted |= VEXEC;
4369 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
4370 !priv_check_cred(cred, PRIV_VFS_READ, 0))
4371 priv_granted |= VREAD;
4373 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
4374 !priv_check_cred(cred, PRIV_VFS_WRITE, 0))
4375 priv_granted |= (VWRITE | VAPPEND);
4377 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
4378 !priv_check_cred(cred, PRIV_VFS_ADMIN, 0))
4379 priv_granted |= VADMIN;
4381 if ((accmode & (priv_granted | dac_granted)) == accmode) {
4382 /* XXX audit: privilege used */
4383 if (privused != NULL)
4388 return ((accmode & VADMIN) ? EPERM : EACCES);
4392 * Credential check based on process requesting service, and per-attribute
4396 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
4397 struct thread *td, accmode_t accmode)
4401 * Kernel-invoked always succeeds.
4407 * Do not allow privileged processes in jail to directly manipulate
4408 * system attributes.
4410 switch (attrnamespace) {
4411 case EXTATTR_NAMESPACE_SYSTEM:
4412 /* Potentially should be: return (EPERM); */
4413 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM, 0));
4414 case EXTATTR_NAMESPACE_USER:
4415 return (VOP_ACCESS(vp, accmode, cred, td));
4421 #ifdef DEBUG_VFS_LOCKS
4423 * This only exists to suppress warnings from unlocked specfs accesses. It is
4424 * no longer ok to have an unlocked VFS.
4426 #define IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL || \
4427 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
4429 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
4430 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
4431 "Drop into debugger on lock violation");
4433 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
4434 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
4435 0, "Check for interlock across VOPs");
4437 int vfs_badlock_print = 1; /* Print lock violations. */
4438 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
4439 0, "Print lock violations");
4441 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
4442 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
4443 0, "Print vnode details on lock violations");
4446 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
4447 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
4448 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
4452 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
4456 if (vfs_badlock_backtrace)
4459 if (vfs_badlock_vnode)
4460 vn_printf(vp, "vnode ");
4461 if (vfs_badlock_print)
4462 printf("%s: %p %s\n", str, (void *)vp, msg);
4463 if (vfs_badlock_ddb)
4464 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4468 assert_vi_locked(struct vnode *vp, const char *str)
4471 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
4472 vfs_badlock("interlock is not locked but should be", str, vp);
4476 assert_vi_unlocked(struct vnode *vp, const char *str)
4479 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
4480 vfs_badlock("interlock is locked but should not be", str, vp);
4484 assert_vop_locked(struct vnode *vp, const char *str)
4488 if (!IGNORE_LOCK(vp)) {
4489 locked = VOP_ISLOCKED(vp);
4490 if (locked == 0 || locked == LK_EXCLOTHER)
4491 vfs_badlock("is not locked but should be", str, vp);
4496 assert_vop_unlocked(struct vnode *vp, const char *str)
4499 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
4500 vfs_badlock("is locked but should not be", str, vp);
4504 assert_vop_elocked(struct vnode *vp, const char *str)
4507 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
4508 vfs_badlock("is not exclusive locked but should be", str, vp);
4513 assert_vop_elocked_other(struct vnode *vp, const char *str)
4516 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLOTHER)
4517 vfs_badlock("is not exclusive locked by another thread",
4522 assert_vop_slocked(struct vnode *vp, const char *str)
4525 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_SHARED)
4526 vfs_badlock("is not locked shared but should be", str, vp);
4529 #endif /* DEBUG_VFS_LOCKS */
4532 vop_rename_fail(struct vop_rename_args *ap)
4535 if (ap->a_tvp != NULL)
4537 if (ap->a_tdvp == ap->a_tvp)
4546 vop_rename_pre(void *ap)
4548 struct vop_rename_args *a = ap;
4550 #ifdef DEBUG_VFS_LOCKS
4552 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
4553 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
4554 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
4555 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
4557 /* Check the source (from). */
4558 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
4559 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
4560 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
4561 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
4562 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
4564 /* Check the target. */
4566 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
4567 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
4569 if (a->a_tdvp != a->a_fdvp)
4571 if (a->a_tvp != a->a_fvp)
4578 #ifdef DEBUG_VFS_LOCKS
4580 vop_strategy_pre(void *ap)
4582 struct vop_strategy_args *a;
4589 * Cluster ops lock their component buffers but not the IO container.
4591 if ((bp->b_flags & B_CLUSTER) != 0)
4594 if (panicstr == NULL && !BUF_ISLOCKED(bp)) {
4595 if (vfs_badlock_print)
4597 "VOP_STRATEGY: bp is not locked but should be\n");
4598 if (vfs_badlock_ddb)
4599 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4604 vop_lock_pre(void *ap)
4606 struct vop_lock1_args *a = ap;
4608 if ((a->a_flags & LK_INTERLOCK) == 0)
4609 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4611 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
4615 vop_lock_post(void *ap, int rc)
4617 struct vop_lock1_args *a = ap;
4619 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4620 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
4621 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
4625 vop_unlock_pre(void *ap)
4627 struct vop_unlock_args *a = ap;
4629 if (a->a_flags & LK_INTERLOCK)
4630 ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
4631 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
4635 vop_unlock_post(void *ap, int rc)
4637 struct vop_unlock_args *a = ap;
4639 if (a->a_flags & LK_INTERLOCK)
4640 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
4645 vop_create_post(void *ap, int rc)
4647 struct vop_create_args *a = ap;
4650 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4654 vop_deleteextattr_post(void *ap, int rc)
4656 struct vop_deleteextattr_args *a = ap;
4659 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4663 vop_link_post(void *ap, int rc)
4665 struct vop_link_args *a = ap;
4668 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
4669 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
4674 vop_mkdir_post(void *ap, int rc)
4676 struct vop_mkdir_args *a = ap;
4679 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4683 vop_mknod_post(void *ap, int rc)
4685 struct vop_mknod_args *a = ap;
4688 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4692 vop_reclaim_post(void *ap, int rc)
4694 struct vop_reclaim_args *a = ap;
4697 VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
4701 vop_remove_post(void *ap, int rc)
4703 struct vop_remove_args *a = ap;
4706 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4707 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4712 vop_rename_post(void *ap, int rc)
4714 struct vop_rename_args *a = ap;
4719 if (a->a_fdvp == a->a_tdvp) {
4720 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
4722 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
4723 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
4725 hint |= NOTE_EXTEND;
4726 if (a->a_fvp->v_type == VDIR)
4728 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
4730 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
4731 a->a_tvp->v_type == VDIR)
4733 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
4736 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
4738 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
4740 if (a->a_tdvp != a->a_fdvp)
4742 if (a->a_tvp != a->a_fvp)
4750 vop_rmdir_post(void *ap, int rc)
4752 struct vop_rmdir_args *a = ap;
4755 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4756 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4761 vop_setattr_post(void *ap, int rc)
4763 struct vop_setattr_args *a = ap;
4766 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4770 vop_setextattr_post(void *ap, int rc)
4772 struct vop_setextattr_args *a = ap;
4775 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4779 vop_symlink_post(void *ap, int rc)
4781 struct vop_symlink_args *a = ap;
4784 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4788 vop_open_post(void *ap, int rc)
4790 struct vop_open_args *a = ap;
4793 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
4797 vop_close_post(void *ap, int rc)
4799 struct vop_close_args *a = ap;
4801 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
4802 (a->a_vp->v_iflag & VI_DOOMED) == 0)) {
4803 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
4804 NOTE_CLOSE_WRITE : NOTE_CLOSE);
4809 vop_read_post(void *ap, int rc)
4811 struct vop_read_args *a = ap;
4814 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
4818 vop_readdir_post(void *ap, int rc)
4820 struct vop_readdir_args *a = ap;
4823 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
4826 static struct knlist fs_knlist;
4829 vfs_event_init(void *arg)
4831 knlist_init_mtx(&fs_knlist, NULL);
4833 /* XXX - correct order? */
4834 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
4837 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
4840 KNOTE_UNLOCKED(&fs_knlist, event);
4843 static int filt_fsattach(struct knote *kn);
4844 static void filt_fsdetach(struct knote *kn);
4845 static int filt_fsevent(struct knote *kn, long hint);
4847 struct filterops fs_filtops = {
4849 .f_attach = filt_fsattach,
4850 .f_detach = filt_fsdetach,
4851 .f_event = filt_fsevent
4855 filt_fsattach(struct knote *kn)
4858 kn->kn_flags |= EV_CLEAR;
4859 knlist_add(&fs_knlist, kn, 0);
4864 filt_fsdetach(struct knote *kn)
4867 knlist_remove(&fs_knlist, kn, 0);
4871 filt_fsevent(struct knote *kn, long hint)
4874 kn->kn_fflags |= hint;
4875 return (kn->kn_fflags != 0);
4879 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
4885 error = SYSCTL_IN(req, &vc, sizeof(vc));
4888 if (vc.vc_vers != VFS_CTL_VERS1)
4890 mp = vfs_getvfs(&vc.vc_fsid);
4893 /* ensure that a specific sysctl goes to the right filesystem. */
4894 if (strcmp(vc.vc_fstypename, "*") != 0 &&
4895 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
4899 VCTLTOREQ(&vc, req);
4900 error = VFS_SYSCTL(mp, vc.vc_op, req);
4905 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_WR,
4906 NULL, 0, sysctl_vfs_ctl, "",
4910 * Function to initialize a va_filerev field sensibly.
4911 * XXX: Wouldn't a random number make a lot more sense ??
4914 init_va_filerev(void)
4919 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
4922 static int filt_vfsread(struct knote *kn, long hint);
4923 static int filt_vfswrite(struct knote *kn, long hint);
4924 static int filt_vfsvnode(struct knote *kn, long hint);
4925 static void filt_vfsdetach(struct knote *kn);
4926 static struct filterops vfsread_filtops = {
4928 .f_detach = filt_vfsdetach,
4929 .f_event = filt_vfsread
4931 static struct filterops vfswrite_filtops = {
4933 .f_detach = filt_vfsdetach,
4934 .f_event = filt_vfswrite
4936 static struct filterops vfsvnode_filtops = {
4938 .f_detach = filt_vfsdetach,
4939 .f_event = filt_vfsvnode
4943 vfs_knllock(void *arg)
4945 struct vnode *vp = arg;
4947 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4951 vfs_knlunlock(void *arg)
4953 struct vnode *vp = arg;
4959 vfs_knl_assert_locked(void *arg)
4961 #ifdef DEBUG_VFS_LOCKS
4962 struct vnode *vp = arg;
4964 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
4969 vfs_knl_assert_unlocked(void *arg)
4971 #ifdef DEBUG_VFS_LOCKS
4972 struct vnode *vp = arg;
4974 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
4979 vfs_kqfilter(struct vop_kqfilter_args *ap)
4981 struct vnode *vp = ap->a_vp;
4982 struct knote *kn = ap->a_kn;
4985 switch (kn->kn_filter) {
4987 kn->kn_fop = &vfsread_filtops;
4990 kn->kn_fop = &vfswrite_filtops;
4993 kn->kn_fop = &vfsvnode_filtops;
4999 kn->kn_hook = (caddr_t)vp;
5002 if (vp->v_pollinfo == NULL)
5004 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5006 knlist_add(knl, kn, 0);
5012 * Detach knote from vnode
5015 filt_vfsdetach(struct knote *kn)
5017 struct vnode *vp = (struct vnode *)kn->kn_hook;
5019 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
5020 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
5026 filt_vfsread(struct knote *kn, long hint)
5028 struct vnode *vp = (struct vnode *)kn->kn_hook;
5033 * filesystem is gone, so set the EOF flag and schedule
5034 * the knote for deletion.
5036 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5038 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5043 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
5047 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
5048 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
5055 filt_vfswrite(struct knote *kn, long hint)
5057 struct vnode *vp = (struct vnode *)kn->kn_hook;
5062 * filesystem is gone, so set the EOF flag and schedule
5063 * the knote for deletion.
5065 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
5066 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5074 filt_vfsvnode(struct knote *kn, long hint)
5076 struct vnode *vp = (struct vnode *)kn->kn_hook;
5080 if (kn->kn_sfflags & hint)
5081 kn->kn_fflags |= hint;
5082 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5083 kn->kn_flags |= EV_EOF;
5087 res = (kn->kn_fflags != 0);
5093 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
5097 if (dp->d_reclen > ap->a_uio->uio_resid)
5098 return (ENAMETOOLONG);
5099 error = uiomove(dp, dp->d_reclen, ap->a_uio);
5101 if (ap->a_ncookies != NULL) {
5102 if (ap->a_cookies != NULL)
5103 free(ap->a_cookies, M_TEMP);
5104 ap->a_cookies = NULL;
5105 *ap->a_ncookies = 0;
5109 if (ap->a_ncookies == NULL)
5112 KASSERT(ap->a_cookies,
5113 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
5115 *ap->a_cookies = realloc(*ap->a_cookies,
5116 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
5117 (*ap->a_cookies)[*ap->a_ncookies] = off;
5118 *ap->a_ncookies += 1;
5123 * Mark for update the access time of the file if the filesystem
5124 * supports VOP_MARKATIME. This functionality is used by execve and
5125 * mmap, so we want to avoid the I/O implied by directly setting
5126 * va_atime for the sake of efficiency.
5129 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
5134 ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
5135 if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
5136 (void)VOP_MARKATIME(vp);
5140 * The purpose of this routine is to remove granularity from accmode_t,
5141 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
5142 * VADMIN and VAPPEND.
5144 * If it returns 0, the caller is supposed to continue with the usual
5145 * access checks using 'accmode' as modified by this routine. If it
5146 * returns nonzero value, the caller is supposed to return that value
5149 * Note that after this routine runs, accmode may be zero.
5152 vfs_unixify_accmode(accmode_t *accmode)
5155 * There is no way to specify explicit "deny" rule using
5156 * file mode or POSIX.1e ACLs.
5158 if (*accmode & VEXPLICIT_DENY) {
5164 * None of these can be translated into usual access bits.
5165 * Also, the common case for NFSv4 ACLs is to not contain
5166 * either of these bits. Caller should check for VWRITE
5167 * on the containing directory instead.
5169 if (*accmode & (VDELETE_CHILD | VDELETE))
5172 if (*accmode & VADMIN_PERMS) {
5173 *accmode &= ~VADMIN_PERMS;
5178 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
5179 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
5181 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
5187 * These are helper functions for filesystems to traverse all
5188 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
5190 * This interface replaces MNT_VNODE_FOREACH.
5193 MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
5196 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
5201 kern_yield(PRI_USER);
5203 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5204 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
5205 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
5206 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
5207 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
5210 if ((vp->v_iflag & VI_DOOMED) != 0) {
5217 __mnt_vnode_markerfree_all(mvp, mp);
5218 /* MNT_IUNLOCK(mp); -- done in above function */
5219 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
5222 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5223 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5229 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
5233 *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
5236 (*mvp)->v_mount = mp;
5237 (*mvp)->v_type = VMARKER;
5239 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
5240 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
5241 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
5244 if ((vp->v_iflag & VI_DOOMED) != 0) {
5253 free(*mvp, M_VNODE_MARKER);
5257 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5263 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
5271 mtx_assert(MNT_MTX(mp), MA_OWNED);
5273 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5274 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5277 free(*mvp, M_VNODE_MARKER);
5282 * These are helper functions for filesystems to traverse their
5283 * active vnodes. See MNT_VNODE_FOREACH_ACTIVE() in sys/mount.h
5286 mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
5289 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5294 free(*mvp, M_VNODE_MARKER);
5298 static struct vnode *
5299 mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
5301 struct vnode *vp, *nvp;
5303 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
5304 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5306 vp = TAILQ_NEXT(*mvp, v_actfreelist);
5307 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
5308 while (vp != NULL) {
5309 if (vp->v_type == VMARKER) {
5310 vp = TAILQ_NEXT(vp, v_actfreelist);
5313 if (!VI_TRYLOCK(vp)) {
5314 if (mp_ncpus == 1 || should_yield()) {
5315 TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
5316 mtx_unlock(&vnode_free_list_mtx);
5318 mtx_lock(&vnode_free_list_mtx);
5323 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
5324 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
5325 ("alien vnode on the active list %p %p", vp, mp));
5326 if (vp->v_mount == mp && (vp->v_iflag & VI_DOOMED) == 0)
5328 nvp = TAILQ_NEXT(vp, v_actfreelist);
5333 /* Check if we are done */
5335 mtx_unlock(&vnode_free_list_mtx);
5336 mnt_vnode_markerfree_active(mvp, mp);
5339 TAILQ_INSERT_AFTER(&mp->mnt_activevnodelist, vp, *mvp, v_actfreelist);
5340 mtx_unlock(&vnode_free_list_mtx);
5341 ASSERT_VI_LOCKED(vp, "active iter");
5342 KASSERT((vp->v_iflag & VI_ACTIVE) != 0, ("Non-active vp %p", vp));
5347 __mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
5351 kern_yield(PRI_USER);
5352 mtx_lock(&vnode_free_list_mtx);
5353 return (mnt_vnode_next_active(mvp, mp));
5357 __mnt_vnode_first_active(struct vnode **mvp, struct mount *mp)
5361 *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
5365 (*mvp)->v_type = VMARKER;
5366 (*mvp)->v_mount = mp;
5368 mtx_lock(&vnode_free_list_mtx);
5369 vp = TAILQ_FIRST(&mp->mnt_activevnodelist);
5371 mtx_unlock(&vnode_free_list_mtx);
5372 mnt_vnode_markerfree_active(mvp, mp);
5375 TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
5376 return (mnt_vnode_next_active(mvp, mp));
5380 __mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
5386 mtx_lock(&vnode_free_list_mtx);
5387 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
5388 mtx_unlock(&vnode_free_list_mtx);
5389 mnt_vnode_markerfree_active(mvp, mp);