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 * These fences are intended for cases where some synchronization is
120 * needed between access of v_iflags and lockless vnode refcount (v_holdcnt
121 * and v_usecount) updates. Access to v_iflags is generally synchronized
122 * by the interlock, but we have some internal assertions that check vnode
123 * flags * without acquiring the lock. Thus, these fences are INVARIANTS-only
127 #define VNODE_REFCOUNT_FENCE_ACQ() atomic_thread_fence_acq()
128 #define VNODE_REFCOUNT_FENCE_REL() atomic_thread_fence_rel()
130 #define VNODE_REFCOUNT_FENCE_ACQ()
131 #define VNODE_REFCOUNT_FENCE_REL()
135 * Number of vnodes in existence. Increased whenever getnewvnode()
136 * allocates a new vnode, decreased in vdropl() for VI_DOOMED vnode.
138 static unsigned long numvnodes;
140 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
141 "Number of vnodes in existence");
143 static counter_u64_t vnodes_created;
144 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
145 "Number of vnodes created by getnewvnode");
148 * Conversion tables for conversion from vnode types to inode formats
151 enum vtype iftovt_tab[16] = {
152 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
153 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
155 int vttoif_tab[10] = {
156 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
157 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
161 * List of vnodes that are ready for recycling.
163 static TAILQ_HEAD(freelst, vnode) vnode_free_list;
166 * "Free" vnode target. Free vnodes are rarely completely free, but are
167 * just ones that are cheap to recycle. Usually they are for files which
168 * have been stat'd but not read; these usually have inode and namecache
169 * data attached to them. This target is the preferred minimum size of a
170 * sub-cache consisting mostly of such files. The system balances the size
171 * of this sub-cache with its complement to try to prevent either from
172 * thrashing while the other is relatively inactive. The targets express
173 * a preference for the best balance.
175 * "Above" this target there are 2 further targets (watermarks) related
176 * to recyling of free vnodes. In the best-operating case, the cache is
177 * exactly full, the free list has size between vlowat and vhiwat above the
178 * free target, and recycling from it and normal use maintains this state.
179 * Sometimes the free list is below vlowat or even empty, but this state
180 * is even better for immediate use provided the cache is not full.
181 * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
182 * ones) to reach one of these states. The watermarks are currently hard-
183 * coded as 4% and 9% of the available space higher. These and the default
184 * of 25% for wantfreevnodes are too large if the memory size is large.
185 * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
186 * whenever vnlru_proc() becomes active.
188 static u_long wantfreevnodes;
189 SYSCTL_ULONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW,
190 &wantfreevnodes, 0, "Target for minimum number of \"free\" vnodes");
191 static u_long freevnodes;
192 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
193 &freevnodes, 0, "Number of \"free\" vnodes");
195 static counter_u64_t recycles_count;
196 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
197 "Number of vnodes recycled to meet vnode cache targets");
200 * Various variables used for debugging the new implementation of
202 * XXX these are probably of (very) limited utility now.
204 static int reassignbufcalls;
205 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0,
206 "Number of calls to reassignbuf");
208 static counter_u64_t free_owe_inact;
209 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, free_owe_inact, CTLFLAG_RD, &free_owe_inact,
210 "Number of times free vnodes kept on active list due to VFS "
211 "owing inactivation");
213 /* To keep more than one thread at a time from running vfs_getnewfsid */
214 static struct mtx mntid_mtx;
217 * Lock for any access to the following:
222 static struct mtx vnode_free_list_mtx;
224 /* Publicly exported FS */
225 struct nfs_public nfs_pub;
227 static uma_zone_t buf_trie_zone;
229 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
230 static uma_zone_t vnode_zone;
231 static uma_zone_t vnodepoll_zone;
234 * The workitem queue.
236 * It is useful to delay writes of file data and filesystem metadata
237 * for tens of seconds so that quickly created and deleted files need
238 * not waste disk bandwidth being created and removed. To realize this,
239 * we append vnodes to a "workitem" queue. When running with a soft
240 * updates implementation, most pending metadata dependencies should
241 * not wait for more than a few seconds. Thus, mounted on block devices
242 * are delayed only about a half the time that file data is delayed.
243 * Similarly, directory updates are more critical, so are only delayed
244 * about a third the time that file data is delayed. Thus, there are
245 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
246 * one each second (driven off the filesystem syncer process). The
247 * syncer_delayno variable indicates the next queue that is to be processed.
248 * Items that need to be processed soon are placed in this queue:
250 * syncer_workitem_pending[syncer_delayno]
252 * A delay of fifteen seconds is done by placing the request fifteen
253 * entries later in the queue:
255 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
258 static int syncer_delayno;
259 static long syncer_mask;
260 LIST_HEAD(synclist, bufobj);
261 static struct synclist *syncer_workitem_pending;
263 * The sync_mtx protects:
268 * syncer_workitem_pending
269 * syncer_worklist_len
272 static struct mtx sync_mtx;
273 static struct cv sync_wakeup;
275 #define SYNCER_MAXDELAY 32
276 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
277 static int syncdelay = 30; /* max time to delay syncing data */
278 static int filedelay = 30; /* time to delay syncing files */
279 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
280 "Time to delay syncing files (in seconds)");
281 static int dirdelay = 29; /* time to delay syncing directories */
282 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
283 "Time to delay syncing directories (in seconds)");
284 static int metadelay = 28; /* time to delay syncing metadata */
285 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
286 "Time to delay syncing metadata (in seconds)");
287 static int rushjob; /* number of slots to run ASAP */
288 static int stat_rush_requests; /* number of times I/O speeded up */
289 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
290 "Number of times I/O speeded up (rush requests)");
293 * When shutting down the syncer, run it at four times normal speed.
295 #define SYNCER_SHUTDOWN_SPEEDUP 4
296 static int sync_vnode_count;
297 static int syncer_worklist_len;
298 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
301 /* Target for maximum number of vnodes. */
303 static int gapvnodes; /* gap between wanted and desired */
304 static int vhiwat; /* enough extras after expansion */
305 static int vlowat; /* minimal extras before expansion */
306 static int vstir; /* nonzero to stir non-free vnodes */
307 static volatile int vsmalltrigger = 8; /* pref to keep if > this many pages */
310 sysctl_update_desiredvnodes(SYSCTL_HANDLER_ARGS)
312 int error, old_desiredvnodes;
314 old_desiredvnodes = desiredvnodes;
315 if ((error = sysctl_handle_int(oidp, arg1, arg2, req)) != 0)
317 if (old_desiredvnodes != desiredvnodes) {
318 wantfreevnodes = desiredvnodes / 4;
319 /* XXX locking seems to be incomplete. */
320 vfs_hash_changesize(desiredvnodes);
321 cache_changesize(desiredvnodes);
326 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
327 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, &desiredvnodes, 0,
328 sysctl_update_desiredvnodes, "I", "Target for maximum number of vnodes");
329 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
330 &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
331 static int vnlru_nowhere;
332 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
333 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
335 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
339 * Support for the bufobj clean & dirty pctrie.
342 buf_trie_alloc(struct pctrie *ptree)
345 return uma_zalloc(buf_trie_zone, M_NOWAIT);
349 buf_trie_free(struct pctrie *ptree, void *node)
352 uma_zfree(buf_trie_zone, node);
354 PCTRIE_DEFINE(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free);
357 * Initialize the vnode management data structures.
359 * Reevaluate the following cap on the number of vnodes after the physical
360 * memory size exceeds 512GB. In the limit, as the physical memory size
361 * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
363 #ifndef MAXVNODES_MAX
364 #define MAXVNODES_MAX (512 * 1024 * 1024 / 64) /* 8M */
368 * Initialize a vnode as it first enters the zone.
371 vnode_init(void *mem, int size, int flags)
381 vp->v_vnlock = &vp->v_lock;
382 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
384 * By default, don't allow shared locks unless filesystems opt-in.
386 lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
387 LK_NOSHARE | LK_IS_VNODE);
393 rw_init(BO_LOCKPTR(bo), "bufobj interlock");
395 TAILQ_INIT(&bo->bo_clean.bv_hd);
396 TAILQ_INIT(&bo->bo_dirty.bv_hd);
398 * Initialize namecache.
400 LIST_INIT(&vp->v_cache_src);
401 TAILQ_INIT(&vp->v_cache_dst);
403 * Initialize rangelocks.
405 rangelock_init(&vp->v_rl);
410 * Free a vnode when it is cleared from the zone.
413 vnode_fini(void *mem, int size)
419 rangelock_destroy(&vp->v_rl);
420 lockdestroy(vp->v_vnlock);
421 mtx_destroy(&vp->v_interlock);
423 rw_destroy(BO_LOCKPTR(bo));
427 * Provide the size of NFS nclnode and NFS fh for calculation of the
428 * vnode memory consumption. The size is specified directly to
429 * eliminate dependency on NFS-private header.
431 * Other filesystems may use bigger or smaller (like UFS and ZFS)
432 * private inode data, but the NFS-based estimation is ample enough.
433 * Still, we care about differences in the size between 64- and 32-bit
436 * Namecache structure size is heuristically
437 * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
440 #define NFS_NCLNODE_SZ (528 + 64)
443 #define NFS_NCLNODE_SZ (360 + 32)
448 vntblinit(void *dummy __unused)
451 int physvnodes, virtvnodes;
454 * Desiredvnodes is a function of the physical memory size and the
455 * kernel's heap size. Generally speaking, it scales with the
456 * physical memory size. The ratio of desiredvnodes to the physical
457 * memory size is 1:16 until desiredvnodes exceeds 98,304.
459 * marginal ratio of desiredvnodes to the physical memory size is
460 * 1:64. However, desiredvnodes is limited by the kernel's heap
461 * size. The memory required by desiredvnodes vnodes and vm objects
462 * must not exceed 1/10th of the kernel's heap size.
464 physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
465 3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
466 virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
467 sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
468 desiredvnodes = min(physvnodes, virtvnodes);
469 if (desiredvnodes > MAXVNODES_MAX) {
471 printf("Reducing kern.maxvnodes %d -> %d\n",
472 desiredvnodes, MAXVNODES_MAX);
473 desiredvnodes = MAXVNODES_MAX;
475 wantfreevnodes = desiredvnodes / 4;
476 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
477 TAILQ_INIT(&vnode_free_list);
478 mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
479 vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
480 vnode_init, vnode_fini, UMA_ALIGN_PTR, 0);
481 vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
482 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
484 * Preallocate enough nodes to support one-per buf so that
485 * we can not fail an insert. reassignbuf() callers can not
486 * tolerate the insertion failure.
488 buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
489 NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
490 UMA_ZONE_NOFREE | UMA_ZONE_VM);
491 uma_prealloc(buf_trie_zone, nbuf);
493 vnodes_created = counter_u64_alloc(M_WAITOK);
494 recycles_count = counter_u64_alloc(M_WAITOK);
495 free_owe_inact = counter_u64_alloc(M_WAITOK);
498 * Initialize the filesystem syncer.
500 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
502 syncer_maxdelay = syncer_mask + 1;
503 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
504 cv_init(&sync_wakeup, "syncer");
505 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
509 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
513 * Mark a mount point as busy. Used to synchronize access and to delay
514 * unmounting. Eventually, mountlist_mtx is not released on failure.
516 * vfs_busy() is a custom lock, it can block the caller.
517 * vfs_busy() only sleeps if the unmount is active on the mount point.
518 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
519 * vnode belonging to mp.
521 * Lookup uses vfs_busy() to traverse mount points.
523 * / vnode lock A / vnode lock (/var) D
524 * /var vnode lock B /log vnode lock(/var/log) E
525 * vfs_busy lock C vfs_busy lock F
527 * Within each file system, the lock order is C->A->B and F->D->E.
529 * When traversing across mounts, the system follows that lock order:
535 * The lookup() process for namei("/var") illustrates the process:
536 * VOP_LOOKUP() obtains B while A is held
537 * vfs_busy() obtains a shared lock on F while A and B are held
538 * vput() releases lock on B
539 * vput() releases lock on A
540 * VFS_ROOT() obtains lock on D while shared lock on F is held
541 * vfs_unbusy() releases shared lock on F
542 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
543 * Attempt to lock A (instead of vp_crossmp) while D is held would
544 * violate the global order, causing deadlocks.
546 * dounmount() locks B while F is drained.
549 vfs_busy(struct mount *mp, int flags)
552 MPASS((flags & ~MBF_MASK) == 0);
553 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
558 * If mount point is currently being unmounted, sleep until the
559 * mount point fate is decided. If thread doing the unmounting fails,
560 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
561 * that this mount point has survived the unmount attempt and vfs_busy
562 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
563 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
564 * about to be really destroyed. vfs_busy needs to release its
565 * reference on the mount point in this case and return with ENOENT,
566 * telling the caller that mount mount it tried to busy is no longer
569 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
570 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
573 CTR1(KTR_VFS, "%s: failed busying before sleeping",
577 if (flags & MBF_MNTLSTLOCK)
578 mtx_unlock(&mountlist_mtx);
579 mp->mnt_kern_flag |= MNTK_MWAIT;
580 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
581 if (flags & MBF_MNTLSTLOCK)
582 mtx_lock(&mountlist_mtx);
585 if (flags & MBF_MNTLSTLOCK)
586 mtx_unlock(&mountlist_mtx);
593 * Free a busy filesystem.
596 vfs_unbusy(struct mount *mp)
599 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
602 KASSERT(mp->mnt_lockref > 0, ("negative mnt_lockref"));
604 if (mp->mnt_lockref == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
605 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
606 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
607 mp->mnt_kern_flag &= ~MNTK_DRAINING;
608 wakeup(&mp->mnt_lockref);
614 * Lookup a mount point by filesystem identifier.
617 vfs_getvfs(fsid_t *fsid)
621 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
622 mtx_lock(&mountlist_mtx);
623 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
624 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
625 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
627 mtx_unlock(&mountlist_mtx);
631 mtx_unlock(&mountlist_mtx);
632 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
633 return ((struct mount *) 0);
637 * Lookup a mount point by filesystem identifier, busying it before
640 * To avoid congestion on mountlist_mtx, implement simple direct-mapped
641 * cache for popular filesystem identifiers. The cache is lockess, using
642 * the fact that struct mount's are never freed. In worst case we may
643 * get pointer to unmounted or even different filesystem, so we have to
644 * check what we got, and go slow way if so.
647 vfs_busyfs(fsid_t *fsid)
649 #define FSID_CACHE_SIZE 256
650 typedef struct mount * volatile vmp_t;
651 static vmp_t cache[FSID_CACHE_SIZE];
656 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
657 hash = fsid->val[0] ^ fsid->val[1];
658 hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
661 mp->mnt_stat.f_fsid.val[0] != fsid->val[0] ||
662 mp->mnt_stat.f_fsid.val[1] != fsid->val[1])
664 if (vfs_busy(mp, 0) != 0) {
668 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
669 mp->mnt_stat.f_fsid.val[1] == fsid->val[1])
675 mtx_lock(&mountlist_mtx);
676 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
677 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
678 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
679 error = vfs_busy(mp, MBF_MNTLSTLOCK);
682 mtx_unlock(&mountlist_mtx);
689 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
690 mtx_unlock(&mountlist_mtx);
691 return ((struct mount *) 0);
695 * Check if a user can access privileged mount options.
698 vfs_suser(struct mount *mp, struct thread *td)
703 * If the thread is jailed, but this is not a jail-friendly file
704 * system, deny immediately.
706 if (!(mp->mnt_vfc->vfc_flags & VFCF_JAIL) && jailed(td->td_ucred))
710 * If the file system was mounted outside the jail of the calling
711 * thread, deny immediately.
713 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
717 * If file system supports delegated administration, we don't check
718 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
719 * by the file system itself.
720 * If this is not the user that did original mount, we check for
721 * the PRIV_VFS_MOUNT_OWNER privilege.
723 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
724 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
725 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
732 * Get a new unique fsid. Try to make its val[0] unique, since this value
733 * will be used to create fake device numbers for stat(). Also try (but
734 * not so hard) make its val[0] unique mod 2^16, since some emulators only
735 * support 16-bit device numbers. We end up with unique val[0]'s for the
736 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
738 * Keep in mind that several mounts may be running in parallel. Starting
739 * the search one past where the previous search terminated is both a
740 * micro-optimization and a defense against returning the same fsid to
744 vfs_getnewfsid(struct mount *mp)
746 static uint16_t mntid_base;
751 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
752 mtx_lock(&mntid_mtx);
753 mtype = mp->mnt_vfc->vfc_typenum;
754 tfsid.val[1] = mtype;
755 mtype = (mtype & 0xFF) << 24;
757 tfsid.val[0] = makedev(255,
758 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
760 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
764 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
765 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
766 mtx_unlock(&mntid_mtx);
770 * Knob to control the precision of file timestamps:
772 * 0 = seconds only; nanoseconds zeroed.
773 * 1 = seconds and nanoseconds, accurate within 1/HZ.
774 * 2 = seconds and nanoseconds, truncated to microseconds.
775 * >=3 = seconds and nanoseconds, maximum precision.
777 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
779 static int timestamp_precision = TSP_USEC;
780 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
781 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
782 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
783 "3+: sec + ns (max. precision))");
786 * Get a current timestamp.
789 vfs_timestamp(struct timespec *tsp)
793 switch (timestamp_precision) {
795 tsp->tv_sec = time_second;
803 TIMEVAL_TO_TIMESPEC(&tv, tsp);
813 * Set vnode attributes to VNOVAL
816 vattr_null(struct vattr *vap)
820 vap->va_size = VNOVAL;
821 vap->va_bytes = VNOVAL;
822 vap->va_mode = VNOVAL;
823 vap->va_nlink = VNOVAL;
824 vap->va_uid = VNOVAL;
825 vap->va_gid = VNOVAL;
826 vap->va_fsid = VNOVAL;
827 vap->va_fileid = VNOVAL;
828 vap->va_blocksize = VNOVAL;
829 vap->va_rdev = VNOVAL;
830 vap->va_atime.tv_sec = VNOVAL;
831 vap->va_atime.tv_nsec = VNOVAL;
832 vap->va_mtime.tv_sec = VNOVAL;
833 vap->va_mtime.tv_nsec = VNOVAL;
834 vap->va_ctime.tv_sec = VNOVAL;
835 vap->va_ctime.tv_nsec = VNOVAL;
836 vap->va_birthtime.tv_sec = VNOVAL;
837 vap->va_birthtime.tv_nsec = VNOVAL;
838 vap->va_flags = VNOVAL;
839 vap->va_gen = VNOVAL;
844 * This routine is called when we have too many vnodes. It attempts
845 * to free <count> vnodes and will potentially free vnodes that still
846 * have VM backing store (VM backing store is typically the cause
847 * of a vnode blowout so we want to do this). Therefore, this operation
848 * is not considered cheap.
850 * A number of conditions may prevent a vnode from being reclaimed.
851 * the buffer cache may have references on the vnode, a directory
852 * vnode may still have references due to the namei cache representing
853 * underlying files, or the vnode may be in active use. It is not
854 * desirable to reuse such vnodes. These conditions may cause the
855 * number of vnodes to reach some minimum value regardless of what
856 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
859 vlrureclaim(struct mount *mp, int reclaim_nc_src, int trigger)
862 int count, done, target;
865 vn_start_write(NULL, &mp, V_WAIT);
867 count = mp->mnt_nvnodelistsize;
868 target = count * (int64_t)gapvnodes / imax(desiredvnodes, 1);
869 target = target / 10 + 1;
870 while (count != 0 && done < target) {
871 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
872 while (vp != NULL && vp->v_type == VMARKER)
873 vp = TAILQ_NEXT(vp, v_nmntvnodes);
877 * XXX LRU is completely broken for non-free vnodes. First
878 * by calling here in mountpoint order, then by moving
879 * unselected vnodes to the end here, and most grossly by
880 * removing the vlruvp() function that was supposed to
881 * maintain the order. (This function was born broken
882 * since syncer problems prevented it doing anything.) The
883 * order is closer to LRC (C = Created).
885 * LRU reclaiming of vnodes seems to have last worked in
886 * FreeBSD-3 where LRU wasn't mentioned under any spelling.
887 * Then there was no hold count, and inactive vnodes were
888 * simply put on the free list in LRU order. The separate
889 * lists also break LRU. We prefer to reclaim from the
890 * free list for technical reasons. This tends to thrash
891 * the free list to keep very unrecently used held vnodes.
892 * The problem is mitigated by keeping the free list large.
894 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
895 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
900 * If it's been deconstructed already, it's still
901 * referenced, or it exceeds the trigger, skip it.
902 * Also skip free vnodes. We are trying to make space
903 * to expand the free list, not reduce it.
905 if (vp->v_usecount ||
906 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
907 ((vp->v_iflag & VI_FREE) != 0) ||
908 (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
909 vp->v_object->resident_page_count > trigger)) {
915 if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT)) {
917 goto next_iter_mntunlocked;
921 * v_usecount may have been bumped after VOP_LOCK() dropped
922 * the vnode interlock and before it was locked again.
924 * It is not necessary to recheck VI_DOOMED because it can
925 * only be set by another thread that holds both the vnode
926 * lock and vnode interlock. If another thread has the
927 * vnode lock before we get to VOP_LOCK() and obtains the
928 * vnode interlock after VOP_LOCK() drops the vnode
929 * interlock, the other thread will be unable to drop the
930 * vnode lock before our VOP_LOCK() call fails.
932 if (vp->v_usecount ||
933 (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
934 (vp->v_iflag & VI_FREE) != 0 ||
935 (vp->v_object != NULL &&
936 vp->v_object->resident_page_count > trigger)) {
937 VOP_UNLOCK(vp, LK_INTERLOCK);
939 goto next_iter_mntunlocked;
941 KASSERT((vp->v_iflag & VI_DOOMED) == 0,
942 ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
943 counter_u64_add(recycles_count, 1);
948 next_iter_mntunlocked:
957 kern_yield(PRI_USER);
962 vn_finished_write(mp);
966 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
967 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
969 "limit on vnode free requests per call to the vnlru_free routine");
972 * Attempt to reduce the free list by the requested amount.
975 vnlru_free_locked(int count, struct vfsops *mnt_op)
980 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
981 if (count > max_vnlru_free)
982 count = max_vnlru_free;
983 for (; count > 0; count--) {
984 vp = TAILQ_FIRST(&vnode_free_list);
986 * The list can be modified while the free_list_mtx
987 * has been dropped and vp could be NULL here.
991 VNASSERT(vp->v_op != NULL, vp,
992 ("vnlru_free: vnode already reclaimed."));
993 KASSERT((vp->v_iflag & VI_FREE) != 0,
994 ("Removing vnode not on freelist"));
995 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
996 ("Mangling active vnode"));
997 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
1000 * Don't recycle if our vnode is from different type
1001 * of mount point. Note that mp is type-safe, the
1002 * check does not reach unmapped address even if
1003 * vnode is reclaimed.
1004 * Don't recycle if we can't get the interlock without
1007 if ((mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1008 mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
1009 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_actfreelist);
1012 VNASSERT((vp->v_iflag & VI_FREE) != 0 && vp->v_holdcnt == 0,
1013 vp, ("vp inconsistent on freelist"));
1016 * The clear of VI_FREE prevents activation of the
1017 * vnode. There is no sense in putting the vnode on
1018 * the mount point active list, only to remove it
1019 * later during recycling. Inline the relevant part
1020 * of vholdl(), to avoid triggering assertions or
1024 vp->v_iflag &= ~VI_FREE;
1025 VNODE_REFCOUNT_FENCE_REL();
1026 refcount_acquire(&vp->v_holdcnt);
1028 mtx_unlock(&vnode_free_list_mtx);
1032 * If the recycled succeeded this vdrop will actually free
1033 * the vnode. If not it will simply place it back on
1037 mtx_lock(&vnode_free_list_mtx);
1042 vnlru_free(int count, struct vfsops *mnt_op)
1045 mtx_lock(&vnode_free_list_mtx);
1046 vnlru_free_locked(count, mnt_op);
1047 mtx_unlock(&vnode_free_list_mtx);
1051 /* XXX some names and initialization are bad for limits and watermarks. */
1057 gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1058 vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1059 vlowat = vhiwat / 2;
1060 if (numvnodes > desiredvnodes)
1062 space = desiredvnodes - numvnodes;
1063 if (freevnodes > wantfreevnodes)
1064 space += freevnodes - wantfreevnodes;
1069 * Attempt to recycle vnodes in a context that is always safe to block.
1070 * Calling vlrurecycle() from the bowels of filesystem code has some
1071 * interesting deadlock problems.
1073 static struct proc *vnlruproc;
1074 static int vnlruproc_sig;
1079 struct mount *mp, *nmp;
1080 unsigned long ofreevnodes, onumvnodes;
1081 int done, force, reclaim_nc_src, trigger, usevnodes;
1083 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1084 SHUTDOWN_PRI_FIRST);
1088 kproc_suspend_check(vnlruproc);
1089 mtx_lock(&vnode_free_list_mtx);
1091 * If numvnodes is too large (due to desiredvnodes being
1092 * adjusted using its sysctl, or emergency growth), first
1093 * try to reduce it by discarding from the free list.
1095 if (numvnodes > desiredvnodes && freevnodes > 0)
1096 vnlru_free_locked(ulmin(numvnodes - desiredvnodes,
1099 * Sleep if the vnode cache is in a good state. This is
1100 * when it is not over-full and has space for about a 4%
1101 * or 9% expansion (by growing its size or inexcessively
1102 * reducing its free list). Otherwise, try to reclaim
1103 * space for a 10% expansion.
1105 if (vstir && force == 0) {
1109 if (vspace() >= vlowat && force == 0) {
1111 wakeup(&vnlruproc_sig);
1112 msleep(vnlruproc, &vnode_free_list_mtx,
1113 PVFS|PDROP, "vlruwt", hz);
1116 mtx_unlock(&vnode_free_list_mtx);
1118 ofreevnodes = freevnodes;
1119 onumvnodes = numvnodes;
1121 * Calculate parameters for recycling. These are the same
1122 * throughout the loop to give some semblance of fairness.
1123 * The trigger point is to avoid recycling vnodes with lots
1124 * of resident pages. We aren't trying to free memory; we
1125 * are trying to recycle or at least free vnodes.
1127 if (numvnodes <= desiredvnodes)
1128 usevnodes = numvnodes - freevnodes;
1130 usevnodes = numvnodes;
1134 * The trigger value is is chosen to give a conservatively
1135 * large value to ensure that it alone doesn't prevent
1136 * making progress. The value can easily be so large that
1137 * it is effectively infinite in some congested and
1138 * misconfigured cases, and this is necessary. Normally
1139 * it is about 8 to 100 (pages), which is quite large.
1141 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1143 trigger = vsmalltrigger;
1144 reclaim_nc_src = force >= 3;
1145 mtx_lock(&mountlist_mtx);
1146 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1147 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK)) {
1148 nmp = TAILQ_NEXT(mp, mnt_list);
1151 done += vlrureclaim(mp, reclaim_nc_src, trigger);
1152 mtx_lock(&mountlist_mtx);
1153 nmp = TAILQ_NEXT(mp, mnt_list);
1156 mtx_unlock(&mountlist_mtx);
1157 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1160 if (force == 0 || force == 1) {
1170 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1172 kern_yield(PRI_USER);
1174 * After becoming active to expand above low water, keep
1175 * active until above high water.
1177 force = vspace() < vhiwat;
1181 static struct kproc_desc vnlru_kp = {
1186 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1190 * Routines having to do with the management of the vnode table.
1194 * Try to recycle a freed vnode. We abort if anyone picks up a reference
1195 * before we actually vgone(). This function must be called with the vnode
1196 * held to prevent the vnode from being returned to the free list midway
1200 vtryrecycle(struct vnode *vp)
1204 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1205 VNASSERT(vp->v_holdcnt, vp,
1206 ("vtryrecycle: Recycling vp %p without a reference.", vp));
1208 * This vnode may found and locked via some other list, if so we
1209 * can't recycle it yet.
1211 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1213 "%s: impossible to recycle, vp %p lock is already held",
1215 return (EWOULDBLOCK);
1218 * Don't recycle if its filesystem is being suspended.
1220 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1223 "%s: impossible to recycle, cannot start the write for %p",
1228 * If we got this far, we need to acquire the interlock and see if
1229 * anyone picked up this vnode from another list. If not, we will
1230 * mark it with DOOMED via vgonel() so that anyone who does find it
1231 * will skip over it.
1234 if (vp->v_usecount) {
1235 VOP_UNLOCK(vp, LK_INTERLOCK);
1236 vn_finished_write(vnmp);
1238 "%s: impossible to recycle, %p is already referenced",
1242 if ((vp->v_iflag & VI_DOOMED) == 0) {
1243 counter_u64_add(recycles_count, 1);
1246 VOP_UNLOCK(vp, LK_INTERLOCK);
1247 vn_finished_write(vnmp);
1255 if (vspace() < vlowat && vnlruproc_sig == 0) {
1262 * Wait if necessary for space for a new vnode.
1265 getnewvnode_wait(int suspended)
1268 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
1269 if (numvnodes >= desiredvnodes) {
1272 * The file system is being suspended. We cannot
1273 * risk a deadlock here, so allow allocation of
1274 * another vnode even if this would give too many.
1278 if (vnlruproc_sig == 0) {
1279 vnlruproc_sig = 1; /* avoid unnecessary wakeups */
1282 msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
1285 /* Post-adjust like the pre-adjust in getnewvnode(). */
1286 if (numvnodes + 1 > desiredvnodes && freevnodes > 1)
1287 vnlru_free_locked(1, NULL);
1288 return (numvnodes >= desiredvnodes ? ENFILE : 0);
1292 * This hack is fragile, and probably not needed any more now that the
1293 * watermark handling works.
1296 getnewvnode_reserve(u_int count)
1300 /* Pre-adjust like the pre-adjust in getnewvnode(), with any count. */
1301 /* XXX no longer so quick, but this part is not racy. */
1302 mtx_lock(&vnode_free_list_mtx);
1303 if (numvnodes + count > desiredvnodes && freevnodes > wantfreevnodes)
1304 vnlru_free_locked(ulmin(numvnodes + count - desiredvnodes,
1305 freevnodes - wantfreevnodes), NULL);
1306 mtx_unlock(&vnode_free_list_mtx);
1309 /* First try to be quick and racy. */
1310 if (atomic_fetchadd_long(&numvnodes, count) + count <= desiredvnodes) {
1311 td->td_vp_reserv += count;
1312 vcheckspace(); /* XXX no longer so quick, but more racy */
1315 atomic_subtract_long(&numvnodes, count);
1317 mtx_lock(&vnode_free_list_mtx);
1319 if (getnewvnode_wait(0) == 0) {
1322 atomic_add_long(&numvnodes, 1);
1326 mtx_unlock(&vnode_free_list_mtx);
1330 * This hack is fragile, especially if desiredvnodes or wantvnodes are
1331 * misconfgured or changed significantly. Reducing desiredvnodes below
1332 * the reserved amount should cause bizarre behaviour like reducing it
1333 * below the number of active vnodes -- the system will try to reduce
1334 * numvnodes to match, but should fail, so the subtraction below should
1338 getnewvnode_drop_reserve(void)
1343 atomic_subtract_long(&numvnodes, td->td_vp_reserv);
1344 td->td_vp_reserv = 0;
1348 * Return the next vnode from the free list.
1351 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1356 struct lock_object *lo;
1357 static int cyclecount;
1360 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1363 if (td->td_vp_reserv > 0) {
1364 td->td_vp_reserv -= 1;
1367 mtx_lock(&vnode_free_list_mtx);
1368 if (numvnodes < desiredvnodes)
1370 else if (cyclecount++ >= freevnodes) {
1375 * Grow the vnode cache if it will not be above its target max
1376 * after growing. Otherwise, if the free list is nonempty, try
1377 * to reclaim 1 item from it before growing the cache (possibly
1378 * above its target max if the reclamation failed or is delayed).
1379 * Otherwise, wait for some space. In all cases, schedule
1380 * vnlru_proc() if we are getting short of space. The watermarks
1381 * should be chosen so that we never wait or even reclaim from
1382 * the free list to below its target minimum.
1384 if (numvnodes + 1 <= desiredvnodes)
1386 else if (freevnodes > 0)
1387 vnlru_free_locked(1, NULL);
1389 error = getnewvnode_wait(mp != NULL && (mp->mnt_kern_flag &
1391 #if 0 /* XXX Not all VFS_VGET/ffs_vget callers check returns. */
1393 mtx_unlock(&vnode_free_list_mtx);
1399 atomic_add_long(&numvnodes, 1);
1400 mtx_unlock(&vnode_free_list_mtx);
1402 counter_u64_add(vnodes_created, 1);
1403 vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK);
1405 * Locks are given the generic name "vnode" when created.
1406 * Follow the historic practice of using the filesystem
1407 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1409 * Locks live in a witness group keyed on their name. Thus,
1410 * when a lock is renamed, it must also move from the witness
1411 * group of its old name to the witness group of its new name.
1413 * The change only needs to be made when the vnode moves
1414 * from one filesystem type to another. We ensure that each
1415 * filesystem use a single static name pointer for its tag so
1416 * that we can compare pointers rather than doing a strcmp().
1418 lo = &vp->v_vnlock->lock_object;
1419 if (lo->lo_name != tag) {
1421 WITNESS_DESTROY(lo);
1422 WITNESS_INIT(lo, tag);
1425 * By default, don't allow shared locks unless filesystems opt-in.
1427 vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1429 * Finalize various vnode identity bits.
1431 KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1432 KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1433 KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1437 v_init_counters(vp);
1438 vp->v_bufobj.bo_ops = &buf_ops_bio;
1440 if (mp == NULL && vops != &dead_vnodeops)
1441 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1445 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1446 mac_vnode_associate_singlelabel(mp, vp);
1449 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1450 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1451 vp->v_vflag |= VV_NOKNOTE;
1455 * For the filesystems which do not use vfs_hash_insert(),
1456 * still initialize v_hash to have vfs_hash_index() useful.
1457 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1460 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1467 * Delete from old mount point vnode list, if on one.
1470 delmntque(struct vnode *vp)
1480 KASSERT(mp->mnt_activevnodelistsize <= mp->mnt_nvnodelistsize,
1481 ("Active vnode list size %d > Vnode list size %d",
1482 mp->mnt_activevnodelistsize, mp->mnt_nvnodelistsize));
1483 active = vp->v_iflag & VI_ACTIVE;
1484 vp->v_iflag &= ~VI_ACTIVE;
1486 mtx_lock(&vnode_free_list_mtx);
1487 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp, v_actfreelist);
1488 mp->mnt_activevnodelistsize--;
1489 mtx_unlock(&vnode_free_list_mtx);
1493 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1494 ("bad mount point vnode list size"));
1495 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1496 mp->mnt_nvnodelistsize--;
1502 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1506 vp->v_op = &dead_vnodeops;
1512 * Insert into list of vnodes for the new mount point, if available.
1515 insmntque1(struct vnode *vp, struct mount *mp,
1516 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1519 KASSERT(vp->v_mount == NULL,
1520 ("insmntque: vnode already on per mount vnode list"));
1521 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1522 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1525 * We acquire the vnode interlock early to ensure that the
1526 * vnode cannot be recycled by another process releasing a
1527 * holdcnt on it before we get it on both the vnode list
1528 * and the active vnode list. The mount mutex protects only
1529 * manipulation of the vnode list and the vnode freelist
1530 * mutex protects only manipulation of the active vnode list.
1531 * Hence the need to hold the vnode interlock throughout.
1535 if (((mp->mnt_kern_flag & MNTK_NOINSMNTQ) != 0 &&
1536 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1537 mp->mnt_nvnodelistsize == 0)) &&
1538 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1547 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1548 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1549 ("neg mount point vnode list size"));
1550 mp->mnt_nvnodelistsize++;
1551 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1552 ("Activating already active vnode"));
1553 vp->v_iflag |= VI_ACTIVE;
1554 mtx_lock(&vnode_free_list_mtx);
1555 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
1556 mp->mnt_activevnodelistsize++;
1557 mtx_unlock(&vnode_free_list_mtx);
1564 insmntque(struct vnode *vp, struct mount *mp)
1567 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1571 * Flush out and invalidate all buffers associated with a bufobj
1572 * Called with the underlying object locked.
1575 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1580 if (flags & V_SAVE) {
1581 error = bufobj_wwait(bo, slpflag, slptimeo);
1586 if (bo->bo_dirty.bv_cnt > 0) {
1588 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1591 * XXX We could save a lock/unlock if this was only
1592 * enabled under INVARIANTS
1595 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1596 panic("vinvalbuf: dirty bufs");
1600 * If you alter this loop please notice that interlock is dropped and
1601 * reacquired in flushbuflist. Special care is needed to ensure that
1602 * no race conditions occur from this.
1605 error = flushbuflist(&bo->bo_clean,
1606 flags, bo, slpflag, slptimeo);
1607 if (error == 0 && !(flags & V_CLEANONLY))
1608 error = flushbuflist(&bo->bo_dirty,
1609 flags, bo, slpflag, slptimeo);
1610 if (error != 0 && error != EAGAIN) {
1614 } while (error != 0);
1617 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1618 * have write I/O in-progress but if there is a VM object then the
1619 * VM object can also have read-I/O in-progress.
1622 bufobj_wwait(bo, 0, 0);
1623 if ((flags & V_VMIO) == 0) {
1625 if (bo->bo_object != NULL) {
1626 VM_OBJECT_WLOCK(bo->bo_object);
1627 vm_object_pip_wait(bo->bo_object, "bovlbx");
1628 VM_OBJECT_WUNLOCK(bo->bo_object);
1632 } while (bo->bo_numoutput > 0);
1636 * Destroy the copy in the VM cache, too.
1638 if (bo->bo_object != NULL &&
1639 (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1640 VM_OBJECT_WLOCK(bo->bo_object);
1641 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1642 OBJPR_CLEANONLY : 0);
1643 VM_OBJECT_WUNLOCK(bo->bo_object);
1648 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1649 V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1650 bo->bo_clean.bv_cnt > 0))
1651 panic("vinvalbuf: flush failed");
1652 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1653 bo->bo_dirty.bv_cnt > 0)
1654 panic("vinvalbuf: flush dirty failed");
1661 * Flush out and invalidate all buffers associated with a vnode.
1662 * Called with the underlying object locked.
1665 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1668 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1669 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1670 if (vp->v_object != NULL && vp->v_object->handle != vp)
1672 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1676 * Flush out buffers on the specified list.
1680 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1683 struct buf *bp, *nbp;
1688 ASSERT_BO_WLOCKED(bo);
1691 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1692 if (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA)) ||
1693 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0)) {
1697 lblkno = nbp->b_lblkno;
1698 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
1701 error = BUF_TIMELOCK(bp,
1702 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
1703 "flushbuf", slpflag, slptimeo);
1706 return (error != ENOLCK ? error : EAGAIN);
1708 KASSERT(bp->b_bufobj == bo,
1709 ("bp %p wrong b_bufobj %p should be %p",
1710 bp, bp->b_bufobj, bo));
1712 * XXX Since there are no node locks for NFS, I
1713 * believe there is a slight chance that a delayed
1714 * write will occur while sleeping just above, so
1717 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1720 bp->b_flags |= B_ASYNC;
1723 return (EAGAIN); /* XXX: why not loop ? */
1726 bp->b_flags |= (B_INVAL | B_RELBUF);
1727 bp->b_flags &= ~B_ASYNC;
1732 nbp = gbincore(bo, lblkno);
1733 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1735 break; /* nbp invalid */
1741 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
1747 ASSERT_BO_LOCKED(bo);
1749 for (lblkno = startn;;) {
1751 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
1752 if (bp == NULL || bp->b_lblkno >= endn ||
1753 bp->b_lblkno < startn)
1755 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
1756 LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
1759 if (error == ENOLCK)
1763 KASSERT(bp->b_bufobj == bo,
1764 ("bp %p wrong b_bufobj %p should be %p",
1765 bp, bp->b_bufobj, bo));
1766 lblkno = bp->b_lblkno + 1;
1767 if ((bp->b_flags & B_MANAGED) == 0)
1769 bp->b_flags |= B_RELBUF;
1771 * In the VMIO case, use the B_NOREUSE flag to hint that the
1772 * pages backing each buffer in the range are unlikely to be
1773 * reused. Dirty buffers will have the hint applied once
1774 * they've been written.
1776 if ((bp->b_flags & B_VMIO) != 0)
1777 bp->b_flags |= B_NOREUSE;
1785 * Truncate a file's buffer and pages to a specified length. This
1786 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
1790 vtruncbuf(struct vnode *vp, struct ucred *cred, off_t length, int blksize)
1792 struct buf *bp, *nbp;
1797 CTR5(KTR_VFS, "%s: vp %p with cred %p and block %d:%ju", __func__,
1798 vp, cred, blksize, (uintmax_t)length);
1801 * Round up to the *next* lbn.
1803 trunclbn = howmany(length, blksize);
1805 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
1812 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
1813 if (bp->b_lblkno < trunclbn)
1816 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1817 BO_LOCKPTR(bo)) == ENOLCK)
1821 bp->b_flags |= (B_INVAL | B_RELBUF);
1822 bp->b_flags &= ~B_ASYNC;
1828 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
1829 (nbp->b_vp != vp) ||
1830 (nbp->b_flags & B_DELWRI))) {
1836 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1837 if (bp->b_lblkno < trunclbn)
1840 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1841 BO_LOCKPTR(bo)) == ENOLCK)
1844 bp->b_flags |= (B_INVAL | B_RELBUF);
1845 bp->b_flags &= ~B_ASYNC;
1851 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
1852 (nbp->b_vp != vp) ||
1853 (nbp->b_flags & B_DELWRI) == 0)) {
1862 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1863 if (bp->b_lblkno > 0)
1866 * Since we hold the vnode lock this should only
1867 * fail if we're racing with the buf daemon.
1870 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1871 BO_LOCKPTR(bo)) == ENOLCK) {
1874 VNASSERT((bp->b_flags & B_DELWRI), vp,
1875 ("buf(%p) on dirty queue without DELWRI", bp));
1884 bufobj_wwait(bo, 0, 0);
1886 vnode_pager_setsize(vp, length);
1892 buf_vlist_remove(struct buf *bp)
1896 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1897 ASSERT_BO_WLOCKED(bp->b_bufobj);
1898 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
1899 (BX_VNDIRTY|BX_VNCLEAN),
1900 ("buf_vlist_remove: Buf %p is on two lists", bp));
1901 if (bp->b_xflags & BX_VNDIRTY)
1902 bv = &bp->b_bufobj->bo_dirty;
1904 bv = &bp->b_bufobj->bo_clean;
1905 BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
1906 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
1908 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1912 * Add the buffer to the sorted clean or dirty block list.
1914 * NOTE: xflags is passed as a constant, optimizing this inline function!
1917 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
1923 ASSERT_BO_WLOCKED(bo);
1924 KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
1925 ("dead bo %p", bo));
1926 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
1927 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
1928 bp->b_xflags |= xflags;
1929 if (xflags & BX_VNDIRTY)
1935 * Keep the list ordered. Optimize empty list insertion. Assume
1936 * we tend to grow at the tail so lookup_le should usually be cheaper
1939 if (bv->bv_cnt == 0 ||
1940 bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
1941 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
1942 else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
1943 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
1945 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
1946 error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
1948 panic("buf_vlist_add: Preallocated nodes insufficient.");
1953 * Look up a buffer using the buffer tries.
1956 gbincore(struct bufobj *bo, daddr_t lblkno)
1960 ASSERT_BO_LOCKED(bo);
1961 bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
1964 return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
1968 * Associate a buffer with a vnode.
1971 bgetvp(struct vnode *vp, struct buf *bp)
1976 ASSERT_BO_WLOCKED(bo);
1977 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
1979 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
1980 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
1981 ("bgetvp: bp already attached! %p", bp));
1987 * Insert onto list for new vnode.
1989 buf_vlist_add(bp, bo, BX_VNCLEAN);
1993 * Disassociate a buffer from a vnode.
1996 brelvp(struct buf *bp)
2001 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2002 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2005 * Delete from old vnode list, if on one.
2007 vp = bp->b_vp; /* XXX */
2010 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2011 buf_vlist_remove(bp);
2013 panic("brelvp: Buffer %p not on queue.", bp);
2014 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2015 bo->bo_flag &= ~BO_ONWORKLST;
2016 mtx_lock(&sync_mtx);
2017 LIST_REMOVE(bo, bo_synclist);
2018 syncer_worklist_len--;
2019 mtx_unlock(&sync_mtx);
2022 bp->b_bufobj = NULL;
2028 * Add an item to the syncer work queue.
2031 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2035 ASSERT_BO_WLOCKED(bo);
2037 mtx_lock(&sync_mtx);
2038 if (bo->bo_flag & BO_ONWORKLST)
2039 LIST_REMOVE(bo, bo_synclist);
2041 bo->bo_flag |= BO_ONWORKLST;
2042 syncer_worklist_len++;
2045 if (delay > syncer_maxdelay - 2)
2046 delay = syncer_maxdelay - 2;
2047 slot = (syncer_delayno + delay) & syncer_mask;
2049 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2050 mtx_unlock(&sync_mtx);
2054 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2058 mtx_lock(&sync_mtx);
2059 len = syncer_worklist_len - sync_vnode_count;
2060 mtx_unlock(&sync_mtx);
2061 error = SYSCTL_OUT(req, &len, sizeof(len));
2065 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
2066 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2068 static struct proc *updateproc;
2069 static void sched_sync(void);
2070 static struct kproc_desc up_kp = {
2075 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2078 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2083 *bo = LIST_FIRST(slp);
2086 vp = (*bo)->__bo_vnode; /* XXX */
2087 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2090 * We use vhold in case the vnode does not
2091 * successfully sync. vhold prevents the vnode from
2092 * going away when we unlock the sync_mtx so that
2093 * we can acquire the vnode interlock.
2096 mtx_unlock(&sync_mtx);
2098 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2100 mtx_lock(&sync_mtx);
2101 return (*bo == LIST_FIRST(slp));
2103 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2104 (void) VOP_FSYNC(vp, MNT_LAZY, td);
2106 vn_finished_write(mp);
2108 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2110 * Put us back on the worklist. The worklist
2111 * routine will remove us from our current
2112 * position and then add us back in at a later
2115 vn_syncer_add_to_worklist(*bo, syncdelay);
2119 mtx_lock(&sync_mtx);
2123 static int first_printf = 1;
2126 * System filesystem synchronizer daemon.
2131 struct synclist *next, *slp;
2134 struct thread *td = curthread;
2136 int net_worklist_len;
2137 int syncer_final_iter;
2141 syncer_final_iter = 0;
2142 syncer_state = SYNCER_RUNNING;
2143 starttime = time_uptime;
2144 td->td_pflags |= TDP_NORUNNINGBUF;
2146 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2149 mtx_lock(&sync_mtx);
2151 if (syncer_state == SYNCER_FINAL_DELAY &&
2152 syncer_final_iter == 0) {
2153 mtx_unlock(&sync_mtx);
2154 kproc_suspend_check(td->td_proc);
2155 mtx_lock(&sync_mtx);
2157 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2158 if (syncer_state != SYNCER_RUNNING &&
2159 starttime != time_uptime) {
2161 printf("\nSyncing disks, vnodes remaining... ");
2164 printf("%d ", net_worklist_len);
2166 starttime = time_uptime;
2169 * Push files whose dirty time has expired. Be careful
2170 * of interrupt race on slp queue.
2172 * Skip over empty worklist slots when shutting down.
2175 slp = &syncer_workitem_pending[syncer_delayno];
2176 syncer_delayno += 1;
2177 if (syncer_delayno == syncer_maxdelay)
2179 next = &syncer_workitem_pending[syncer_delayno];
2181 * If the worklist has wrapped since the
2182 * it was emptied of all but syncer vnodes,
2183 * switch to the FINAL_DELAY state and run
2184 * for one more second.
2186 if (syncer_state == SYNCER_SHUTTING_DOWN &&
2187 net_worklist_len == 0 &&
2188 last_work_seen == syncer_delayno) {
2189 syncer_state = SYNCER_FINAL_DELAY;
2190 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2192 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2193 syncer_worklist_len > 0);
2196 * Keep track of the last time there was anything
2197 * on the worklist other than syncer vnodes.
2198 * Return to the SHUTTING_DOWN state if any
2201 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2202 last_work_seen = syncer_delayno;
2203 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2204 syncer_state = SYNCER_SHUTTING_DOWN;
2205 while (!LIST_EMPTY(slp)) {
2206 error = sync_vnode(slp, &bo, td);
2208 LIST_REMOVE(bo, bo_synclist);
2209 LIST_INSERT_HEAD(next, bo, bo_synclist);
2213 if (first_printf == 0) {
2215 * Drop the sync mutex, because some watchdog
2216 * drivers need to sleep while patting
2218 mtx_unlock(&sync_mtx);
2219 wdog_kern_pat(WD_LASTVAL);
2220 mtx_lock(&sync_mtx);
2224 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2225 syncer_final_iter--;
2227 * The variable rushjob allows the kernel to speed up the
2228 * processing of the filesystem syncer process. A rushjob
2229 * value of N tells the filesystem syncer to process the next
2230 * N seconds worth of work on its queue ASAP. Currently rushjob
2231 * is used by the soft update code to speed up the filesystem
2232 * syncer process when the incore state is getting so far
2233 * ahead of the disk that the kernel memory pool is being
2234 * threatened with exhaustion.
2241 * Just sleep for a short period of time between
2242 * iterations when shutting down to allow some I/O
2245 * If it has taken us less than a second to process the
2246 * current work, then wait. Otherwise start right over
2247 * again. We can still lose time if any single round
2248 * takes more than two seconds, but it does not really
2249 * matter as we are just trying to generally pace the
2250 * filesystem activity.
2252 if (syncer_state != SYNCER_RUNNING ||
2253 time_uptime == starttime) {
2255 sched_prio(td, PPAUSE);
2258 if (syncer_state != SYNCER_RUNNING)
2259 cv_timedwait(&sync_wakeup, &sync_mtx,
2260 hz / SYNCER_SHUTDOWN_SPEEDUP);
2261 else if (time_uptime == starttime)
2262 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2267 * Request the syncer daemon to speed up its work.
2268 * We never push it to speed up more than half of its
2269 * normal turn time, otherwise it could take over the cpu.
2272 speedup_syncer(void)
2276 mtx_lock(&sync_mtx);
2277 if (rushjob < syncdelay / 2) {
2279 stat_rush_requests += 1;
2282 mtx_unlock(&sync_mtx);
2283 cv_broadcast(&sync_wakeup);
2288 * Tell the syncer to speed up its work and run though its work
2289 * list several times, then tell it to shut down.
2292 syncer_shutdown(void *arg, int howto)
2295 if (howto & RB_NOSYNC)
2297 mtx_lock(&sync_mtx);
2298 syncer_state = SYNCER_SHUTTING_DOWN;
2300 mtx_unlock(&sync_mtx);
2301 cv_broadcast(&sync_wakeup);
2302 kproc_shutdown(arg, howto);
2306 syncer_suspend(void)
2309 syncer_shutdown(updateproc, 0);
2316 mtx_lock(&sync_mtx);
2318 syncer_state = SYNCER_RUNNING;
2319 mtx_unlock(&sync_mtx);
2320 cv_broadcast(&sync_wakeup);
2321 kproc_resume(updateproc);
2325 * Reassign a buffer from one vnode to another.
2326 * Used to assign file specific control information
2327 * (indirect blocks) to the vnode to which they belong.
2330 reassignbuf(struct buf *bp)
2343 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2344 bp, bp->b_vp, bp->b_flags);
2346 * B_PAGING flagged buffers cannot be reassigned because their vp
2347 * is not fully linked in.
2349 if (bp->b_flags & B_PAGING)
2350 panic("cannot reassign paging buffer");
2353 * Delete from old vnode list, if on one.
2356 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2357 buf_vlist_remove(bp);
2359 panic("reassignbuf: Buffer %p not on queue.", bp);
2361 * If dirty, put on list of dirty buffers; otherwise insert onto list
2364 if (bp->b_flags & B_DELWRI) {
2365 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2366 switch (vp->v_type) {
2376 vn_syncer_add_to_worklist(bo, delay);
2378 buf_vlist_add(bp, bo, BX_VNDIRTY);
2380 buf_vlist_add(bp, bo, BX_VNCLEAN);
2382 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2383 mtx_lock(&sync_mtx);
2384 LIST_REMOVE(bo, bo_synclist);
2385 syncer_worklist_len--;
2386 mtx_unlock(&sync_mtx);
2387 bo->bo_flag &= ~BO_ONWORKLST;
2392 bp = TAILQ_FIRST(&bv->bv_hd);
2393 KASSERT(bp == NULL || bp->b_bufobj == bo,
2394 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2395 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2396 KASSERT(bp == NULL || bp->b_bufobj == bo,
2397 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2399 bp = TAILQ_FIRST(&bv->bv_hd);
2400 KASSERT(bp == NULL || bp->b_bufobj == bo,
2401 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2402 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2403 KASSERT(bp == NULL || bp->b_bufobj == bo,
2404 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2410 v_init_counters(struct vnode *vp)
2413 VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2414 vp, ("%s called for an initialized vnode", __FUNCTION__));
2415 ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2417 refcount_init(&vp->v_holdcnt, 1);
2418 refcount_init(&vp->v_usecount, 1);
2422 v_incr_usecount_locked(struct vnode *vp)
2425 ASSERT_VI_LOCKED(vp, __func__);
2426 if ((vp->v_iflag & VI_OWEINACT) != 0) {
2427 VNASSERT(vp->v_usecount == 0, vp,
2428 ("vnode with usecount and VI_OWEINACT set"));
2429 vp->v_iflag &= ~VI_OWEINACT;
2431 refcount_acquire(&vp->v_usecount);
2432 v_incr_devcount(vp);
2436 * Increment the use and hold counts on the vnode, taking care to reference
2437 * the driver's usecount if this is a chardev. The _vhold() will remove
2438 * the vnode from the free list if it is presently free.
2441 v_incr_usecount(struct vnode *vp)
2444 ASSERT_VI_UNLOCKED(vp, __func__);
2445 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2447 if (vp->v_type != VCHR &&
2448 refcount_acquire_if_not_zero(&vp->v_usecount)) {
2449 VNODE_REFCOUNT_FENCE_ACQ();
2450 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2451 ("vnode with usecount and VI_OWEINACT set"));
2454 v_incr_usecount_locked(vp);
2460 * Increment si_usecount of the associated device, if any.
2463 v_incr_devcount(struct vnode *vp)
2466 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2467 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2469 vp->v_rdev->si_usecount++;
2475 * Decrement si_usecount of the associated device, if any.
2478 v_decr_devcount(struct vnode *vp)
2481 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2482 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2484 vp->v_rdev->si_usecount--;
2490 * Grab a particular vnode from the free list, increment its
2491 * reference count and lock it. VI_DOOMED is set if the vnode
2492 * is being destroyed. Only callers who specify LK_RETRY will
2493 * see doomed vnodes. If inactive processing was delayed in
2494 * vput try to do it here.
2496 * Notes on lockless counter manipulation:
2497 * _vhold, vputx and other routines make various decisions based
2498 * on either holdcnt or usecount being 0. As long as either counter
2499 * is not transitioning 0->1 nor 1->0, the manipulation can be done
2500 * with atomic operations. Otherwise the interlock is taken covering
2501 * both the atomic and additional actions.
2504 vget(struct vnode *vp, int flags, struct thread *td)
2506 int error, oweinact;
2508 VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2509 ("vget: invalid lock operation"));
2511 if ((flags & LK_INTERLOCK) != 0)
2512 ASSERT_VI_LOCKED(vp, __func__);
2514 ASSERT_VI_UNLOCKED(vp, __func__);
2515 if ((flags & LK_VNHELD) != 0)
2516 VNASSERT((vp->v_holdcnt > 0), vp,
2517 ("vget: LK_VNHELD passed but vnode not held"));
2519 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2521 if ((flags & LK_VNHELD) == 0)
2522 _vhold(vp, (flags & LK_INTERLOCK) != 0);
2524 if ((error = vn_lock(vp, flags)) != 0) {
2526 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2530 if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0)
2531 panic("vget: vn_lock failed to return ENOENT\n");
2533 * We don't guarantee that any particular close will
2534 * trigger inactive processing so just make a best effort
2535 * here at preventing a reference to a removed file. If
2536 * we don't succeed no harm is done.
2538 * Upgrade our holdcnt to a usecount.
2540 if (vp->v_type == VCHR ||
2541 !refcount_acquire_if_not_zero(&vp->v_usecount)) {
2543 if ((vp->v_iflag & VI_OWEINACT) == 0) {
2547 vp->v_iflag &= ~VI_OWEINACT;
2548 VNODE_REFCOUNT_FENCE_REL();
2550 refcount_acquire(&vp->v_usecount);
2551 v_incr_devcount(vp);
2552 if (oweinact && VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2553 (flags & LK_NOWAIT) == 0)
2561 * Increase the reference count of a vnode.
2564 vref(struct vnode *vp)
2567 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2569 v_incr_usecount(vp);
2573 vrefl(struct vnode *vp)
2576 ASSERT_VI_LOCKED(vp, __func__);
2577 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2579 v_incr_usecount_locked(vp);
2583 vrefact(struct vnode *vp)
2586 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2587 if (__predict_false(vp->v_type == VCHR)) {
2588 VNASSERT(vp->v_holdcnt > 0 && vp->v_usecount > 0, vp,
2589 ("%s: wrong ref counts", __func__));
2594 int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
2595 VNASSERT(old > 0, vp, ("%s: wrong hold count", __func__));
2596 old = atomic_fetchadd_int(&vp->v_usecount, 1);
2597 VNASSERT(old > 0, vp, ("%s: wrong use count", __func__));
2599 refcount_acquire(&vp->v_holdcnt);
2600 refcount_acquire(&vp->v_usecount);
2605 * Return reference count of a vnode.
2607 * The results of this call are only guaranteed when some mechanism is used to
2608 * stop other processes from gaining references to the vnode. This may be the
2609 * case if the caller holds the only reference. This is also useful when stale
2610 * data is acceptable as race conditions may be accounted for by some other
2614 vrefcnt(struct vnode *vp)
2617 return (vp->v_usecount);
2620 #define VPUTX_VRELE 1
2621 #define VPUTX_VPUT 2
2622 #define VPUTX_VUNREF 3
2625 * Decrement the use and hold counts for a vnode.
2627 * See an explanation near vget() as to why atomic operation is safe.
2630 vputx(struct vnode *vp, int func)
2634 KASSERT(vp != NULL, ("vputx: null vp"));
2635 if (func == VPUTX_VUNREF)
2636 ASSERT_VOP_LOCKED(vp, "vunref");
2637 else if (func == VPUTX_VPUT)
2638 ASSERT_VOP_LOCKED(vp, "vput");
2640 KASSERT(func == VPUTX_VRELE, ("vputx: wrong func"));
2641 ASSERT_VI_UNLOCKED(vp, __func__);
2642 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2644 if (vp->v_type != VCHR &&
2645 refcount_release_if_not_last(&vp->v_usecount)) {
2646 if (func == VPUTX_VPUT)
2655 * We want to hold the vnode until the inactive finishes to
2656 * prevent vgone() races. We drop the use count here and the
2657 * hold count below when we're done.
2659 if (!refcount_release(&vp->v_usecount) ||
2660 (vp->v_iflag & VI_DOINGINACT)) {
2661 if (func == VPUTX_VPUT)
2663 v_decr_devcount(vp);
2668 v_decr_devcount(vp);
2672 if (vp->v_usecount != 0) {
2673 vn_printf(vp, "vputx: usecount not zero for vnode ");
2674 panic("vputx: usecount not zero");
2677 CTR2(KTR_VFS, "%s: return vnode %p to the freelist", __func__, vp);
2680 * We must call VOP_INACTIVE with the node locked. Mark
2681 * as VI_DOINGINACT to avoid recursion.
2683 vp->v_iflag |= VI_OWEINACT;
2686 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
2690 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2691 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
2697 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2698 error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
2703 VNASSERT(vp->v_usecount == 0 || (vp->v_iflag & VI_OWEINACT) == 0, vp,
2704 ("vnode with usecount and VI_OWEINACT set"));
2706 if (vp->v_iflag & VI_OWEINACT)
2707 vinactive(vp, curthread);
2708 if (func != VPUTX_VUNREF)
2715 * Vnode put/release.
2716 * If count drops to zero, call inactive routine and return to freelist.
2719 vrele(struct vnode *vp)
2722 vputx(vp, VPUTX_VRELE);
2726 * Release an already locked vnode. This give the same effects as
2727 * unlock+vrele(), but takes less time and avoids releasing and
2728 * re-aquiring the lock (as vrele() acquires the lock internally.)
2731 vput(struct vnode *vp)
2734 vputx(vp, VPUTX_VPUT);
2738 * Release an exclusively locked vnode. Do not unlock the vnode lock.
2741 vunref(struct vnode *vp)
2744 vputx(vp, VPUTX_VUNREF);
2748 * Increase the hold count and activate if this is the first reference.
2751 _vhold(struct vnode *vp, bool locked)
2756 ASSERT_VI_LOCKED(vp, __func__);
2758 ASSERT_VI_UNLOCKED(vp, __func__);
2759 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2761 if (refcount_acquire_if_not_zero(&vp->v_holdcnt)) {
2762 VNODE_REFCOUNT_FENCE_ACQ();
2763 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2764 ("_vhold: vnode with holdcnt is free"));
2769 if ((vp->v_iflag & VI_FREE) == 0) {
2770 refcount_acquire(&vp->v_holdcnt);
2775 VNASSERT(vp->v_holdcnt == 0, vp,
2776 ("%s: wrong hold count", __func__));
2777 VNASSERT(vp->v_op != NULL, vp,
2778 ("%s: vnode already reclaimed.", __func__));
2780 * Remove a vnode from the free list, mark it as in use,
2781 * and put it on the active list.
2783 mtx_lock(&vnode_free_list_mtx);
2784 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
2786 vp->v_iflag &= ~VI_FREE;
2787 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
2788 ("Activating already active vnode"));
2789 vp->v_iflag |= VI_ACTIVE;
2791 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
2792 mp->mnt_activevnodelistsize++;
2793 mtx_unlock(&vnode_free_list_mtx);
2794 refcount_acquire(&vp->v_holdcnt);
2800 * Drop the hold count of the vnode. If this is the last reference to
2801 * the vnode we place it on the free list unless it has been vgone'd
2802 * (marked VI_DOOMED) in which case we will free it.
2804 * Because the vnode vm object keeps a hold reference on the vnode if
2805 * there is at least one resident non-cached page, the vnode cannot
2806 * leave the active list without the page cleanup done.
2809 _vdrop(struct vnode *vp, bool locked)
2816 ASSERT_VI_LOCKED(vp, __func__);
2818 ASSERT_VI_UNLOCKED(vp, __func__);
2819 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2820 if ((int)vp->v_holdcnt <= 0)
2821 panic("vdrop: holdcnt %d", vp->v_holdcnt);
2823 if (refcount_release_if_not_last(&vp->v_holdcnt))
2827 if (refcount_release(&vp->v_holdcnt) == 0) {
2831 if ((vp->v_iflag & VI_DOOMED) == 0) {
2833 * Mark a vnode as free: remove it from its active list
2834 * and put it up for recycling on the freelist.
2836 VNASSERT(vp->v_op != NULL, vp,
2837 ("vdropl: vnode already reclaimed."));
2838 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2839 ("vnode already free"));
2840 VNASSERT(vp->v_holdcnt == 0, vp,
2841 ("vdropl: freeing when we shouldn't"));
2842 active = vp->v_iflag & VI_ACTIVE;
2843 if ((vp->v_iflag & VI_OWEINACT) == 0) {
2844 vp->v_iflag &= ~VI_ACTIVE;
2846 mtx_lock(&vnode_free_list_mtx);
2848 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp,
2850 mp->mnt_activevnodelistsize--;
2852 TAILQ_INSERT_TAIL(&vnode_free_list, vp,
2855 vp->v_iflag |= VI_FREE;
2856 mtx_unlock(&vnode_free_list_mtx);
2858 counter_u64_add(free_owe_inact, 1);
2864 * The vnode has been marked for destruction, so free it.
2866 * The vnode will be returned to the zone where it will
2867 * normally remain until it is needed for another vnode. We
2868 * need to cleanup (or verify that the cleanup has already
2869 * been done) any residual data left from its current use
2870 * so as not to contaminate the freshly allocated vnode.
2872 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
2873 atomic_subtract_long(&numvnodes, 1);
2875 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2876 ("cleaned vnode still on the free list."));
2877 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
2878 VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
2879 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
2880 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
2881 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
2882 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
2883 VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
2884 ("clean blk trie not empty"));
2885 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
2886 VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
2887 ("dirty blk trie not empty"));
2888 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
2889 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
2890 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
2891 VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
2892 ("Dangling rangelock waiters"));
2895 mac_vnode_destroy(vp);
2897 if (vp->v_pollinfo != NULL) {
2898 destroy_vpollinfo(vp->v_pollinfo);
2899 vp->v_pollinfo = NULL;
2902 /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
2905 bzero(&vp->v_un, sizeof(vp->v_un));
2906 vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
2910 uma_zfree(vnode_zone, vp);
2914 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
2915 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
2916 * OWEINACT tracks whether a vnode missed a call to inactive due to a
2917 * failed lock upgrade.
2920 vinactive(struct vnode *vp, struct thread *td)
2922 struct vm_object *obj;
2924 ASSERT_VOP_ELOCKED(vp, "vinactive");
2925 ASSERT_VI_LOCKED(vp, "vinactive");
2926 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
2927 ("vinactive: recursed on VI_DOINGINACT"));
2928 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2929 vp->v_iflag |= VI_DOINGINACT;
2930 vp->v_iflag &= ~VI_OWEINACT;
2933 * Before moving off the active list, we must be sure that any
2934 * modified pages are converted into the vnode's dirty
2935 * buffers, since these will no longer be checked once the
2936 * vnode is on the inactive list.
2938 * The write-out of the dirty pages is asynchronous. At the
2939 * point that VOP_INACTIVE() is called, there could still be
2940 * pending I/O and dirty pages in the object.
2942 if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
2943 (obj->flags & OBJ_MIGHTBEDIRTY) != 0) {
2944 VM_OBJECT_WLOCK(obj);
2945 vm_object_page_clean(obj, 0, 0, 0);
2946 VM_OBJECT_WUNLOCK(obj);
2948 VOP_INACTIVE(vp, td);
2950 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
2951 ("vinactive: lost VI_DOINGINACT"));
2952 vp->v_iflag &= ~VI_DOINGINACT;
2956 * Remove any vnodes in the vnode table belonging to mount point mp.
2958 * If FORCECLOSE is not specified, there should not be any active ones,
2959 * return error if any are found (nb: this is a user error, not a
2960 * system error). If FORCECLOSE is specified, detach any active vnodes
2963 * If WRITECLOSE is set, only flush out regular file vnodes open for
2966 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
2968 * `rootrefs' specifies the base reference count for the root vnode
2969 * of this filesystem. The root vnode is considered busy if its
2970 * v_usecount exceeds this value. On a successful return, vflush(, td)
2971 * will call vrele() on the root vnode exactly rootrefs times.
2972 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
2976 static int busyprt = 0; /* print out busy vnodes */
2977 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
2981 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
2983 struct vnode *vp, *mvp, *rootvp = NULL;
2985 int busy = 0, error;
2987 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
2990 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
2991 ("vflush: bad args"));
2993 * Get the filesystem root vnode. We can vput() it
2994 * immediately, since with rootrefs > 0, it won't go away.
2996 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
2997 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3004 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3006 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3009 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3013 * Skip over a vnodes marked VV_SYSTEM.
3015 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3021 * If WRITECLOSE is set, flush out unlinked but still open
3022 * files (even if open only for reading) and regular file
3023 * vnodes open for writing.
3025 if (flags & WRITECLOSE) {
3026 if (vp->v_object != NULL) {
3027 VM_OBJECT_WLOCK(vp->v_object);
3028 vm_object_page_clean(vp->v_object, 0, 0, 0);
3029 VM_OBJECT_WUNLOCK(vp->v_object);
3031 error = VOP_FSYNC(vp, MNT_WAIT, td);
3035 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3038 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3041 if ((vp->v_type == VNON ||
3042 (error == 0 && vattr.va_nlink > 0)) &&
3043 (vp->v_writecount == 0 || vp->v_type != VREG)) {
3051 * With v_usecount == 0, all we need to do is clear out the
3052 * vnode data structures and we are done.
3054 * If FORCECLOSE is set, forcibly close the vnode.
3056 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3062 vn_printf(vp, "vflush: busy vnode ");
3068 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3070 * If just the root vnode is busy, and if its refcount
3071 * is equal to `rootrefs', then go ahead and kill it.
3074 KASSERT(busy > 0, ("vflush: not busy"));
3075 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3076 ("vflush: usecount %d < rootrefs %d",
3077 rootvp->v_usecount, rootrefs));
3078 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3079 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3081 VOP_UNLOCK(rootvp, 0);
3087 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3091 for (; rootrefs > 0; rootrefs--)
3097 * Recycle an unused vnode to the front of the free list.
3100 vrecycle(struct vnode *vp)
3104 ASSERT_VOP_ELOCKED(vp, "vrecycle");
3105 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3108 if (vp->v_usecount == 0) {
3117 * Eliminate all activity associated with a vnode
3118 * in preparation for reuse.
3121 vgone(struct vnode *vp)
3129 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3130 struct vnode *lowervp __unused)
3135 * Notify upper mounts about reclaimed or unlinked vnode.
3138 vfs_notify_upper(struct vnode *vp, int event)
3140 static struct vfsops vgonel_vfsops = {
3141 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3142 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3144 struct mount *mp, *ump, *mmp;
3151 if (TAILQ_EMPTY(&mp->mnt_uppers))
3154 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3155 mmp->mnt_op = &vgonel_vfsops;
3156 mmp->mnt_kern_flag |= MNTK_MARKER;
3158 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3159 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3160 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3161 ump = TAILQ_NEXT(ump, mnt_upper_link);
3164 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3167 case VFS_NOTIFY_UPPER_RECLAIM:
3168 VFS_RECLAIM_LOWERVP(ump, vp);
3170 case VFS_NOTIFY_UPPER_UNLINK:
3171 VFS_UNLINK_LOWERVP(ump, vp);
3174 KASSERT(0, ("invalid event %d", event));
3178 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3179 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3182 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3183 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3184 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3185 wakeup(&mp->mnt_uppers);
3192 * vgone, with the vp interlock held.
3195 vgonel(struct vnode *vp)
3202 ASSERT_VOP_ELOCKED(vp, "vgonel");
3203 ASSERT_VI_LOCKED(vp, "vgonel");
3204 VNASSERT(vp->v_holdcnt, vp,
3205 ("vgonel: vp %p has no reference.", vp));
3206 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3210 * Don't vgonel if we're already doomed.
3212 if (vp->v_iflag & VI_DOOMED)
3214 vp->v_iflag |= VI_DOOMED;
3217 * Check to see if the vnode is in use. If so, we have to call
3218 * VOP_CLOSE() and VOP_INACTIVE().
3220 active = vp->v_usecount;
3221 oweinact = (vp->v_iflag & VI_OWEINACT);
3223 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
3226 * If purging an active vnode, it must be closed and
3227 * deactivated before being reclaimed.
3230 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
3231 if (oweinact || active) {
3233 if ((vp->v_iflag & VI_DOINGINACT) == 0)
3237 if (vp->v_type == VSOCK)
3238 vfs_unp_reclaim(vp);
3241 * Clean out any buffers associated with the vnode.
3242 * If the flush fails, just toss the buffers.
3245 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
3246 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
3247 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
3248 while (vinvalbuf(vp, 0, 0, 0) != 0)
3252 BO_LOCK(&vp->v_bufobj);
3253 KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
3254 vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
3255 TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
3256 vp->v_bufobj.bo_clean.bv_cnt == 0,
3257 ("vp %p bufobj not invalidated", vp));
3260 * For VMIO bufobj, BO_DEAD is set in vm_object_terminate()
3261 * after the object's page queue is flushed.
3263 if (vp->v_bufobj.bo_object == NULL)
3264 vp->v_bufobj.bo_flag |= BO_DEAD;
3265 BO_UNLOCK(&vp->v_bufobj);
3268 * Reclaim the vnode.
3270 if (VOP_RECLAIM(vp, td))
3271 panic("vgone: cannot reclaim");
3273 vn_finished_secondary_write(mp);
3274 VNASSERT(vp->v_object == NULL, vp,
3275 ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
3277 * Clear the advisory locks and wake up waiting threads.
3279 (void)VOP_ADVLOCKPURGE(vp);
3282 * Delete from old mount point vnode list.
3287 * Done with purge, reset to the standard lock and invalidate
3291 vp->v_vnlock = &vp->v_lock;
3292 vp->v_op = &dead_vnodeops;
3298 * Calculate the total number of references to a special device.
3301 vcount(struct vnode *vp)
3306 count = vp->v_rdev->si_usecount;
3312 * Same as above, but using the struct cdev *as argument
3315 count_dev(struct cdev *dev)
3320 count = dev->si_usecount;
3326 * Print out a description of a vnode.
3328 static char *typename[] =
3329 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
3333 vn_printf(struct vnode *vp, const char *fmt, ...)
3336 char buf[256], buf2[16];
3342 printf("%p: ", (void *)vp);
3343 printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
3344 printf(" usecount %d, writecount %d, refcount %d",
3345 vp->v_usecount, vp->v_writecount, vp->v_holdcnt);
3346 switch (vp->v_type) {
3348 printf(" mountedhere %p\n", vp->v_mountedhere);
3351 printf(" rdev %p\n", vp->v_rdev);
3354 printf(" socket %p\n", vp->v_socket);
3357 printf(" fifoinfo %p\n", vp->v_fifoinfo);
3365 if (vp->v_vflag & VV_ROOT)
3366 strlcat(buf, "|VV_ROOT", sizeof(buf));
3367 if (vp->v_vflag & VV_ISTTY)
3368 strlcat(buf, "|VV_ISTTY", sizeof(buf));
3369 if (vp->v_vflag & VV_NOSYNC)
3370 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
3371 if (vp->v_vflag & VV_ETERNALDEV)
3372 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
3373 if (vp->v_vflag & VV_CACHEDLABEL)
3374 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
3375 if (vp->v_vflag & VV_TEXT)
3376 strlcat(buf, "|VV_TEXT", sizeof(buf));
3377 if (vp->v_vflag & VV_COPYONWRITE)
3378 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
3379 if (vp->v_vflag & VV_SYSTEM)
3380 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
3381 if (vp->v_vflag & VV_PROCDEP)
3382 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
3383 if (vp->v_vflag & VV_NOKNOTE)
3384 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
3385 if (vp->v_vflag & VV_DELETED)
3386 strlcat(buf, "|VV_DELETED", sizeof(buf));
3387 if (vp->v_vflag & VV_MD)
3388 strlcat(buf, "|VV_MD", sizeof(buf));
3389 if (vp->v_vflag & VV_FORCEINSMQ)
3390 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
3391 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
3392 VV_CACHEDLABEL | VV_TEXT | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
3393 VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
3395 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
3396 strlcat(buf, buf2, sizeof(buf));
3398 if (vp->v_iflag & VI_MOUNT)
3399 strlcat(buf, "|VI_MOUNT", sizeof(buf));
3400 if (vp->v_iflag & VI_DOOMED)
3401 strlcat(buf, "|VI_DOOMED", sizeof(buf));
3402 if (vp->v_iflag & VI_FREE)
3403 strlcat(buf, "|VI_FREE", sizeof(buf));
3404 if (vp->v_iflag & VI_ACTIVE)
3405 strlcat(buf, "|VI_ACTIVE", sizeof(buf));
3406 if (vp->v_iflag & VI_DOINGINACT)
3407 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
3408 if (vp->v_iflag & VI_OWEINACT)
3409 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
3410 flags = vp->v_iflag & ~(VI_MOUNT | VI_DOOMED | VI_FREE |
3411 VI_ACTIVE | VI_DOINGINACT | VI_OWEINACT);
3413 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
3414 strlcat(buf, buf2, sizeof(buf));
3416 printf(" flags (%s)\n", buf + 1);
3417 if (mtx_owned(VI_MTX(vp)))
3418 printf(" VI_LOCKed");
3419 if (vp->v_object != NULL)
3420 printf(" v_object %p ref %d pages %d "
3421 "cleanbuf %d dirtybuf %d\n",
3422 vp->v_object, vp->v_object->ref_count,
3423 vp->v_object->resident_page_count,
3424 vp->v_bufobj.bo_clean.bv_cnt,
3425 vp->v_bufobj.bo_dirty.bv_cnt);
3427 lockmgr_printinfo(vp->v_vnlock);
3428 if (vp->v_data != NULL)
3434 * List all of the locked vnodes in the system.
3435 * Called when debugging the kernel.
3437 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
3443 * Note: because this is DDB, we can't obey the locking semantics
3444 * for these structures, which means we could catch an inconsistent
3445 * state and dereference a nasty pointer. Not much to be done
3448 db_printf("Locked vnodes\n");
3449 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3450 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3451 if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
3452 vn_printf(vp, "vnode ");
3458 * Show details about the given vnode.
3460 DB_SHOW_COMMAND(vnode, db_show_vnode)
3466 vp = (struct vnode *)addr;
3467 vn_printf(vp, "vnode ");
3471 * Show details about the given mount point.
3473 DB_SHOW_COMMAND(mount, db_show_mount)
3484 /* No address given, print short info about all mount points. */
3485 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3486 db_printf("%p %s on %s (%s)\n", mp,
3487 mp->mnt_stat.f_mntfromname,
3488 mp->mnt_stat.f_mntonname,
3489 mp->mnt_stat.f_fstypename);
3493 db_printf("\nMore info: show mount <addr>\n");
3497 mp = (struct mount *)addr;
3498 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
3499 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
3502 mflags = mp->mnt_flag;
3503 #define MNT_FLAG(flag) do { \
3504 if (mflags & (flag)) { \
3505 if (buf[0] != '\0') \
3506 strlcat(buf, ", ", sizeof(buf)); \
3507 strlcat(buf, (#flag) + 4, sizeof(buf)); \
3508 mflags &= ~(flag); \
3511 MNT_FLAG(MNT_RDONLY);
3512 MNT_FLAG(MNT_SYNCHRONOUS);
3513 MNT_FLAG(MNT_NOEXEC);
3514 MNT_FLAG(MNT_NOSUID);
3515 MNT_FLAG(MNT_NFS4ACLS);
3516 MNT_FLAG(MNT_UNION);
3517 MNT_FLAG(MNT_ASYNC);
3518 MNT_FLAG(MNT_SUIDDIR);
3519 MNT_FLAG(MNT_SOFTDEP);
3520 MNT_FLAG(MNT_NOSYMFOLLOW);
3521 MNT_FLAG(MNT_GJOURNAL);
3522 MNT_FLAG(MNT_MULTILABEL);
3524 MNT_FLAG(MNT_NOATIME);
3525 MNT_FLAG(MNT_NOCLUSTERR);
3526 MNT_FLAG(MNT_NOCLUSTERW);
3528 MNT_FLAG(MNT_EXRDONLY);
3529 MNT_FLAG(MNT_EXPORTED);
3530 MNT_FLAG(MNT_DEFEXPORTED);
3531 MNT_FLAG(MNT_EXPORTANON);
3532 MNT_FLAG(MNT_EXKERB);
3533 MNT_FLAG(MNT_EXPUBLIC);
3534 MNT_FLAG(MNT_LOCAL);
3535 MNT_FLAG(MNT_QUOTA);
3536 MNT_FLAG(MNT_ROOTFS);
3538 MNT_FLAG(MNT_IGNORE);
3539 MNT_FLAG(MNT_UPDATE);
3540 MNT_FLAG(MNT_DELEXPORT);
3541 MNT_FLAG(MNT_RELOAD);
3542 MNT_FLAG(MNT_FORCE);
3543 MNT_FLAG(MNT_SNAPSHOT);
3544 MNT_FLAG(MNT_BYFSID);
3548 strlcat(buf, ", ", sizeof(buf));
3549 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3550 "0x%016jx", mflags);
3552 db_printf(" mnt_flag = %s\n", buf);
3555 flags = mp->mnt_kern_flag;
3556 #define MNT_KERN_FLAG(flag) do { \
3557 if (flags & (flag)) { \
3558 if (buf[0] != '\0') \
3559 strlcat(buf, ", ", sizeof(buf)); \
3560 strlcat(buf, (#flag) + 5, sizeof(buf)); \
3564 MNT_KERN_FLAG(MNTK_UNMOUNTF);
3565 MNT_KERN_FLAG(MNTK_ASYNC);
3566 MNT_KERN_FLAG(MNTK_SOFTDEP);
3567 MNT_KERN_FLAG(MNTK_NOINSMNTQ);
3568 MNT_KERN_FLAG(MNTK_DRAINING);
3569 MNT_KERN_FLAG(MNTK_REFEXPIRE);
3570 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
3571 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
3572 MNT_KERN_FLAG(MNTK_NO_IOPF);
3573 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
3574 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
3575 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
3576 MNT_KERN_FLAG(MNTK_MARKER);
3577 MNT_KERN_FLAG(MNTK_USES_BCACHE);
3578 MNT_KERN_FLAG(MNTK_NOASYNC);
3579 MNT_KERN_FLAG(MNTK_UNMOUNT);
3580 MNT_KERN_FLAG(MNTK_MWAIT);
3581 MNT_KERN_FLAG(MNTK_SUSPEND);
3582 MNT_KERN_FLAG(MNTK_SUSPEND2);
3583 MNT_KERN_FLAG(MNTK_SUSPENDED);
3584 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
3585 MNT_KERN_FLAG(MNTK_NOKNOTE);
3586 #undef MNT_KERN_FLAG
3589 strlcat(buf, ", ", sizeof(buf));
3590 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3593 db_printf(" mnt_kern_flag = %s\n", buf);
3595 db_printf(" mnt_opt = ");
3596 opt = TAILQ_FIRST(mp->mnt_opt);
3598 db_printf("%s", opt->name);
3599 opt = TAILQ_NEXT(opt, link);
3600 while (opt != NULL) {
3601 db_printf(", %s", opt->name);
3602 opt = TAILQ_NEXT(opt, link);
3608 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
3609 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
3610 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
3611 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
3612 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
3613 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
3614 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
3615 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
3616 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
3617 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
3618 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
3619 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
3621 db_printf(" mnt_cred = { uid=%u ruid=%u",
3622 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
3623 if (jailed(mp->mnt_cred))
3624 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
3626 db_printf(" mnt_ref = %d\n", mp->mnt_ref);
3627 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
3628 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
3629 db_printf(" mnt_activevnodelistsize = %d\n",
3630 mp->mnt_activevnodelistsize);
3631 db_printf(" mnt_writeopcount = %d\n", mp->mnt_writeopcount);
3632 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
3633 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
3634 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
3635 db_printf(" mnt_lockref = %d\n", mp->mnt_lockref);
3636 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
3637 db_printf(" mnt_secondary_accwrites = %d\n",
3638 mp->mnt_secondary_accwrites);
3639 db_printf(" mnt_gjprovider = %s\n",
3640 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
3642 db_printf("\n\nList of active vnodes\n");
3643 TAILQ_FOREACH(vp, &mp->mnt_activevnodelist, v_actfreelist) {
3644 if (vp->v_type != VMARKER) {
3645 vn_printf(vp, "vnode ");
3650 db_printf("\n\nList of inactive vnodes\n");
3651 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3652 if (vp->v_type != VMARKER && (vp->v_iflag & VI_ACTIVE) == 0) {
3653 vn_printf(vp, "vnode ");
3662 * Fill in a struct xvfsconf based on a struct vfsconf.
3665 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
3667 struct xvfsconf xvfsp;
3669 bzero(&xvfsp, sizeof(xvfsp));
3670 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
3671 xvfsp.vfc_typenum = vfsp->vfc_typenum;
3672 xvfsp.vfc_refcount = vfsp->vfc_refcount;
3673 xvfsp.vfc_flags = vfsp->vfc_flags;
3675 * These are unused in userland, we keep them
3676 * to not break binary compatibility.
3678 xvfsp.vfc_vfsops = NULL;
3679 xvfsp.vfc_next = NULL;
3680 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3683 #ifdef COMPAT_FREEBSD32
3685 uint32_t vfc_vfsops;
3686 char vfc_name[MFSNAMELEN];
3687 int32_t vfc_typenum;
3688 int32_t vfc_refcount;
3694 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
3696 struct xvfsconf32 xvfsp;
3698 bzero(&xvfsp, sizeof(xvfsp));
3699 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
3700 xvfsp.vfc_typenum = vfsp->vfc_typenum;
3701 xvfsp.vfc_refcount = vfsp->vfc_refcount;
3702 xvfsp.vfc_flags = vfsp->vfc_flags;
3703 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3708 * Top level filesystem related information gathering.
3711 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
3713 struct vfsconf *vfsp;
3718 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3719 #ifdef COMPAT_FREEBSD32
3720 if (req->flags & SCTL_MASK32)
3721 error = vfsconf2x32(req, vfsp);
3724 error = vfsconf2x(req, vfsp);
3732 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
3733 CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
3734 "S,xvfsconf", "List of all configured filesystems");
3736 #ifndef BURN_BRIDGES
3737 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
3740 vfs_sysctl(SYSCTL_HANDLER_ARGS)
3742 int *name = (int *)arg1 - 1; /* XXX */
3743 u_int namelen = arg2 + 1; /* XXX */
3744 struct vfsconf *vfsp;
3746 log(LOG_WARNING, "userland calling deprecated sysctl, "
3747 "please rebuild world\n");
3749 #if 1 || defined(COMPAT_PRELITE2)
3750 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
3752 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
3756 case VFS_MAXTYPENUM:
3759 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
3762 return (ENOTDIR); /* overloaded */
3764 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3765 if (vfsp->vfc_typenum == name[2])
3770 return (EOPNOTSUPP);
3771 #ifdef COMPAT_FREEBSD32
3772 if (req->flags & SCTL_MASK32)
3773 return (vfsconf2x32(req, vfsp));
3776 return (vfsconf2x(req, vfsp));
3778 return (EOPNOTSUPP);
3781 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
3782 CTLFLAG_MPSAFE, vfs_sysctl,
3783 "Generic filesystem");
3785 #if 1 || defined(COMPAT_PRELITE2)
3788 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
3791 struct vfsconf *vfsp;
3792 struct ovfsconf ovfs;
3795 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3796 bzero(&ovfs, sizeof(ovfs));
3797 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
3798 strcpy(ovfs.vfc_name, vfsp->vfc_name);
3799 ovfs.vfc_index = vfsp->vfc_typenum;
3800 ovfs.vfc_refcount = vfsp->vfc_refcount;
3801 ovfs.vfc_flags = vfsp->vfc_flags;
3802 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
3812 #endif /* 1 || COMPAT_PRELITE2 */
3813 #endif /* !BURN_BRIDGES */
3815 #define KINFO_VNODESLOP 10
3818 * Dump vnode list (via sysctl).
3822 sysctl_vnode(SYSCTL_HANDLER_ARGS)
3830 * Stale numvnodes access is not fatal here.
3833 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
3835 /* Make an estimate */
3836 return (SYSCTL_OUT(req, 0, len));
3838 error = sysctl_wire_old_buffer(req, 0);
3841 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
3843 mtx_lock(&mountlist_mtx);
3844 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3845 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
3848 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3852 xvn[n].xv_size = sizeof *xvn;
3853 xvn[n].xv_vnode = vp;
3854 xvn[n].xv_id = 0; /* XXX compat */
3855 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
3857 XV_COPY(writecount);
3863 xvn[n].xv_flag = vp->v_vflag;
3865 switch (vp->v_type) {
3872 if (vp->v_rdev == NULL) {
3876 xvn[n].xv_dev = dev2udev(vp->v_rdev);
3879 xvn[n].xv_socket = vp->v_socket;
3882 xvn[n].xv_fifo = vp->v_fifoinfo;
3887 /* shouldn't happen? */
3895 mtx_lock(&mountlist_mtx);
3900 mtx_unlock(&mountlist_mtx);
3902 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
3907 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
3908 CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
3913 unmount_or_warn(struct mount *mp)
3917 error = dounmount(mp, MNT_FORCE, curthread);
3919 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
3923 printf("%d)\n", error);
3928 * Unmount all filesystems. The list is traversed in reverse order
3929 * of mounting to avoid dependencies.
3932 vfs_unmountall(void)
3934 struct mount *mp, *tmp;
3936 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
3939 * Since this only runs when rebooting, it is not interlocked.
3941 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
3945 * Forcibly unmounting "/dev" before "/" would prevent clean
3946 * unmount of the latter.
3948 if (mp == rootdevmp)
3951 unmount_or_warn(mp);
3954 if (rootdevmp != NULL)
3955 unmount_or_warn(rootdevmp);
3959 * perform msync on all vnodes under a mount point
3960 * the mount point must be locked.
3963 vfs_msync(struct mount *mp, int flags)
3965 struct vnode *vp, *mvp;
3966 struct vm_object *obj;
3968 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
3969 MNT_VNODE_FOREACH_ACTIVE(vp, mp, mvp) {
3971 if (obj != NULL && (obj->flags & OBJ_MIGHTBEDIRTY) != 0 &&
3972 (flags == MNT_WAIT || VOP_ISLOCKED(vp) == 0)) {
3974 LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
3976 if (vp->v_vflag & VV_NOSYNC) { /* unlinked */
3983 VM_OBJECT_WLOCK(obj);
3984 vm_object_page_clean(obj, 0, 0,
3986 OBJPC_SYNC : OBJPC_NOSYNC);
3987 VM_OBJECT_WUNLOCK(obj);
3997 destroy_vpollinfo_free(struct vpollinfo *vi)
4000 knlist_destroy(&vi->vpi_selinfo.si_note);
4001 mtx_destroy(&vi->vpi_lock);
4002 uma_zfree(vnodepoll_zone, vi);
4006 destroy_vpollinfo(struct vpollinfo *vi)
4009 knlist_clear(&vi->vpi_selinfo.si_note, 1);
4010 seldrain(&vi->vpi_selinfo);
4011 destroy_vpollinfo_free(vi);
4015 * Initialize per-vnode helper structure to hold poll-related state.
4018 v_addpollinfo(struct vnode *vp)
4020 struct vpollinfo *vi;
4022 if (vp->v_pollinfo != NULL)
4024 vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4025 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4026 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4027 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4029 if (vp->v_pollinfo != NULL) {
4031 destroy_vpollinfo_free(vi);
4034 vp->v_pollinfo = vi;
4039 * Record a process's interest in events which might happen to
4040 * a vnode. Because poll uses the historic select-style interface
4041 * internally, this routine serves as both the ``check for any
4042 * pending events'' and the ``record my interest in future events''
4043 * functions. (These are done together, while the lock is held,
4044 * to avoid race conditions.)
4047 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4051 mtx_lock(&vp->v_pollinfo->vpi_lock);
4052 if (vp->v_pollinfo->vpi_revents & events) {
4054 * This leaves events we are not interested
4055 * in available for the other process which
4056 * which presumably had requested them
4057 * (otherwise they would never have been
4060 events &= vp->v_pollinfo->vpi_revents;
4061 vp->v_pollinfo->vpi_revents &= ~events;
4063 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4066 vp->v_pollinfo->vpi_events |= events;
4067 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4068 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4073 * Routine to create and manage a filesystem syncer vnode.
4075 #define sync_close ((int (*)(struct vop_close_args *))nullop)
4076 static int sync_fsync(struct vop_fsync_args *);
4077 static int sync_inactive(struct vop_inactive_args *);
4078 static int sync_reclaim(struct vop_reclaim_args *);
4080 static struct vop_vector sync_vnodeops = {
4081 .vop_bypass = VOP_EOPNOTSUPP,
4082 .vop_close = sync_close, /* close */
4083 .vop_fsync = sync_fsync, /* fsync */
4084 .vop_inactive = sync_inactive, /* inactive */
4085 .vop_reclaim = sync_reclaim, /* reclaim */
4086 .vop_lock1 = vop_stdlock, /* lock */
4087 .vop_unlock = vop_stdunlock, /* unlock */
4088 .vop_islocked = vop_stdislocked, /* islocked */
4092 * Create a new filesystem syncer vnode for the specified mount point.
4095 vfs_allocate_syncvnode(struct mount *mp)
4099 static long start, incr, next;
4102 /* Allocate a new vnode */
4103 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
4105 panic("vfs_allocate_syncvnode: getnewvnode() failed");
4107 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4108 vp->v_vflag |= VV_FORCEINSMQ;
4109 error = insmntque(vp, mp);
4111 panic("vfs_allocate_syncvnode: insmntque() failed");
4112 vp->v_vflag &= ~VV_FORCEINSMQ;
4115 * Place the vnode onto the syncer worklist. We attempt to
4116 * scatter them about on the list so that they will go off
4117 * at evenly distributed times even if all the filesystems
4118 * are mounted at once.
4121 if (next == 0 || next > syncer_maxdelay) {
4125 start = syncer_maxdelay / 2;
4126 incr = syncer_maxdelay;
4132 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
4133 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
4134 mtx_lock(&sync_mtx);
4136 if (mp->mnt_syncer == NULL) {
4137 mp->mnt_syncer = vp;
4140 mtx_unlock(&sync_mtx);
4143 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4150 vfs_deallocate_syncvnode(struct mount *mp)
4154 mtx_lock(&sync_mtx);
4155 vp = mp->mnt_syncer;
4157 mp->mnt_syncer = NULL;
4158 mtx_unlock(&sync_mtx);
4164 * Do a lazy sync of the filesystem.
4167 sync_fsync(struct vop_fsync_args *ap)
4169 struct vnode *syncvp = ap->a_vp;
4170 struct mount *mp = syncvp->v_mount;
4175 * We only need to do something if this is a lazy evaluation.
4177 if (ap->a_waitfor != MNT_LAZY)
4181 * Move ourselves to the back of the sync list.
4183 bo = &syncvp->v_bufobj;
4185 vn_syncer_add_to_worklist(bo, syncdelay);
4189 * Walk the list of vnodes pushing all that are dirty and
4190 * not already on the sync list.
4192 if (vfs_busy(mp, MBF_NOWAIT) != 0)
4194 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
4198 save = curthread_pflags_set(TDP_SYNCIO);
4199 vfs_msync(mp, MNT_NOWAIT);
4200 error = VFS_SYNC(mp, MNT_LAZY);
4201 curthread_pflags_restore(save);
4202 vn_finished_write(mp);
4208 * The syncer vnode is no referenced.
4211 sync_inactive(struct vop_inactive_args *ap)
4219 * The syncer vnode is no longer needed and is being decommissioned.
4221 * Modifications to the worklist must be protected by sync_mtx.
4224 sync_reclaim(struct vop_reclaim_args *ap)
4226 struct vnode *vp = ap->a_vp;
4231 mtx_lock(&sync_mtx);
4232 if (vp->v_mount->mnt_syncer == vp)
4233 vp->v_mount->mnt_syncer = NULL;
4234 if (bo->bo_flag & BO_ONWORKLST) {
4235 LIST_REMOVE(bo, bo_synclist);
4236 syncer_worklist_len--;
4238 bo->bo_flag &= ~BO_ONWORKLST;
4240 mtx_unlock(&sync_mtx);
4247 * Check if vnode represents a disk device
4250 vn_isdisk(struct vnode *vp, int *errp)
4254 if (vp->v_type != VCHR) {
4260 if (vp->v_rdev == NULL)
4262 else if (vp->v_rdev->si_devsw == NULL)
4264 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
4270 return (error == 0);
4274 * Common filesystem object access control check routine. Accepts a
4275 * vnode's type, "mode", uid and gid, requested access mode, credentials,
4276 * and optional call-by-reference privused argument allowing vaccess()
4277 * to indicate to the caller whether privilege was used to satisfy the
4278 * request (obsoleted). Returns 0 on success, or an errno on failure.
4281 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
4282 accmode_t accmode, struct ucred *cred, int *privused)
4284 accmode_t dac_granted;
4285 accmode_t priv_granted;
4287 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
4288 ("invalid bit in accmode"));
4289 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
4290 ("VAPPEND without VWRITE"));
4293 * Look for a normal, non-privileged way to access the file/directory
4294 * as requested. If it exists, go with that.
4297 if (privused != NULL)
4302 /* Check the owner. */
4303 if (cred->cr_uid == file_uid) {
4304 dac_granted |= VADMIN;
4305 if (file_mode & S_IXUSR)
4306 dac_granted |= VEXEC;
4307 if (file_mode & S_IRUSR)
4308 dac_granted |= VREAD;
4309 if (file_mode & S_IWUSR)
4310 dac_granted |= (VWRITE | VAPPEND);
4312 if ((accmode & dac_granted) == accmode)
4318 /* Otherwise, check the groups (first match) */
4319 if (groupmember(file_gid, cred)) {
4320 if (file_mode & S_IXGRP)
4321 dac_granted |= VEXEC;
4322 if (file_mode & S_IRGRP)
4323 dac_granted |= VREAD;
4324 if (file_mode & S_IWGRP)
4325 dac_granted |= (VWRITE | VAPPEND);
4327 if ((accmode & dac_granted) == accmode)
4333 /* Otherwise, check everyone else. */
4334 if (file_mode & S_IXOTH)
4335 dac_granted |= VEXEC;
4336 if (file_mode & S_IROTH)
4337 dac_granted |= VREAD;
4338 if (file_mode & S_IWOTH)
4339 dac_granted |= (VWRITE | VAPPEND);
4340 if ((accmode & dac_granted) == accmode)
4345 * Build a privilege mask to determine if the set of privileges
4346 * satisfies the requirements when combined with the granted mask
4347 * from above. For each privilege, if the privilege is required,
4348 * bitwise or the request type onto the priv_granted mask.
4354 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
4355 * requests, instead of PRIV_VFS_EXEC.
4357 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4358 !priv_check_cred(cred, PRIV_VFS_LOOKUP, 0))
4359 priv_granted |= VEXEC;
4362 * Ensure that at least one execute bit is on. Otherwise,
4363 * a privileged user will always succeed, and we don't want
4364 * this to happen unless the file really is executable.
4366 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4367 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
4368 !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
4369 priv_granted |= VEXEC;
4372 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
4373 !priv_check_cred(cred, PRIV_VFS_READ, 0))
4374 priv_granted |= VREAD;
4376 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
4377 !priv_check_cred(cred, PRIV_VFS_WRITE, 0))
4378 priv_granted |= (VWRITE | VAPPEND);
4380 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
4381 !priv_check_cred(cred, PRIV_VFS_ADMIN, 0))
4382 priv_granted |= VADMIN;
4384 if ((accmode & (priv_granted | dac_granted)) == accmode) {
4385 /* XXX audit: privilege used */
4386 if (privused != NULL)
4391 return ((accmode & VADMIN) ? EPERM : EACCES);
4395 * Credential check based on process requesting service, and per-attribute
4399 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
4400 struct thread *td, accmode_t accmode)
4404 * Kernel-invoked always succeeds.
4410 * Do not allow privileged processes in jail to directly manipulate
4411 * system attributes.
4413 switch (attrnamespace) {
4414 case EXTATTR_NAMESPACE_SYSTEM:
4415 /* Potentially should be: return (EPERM); */
4416 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM, 0));
4417 case EXTATTR_NAMESPACE_USER:
4418 return (VOP_ACCESS(vp, accmode, cred, td));
4424 #ifdef DEBUG_VFS_LOCKS
4426 * This only exists to suppress warnings from unlocked specfs accesses. It is
4427 * no longer ok to have an unlocked VFS.
4429 #define IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL || \
4430 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
4432 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
4433 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
4434 "Drop into debugger on lock violation");
4436 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
4437 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
4438 0, "Check for interlock across VOPs");
4440 int vfs_badlock_print = 1; /* Print lock violations. */
4441 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
4442 0, "Print lock violations");
4444 int vfs_badlock_vnode = 1; /* Print vnode details on lock violations. */
4445 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
4446 0, "Print vnode details on lock violations");
4449 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
4450 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
4451 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
4455 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
4459 if (vfs_badlock_backtrace)
4462 if (vfs_badlock_vnode)
4463 vn_printf(vp, "vnode ");
4464 if (vfs_badlock_print)
4465 printf("%s: %p %s\n", str, (void *)vp, msg);
4466 if (vfs_badlock_ddb)
4467 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4471 assert_vi_locked(struct vnode *vp, const char *str)
4474 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
4475 vfs_badlock("interlock is not locked but should be", str, vp);
4479 assert_vi_unlocked(struct vnode *vp, const char *str)
4482 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
4483 vfs_badlock("interlock is locked but should not be", str, vp);
4487 assert_vop_locked(struct vnode *vp, const char *str)
4491 if (!IGNORE_LOCK(vp)) {
4492 locked = VOP_ISLOCKED(vp);
4493 if (locked == 0 || locked == LK_EXCLOTHER)
4494 vfs_badlock("is not locked but should be", str, vp);
4499 assert_vop_unlocked(struct vnode *vp, const char *str)
4502 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
4503 vfs_badlock("is locked but should not be", str, vp);
4507 assert_vop_elocked(struct vnode *vp, const char *str)
4510 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
4511 vfs_badlock("is not exclusive locked but should be", str, vp);
4516 assert_vop_elocked_other(struct vnode *vp, const char *str)
4519 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLOTHER)
4520 vfs_badlock("is not exclusive locked by another thread",
4525 assert_vop_slocked(struct vnode *vp, const char *str)
4528 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_SHARED)
4529 vfs_badlock("is not locked shared but should be", str, vp);
4532 #endif /* DEBUG_VFS_LOCKS */
4535 vop_rename_fail(struct vop_rename_args *ap)
4538 if (ap->a_tvp != NULL)
4540 if (ap->a_tdvp == ap->a_tvp)
4549 vop_rename_pre(void *ap)
4551 struct vop_rename_args *a = ap;
4553 #ifdef DEBUG_VFS_LOCKS
4555 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
4556 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
4557 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
4558 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
4560 /* Check the source (from). */
4561 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
4562 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
4563 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
4564 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
4565 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
4567 /* Check the target. */
4569 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
4570 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
4572 if (a->a_tdvp != a->a_fdvp)
4574 if (a->a_tvp != a->a_fvp)
4581 #ifdef DEBUG_VFS_LOCKS
4583 vop_strategy_pre(void *ap)
4585 struct vop_strategy_args *a;
4592 * Cluster ops lock their component buffers but not the IO container.
4594 if ((bp->b_flags & B_CLUSTER) != 0)
4597 if (panicstr == NULL && !BUF_ISLOCKED(bp)) {
4598 if (vfs_badlock_print)
4600 "VOP_STRATEGY: bp is not locked but should be\n");
4601 if (vfs_badlock_ddb)
4602 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4607 vop_lock_pre(void *ap)
4609 struct vop_lock1_args *a = ap;
4611 if ((a->a_flags & LK_INTERLOCK) == 0)
4612 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4614 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
4618 vop_lock_post(void *ap, int rc)
4620 struct vop_lock1_args *a = ap;
4622 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4623 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
4624 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
4628 vop_unlock_pre(void *ap)
4630 struct vop_unlock_args *a = ap;
4632 if (a->a_flags & LK_INTERLOCK)
4633 ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
4634 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
4638 vop_unlock_post(void *ap, int rc)
4640 struct vop_unlock_args *a = ap;
4642 if (a->a_flags & LK_INTERLOCK)
4643 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
4648 vop_create_post(void *ap, int rc)
4650 struct vop_create_args *a = ap;
4653 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4657 vop_deleteextattr_post(void *ap, int rc)
4659 struct vop_deleteextattr_args *a = ap;
4662 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4666 vop_link_post(void *ap, int rc)
4668 struct vop_link_args *a = ap;
4671 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
4672 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
4677 vop_mkdir_post(void *ap, int rc)
4679 struct vop_mkdir_args *a = ap;
4682 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4686 vop_mknod_post(void *ap, int rc)
4688 struct vop_mknod_args *a = ap;
4691 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4695 vop_reclaim_post(void *ap, int rc)
4697 struct vop_reclaim_args *a = ap;
4700 VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
4704 vop_remove_post(void *ap, int rc)
4706 struct vop_remove_args *a = ap;
4709 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4710 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4715 vop_rename_post(void *ap, int rc)
4717 struct vop_rename_args *a = ap;
4722 if (a->a_fdvp == a->a_tdvp) {
4723 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
4725 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
4726 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
4728 hint |= NOTE_EXTEND;
4729 if (a->a_fvp->v_type == VDIR)
4731 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
4733 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
4734 a->a_tvp->v_type == VDIR)
4736 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
4739 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
4741 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
4743 if (a->a_tdvp != a->a_fdvp)
4745 if (a->a_tvp != a->a_fvp)
4753 vop_rmdir_post(void *ap, int rc)
4755 struct vop_rmdir_args *a = ap;
4758 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4759 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4764 vop_setattr_post(void *ap, int rc)
4766 struct vop_setattr_args *a = ap;
4769 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4773 vop_setextattr_post(void *ap, int rc)
4775 struct vop_setextattr_args *a = ap;
4778 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4782 vop_symlink_post(void *ap, int rc)
4784 struct vop_symlink_args *a = ap;
4787 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4791 vop_open_post(void *ap, int rc)
4793 struct vop_open_args *a = ap;
4796 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
4800 vop_close_post(void *ap, int rc)
4802 struct vop_close_args *a = ap;
4804 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
4805 (a->a_vp->v_iflag & VI_DOOMED) == 0)) {
4806 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
4807 NOTE_CLOSE_WRITE : NOTE_CLOSE);
4812 vop_read_post(void *ap, int rc)
4814 struct vop_read_args *a = ap;
4817 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
4821 vop_readdir_post(void *ap, int rc)
4823 struct vop_readdir_args *a = ap;
4826 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
4829 static struct knlist fs_knlist;
4832 vfs_event_init(void *arg)
4834 knlist_init_mtx(&fs_knlist, NULL);
4836 /* XXX - correct order? */
4837 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
4840 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
4843 KNOTE_UNLOCKED(&fs_knlist, event);
4846 static int filt_fsattach(struct knote *kn);
4847 static void filt_fsdetach(struct knote *kn);
4848 static int filt_fsevent(struct knote *kn, long hint);
4850 struct filterops fs_filtops = {
4852 .f_attach = filt_fsattach,
4853 .f_detach = filt_fsdetach,
4854 .f_event = filt_fsevent
4858 filt_fsattach(struct knote *kn)
4861 kn->kn_flags |= EV_CLEAR;
4862 knlist_add(&fs_knlist, kn, 0);
4867 filt_fsdetach(struct knote *kn)
4870 knlist_remove(&fs_knlist, kn, 0);
4874 filt_fsevent(struct knote *kn, long hint)
4877 kn->kn_fflags |= hint;
4878 return (kn->kn_fflags != 0);
4882 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
4888 error = SYSCTL_IN(req, &vc, sizeof(vc));
4891 if (vc.vc_vers != VFS_CTL_VERS1)
4893 mp = vfs_getvfs(&vc.vc_fsid);
4896 /* ensure that a specific sysctl goes to the right filesystem. */
4897 if (strcmp(vc.vc_fstypename, "*") != 0 &&
4898 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
4902 VCTLTOREQ(&vc, req);
4903 error = VFS_SYSCTL(mp, vc.vc_op, req);
4908 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_WR,
4909 NULL, 0, sysctl_vfs_ctl, "",
4913 * Function to initialize a va_filerev field sensibly.
4914 * XXX: Wouldn't a random number make a lot more sense ??
4917 init_va_filerev(void)
4922 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
4925 static int filt_vfsread(struct knote *kn, long hint);
4926 static int filt_vfswrite(struct knote *kn, long hint);
4927 static int filt_vfsvnode(struct knote *kn, long hint);
4928 static void filt_vfsdetach(struct knote *kn);
4929 static struct filterops vfsread_filtops = {
4931 .f_detach = filt_vfsdetach,
4932 .f_event = filt_vfsread
4934 static struct filterops vfswrite_filtops = {
4936 .f_detach = filt_vfsdetach,
4937 .f_event = filt_vfswrite
4939 static struct filterops vfsvnode_filtops = {
4941 .f_detach = filt_vfsdetach,
4942 .f_event = filt_vfsvnode
4946 vfs_knllock(void *arg)
4948 struct vnode *vp = arg;
4950 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4954 vfs_knlunlock(void *arg)
4956 struct vnode *vp = arg;
4962 vfs_knl_assert_locked(void *arg)
4964 #ifdef DEBUG_VFS_LOCKS
4965 struct vnode *vp = arg;
4967 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
4972 vfs_knl_assert_unlocked(void *arg)
4974 #ifdef DEBUG_VFS_LOCKS
4975 struct vnode *vp = arg;
4977 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
4982 vfs_kqfilter(struct vop_kqfilter_args *ap)
4984 struct vnode *vp = ap->a_vp;
4985 struct knote *kn = ap->a_kn;
4988 switch (kn->kn_filter) {
4990 kn->kn_fop = &vfsread_filtops;
4993 kn->kn_fop = &vfswrite_filtops;
4996 kn->kn_fop = &vfsvnode_filtops;
5002 kn->kn_hook = (caddr_t)vp;
5005 if (vp->v_pollinfo == NULL)
5007 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5009 knlist_add(knl, kn, 0);
5015 * Detach knote from vnode
5018 filt_vfsdetach(struct knote *kn)
5020 struct vnode *vp = (struct vnode *)kn->kn_hook;
5022 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
5023 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
5029 filt_vfsread(struct knote *kn, long hint)
5031 struct vnode *vp = (struct vnode *)kn->kn_hook;
5036 * filesystem is gone, so set the EOF flag and schedule
5037 * the knote for deletion.
5039 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5041 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5046 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
5050 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
5051 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
5058 filt_vfswrite(struct knote *kn, long hint)
5060 struct vnode *vp = (struct vnode *)kn->kn_hook;
5065 * filesystem is gone, so set the EOF flag and schedule
5066 * the knote for deletion.
5068 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
5069 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5077 filt_vfsvnode(struct knote *kn, long hint)
5079 struct vnode *vp = (struct vnode *)kn->kn_hook;
5083 if (kn->kn_sfflags & hint)
5084 kn->kn_fflags |= hint;
5085 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5086 kn->kn_flags |= EV_EOF;
5090 res = (kn->kn_fflags != 0);
5096 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
5100 if (dp->d_reclen > ap->a_uio->uio_resid)
5101 return (ENAMETOOLONG);
5102 error = uiomove(dp, dp->d_reclen, ap->a_uio);
5104 if (ap->a_ncookies != NULL) {
5105 if (ap->a_cookies != NULL)
5106 free(ap->a_cookies, M_TEMP);
5107 ap->a_cookies = NULL;
5108 *ap->a_ncookies = 0;
5112 if (ap->a_ncookies == NULL)
5115 KASSERT(ap->a_cookies,
5116 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
5118 *ap->a_cookies = realloc(*ap->a_cookies,
5119 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
5120 (*ap->a_cookies)[*ap->a_ncookies] = off;
5121 *ap->a_ncookies += 1;
5126 * Mark for update the access time of the file if the filesystem
5127 * supports VOP_MARKATIME. This functionality is used by execve and
5128 * mmap, so we want to avoid the I/O implied by directly setting
5129 * va_atime for the sake of efficiency.
5132 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
5137 ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
5138 if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
5139 (void)VOP_MARKATIME(vp);
5143 * The purpose of this routine is to remove granularity from accmode_t,
5144 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
5145 * VADMIN and VAPPEND.
5147 * If it returns 0, the caller is supposed to continue with the usual
5148 * access checks using 'accmode' as modified by this routine. If it
5149 * returns nonzero value, the caller is supposed to return that value
5152 * Note that after this routine runs, accmode may be zero.
5155 vfs_unixify_accmode(accmode_t *accmode)
5158 * There is no way to specify explicit "deny" rule using
5159 * file mode or POSIX.1e ACLs.
5161 if (*accmode & VEXPLICIT_DENY) {
5167 * None of these can be translated into usual access bits.
5168 * Also, the common case for NFSv4 ACLs is to not contain
5169 * either of these bits. Caller should check for VWRITE
5170 * on the containing directory instead.
5172 if (*accmode & (VDELETE_CHILD | VDELETE))
5175 if (*accmode & VADMIN_PERMS) {
5176 *accmode &= ~VADMIN_PERMS;
5181 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
5182 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
5184 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
5190 * These are helper functions for filesystems to traverse all
5191 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
5193 * This interface replaces MNT_VNODE_FOREACH.
5196 MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
5199 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
5204 kern_yield(PRI_USER);
5206 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5207 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
5208 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
5209 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
5210 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
5213 if ((vp->v_iflag & VI_DOOMED) != 0) {
5220 __mnt_vnode_markerfree_all(mvp, mp);
5221 /* MNT_IUNLOCK(mp); -- done in above function */
5222 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
5225 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5226 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5232 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
5236 *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
5239 (*mvp)->v_mount = mp;
5240 (*mvp)->v_type = VMARKER;
5242 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
5243 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
5244 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
5247 if ((vp->v_iflag & VI_DOOMED) != 0) {
5256 free(*mvp, M_VNODE_MARKER);
5260 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5266 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
5274 mtx_assert(MNT_MTX(mp), MA_OWNED);
5276 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5277 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5280 free(*mvp, M_VNODE_MARKER);
5285 * These are helper functions for filesystems to traverse their
5286 * active vnodes. See MNT_VNODE_FOREACH_ACTIVE() in sys/mount.h
5289 mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
5292 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5297 free(*mvp, M_VNODE_MARKER);
5301 static struct vnode *
5302 mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
5304 struct vnode *vp, *nvp;
5306 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
5307 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5309 vp = TAILQ_NEXT(*mvp, v_actfreelist);
5310 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
5311 while (vp != NULL) {
5312 if (vp->v_type == VMARKER) {
5313 vp = TAILQ_NEXT(vp, v_actfreelist);
5316 if (!VI_TRYLOCK(vp)) {
5317 if (mp_ncpus == 1 || should_yield()) {
5318 TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
5319 mtx_unlock(&vnode_free_list_mtx);
5321 mtx_lock(&vnode_free_list_mtx);
5326 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
5327 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
5328 ("alien vnode on the active list %p %p", vp, mp));
5329 if (vp->v_mount == mp && (vp->v_iflag & VI_DOOMED) == 0)
5331 nvp = TAILQ_NEXT(vp, v_actfreelist);
5336 /* Check if we are done */
5338 mtx_unlock(&vnode_free_list_mtx);
5339 mnt_vnode_markerfree_active(mvp, mp);
5342 TAILQ_INSERT_AFTER(&mp->mnt_activevnodelist, vp, *mvp, v_actfreelist);
5343 mtx_unlock(&vnode_free_list_mtx);
5344 ASSERT_VI_LOCKED(vp, "active iter");
5345 KASSERT((vp->v_iflag & VI_ACTIVE) != 0, ("Non-active vp %p", vp));
5350 __mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
5354 kern_yield(PRI_USER);
5355 mtx_lock(&vnode_free_list_mtx);
5356 return (mnt_vnode_next_active(mvp, mp));
5360 __mnt_vnode_first_active(struct vnode **mvp, struct mount *mp)
5364 *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
5368 (*mvp)->v_type = VMARKER;
5369 (*mvp)->v_mount = mp;
5371 mtx_lock(&vnode_free_list_mtx);
5372 vp = TAILQ_FIRST(&mp->mnt_activevnodelist);
5374 mtx_unlock(&vnode_free_list_mtx);
5375 mnt_vnode_markerfree_active(mvp, mp);
5378 TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
5379 return (mnt_vnode_next_active(mvp, mp));
5383 __mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
5389 mtx_lock(&vnode_free_list_mtx);
5390 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
5391 mtx_unlock(&vnode_free_list_mtx);
5392 mnt_vnode_markerfree_active(mvp, mp);