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/dirent.h>
55 #include <sys/event.h>
56 #include <sys/eventhandler.h>
57 #include <sys/extattr.h>
59 #include <sys/fcntl.h>
62 #include <sys/kernel.h>
63 #include <sys/kthread.h>
64 #include <sys/lockf.h>
65 #include <sys/malloc.h>
66 #include <sys/mount.h>
67 #include <sys/namei.h>
69 #include <sys/reboot.h>
70 #include <sys/rwlock.h>
71 #include <sys/sched.h>
72 #include <sys/sleepqueue.h>
75 #include <sys/sysctl.h>
76 #include <sys/syslog.h>
77 #include <sys/vmmeter.h>
78 #include <sys/vnode.h>
79 #include <sys/watchdog.h>
81 #include <machine/stdarg.h>
83 #include <security/mac/mac_framework.h>
86 #include <vm/vm_object.h>
87 #include <vm/vm_extern.h>
89 #include <vm/vm_map.h>
90 #include <vm/vm_page.h>
91 #include <vm/vm_kern.h>
98 static void delmntque(struct vnode *vp);
99 static int flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
100 int slpflag, int slptimeo);
101 static void syncer_shutdown(void *arg, int howto);
102 static int vtryrecycle(struct vnode *vp);
103 static void v_incr_usecount(struct vnode *);
104 static void v_decr_usecount(struct vnode *);
105 static void v_decr_useonly(struct vnode *);
106 static void v_upgrade_usecount(struct vnode *);
107 static void vnlru_free(int);
108 static void vgonel(struct vnode *);
109 static void vfs_knllock(void *arg);
110 static void vfs_knlunlock(void *arg);
111 static void vfs_knl_assert_locked(void *arg);
112 static void vfs_knl_assert_unlocked(void *arg);
113 static void destroy_vpollinfo(struct vpollinfo *vi);
116 * Number of vnodes in existence. Increased whenever getnewvnode()
117 * allocates a new vnode, decreased in vdropl() for VI_DOOMED vnode.
119 static unsigned long numvnodes;
121 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
122 "Number of vnodes in existence");
125 * Conversion tables for conversion from vnode types to inode formats
128 enum vtype iftovt_tab[16] = {
129 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
130 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
132 int vttoif_tab[10] = {
133 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
134 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
138 * List of vnodes that are ready for recycling.
140 static TAILQ_HEAD(freelst, vnode) vnode_free_list;
143 * Free vnode target. Free vnodes may simply be files which have been stat'd
144 * but not read. This is somewhat common, and a small cache of such files
145 * should be kept to avoid recreation costs.
147 static u_long wantfreevnodes;
148 SYSCTL_ULONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW, &wantfreevnodes, 0, "");
149 /* Number of vnodes in the free list. */
150 static u_long freevnodes;
151 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD, &freevnodes, 0,
152 "Number of vnodes in the free list");
154 static int vlru_allow_cache_src;
155 SYSCTL_INT(_vfs, OID_AUTO, vlru_allow_cache_src, CTLFLAG_RW,
156 &vlru_allow_cache_src, 0, "Allow vlru to reclaim source vnode");
159 * Various variables used for debugging the new implementation of
161 * XXX these are probably of (very) limited utility now.
163 static int reassignbufcalls;
164 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0,
165 "Number of calls to reassignbuf");
168 * Cache for the mount type id assigned to NFS. This is used for
169 * special checks in nfs/nfs_nqlease.c and vm/vnode_pager.c.
171 int nfs_mount_type = -1;
173 /* To keep more than one thread at a time from running vfs_getnewfsid */
174 static struct mtx mntid_mtx;
177 * Lock for any access to the following:
182 static struct mtx vnode_free_list_mtx;
184 /* Publicly exported FS */
185 struct nfs_public nfs_pub;
187 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
188 static uma_zone_t vnode_zone;
189 static uma_zone_t vnodepoll_zone;
192 * The workitem queue.
194 * It is useful to delay writes of file data and filesystem metadata
195 * for tens of seconds so that quickly created and deleted files need
196 * not waste disk bandwidth being created and removed. To realize this,
197 * we append vnodes to a "workitem" queue. When running with a soft
198 * updates implementation, most pending metadata dependencies should
199 * not wait for more than a few seconds. Thus, mounted on block devices
200 * are delayed only about a half the time that file data is delayed.
201 * Similarly, directory updates are more critical, so are only delayed
202 * about a third the time that file data is delayed. Thus, there are
203 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
204 * one each second (driven off the filesystem syncer process). The
205 * syncer_delayno variable indicates the next queue that is to be processed.
206 * Items that need to be processed soon are placed in this queue:
208 * syncer_workitem_pending[syncer_delayno]
210 * A delay of fifteen seconds is done by placing the request fifteen
211 * entries later in the queue:
213 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
216 static int syncer_delayno;
217 static long syncer_mask;
218 LIST_HEAD(synclist, bufobj);
219 static struct synclist *syncer_workitem_pending;
221 * The sync_mtx protects:
226 * syncer_workitem_pending
227 * syncer_worklist_len
230 static struct mtx sync_mtx;
231 static struct cv sync_wakeup;
233 #define SYNCER_MAXDELAY 32
234 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
235 static int syncdelay = 30; /* max time to delay syncing data */
236 static int filedelay = 30; /* time to delay syncing files */
237 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
238 "Time to delay syncing files (in seconds)");
239 static int dirdelay = 29; /* time to delay syncing directories */
240 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
241 "Time to delay syncing directories (in seconds)");
242 static int metadelay = 28; /* time to delay syncing metadata */
243 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
244 "Time to delay syncing metadata (in seconds)");
245 static int rushjob; /* number of slots to run ASAP */
246 static int stat_rush_requests; /* number of times I/O speeded up */
247 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
248 "Number of times I/O speeded up (rush requests)");
251 * When shutting down the syncer, run it at four times normal speed.
253 #define SYNCER_SHUTDOWN_SPEEDUP 4
254 static int sync_vnode_count;
255 static int syncer_worklist_len;
256 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
260 * Number of vnodes we want to exist at any one time. This is mostly used
261 * to size hash tables in vnode-related code. It is normally not used in
262 * getnewvnode(), as wantfreevnodes is normally nonzero.)
264 * XXX desiredvnodes is historical cruft and should not exist.
267 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
268 &desiredvnodes, 0, "Maximum number of vnodes");
269 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
270 &wantfreevnodes, 0, "Minimum number of vnodes (legacy)");
271 static int vnlru_nowhere;
272 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
273 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
276 * Macros to control when a vnode is freed and recycled. All require
277 * the vnode interlock.
279 #define VCANRECYCLE(vp) (((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
280 #define VSHOULDFREE(vp) (!((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
281 #define VSHOULDBUSY(vp) (((vp)->v_iflag & VI_FREE) && (vp)->v_holdcnt)
283 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
287 * Initialize the vnode management data structures.
289 * Reevaluate the following cap on the number of vnodes after the physical
290 * memory size exceeds 512GB. In the limit, as the physical memory size
291 * grows, the ratio of physical pages to vnodes approaches sixteen to one.
293 #ifndef MAXVNODES_MAX
294 #define MAXVNODES_MAX (512 * (1024 * 1024 * 1024 / (int)PAGE_SIZE / 16))
297 vntblinit(void *dummy __unused)
300 int physvnodes, virtvnodes;
303 * Desiredvnodes is a function of the physical memory size and the
304 * kernel's heap size. Generally speaking, it scales with the
305 * physical memory size. The ratio of desiredvnodes to physical pages
306 * is one to four until desiredvnodes exceeds 98,304. Thereafter, the
307 * marginal ratio of desiredvnodes to physical pages is one to
308 * sixteen. However, desiredvnodes is limited by the kernel's heap
309 * size. The memory required by desiredvnodes vnodes and vm objects
310 * may not exceed one seventh of the kernel's heap size.
312 physvnodes = maxproc + cnt.v_page_count / 16 + 3 * min(98304 * 4,
313 cnt.v_page_count) / 16;
314 virtvnodes = vm_kmem_size / (7 * (sizeof(struct vm_object) +
315 sizeof(struct vnode)));
316 desiredvnodes = min(physvnodes, virtvnodes);
317 if (desiredvnodes > MAXVNODES_MAX) {
319 printf("Reducing kern.maxvnodes %d -> %d\n",
320 desiredvnodes, MAXVNODES_MAX);
321 desiredvnodes = MAXVNODES_MAX;
323 wantfreevnodes = desiredvnodes / 4;
324 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
325 TAILQ_INIT(&vnode_free_list);
326 mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
327 vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
328 NULL, NULL, UMA_ALIGN_PTR, 0);
329 vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
330 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
332 * Initialize the filesystem syncer.
334 syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
336 syncer_maxdelay = syncer_mask + 1;
337 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
338 cv_init(&sync_wakeup, "syncer");
339 for (i = 1; i <= sizeof(struct vnode); i <<= 1)
343 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
347 * Mark a mount point as busy. Used to synchronize access and to delay
348 * unmounting. Eventually, mountlist_mtx is not released on failure.
350 * vfs_busy() is a custom lock, it can block the caller.
351 * vfs_busy() only sleeps if the unmount is active on the mount point.
352 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
353 * vnode belonging to mp.
355 * Lookup uses vfs_busy() to traverse mount points.
357 * / vnode lock A / vnode lock (/var) D
358 * /var vnode lock B /log vnode lock(/var/log) E
359 * vfs_busy lock C vfs_busy lock F
361 * Within each file system, the lock order is C->A->B and F->D->E.
363 * When traversing across mounts, the system follows that lock order:
369 * The lookup() process for namei("/var") illustrates the process:
370 * VOP_LOOKUP() obtains B while A is held
371 * vfs_busy() obtains a shared lock on F while A and B are held
372 * vput() releases lock on B
373 * vput() releases lock on A
374 * VFS_ROOT() obtains lock on D while shared lock on F is held
375 * vfs_unbusy() releases shared lock on F
376 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
377 * Attempt to lock A (instead of vp_crossmp) while D is held would
378 * violate the global order, causing deadlocks.
380 * dounmount() locks B while F is drained.
383 vfs_busy(struct mount *mp, int flags)
386 MPASS((flags & ~MBF_MASK) == 0);
387 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
392 * If mount point is currenly being unmounted, sleep until the
393 * mount point fate is decided. If thread doing the unmounting fails,
394 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
395 * that this mount point has survived the unmount attempt and vfs_busy
396 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
397 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
398 * about to be really destroyed. vfs_busy needs to release its
399 * reference on the mount point in this case and return with ENOENT,
400 * telling the caller that mount mount it tried to busy is no longer
403 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
404 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
407 CTR1(KTR_VFS, "%s: failed busying before sleeping",
411 if (flags & MBF_MNTLSTLOCK)
412 mtx_unlock(&mountlist_mtx);
413 mp->mnt_kern_flag |= MNTK_MWAIT;
414 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
415 if (flags & MBF_MNTLSTLOCK)
416 mtx_lock(&mountlist_mtx);
419 if (flags & MBF_MNTLSTLOCK)
420 mtx_unlock(&mountlist_mtx);
427 * Free a busy filesystem.
430 vfs_unbusy(struct mount *mp)
433 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
436 KASSERT(mp->mnt_lockref > 0, ("negative mnt_lockref"));
438 if (mp->mnt_lockref == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
439 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
440 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
441 mp->mnt_kern_flag &= ~MNTK_DRAINING;
442 wakeup(&mp->mnt_lockref);
448 * Lookup a mount point by filesystem identifier.
451 vfs_getvfs(fsid_t *fsid)
455 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
456 mtx_lock(&mountlist_mtx);
457 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
458 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
459 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
461 mtx_unlock(&mountlist_mtx);
465 mtx_unlock(&mountlist_mtx);
466 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
467 return ((struct mount *) 0);
471 * Lookup a mount point by filesystem identifier, busying it before
475 vfs_busyfs(fsid_t *fsid)
480 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
481 mtx_lock(&mountlist_mtx);
482 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
483 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
484 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
485 error = vfs_busy(mp, MBF_MNTLSTLOCK);
487 mtx_unlock(&mountlist_mtx);
493 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
494 mtx_unlock(&mountlist_mtx);
495 return ((struct mount *) 0);
499 * Check if a user can access privileged mount options.
502 vfs_suser(struct mount *mp, struct thread *td)
507 * If the thread is jailed, but this is not a jail-friendly file
508 * system, deny immediately.
510 if (!(mp->mnt_vfc->vfc_flags & VFCF_JAIL) && jailed(td->td_ucred))
514 * If the file system was mounted outside the jail of the calling
515 * thread, deny immediately.
517 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
521 * If file system supports delegated administration, we don't check
522 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
523 * by the file system itself.
524 * If this is not the user that did original mount, we check for
525 * the PRIV_VFS_MOUNT_OWNER privilege.
527 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
528 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
529 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
536 * Get a new unique fsid. Try to make its val[0] unique, since this value
537 * will be used to create fake device numbers for stat(). Also try (but
538 * not so hard) make its val[0] unique mod 2^16, since some emulators only
539 * support 16-bit device numbers. We end up with unique val[0]'s for the
540 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
542 * Keep in mind that several mounts may be running in parallel. Starting
543 * the search one past where the previous search terminated is both a
544 * micro-optimization and a defense against returning the same fsid to
548 vfs_getnewfsid(struct mount *mp)
550 static uint16_t mntid_base;
555 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
556 mtx_lock(&mntid_mtx);
557 mtype = mp->mnt_vfc->vfc_typenum;
558 tfsid.val[1] = mtype;
559 mtype = (mtype & 0xFF) << 24;
561 tfsid.val[0] = makedev(255,
562 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
564 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
568 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
569 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
570 mtx_unlock(&mntid_mtx);
574 * Knob to control the precision of file timestamps:
576 * 0 = seconds only; nanoseconds zeroed.
577 * 1 = seconds and nanoseconds, accurate within 1/HZ.
578 * 2 = seconds and nanoseconds, truncated to microseconds.
579 * >=3 = seconds and nanoseconds, maximum precision.
581 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
583 static int timestamp_precision = TSP_SEC;
584 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
585 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
586 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to ms, "
587 "3+: sec + ns (max. precision))");
590 * Get a current timestamp.
593 vfs_timestamp(struct timespec *tsp)
597 switch (timestamp_precision) {
599 tsp->tv_sec = time_second;
607 TIMEVAL_TO_TIMESPEC(&tv, tsp);
617 * Set vnode attributes to VNOVAL
620 vattr_null(struct vattr *vap)
624 vap->va_size = VNOVAL;
625 vap->va_bytes = VNOVAL;
626 vap->va_mode = VNOVAL;
627 vap->va_nlink = VNOVAL;
628 vap->va_uid = VNOVAL;
629 vap->va_gid = VNOVAL;
630 vap->va_fsid = VNOVAL;
631 vap->va_fileid = VNOVAL;
632 vap->va_blocksize = VNOVAL;
633 vap->va_rdev = VNOVAL;
634 vap->va_atime.tv_sec = VNOVAL;
635 vap->va_atime.tv_nsec = VNOVAL;
636 vap->va_mtime.tv_sec = VNOVAL;
637 vap->va_mtime.tv_nsec = VNOVAL;
638 vap->va_ctime.tv_sec = VNOVAL;
639 vap->va_ctime.tv_nsec = VNOVAL;
640 vap->va_birthtime.tv_sec = VNOVAL;
641 vap->va_birthtime.tv_nsec = VNOVAL;
642 vap->va_flags = VNOVAL;
643 vap->va_gen = VNOVAL;
648 * This routine is called when we have too many vnodes. It attempts
649 * to free <count> vnodes and will potentially free vnodes that still
650 * have VM backing store (VM backing store is typically the cause
651 * of a vnode blowout so we want to do this). Therefore, this operation
652 * is not considered cheap.
654 * A number of conditions may prevent a vnode from being reclaimed.
655 * the buffer cache may have references on the vnode, a directory
656 * vnode may still have references due to the namei cache representing
657 * underlying files, or the vnode may be in active use. It is not
658 * desireable to reuse such vnodes. These conditions may cause the
659 * number of vnodes to reach some minimum value regardless of what
660 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
663 vlrureclaim(struct mount *mp)
672 * Calculate the trigger point, don't allow user
673 * screwups to blow us up. This prevents us from
674 * recycling vnodes with lots of resident pages. We
675 * aren't trying to free memory, we are trying to
678 usevnodes = desiredvnodes;
681 trigger = cnt.v_page_count * 2 / usevnodes;
683 vn_start_write(NULL, &mp, V_WAIT);
685 count = mp->mnt_nvnodelistsize / 10 + 1;
687 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
688 while (vp != NULL && vp->v_type == VMARKER)
689 vp = TAILQ_NEXT(vp, v_nmntvnodes);
692 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
693 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
698 * If it's been deconstructed already, it's still
699 * referenced, or it exceeds the trigger, skip it.
701 if (vp->v_usecount ||
702 (!vlru_allow_cache_src &&
703 !LIST_EMPTY(&(vp)->v_cache_src)) ||
704 (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
705 vp->v_object->resident_page_count > trigger)) {
711 if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT)) {
713 goto next_iter_mntunlocked;
717 * v_usecount may have been bumped after VOP_LOCK() dropped
718 * the vnode interlock and before it was locked again.
720 * It is not necessary to recheck VI_DOOMED because it can
721 * only be set by another thread that holds both the vnode
722 * lock and vnode interlock. If another thread has the
723 * vnode lock before we get to VOP_LOCK() and obtains the
724 * vnode interlock after VOP_LOCK() drops the vnode
725 * interlock, the other thread will be unable to drop the
726 * vnode lock before our VOP_LOCK() call fails.
728 if (vp->v_usecount ||
729 (!vlru_allow_cache_src &&
730 !LIST_EMPTY(&(vp)->v_cache_src)) ||
731 (vp->v_object != NULL &&
732 vp->v_object->resident_page_count > trigger)) {
733 VOP_UNLOCK(vp, LK_INTERLOCK);
734 goto next_iter_mntunlocked;
736 KASSERT((vp->v_iflag & VI_DOOMED) == 0,
737 ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
742 next_iter_mntunlocked:
751 kern_yield(PRI_USER);
756 vn_finished_write(mp);
761 * Attempt to keep the free list at wantfreevnodes length.
764 vnlru_free(int count)
768 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
769 for (; count > 0; count--) {
770 vp = TAILQ_FIRST(&vnode_free_list);
772 * The list can be modified while the free_list_mtx
773 * has been dropped and vp could be NULL here.
777 VNASSERT(vp->v_op != NULL, vp,
778 ("vnlru_free: vnode already reclaimed."));
779 KASSERT((vp->v_iflag & VI_FREE) != 0,
780 ("Removing vnode not on freelist"));
781 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
782 ("Mangling active vnode"));
783 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
785 * Don't recycle if we can't get the interlock.
787 if (!VI_TRYLOCK(vp)) {
788 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_actfreelist);
791 VNASSERT(VCANRECYCLE(vp), vp,
792 ("vp inconsistent on freelist"));
794 vp->v_iflag &= ~VI_FREE;
796 mtx_unlock(&vnode_free_list_mtx);
800 * If the recycled succeeded this vdrop will actually free
801 * the vnode. If not it will simply place it back on
805 mtx_lock(&vnode_free_list_mtx);
809 * Attempt to recycle vnodes in a context that is always safe to block.
810 * Calling vlrurecycle() from the bowels of filesystem code has some
811 * interesting deadlock problems.
813 static struct proc *vnlruproc;
814 static int vnlruproc_sig;
819 struct mount *mp, *nmp;
821 struct proc *p = vnlruproc;
823 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, p,
827 kproc_suspend_check(p);
828 mtx_lock(&vnode_free_list_mtx);
829 if (freevnodes > wantfreevnodes)
830 vnlru_free(freevnodes - wantfreevnodes);
831 if (numvnodes <= desiredvnodes * 9 / 10) {
833 wakeup(&vnlruproc_sig);
834 msleep(vnlruproc, &vnode_free_list_mtx,
835 PVFS|PDROP, "vlruwt", hz);
838 mtx_unlock(&vnode_free_list_mtx);
840 mtx_lock(&mountlist_mtx);
841 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
842 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK)) {
843 nmp = TAILQ_NEXT(mp, mnt_list);
846 done += vlrureclaim(mp);
847 mtx_lock(&mountlist_mtx);
848 nmp = TAILQ_NEXT(mp, mnt_list);
851 mtx_unlock(&mountlist_mtx);
854 /* These messages are temporary debugging aids */
855 if (vnlru_nowhere < 5)
856 printf("vnlru process getting nowhere..\n");
857 else if (vnlru_nowhere == 5)
858 printf("vnlru process messages stopped.\n");
861 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
863 kern_yield(PRI_USER);
867 static struct kproc_desc vnlru_kp = {
872 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
876 * Routines having to do with the management of the vnode table.
880 * Try to recycle a freed vnode. We abort if anyone picks up a reference
881 * before we actually vgone(). This function must be called with the vnode
882 * held to prevent the vnode from being returned to the free list midway
886 vtryrecycle(struct vnode *vp)
890 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
891 VNASSERT(vp->v_holdcnt, vp,
892 ("vtryrecycle: Recycling vp %p without a reference.", vp));
894 * This vnode may found and locked via some other list, if so we
895 * can't recycle it yet.
897 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
899 "%s: impossible to recycle, vp %p lock is already held",
901 return (EWOULDBLOCK);
904 * Don't recycle if its filesystem is being suspended.
906 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
909 "%s: impossible to recycle, cannot start the write for %p",
914 * If we got this far, we need to acquire the interlock and see if
915 * anyone picked up this vnode from another list. If not, we will
916 * mark it with DOOMED via vgonel() so that anyone who does find it
920 if (vp->v_usecount) {
921 VOP_UNLOCK(vp, LK_INTERLOCK);
922 vn_finished_write(vnmp);
924 "%s: impossible to recycle, %p is already referenced",
928 if ((vp->v_iflag & VI_DOOMED) == 0)
930 VOP_UNLOCK(vp, LK_INTERLOCK);
931 vn_finished_write(vnmp);
936 * Wait for available vnodes.
939 getnewvnode_wait(int suspended)
942 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
943 if (numvnodes > desiredvnodes) {
946 * File system is beeing suspended, we cannot risk a
947 * deadlock here, so allocate new vnode anyway.
949 if (freevnodes > wantfreevnodes)
950 vnlru_free(freevnodes - wantfreevnodes);
953 if (vnlruproc_sig == 0) {
954 vnlruproc_sig = 1; /* avoid unnecessary wakeups */
957 msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
960 return (numvnodes > desiredvnodes ? ENFILE : 0);
964 getnewvnode_reserve(u_int count)
969 mtx_lock(&vnode_free_list_mtx);
971 if (getnewvnode_wait(0) == 0) {
977 mtx_unlock(&vnode_free_list_mtx);
981 getnewvnode_drop_reserve(void)
986 mtx_lock(&vnode_free_list_mtx);
987 KASSERT(numvnodes >= td->td_vp_reserv, ("reserve too large"));
988 numvnodes -= td->td_vp_reserv;
989 mtx_unlock(&vnode_free_list_mtx);
990 td->td_vp_reserv = 0;
994 * Return the next vnode from the free list.
997 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1005 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1008 if (td->td_vp_reserv > 0) {
1009 td->td_vp_reserv -= 1;
1012 mtx_lock(&vnode_free_list_mtx);
1014 * Lend our context to reclaim vnodes if they've exceeded the max.
1016 if (freevnodes > wantfreevnodes)
1018 error = getnewvnode_wait(mp != NULL && (mp->mnt_kern_flag &
1020 #if 0 /* XXX Not all VFS_VGET/ffs_vget callers check returns. */
1022 mtx_unlock(&vnode_free_list_mtx);
1027 mtx_unlock(&vnode_free_list_mtx);
1029 vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK|M_ZERO);
1033 vp->v_vnlock = &vp->v_lock;
1034 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
1036 * By default, don't allow shared locks unless filesystems
1039 lockinit(vp->v_vnlock, PVFS, tag, VLKTIMEOUT, LK_NOSHARE);
1041 * Initialize bufobj.
1044 bo->__bo_vnode = vp;
1045 mtx_init(BO_MTX(bo), "bufobj interlock", NULL, MTX_DEF);
1046 bo->bo_ops = &buf_ops_bio;
1047 bo->bo_private = vp;
1048 TAILQ_INIT(&bo->bo_clean.bv_hd);
1049 TAILQ_INIT(&bo->bo_dirty.bv_hd);
1051 * Initialize namecache.
1053 LIST_INIT(&vp->v_cache_src);
1054 TAILQ_INIT(&vp->v_cache_dst);
1056 * Finalize various vnode identity bits.
1061 v_incr_usecount(vp);
1065 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1066 mac_vnode_associate_singlelabel(mp, vp);
1067 else if (mp == NULL && vops != &dead_vnodeops)
1068 printf("NULL mp in getnewvnode()\n");
1071 bo->bo_bsize = mp->mnt_stat.f_iosize;
1072 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1073 vp->v_vflag |= VV_NOKNOTE;
1075 rangelock_init(&vp->v_rl);
1078 * For the filesystems which do not use vfs_hash_insert(),
1079 * still initialize v_hash to have vfs_hash_index() useful.
1080 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1083 vp->v_hash = (uintptr_t)vp >> vnsz2log;
1090 * Delete from old mount point vnode list, if on one.
1093 delmntque(struct vnode *vp)
1103 KASSERT(mp->mnt_activevnodelistsize <= mp->mnt_nvnodelistsize,
1104 ("Active vnode list size %d > Vnode list size %d",
1105 mp->mnt_activevnodelistsize, mp->mnt_nvnodelistsize));
1106 active = vp->v_iflag & VI_ACTIVE;
1107 vp->v_iflag &= ~VI_ACTIVE;
1109 mtx_lock(&vnode_free_list_mtx);
1110 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp, v_actfreelist);
1111 mp->mnt_activevnodelistsize--;
1112 mtx_unlock(&vnode_free_list_mtx);
1116 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1117 ("bad mount point vnode list size"));
1118 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1119 mp->mnt_nvnodelistsize--;
1125 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1129 vp->v_op = &dead_vnodeops;
1135 * Insert into list of vnodes for the new mount point, if available.
1138 insmntque1(struct vnode *vp, struct mount *mp,
1139 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1142 KASSERT(vp->v_mount == NULL,
1143 ("insmntque: vnode already on per mount vnode list"));
1144 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1145 ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1148 * We acquire the vnode interlock early to ensure that the
1149 * vnode cannot be recycled by another process releasing a
1150 * holdcnt on it before we get it on both the vnode list
1151 * and the active vnode list. The mount mutex protects only
1152 * manipulation of the vnode list and the vnode freelist
1153 * mutex protects only manipulation of the active vnode list.
1154 * Hence the need to hold the vnode interlock throughout.
1158 if (((mp->mnt_kern_flag & MNTK_NOINSMNTQ) != 0 &&
1159 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1160 mp->mnt_nvnodelistsize == 0)) &&
1161 (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1170 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1171 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1172 ("neg mount point vnode list size"));
1173 mp->mnt_nvnodelistsize++;
1174 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1175 ("Activating already active vnode"));
1176 vp->v_iflag |= VI_ACTIVE;
1177 mtx_lock(&vnode_free_list_mtx);
1178 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
1179 mp->mnt_activevnodelistsize++;
1180 mtx_unlock(&vnode_free_list_mtx);
1187 insmntque(struct vnode *vp, struct mount *mp)
1190 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1194 * Flush out and invalidate all buffers associated with a bufobj
1195 * Called with the underlying object locked.
1198 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1203 if (flags & V_SAVE) {
1204 error = bufobj_wwait(bo, slpflag, slptimeo);
1209 if (bo->bo_dirty.bv_cnt > 0) {
1211 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1214 * XXX We could save a lock/unlock if this was only
1215 * enabled under INVARIANTS
1218 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1219 panic("vinvalbuf: dirty bufs");
1223 * If you alter this loop please notice that interlock is dropped and
1224 * reacquired in flushbuflist. Special care is needed to ensure that
1225 * no race conditions occur from this.
1228 error = flushbuflist(&bo->bo_clean,
1229 flags, bo, slpflag, slptimeo);
1230 if (error == 0 && !(flags & V_CLEANONLY))
1231 error = flushbuflist(&bo->bo_dirty,
1232 flags, bo, slpflag, slptimeo);
1233 if (error != 0 && error != EAGAIN) {
1237 } while (error != 0);
1240 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1241 * have write I/O in-progress but if there is a VM object then the
1242 * VM object can also have read-I/O in-progress.
1245 bufobj_wwait(bo, 0, 0);
1247 if (bo->bo_object != NULL) {
1248 VM_OBJECT_WLOCK(bo->bo_object);
1249 vm_object_pip_wait(bo->bo_object, "bovlbx");
1250 VM_OBJECT_WUNLOCK(bo->bo_object);
1253 } while (bo->bo_numoutput > 0);
1257 * Destroy the copy in the VM cache, too.
1259 if (bo->bo_object != NULL &&
1260 (flags & (V_ALT | V_NORMAL | V_CLEANONLY)) == 0) {
1261 VM_OBJECT_WLOCK(bo->bo_object);
1262 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1263 OBJPR_CLEANONLY : 0);
1264 VM_OBJECT_WUNLOCK(bo->bo_object);
1269 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY)) == 0 &&
1270 (bo->bo_dirty.bv_cnt > 0 || bo->bo_clean.bv_cnt > 0))
1271 panic("vinvalbuf: flush failed");
1278 * Flush out and invalidate all buffers associated with a vnode.
1279 * Called with the underlying object locked.
1282 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1285 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1286 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1287 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1291 * Flush out buffers on the specified list.
1295 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1298 struct buf *bp, *nbp;
1303 ASSERT_BO_LOCKED(bo);
1306 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1307 if (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA)) ||
1308 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0)) {
1314 lblkno = nbp->b_lblkno;
1315 xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
1318 error = BUF_TIMELOCK(bp,
1319 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_MTX(bo),
1320 "flushbuf", slpflag, slptimeo);
1323 return (error != ENOLCK ? error : EAGAIN);
1325 KASSERT(bp->b_bufobj == bo,
1326 ("bp %p wrong b_bufobj %p should be %p",
1327 bp, bp->b_bufobj, bo));
1328 if (bp->b_bufobj != bo) { /* XXX: necessary ? */
1334 * XXX Since there are no node locks for NFS, I
1335 * believe there is a slight chance that a delayed
1336 * write will occur while sleeping just above, so
1339 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1344 bp->b_flags |= B_ASYNC;
1347 return (EAGAIN); /* XXX: why not loop ? */
1352 bp->b_flags |= (B_INVAL | B_RELBUF);
1353 bp->b_flags &= ~B_ASYNC;
1357 (nbp->b_bufobj != bo ||
1358 nbp->b_lblkno != lblkno ||
1359 (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN)) != xflags))
1360 break; /* nbp invalid */
1366 * Truncate a file's buffer and pages to a specified length. This
1367 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
1371 vtruncbuf(struct vnode *vp, struct ucred *cred, off_t length, int blksize)
1373 struct buf *bp, *nbp;
1378 CTR5(KTR_VFS, "%s: vp %p with cred %p and block %d:%ju", __func__,
1379 vp, cred, blksize, (uintmax_t)length);
1382 * Round up to the *next* lbn.
1384 trunclbn = (length + blksize - 1) / blksize;
1386 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
1393 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
1394 if (bp->b_lblkno < trunclbn)
1397 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1398 BO_MTX(bo)) == ENOLCK)
1404 bp->b_flags |= (B_INVAL | B_RELBUF);
1405 bp->b_flags &= ~B_ASYNC;
1411 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
1412 (nbp->b_vp != vp) ||
1413 (nbp->b_flags & B_DELWRI))) {
1419 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1420 if (bp->b_lblkno < trunclbn)
1423 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1424 BO_MTX(bo)) == ENOLCK)
1429 bp->b_flags |= (B_INVAL | B_RELBUF);
1430 bp->b_flags &= ~B_ASYNC;
1436 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
1437 (nbp->b_vp != vp) ||
1438 (nbp->b_flags & B_DELWRI) == 0)) {
1447 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1448 if (bp->b_lblkno > 0)
1451 * Since we hold the vnode lock this should only
1452 * fail if we're racing with the buf daemon.
1455 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1456 BO_MTX(bo)) == ENOLCK) {
1459 VNASSERT((bp->b_flags & B_DELWRI), vp,
1460 ("buf(%p) on dirty queue without DELWRI", bp));
1471 bufobj_wwait(bo, 0, 0);
1473 vnode_pager_setsize(vp, length);
1479 * buf_splay() - splay tree core for the clean/dirty list of buffers in
1482 * NOTE: We have to deal with the special case of a background bitmap
1483 * buffer, a situation where two buffers will have the same logical
1484 * block offset. We want (1) only the foreground buffer to be accessed
1485 * in a lookup and (2) must differentiate between the foreground and
1486 * background buffer in the splay tree algorithm because the splay
1487 * tree cannot normally handle multiple entities with the same 'index'.
1488 * We accomplish this by adding differentiating flags to the splay tree's
1493 buf_splay(daddr_t lblkno, b_xflags_t xflags, struct buf *root)
1496 struct buf *lefttreemax, *righttreemin, *y;
1500 lefttreemax = righttreemin = &dummy;
1502 if (lblkno < root->b_lblkno) {
1503 if ((y = root->b_left) == NULL)
1505 if (lblkno < y->b_lblkno) {
1507 root->b_left = y->b_right;
1510 if ((y = root->b_left) == NULL)
1513 /* Link into the new root's right tree. */
1514 righttreemin->b_left = root;
1515 righttreemin = root;
1516 } else if (lblkno > root->b_lblkno) {
1517 if ((y = root->b_right) == NULL)
1519 if (lblkno > y->b_lblkno) {
1521 root->b_right = y->b_left;
1524 if ((y = root->b_right) == NULL)
1527 /* Link into the new root's left tree. */
1528 lefttreemax->b_right = root;
1535 /* Assemble the new root. */
1536 lefttreemax->b_right = root->b_left;
1537 righttreemin->b_left = root->b_right;
1538 root->b_left = dummy.b_right;
1539 root->b_right = dummy.b_left;
1544 buf_vlist_remove(struct buf *bp)
1549 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1550 ASSERT_BO_LOCKED(bp->b_bufobj);
1551 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
1552 (BX_VNDIRTY|BX_VNCLEAN),
1553 ("buf_vlist_remove: Buf %p is on two lists", bp));
1554 if (bp->b_xflags & BX_VNDIRTY)
1555 bv = &bp->b_bufobj->bo_dirty;
1557 bv = &bp->b_bufobj->bo_clean;
1558 if (bp != bv->bv_root) {
1559 root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1560 KASSERT(root == bp, ("splay lookup failed in remove"));
1562 if (bp->b_left == NULL) {
1565 root = buf_splay(bp->b_lblkno, bp->b_xflags, bp->b_left);
1566 root->b_right = bp->b_right;
1569 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
1571 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1575 * Add the buffer to the sorted clean or dirty block list using a
1576 * splay tree algorithm.
1578 * NOTE: xflags is passed as a constant, optimizing this inline function!
1581 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
1586 ASSERT_BO_LOCKED(bo);
1587 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
1588 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
1589 bp->b_xflags |= xflags;
1590 if (xflags & BX_VNDIRTY)
1595 root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1599 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
1600 } else if (bp->b_lblkno < root->b_lblkno) {
1601 bp->b_left = root->b_left;
1603 root->b_left = NULL;
1604 TAILQ_INSERT_BEFORE(root, bp, b_bobufs);
1606 bp->b_right = root->b_right;
1608 root->b_right = NULL;
1609 TAILQ_INSERT_AFTER(&bv->bv_hd, root, bp, b_bobufs);
1616 * Lookup a buffer using the splay tree. Note that we specifically avoid
1617 * shadow buffers used in background bitmap writes.
1619 * This code isn't quite efficient as it could be because we are maintaining
1620 * two sorted lists and do not know which list the block resides in.
1622 * During a "make buildworld" the desired buffer is found at one of
1623 * the roots more than 60% of the time. Thus, checking both roots
1624 * before performing either splay eliminates unnecessary splays on the
1625 * first tree splayed.
1628 gbincore(struct bufobj *bo, daddr_t lblkno)
1632 ASSERT_BO_LOCKED(bo);
1633 if ((bp = bo->bo_clean.bv_root) != NULL && bp->b_lblkno == lblkno)
1635 if ((bp = bo->bo_dirty.bv_root) != NULL && bp->b_lblkno == lblkno)
1637 if ((bp = bo->bo_clean.bv_root) != NULL) {
1638 bo->bo_clean.bv_root = bp = buf_splay(lblkno, 0, bp);
1639 if (bp->b_lblkno == lblkno)
1642 if ((bp = bo->bo_dirty.bv_root) != NULL) {
1643 bo->bo_dirty.bv_root = bp = buf_splay(lblkno, 0, bp);
1644 if (bp->b_lblkno == lblkno)
1651 * Associate a buffer with a vnode.
1654 bgetvp(struct vnode *vp, struct buf *bp)
1659 ASSERT_BO_LOCKED(bo);
1660 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
1662 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
1663 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
1664 ("bgetvp: bp already attached! %p", bp));
1670 * Insert onto list for new vnode.
1672 buf_vlist_add(bp, bo, BX_VNCLEAN);
1676 * Disassociate a buffer from a vnode.
1679 brelvp(struct buf *bp)
1684 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1685 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1688 * Delete from old vnode list, if on one.
1690 vp = bp->b_vp; /* XXX */
1693 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1694 buf_vlist_remove(bp);
1696 panic("brelvp: Buffer %p not on queue.", bp);
1697 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1698 bo->bo_flag &= ~BO_ONWORKLST;
1699 mtx_lock(&sync_mtx);
1700 LIST_REMOVE(bo, bo_synclist);
1701 syncer_worklist_len--;
1702 mtx_unlock(&sync_mtx);
1705 bp->b_bufobj = NULL;
1711 * Add an item to the syncer work queue.
1714 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
1718 ASSERT_BO_LOCKED(bo);
1720 mtx_lock(&sync_mtx);
1721 if (bo->bo_flag & BO_ONWORKLST)
1722 LIST_REMOVE(bo, bo_synclist);
1724 bo->bo_flag |= BO_ONWORKLST;
1725 syncer_worklist_len++;
1728 if (delay > syncer_maxdelay - 2)
1729 delay = syncer_maxdelay - 2;
1730 slot = (syncer_delayno + delay) & syncer_mask;
1732 LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
1733 mtx_unlock(&sync_mtx);
1737 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
1741 mtx_lock(&sync_mtx);
1742 len = syncer_worklist_len - sync_vnode_count;
1743 mtx_unlock(&sync_mtx);
1744 error = SYSCTL_OUT(req, &len, sizeof(len));
1748 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
1749 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
1751 static struct proc *updateproc;
1752 static void sched_sync(void);
1753 static struct kproc_desc up_kp = {
1758 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
1761 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
1766 *bo = LIST_FIRST(slp);
1769 vp = (*bo)->__bo_vnode; /* XXX */
1770 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
1773 * We use vhold in case the vnode does not
1774 * successfully sync. vhold prevents the vnode from
1775 * going away when we unlock the sync_mtx so that
1776 * we can acquire the vnode interlock.
1779 mtx_unlock(&sync_mtx);
1781 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1783 mtx_lock(&sync_mtx);
1784 return (*bo == LIST_FIRST(slp));
1786 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1787 (void) VOP_FSYNC(vp, MNT_LAZY, td);
1789 vn_finished_write(mp);
1791 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
1793 * Put us back on the worklist. The worklist
1794 * routine will remove us from our current
1795 * position and then add us back in at a later
1798 vn_syncer_add_to_worklist(*bo, syncdelay);
1802 mtx_lock(&sync_mtx);
1807 * System filesystem synchronizer daemon.
1812 struct synclist *next, *slp;
1815 struct thread *td = curthread;
1817 int net_worklist_len;
1818 int syncer_final_iter;
1823 syncer_final_iter = 0;
1825 syncer_state = SYNCER_RUNNING;
1826 starttime = time_uptime;
1827 td->td_pflags |= TDP_NORUNNINGBUF;
1829 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
1832 mtx_lock(&sync_mtx);
1834 if (syncer_state == SYNCER_FINAL_DELAY &&
1835 syncer_final_iter == 0) {
1836 mtx_unlock(&sync_mtx);
1837 kproc_suspend_check(td->td_proc);
1838 mtx_lock(&sync_mtx);
1840 net_worklist_len = syncer_worklist_len - sync_vnode_count;
1841 if (syncer_state != SYNCER_RUNNING &&
1842 starttime != time_uptime) {
1844 printf("\nSyncing disks, vnodes remaining...");
1847 printf("%d ", net_worklist_len);
1849 starttime = time_uptime;
1852 * Push files whose dirty time has expired. Be careful
1853 * of interrupt race on slp queue.
1855 * Skip over empty worklist slots when shutting down.
1858 slp = &syncer_workitem_pending[syncer_delayno];
1859 syncer_delayno += 1;
1860 if (syncer_delayno == syncer_maxdelay)
1862 next = &syncer_workitem_pending[syncer_delayno];
1864 * If the worklist has wrapped since the
1865 * it was emptied of all but syncer vnodes,
1866 * switch to the FINAL_DELAY state and run
1867 * for one more second.
1869 if (syncer_state == SYNCER_SHUTTING_DOWN &&
1870 net_worklist_len == 0 &&
1871 last_work_seen == syncer_delayno) {
1872 syncer_state = SYNCER_FINAL_DELAY;
1873 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
1875 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
1876 syncer_worklist_len > 0);
1879 * Keep track of the last time there was anything
1880 * on the worklist other than syncer vnodes.
1881 * Return to the SHUTTING_DOWN state if any
1884 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
1885 last_work_seen = syncer_delayno;
1886 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
1887 syncer_state = SYNCER_SHUTTING_DOWN;
1888 while (!LIST_EMPTY(slp)) {
1889 error = sync_vnode(slp, &bo, td);
1891 LIST_REMOVE(bo, bo_synclist);
1892 LIST_INSERT_HEAD(next, bo, bo_synclist);
1896 if (first_printf == 0)
1897 wdog_kern_pat(WD_LASTVAL);
1900 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
1901 syncer_final_iter--;
1903 * The variable rushjob allows the kernel to speed up the
1904 * processing of the filesystem syncer process. A rushjob
1905 * value of N tells the filesystem syncer to process the next
1906 * N seconds worth of work on its queue ASAP. Currently rushjob
1907 * is used by the soft update code to speed up the filesystem
1908 * syncer process when the incore state is getting so far
1909 * ahead of the disk that the kernel memory pool is being
1910 * threatened with exhaustion.
1917 * Just sleep for a short period of time between
1918 * iterations when shutting down to allow some I/O
1921 * If it has taken us less than a second to process the
1922 * current work, then wait. Otherwise start right over
1923 * again. We can still lose time if any single round
1924 * takes more than two seconds, but it does not really
1925 * matter as we are just trying to generally pace the
1926 * filesystem activity.
1928 if (syncer_state != SYNCER_RUNNING ||
1929 time_uptime == starttime) {
1931 sched_prio(td, PPAUSE);
1934 if (syncer_state != SYNCER_RUNNING)
1935 cv_timedwait(&sync_wakeup, &sync_mtx,
1936 hz / SYNCER_SHUTDOWN_SPEEDUP);
1937 else if (time_uptime == starttime)
1938 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
1943 * Request the syncer daemon to speed up its work.
1944 * We never push it to speed up more than half of its
1945 * normal turn time, otherwise it could take over the cpu.
1948 speedup_syncer(void)
1952 mtx_lock(&sync_mtx);
1953 if (rushjob < syncdelay / 2) {
1955 stat_rush_requests += 1;
1958 mtx_unlock(&sync_mtx);
1959 cv_broadcast(&sync_wakeup);
1964 * Tell the syncer to speed up its work and run though its work
1965 * list several times, then tell it to shut down.
1968 syncer_shutdown(void *arg, int howto)
1971 if (howto & RB_NOSYNC)
1973 mtx_lock(&sync_mtx);
1974 syncer_state = SYNCER_SHUTTING_DOWN;
1976 mtx_unlock(&sync_mtx);
1977 cv_broadcast(&sync_wakeup);
1978 kproc_shutdown(arg, howto);
1982 * Reassign a buffer from one vnode to another.
1983 * Used to assign file specific control information
1984 * (indirect blocks) to the vnode to which they belong.
1987 reassignbuf(struct buf *bp)
2000 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2001 bp, bp->b_vp, bp->b_flags);
2003 * B_PAGING flagged buffers cannot be reassigned because their vp
2004 * is not fully linked in.
2006 if (bp->b_flags & B_PAGING)
2007 panic("cannot reassign paging buffer");
2010 * Delete from old vnode list, if on one.
2013 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2014 buf_vlist_remove(bp);
2016 panic("reassignbuf: Buffer %p not on queue.", bp);
2018 * If dirty, put on list of dirty buffers; otherwise insert onto list
2021 if (bp->b_flags & B_DELWRI) {
2022 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2023 switch (vp->v_type) {
2033 vn_syncer_add_to_worklist(bo, delay);
2035 buf_vlist_add(bp, bo, BX_VNDIRTY);
2037 buf_vlist_add(bp, bo, BX_VNCLEAN);
2039 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2040 mtx_lock(&sync_mtx);
2041 LIST_REMOVE(bo, bo_synclist);
2042 syncer_worklist_len--;
2043 mtx_unlock(&sync_mtx);
2044 bo->bo_flag &= ~BO_ONWORKLST;
2049 bp = TAILQ_FIRST(&bv->bv_hd);
2050 KASSERT(bp == NULL || bp->b_bufobj == bo,
2051 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2052 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2053 KASSERT(bp == NULL || bp->b_bufobj == bo,
2054 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2056 bp = TAILQ_FIRST(&bv->bv_hd);
2057 KASSERT(bp == NULL || bp->b_bufobj == bo,
2058 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2059 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2060 KASSERT(bp == NULL || bp->b_bufobj == bo,
2061 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2067 * Increment the use and hold counts on the vnode, taking care to reference
2068 * the driver's usecount if this is a chardev. The vholdl() will remove
2069 * the vnode from the free list if it is presently free. Requires the
2070 * vnode interlock and returns with it held.
2073 v_incr_usecount(struct vnode *vp)
2076 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2078 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2080 vp->v_rdev->si_usecount++;
2087 * Turn a holdcnt into a use+holdcnt such that only one call to
2088 * v_decr_usecount is needed.
2091 v_upgrade_usecount(struct vnode *vp)
2094 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2096 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2098 vp->v_rdev->si_usecount++;
2104 * Decrement the vnode use and hold count along with the driver's usecount
2105 * if this is a chardev. The vdropl() below releases the vnode interlock
2106 * as it may free the vnode.
2109 v_decr_usecount(struct vnode *vp)
2112 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2113 VNASSERT(vp->v_usecount > 0, vp,
2114 ("v_decr_usecount: negative usecount"));
2115 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2117 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2119 vp->v_rdev->si_usecount--;
2126 * Decrement only the use count and driver use count. This is intended to
2127 * be paired with a follow on vdropl() to release the remaining hold count.
2128 * In this way we may vgone() a vnode with a 0 usecount without risk of
2129 * having it end up on a free list because the hold count is kept above 0.
2132 v_decr_useonly(struct vnode *vp)
2135 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2136 VNASSERT(vp->v_usecount > 0, vp,
2137 ("v_decr_useonly: negative usecount"));
2138 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2140 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2142 vp->v_rdev->si_usecount--;
2148 * Grab a particular vnode from the free list, increment its
2149 * reference count and lock it. VI_DOOMED is set if the vnode
2150 * is being destroyed. Only callers who specify LK_RETRY will
2151 * see doomed vnodes. If inactive processing was delayed in
2152 * vput try to do it here.
2155 vget(struct vnode *vp, int flags, struct thread *td)
2160 VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2161 ("vget: invalid lock operation"));
2162 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2164 if ((flags & LK_INTERLOCK) == 0)
2167 if ((error = vn_lock(vp, flags | LK_INTERLOCK)) != 0) {
2169 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2173 if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0)
2174 panic("vget: vn_lock failed to return ENOENT\n");
2176 /* Upgrade our holdcnt to a usecount. */
2177 v_upgrade_usecount(vp);
2179 * We don't guarantee that any particular close will
2180 * trigger inactive processing so just make a best effort
2181 * here at preventing a reference to a removed file. If
2182 * we don't succeed no harm is done.
2184 if (vp->v_iflag & VI_OWEINACT) {
2185 if (VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2186 (flags & LK_NOWAIT) == 0)
2188 vp->v_iflag &= ~VI_OWEINACT;
2195 * Increase the reference count of a vnode.
2198 vref(struct vnode *vp)
2201 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2203 v_incr_usecount(vp);
2208 * Return reference count of a vnode.
2210 * The results of this call are only guaranteed when some mechanism other
2211 * than the VI lock is used to stop other processes from gaining references
2212 * to the vnode. This may be the case if the caller holds the only reference.
2213 * This is also useful when stale data is acceptable as race conditions may
2214 * be accounted for by some other means.
2217 vrefcnt(struct vnode *vp)
2222 usecnt = vp->v_usecount;
2228 #define VPUTX_VRELE 1
2229 #define VPUTX_VPUT 2
2230 #define VPUTX_VUNREF 3
2233 vputx(struct vnode *vp, int func)
2237 KASSERT(vp != NULL, ("vputx: null vp"));
2238 if (func == VPUTX_VUNREF)
2239 ASSERT_VOP_LOCKED(vp, "vunref");
2240 else if (func == VPUTX_VPUT)
2241 ASSERT_VOP_LOCKED(vp, "vput");
2243 KASSERT(func == VPUTX_VRELE, ("vputx: wrong func"));
2244 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2247 /* Skip this v_writecount check if we're going to panic below. */
2248 VNASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1, vp,
2249 ("vputx: missed vn_close"));
2252 if (vp->v_usecount > 1 || ((vp->v_iflag & VI_DOINGINACT) &&
2253 vp->v_usecount == 1)) {
2254 if (func == VPUTX_VPUT)
2256 v_decr_usecount(vp);
2260 if (vp->v_usecount != 1) {
2261 vprint("vputx: negative ref count", vp);
2262 panic("vputx: negative ref cnt");
2264 CTR2(KTR_VFS, "%s: return vnode %p to the freelist", __func__, vp);
2266 * We want to hold the vnode until the inactive finishes to
2267 * prevent vgone() races. We drop the use count here and the
2268 * hold count below when we're done.
2272 * We must call VOP_INACTIVE with the node locked. Mark
2273 * as VI_DOINGINACT to avoid recursion.
2275 vp->v_iflag |= VI_OWEINACT;
2278 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
2282 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2283 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
2289 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
2293 if (vp->v_usecount > 0)
2294 vp->v_iflag &= ~VI_OWEINACT;
2296 if (vp->v_iflag & VI_OWEINACT)
2297 vinactive(vp, curthread);
2298 if (func != VPUTX_VUNREF)
2305 * Vnode put/release.
2306 * If count drops to zero, call inactive routine and return to freelist.
2309 vrele(struct vnode *vp)
2312 vputx(vp, VPUTX_VRELE);
2316 * Release an already locked vnode. This give the same effects as
2317 * unlock+vrele(), but takes less time and avoids releasing and
2318 * re-aquiring the lock (as vrele() acquires the lock internally.)
2321 vput(struct vnode *vp)
2324 vputx(vp, VPUTX_VPUT);
2328 * Release an exclusively locked vnode. Do not unlock the vnode lock.
2331 vunref(struct vnode *vp)
2334 vputx(vp, VPUTX_VUNREF);
2338 * Somebody doesn't want the vnode recycled.
2341 vhold(struct vnode *vp)
2350 * Increase the hold count and activate if this is the first reference.
2353 vholdl(struct vnode *vp)
2357 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2359 if (!VSHOULDBUSY(vp))
2361 ASSERT_VI_LOCKED(vp, "vholdl");
2362 VNASSERT((vp->v_iflag & VI_FREE) != 0, vp, ("vnode not free"));
2363 VNASSERT(vp->v_op != NULL, vp, ("vholdl: vnode already reclaimed."));
2365 * Remove a vnode from the free list, mark it as in use,
2366 * and put it on the active list.
2368 mtx_lock(&vnode_free_list_mtx);
2369 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
2371 vp->v_iflag &= ~(VI_FREE|VI_AGE);
2372 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
2373 ("Activating already active vnode"));
2374 vp->v_iflag |= VI_ACTIVE;
2376 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
2377 mp->mnt_activevnodelistsize++;
2378 mtx_unlock(&vnode_free_list_mtx);
2382 * Note that there is one less who cares about this vnode.
2383 * vdrop() is the opposite of vhold().
2386 vdrop(struct vnode *vp)
2394 * Drop the hold count of the vnode. If this is the last reference to
2395 * the vnode we place it on the free list unless it has been vgone'd
2396 * (marked VI_DOOMED) in which case we will free it.
2399 vdropl(struct vnode *vp)
2405 ASSERT_VI_LOCKED(vp, "vdropl");
2406 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2407 if (vp->v_holdcnt <= 0)
2408 panic("vdrop: holdcnt %d", vp->v_holdcnt);
2410 if (vp->v_holdcnt > 0) {
2414 if ((vp->v_iflag & VI_DOOMED) == 0) {
2416 * Mark a vnode as free: remove it from its active list
2417 * and put it up for recycling on the freelist.
2419 VNASSERT(vp->v_op != NULL, vp,
2420 ("vdropl: vnode already reclaimed."));
2421 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2422 ("vnode already free"));
2423 VNASSERT(VSHOULDFREE(vp), vp,
2424 ("vdropl: freeing when we shouldn't"));
2425 active = vp->v_iflag & VI_ACTIVE;
2426 vp->v_iflag &= ~VI_ACTIVE;
2428 mtx_lock(&vnode_free_list_mtx);
2430 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp,
2432 mp->mnt_activevnodelistsize--;
2434 if (vp->v_iflag & VI_AGE) {
2435 TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_actfreelist);
2437 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_actfreelist);
2440 vp->v_iflag &= ~VI_AGE;
2441 vp->v_iflag |= VI_FREE;
2442 mtx_unlock(&vnode_free_list_mtx);
2447 * The vnode has been marked for destruction, so free it.
2449 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
2450 mtx_lock(&vnode_free_list_mtx);
2452 mtx_unlock(&vnode_free_list_mtx);
2454 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2455 ("cleaned vnode still on the free list."));
2456 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
2457 VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
2458 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
2459 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
2460 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
2461 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
2462 VNASSERT(bo->bo_clean.bv_root == NULL, vp, ("cleanblkroot not NULL"));
2463 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
2464 VNASSERT(bo->bo_dirty.bv_root == NULL, vp, ("dirtyblkroot not NULL"));
2465 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
2466 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
2467 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
2470 mac_vnode_destroy(vp);
2472 if (vp->v_pollinfo != NULL)
2473 destroy_vpollinfo(vp->v_pollinfo);
2475 /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
2478 rangelock_destroy(&vp->v_rl);
2479 lockdestroy(vp->v_vnlock);
2480 mtx_destroy(&vp->v_interlock);
2481 mtx_destroy(BO_MTX(bo));
2482 uma_zfree(vnode_zone, vp);
2486 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
2487 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
2488 * OWEINACT tracks whether a vnode missed a call to inactive due to a
2489 * failed lock upgrade.
2492 vinactive(struct vnode *vp, struct thread *td)
2494 struct vm_object *obj;
2496 ASSERT_VOP_ELOCKED(vp, "vinactive");
2497 ASSERT_VI_LOCKED(vp, "vinactive");
2498 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
2499 ("vinactive: recursed on VI_DOINGINACT"));
2500 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2501 vp->v_iflag |= VI_DOINGINACT;
2502 vp->v_iflag &= ~VI_OWEINACT;
2505 * Before moving off the active list, we must be sure that any
2506 * modified pages are on the vnode's dirty list since these will
2507 * no longer be checked once the vnode is on the inactive list.
2508 * Because the vnode vm object keeps a hold reference on the vnode
2509 * if there is at least one resident non-cached page, the vnode
2510 * cannot leave the active list without the page cleanup done.
2513 if (obj != NULL && (obj->flags & OBJ_MIGHTBEDIRTY) != 0) {
2514 VM_OBJECT_WLOCK(obj);
2515 vm_object_page_clean(obj, 0, 0, OBJPC_NOSYNC);
2516 VM_OBJECT_WUNLOCK(obj);
2518 VOP_INACTIVE(vp, td);
2520 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
2521 ("vinactive: lost VI_DOINGINACT"));
2522 vp->v_iflag &= ~VI_DOINGINACT;
2526 * Remove any vnodes in the vnode table belonging to mount point mp.
2528 * If FORCECLOSE is not specified, there should not be any active ones,
2529 * return error if any are found (nb: this is a user error, not a
2530 * system error). If FORCECLOSE is specified, detach any active vnodes
2533 * If WRITECLOSE is set, only flush out regular file vnodes open for
2536 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
2538 * `rootrefs' specifies the base reference count for the root vnode
2539 * of this filesystem. The root vnode is considered busy if its
2540 * v_usecount exceeds this value. On a successful return, vflush(, td)
2541 * will call vrele() on the root vnode exactly rootrefs times.
2542 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
2546 static int busyprt = 0; /* print out busy vnodes */
2547 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
2551 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
2553 struct vnode *vp, *mvp, *rootvp = NULL;
2555 int busy = 0, error;
2557 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
2560 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
2561 ("vflush: bad args"));
2563 * Get the filesystem root vnode. We can vput() it
2564 * immediately, since with rootrefs > 0, it won't go away.
2566 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
2567 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
2574 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
2576 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
2579 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
2583 * Skip over a vnodes marked VV_SYSTEM.
2585 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
2591 * If WRITECLOSE is set, flush out unlinked but still open
2592 * files (even if open only for reading) and regular file
2593 * vnodes open for writing.
2595 if (flags & WRITECLOSE) {
2596 if (vp->v_object != NULL) {
2597 VM_OBJECT_WLOCK(vp->v_object);
2598 vm_object_page_clean(vp->v_object, 0, 0, 0);
2599 VM_OBJECT_WUNLOCK(vp->v_object);
2601 error = VOP_FSYNC(vp, MNT_WAIT, td);
2605 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
2608 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
2611 if ((vp->v_type == VNON ||
2612 (error == 0 && vattr.va_nlink > 0)) &&
2613 (vp->v_writecount == 0 || vp->v_type != VREG)) {
2621 * With v_usecount == 0, all we need to do is clear out the
2622 * vnode data structures and we are done.
2624 * If FORCECLOSE is set, forcibly close the vnode.
2626 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
2627 VNASSERT(vp->v_usecount == 0 ||
2628 (vp->v_type != VCHR && vp->v_type != VBLK), vp,
2629 ("device VNODE %p is FORCECLOSED", vp));
2635 vprint("vflush: busy vnode", vp);
2641 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
2643 * If just the root vnode is busy, and if its refcount
2644 * is equal to `rootrefs', then go ahead and kill it.
2647 KASSERT(busy > 0, ("vflush: not busy"));
2648 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
2649 ("vflush: usecount %d < rootrefs %d",
2650 rootvp->v_usecount, rootrefs));
2651 if (busy == 1 && rootvp->v_usecount == rootrefs) {
2652 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
2654 VOP_UNLOCK(rootvp, 0);
2660 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
2664 for (; rootrefs > 0; rootrefs--)
2670 * Recycle an unused vnode to the front of the free list.
2673 vrecycle(struct vnode *vp)
2677 ASSERT_VOP_ELOCKED(vp, "vrecycle");
2678 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2681 if (vp->v_usecount == 0) {
2690 * Eliminate all activity associated with a vnode
2691 * in preparation for reuse.
2694 vgone(struct vnode *vp)
2702 vgonel_reclaim_lowervp_vfs(struct mount *mp __unused,
2703 struct vnode *lowervp __unused)
2708 * Notify upper mounts about reclaimed vnode.
2711 vgonel_reclaim_lowervp(struct vnode *vp)
2713 static struct vfsops vgonel_vfsops = {
2714 .vfs_reclaim_lowervp = vgonel_reclaim_lowervp_vfs
2716 struct mount *mp, *ump, *mmp;
2723 if (TAILQ_EMPTY(&mp->mnt_uppers))
2726 mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
2727 mmp->mnt_op = &vgonel_vfsops;
2728 mmp->mnt_kern_flag |= MNTK_MARKER;
2730 mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
2731 for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
2732 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
2733 ump = TAILQ_NEXT(ump, mnt_upper_link);
2736 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
2738 VFS_RECLAIM_LOWERVP(ump, vp);
2740 ump = TAILQ_NEXT(mmp, mnt_upper_link);
2741 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
2744 mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
2745 if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
2746 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
2747 wakeup(&mp->mnt_uppers);
2754 * vgone, with the vp interlock held.
2757 vgonel(struct vnode *vp)
2764 ASSERT_VOP_ELOCKED(vp, "vgonel");
2765 ASSERT_VI_LOCKED(vp, "vgonel");
2766 VNASSERT(vp->v_holdcnt, vp,
2767 ("vgonel: vp %p has no reference.", vp));
2768 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2772 * Don't vgonel if we're already doomed.
2774 if (vp->v_iflag & VI_DOOMED)
2776 vp->v_iflag |= VI_DOOMED;
2779 * Check to see if the vnode is in use. If so, we have to call
2780 * VOP_CLOSE() and VOP_INACTIVE().
2782 active = vp->v_usecount;
2783 oweinact = (vp->v_iflag & VI_OWEINACT);
2785 vgonel_reclaim_lowervp(vp);
2788 * Clean out any buffers associated with the vnode.
2789 * If the flush fails, just toss the buffers.
2792 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
2793 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
2794 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0)
2795 vinvalbuf(vp, 0, 0, 0);
2798 * If purging an active vnode, it must be closed and
2799 * deactivated before being reclaimed.
2802 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
2803 if (oweinact || active) {
2805 if ((vp->v_iflag & VI_DOINGINACT) == 0)
2809 if (vp->v_type == VSOCK)
2810 vfs_unp_reclaim(vp);
2812 * Reclaim the vnode.
2814 if (VOP_RECLAIM(vp, td))
2815 panic("vgone: cannot reclaim");
2817 vn_finished_secondary_write(mp);
2818 VNASSERT(vp->v_object == NULL, vp,
2819 ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
2821 * Clear the advisory locks and wake up waiting threads.
2823 (void)VOP_ADVLOCKPURGE(vp);
2825 * Delete from old mount point vnode list.
2830 * Done with purge, reset to the standard lock and invalidate
2834 vp->v_vnlock = &vp->v_lock;
2835 vp->v_op = &dead_vnodeops;
2841 * Calculate the total number of references to a special device.
2844 vcount(struct vnode *vp)
2849 count = vp->v_rdev->si_usecount;
2855 * Same as above, but using the struct cdev *as argument
2858 count_dev(struct cdev *dev)
2863 count = dev->si_usecount;
2869 * Print out a description of a vnode.
2871 static char *typename[] =
2872 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
2876 vn_printf(struct vnode *vp, const char *fmt, ...)
2879 char buf[256], buf2[16];
2885 printf("%p: ", (void *)vp);
2886 printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
2887 printf(" usecount %d, writecount %d, refcount %d mountedhere %p\n",
2888 vp->v_usecount, vp->v_writecount, vp->v_holdcnt, vp->v_mountedhere);
2891 if (vp->v_vflag & VV_ROOT)
2892 strlcat(buf, "|VV_ROOT", sizeof(buf));
2893 if (vp->v_vflag & VV_ISTTY)
2894 strlcat(buf, "|VV_ISTTY", sizeof(buf));
2895 if (vp->v_vflag & VV_NOSYNC)
2896 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
2897 if (vp->v_vflag & VV_ETERNALDEV)
2898 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
2899 if (vp->v_vflag & VV_CACHEDLABEL)
2900 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
2901 if (vp->v_vflag & VV_TEXT)
2902 strlcat(buf, "|VV_TEXT", sizeof(buf));
2903 if (vp->v_vflag & VV_COPYONWRITE)
2904 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
2905 if (vp->v_vflag & VV_SYSTEM)
2906 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
2907 if (vp->v_vflag & VV_PROCDEP)
2908 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
2909 if (vp->v_vflag & VV_NOKNOTE)
2910 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
2911 if (vp->v_vflag & VV_DELETED)
2912 strlcat(buf, "|VV_DELETED", sizeof(buf));
2913 if (vp->v_vflag & VV_MD)
2914 strlcat(buf, "|VV_MD", sizeof(buf));
2915 if (vp->v_vflag & VV_FORCEINSMQ)
2916 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
2917 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
2918 VV_CACHEDLABEL | VV_TEXT | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
2919 VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
2921 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
2922 strlcat(buf, buf2, sizeof(buf));
2924 if (vp->v_iflag & VI_MOUNT)
2925 strlcat(buf, "|VI_MOUNT", sizeof(buf));
2926 if (vp->v_iflag & VI_AGE)
2927 strlcat(buf, "|VI_AGE", sizeof(buf));
2928 if (vp->v_iflag & VI_DOOMED)
2929 strlcat(buf, "|VI_DOOMED", sizeof(buf));
2930 if (vp->v_iflag & VI_FREE)
2931 strlcat(buf, "|VI_FREE", sizeof(buf));
2932 if (vp->v_iflag & VI_ACTIVE)
2933 strlcat(buf, "|VI_ACTIVE", sizeof(buf));
2934 if (vp->v_iflag & VI_DOINGINACT)
2935 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
2936 if (vp->v_iflag & VI_OWEINACT)
2937 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
2938 flags = vp->v_iflag & ~(VI_MOUNT | VI_AGE | VI_DOOMED | VI_FREE |
2939 VI_ACTIVE | VI_DOINGINACT | VI_OWEINACT);
2941 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
2942 strlcat(buf, buf2, sizeof(buf));
2944 printf(" flags (%s)\n", buf + 1);
2945 if (mtx_owned(VI_MTX(vp)))
2946 printf(" VI_LOCKed");
2947 if (vp->v_object != NULL)
2948 printf(" v_object %p ref %d pages %d\n",
2949 vp->v_object, vp->v_object->ref_count,
2950 vp->v_object->resident_page_count);
2952 lockmgr_printinfo(vp->v_vnlock);
2953 if (vp->v_data != NULL)
2959 * List all of the locked vnodes in the system.
2960 * Called when debugging the kernel.
2962 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
2964 struct mount *mp, *nmp;
2968 * Note: because this is DDB, we can't obey the locking semantics
2969 * for these structures, which means we could catch an inconsistent
2970 * state and dereference a nasty pointer. Not much to be done
2973 db_printf("Locked vnodes\n");
2974 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2975 nmp = TAILQ_NEXT(mp, mnt_list);
2976 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2977 if (vp->v_type != VMARKER &&
2981 nmp = TAILQ_NEXT(mp, mnt_list);
2986 * Show details about the given vnode.
2988 DB_SHOW_COMMAND(vnode, db_show_vnode)
2994 vp = (struct vnode *)addr;
2995 vn_printf(vp, "vnode ");
2999 * Show details about the given mount point.
3001 DB_SHOW_COMMAND(mount, db_show_mount)
3012 /* No address given, print short info about all mount points. */
3013 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3014 db_printf("%p %s on %s (%s)\n", mp,
3015 mp->mnt_stat.f_mntfromname,
3016 mp->mnt_stat.f_mntonname,
3017 mp->mnt_stat.f_fstypename);
3021 db_printf("\nMore info: show mount <addr>\n");
3025 mp = (struct mount *)addr;
3026 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
3027 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
3030 mflags = mp->mnt_flag;
3031 #define MNT_FLAG(flag) do { \
3032 if (mflags & (flag)) { \
3033 if (buf[0] != '\0') \
3034 strlcat(buf, ", ", sizeof(buf)); \
3035 strlcat(buf, (#flag) + 4, sizeof(buf)); \
3036 mflags &= ~(flag); \
3039 MNT_FLAG(MNT_RDONLY);
3040 MNT_FLAG(MNT_SYNCHRONOUS);
3041 MNT_FLAG(MNT_NOEXEC);
3042 MNT_FLAG(MNT_NOSUID);
3043 MNT_FLAG(MNT_NFS4ACLS);
3044 MNT_FLAG(MNT_UNION);
3045 MNT_FLAG(MNT_ASYNC);
3046 MNT_FLAG(MNT_SUIDDIR);
3047 MNT_FLAG(MNT_SOFTDEP);
3048 MNT_FLAG(MNT_NOSYMFOLLOW);
3049 MNT_FLAG(MNT_GJOURNAL);
3050 MNT_FLAG(MNT_MULTILABEL);
3052 MNT_FLAG(MNT_NOATIME);
3053 MNT_FLAG(MNT_NOCLUSTERR);
3054 MNT_FLAG(MNT_NOCLUSTERW);
3056 MNT_FLAG(MNT_EXRDONLY);
3057 MNT_FLAG(MNT_EXPORTED);
3058 MNT_FLAG(MNT_DEFEXPORTED);
3059 MNT_FLAG(MNT_EXPORTANON);
3060 MNT_FLAG(MNT_EXKERB);
3061 MNT_FLAG(MNT_EXPUBLIC);
3062 MNT_FLAG(MNT_LOCAL);
3063 MNT_FLAG(MNT_QUOTA);
3064 MNT_FLAG(MNT_ROOTFS);
3066 MNT_FLAG(MNT_IGNORE);
3067 MNT_FLAG(MNT_UPDATE);
3068 MNT_FLAG(MNT_DELEXPORT);
3069 MNT_FLAG(MNT_RELOAD);
3070 MNT_FLAG(MNT_FORCE);
3071 MNT_FLAG(MNT_SNAPSHOT);
3072 MNT_FLAG(MNT_BYFSID);
3076 strlcat(buf, ", ", sizeof(buf));
3077 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3078 "0x%016jx", mflags);
3080 db_printf(" mnt_flag = %s\n", buf);
3083 flags = mp->mnt_kern_flag;
3084 #define MNT_KERN_FLAG(flag) do { \
3085 if (flags & (flag)) { \
3086 if (buf[0] != '\0') \
3087 strlcat(buf, ", ", sizeof(buf)); \
3088 strlcat(buf, (#flag) + 5, sizeof(buf)); \
3092 MNT_KERN_FLAG(MNTK_UNMOUNTF);
3093 MNT_KERN_FLAG(MNTK_ASYNC);
3094 MNT_KERN_FLAG(MNTK_SOFTDEP);
3095 MNT_KERN_FLAG(MNTK_NOINSMNTQ);
3096 MNT_KERN_FLAG(MNTK_DRAINING);
3097 MNT_KERN_FLAG(MNTK_REFEXPIRE);
3098 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
3099 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
3100 MNT_KERN_FLAG(MNTK_NO_IOPF);
3101 MNT_KERN_FLAG(MNTK_VGONE_UPPER);
3102 MNT_KERN_FLAG(MNTK_VGONE_WAITER);
3103 MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
3104 MNT_KERN_FLAG(MNTK_MARKER);
3105 MNT_KERN_FLAG(MNTK_NOASYNC);
3106 MNT_KERN_FLAG(MNTK_UNMOUNT);
3107 MNT_KERN_FLAG(MNTK_MWAIT);
3108 MNT_KERN_FLAG(MNTK_SUSPEND);
3109 MNT_KERN_FLAG(MNTK_SUSPEND2);
3110 MNT_KERN_FLAG(MNTK_SUSPENDED);
3111 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
3112 MNT_KERN_FLAG(MNTK_NOKNOTE);
3113 #undef MNT_KERN_FLAG
3116 strlcat(buf, ", ", sizeof(buf));
3117 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3120 db_printf(" mnt_kern_flag = %s\n", buf);
3122 db_printf(" mnt_opt = ");
3123 opt = TAILQ_FIRST(mp->mnt_opt);
3125 db_printf("%s", opt->name);
3126 opt = TAILQ_NEXT(opt, link);
3127 while (opt != NULL) {
3128 db_printf(", %s", opt->name);
3129 opt = TAILQ_NEXT(opt, link);
3135 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
3136 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
3137 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
3138 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
3139 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
3140 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
3141 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
3142 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
3143 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
3144 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
3145 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
3146 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
3148 db_printf(" mnt_cred = { uid=%u ruid=%u",
3149 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
3150 if (jailed(mp->mnt_cred))
3151 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
3153 db_printf(" mnt_ref = %d\n", mp->mnt_ref);
3154 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
3155 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
3156 db_printf(" mnt_activevnodelistsize = %d\n",
3157 mp->mnt_activevnodelistsize);
3158 db_printf(" mnt_writeopcount = %d\n", mp->mnt_writeopcount);
3159 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
3160 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
3161 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
3162 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
3163 db_printf(" mnt_secondary_accwrites = %d\n",
3164 mp->mnt_secondary_accwrites);
3165 db_printf(" mnt_gjprovider = %s\n",
3166 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
3168 db_printf("\n\nList of active vnodes\n");
3169 TAILQ_FOREACH(vp, &mp->mnt_activevnodelist, v_actfreelist) {
3170 if (vp->v_type != VMARKER) {
3171 vn_printf(vp, "vnode ");
3176 db_printf("\n\nList of inactive vnodes\n");
3177 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3178 if (vp->v_type != VMARKER && (vp->v_iflag & VI_ACTIVE) == 0) {
3179 vn_printf(vp, "vnode ");
3188 * Fill in a struct xvfsconf based on a struct vfsconf.
3191 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
3193 struct xvfsconf xvfsp;
3195 bzero(&xvfsp, sizeof(xvfsp));
3196 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
3197 xvfsp.vfc_typenum = vfsp->vfc_typenum;
3198 xvfsp.vfc_refcount = vfsp->vfc_refcount;
3199 xvfsp.vfc_flags = vfsp->vfc_flags;
3201 * These are unused in userland, we keep them
3202 * to not break binary compatibility.
3204 xvfsp.vfc_vfsops = NULL;
3205 xvfsp.vfc_next = NULL;
3206 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3209 #ifdef COMPAT_FREEBSD32
3211 uint32_t vfc_vfsops;
3212 char vfc_name[MFSNAMELEN];
3213 int32_t vfc_typenum;
3214 int32_t vfc_refcount;
3220 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
3222 struct xvfsconf32 xvfsp;
3224 strcpy(xvfsp.vfc_name, vfsp->vfc_name);
3225 xvfsp.vfc_typenum = vfsp->vfc_typenum;
3226 xvfsp.vfc_refcount = vfsp->vfc_refcount;
3227 xvfsp.vfc_flags = vfsp->vfc_flags;
3228 xvfsp.vfc_vfsops = 0;
3230 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3235 * Top level filesystem related information gathering.
3238 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
3240 struct vfsconf *vfsp;
3244 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3245 #ifdef COMPAT_FREEBSD32
3246 if (req->flags & SCTL_MASK32)
3247 error = vfsconf2x32(req, vfsp);
3250 error = vfsconf2x(req, vfsp);
3257 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD,
3258 NULL, 0, sysctl_vfs_conflist,
3259 "S,xvfsconf", "List of all configured filesystems");
3261 #ifndef BURN_BRIDGES
3262 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
3265 vfs_sysctl(SYSCTL_HANDLER_ARGS)
3267 int *name = (int *)arg1 - 1; /* XXX */
3268 u_int namelen = arg2 + 1; /* XXX */
3269 struct vfsconf *vfsp;
3271 log(LOG_WARNING, "userland calling deprecated sysctl, "
3272 "please rebuild world\n");
3274 #if 1 || defined(COMPAT_PRELITE2)
3275 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
3277 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
3281 case VFS_MAXTYPENUM:
3284 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
3287 return (ENOTDIR); /* overloaded */
3288 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list)
3289 if (vfsp->vfc_typenum == name[2])
3292 return (EOPNOTSUPP);
3293 #ifdef COMPAT_FREEBSD32
3294 if (req->flags & SCTL_MASK32)
3295 return (vfsconf2x32(req, vfsp));
3298 return (vfsconf2x(req, vfsp));
3300 return (EOPNOTSUPP);
3303 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP,
3304 vfs_sysctl, "Generic filesystem");
3306 #if 1 || defined(COMPAT_PRELITE2)
3309 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
3312 struct vfsconf *vfsp;
3313 struct ovfsconf ovfs;
3315 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3316 bzero(&ovfs, sizeof(ovfs));
3317 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
3318 strcpy(ovfs.vfc_name, vfsp->vfc_name);
3319 ovfs.vfc_index = vfsp->vfc_typenum;
3320 ovfs.vfc_refcount = vfsp->vfc_refcount;
3321 ovfs.vfc_flags = vfsp->vfc_flags;
3322 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
3329 #endif /* 1 || COMPAT_PRELITE2 */
3330 #endif /* !BURN_BRIDGES */
3332 #define KINFO_VNODESLOP 10
3335 * Dump vnode list (via sysctl).
3339 sysctl_vnode(SYSCTL_HANDLER_ARGS)
3347 * Stale numvnodes access is not fatal here.
3350 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
3352 /* Make an estimate */
3353 return (SYSCTL_OUT(req, 0, len));
3355 error = sysctl_wire_old_buffer(req, 0);
3358 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
3360 mtx_lock(&mountlist_mtx);
3361 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3362 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
3365 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3369 xvn[n].xv_size = sizeof *xvn;
3370 xvn[n].xv_vnode = vp;
3371 xvn[n].xv_id = 0; /* XXX compat */
3372 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
3374 XV_COPY(writecount);
3380 xvn[n].xv_flag = vp->v_vflag;
3382 switch (vp->v_type) {
3389 if (vp->v_rdev == NULL) {
3393 xvn[n].xv_dev = dev2udev(vp->v_rdev);
3396 xvn[n].xv_socket = vp->v_socket;
3399 xvn[n].xv_fifo = vp->v_fifoinfo;
3404 /* shouldn't happen? */
3412 mtx_lock(&mountlist_mtx);
3417 mtx_unlock(&mountlist_mtx);
3419 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
3424 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
3425 0, 0, sysctl_vnode, "S,xvnode", "");
3429 * Unmount all filesystems. The list is traversed in reverse order
3430 * of mounting to avoid dependencies.
3433 vfs_unmountall(void)
3439 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
3443 * Since this only runs when rebooting, it is not interlocked.
3445 while(!TAILQ_EMPTY(&mountlist)) {
3446 mp = TAILQ_LAST(&mountlist, mntlist);
3447 error = dounmount(mp, MNT_FORCE, td);
3449 TAILQ_REMOVE(&mountlist, mp, mnt_list);
3451 * XXX: Due to the way in which we mount the root
3452 * file system off of devfs, devfs will generate a
3453 * "busy" warning when we try to unmount it before
3454 * the root. Don't print a warning as a result in
3455 * order to avoid false positive errors that may
3456 * cause needless upset.
3458 if (strcmp(mp->mnt_vfc->vfc_name, "devfs") != 0) {
3459 printf("unmount of %s failed (",
3460 mp->mnt_stat.f_mntonname);
3464 printf("%d)\n", error);
3467 /* The unmount has removed mp from the mountlist */
3473 * perform msync on all vnodes under a mount point
3474 * the mount point must be locked.
3477 vfs_msync(struct mount *mp, int flags)
3479 struct vnode *vp, *mvp;
3480 struct vm_object *obj;
3482 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
3483 MNT_VNODE_FOREACH_ACTIVE(vp, mp, mvp) {
3485 if (obj != NULL && (obj->flags & OBJ_MIGHTBEDIRTY) != 0 &&
3486 (flags == MNT_WAIT || VOP_ISLOCKED(vp) == 0)) {
3488 LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
3490 if (vp->v_vflag & VV_NOSYNC) { /* unlinked */
3497 VM_OBJECT_WLOCK(obj);
3498 vm_object_page_clean(obj, 0, 0,
3500 OBJPC_SYNC : OBJPC_NOSYNC);
3501 VM_OBJECT_WUNLOCK(obj);
3511 destroy_vpollinfo(struct vpollinfo *vi)
3513 seldrain(&vi->vpi_selinfo);
3514 knlist_destroy(&vi->vpi_selinfo.si_note);
3515 mtx_destroy(&vi->vpi_lock);
3516 uma_zfree(vnodepoll_zone, vi);
3520 * Initalize per-vnode helper structure to hold poll-related state.
3523 v_addpollinfo(struct vnode *vp)
3525 struct vpollinfo *vi;
3527 if (vp->v_pollinfo != NULL)
3529 vi = uma_zalloc(vnodepoll_zone, M_WAITOK);
3530 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
3531 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
3532 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
3534 if (vp->v_pollinfo != NULL) {
3536 destroy_vpollinfo(vi);
3539 vp->v_pollinfo = vi;
3544 * Record a process's interest in events which might happen to
3545 * a vnode. Because poll uses the historic select-style interface
3546 * internally, this routine serves as both the ``check for any
3547 * pending events'' and the ``record my interest in future events''
3548 * functions. (These are done together, while the lock is held,
3549 * to avoid race conditions.)
3552 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
3556 mtx_lock(&vp->v_pollinfo->vpi_lock);
3557 if (vp->v_pollinfo->vpi_revents & events) {
3559 * This leaves events we are not interested
3560 * in available for the other process which
3561 * which presumably had requested them
3562 * (otherwise they would never have been
3565 events &= vp->v_pollinfo->vpi_revents;
3566 vp->v_pollinfo->vpi_revents &= ~events;
3568 mtx_unlock(&vp->v_pollinfo->vpi_lock);
3571 vp->v_pollinfo->vpi_events |= events;
3572 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
3573 mtx_unlock(&vp->v_pollinfo->vpi_lock);
3578 * Routine to create and manage a filesystem syncer vnode.
3580 #define sync_close ((int (*)(struct vop_close_args *))nullop)
3581 static int sync_fsync(struct vop_fsync_args *);
3582 static int sync_inactive(struct vop_inactive_args *);
3583 static int sync_reclaim(struct vop_reclaim_args *);
3585 static struct vop_vector sync_vnodeops = {
3586 .vop_bypass = VOP_EOPNOTSUPP,
3587 .vop_close = sync_close, /* close */
3588 .vop_fsync = sync_fsync, /* fsync */
3589 .vop_inactive = sync_inactive, /* inactive */
3590 .vop_reclaim = sync_reclaim, /* reclaim */
3591 .vop_lock1 = vop_stdlock, /* lock */
3592 .vop_unlock = vop_stdunlock, /* unlock */
3593 .vop_islocked = vop_stdislocked, /* islocked */
3597 * Create a new filesystem syncer vnode for the specified mount point.
3600 vfs_allocate_syncvnode(struct mount *mp)
3604 static long start, incr, next;
3607 /* Allocate a new vnode */
3608 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
3610 panic("vfs_allocate_syncvnode: getnewvnode() failed");
3612 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3613 vp->v_vflag |= VV_FORCEINSMQ;
3614 error = insmntque(vp, mp);
3616 panic("vfs_allocate_syncvnode: insmntque() failed");
3617 vp->v_vflag &= ~VV_FORCEINSMQ;
3620 * Place the vnode onto the syncer worklist. We attempt to
3621 * scatter them about on the list so that they will go off
3622 * at evenly distributed times even if all the filesystems
3623 * are mounted at once.
3626 if (next == 0 || next > syncer_maxdelay) {
3630 start = syncer_maxdelay / 2;
3631 incr = syncer_maxdelay;
3637 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
3638 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
3639 mtx_lock(&sync_mtx);
3641 if (mp->mnt_syncer == NULL) {
3642 mp->mnt_syncer = vp;
3645 mtx_unlock(&sync_mtx);
3648 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3655 vfs_deallocate_syncvnode(struct mount *mp)
3659 mtx_lock(&sync_mtx);
3660 vp = mp->mnt_syncer;
3662 mp->mnt_syncer = NULL;
3663 mtx_unlock(&sync_mtx);
3669 * Do a lazy sync of the filesystem.
3672 sync_fsync(struct vop_fsync_args *ap)
3674 struct vnode *syncvp = ap->a_vp;
3675 struct mount *mp = syncvp->v_mount;
3680 * We only need to do something if this is a lazy evaluation.
3682 if (ap->a_waitfor != MNT_LAZY)
3686 * Move ourselves to the back of the sync list.
3688 bo = &syncvp->v_bufobj;
3690 vn_syncer_add_to_worklist(bo, syncdelay);
3694 * Walk the list of vnodes pushing all that are dirty and
3695 * not already on the sync list.
3697 mtx_lock(&mountlist_mtx);
3698 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK) != 0) {
3699 mtx_unlock(&mountlist_mtx);
3702 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
3706 save = curthread_pflags_set(TDP_SYNCIO);
3707 vfs_msync(mp, MNT_NOWAIT);
3708 error = VFS_SYNC(mp, MNT_LAZY);
3709 curthread_pflags_restore(save);
3710 vn_finished_write(mp);
3716 * The syncer vnode is no referenced.
3719 sync_inactive(struct vop_inactive_args *ap)
3727 * The syncer vnode is no longer needed and is being decommissioned.
3729 * Modifications to the worklist must be protected by sync_mtx.
3732 sync_reclaim(struct vop_reclaim_args *ap)
3734 struct vnode *vp = ap->a_vp;
3739 mtx_lock(&sync_mtx);
3740 if (vp->v_mount->mnt_syncer == vp)
3741 vp->v_mount->mnt_syncer = NULL;
3742 if (bo->bo_flag & BO_ONWORKLST) {
3743 LIST_REMOVE(bo, bo_synclist);
3744 syncer_worklist_len--;
3746 bo->bo_flag &= ~BO_ONWORKLST;
3748 mtx_unlock(&sync_mtx);
3755 * Check if vnode represents a disk device
3758 vn_isdisk(struct vnode *vp, int *errp)
3764 if (vp->v_type != VCHR)
3766 else if (vp->v_rdev == NULL)
3768 else if (vp->v_rdev->si_devsw == NULL)
3770 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
3775 return (error == 0);
3779 * Common filesystem object access control check routine. Accepts a
3780 * vnode's type, "mode", uid and gid, requested access mode, credentials,
3781 * and optional call-by-reference privused argument allowing vaccess()
3782 * to indicate to the caller whether privilege was used to satisfy the
3783 * request (obsoleted). Returns 0 on success, or an errno on failure.
3786 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
3787 accmode_t accmode, struct ucred *cred, int *privused)
3789 accmode_t dac_granted;
3790 accmode_t priv_granted;
3792 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
3793 ("invalid bit in accmode"));
3794 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
3795 ("VAPPEND without VWRITE"));
3798 * Look for a normal, non-privileged way to access the file/directory
3799 * as requested. If it exists, go with that.
3802 if (privused != NULL)
3807 /* Check the owner. */
3808 if (cred->cr_uid == file_uid) {
3809 dac_granted |= VADMIN;
3810 if (file_mode & S_IXUSR)
3811 dac_granted |= VEXEC;
3812 if (file_mode & S_IRUSR)
3813 dac_granted |= VREAD;
3814 if (file_mode & S_IWUSR)
3815 dac_granted |= (VWRITE | VAPPEND);
3817 if ((accmode & dac_granted) == accmode)
3823 /* Otherwise, check the groups (first match) */
3824 if (groupmember(file_gid, cred)) {
3825 if (file_mode & S_IXGRP)
3826 dac_granted |= VEXEC;
3827 if (file_mode & S_IRGRP)
3828 dac_granted |= VREAD;
3829 if (file_mode & S_IWGRP)
3830 dac_granted |= (VWRITE | VAPPEND);
3832 if ((accmode & dac_granted) == accmode)
3838 /* Otherwise, check everyone else. */
3839 if (file_mode & S_IXOTH)
3840 dac_granted |= VEXEC;
3841 if (file_mode & S_IROTH)
3842 dac_granted |= VREAD;
3843 if (file_mode & S_IWOTH)
3844 dac_granted |= (VWRITE | VAPPEND);
3845 if ((accmode & dac_granted) == accmode)
3850 * Build a privilege mask to determine if the set of privileges
3851 * satisfies the requirements when combined with the granted mask
3852 * from above. For each privilege, if the privilege is required,
3853 * bitwise or the request type onto the priv_granted mask.
3859 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
3860 * requests, instead of PRIV_VFS_EXEC.
3862 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3863 !priv_check_cred(cred, PRIV_VFS_LOOKUP, 0))
3864 priv_granted |= VEXEC;
3867 * Ensure that at least one execute bit is on. Otherwise,
3868 * a privileged user will always succeed, and we don't want
3869 * this to happen unless the file really is executable.
3871 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3872 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
3873 !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
3874 priv_granted |= VEXEC;
3877 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
3878 !priv_check_cred(cred, PRIV_VFS_READ, 0))
3879 priv_granted |= VREAD;
3881 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
3882 !priv_check_cred(cred, PRIV_VFS_WRITE, 0))
3883 priv_granted |= (VWRITE | VAPPEND);
3885 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
3886 !priv_check_cred(cred, PRIV_VFS_ADMIN, 0))
3887 priv_granted |= VADMIN;
3889 if ((accmode & (priv_granted | dac_granted)) == accmode) {
3890 /* XXX audit: privilege used */
3891 if (privused != NULL)
3896 return ((accmode & VADMIN) ? EPERM : EACCES);
3900 * Credential check based on process requesting service, and per-attribute
3904 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
3905 struct thread *td, accmode_t accmode)
3909 * Kernel-invoked always succeeds.
3915 * Do not allow privileged processes in jail to directly manipulate
3916 * system attributes.
3918 switch (attrnamespace) {
3919 case EXTATTR_NAMESPACE_SYSTEM:
3920 /* Potentially should be: return (EPERM); */
3921 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM, 0));
3922 case EXTATTR_NAMESPACE_USER:
3923 return (VOP_ACCESS(vp, accmode, cred, td));
3929 #ifdef DEBUG_VFS_LOCKS
3931 * This only exists to supress warnings from unlocked specfs accesses. It is
3932 * no longer ok to have an unlocked VFS.
3934 #define IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL || \
3935 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
3937 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
3938 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
3939 "Drop into debugger on lock violation");
3941 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
3942 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
3943 0, "Check for interlock across VOPs");
3945 int vfs_badlock_print = 1; /* Print lock violations. */
3946 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
3947 0, "Print lock violations");
3950 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
3951 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
3952 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
3956 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
3960 if (vfs_badlock_backtrace)
3963 if (vfs_badlock_print)
3964 printf("%s: %p %s\n", str, (void *)vp, msg);
3965 if (vfs_badlock_ddb)
3966 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
3970 assert_vi_locked(struct vnode *vp, const char *str)
3973 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
3974 vfs_badlock("interlock is not locked but should be", str, vp);
3978 assert_vi_unlocked(struct vnode *vp, const char *str)
3981 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
3982 vfs_badlock("interlock is locked but should not be", str, vp);
3986 assert_vop_locked(struct vnode *vp, const char *str)
3990 if (!IGNORE_LOCK(vp)) {
3991 locked = VOP_ISLOCKED(vp);
3992 if (locked == 0 || locked == LK_EXCLOTHER)
3993 vfs_badlock("is not locked but should be", str, vp);
3998 assert_vop_unlocked(struct vnode *vp, const char *str)
4001 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
4002 vfs_badlock("is locked but should not be", str, vp);
4006 assert_vop_elocked(struct vnode *vp, const char *str)
4009 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
4010 vfs_badlock("is not exclusive locked but should be", str, vp);
4015 assert_vop_elocked_other(struct vnode *vp, const char *str)
4018 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLOTHER)
4019 vfs_badlock("is not exclusive locked by another thread",
4024 assert_vop_slocked(struct vnode *vp, const char *str)
4027 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_SHARED)
4028 vfs_badlock("is not locked shared but should be", str, vp);
4031 #endif /* DEBUG_VFS_LOCKS */
4034 vop_rename_fail(struct vop_rename_args *ap)
4037 if (ap->a_tvp != NULL)
4039 if (ap->a_tdvp == ap->a_tvp)
4048 vop_rename_pre(void *ap)
4050 struct vop_rename_args *a = ap;
4052 #ifdef DEBUG_VFS_LOCKS
4054 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
4055 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
4056 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
4057 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
4059 /* Check the source (from). */
4060 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
4061 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
4062 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
4063 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
4064 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
4066 /* Check the target. */
4068 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
4069 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
4071 if (a->a_tdvp != a->a_fdvp)
4073 if (a->a_tvp != a->a_fvp)
4081 vop_strategy_pre(void *ap)
4083 #ifdef DEBUG_VFS_LOCKS
4084 struct vop_strategy_args *a;
4091 * Cluster ops lock their component buffers but not the IO container.
4093 if ((bp->b_flags & B_CLUSTER) != 0)
4096 if (panicstr == NULL && !BUF_ISLOCKED(bp)) {
4097 if (vfs_badlock_print)
4099 "VOP_STRATEGY: bp is not locked but should be\n");
4100 if (vfs_badlock_ddb)
4101 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4107 vop_lock_pre(void *ap)
4109 #ifdef DEBUG_VFS_LOCKS
4110 struct vop_lock1_args *a = ap;
4112 if ((a->a_flags & LK_INTERLOCK) == 0)
4113 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4115 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
4120 vop_lock_post(void *ap, int rc)
4122 #ifdef DEBUG_VFS_LOCKS
4123 struct vop_lock1_args *a = ap;
4125 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4126 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
4127 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
4132 vop_unlock_pre(void *ap)
4134 #ifdef DEBUG_VFS_LOCKS
4135 struct vop_unlock_args *a = ap;
4137 if (a->a_flags & LK_INTERLOCK)
4138 ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
4139 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
4144 vop_unlock_post(void *ap, int rc)
4146 #ifdef DEBUG_VFS_LOCKS
4147 struct vop_unlock_args *a = ap;
4149 if (a->a_flags & LK_INTERLOCK)
4150 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
4155 vop_create_post(void *ap, int rc)
4157 struct vop_create_args *a = ap;
4160 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4164 vop_deleteextattr_post(void *ap, int rc)
4166 struct vop_deleteextattr_args *a = ap;
4169 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4173 vop_link_post(void *ap, int rc)
4175 struct vop_link_args *a = ap;
4178 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
4179 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
4184 vop_mkdir_post(void *ap, int rc)
4186 struct vop_mkdir_args *a = ap;
4189 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4193 vop_mknod_post(void *ap, int rc)
4195 struct vop_mknod_args *a = ap;
4198 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4202 vop_remove_post(void *ap, int rc)
4204 struct vop_remove_args *a = ap;
4207 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4208 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4213 vop_rename_post(void *ap, int rc)
4215 struct vop_rename_args *a = ap;
4218 VFS_KNOTE_UNLOCKED(a->a_fdvp, NOTE_WRITE);
4219 VFS_KNOTE_UNLOCKED(a->a_tdvp, NOTE_WRITE);
4220 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
4222 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
4224 if (a->a_tdvp != a->a_fdvp)
4226 if (a->a_tvp != a->a_fvp)
4234 vop_rmdir_post(void *ap, int rc)
4236 struct vop_rmdir_args *a = ap;
4239 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4240 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4245 vop_setattr_post(void *ap, int rc)
4247 struct vop_setattr_args *a = ap;
4250 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4254 vop_setextattr_post(void *ap, int rc)
4256 struct vop_setextattr_args *a = ap;
4259 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4263 vop_symlink_post(void *ap, int rc)
4265 struct vop_symlink_args *a = ap;
4268 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4271 static struct knlist fs_knlist;
4274 vfs_event_init(void *arg)
4276 knlist_init_mtx(&fs_knlist, NULL);
4278 /* XXX - correct order? */
4279 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
4282 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
4285 KNOTE_UNLOCKED(&fs_knlist, event);
4288 static int filt_fsattach(struct knote *kn);
4289 static void filt_fsdetach(struct knote *kn);
4290 static int filt_fsevent(struct knote *kn, long hint);
4292 struct filterops fs_filtops = {
4294 .f_attach = filt_fsattach,
4295 .f_detach = filt_fsdetach,
4296 .f_event = filt_fsevent
4300 filt_fsattach(struct knote *kn)
4303 kn->kn_flags |= EV_CLEAR;
4304 knlist_add(&fs_knlist, kn, 0);
4309 filt_fsdetach(struct knote *kn)
4312 knlist_remove(&fs_knlist, kn, 0);
4316 filt_fsevent(struct knote *kn, long hint)
4319 kn->kn_fflags |= hint;
4320 return (kn->kn_fflags != 0);
4324 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
4330 error = SYSCTL_IN(req, &vc, sizeof(vc));
4333 if (vc.vc_vers != VFS_CTL_VERS1)
4335 mp = vfs_getvfs(&vc.vc_fsid);
4338 /* ensure that a specific sysctl goes to the right filesystem. */
4339 if (strcmp(vc.vc_fstypename, "*") != 0 &&
4340 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
4344 VCTLTOREQ(&vc, req);
4345 error = VFS_SYSCTL(mp, vc.vc_op, req);
4350 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_WR,
4351 NULL, 0, sysctl_vfs_ctl, "",
4355 * Function to initialize a va_filerev field sensibly.
4356 * XXX: Wouldn't a random number make a lot more sense ??
4359 init_va_filerev(void)
4364 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
4367 static int filt_vfsread(struct knote *kn, long hint);
4368 static int filt_vfswrite(struct knote *kn, long hint);
4369 static int filt_vfsvnode(struct knote *kn, long hint);
4370 static void filt_vfsdetach(struct knote *kn);
4371 static struct filterops vfsread_filtops = {
4373 .f_detach = filt_vfsdetach,
4374 .f_event = filt_vfsread
4376 static struct filterops vfswrite_filtops = {
4378 .f_detach = filt_vfsdetach,
4379 .f_event = filt_vfswrite
4381 static struct filterops vfsvnode_filtops = {
4383 .f_detach = filt_vfsdetach,
4384 .f_event = filt_vfsvnode
4388 vfs_knllock(void *arg)
4390 struct vnode *vp = arg;
4392 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4396 vfs_knlunlock(void *arg)
4398 struct vnode *vp = arg;
4404 vfs_knl_assert_locked(void *arg)
4406 #ifdef DEBUG_VFS_LOCKS
4407 struct vnode *vp = arg;
4409 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
4414 vfs_knl_assert_unlocked(void *arg)
4416 #ifdef DEBUG_VFS_LOCKS
4417 struct vnode *vp = arg;
4419 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
4424 vfs_kqfilter(struct vop_kqfilter_args *ap)
4426 struct vnode *vp = ap->a_vp;
4427 struct knote *kn = ap->a_kn;
4430 switch (kn->kn_filter) {
4432 kn->kn_fop = &vfsread_filtops;
4435 kn->kn_fop = &vfswrite_filtops;
4438 kn->kn_fop = &vfsvnode_filtops;
4444 kn->kn_hook = (caddr_t)vp;
4447 if (vp->v_pollinfo == NULL)
4449 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
4450 knlist_add(knl, kn, 0);
4456 * Detach knote from vnode
4459 filt_vfsdetach(struct knote *kn)
4461 struct vnode *vp = (struct vnode *)kn->kn_hook;
4463 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
4464 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
4469 filt_vfsread(struct knote *kn, long hint)
4471 struct vnode *vp = (struct vnode *)kn->kn_hook;
4476 * filesystem is gone, so set the EOF flag and schedule
4477 * the knote for deletion.
4479 if (hint == NOTE_REVOKE) {
4481 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
4486 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
4490 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
4491 res = (kn->kn_data != 0);
4498 filt_vfswrite(struct knote *kn, long hint)
4500 struct vnode *vp = (struct vnode *)kn->kn_hook;
4505 * filesystem is gone, so set the EOF flag and schedule
4506 * the knote for deletion.
4508 if (hint == NOTE_REVOKE)
4509 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
4517 filt_vfsvnode(struct knote *kn, long hint)
4519 struct vnode *vp = (struct vnode *)kn->kn_hook;
4523 if (kn->kn_sfflags & hint)
4524 kn->kn_fflags |= hint;
4525 if (hint == NOTE_REVOKE) {
4526 kn->kn_flags |= EV_EOF;
4530 res = (kn->kn_fflags != 0);
4536 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
4540 if (dp->d_reclen > ap->a_uio->uio_resid)
4541 return (ENAMETOOLONG);
4542 error = uiomove(dp, dp->d_reclen, ap->a_uio);
4544 if (ap->a_ncookies != NULL) {
4545 if (ap->a_cookies != NULL)
4546 free(ap->a_cookies, M_TEMP);
4547 ap->a_cookies = NULL;
4548 *ap->a_ncookies = 0;
4552 if (ap->a_ncookies == NULL)
4555 KASSERT(ap->a_cookies,
4556 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
4558 *ap->a_cookies = realloc(*ap->a_cookies,
4559 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
4560 (*ap->a_cookies)[*ap->a_ncookies] = off;
4565 * Mark for update the access time of the file if the filesystem
4566 * supports VOP_MARKATIME. This functionality is used by execve and
4567 * mmap, so we want to avoid the I/O implied by directly setting
4568 * va_atime for the sake of efficiency.
4571 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
4576 ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
4577 if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
4578 (void)VOP_MARKATIME(vp);
4582 * The purpose of this routine is to remove granularity from accmode_t,
4583 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
4584 * VADMIN and VAPPEND.
4586 * If it returns 0, the caller is supposed to continue with the usual
4587 * access checks using 'accmode' as modified by this routine. If it
4588 * returns nonzero value, the caller is supposed to return that value
4591 * Note that after this routine runs, accmode may be zero.
4594 vfs_unixify_accmode(accmode_t *accmode)
4597 * There is no way to specify explicit "deny" rule using
4598 * file mode or POSIX.1e ACLs.
4600 if (*accmode & VEXPLICIT_DENY) {
4606 * None of these can be translated into usual access bits.
4607 * Also, the common case for NFSv4 ACLs is to not contain
4608 * either of these bits. Caller should check for VWRITE
4609 * on the containing directory instead.
4611 if (*accmode & (VDELETE_CHILD | VDELETE))
4614 if (*accmode & VADMIN_PERMS) {
4615 *accmode &= ~VADMIN_PERMS;
4620 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
4621 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
4623 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
4629 * These are helper functions for filesystems to traverse all
4630 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
4632 * This interface replaces MNT_VNODE_FOREACH.
4635 MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
4638 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
4643 kern_yield(PRI_USER);
4645 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
4646 vp = TAILQ_NEXT(*mvp, v_nmntvnodes);
4647 while (vp != NULL && (vp->v_type == VMARKER ||
4648 (vp->v_iflag & VI_DOOMED) != 0))
4649 vp = TAILQ_NEXT(vp, v_nmntvnodes);
4651 /* Check if we are done */
4653 __mnt_vnode_markerfree_all(mvp, mp);
4654 /* MNT_IUNLOCK(mp); -- done in above function */
4655 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
4658 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
4659 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
4666 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
4670 *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
4673 (*mvp)->v_type = VMARKER;
4675 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
4676 while (vp != NULL && (vp->v_type == VMARKER ||
4677 (vp->v_iflag & VI_DOOMED) != 0))
4678 vp = TAILQ_NEXT(vp, v_nmntvnodes);
4680 /* Check if we are done */
4684 free(*mvp, M_VNODE_MARKER);
4688 (*mvp)->v_mount = mp;
4689 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
4697 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
4705 mtx_assert(MNT_MTX(mp), MA_OWNED);
4707 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
4708 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
4711 free(*mvp, M_VNODE_MARKER);
4716 * These are helper functions for filesystems to traverse their
4717 * active vnodes. See MNT_VNODE_FOREACH_ACTIVE() in sys/mount.h
4720 mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
4723 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
4728 free(*mvp, M_VNODE_MARKER);
4732 static struct vnode *
4733 mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
4735 struct vnode *vp, *nvp;
4737 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
4738 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
4740 vp = TAILQ_NEXT(*mvp, v_actfreelist);
4741 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
4742 while (vp != NULL) {
4743 if (vp->v_type == VMARKER) {
4744 vp = TAILQ_NEXT(vp, v_actfreelist);
4747 if (!VI_TRYLOCK(vp)) {
4748 if (mp_ncpus == 1 || should_yield()) {
4749 TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
4750 mtx_unlock(&vnode_free_list_mtx);
4751 kern_yield(PRI_USER);
4752 mtx_lock(&vnode_free_list_mtx);
4757 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
4758 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
4759 ("alien vnode on the active list %p %p", vp, mp));
4760 if (vp->v_mount == mp && (vp->v_iflag & VI_DOOMED) == 0)
4762 nvp = TAILQ_NEXT(vp, v_actfreelist);
4767 /* Check if we are done */
4769 mtx_unlock(&vnode_free_list_mtx);
4770 mnt_vnode_markerfree_active(mvp, mp);
4773 TAILQ_INSERT_AFTER(&mp->mnt_activevnodelist, vp, *mvp, v_actfreelist);
4774 mtx_unlock(&vnode_free_list_mtx);
4775 ASSERT_VI_LOCKED(vp, "active iter");
4776 KASSERT((vp->v_iflag & VI_ACTIVE) != 0, ("Non-active vp %p", vp));
4781 __mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
4785 kern_yield(PRI_USER);
4786 mtx_lock(&vnode_free_list_mtx);
4787 return (mnt_vnode_next_active(mvp, mp));
4791 __mnt_vnode_first_active(struct vnode **mvp, struct mount *mp)
4795 *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
4799 (*mvp)->v_type = VMARKER;
4800 (*mvp)->v_mount = mp;
4802 mtx_lock(&vnode_free_list_mtx);
4803 vp = TAILQ_FIRST(&mp->mnt_activevnodelist);
4805 mtx_unlock(&vnode_free_list_mtx);
4806 mnt_vnode_markerfree_active(mvp, mp);
4809 TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
4810 return (mnt_vnode_next_active(mvp, mp));
4814 __mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
4820 mtx_lock(&vnode_free_list_mtx);
4821 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
4822 mtx_unlock(&vnode_free_list_mtx);
4823 mnt_vnode_markerfree_active(mvp, mp);