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$");
45 #include "opt_watchdog.h"
47 #include <sys/param.h>
48 #include <sys/systm.h>
51 #include <sys/condvar.h>
53 #include <sys/dirent.h>
54 #include <sys/event.h>
55 #include <sys/eventhandler.h>
56 #include <sys/extattr.h>
58 #include <sys/fcntl.h>
61 #include <sys/kernel.h>
62 #include <sys/kthread.h>
63 #include <sys/lockf.h>
64 #include <sys/malloc.h>
65 #include <sys/mount.h>
66 #include <sys/namei.h>
68 #include <sys/reboot.h>
69 #include <sys/sched.h>
70 #include <sys/sleepqueue.h>
72 #include <sys/sysctl.h>
73 #include <sys/syslog.h>
74 #include <sys/vmmeter.h>
75 #include <sys/vnode.h>
77 #include <sys/watchdog.h>
80 #include <machine/stdarg.h>
82 #include <security/mac/mac_framework.h>
85 #include <vm/vm_object.h>
86 #include <vm/vm_extern.h>
88 #include <vm/vm_map.h>
89 #include <vm/vm_page.h>
90 #include <vm/vm_kern.h>
100 static void delmntque(struct vnode *vp);
101 static int flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
102 int slpflag, int slptimeo);
103 static void syncer_shutdown(void *arg, int howto);
104 static int vtryrecycle(struct vnode *vp);
105 static void v_incr_usecount(struct vnode *);
106 static void v_decr_usecount(struct vnode *);
107 static void v_decr_useonly(struct vnode *);
108 static void v_upgrade_usecount(struct vnode *);
109 static void vnlru_free(int);
110 static void vgonel(struct vnode *);
111 static void vfs_knllock(void *arg);
112 static void vfs_knlunlock(void *arg);
113 static void vfs_knl_assert_locked(void *arg);
114 static void vfs_knl_assert_unlocked(void *arg);
115 static void destroy_vpollinfo(struct vpollinfo *vi);
118 * Number of vnodes in existence. Increased whenever getnewvnode()
119 * allocates a new vnode, decreased in vdropl() for VI_DOOMED vnode.
121 static unsigned long numvnodes;
123 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
124 "Number of vnodes in existence");
127 * Conversion tables for conversion from vnode types to inode formats
130 enum vtype iftovt_tab[16] = {
131 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
132 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
134 int vttoif_tab[10] = {
135 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
136 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
140 * List of vnodes that are ready for recycling.
142 static TAILQ_HEAD(freelst, vnode) vnode_free_list;
145 * Free vnode target. Free vnodes may simply be files which have been stat'd
146 * but not read. This is somewhat common, and a small cache of such files
147 * should be kept to avoid recreation costs.
149 static u_long wantfreevnodes;
150 SYSCTL_ULONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW, &wantfreevnodes, 0, "");
151 /* Number of vnodes in the free list. */
152 static u_long freevnodes;
153 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD, &freevnodes, 0,
154 "Number of vnodes in the free list");
156 static int vlru_allow_cache_src;
157 SYSCTL_INT(_vfs, OID_AUTO, vlru_allow_cache_src, CTLFLAG_RW,
158 &vlru_allow_cache_src, 0, "Allow vlru to reclaim source vnode");
161 * Various variables used for debugging the new implementation of
163 * XXX these are probably of (very) limited utility now.
165 static int reassignbufcalls;
166 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0,
167 "Number of calls to reassignbuf");
170 * Cache for the mount type id assigned to NFS. This is used for
171 * special checks in nfs/nfs_nqlease.c and vm/vnode_pager.c.
173 int nfs_mount_type = -1;
175 /* To keep more than one thread at a time from running vfs_getnewfsid */
176 static struct mtx mntid_mtx;
179 * Lock for any access to the following:
184 static struct mtx vnode_free_list_mtx;
186 /* Publicly exported FS */
187 struct nfs_public nfs_pub;
189 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
190 static uma_zone_t vnode_zone;
191 static uma_zone_t vnodepoll_zone;
194 * The workitem queue.
196 * It is useful to delay writes of file data and filesystem metadata
197 * for tens of seconds so that quickly created and deleted files need
198 * not waste disk bandwidth being created and removed. To realize this,
199 * we append vnodes to a "workitem" queue. When running with a soft
200 * updates implementation, most pending metadata dependencies should
201 * not wait for more than a few seconds. Thus, mounted on block devices
202 * are delayed only about a half the time that file data is delayed.
203 * Similarly, directory updates are more critical, so are only delayed
204 * about a third the time that file data is delayed. Thus, there are
205 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
206 * one each second (driven off the filesystem syncer process). The
207 * syncer_delayno variable indicates the next queue that is to be processed.
208 * Items that need to be processed soon are placed in this queue:
210 * syncer_workitem_pending[syncer_delayno]
212 * A delay of fifteen seconds is done by placing the request fifteen
213 * entries later in the queue:
215 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
218 static int syncer_delayno;
219 static long syncer_mask;
220 LIST_HEAD(synclist, bufobj);
221 static struct synclist *syncer_workitem_pending[2];
223 * The sync_mtx protects:
228 * syncer_workitem_pending
229 * syncer_worklist_len
232 static struct mtx sync_mtx;
233 static struct cv sync_wakeup;
235 #define SYNCER_MAXDELAY 32
236 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
237 static int syncdelay = 30; /* max time to delay syncing data */
238 static int filedelay = 30; /* time to delay syncing files */
239 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
240 "Time to delay syncing files (in seconds)");
241 static int dirdelay = 29; /* time to delay syncing directories */
242 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
243 "Time to delay syncing directories (in seconds)");
244 static int metadelay = 28; /* time to delay syncing metadata */
245 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
246 "Time to delay syncing metadata (in seconds)");
247 static int rushjob; /* number of slots to run ASAP */
248 static int stat_rush_requests; /* number of times I/O speeded up */
249 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
250 "Number of times I/O speeded up (rush requests)");
253 * When shutting down the syncer, run it at four times normal speed.
255 #define SYNCER_SHUTDOWN_SPEEDUP 4
256 static int sync_vnode_count;
257 static int syncer_worklist_len;
258 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
262 * Number of vnodes we want to exist at any one time. This is mostly used
263 * to size hash tables in vnode-related code. It is normally not used in
264 * getnewvnode(), as wantfreevnodes is normally nonzero.)
266 * XXX desiredvnodes is historical cruft and should not exist.
269 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
270 &desiredvnodes, 0, "Maximum number of vnodes");
271 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
272 &wantfreevnodes, 0, "Minimum number of vnodes (legacy)");
273 static int vnlru_nowhere;
274 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
275 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
278 * Macros to control when a vnode is freed and recycled. All require
279 * the vnode interlock.
281 #define VCANRECYCLE(vp) (((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
282 #define VSHOULDFREE(vp) (!((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
283 #define VSHOULDBUSY(vp) (((vp)->v_iflag & VI_FREE) && (vp)->v_holdcnt)
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)
299 int physvnodes, virtvnodes;
302 * Desiredvnodes is a function of the physical memory size and the
303 * kernel's heap size. Generally speaking, it scales with the
304 * physical memory size. The ratio of desiredvnodes to physical pages
305 * is one to four until desiredvnodes exceeds 98,304. Thereafter, the
306 * marginal ratio of desiredvnodes to physical pages is one to
307 * sixteen. However, desiredvnodes is limited by the kernel's heap
308 * size. The memory required by desiredvnodes vnodes and vm objects
309 * may not exceed one seventh of the kernel's heap size.
311 physvnodes = maxproc + cnt.v_page_count / 16 + 3 * min(98304 * 4,
312 cnt.v_page_count) / 16;
313 virtvnodes = vm_kmem_size / (7 * (sizeof(struct vm_object) +
314 sizeof(struct vnode)));
315 desiredvnodes = min(physvnodes, virtvnodes);
316 if (desiredvnodes > MAXVNODES_MAX) {
318 printf("Reducing kern.maxvnodes %d -> %d\n",
319 desiredvnodes, MAXVNODES_MAX);
320 desiredvnodes = MAXVNODES_MAX;
322 wantfreevnodes = desiredvnodes / 4;
323 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
324 TAILQ_INIT(&vnode_free_list);
325 mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
326 vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
327 NULL, NULL, UMA_ALIGN_PTR, 0);
328 vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
329 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
331 * Initialize the filesystem syncer.
333 syncer_workitem_pending[WI_MPSAFEQ] = hashinit(syncer_maxdelay, M_VNODE,
335 syncer_workitem_pending[WI_GIANTQ] = hashinit(syncer_maxdelay, M_VNODE,
337 syncer_maxdelay = syncer_mask + 1;
338 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
339 cv_init(&sync_wakeup, "syncer");
341 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
345 * Mark a mount point as busy. Used to synchronize access and to delay
346 * unmounting. Eventually, mountlist_mtx is not released on failure.
348 * vfs_busy() is a custom lock, it can block the caller.
349 * vfs_busy() only sleeps if the unmount is active on the mount point.
350 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
351 * vnode belonging to mp.
353 * Lookup uses vfs_busy() to traverse mount points.
355 * / vnode lock A / vnode lock (/var) D
356 * /var vnode lock B /log vnode lock(/var/log) E
357 * vfs_busy lock C vfs_busy lock F
359 * Within each file system, the lock order is C->A->B and F->D->E.
361 * When traversing across mounts, the system follows that lock order:
367 * The lookup() process for namei("/var") illustrates the process:
368 * VOP_LOOKUP() obtains B while A is held
369 * vfs_busy() obtains a shared lock on F while A and B are held
370 * vput() releases lock on B
371 * vput() releases lock on A
372 * VFS_ROOT() obtains lock on D while shared lock on F is held
373 * vfs_unbusy() releases shared lock on F
374 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
375 * Attempt to lock A (instead of vp_crossmp) while D is held would
376 * violate the global order, causing deadlocks.
378 * dounmount() locks B while F is drained.
381 vfs_busy(struct mount *mp, int flags)
384 MPASS((flags & ~MBF_MASK) == 0);
385 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
390 * If mount point is currenly being unmounted, sleep until the
391 * mount point fate is decided. If thread doing the unmounting fails,
392 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
393 * that this mount point has survived the unmount attempt and vfs_busy
394 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
395 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
396 * about to be really destroyed. vfs_busy needs to release its
397 * reference on the mount point in this case and return with ENOENT,
398 * telling the caller that mount mount it tried to busy is no longer
401 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
402 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
405 CTR1(KTR_VFS, "%s: failed busying before sleeping",
409 if (flags & MBF_MNTLSTLOCK)
410 mtx_unlock(&mountlist_mtx);
411 mp->mnt_kern_flag |= MNTK_MWAIT;
412 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
413 if (flags & MBF_MNTLSTLOCK)
414 mtx_lock(&mountlist_mtx);
417 if (flags & MBF_MNTLSTLOCK)
418 mtx_unlock(&mountlist_mtx);
425 * Free a busy filesystem.
428 vfs_unbusy(struct mount *mp)
431 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
434 KASSERT(mp->mnt_lockref > 0, ("negative mnt_lockref"));
436 if (mp->mnt_lockref == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
437 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
438 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
439 mp->mnt_kern_flag &= ~MNTK_DRAINING;
440 wakeup(&mp->mnt_lockref);
446 * Lookup a mount point by filesystem identifier.
449 vfs_getvfs(fsid_t *fsid)
453 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
454 mtx_lock(&mountlist_mtx);
455 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
456 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
457 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
459 mtx_unlock(&mountlist_mtx);
463 mtx_unlock(&mountlist_mtx);
464 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
465 return ((struct mount *) 0);
469 * Lookup a mount point by filesystem identifier, busying it before
473 vfs_busyfs(fsid_t *fsid)
478 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
479 mtx_lock(&mountlist_mtx);
480 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
481 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
482 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
483 error = vfs_busy(mp, MBF_MNTLSTLOCK);
485 mtx_unlock(&mountlist_mtx);
491 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
492 mtx_unlock(&mountlist_mtx);
493 return ((struct mount *) 0);
497 * Check if a user can access privileged mount options.
500 vfs_suser(struct mount *mp, struct thread *td)
505 * If the thread is jailed, but this is not a jail-friendly file
506 * system, deny immediately.
508 if (!(mp->mnt_vfc->vfc_flags & VFCF_JAIL) && jailed(td->td_ucred))
512 * If the file system was mounted outside the jail of the calling
513 * thread, deny immediately.
515 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
519 * If file system supports delegated administration, we don't check
520 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
521 * by the file system itself.
522 * If this is not the user that did original mount, we check for
523 * the PRIV_VFS_MOUNT_OWNER privilege.
525 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
526 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
527 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
534 * Get a new unique fsid. Try to make its val[0] unique, since this value
535 * will be used to create fake device numbers for stat(). Also try (but
536 * not so hard) make its val[0] unique mod 2^16, since some emulators only
537 * support 16-bit device numbers. We end up with unique val[0]'s for the
538 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
540 * Keep in mind that several mounts may be running in parallel. Starting
541 * the search one past where the previous search terminated is both a
542 * micro-optimization and a defense against returning the same fsid to
546 vfs_getnewfsid(struct mount *mp)
548 static uint16_t mntid_base;
553 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
554 mtx_lock(&mntid_mtx);
555 mtype = mp->mnt_vfc->vfc_typenum;
556 tfsid.val[1] = mtype;
557 mtype = (mtype & 0xFF) << 24;
559 tfsid.val[0] = makedev(255,
560 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
562 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
566 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
567 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
568 mtx_unlock(&mntid_mtx);
572 * Knob to control the precision of file timestamps:
574 * 0 = seconds only; nanoseconds zeroed.
575 * 1 = seconds and nanoseconds, accurate within 1/HZ.
576 * 2 = seconds and nanoseconds, truncated to microseconds.
577 * >=3 = seconds and nanoseconds, maximum precision.
579 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
581 static int timestamp_precision = TSP_SEC;
582 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
583 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
584 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to ms, "
585 "3+: sec + ns (max. precision))");
588 * Get a current timestamp.
591 vfs_timestamp(struct timespec *tsp)
595 switch (timestamp_precision) {
597 tsp->tv_sec = time_second;
605 TIMEVAL_TO_TIMESPEC(&tv, tsp);
615 * Set vnode attributes to VNOVAL
618 vattr_null(struct vattr *vap)
622 vap->va_size = VNOVAL;
623 vap->va_bytes = VNOVAL;
624 vap->va_mode = VNOVAL;
625 vap->va_nlink = VNOVAL;
626 vap->va_uid = VNOVAL;
627 vap->va_gid = VNOVAL;
628 vap->va_fsid = VNOVAL;
629 vap->va_fileid = VNOVAL;
630 vap->va_blocksize = VNOVAL;
631 vap->va_rdev = VNOVAL;
632 vap->va_atime.tv_sec = VNOVAL;
633 vap->va_atime.tv_nsec = VNOVAL;
634 vap->va_mtime.tv_sec = VNOVAL;
635 vap->va_mtime.tv_nsec = VNOVAL;
636 vap->va_ctime.tv_sec = VNOVAL;
637 vap->va_ctime.tv_nsec = VNOVAL;
638 vap->va_birthtime.tv_sec = VNOVAL;
639 vap->va_birthtime.tv_nsec = VNOVAL;
640 vap->va_flags = VNOVAL;
641 vap->va_gen = VNOVAL;
646 * This routine is called when we have too many vnodes. It attempts
647 * to free <count> vnodes and will potentially free vnodes that still
648 * have VM backing store (VM backing store is typically the cause
649 * of a vnode blowout so we want to do this). Therefore, this operation
650 * is not considered cheap.
652 * A number of conditions may prevent a vnode from being reclaimed.
653 * the buffer cache may have references on the vnode, a directory
654 * vnode may still have references due to the namei cache representing
655 * underlying files, or the vnode may be in active use. It is not
656 * desireable to reuse such vnodes. These conditions may cause the
657 * number of vnodes to reach some minimum value regardless of what
658 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
661 vlrureclaim(struct mount *mp)
670 * Calculate the trigger point, don't allow user
671 * screwups to blow us up. This prevents us from
672 * recycling vnodes with lots of resident pages. We
673 * aren't trying to free memory, we are trying to
676 usevnodes = desiredvnodes;
679 trigger = cnt.v_page_count * 2 / usevnodes;
681 vn_start_write(NULL, &mp, V_WAIT);
683 count = mp->mnt_nvnodelistsize / 10 + 1;
685 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
686 while (vp != NULL && vp->v_type == VMARKER)
687 vp = TAILQ_NEXT(vp, v_nmntvnodes);
690 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
691 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
696 * If it's been deconstructed already, it's still
697 * referenced, or it exceeds the trigger, skip it.
699 if (vp->v_usecount ||
700 (!vlru_allow_cache_src &&
701 !LIST_EMPTY(&(vp)->v_cache_src)) ||
702 (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
703 vp->v_object->resident_page_count > trigger)) {
709 if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT)) {
711 goto next_iter_mntunlocked;
715 * v_usecount may have been bumped after VOP_LOCK() dropped
716 * the vnode interlock and before it was locked again.
718 * It is not necessary to recheck VI_DOOMED because it can
719 * only be set by another thread that holds both the vnode
720 * lock and vnode interlock. If another thread has the
721 * vnode lock before we get to VOP_LOCK() and obtains the
722 * vnode interlock after VOP_LOCK() drops the vnode
723 * interlock, the other thread will be unable to drop the
724 * vnode lock before our VOP_LOCK() call fails.
726 if (vp->v_usecount ||
727 (!vlru_allow_cache_src &&
728 !LIST_EMPTY(&(vp)->v_cache_src)) ||
729 (vp->v_object != NULL &&
730 vp->v_object->resident_page_count > trigger)) {
731 VOP_UNLOCK(vp, LK_INTERLOCK);
732 goto next_iter_mntunlocked;
734 KASSERT((vp->v_iflag & VI_DOOMED) == 0,
735 ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
740 next_iter_mntunlocked:
749 kern_yield(PRI_UNCHANGED);
754 vn_finished_write(mp);
759 * Attempt to keep the free list at wantfreevnodes length.
762 vnlru_free(int count)
767 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
768 for (; count > 0; count--) {
769 vp = TAILQ_FIRST(&vnode_free_list);
771 * The list can be modified while the free_list_mtx
772 * has been dropped and vp could be NULL here.
776 VNASSERT(vp->v_op != NULL, vp,
777 ("vnlru_free: vnode already reclaimed."));
778 KASSERT((vp->v_iflag & VI_FREE) != 0,
779 ("Removing vnode not on freelist"));
780 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
781 ("Mangling active vnode"));
782 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
784 * Don't recycle if we can't get the interlock.
786 if (!VI_TRYLOCK(vp)) {
787 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_actfreelist);
790 VNASSERT(VCANRECYCLE(vp), vp,
791 ("vp inconsistent on freelist"));
793 vp->v_iflag &= ~VI_FREE;
795 mtx_unlock(&vnode_free_list_mtx);
797 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
799 VFS_UNLOCK_GIANT(vfslocked);
801 * If the recycled succeeded this vdrop will actually free
802 * the vnode. If not it will simply place it back on
806 mtx_lock(&vnode_free_list_mtx);
810 * Attempt to recycle vnodes in a context that is always safe to block.
811 * Calling vlrurecycle() from the bowels of filesystem code has some
812 * interesting deadlock problems.
814 static struct proc *vnlruproc;
815 static int vnlruproc_sig;
820 struct mount *mp, *nmp;
822 struct proc *p = vnlruproc;
824 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, p,
828 kproc_suspend_check(p);
829 mtx_lock(&vnode_free_list_mtx);
830 if (freevnodes > wantfreevnodes)
831 vnlru_free(freevnodes - wantfreevnodes);
832 if (numvnodes <= desiredvnodes * 9 / 10) {
834 wakeup(&vnlruproc_sig);
835 msleep(vnlruproc, &vnode_free_list_mtx,
836 PVFS|PDROP, "vlruwt", hz);
839 mtx_unlock(&vnode_free_list_mtx);
841 mtx_lock(&mountlist_mtx);
842 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
843 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK)) {
844 nmp = TAILQ_NEXT(mp, mnt_list);
847 vfslocked = VFS_LOCK_GIANT(mp);
848 done += vlrureclaim(mp);
849 VFS_UNLOCK_GIANT(vfslocked);
850 mtx_lock(&mountlist_mtx);
851 nmp = TAILQ_NEXT(mp, mnt_list);
854 mtx_unlock(&mountlist_mtx);
857 /* These messages are temporary debugging aids */
858 if (vnlru_nowhere < 5)
859 printf("vnlru process getting nowhere..\n");
860 else if (vnlru_nowhere == 5)
861 printf("vnlru process messages stopped.\n");
864 tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
866 kern_yield(PRI_UNCHANGED);
870 static struct kproc_desc vnlru_kp = {
875 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
879 * Routines having to do with the management of the vnode table.
883 * Try to recycle a freed vnode. We abort if anyone picks up a reference
884 * before we actually vgone(). This function must be called with the vnode
885 * held to prevent the vnode from being returned to the free list midway
889 vtryrecycle(struct vnode *vp)
893 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
894 VNASSERT(vp->v_holdcnt, vp,
895 ("vtryrecycle: Recycling vp %p without a reference.", vp));
897 * This vnode may found and locked via some other list, if so we
898 * can't recycle it yet.
900 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
902 "%s: impossible to recycle, vp %p lock is already held",
904 return (EWOULDBLOCK);
907 * Don't recycle if its filesystem is being suspended.
909 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
912 "%s: impossible to recycle, cannot start the write for %p",
917 * If we got this far, we need to acquire the interlock and see if
918 * anyone picked up this vnode from another list. If not, we will
919 * mark it with DOOMED via vgonel() so that anyone who does find it
923 if (vp->v_usecount) {
924 VOP_UNLOCK(vp, LK_INTERLOCK);
925 vn_finished_write(vnmp);
927 "%s: impossible to recycle, %p is already referenced",
931 if ((vp->v_iflag & VI_DOOMED) == 0)
933 VOP_UNLOCK(vp, LK_INTERLOCK);
934 vn_finished_write(vnmp);
939 * Return the next vnode from the free list.
942 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
945 struct vnode *vp = NULL;
948 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
949 mtx_lock(&vnode_free_list_mtx);
951 * Lend our context to reclaim vnodes if they've exceeded the max.
953 if (freevnodes > wantfreevnodes)
956 * Wait for available vnodes.
958 if (numvnodes > desiredvnodes) {
959 if (mp != NULL && (mp->mnt_kern_flag & MNTK_SUSPEND)) {
961 * File system is beeing suspended, we cannot risk a
962 * deadlock here, so allocate new vnode anyway.
964 if (freevnodes > wantfreevnodes)
965 vnlru_free(freevnodes - wantfreevnodes);
968 if (vnlruproc_sig == 0) {
969 vnlruproc_sig = 1; /* avoid unnecessary wakeups */
972 msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
974 #if 0 /* XXX Not all VFS_VGET/ffs_vget callers check returns. */
975 if (numvnodes > desiredvnodes) {
976 mtx_unlock(&vnode_free_list_mtx);
983 mtx_unlock(&vnode_free_list_mtx);
984 vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK|M_ZERO);
988 vp->v_vnlock = &vp->v_lock;
989 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
991 * By default, don't allow shared locks unless filesystems
994 lockinit(vp->v_vnlock, PVFS, tag, VLKTIMEOUT, LK_NOSHARE);
1000 mtx_init(BO_MTX(bo), "bufobj interlock", NULL, MTX_DEF);
1001 bo->bo_ops = &buf_ops_bio;
1002 bo->bo_private = vp;
1003 TAILQ_INIT(&bo->bo_clean.bv_hd);
1004 TAILQ_INIT(&bo->bo_dirty.bv_hd);
1006 * Initialize namecache.
1008 LIST_INIT(&vp->v_cache_src);
1009 TAILQ_INIT(&vp->v_cache_dst);
1011 * Finalize various vnode identity bits.
1016 v_incr_usecount(vp);
1020 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1021 mac_vnode_associate_singlelabel(mp, vp);
1022 else if (mp == NULL && vops != &dead_vnodeops)
1023 printf("NULL mp in getnewvnode()\n");
1026 bo->bo_bsize = mp->mnt_stat.f_iosize;
1027 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1028 vp->v_vflag |= VV_NOKNOTE;
1036 * Delete from old mount point vnode list, if on one.
1039 delmntque(struct vnode *vp)
1049 KASSERT(mp->mnt_activevnodelistsize <= mp->mnt_nvnodelistsize,
1050 ("Active vnode list size %d > Vnode list size %d",
1051 mp->mnt_activevnodelistsize, mp->mnt_nvnodelistsize));
1052 active = vp->v_iflag & VI_ACTIVE;
1053 vp->v_iflag &= ~VI_ACTIVE;
1055 mtx_lock(&vnode_free_list_mtx);
1056 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp, v_actfreelist);
1057 mp->mnt_activevnodelistsize--;
1058 mtx_unlock(&vnode_free_list_mtx);
1062 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1063 ("bad mount point vnode list size"));
1064 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1065 mp->mnt_nvnodelistsize--;
1071 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1075 vp->v_op = &dead_vnodeops;
1076 /* XXX non mp-safe fs may still call insmntque with vnode
1078 if (!VOP_ISLOCKED(vp))
1079 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1085 * Insert into list of vnodes for the new mount point, if available.
1088 insmntque1(struct vnode *vp, struct mount *mp,
1089 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1093 KASSERT(vp->v_mount == NULL,
1094 ("insmntque: vnode already on per mount vnode list"));
1095 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1096 #ifdef DEBUG_VFS_LOCKS
1097 if (!VFS_NEEDSGIANT(mp))
1098 ASSERT_VOP_ELOCKED(vp,
1099 "insmntque: mp-safe fs and non-locked vp");
1102 * We acquire the vnode interlock early to ensure that the
1103 * vnode cannot be recycled by another process releasing a
1104 * holdcnt on it before we get it on both the vnode list
1105 * and the active vnode list. The mount mutex protects only
1106 * manipulation of the vnode list and the vnode freelist
1107 * mutex protects only manipulation of the active vnode list.
1108 * Hence the need to hold the vnode interlock throughout.
1112 if ((mp->mnt_kern_flag & MNTK_NOINSMNTQ) != 0 &&
1113 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1114 mp->mnt_nvnodelistsize == 0)) {
1115 locked = VOP_ISLOCKED(vp);
1116 if (!locked || (locked == LK_EXCLUSIVE &&
1117 (vp->v_vflag & VV_FORCEINSMQ) == 0)) {
1127 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1128 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1129 ("neg mount point vnode list size"));
1130 mp->mnt_nvnodelistsize++;
1131 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1132 ("Activating already active vnode"));
1133 vp->v_iflag |= VI_ACTIVE;
1134 mtx_lock(&vnode_free_list_mtx);
1135 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
1136 mp->mnt_activevnodelistsize++;
1137 mtx_unlock(&vnode_free_list_mtx);
1144 insmntque(struct vnode *vp, struct mount *mp)
1147 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1151 * Flush out and invalidate all buffers associated with a bufobj
1152 * Called with the underlying object locked.
1155 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1160 if (flags & V_SAVE) {
1161 error = bufobj_wwait(bo, slpflag, slptimeo);
1166 if (bo->bo_dirty.bv_cnt > 0) {
1168 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1171 * XXX We could save a lock/unlock if this was only
1172 * enabled under INVARIANTS
1175 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1176 panic("vinvalbuf: dirty bufs");
1180 * If you alter this loop please notice that interlock is dropped and
1181 * reacquired in flushbuflist. Special care is needed to ensure that
1182 * no race conditions occur from this.
1185 error = flushbuflist(&bo->bo_clean,
1186 flags, bo, slpflag, slptimeo);
1187 if (error == 0 && !(flags & V_CLEANONLY))
1188 error = flushbuflist(&bo->bo_dirty,
1189 flags, bo, slpflag, slptimeo);
1190 if (error != 0 && error != EAGAIN) {
1194 } while (error != 0);
1197 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1198 * have write I/O in-progress but if there is a VM object then the
1199 * VM object can also have read-I/O in-progress.
1202 bufobj_wwait(bo, 0, 0);
1204 if (bo->bo_object != NULL) {
1205 VM_OBJECT_LOCK(bo->bo_object);
1206 vm_object_pip_wait(bo->bo_object, "bovlbx");
1207 VM_OBJECT_UNLOCK(bo->bo_object);
1210 } while (bo->bo_numoutput > 0);
1214 * Destroy the copy in the VM cache, too.
1216 if (bo->bo_object != NULL &&
1217 (flags & (V_ALT | V_NORMAL | V_CLEANONLY)) == 0) {
1218 VM_OBJECT_LOCK(bo->bo_object);
1219 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1220 OBJPR_CLEANONLY : 0);
1221 VM_OBJECT_UNLOCK(bo->bo_object);
1226 if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY)) == 0 &&
1227 (bo->bo_dirty.bv_cnt > 0 || bo->bo_clean.bv_cnt > 0))
1228 panic("vinvalbuf: flush failed");
1235 * Flush out and invalidate all buffers associated with a vnode.
1236 * Called with the underlying object locked.
1239 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1242 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1243 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1244 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1248 * Flush out buffers on the specified list.
1252 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1255 struct buf *bp, *nbp;
1260 ASSERT_BO_LOCKED(bo);
1263 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1264 if (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA)) ||
1265 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0)) {
1271 lblkno = nbp->b_lblkno;
1272 xflags = nbp->b_xflags &
1273 (BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN);
1276 error = BUF_TIMELOCK(bp,
1277 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_MTX(bo),
1278 "flushbuf", slpflag, slptimeo);
1281 return (error != ENOLCK ? error : EAGAIN);
1283 KASSERT(bp->b_bufobj == bo,
1284 ("bp %p wrong b_bufobj %p should be %p",
1285 bp, bp->b_bufobj, bo));
1286 if (bp->b_bufobj != bo) { /* XXX: necessary ? */
1292 * XXX Since there are no node locks for NFS, I
1293 * believe there is a slight chance that a delayed
1294 * write will occur while sleeping just above, so
1297 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1302 bp->b_flags |= B_ASYNC;
1305 return (EAGAIN); /* XXX: why not loop ? */
1310 bp->b_flags |= (B_INVAL | B_RELBUF);
1311 bp->b_flags &= ~B_ASYNC;
1315 (nbp->b_bufobj != bo ||
1316 nbp->b_lblkno != lblkno ||
1318 (BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN)) != xflags))
1319 break; /* nbp invalid */
1325 * Truncate a file's buffer and pages to a specified length. This
1326 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
1330 vtruncbuf(struct vnode *vp, struct ucred *cred, off_t length, int blksize)
1332 struct buf *bp, *nbp;
1337 CTR5(KTR_VFS, "%s: vp %p with cred %p and block %d:%ju", __func__,
1338 vp, cred, blksize, (uintmax_t)length);
1341 * Round up to the *next* lbn.
1343 trunclbn = (length + blksize - 1) / blksize;
1345 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
1352 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
1353 if (bp->b_lblkno < trunclbn)
1356 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1357 BO_MTX(bo)) == ENOLCK)
1363 bp->b_flags |= (B_INVAL | B_RELBUF);
1364 bp->b_flags &= ~B_ASYNC;
1370 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
1371 (nbp->b_vp != vp) ||
1372 (nbp->b_flags & B_DELWRI))) {
1378 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1379 if (bp->b_lblkno < trunclbn)
1382 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1383 BO_MTX(bo)) == ENOLCK)
1388 bp->b_flags |= (B_INVAL | B_RELBUF);
1389 bp->b_flags &= ~B_ASYNC;
1395 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
1396 (nbp->b_vp != vp) ||
1397 (nbp->b_flags & B_DELWRI) == 0)) {
1406 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1407 if (bp->b_lblkno > 0)
1410 * Since we hold the vnode lock this should only
1411 * fail if we're racing with the buf daemon.
1414 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1415 BO_MTX(bo)) == ENOLCK) {
1418 VNASSERT((bp->b_flags & B_DELWRI), vp,
1419 ("buf(%p) on dirty queue without DELWRI", bp));
1430 bufobj_wwait(bo, 0, 0);
1432 vnode_pager_setsize(vp, length);
1438 * buf_splay() - splay tree core for the clean/dirty list of buffers in
1441 * NOTE: We have to deal with the special case of a background bitmap
1442 * buffer, a situation where two buffers will have the same logical
1443 * block offset. We want (1) only the foreground buffer to be accessed
1444 * in a lookup and (2) must differentiate between the foreground and
1445 * background buffer in the splay tree algorithm because the splay
1446 * tree cannot normally handle multiple entities with the same 'index'.
1447 * We accomplish this by adding differentiating flags to the splay tree's
1452 buf_splay(daddr_t lblkno, b_xflags_t xflags, struct buf *root)
1455 struct buf *lefttreemax, *righttreemin, *y;
1459 lefttreemax = righttreemin = &dummy;
1461 if (lblkno < root->b_lblkno ||
1462 (lblkno == root->b_lblkno &&
1463 (xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
1464 if ((y = root->b_left) == NULL)
1466 if (lblkno < y->b_lblkno) {
1468 root->b_left = y->b_right;
1471 if ((y = root->b_left) == NULL)
1474 /* Link into the new root's right tree. */
1475 righttreemin->b_left = root;
1476 righttreemin = root;
1477 } else if (lblkno > root->b_lblkno ||
1478 (lblkno == root->b_lblkno &&
1479 (xflags & BX_BKGRDMARKER) > (root->b_xflags & BX_BKGRDMARKER))) {
1480 if ((y = root->b_right) == NULL)
1482 if (lblkno > y->b_lblkno) {
1484 root->b_right = y->b_left;
1487 if ((y = root->b_right) == NULL)
1490 /* Link into the new root's left tree. */
1491 lefttreemax->b_right = root;
1498 /* Assemble the new root. */
1499 lefttreemax->b_right = root->b_left;
1500 righttreemin->b_left = root->b_right;
1501 root->b_left = dummy.b_right;
1502 root->b_right = dummy.b_left;
1507 buf_vlist_remove(struct buf *bp)
1512 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1513 ASSERT_BO_LOCKED(bp->b_bufobj);
1514 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
1515 (BX_VNDIRTY|BX_VNCLEAN),
1516 ("buf_vlist_remove: Buf %p is on two lists", bp));
1517 if (bp->b_xflags & BX_VNDIRTY)
1518 bv = &bp->b_bufobj->bo_dirty;
1520 bv = &bp->b_bufobj->bo_clean;
1521 if (bp != bv->bv_root) {
1522 root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1523 KASSERT(root == bp, ("splay lookup failed in remove"));
1525 if (bp->b_left == NULL) {
1528 root = buf_splay(bp->b_lblkno, bp->b_xflags, bp->b_left);
1529 root->b_right = bp->b_right;
1532 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
1534 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1538 * Add the buffer to the sorted clean or dirty block list using a
1539 * splay tree algorithm.
1541 * NOTE: xflags is passed as a constant, optimizing this inline function!
1544 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
1549 ASSERT_BO_LOCKED(bo);
1550 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
1551 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
1552 bp->b_xflags |= xflags;
1553 if (xflags & BX_VNDIRTY)
1558 root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1562 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
1563 } else if (bp->b_lblkno < root->b_lblkno ||
1564 (bp->b_lblkno == root->b_lblkno &&
1565 (bp->b_xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
1566 bp->b_left = root->b_left;
1568 root->b_left = NULL;
1569 TAILQ_INSERT_BEFORE(root, bp, b_bobufs);
1571 bp->b_right = root->b_right;
1573 root->b_right = NULL;
1574 TAILQ_INSERT_AFTER(&bv->bv_hd, root, bp, b_bobufs);
1581 * Lookup a buffer using the splay tree. Note that we specifically avoid
1582 * shadow buffers used in background bitmap writes.
1584 * This code isn't quite efficient as it could be because we are maintaining
1585 * two sorted lists and do not know which list the block resides in.
1587 * During a "make buildworld" the desired buffer is found at one of
1588 * the roots more than 60% of the time. Thus, checking both roots
1589 * before performing either splay eliminates unnecessary splays on the
1590 * first tree splayed.
1593 gbincore(struct bufobj *bo, daddr_t lblkno)
1597 ASSERT_BO_LOCKED(bo);
1598 if ((bp = bo->bo_clean.bv_root) != NULL &&
1599 bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1601 if ((bp = bo->bo_dirty.bv_root) != NULL &&
1602 bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1604 if ((bp = bo->bo_clean.bv_root) != NULL) {
1605 bo->bo_clean.bv_root = bp = buf_splay(lblkno, 0, bp);
1606 if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1609 if ((bp = bo->bo_dirty.bv_root) != NULL) {
1610 bo->bo_dirty.bv_root = bp = buf_splay(lblkno, 0, bp);
1611 if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1618 * Associate a buffer with a vnode.
1621 bgetvp(struct vnode *vp, struct buf *bp)
1626 ASSERT_BO_LOCKED(bo);
1627 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
1629 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
1630 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
1631 ("bgetvp: bp already attached! %p", bp));
1634 if (VFS_NEEDSGIANT(vp->v_mount) || bo->bo_flag & BO_NEEDSGIANT)
1635 bp->b_flags |= B_NEEDSGIANT;
1639 * Insert onto list for new vnode.
1641 buf_vlist_add(bp, bo, BX_VNCLEAN);
1645 * Disassociate a buffer from a vnode.
1648 brelvp(struct buf *bp)
1653 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1654 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1657 * Delete from old vnode list, if on one.
1659 vp = bp->b_vp; /* XXX */
1662 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1663 buf_vlist_remove(bp);
1665 panic("brelvp: Buffer %p not on queue.", bp);
1666 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1667 bo->bo_flag &= ~BO_ONWORKLST;
1668 mtx_lock(&sync_mtx);
1669 LIST_REMOVE(bo, bo_synclist);
1670 syncer_worklist_len--;
1671 mtx_unlock(&sync_mtx);
1673 bp->b_flags &= ~B_NEEDSGIANT;
1675 bp->b_bufobj = NULL;
1681 * Add an item to the syncer work queue.
1684 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
1688 ASSERT_BO_LOCKED(bo);
1690 mtx_lock(&sync_mtx);
1691 if (bo->bo_flag & BO_ONWORKLST)
1692 LIST_REMOVE(bo, bo_synclist);
1694 bo->bo_flag |= BO_ONWORKLST;
1695 syncer_worklist_len++;
1698 if (delay > syncer_maxdelay - 2)
1699 delay = syncer_maxdelay - 2;
1700 slot = (syncer_delayno + delay) & syncer_mask;
1702 queue = VFS_NEEDSGIANT(bo->__bo_vnode->v_mount) ? WI_GIANTQ :
1704 LIST_INSERT_HEAD(&syncer_workitem_pending[queue][slot], bo,
1706 mtx_unlock(&sync_mtx);
1710 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
1714 mtx_lock(&sync_mtx);
1715 len = syncer_worklist_len - sync_vnode_count;
1716 mtx_unlock(&sync_mtx);
1717 error = SYSCTL_OUT(req, &len, sizeof(len));
1721 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
1722 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
1724 static struct proc *updateproc;
1725 static void sched_sync(void);
1726 static struct kproc_desc up_kp = {
1731 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
1734 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
1739 *bo = LIST_FIRST(slp);
1742 vp = (*bo)->__bo_vnode; /* XXX */
1743 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
1746 * We use vhold in case the vnode does not
1747 * successfully sync. vhold prevents the vnode from
1748 * going away when we unlock the sync_mtx so that
1749 * we can acquire the vnode interlock.
1752 mtx_unlock(&sync_mtx);
1754 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1756 mtx_lock(&sync_mtx);
1757 return (*bo == LIST_FIRST(slp));
1759 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1760 (void) VOP_FSYNC(vp, MNT_LAZY, td);
1762 vn_finished_write(mp);
1764 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
1766 * Put us back on the worklist. The worklist
1767 * routine will remove us from our current
1768 * position and then add us back in at a later
1771 vn_syncer_add_to_worklist(*bo, syncdelay);
1775 mtx_lock(&sync_mtx);
1780 * System filesystem synchronizer daemon.
1785 struct synclist *gnext, *next;
1786 struct synclist *gslp, *slp;
1789 struct thread *td = curthread;
1791 int net_worklist_len;
1792 int syncer_final_iter;
1797 syncer_final_iter = 0;
1799 syncer_state = SYNCER_RUNNING;
1800 starttime = time_uptime;
1801 td->td_pflags |= TDP_NORUNNINGBUF;
1803 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
1806 mtx_lock(&sync_mtx);
1808 if (syncer_state == SYNCER_FINAL_DELAY &&
1809 syncer_final_iter == 0) {
1810 mtx_unlock(&sync_mtx);
1811 kproc_suspend_check(td->td_proc);
1812 mtx_lock(&sync_mtx);
1814 net_worklist_len = syncer_worklist_len - sync_vnode_count;
1815 if (syncer_state != SYNCER_RUNNING &&
1816 starttime != time_uptime) {
1818 printf("\nSyncing disks, vnodes remaining...");
1821 printf("%d ", net_worklist_len);
1823 starttime = time_uptime;
1826 * Push files whose dirty time has expired. Be careful
1827 * of interrupt race on slp queue.
1829 * Skip over empty worklist slots when shutting down.
1832 slp = &syncer_workitem_pending[WI_MPSAFEQ][syncer_delayno];
1833 gslp = &syncer_workitem_pending[WI_GIANTQ][syncer_delayno];
1834 syncer_delayno += 1;
1835 if (syncer_delayno == syncer_maxdelay)
1837 next = &syncer_workitem_pending[WI_MPSAFEQ][syncer_delayno];
1838 gnext = &syncer_workitem_pending[WI_GIANTQ][syncer_delayno];
1840 * If the worklist has wrapped since the
1841 * it was emptied of all but syncer vnodes,
1842 * switch to the FINAL_DELAY state and run
1843 * for one more second.
1845 if (syncer_state == SYNCER_SHUTTING_DOWN &&
1846 net_worklist_len == 0 &&
1847 last_work_seen == syncer_delayno) {
1848 syncer_state = SYNCER_FINAL_DELAY;
1849 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
1851 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
1852 LIST_EMPTY(gslp) && syncer_worklist_len > 0);
1855 * Keep track of the last time there was anything
1856 * on the worklist other than syncer vnodes.
1857 * Return to the SHUTTING_DOWN state if any
1860 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
1861 last_work_seen = syncer_delayno;
1862 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
1863 syncer_state = SYNCER_SHUTTING_DOWN;
1864 while (!LIST_EMPTY(slp)) {
1865 error = sync_vnode(slp, &bo, td);
1867 LIST_REMOVE(bo, bo_synclist);
1868 LIST_INSERT_HEAD(next, bo, bo_synclist);
1872 if (first_printf == 0)
1873 wdog_kern_pat(WD_LASTVAL);
1876 if (!LIST_EMPTY(gslp)) {
1877 mtx_unlock(&sync_mtx);
1879 mtx_lock(&sync_mtx);
1880 while (!LIST_EMPTY(gslp)) {
1881 error = sync_vnode(gslp, &bo, td);
1883 LIST_REMOVE(bo, bo_synclist);
1884 LIST_INSERT_HEAD(gnext, bo,
1891 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
1892 syncer_final_iter--;
1894 * The variable rushjob allows the kernel to speed up the
1895 * processing of the filesystem syncer process. A rushjob
1896 * value of N tells the filesystem syncer to process the next
1897 * N seconds worth of work on its queue ASAP. Currently rushjob
1898 * is used by the soft update code to speed up the filesystem
1899 * syncer process when the incore state is getting so far
1900 * ahead of the disk that the kernel memory pool is being
1901 * threatened with exhaustion.
1908 * Just sleep for a short period of time between
1909 * iterations when shutting down to allow some I/O
1912 * If it has taken us less than a second to process the
1913 * current work, then wait. Otherwise start right over
1914 * again. We can still lose time if any single round
1915 * takes more than two seconds, but it does not really
1916 * matter as we are just trying to generally pace the
1917 * filesystem activity.
1919 if (syncer_state != SYNCER_RUNNING ||
1920 time_uptime == starttime) {
1922 sched_prio(td, PPAUSE);
1925 if (syncer_state != SYNCER_RUNNING)
1926 cv_timedwait(&sync_wakeup, &sync_mtx,
1927 hz / SYNCER_SHUTDOWN_SPEEDUP);
1928 else if (time_uptime == starttime)
1929 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
1934 * Request the syncer daemon to speed up its work.
1935 * We never push it to speed up more than half of its
1936 * normal turn time, otherwise it could take over the cpu.
1939 speedup_syncer(void)
1943 mtx_lock(&sync_mtx);
1944 if (rushjob < syncdelay / 2) {
1946 stat_rush_requests += 1;
1949 mtx_unlock(&sync_mtx);
1950 cv_broadcast(&sync_wakeup);
1955 * Tell the syncer to speed up its work and run though its work
1956 * list several times, then tell it to shut down.
1959 syncer_shutdown(void *arg, int howto)
1962 if (howto & RB_NOSYNC)
1964 mtx_lock(&sync_mtx);
1965 syncer_state = SYNCER_SHUTTING_DOWN;
1967 mtx_unlock(&sync_mtx);
1968 cv_broadcast(&sync_wakeup);
1969 kproc_shutdown(arg, howto);
1973 * Reassign a buffer from one vnode to another.
1974 * Used to assign file specific control information
1975 * (indirect blocks) to the vnode to which they belong.
1978 reassignbuf(struct buf *bp)
1991 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
1992 bp, bp->b_vp, bp->b_flags);
1994 * B_PAGING flagged buffers cannot be reassigned because their vp
1995 * is not fully linked in.
1997 if (bp->b_flags & B_PAGING)
1998 panic("cannot reassign paging buffer");
2001 * Delete from old vnode list, if on one.
2004 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2005 buf_vlist_remove(bp);
2007 panic("reassignbuf: Buffer %p not on queue.", bp);
2009 * If dirty, put on list of dirty buffers; otherwise insert onto list
2012 if (bp->b_flags & B_DELWRI) {
2013 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2014 switch (vp->v_type) {
2024 vn_syncer_add_to_worklist(bo, delay);
2026 buf_vlist_add(bp, bo, BX_VNDIRTY);
2028 buf_vlist_add(bp, bo, BX_VNCLEAN);
2030 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2031 mtx_lock(&sync_mtx);
2032 LIST_REMOVE(bo, bo_synclist);
2033 syncer_worklist_len--;
2034 mtx_unlock(&sync_mtx);
2035 bo->bo_flag &= ~BO_ONWORKLST;
2040 bp = TAILQ_FIRST(&bv->bv_hd);
2041 KASSERT(bp == NULL || bp->b_bufobj == bo,
2042 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2043 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2044 KASSERT(bp == NULL || bp->b_bufobj == bo,
2045 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2047 bp = TAILQ_FIRST(&bv->bv_hd);
2048 KASSERT(bp == NULL || bp->b_bufobj == bo,
2049 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2050 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2051 KASSERT(bp == NULL || bp->b_bufobj == bo,
2052 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2058 * Increment the use and hold counts on the vnode, taking care to reference
2059 * the driver's usecount if this is a chardev. The vholdl() will remove
2060 * the vnode from the free list if it is presently free. Requires the
2061 * vnode interlock and returns with it held.
2064 v_incr_usecount(struct vnode *vp)
2067 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2069 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2071 vp->v_rdev->si_usecount++;
2078 * Turn a holdcnt into a use+holdcnt such that only one call to
2079 * v_decr_usecount is needed.
2082 v_upgrade_usecount(struct vnode *vp)
2085 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2087 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2089 vp->v_rdev->si_usecount++;
2095 * Decrement the vnode use and hold count along with the driver's usecount
2096 * if this is a chardev. The vdropl() below releases the vnode interlock
2097 * as it may free the vnode.
2100 v_decr_usecount(struct vnode *vp)
2103 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2104 VNASSERT(vp->v_usecount > 0, vp,
2105 ("v_decr_usecount: negative usecount"));
2106 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2108 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2110 vp->v_rdev->si_usecount--;
2117 * Decrement only the use count and driver use count. This is intended to
2118 * be paired with a follow on vdropl() to release the remaining hold count.
2119 * In this way we may vgone() a vnode with a 0 usecount without risk of
2120 * having it end up on a free list because the hold count is kept above 0.
2123 v_decr_useonly(struct vnode *vp)
2126 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2127 VNASSERT(vp->v_usecount > 0, vp,
2128 ("v_decr_useonly: negative usecount"));
2129 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2131 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2133 vp->v_rdev->si_usecount--;
2139 * Grab a particular vnode from the free list, increment its
2140 * reference count and lock it. VI_DOOMED is set if the vnode
2141 * is being destroyed. Only callers who specify LK_RETRY will
2142 * see doomed vnodes. If inactive processing was delayed in
2143 * vput try to do it here.
2146 vget(struct vnode *vp, int flags, struct thread *td)
2151 VFS_ASSERT_GIANT(vp->v_mount);
2152 VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2153 ("vget: invalid lock operation"));
2154 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2156 if ((flags & LK_INTERLOCK) == 0)
2159 if ((error = vn_lock(vp, flags | LK_INTERLOCK)) != 0) {
2161 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2165 if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0)
2166 panic("vget: vn_lock failed to return ENOENT\n");
2168 /* Upgrade our holdcnt to a usecount. */
2169 v_upgrade_usecount(vp);
2171 * We don't guarantee that any particular close will
2172 * trigger inactive processing so just make a best effort
2173 * here at preventing a reference to a removed file. If
2174 * we don't succeed no harm is done.
2176 if (vp->v_iflag & VI_OWEINACT) {
2177 if (VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2178 (flags & LK_NOWAIT) == 0)
2180 vp->v_iflag &= ~VI_OWEINACT;
2187 * Increase the reference count of a vnode.
2190 vref(struct vnode *vp)
2193 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2195 v_incr_usecount(vp);
2200 * Return reference count of a vnode.
2202 * The results of this call are only guaranteed when some mechanism other
2203 * than the VI lock is used to stop other processes from gaining references
2204 * to the vnode. This may be the case if the caller holds the only reference.
2205 * This is also useful when stale data is acceptable as race conditions may
2206 * be accounted for by some other means.
2209 vrefcnt(struct vnode *vp)
2214 usecnt = vp->v_usecount;
2220 #define VPUTX_VRELE 1
2221 #define VPUTX_VPUT 2
2222 #define VPUTX_VUNREF 3
2225 vputx(struct vnode *vp, int func)
2229 KASSERT(vp != NULL, ("vputx: null vp"));
2230 if (func == VPUTX_VUNREF)
2231 ASSERT_VOP_LOCKED(vp, "vunref");
2232 else if (func == VPUTX_VPUT)
2233 ASSERT_VOP_LOCKED(vp, "vput");
2235 KASSERT(func == VPUTX_VRELE, ("vputx: wrong func"));
2236 VFS_ASSERT_GIANT(vp->v_mount);
2237 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2240 /* Skip this v_writecount check if we're going to panic below. */
2241 VNASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1, vp,
2242 ("vputx: missed vn_close"));
2245 if (vp->v_usecount > 1 || ((vp->v_iflag & VI_DOINGINACT) &&
2246 vp->v_usecount == 1)) {
2247 if (func == VPUTX_VPUT)
2249 v_decr_usecount(vp);
2253 if (vp->v_usecount != 1) {
2254 vprint("vputx: negative ref count", vp);
2255 panic("vputx: negative ref cnt");
2257 CTR2(KTR_VFS, "%s: return vnode %p to the freelist", __func__, vp);
2259 * We want to hold the vnode until the inactive finishes to
2260 * prevent vgone() races. We drop the use count here and the
2261 * hold count below when we're done.
2265 * We must call VOP_INACTIVE with the node locked. Mark
2266 * as VI_DOINGINACT to avoid recursion.
2268 vp->v_iflag |= VI_OWEINACT;
2271 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
2275 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2276 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
2282 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
2286 if (vp->v_usecount > 0)
2287 vp->v_iflag &= ~VI_OWEINACT;
2289 if (vp->v_iflag & VI_OWEINACT)
2290 vinactive(vp, curthread);
2291 if (func != VPUTX_VUNREF)
2298 * Vnode put/release.
2299 * If count drops to zero, call inactive routine and return to freelist.
2302 vrele(struct vnode *vp)
2305 vputx(vp, VPUTX_VRELE);
2309 * Release an already locked vnode. This give the same effects as
2310 * unlock+vrele(), but takes less time and avoids releasing and
2311 * re-aquiring the lock (as vrele() acquires the lock internally.)
2314 vput(struct vnode *vp)
2317 vputx(vp, VPUTX_VPUT);
2321 * Release an exclusively locked vnode. Do not unlock the vnode lock.
2324 vunref(struct vnode *vp)
2327 vputx(vp, VPUTX_VUNREF);
2331 * Somebody doesn't want the vnode recycled.
2334 vhold(struct vnode *vp)
2343 * Increase the hold count and activate if this is the first reference.
2346 vholdl(struct vnode *vp)
2350 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2352 if (!VSHOULDBUSY(vp))
2354 ASSERT_VI_LOCKED(vp, "vholdl");
2355 VNASSERT((vp->v_iflag & VI_FREE) != 0, vp, ("vnode not free"));
2356 VNASSERT(vp->v_op != NULL, vp, ("vholdl: vnode already reclaimed."));
2358 * Remove a vnode from the free list, mark it as in use,
2359 * and put it on the active list.
2361 mtx_lock(&vnode_free_list_mtx);
2362 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
2364 vp->v_iflag &= ~(VI_FREE|VI_AGE);
2365 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
2366 ("Activating already active vnode"));
2367 vp->v_iflag |= VI_ACTIVE;
2369 TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
2370 mp->mnt_activevnodelistsize++;
2371 mtx_unlock(&vnode_free_list_mtx);
2375 * Note that there is one less who cares about this vnode.
2376 * vdrop() is the opposite of vhold().
2379 vdrop(struct vnode *vp)
2387 * Drop the hold count of the vnode. If this is the last reference to
2388 * the vnode we place it on the free list unless it has been vgone'd
2389 * (marked VI_DOOMED) in which case we will free it.
2392 vdropl(struct vnode *vp)
2398 ASSERT_VI_LOCKED(vp, "vdropl");
2399 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2400 if (vp->v_holdcnt <= 0)
2401 panic("vdrop: holdcnt %d", vp->v_holdcnt);
2403 if (vp->v_holdcnt > 0) {
2407 if ((vp->v_iflag & VI_DOOMED) == 0) {
2409 * Mark a vnode as free: remove it from its active list
2410 * and put it up for recycling on the freelist.
2412 VNASSERT(vp->v_op != NULL, vp,
2413 ("vdropl: vnode already reclaimed."));
2414 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2415 ("vnode already free"));
2416 VNASSERT(VSHOULDFREE(vp), vp,
2417 ("vdropl: freeing when we shouldn't"));
2418 active = vp->v_iflag & VI_ACTIVE;
2419 vp->v_iflag &= ~VI_ACTIVE;
2421 mtx_lock(&vnode_free_list_mtx);
2423 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp,
2425 mp->mnt_activevnodelistsize--;
2427 if (vp->v_iflag & VI_AGE) {
2428 TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_actfreelist);
2430 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_actfreelist);
2433 vp->v_iflag &= ~VI_AGE;
2434 vp->v_iflag |= VI_FREE;
2435 mtx_unlock(&vnode_free_list_mtx);
2440 * The vnode has been marked for destruction, so free it.
2442 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
2443 mtx_lock(&vnode_free_list_mtx);
2445 mtx_unlock(&vnode_free_list_mtx);
2447 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2448 ("cleaned vnode still on the free list."));
2449 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
2450 VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
2451 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
2452 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
2453 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
2454 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
2455 VNASSERT(bo->bo_clean.bv_root == NULL, vp, ("cleanblkroot not NULL"));
2456 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
2457 VNASSERT(bo->bo_dirty.bv_root == NULL, vp, ("dirtyblkroot not NULL"));
2458 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
2459 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
2460 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
2463 mac_vnode_destroy(vp);
2465 if (vp->v_pollinfo != NULL)
2466 destroy_vpollinfo(vp->v_pollinfo);
2468 /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
2471 lockdestroy(vp->v_vnlock);
2472 mtx_destroy(&vp->v_interlock);
2473 mtx_destroy(BO_MTX(bo));
2474 uma_zfree(vnode_zone, vp);
2478 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
2479 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
2480 * OWEINACT tracks whether a vnode missed a call to inactive due to a
2481 * failed lock upgrade.
2484 vinactive(struct vnode *vp, struct thread *td)
2486 struct vm_object *obj;
2488 ASSERT_VOP_ELOCKED(vp, "vinactive");
2489 ASSERT_VI_LOCKED(vp, "vinactive");
2490 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
2491 ("vinactive: recursed on VI_DOINGINACT"));
2492 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2493 vp->v_iflag |= VI_DOINGINACT;
2494 vp->v_iflag &= ~VI_OWEINACT;
2497 * Before moving off the active list, we must be sure that any
2498 * modified pages are on the vnode's dirty list since these will
2499 * no longer be checked once the vnode is on the inactive list.
2502 if (obj != NULL && (obj->flags & OBJ_MIGHTBEDIRTY) != 0) {
2503 VM_OBJECT_LOCK(obj);
2504 vm_object_page_clean(obj, 0, 0, OBJPC_NOSYNC);
2505 VM_OBJECT_UNLOCK(obj);
2507 VOP_INACTIVE(vp, td);
2509 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
2510 ("vinactive: lost VI_DOINGINACT"));
2511 vp->v_iflag &= ~VI_DOINGINACT;
2515 * Remove any vnodes in the vnode table belonging to mount point mp.
2517 * If FORCECLOSE is not specified, there should not be any active ones,
2518 * return error if any are found (nb: this is a user error, not a
2519 * system error). If FORCECLOSE is specified, detach any active vnodes
2522 * If WRITECLOSE is set, only flush out regular file vnodes open for
2525 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
2527 * `rootrefs' specifies the base reference count for the root vnode
2528 * of this filesystem. The root vnode is considered busy if its
2529 * v_usecount exceeds this value. On a successful return, vflush(, td)
2530 * will call vrele() on the root vnode exactly rootrefs times.
2531 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
2535 static int busyprt = 0; /* print out busy vnodes */
2536 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
2540 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
2542 struct vnode *vp, *mvp, *rootvp = NULL;
2544 int busy = 0, error;
2546 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
2549 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
2550 ("vflush: bad args"));
2552 * Get the filesystem root vnode. We can vput() it
2553 * immediately, since with rootrefs > 0, it won't go away.
2555 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
2556 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
2563 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
2565 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
2568 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
2572 * Skip over a vnodes marked VV_SYSTEM.
2574 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
2580 * If WRITECLOSE is set, flush out unlinked but still open
2581 * files (even if open only for reading) and regular file
2582 * vnodes open for writing.
2584 if (flags & WRITECLOSE) {
2585 if (vp->v_object != NULL) {
2586 VM_OBJECT_LOCK(vp->v_object);
2587 vm_object_page_clean(vp->v_object, 0, 0, 0);
2588 VM_OBJECT_UNLOCK(vp->v_object);
2590 error = VOP_FSYNC(vp, MNT_WAIT, td);
2594 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
2597 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
2600 if ((vp->v_type == VNON ||
2601 (error == 0 && vattr.va_nlink > 0)) &&
2602 (vp->v_writecount == 0 || vp->v_type != VREG)) {
2610 * With v_usecount == 0, all we need to do is clear out the
2611 * vnode data structures and we are done.
2613 * If FORCECLOSE is set, forcibly close the vnode.
2615 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
2616 VNASSERT(vp->v_usecount == 0 ||
2617 (vp->v_type != VCHR && vp->v_type != VBLK), vp,
2618 ("device VNODE %p is FORCECLOSED", vp));
2624 vprint("vflush: busy vnode", vp);
2630 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
2632 * If just the root vnode is busy, and if its refcount
2633 * is equal to `rootrefs', then go ahead and kill it.
2636 KASSERT(busy > 0, ("vflush: not busy"));
2637 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
2638 ("vflush: usecount %d < rootrefs %d",
2639 rootvp->v_usecount, rootrefs));
2640 if (busy == 1 && rootvp->v_usecount == rootrefs) {
2641 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
2643 VOP_UNLOCK(rootvp, 0);
2649 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
2653 for (; rootrefs > 0; rootrefs--)
2659 * Recycle an unused vnode to the front of the free list.
2662 vrecycle(struct vnode *vp)
2666 ASSERT_VOP_ELOCKED(vp, "vrecycle");
2667 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2670 if (vp->v_usecount == 0) {
2679 * Eliminate all activity associated with a vnode
2680 * in preparation for reuse.
2683 vgone(struct vnode *vp)
2691 * vgone, with the vp interlock held.
2694 vgonel(struct vnode *vp)
2701 ASSERT_VOP_ELOCKED(vp, "vgonel");
2702 ASSERT_VI_LOCKED(vp, "vgonel");
2703 VNASSERT(vp->v_holdcnt, vp,
2704 ("vgonel: vp %p has no reference.", vp));
2705 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2709 * Don't vgonel if we're already doomed.
2711 if (vp->v_iflag & VI_DOOMED)
2713 vp->v_iflag |= VI_DOOMED;
2715 * Check to see if the vnode is in use. If so, we have to call
2716 * VOP_CLOSE() and VOP_INACTIVE().
2718 active = vp->v_usecount;
2719 oweinact = (vp->v_iflag & VI_OWEINACT);
2722 * Clean out any buffers associated with the vnode.
2723 * If the flush fails, just toss the buffers.
2726 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
2727 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
2728 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0)
2729 vinvalbuf(vp, 0, 0, 0);
2732 * If purging an active vnode, it must be closed and
2733 * deactivated before being reclaimed.
2736 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
2737 if (oweinact || active) {
2739 if ((vp->v_iflag & VI_DOINGINACT) == 0)
2743 if (vp->v_type == VSOCK)
2744 vfs_unp_reclaim(vp);
2746 * Reclaim the vnode.
2748 if (VOP_RECLAIM(vp, td))
2749 panic("vgone: cannot reclaim");
2751 vn_finished_secondary_write(mp);
2752 VNASSERT(vp->v_object == NULL, vp,
2753 ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
2755 * Clear the advisory locks and wake up waiting threads.
2757 (void)VOP_ADVLOCKPURGE(vp);
2759 * Delete from old mount point vnode list.
2764 * Done with purge, reset to the standard lock and invalidate
2768 vp->v_vnlock = &vp->v_lock;
2769 vp->v_op = &dead_vnodeops;
2775 * Calculate the total number of references to a special device.
2778 vcount(struct vnode *vp)
2783 count = vp->v_rdev->si_usecount;
2789 * Same as above, but using the struct cdev *as argument
2792 count_dev(struct cdev *dev)
2797 count = dev->si_usecount;
2803 * Print out a description of a vnode.
2805 static char *typename[] =
2806 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
2810 vn_printf(struct vnode *vp, const char *fmt, ...)
2813 char buf[256], buf2[16];
2819 printf("%p: ", (void *)vp);
2820 printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
2821 printf(" usecount %d, writecount %d, refcount %d mountedhere %p\n",
2822 vp->v_usecount, vp->v_writecount, vp->v_holdcnt, vp->v_mountedhere);
2825 if (vp->v_vflag & VV_ROOT)
2826 strlcat(buf, "|VV_ROOT", sizeof(buf));
2827 if (vp->v_vflag & VV_ISTTY)
2828 strlcat(buf, "|VV_ISTTY", sizeof(buf));
2829 if (vp->v_vflag & VV_NOSYNC)
2830 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
2831 if (vp->v_vflag & VV_CACHEDLABEL)
2832 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
2833 if (vp->v_vflag & VV_TEXT)
2834 strlcat(buf, "|VV_TEXT", sizeof(buf));
2835 if (vp->v_vflag & VV_COPYONWRITE)
2836 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
2837 if (vp->v_vflag & VV_SYSTEM)
2838 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
2839 if (vp->v_vflag & VV_PROCDEP)
2840 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
2841 if (vp->v_vflag & VV_NOKNOTE)
2842 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
2843 if (vp->v_vflag & VV_DELETED)
2844 strlcat(buf, "|VV_DELETED", sizeof(buf));
2845 if (vp->v_vflag & VV_MD)
2846 strlcat(buf, "|VV_MD", sizeof(buf));
2847 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC |
2848 VV_CACHEDLABEL | VV_TEXT | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
2849 VV_NOKNOTE | VV_DELETED | VV_MD);
2851 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
2852 strlcat(buf, buf2, sizeof(buf));
2854 if (vp->v_iflag & VI_MOUNT)
2855 strlcat(buf, "|VI_MOUNT", sizeof(buf));
2856 if (vp->v_iflag & VI_AGE)
2857 strlcat(buf, "|VI_AGE", sizeof(buf));
2858 if (vp->v_iflag & VI_DOOMED)
2859 strlcat(buf, "|VI_DOOMED", sizeof(buf));
2860 if (vp->v_iflag & VI_FREE)
2861 strlcat(buf, "|VI_FREE", sizeof(buf));
2862 if (vp->v_iflag & VI_DOINGINACT)
2863 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
2864 if (vp->v_iflag & VI_OWEINACT)
2865 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
2866 flags = vp->v_iflag & ~(VI_MOUNT | VI_AGE | VI_DOOMED | VI_FREE |
2867 VI_DOINGINACT | VI_OWEINACT);
2869 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
2870 strlcat(buf, buf2, sizeof(buf));
2872 printf(" flags (%s)\n", buf + 1);
2873 if (mtx_owned(VI_MTX(vp)))
2874 printf(" VI_LOCKed");
2875 if (vp->v_object != NULL)
2876 printf(" v_object %p ref %d pages %d\n",
2877 vp->v_object, vp->v_object->ref_count,
2878 vp->v_object->resident_page_count);
2880 lockmgr_printinfo(vp->v_vnlock);
2881 if (vp->v_data != NULL)
2887 * List all of the locked vnodes in the system.
2888 * Called when debugging the kernel.
2890 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
2892 struct mount *mp, *nmp;
2896 * Note: because this is DDB, we can't obey the locking semantics
2897 * for these structures, which means we could catch an inconsistent
2898 * state and dereference a nasty pointer. Not much to be done
2901 db_printf("Locked vnodes\n");
2902 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2903 nmp = TAILQ_NEXT(mp, mnt_list);
2904 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2905 if (vp->v_type != VMARKER &&
2909 nmp = TAILQ_NEXT(mp, mnt_list);
2914 * Show details about the given vnode.
2916 DB_SHOW_COMMAND(vnode, db_show_vnode)
2922 vp = (struct vnode *)addr;
2923 vn_printf(vp, "vnode ");
2927 * Show details about the given mount point.
2929 DB_SHOW_COMMAND(mount, db_show_mount)
2940 /* No address given, print short info about all mount points. */
2941 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2942 db_printf("%p %s on %s (%s)\n", mp,
2943 mp->mnt_stat.f_mntfromname,
2944 mp->mnt_stat.f_mntonname,
2945 mp->mnt_stat.f_fstypename);
2949 db_printf("\nMore info: show mount <addr>\n");
2953 mp = (struct mount *)addr;
2954 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
2955 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
2958 mflags = mp->mnt_flag;
2959 #define MNT_FLAG(flag) do { \
2960 if (mflags & (flag)) { \
2961 if (buf[0] != '\0') \
2962 strlcat(buf, ", ", sizeof(buf)); \
2963 strlcat(buf, (#flag) + 4, sizeof(buf)); \
2964 mflags &= ~(flag); \
2967 MNT_FLAG(MNT_RDONLY);
2968 MNT_FLAG(MNT_SYNCHRONOUS);
2969 MNT_FLAG(MNT_NOEXEC);
2970 MNT_FLAG(MNT_NOSUID);
2971 MNT_FLAG(MNT_UNION);
2972 MNT_FLAG(MNT_ASYNC);
2973 MNT_FLAG(MNT_SUIDDIR);
2974 MNT_FLAG(MNT_SOFTDEP);
2976 MNT_FLAG(MNT_NOSYMFOLLOW);
2977 MNT_FLAG(MNT_GJOURNAL);
2978 MNT_FLAG(MNT_MULTILABEL);
2980 MNT_FLAG(MNT_NOATIME);
2981 MNT_FLAG(MNT_NOCLUSTERR);
2982 MNT_FLAG(MNT_NOCLUSTERW);
2983 MNT_FLAG(MNT_NFS4ACLS);
2984 MNT_FLAG(MNT_EXRDONLY);
2985 MNT_FLAG(MNT_EXPORTED);
2986 MNT_FLAG(MNT_DEFEXPORTED);
2987 MNT_FLAG(MNT_EXPORTANON);
2988 MNT_FLAG(MNT_EXKERB);
2989 MNT_FLAG(MNT_EXPUBLIC);
2990 MNT_FLAG(MNT_LOCAL);
2991 MNT_FLAG(MNT_QUOTA);
2992 MNT_FLAG(MNT_ROOTFS);
2994 MNT_FLAG(MNT_IGNORE);
2995 MNT_FLAG(MNT_UPDATE);
2996 MNT_FLAG(MNT_DELEXPORT);
2997 MNT_FLAG(MNT_RELOAD);
2998 MNT_FLAG(MNT_FORCE);
2999 MNT_FLAG(MNT_SNAPSHOT);
3000 MNT_FLAG(MNT_BYFSID);
3004 strlcat(buf, ", ", sizeof(buf));
3005 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3006 "0x%016jx", mflags);
3008 db_printf(" mnt_flag = %s\n", buf);
3011 flags = mp->mnt_kern_flag;
3012 #define MNT_KERN_FLAG(flag) do { \
3013 if (flags & (flag)) { \
3014 if (buf[0] != '\0') \
3015 strlcat(buf, ", ", sizeof(buf)); \
3016 strlcat(buf, (#flag) + 5, sizeof(buf)); \
3020 MNT_KERN_FLAG(MNTK_UNMOUNTF);
3021 MNT_KERN_FLAG(MNTK_ASYNC);
3022 MNT_KERN_FLAG(MNTK_SOFTDEP);
3023 MNT_KERN_FLAG(MNTK_NOINSMNTQ);
3024 MNT_KERN_FLAG(MNTK_DRAINING);
3025 MNT_KERN_FLAG(MNTK_REFEXPIRE);
3026 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
3027 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
3028 MNT_KERN_FLAG(MNTK_NOASYNC);
3029 MNT_KERN_FLAG(MNTK_UNMOUNT);
3030 MNT_KERN_FLAG(MNTK_MWAIT);
3031 MNT_KERN_FLAG(MNTK_SUSPEND);
3032 MNT_KERN_FLAG(MNTK_SUSPEND2);
3033 MNT_KERN_FLAG(MNTK_SUSPENDED);
3034 MNT_KERN_FLAG(MNTK_MPSAFE);
3035 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
3036 MNT_KERN_FLAG(MNTK_NOKNOTE);
3037 #undef MNT_KERN_FLAG
3040 strlcat(buf, ", ", sizeof(buf));
3041 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3044 db_printf(" mnt_kern_flag = %s\n", buf);
3046 db_printf(" mnt_opt = ");
3047 opt = TAILQ_FIRST(mp->mnt_opt);
3049 db_printf("%s", opt->name);
3050 opt = TAILQ_NEXT(opt, link);
3051 while (opt != NULL) {
3052 db_printf(", %s", opt->name);
3053 opt = TAILQ_NEXT(opt, link);
3059 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
3060 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
3061 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
3062 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
3063 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
3064 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
3065 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
3066 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
3067 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
3068 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
3069 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
3070 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
3072 db_printf(" mnt_cred = { uid=%u ruid=%u",
3073 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
3074 if (jailed(mp->mnt_cred))
3075 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
3077 db_printf(" mnt_ref = %d\n", mp->mnt_ref);
3078 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
3079 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
3080 db_printf(" mnt_activevnodelistsize = %d\n",
3081 mp->mnt_activevnodelistsize);
3082 db_printf(" mnt_writeopcount = %d\n", mp->mnt_writeopcount);
3083 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
3084 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
3085 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
3086 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
3087 db_printf(" mnt_secondary_accwrites = %d\n",
3088 mp->mnt_secondary_accwrites);
3089 db_printf(" mnt_gjprovider = %s\n",
3090 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
3092 db_printf("\n\nList of active vnodes\n");
3093 TAILQ_FOREACH(vp, &mp->mnt_activevnodelist, v_actfreelist) {
3094 if (vp->v_type != VMARKER) {
3095 vn_printf(vp, "vnode ");
3100 db_printf("\n\nList of inactive vnodes\n");
3101 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3102 if (vp->v_type != VMARKER && (vp->v_iflag & VI_ACTIVE) == 0) {
3103 vn_printf(vp, "vnode ");
3112 * Fill in a struct xvfsconf based on a struct vfsconf.
3115 vfsconf2x(struct vfsconf *vfsp, struct xvfsconf *xvfsp)
3118 strcpy(xvfsp->vfc_name, vfsp->vfc_name);
3119 xvfsp->vfc_typenum = vfsp->vfc_typenum;
3120 xvfsp->vfc_refcount = vfsp->vfc_refcount;
3121 xvfsp->vfc_flags = vfsp->vfc_flags;
3123 * These are unused in userland, we keep them
3124 * to not break binary compatibility.
3126 xvfsp->vfc_vfsops = NULL;
3127 xvfsp->vfc_next = NULL;
3131 * Top level filesystem related information gathering.
3134 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
3136 struct vfsconf *vfsp;
3137 struct xvfsconf xvfsp;
3141 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3142 bzero(&xvfsp, sizeof(xvfsp));
3143 vfsconf2x(vfsp, &xvfsp);
3144 error = SYSCTL_OUT(req, &xvfsp, sizeof xvfsp);
3151 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD,
3152 NULL, 0, sysctl_vfs_conflist,
3153 "S,xvfsconf", "List of all configured filesystems");
3155 #ifndef BURN_BRIDGES
3156 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
3159 vfs_sysctl(SYSCTL_HANDLER_ARGS)
3161 int *name = (int *)arg1 - 1; /* XXX */
3162 u_int namelen = arg2 + 1; /* XXX */
3163 struct vfsconf *vfsp;
3164 struct xvfsconf xvfsp;
3166 log(LOG_WARNING, "userland calling deprecated sysctl, "
3167 "please rebuild world\n");
3169 #if 1 || defined(COMPAT_PRELITE2)
3170 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
3172 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
3176 case VFS_MAXTYPENUM:
3179 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
3182 return (ENOTDIR); /* overloaded */
3183 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list)
3184 if (vfsp->vfc_typenum == name[2])
3187 return (EOPNOTSUPP);
3188 bzero(&xvfsp, sizeof(xvfsp));
3189 vfsconf2x(vfsp, &xvfsp);
3190 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3192 return (EOPNOTSUPP);
3195 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP,
3196 vfs_sysctl, "Generic filesystem");
3198 #if 1 || defined(COMPAT_PRELITE2)
3201 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
3204 struct vfsconf *vfsp;
3205 struct ovfsconf ovfs;
3207 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3208 bzero(&ovfs, sizeof(ovfs));
3209 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
3210 strcpy(ovfs.vfc_name, vfsp->vfc_name);
3211 ovfs.vfc_index = vfsp->vfc_typenum;
3212 ovfs.vfc_refcount = vfsp->vfc_refcount;
3213 ovfs.vfc_flags = vfsp->vfc_flags;
3214 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
3221 #endif /* 1 || COMPAT_PRELITE2 */
3222 #endif /* !BURN_BRIDGES */
3224 #define KINFO_VNODESLOP 10
3227 * Dump vnode list (via sysctl).
3231 sysctl_vnode(SYSCTL_HANDLER_ARGS)
3239 * Stale numvnodes access is not fatal here.
3242 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
3244 /* Make an estimate */
3245 return (SYSCTL_OUT(req, 0, len));
3247 error = sysctl_wire_old_buffer(req, 0);
3250 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
3252 mtx_lock(&mountlist_mtx);
3253 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3254 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
3257 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3261 xvn[n].xv_size = sizeof *xvn;
3262 xvn[n].xv_vnode = vp;
3263 xvn[n].xv_id = 0; /* XXX compat */
3264 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
3266 XV_COPY(writecount);
3272 xvn[n].xv_flag = vp->v_vflag;
3274 switch (vp->v_type) {
3281 if (vp->v_rdev == NULL) {
3285 xvn[n].xv_dev = dev2udev(vp->v_rdev);
3288 xvn[n].xv_socket = vp->v_socket;
3291 xvn[n].xv_fifo = vp->v_fifoinfo;
3296 /* shouldn't happen? */
3304 mtx_lock(&mountlist_mtx);
3309 mtx_unlock(&mountlist_mtx);
3311 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
3316 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
3317 0, 0, sysctl_vnode, "S,xvnode", "");
3321 * Unmount all filesystems. The list is traversed in reverse order
3322 * of mounting to avoid dependencies.
3325 vfs_unmountall(void)
3331 KASSERT(curthread != NULL, ("vfs_unmountall: NULL curthread"));
3332 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
3336 * Since this only runs when rebooting, it is not interlocked.
3338 while(!TAILQ_EMPTY(&mountlist)) {
3339 mp = TAILQ_LAST(&mountlist, mntlist);
3340 error = dounmount(mp, MNT_FORCE, td);
3342 TAILQ_REMOVE(&mountlist, mp, mnt_list);
3344 * XXX: Due to the way in which we mount the root
3345 * file system off of devfs, devfs will generate a
3346 * "busy" warning when we try to unmount it before
3347 * the root. Don't print a warning as a result in
3348 * order to avoid false positive errors that may
3349 * cause needless upset.
3351 if (strcmp(mp->mnt_vfc->vfc_name, "devfs") != 0) {
3352 printf("unmount of %s failed (",
3353 mp->mnt_stat.f_mntonname);
3357 printf("%d)\n", error);
3360 /* The unmount has removed mp from the mountlist */
3366 * perform msync on all vnodes under a mount point
3367 * the mount point must be locked.
3370 vfs_msync(struct mount *mp, int flags)
3372 struct vnode *vp, *mvp;
3373 struct vm_object *obj;
3375 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
3376 MNT_VNODE_FOREACH_ACTIVE(vp, mp, mvp) {
3378 if (obj != NULL && (obj->flags & OBJ_MIGHTBEDIRTY) != 0 &&
3379 (flags == MNT_WAIT || VOP_ISLOCKED(vp) == 0)) {
3381 LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
3383 if (vp->v_vflag & VV_NOSYNC) { /* unlinked */
3390 VM_OBJECT_LOCK(obj);
3391 vm_object_page_clean(obj, 0, 0,
3393 OBJPC_SYNC : OBJPC_NOSYNC);
3394 VM_OBJECT_UNLOCK(obj);
3404 destroy_vpollinfo(struct vpollinfo *vi)
3406 seldrain(&vi->vpi_selinfo);
3407 knlist_destroy(&vi->vpi_selinfo.si_note);
3408 mtx_destroy(&vi->vpi_lock);
3409 uma_zfree(vnodepoll_zone, vi);
3413 * Initalize per-vnode helper structure to hold poll-related state.
3416 v_addpollinfo(struct vnode *vp)
3418 struct vpollinfo *vi;
3420 if (vp->v_pollinfo != NULL)
3422 vi = uma_zalloc(vnodepoll_zone, M_WAITOK);
3423 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
3424 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
3425 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
3427 if (vp->v_pollinfo != NULL) {
3429 destroy_vpollinfo(vi);
3432 vp->v_pollinfo = vi;
3437 * Record a process's interest in events which might happen to
3438 * a vnode. Because poll uses the historic select-style interface
3439 * internally, this routine serves as both the ``check for any
3440 * pending events'' and the ``record my interest in future events''
3441 * functions. (These are done together, while the lock is held,
3442 * to avoid race conditions.)
3445 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
3449 mtx_lock(&vp->v_pollinfo->vpi_lock);
3450 if (vp->v_pollinfo->vpi_revents & events) {
3452 * This leaves events we are not interested
3453 * in available for the other process which
3454 * which presumably had requested them
3455 * (otherwise they would never have been
3458 events &= vp->v_pollinfo->vpi_revents;
3459 vp->v_pollinfo->vpi_revents &= ~events;
3461 mtx_unlock(&vp->v_pollinfo->vpi_lock);
3464 vp->v_pollinfo->vpi_events |= events;
3465 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
3466 mtx_unlock(&vp->v_pollinfo->vpi_lock);
3471 * Routine to create and manage a filesystem syncer vnode.
3473 #define sync_close ((int (*)(struct vop_close_args *))nullop)
3474 static int sync_fsync(struct vop_fsync_args *);
3475 static int sync_inactive(struct vop_inactive_args *);
3476 static int sync_reclaim(struct vop_reclaim_args *);
3478 static struct vop_vector sync_vnodeops = {
3479 .vop_bypass = VOP_EOPNOTSUPP,
3480 .vop_close = sync_close, /* close */
3481 .vop_fsync = sync_fsync, /* fsync */
3482 .vop_inactive = sync_inactive, /* inactive */
3483 .vop_reclaim = sync_reclaim, /* reclaim */
3484 .vop_lock1 = vop_stdlock, /* lock */
3485 .vop_unlock = vop_stdunlock, /* unlock */
3486 .vop_islocked = vop_stdislocked, /* islocked */
3490 * Create a new filesystem syncer vnode for the specified mount point.
3493 vfs_allocate_syncvnode(struct mount *mp)
3497 static long start, incr, next;
3500 /* Allocate a new vnode */
3501 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
3503 panic("vfs_allocate_syncvnode: getnewvnode() failed");
3505 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3506 vp->v_vflag |= VV_FORCEINSMQ;
3507 error = insmntque(vp, mp);
3509 panic("vfs_allocate_syncvnode: insmntque() failed");
3510 vp->v_vflag &= ~VV_FORCEINSMQ;
3513 * Place the vnode onto the syncer worklist. We attempt to
3514 * scatter them about on the list so that they will go off
3515 * at evenly distributed times even if all the filesystems
3516 * are mounted at once.
3519 if (next == 0 || next > syncer_maxdelay) {
3523 start = syncer_maxdelay / 2;
3524 incr = syncer_maxdelay;
3530 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
3531 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
3532 mtx_lock(&sync_mtx);
3534 if (mp->mnt_syncer == NULL) {
3535 mp->mnt_syncer = vp;
3538 mtx_unlock(&sync_mtx);
3541 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3548 vfs_deallocate_syncvnode(struct mount *mp)
3552 mtx_lock(&sync_mtx);
3553 vp = mp->mnt_syncer;
3555 mp->mnt_syncer = NULL;
3556 mtx_unlock(&sync_mtx);
3562 * Do a lazy sync of the filesystem.
3565 sync_fsync(struct vop_fsync_args *ap)
3567 struct vnode *syncvp = ap->a_vp;
3568 struct mount *mp = syncvp->v_mount;
3573 * We only need to do something if this is a lazy evaluation.
3575 if (ap->a_waitfor != MNT_LAZY)
3579 * Move ourselves to the back of the sync list.
3581 bo = &syncvp->v_bufobj;
3583 vn_syncer_add_to_worklist(bo, syncdelay);
3587 * Walk the list of vnodes pushing all that are dirty and
3588 * not already on the sync list.
3590 mtx_lock(&mountlist_mtx);
3591 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK) != 0) {
3592 mtx_unlock(&mountlist_mtx);
3595 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
3599 save = curthread_pflags_set(TDP_SYNCIO);
3600 vfs_msync(mp, MNT_NOWAIT);
3601 error = VFS_SYNC(mp, MNT_LAZY);
3602 curthread_pflags_restore(save);
3603 vn_finished_write(mp);
3609 * The syncer vnode is no referenced.
3612 sync_inactive(struct vop_inactive_args *ap)
3620 * The syncer vnode is no longer needed and is being decommissioned.
3622 * Modifications to the worklist must be protected by sync_mtx.
3625 sync_reclaim(struct vop_reclaim_args *ap)
3627 struct vnode *vp = ap->a_vp;
3632 mtx_lock(&sync_mtx);
3633 if (vp->v_mount->mnt_syncer == vp)
3634 vp->v_mount->mnt_syncer = NULL;
3635 if (bo->bo_flag & BO_ONWORKLST) {
3636 LIST_REMOVE(bo, bo_synclist);
3637 syncer_worklist_len--;
3639 bo->bo_flag &= ~BO_ONWORKLST;
3641 mtx_unlock(&sync_mtx);
3648 * Check if vnode represents a disk device
3651 vn_isdisk(struct vnode *vp, int *errp)
3657 if (vp->v_type != VCHR)
3659 else if (vp->v_rdev == NULL)
3661 else if (vp->v_rdev->si_devsw == NULL)
3663 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
3668 return (error == 0);
3672 * Common filesystem object access control check routine. Accepts a
3673 * vnode's type, "mode", uid and gid, requested access mode, credentials,
3674 * and optional call-by-reference privused argument allowing vaccess()
3675 * to indicate to the caller whether privilege was used to satisfy the
3676 * request (obsoleted). Returns 0 on success, or an errno on failure.
3679 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
3680 accmode_t accmode, struct ucred *cred, int *privused)
3682 accmode_t dac_granted;
3683 accmode_t priv_granted;
3685 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
3686 ("invalid bit in accmode"));
3687 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
3688 ("VAPPEND without VWRITE"));
3691 * Look for a normal, non-privileged way to access the file/directory
3692 * as requested. If it exists, go with that.
3695 if (privused != NULL)
3700 /* Check the owner. */
3701 if (cred->cr_uid == file_uid) {
3702 dac_granted |= VADMIN;
3703 if (file_mode & S_IXUSR)
3704 dac_granted |= VEXEC;
3705 if (file_mode & S_IRUSR)
3706 dac_granted |= VREAD;
3707 if (file_mode & S_IWUSR)
3708 dac_granted |= (VWRITE | VAPPEND);
3710 if ((accmode & dac_granted) == accmode)
3716 /* Otherwise, check the groups (first match) */
3717 if (groupmember(file_gid, cred)) {
3718 if (file_mode & S_IXGRP)
3719 dac_granted |= VEXEC;
3720 if (file_mode & S_IRGRP)
3721 dac_granted |= VREAD;
3722 if (file_mode & S_IWGRP)
3723 dac_granted |= (VWRITE | VAPPEND);
3725 if ((accmode & dac_granted) == accmode)
3731 /* Otherwise, check everyone else. */
3732 if (file_mode & S_IXOTH)
3733 dac_granted |= VEXEC;
3734 if (file_mode & S_IROTH)
3735 dac_granted |= VREAD;
3736 if (file_mode & S_IWOTH)
3737 dac_granted |= (VWRITE | VAPPEND);
3738 if ((accmode & dac_granted) == accmode)
3743 * Build a privilege mask to determine if the set of privileges
3744 * satisfies the requirements when combined with the granted mask
3745 * from above. For each privilege, if the privilege is required,
3746 * bitwise or the request type onto the priv_granted mask.
3752 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
3753 * requests, instead of PRIV_VFS_EXEC.
3755 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3756 !priv_check_cred(cred, PRIV_VFS_LOOKUP, 0))
3757 priv_granted |= VEXEC;
3760 * Ensure that at least one execute bit is on. Otherwise,
3761 * a privileged user will always succeed, and we don't want
3762 * this to happen unless the file really is executable.
3764 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3765 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
3766 !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
3767 priv_granted |= VEXEC;
3770 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
3771 !priv_check_cred(cred, PRIV_VFS_READ, 0))
3772 priv_granted |= VREAD;
3774 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
3775 !priv_check_cred(cred, PRIV_VFS_WRITE, 0))
3776 priv_granted |= (VWRITE | VAPPEND);
3778 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
3779 !priv_check_cred(cred, PRIV_VFS_ADMIN, 0))
3780 priv_granted |= VADMIN;
3782 if ((accmode & (priv_granted | dac_granted)) == accmode) {
3783 /* XXX audit: privilege used */
3784 if (privused != NULL)
3789 return ((accmode & VADMIN) ? EPERM : EACCES);
3793 * Credential check based on process requesting service, and per-attribute
3797 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
3798 struct thread *td, accmode_t accmode)
3802 * Kernel-invoked always succeeds.
3808 * Do not allow privileged processes in jail to directly manipulate
3809 * system attributes.
3811 switch (attrnamespace) {
3812 case EXTATTR_NAMESPACE_SYSTEM:
3813 /* Potentially should be: return (EPERM); */
3814 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM, 0));
3815 case EXTATTR_NAMESPACE_USER:
3816 return (VOP_ACCESS(vp, accmode, cred, td));
3822 #ifdef DEBUG_VFS_LOCKS
3824 * This only exists to supress warnings from unlocked specfs accesses. It is
3825 * no longer ok to have an unlocked VFS.
3827 #define IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL || \
3828 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
3830 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
3831 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
3832 "Drop into debugger on lock violation");
3834 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
3835 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
3836 0, "Check for interlock across VOPs");
3838 int vfs_badlock_print = 1; /* Print lock violations. */
3839 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
3840 0, "Print lock violations");
3843 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
3844 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
3845 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
3849 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
3853 if (vfs_badlock_backtrace)
3856 if (vfs_badlock_print)
3857 printf("%s: %p %s\n", str, (void *)vp, msg);
3858 if (vfs_badlock_ddb)
3859 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
3863 assert_vi_locked(struct vnode *vp, const char *str)
3866 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
3867 vfs_badlock("interlock is not locked but should be", str, vp);
3871 assert_vi_unlocked(struct vnode *vp, const char *str)
3874 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
3875 vfs_badlock("interlock is locked but should not be", str, vp);
3879 assert_vop_locked(struct vnode *vp, const char *str)
3882 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == 0)
3883 vfs_badlock("is not locked but should be", str, vp);
3887 assert_vop_unlocked(struct vnode *vp, const char *str)
3890 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
3891 vfs_badlock("is locked but should not be", str, vp);
3895 assert_vop_elocked(struct vnode *vp, const char *str)
3898 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
3899 vfs_badlock("is not exclusive locked but should be", str, vp);
3904 assert_vop_elocked_other(struct vnode *vp, const char *str)
3907 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLOTHER)
3908 vfs_badlock("is not exclusive locked by another thread",
3913 assert_vop_slocked(struct vnode *vp, const char *str)
3916 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_SHARED)
3917 vfs_badlock("is not locked shared but should be", str, vp);
3920 #endif /* DEBUG_VFS_LOCKS */
3923 vop_rename_fail(struct vop_rename_args *ap)
3926 if (ap->a_tvp != NULL)
3928 if (ap->a_tdvp == ap->a_tvp)
3937 vop_rename_pre(void *ap)
3939 struct vop_rename_args *a = ap;
3941 #ifdef DEBUG_VFS_LOCKS
3943 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
3944 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
3945 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
3946 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
3948 /* Check the source (from). */
3949 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
3950 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
3951 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
3952 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
3953 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
3955 /* Check the target. */
3957 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
3958 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
3960 if (a->a_tdvp != a->a_fdvp)
3962 if (a->a_tvp != a->a_fvp)
3970 vop_strategy_pre(void *ap)
3972 #ifdef DEBUG_VFS_LOCKS
3973 struct vop_strategy_args *a;
3980 * Cluster ops lock their component buffers but not the IO container.
3982 if ((bp->b_flags & B_CLUSTER) != 0)
3985 if (panicstr == NULL && !BUF_ISLOCKED(bp)) {
3986 if (vfs_badlock_print)
3988 "VOP_STRATEGY: bp is not locked but should be\n");
3989 if (vfs_badlock_ddb)
3990 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
3996 vop_lookup_pre(void *ap)
3998 #ifdef DEBUG_VFS_LOCKS
3999 struct vop_lookup_args *a;
4004 ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
4005 ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
4010 vop_lookup_post(void *ap, int rc)
4012 #ifdef DEBUG_VFS_LOCKS
4013 struct vop_lookup_args *a;
4021 ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
4022 ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
4025 ASSERT_VOP_LOCKED(vp, "VOP_LOOKUP (child)");
4030 vop_lock_pre(void *ap)
4032 #ifdef DEBUG_VFS_LOCKS
4033 struct vop_lock1_args *a = ap;
4035 if ((a->a_flags & LK_INTERLOCK) == 0)
4036 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4038 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
4043 vop_lock_post(void *ap, int rc)
4045 #ifdef DEBUG_VFS_LOCKS
4046 struct vop_lock1_args *a = ap;
4048 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4050 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
4055 vop_unlock_pre(void *ap)
4057 #ifdef DEBUG_VFS_LOCKS
4058 struct vop_unlock_args *a = ap;
4060 if (a->a_flags & LK_INTERLOCK)
4061 ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
4062 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
4067 vop_unlock_post(void *ap, int rc)
4069 #ifdef DEBUG_VFS_LOCKS
4070 struct vop_unlock_args *a = ap;
4072 if (a->a_flags & LK_INTERLOCK)
4073 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
4078 vop_create_post(void *ap, int rc)
4080 struct vop_create_args *a = ap;
4083 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4087 vop_deleteextattr_post(void *ap, int rc)
4089 struct vop_deleteextattr_args *a = ap;
4092 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4096 vop_link_post(void *ap, int rc)
4098 struct vop_link_args *a = ap;
4101 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
4102 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
4107 vop_mkdir_post(void *ap, int rc)
4109 struct vop_mkdir_args *a = ap;
4112 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4116 vop_mknod_post(void *ap, int rc)
4118 struct vop_mknod_args *a = ap;
4121 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4125 vop_remove_post(void *ap, int rc)
4127 struct vop_remove_args *a = ap;
4130 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4131 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4136 vop_rename_post(void *ap, int rc)
4138 struct vop_rename_args *a = ap;
4141 VFS_KNOTE_UNLOCKED(a->a_fdvp, NOTE_WRITE);
4142 VFS_KNOTE_UNLOCKED(a->a_tdvp, NOTE_WRITE);
4143 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
4145 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
4147 if (a->a_tdvp != a->a_fdvp)
4149 if (a->a_tvp != a->a_fvp)
4157 vop_rmdir_post(void *ap, int rc)
4159 struct vop_rmdir_args *a = ap;
4162 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4163 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4168 vop_setattr_post(void *ap, int rc)
4170 struct vop_setattr_args *a = ap;
4173 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4177 vop_setextattr_post(void *ap, int rc)
4179 struct vop_setextattr_args *a = ap;
4182 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4186 vop_symlink_post(void *ap, int rc)
4188 struct vop_symlink_args *a = ap;
4191 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4194 static struct knlist fs_knlist;
4197 vfs_event_init(void *arg)
4199 knlist_init_mtx(&fs_knlist, NULL);
4201 /* XXX - correct order? */
4202 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
4205 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
4208 KNOTE_UNLOCKED(&fs_knlist, event);
4211 static int filt_fsattach(struct knote *kn);
4212 static void filt_fsdetach(struct knote *kn);
4213 static int filt_fsevent(struct knote *kn, long hint);
4215 struct filterops fs_filtops = {
4217 .f_attach = filt_fsattach,
4218 .f_detach = filt_fsdetach,
4219 .f_event = filt_fsevent
4223 filt_fsattach(struct knote *kn)
4226 kn->kn_flags |= EV_CLEAR;
4227 knlist_add(&fs_knlist, kn, 0);
4232 filt_fsdetach(struct knote *kn)
4235 knlist_remove(&fs_knlist, kn, 0);
4239 filt_fsevent(struct knote *kn, long hint)
4242 kn->kn_fflags |= hint;
4243 return (kn->kn_fflags != 0);
4247 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
4253 error = SYSCTL_IN(req, &vc, sizeof(vc));
4256 if (vc.vc_vers != VFS_CTL_VERS1)
4258 mp = vfs_getvfs(&vc.vc_fsid);
4261 /* ensure that a specific sysctl goes to the right filesystem. */
4262 if (strcmp(vc.vc_fstypename, "*") != 0 &&
4263 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
4267 VCTLTOREQ(&vc, req);
4268 error = VFS_SYSCTL(mp, vc.vc_op, req);
4273 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_WR,
4274 NULL, 0, sysctl_vfs_ctl, "",
4278 * Function to initialize a va_filerev field sensibly.
4279 * XXX: Wouldn't a random number make a lot more sense ??
4282 init_va_filerev(void)
4287 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
4290 static int filt_vfsread(struct knote *kn, long hint);
4291 static int filt_vfswrite(struct knote *kn, long hint);
4292 static int filt_vfsvnode(struct knote *kn, long hint);
4293 static void filt_vfsdetach(struct knote *kn);
4294 static struct filterops vfsread_filtops = {
4296 .f_detach = filt_vfsdetach,
4297 .f_event = filt_vfsread
4299 static struct filterops vfswrite_filtops = {
4301 .f_detach = filt_vfsdetach,
4302 .f_event = filt_vfswrite
4304 static struct filterops vfsvnode_filtops = {
4306 .f_detach = filt_vfsdetach,
4307 .f_event = filt_vfsvnode
4311 vfs_knllock(void *arg)
4313 struct vnode *vp = arg;
4315 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4319 vfs_knlunlock(void *arg)
4321 struct vnode *vp = arg;
4327 vfs_knl_assert_locked(void *arg)
4329 #ifdef DEBUG_VFS_LOCKS
4330 struct vnode *vp = arg;
4332 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
4337 vfs_knl_assert_unlocked(void *arg)
4339 #ifdef DEBUG_VFS_LOCKS
4340 struct vnode *vp = arg;
4342 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
4347 vfs_kqfilter(struct vop_kqfilter_args *ap)
4349 struct vnode *vp = ap->a_vp;
4350 struct knote *kn = ap->a_kn;
4353 switch (kn->kn_filter) {
4355 kn->kn_fop = &vfsread_filtops;
4358 kn->kn_fop = &vfswrite_filtops;
4361 kn->kn_fop = &vfsvnode_filtops;
4367 kn->kn_hook = (caddr_t)vp;
4370 if (vp->v_pollinfo == NULL)
4372 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
4373 knlist_add(knl, kn, 0);
4379 * Detach knote from vnode
4382 filt_vfsdetach(struct knote *kn)
4384 struct vnode *vp = (struct vnode *)kn->kn_hook;
4386 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
4387 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
4392 filt_vfsread(struct knote *kn, long hint)
4394 struct vnode *vp = (struct vnode *)kn->kn_hook;
4399 * filesystem is gone, so set the EOF flag and schedule
4400 * the knote for deletion.
4402 if (hint == NOTE_REVOKE) {
4404 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
4409 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
4413 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
4414 res = (kn->kn_data != 0);
4421 filt_vfswrite(struct knote *kn, long hint)
4423 struct vnode *vp = (struct vnode *)kn->kn_hook;
4428 * filesystem is gone, so set the EOF flag and schedule
4429 * the knote for deletion.
4431 if (hint == NOTE_REVOKE)
4432 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
4440 filt_vfsvnode(struct knote *kn, long hint)
4442 struct vnode *vp = (struct vnode *)kn->kn_hook;
4446 if (kn->kn_sfflags & hint)
4447 kn->kn_fflags |= hint;
4448 if (hint == NOTE_REVOKE) {
4449 kn->kn_flags |= EV_EOF;
4453 res = (kn->kn_fflags != 0);
4459 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
4463 if (dp->d_reclen > ap->a_uio->uio_resid)
4464 return (ENAMETOOLONG);
4465 error = uiomove(dp, dp->d_reclen, ap->a_uio);
4467 if (ap->a_ncookies != NULL) {
4468 if (ap->a_cookies != NULL)
4469 free(ap->a_cookies, M_TEMP);
4470 ap->a_cookies = NULL;
4471 *ap->a_ncookies = 0;
4475 if (ap->a_ncookies == NULL)
4478 KASSERT(ap->a_cookies,
4479 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
4481 *ap->a_cookies = realloc(*ap->a_cookies,
4482 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
4483 (*ap->a_cookies)[*ap->a_ncookies] = off;
4488 * Mark for update the access time of the file if the filesystem
4489 * supports VOP_MARKATIME. This functionality is used by execve and
4490 * mmap, so we want to avoid the I/O implied by directly setting
4491 * va_atime for the sake of efficiency.
4494 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
4499 VFS_ASSERT_GIANT(mp);
4500 ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
4501 if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
4502 (void)VOP_MARKATIME(vp);
4506 * The purpose of this routine is to remove granularity from accmode_t,
4507 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
4508 * VADMIN and VAPPEND.
4510 * If it returns 0, the caller is supposed to continue with the usual
4511 * access checks using 'accmode' as modified by this routine. If it
4512 * returns nonzero value, the caller is supposed to return that value
4515 * Note that after this routine runs, accmode may be zero.
4518 vfs_unixify_accmode(accmode_t *accmode)
4521 * There is no way to specify explicit "deny" rule using
4522 * file mode or POSIX.1e ACLs.
4524 if (*accmode & VEXPLICIT_DENY) {
4530 * None of these can be translated into usual access bits.
4531 * Also, the common case for NFSv4 ACLs is to not contain
4532 * either of these bits. Caller should check for VWRITE
4533 * on the containing directory instead.
4535 if (*accmode & (VDELETE_CHILD | VDELETE))
4538 if (*accmode & VADMIN_PERMS) {
4539 *accmode &= ~VADMIN_PERMS;
4544 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
4545 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
4547 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
4553 * These are helper functions for filesystems to traverse all
4554 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
4556 * This interface replaces MNT_VNODE_FOREACH.
4559 MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
4562 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
4567 kern_yield(PRI_UNCHANGED);
4569 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
4570 vp = TAILQ_NEXT(*mvp, v_nmntvnodes);
4571 while (vp != NULL && (vp->v_type == VMARKER ||
4572 (vp->v_iflag & VI_DOOMED) != 0))
4573 vp = TAILQ_NEXT(vp, v_nmntvnodes);
4575 /* Check if we are done */
4577 __mnt_vnode_markerfree_all(mvp, mp);
4578 /* MNT_IUNLOCK(mp); -- done in above function */
4579 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
4582 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
4583 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
4590 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
4594 *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
4597 (*mvp)->v_type = VMARKER;
4599 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
4600 while (vp != NULL && (vp->v_type == VMARKER ||
4601 (vp->v_iflag & VI_DOOMED) != 0))
4602 vp = TAILQ_NEXT(vp, v_nmntvnodes);
4604 /* Check if we are done */
4608 free(*mvp, M_VNODE_MARKER);
4612 (*mvp)->v_mount = mp;
4613 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
4621 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
4629 mtx_assert(MNT_MTX(mp), MA_OWNED);
4631 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
4632 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
4635 free(*mvp, M_VNODE_MARKER);
4640 * These are helper functions for filesystems to traverse their
4641 * active vnodes. See MNT_VNODE_FOREACH_ACTIVE() in sys/mount.h
4644 __mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
4646 struct vnode *vp, *nvp;
4649 kern_yield(PRI_UNCHANGED);
4651 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
4652 vp = TAILQ_NEXT(*mvp, v_actfreelist);
4653 while (vp != NULL) {
4655 if (vp->v_mount == mp && vp->v_type != VMARKER &&
4656 (vp->v_iflag & VI_DOOMED) == 0)
4658 nvp = TAILQ_NEXT(vp, v_actfreelist);
4663 /* Check if we are done */
4665 __mnt_vnode_markerfree_active(mvp, mp);
4666 /* MNT_IUNLOCK(mp); -- done in above function */
4667 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
4670 mtx_lock(&vnode_free_list_mtx);
4671 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
4672 TAILQ_INSERT_AFTER(&mp->mnt_activevnodelist, vp, *mvp, v_actfreelist);
4673 mtx_unlock(&vnode_free_list_mtx);
4679 __mnt_vnode_first_active(struct vnode **mvp, struct mount *mp)
4681 struct vnode *vp, *nvp;
4683 *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
4686 (*mvp)->v_type = VMARKER;
4688 vp = TAILQ_NEXT(*mvp, v_actfreelist);
4689 while (vp != NULL) {
4691 if (vp->v_mount == mp && vp->v_type != VMARKER &&
4692 (vp->v_iflag & VI_DOOMED) == 0)
4694 nvp = TAILQ_NEXT(vp, v_actfreelist);
4699 /* Check if we are done */
4703 free(*mvp, M_VNODE_MARKER);
4707 (*mvp)->v_mount = mp;
4708 mtx_lock(&vnode_free_list_mtx);
4709 TAILQ_INSERT_AFTER(&mp->mnt_activevnodelist, vp, *mvp, v_actfreelist);
4710 mtx_unlock(&vnode_free_list_mtx);
4716 __mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
4724 mtx_assert(MNT_MTX(mp), MA_OWNED);
4726 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
4727 mtx_lock(&vnode_free_list_mtx);
4728 TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
4729 mtx_unlock(&vnode_free_list_mtx);
4732 free(*mvp, M_VNODE_MARKER);