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 vbusy(struct vnode *vp);
106 static void vinactive(struct vnode *, struct thread *);
107 static void v_incr_usecount(struct vnode *);
108 static void v_decr_usecount(struct vnode *);
109 static void v_decr_useonly(struct vnode *);
110 static void v_upgrade_usecount(struct vnode *);
111 static void vfree(struct vnode *);
112 static void vnlru_free(int);
113 static void vgonel(struct vnode *);
114 static void vfs_knllock(void *arg);
115 static void vfs_knlunlock(void *arg);
116 static void vfs_knl_assert_locked(void *arg);
117 static void vfs_knl_assert_unlocked(void *arg);
118 static void destroy_vpollinfo(struct vpollinfo *vi);
121 * Number of vnodes in existence. Increased whenever getnewvnode()
122 * allocates a new vnode, decreased on vdestroy() called on VI_DOOMed
125 static unsigned long numvnodes;
127 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
128 "Number of vnodes in existence");
131 * Conversion tables for conversion from vnode types to inode formats
134 enum vtype iftovt_tab[16] = {
135 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
136 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
138 int vttoif_tab[10] = {
139 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
140 S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
144 * List of vnodes that are ready for recycling.
146 static TAILQ_HEAD(freelst, vnode) vnode_free_list;
149 * Free vnode target. Free vnodes may simply be files which have been stat'd
150 * but not read. This is somewhat common, and a small cache of such files
151 * should be kept to avoid recreation costs.
153 static u_long wantfreevnodes;
154 SYSCTL_ULONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW, &wantfreevnodes, 0, "");
155 /* Number of vnodes in the free list. */
156 static u_long freevnodes;
157 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD, &freevnodes, 0,
158 "Number of vnodes in the free list");
160 static int vlru_allow_cache_src;
161 SYSCTL_INT(_vfs, OID_AUTO, vlru_allow_cache_src, CTLFLAG_RW,
162 &vlru_allow_cache_src, 0, "Allow vlru to reclaim source vnode");
165 * Various variables used for debugging the new implementation of
167 * XXX these are probably of (very) limited utility now.
169 static int reassignbufcalls;
170 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0,
171 "Number of calls to reassignbuf");
174 * Cache for the mount type id assigned to NFS. This is used for
175 * special checks in nfs/nfs_nqlease.c and vm/vnode_pager.c.
177 int nfs_mount_type = -1;
179 /* To keep more than one thread at a time from running vfs_getnewfsid */
180 static struct mtx mntid_mtx;
183 * Lock for any access to the following:
188 static struct mtx vnode_free_list_mtx;
190 /* Publicly exported FS */
191 struct nfs_public nfs_pub;
193 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
194 static uma_zone_t vnode_zone;
195 static uma_zone_t vnodepoll_zone;
198 * The workitem queue.
200 * It is useful to delay writes of file data and filesystem metadata
201 * for tens of seconds so that quickly created and deleted files need
202 * not waste disk bandwidth being created and removed. To realize this,
203 * we append vnodes to a "workitem" queue. When running with a soft
204 * updates implementation, most pending metadata dependencies should
205 * not wait for more than a few seconds. Thus, mounted on block devices
206 * are delayed only about a half the time that file data is delayed.
207 * Similarly, directory updates are more critical, so are only delayed
208 * about a third the time that file data is delayed. Thus, there are
209 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
210 * one each second (driven off the filesystem syncer process). The
211 * syncer_delayno variable indicates the next queue that is to be processed.
212 * Items that need to be processed soon are placed in this queue:
214 * syncer_workitem_pending[syncer_delayno]
216 * A delay of fifteen seconds is done by placing the request fifteen
217 * entries later in the queue:
219 * syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
222 static int syncer_delayno;
223 static long syncer_mask;
224 LIST_HEAD(synclist, bufobj);
225 static struct synclist *syncer_workitem_pending[2];
227 * The sync_mtx protects:
232 * syncer_workitem_pending
233 * syncer_worklist_len
236 static struct mtx sync_mtx;
237 static struct cv sync_wakeup;
239 #define SYNCER_MAXDELAY 32
240 static int syncer_maxdelay = SYNCER_MAXDELAY; /* maximum delay time */
241 static int syncdelay = 30; /* max time to delay syncing data */
242 static int filedelay = 30; /* time to delay syncing files */
243 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
244 "Time to delay syncing files (in seconds)");
245 static int dirdelay = 29; /* time to delay syncing directories */
246 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
247 "Time to delay syncing directories (in seconds)");
248 static int metadelay = 28; /* time to delay syncing metadata */
249 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
250 "Time to delay syncing metadata (in seconds)");
251 static int rushjob; /* number of slots to run ASAP */
252 static int stat_rush_requests; /* number of times I/O speeded up */
253 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
254 "Number of times I/O speeded up (rush requests)");
257 * When shutting down the syncer, run it at four times normal speed.
259 #define SYNCER_SHUTDOWN_SPEEDUP 4
260 static int sync_vnode_count;
261 static int syncer_worklist_len;
262 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
266 * Number of vnodes we want to exist at any one time. This is mostly used
267 * to size hash tables in vnode-related code. It is normally not used in
268 * getnewvnode(), as wantfreevnodes is normally nonzero.)
270 * XXX desiredvnodes is historical cruft and should not exist.
273 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
274 &desiredvnodes, 0, "Maximum number of vnodes");
275 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
276 &wantfreevnodes, 0, "Minimum number of vnodes (legacy)");
277 static int vnlru_nowhere;
278 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
279 &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
282 * Macros to control when a vnode is freed and recycled. All require
283 * the vnode interlock.
285 #define VCANRECYCLE(vp) (((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
286 #define VSHOULDFREE(vp) (!((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
287 #define VSHOULDBUSY(vp) (((vp)->v_iflag & VI_FREE) && (vp)->v_holdcnt)
291 * Initialize the vnode management data structures.
293 * Reevaluate the following cap on the number of vnodes after the physical
294 * memory size exceeds 512GB. In the limit, as the physical memory size
295 * grows, the ratio of physical pages to vnodes approaches sixteen to one.
297 #ifndef MAXVNODES_MAX
298 #define MAXVNODES_MAX (512 * (1024 * 1024 * 1024 / (int)PAGE_SIZE / 16))
301 vntblinit(void *dummy __unused)
303 int physvnodes, virtvnodes;
306 * Desiredvnodes is a function of the physical memory size and the
307 * kernel's heap size. Generally speaking, it scales with the
308 * physical memory size. The ratio of desiredvnodes to physical pages
309 * is one to four until desiredvnodes exceeds 98,304. Thereafter, the
310 * marginal ratio of desiredvnodes to physical pages is one to
311 * sixteen. However, desiredvnodes is limited by the kernel's heap
312 * size. The memory required by desiredvnodes vnodes and vm objects
313 * may not exceed one seventh of the kernel's heap size.
315 physvnodes = maxproc + cnt.v_page_count / 16 + 3 * min(98304 * 4,
316 cnt.v_page_count) / 16;
317 virtvnodes = vm_kmem_size / (7 * (sizeof(struct vm_object) +
318 sizeof(struct vnode)));
319 desiredvnodes = min(physvnodes, virtvnodes);
320 if (desiredvnodes > MAXVNODES_MAX) {
322 printf("Reducing kern.maxvnodes %d -> %d\n",
323 desiredvnodes, MAXVNODES_MAX);
324 desiredvnodes = MAXVNODES_MAX;
326 wantfreevnodes = desiredvnodes / 4;
327 mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
328 TAILQ_INIT(&vnode_free_list);
329 mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
330 vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
331 NULL, NULL, UMA_ALIGN_PTR, 0);
332 vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
333 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
335 * Initialize the filesystem syncer.
337 syncer_workitem_pending[WI_MPSAFEQ] = hashinit(syncer_maxdelay, M_VNODE,
339 syncer_workitem_pending[WI_GIANTQ] = hashinit(syncer_maxdelay, M_VNODE,
341 syncer_maxdelay = syncer_mask + 1;
342 mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
343 cv_init(&sync_wakeup, "syncer");
345 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
349 * Mark a mount point as busy. Used to synchronize access and to delay
350 * unmounting. Eventually, mountlist_mtx is not released on failure.
352 * vfs_busy() is a custom lock, it can block the caller.
353 * vfs_busy() only sleeps if the unmount is active on the mount point.
354 * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
355 * vnode belonging to mp.
357 * Lookup uses vfs_busy() to traverse mount points.
359 * / vnode lock A / vnode lock (/var) D
360 * /var vnode lock B /log vnode lock(/var/log) E
361 * vfs_busy lock C vfs_busy lock F
363 * Within each file system, the lock order is C->A->B and F->D->E.
365 * When traversing across mounts, the system follows that lock order:
371 * The lookup() process for namei("/var") illustrates the process:
372 * VOP_LOOKUP() obtains B while A is held
373 * vfs_busy() obtains a shared lock on F while A and B are held
374 * vput() releases lock on B
375 * vput() releases lock on A
376 * VFS_ROOT() obtains lock on D while shared lock on F is held
377 * vfs_unbusy() releases shared lock on F
378 * vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
379 * Attempt to lock A (instead of vp_crossmp) while D is held would
380 * violate the global order, causing deadlocks.
382 * dounmount() locks B while F is drained.
385 vfs_busy(struct mount *mp, int flags)
388 MPASS((flags & ~MBF_MASK) == 0);
389 CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
394 * If mount point is currenly being unmounted, sleep until the
395 * mount point fate is decided. If thread doing the unmounting fails,
396 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
397 * that this mount point has survived the unmount attempt and vfs_busy
398 * should retry. Otherwise the unmounter thread will set MNTK_REFEXPIRE
399 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
400 * about to be really destroyed. vfs_busy needs to release its
401 * reference on the mount point in this case and return with ENOENT,
402 * telling the caller that mount mount it tried to busy is no longer
405 while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
406 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
409 CTR1(KTR_VFS, "%s: failed busying before sleeping",
413 if (flags & MBF_MNTLSTLOCK)
414 mtx_unlock(&mountlist_mtx);
415 mp->mnt_kern_flag |= MNTK_MWAIT;
416 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
417 if (flags & MBF_MNTLSTLOCK)
418 mtx_lock(&mountlist_mtx);
421 if (flags & MBF_MNTLSTLOCK)
422 mtx_unlock(&mountlist_mtx);
429 * Free a busy filesystem.
432 vfs_unbusy(struct mount *mp)
435 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
438 KASSERT(mp->mnt_lockref > 0, ("negative mnt_lockref"));
440 if (mp->mnt_lockref == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
441 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
442 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
443 mp->mnt_kern_flag &= ~MNTK_DRAINING;
444 wakeup(&mp->mnt_lockref);
450 * Lookup a mount point by filesystem identifier.
453 vfs_getvfs(fsid_t *fsid)
457 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
458 mtx_lock(&mountlist_mtx);
459 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
460 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
461 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
463 mtx_unlock(&mountlist_mtx);
467 mtx_unlock(&mountlist_mtx);
468 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
469 return ((struct mount *) 0);
473 * Lookup a mount point by filesystem identifier, busying it before
477 vfs_busyfs(fsid_t *fsid)
482 CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
483 mtx_lock(&mountlist_mtx);
484 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
485 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
486 mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
487 error = vfs_busy(mp, MBF_MNTLSTLOCK);
489 mtx_unlock(&mountlist_mtx);
495 CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
496 mtx_unlock(&mountlist_mtx);
497 return ((struct mount *) 0);
501 * Check if a user can access privileged mount options.
504 vfs_suser(struct mount *mp, struct thread *td)
509 * If the thread is jailed, but this is not a jail-friendly file
510 * system, deny immediately.
512 if (!(mp->mnt_vfc->vfc_flags & VFCF_JAIL) && jailed(td->td_ucred))
516 * If the file system was mounted outside the jail of the calling
517 * thread, deny immediately.
519 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
523 * If file system supports delegated administration, we don't check
524 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
525 * by the file system itself.
526 * If this is not the user that did original mount, we check for
527 * the PRIV_VFS_MOUNT_OWNER privilege.
529 if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
530 mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
531 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
538 * Get a new unique fsid. Try to make its val[0] unique, since this value
539 * will be used to create fake device numbers for stat(). Also try (but
540 * not so hard) make its val[0] unique mod 2^16, since some emulators only
541 * support 16-bit device numbers. We end up with unique val[0]'s for the
542 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
544 * Keep in mind that several mounts may be running in parallel. Starting
545 * the search one past where the previous search terminated is both a
546 * micro-optimization and a defense against returning the same fsid to
550 vfs_getnewfsid(struct mount *mp)
552 static uint16_t mntid_base;
557 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
558 mtx_lock(&mntid_mtx);
559 mtype = mp->mnt_vfc->vfc_typenum;
560 tfsid.val[1] = mtype;
561 mtype = (mtype & 0xFF) << 24;
563 tfsid.val[0] = makedev(255,
564 mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
566 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
570 mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
571 mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
572 mtx_unlock(&mntid_mtx);
576 * Knob to control the precision of file timestamps:
578 * 0 = seconds only; nanoseconds zeroed.
579 * 1 = seconds and nanoseconds, accurate within 1/HZ.
580 * 2 = seconds and nanoseconds, truncated to microseconds.
581 * >=3 = seconds and nanoseconds, maximum precision.
583 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
585 static int timestamp_precision = TSP_SEC;
586 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
587 ×tamp_precision, 0, "File timestamp precision (0: seconds, "
588 "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to ms, "
589 "3+: sec + ns (max. precision))");
592 * Get a current timestamp.
595 vfs_timestamp(struct timespec *tsp)
599 switch (timestamp_precision) {
601 tsp->tv_sec = time_second;
609 TIMEVAL_TO_TIMESPEC(&tv, tsp);
619 * Set vnode attributes to VNOVAL
622 vattr_null(struct vattr *vap)
626 vap->va_size = VNOVAL;
627 vap->va_bytes = VNOVAL;
628 vap->va_mode = VNOVAL;
629 vap->va_nlink = VNOVAL;
630 vap->va_uid = VNOVAL;
631 vap->va_gid = VNOVAL;
632 vap->va_fsid = VNOVAL;
633 vap->va_fileid = VNOVAL;
634 vap->va_blocksize = VNOVAL;
635 vap->va_rdev = VNOVAL;
636 vap->va_atime.tv_sec = VNOVAL;
637 vap->va_atime.tv_nsec = VNOVAL;
638 vap->va_mtime.tv_sec = VNOVAL;
639 vap->va_mtime.tv_nsec = VNOVAL;
640 vap->va_ctime.tv_sec = VNOVAL;
641 vap->va_ctime.tv_nsec = VNOVAL;
642 vap->va_birthtime.tv_sec = VNOVAL;
643 vap->va_birthtime.tv_nsec = VNOVAL;
644 vap->va_flags = VNOVAL;
645 vap->va_gen = VNOVAL;
650 * This routine is called when we have too many vnodes. It attempts
651 * to free <count> vnodes and will potentially free vnodes that still
652 * have VM backing store (VM backing store is typically the cause
653 * of a vnode blowout so we want to do this). Therefore, this operation
654 * is not considered cheap.
656 * A number of conditions may prevent a vnode from being reclaimed.
657 * the buffer cache may have references on the vnode, a directory
658 * vnode may still have references due to the namei cache representing
659 * underlying files, or the vnode may be in active use. It is not
660 * desireable to reuse such vnodes. These conditions may cause the
661 * number of vnodes to reach some minimum value regardless of what
662 * you set kern.maxvnodes to. Do not set kern.maxvnodes too low.
665 vlrureclaim(struct mount *mp)
674 * Calculate the trigger point, don't allow user
675 * screwups to blow us up. This prevents us from
676 * recycling vnodes with lots of resident pages. We
677 * aren't trying to free memory, we are trying to
680 usevnodes = desiredvnodes;
683 trigger = cnt.v_page_count * 2 / usevnodes;
685 vn_start_write(NULL, &mp, V_WAIT);
687 count = mp->mnt_nvnodelistsize / 10 + 1;
689 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
690 while (vp != NULL && vp->v_type == VMARKER)
691 vp = TAILQ_NEXT(vp, v_nmntvnodes);
694 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
695 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
700 * If it's been deconstructed already, it's still
701 * referenced, or it exceeds the trigger, skip it.
703 if (vp->v_usecount ||
704 (!vlru_allow_cache_src &&
705 !LIST_EMPTY(&(vp)->v_cache_src)) ||
706 (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
707 vp->v_object->resident_page_count > trigger)) {
713 if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT)) {
715 goto next_iter_mntunlocked;
719 * v_usecount may have been bumped after VOP_LOCK() dropped
720 * the vnode interlock and before it was locked again.
722 * It is not necessary to recheck VI_DOOMED because it can
723 * only be set by another thread that holds both the vnode
724 * lock and vnode interlock. If another thread has the
725 * vnode lock before we get to VOP_LOCK() and obtains the
726 * vnode interlock after VOP_LOCK() drops the vnode
727 * interlock, the other thread will be unable to drop the
728 * vnode lock before our VOP_LOCK() call fails.
730 if (vp->v_usecount ||
731 (!vlru_allow_cache_src &&
732 !LIST_EMPTY(&(vp)->v_cache_src)) ||
733 (vp->v_object != NULL &&
734 vp->v_object->resident_page_count > trigger)) {
735 VOP_UNLOCK(vp, LK_INTERLOCK);
736 goto next_iter_mntunlocked;
738 KASSERT((vp->v_iflag & VI_DOOMED) == 0,
739 ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
744 next_iter_mntunlocked:
753 kern_yield(PRI_UNCHANGED);
758 vn_finished_write(mp);
763 * Attempt to keep the free list at wantfreevnodes length.
766 vnlru_free(int count)
771 mtx_assert(&vnode_free_list_mtx, MA_OWNED);
772 for (; count > 0; count--) {
773 vp = TAILQ_FIRST(&vnode_free_list);
775 * The list can be modified while the free_list_mtx
776 * has been dropped and vp could be NULL here.
780 VNASSERT(vp->v_op != NULL, vp,
781 ("vnlru_free: vnode already reclaimed."));
782 TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
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_freelist);
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 vdestroy(struct vnode *vp)
887 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
888 mtx_lock(&vnode_free_list_mtx);
890 mtx_unlock(&vnode_free_list_mtx);
892 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
893 ("cleaned vnode still on the free list."));
894 VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
895 VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
896 VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
897 VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
898 VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
899 VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
900 VNASSERT(bo->bo_clean.bv_root == NULL, vp, ("cleanblkroot not NULL"));
901 VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
902 VNASSERT(bo->bo_dirty.bv_root == NULL, vp, ("dirtyblkroot not NULL"));
903 VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
904 VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
905 VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
908 mac_vnode_destroy(vp);
910 if (vp->v_pollinfo != NULL)
911 destroy_vpollinfo(vp->v_pollinfo);
913 /* XXX Elsewhere we can detect an already freed vnode via NULL v_op. */
916 lockdestroy(vp->v_vnlock);
917 mtx_destroy(&vp->v_interlock);
918 mtx_destroy(BO_MTX(bo));
919 uma_zfree(vnode_zone, vp);
923 * Try to recycle a freed vnode. We abort if anyone picks up a reference
924 * before we actually vgone(). This function must be called with the vnode
925 * held to prevent the vnode from being returned to the free list midway
929 vtryrecycle(struct vnode *vp)
933 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
934 VNASSERT(vp->v_holdcnt, vp,
935 ("vtryrecycle: Recycling vp %p without a reference.", vp));
937 * This vnode may found and locked via some other list, if so we
938 * can't recycle it yet.
940 if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
942 "%s: impossible to recycle, vp %p lock is already held",
944 return (EWOULDBLOCK);
947 * Don't recycle if its filesystem is being suspended.
949 if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
952 "%s: impossible to recycle, cannot start the write for %p",
957 * If we got this far, we need to acquire the interlock and see if
958 * anyone picked up this vnode from another list. If not, we will
959 * mark it with DOOMED via vgonel() so that anyone who does find it
963 if (vp->v_usecount) {
964 VOP_UNLOCK(vp, LK_INTERLOCK);
965 vn_finished_write(vnmp);
967 "%s: impossible to recycle, %p is already referenced",
971 if ((vp->v_iflag & VI_DOOMED) == 0)
973 VOP_UNLOCK(vp, LK_INTERLOCK);
974 vn_finished_write(vnmp);
979 * Return the next vnode from the free list.
982 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
985 struct vnode *vp = NULL;
988 CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
989 mtx_lock(&vnode_free_list_mtx);
991 * Lend our context to reclaim vnodes if they've exceeded the max.
993 if (freevnodes > wantfreevnodes)
996 * Wait for available vnodes.
998 if (numvnodes > desiredvnodes) {
999 if (mp != NULL && (mp->mnt_kern_flag & MNTK_SUSPEND)) {
1001 * File system is beeing suspended, we cannot risk a
1002 * deadlock here, so allocate new vnode anyway.
1004 if (freevnodes > wantfreevnodes)
1005 vnlru_free(freevnodes - wantfreevnodes);
1008 if (vnlruproc_sig == 0) {
1009 vnlruproc_sig = 1; /* avoid unnecessary wakeups */
1012 msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
1014 #if 0 /* XXX Not all VFS_VGET/ffs_vget callers check returns. */
1015 if (numvnodes > desiredvnodes) {
1016 mtx_unlock(&vnode_free_list_mtx);
1023 mtx_unlock(&vnode_free_list_mtx);
1024 vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK|M_ZERO);
1028 vp->v_vnlock = &vp->v_lock;
1029 mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
1031 * By default, don't allow shared locks unless filesystems
1034 lockinit(vp->v_vnlock, PVFS, tag, VLKTIMEOUT, LK_NOSHARE);
1036 * Initialize bufobj.
1039 bo->__bo_vnode = vp;
1040 mtx_init(BO_MTX(bo), "bufobj interlock", NULL, MTX_DEF);
1041 bo->bo_ops = &buf_ops_bio;
1042 bo->bo_private = vp;
1043 TAILQ_INIT(&bo->bo_clean.bv_hd);
1044 TAILQ_INIT(&bo->bo_dirty.bv_hd);
1046 * Initialize namecache.
1048 LIST_INIT(&vp->v_cache_src);
1049 TAILQ_INIT(&vp->v_cache_dst);
1051 * Finalize various vnode identity bits.
1056 v_incr_usecount(vp);
1060 if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1061 mac_vnode_associate_singlelabel(mp, vp);
1062 else if (mp == NULL && vops != &dead_vnodeops)
1063 printf("NULL mp in getnewvnode()\n");
1066 bo->bo_bsize = mp->mnt_stat.f_iosize;
1067 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1068 vp->v_vflag |= VV_NOKNOTE;
1076 * Delete from old mount point vnode list, if on one.
1079 delmntque(struct vnode *vp)
1088 VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1089 ("bad mount point vnode list size"));
1090 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1091 mp->mnt_nvnodelistsize--;
1097 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1101 vp->v_op = &dead_vnodeops;
1102 /* XXX non mp-safe fs may still call insmntque with vnode
1104 if (!VOP_ISLOCKED(vp))
1105 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1111 * Insert into list of vnodes for the new mount point, if available.
1114 insmntque1(struct vnode *vp, struct mount *mp,
1115 void (*dtr)(struct vnode *, void *), void *dtr_arg)
1119 KASSERT(vp->v_mount == NULL,
1120 ("insmntque: vnode already on per mount vnode list"));
1121 VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1122 #ifdef DEBUG_VFS_LOCKS
1123 if (!VFS_NEEDSGIANT(mp))
1124 ASSERT_VOP_ELOCKED(vp,
1125 "insmntque: mp-safe fs and non-locked vp");
1128 if ((mp->mnt_kern_flag & MNTK_NOINSMNTQ) != 0 &&
1129 ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1130 mp->mnt_nvnodelistsize == 0)) {
1131 locked = VOP_ISLOCKED(vp);
1132 if (!locked || (locked == LK_EXCLUSIVE &&
1133 (vp->v_vflag & VV_FORCEINSMQ) == 0)) {
1142 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1143 VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1144 ("neg mount point vnode list size"));
1145 mp->mnt_nvnodelistsize++;
1151 insmntque(struct vnode *vp, struct mount *mp)
1154 return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1158 * Flush out and invalidate all buffers associated with a bufobj
1159 * Called with the underlying object locked.
1162 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1167 if (flags & V_SAVE) {
1168 error = bufobj_wwait(bo, slpflag, slptimeo);
1173 if (bo->bo_dirty.bv_cnt > 0) {
1175 if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1178 * XXX We could save a lock/unlock if this was only
1179 * enabled under INVARIANTS
1182 if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1183 panic("vinvalbuf: dirty bufs");
1187 * If you alter this loop please notice that interlock is dropped and
1188 * reacquired in flushbuflist. Special care is needed to ensure that
1189 * no race conditions occur from this.
1192 error = flushbuflist(&bo->bo_clean,
1193 flags, bo, slpflag, slptimeo);
1195 error = flushbuflist(&bo->bo_dirty,
1196 flags, bo, slpflag, slptimeo);
1197 if (error != 0 && error != EAGAIN) {
1201 } while (error != 0);
1204 * Wait for I/O to complete. XXX needs cleaning up. The vnode can
1205 * have write I/O in-progress but if there is a VM object then the
1206 * VM object can also have read-I/O in-progress.
1209 bufobj_wwait(bo, 0, 0);
1211 if (bo->bo_object != NULL) {
1212 VM_OBJECT_LOCK(bo->bo_object);
1213 vm_object_pip_wait(bo->bo_object, "bovlbx");
1214 VM_OBJECT_UNLOCK(bo->bo_object);
1217 } while (bo->bo_numoutput > 0);
1221 * Destroy the copy in the VM cache, too.
1223 if (bo->bo_object != NULL && (flags & (V_ALT | V_NORMAL)) == 0) {
1224 VM_OBJECT_LOCK(bo->bo_object);
1225 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1226 OBJPR_CLEANONLY : 0);
1227 VM_OBJECT_UNLOCK(bo->bo_object);
1232 if ((flags & (V_ALT | V_NORMAL)) == 0 &&
1233 (bo->bo_dirty.bv_cnt > 0 || bo->bo_clean.bv_cnt > 0))
1234 panic("vinvalbuf: flush failed");
1241 * Flush out and invalidate all buffers associated with a vnode.
1242 * Called with the underlying object locked.
1245 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1248 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1249 ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1250 return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1254 * Flush out buffers on the specified list.
1258 flushbuflist( struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1261 struct buf *bp, *nbp;
1266 ASSERT_BO_LOCKED(bo);
1269 TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1270 if (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA)) ||
1271 ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0)) {
1277 lblkno = nbp->b_lblkno;
1278 xflags = nbp->b_xflags &
1279 (BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN);
1282 error = BUF_TIMELOCK(bp,
1283 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_MTX(bo),
1284 "flushbuf", slpflag, slptimeo);
1287 return (error != ENOLCK ? error : EAGAIN);
1289 KASSERT(bp->b_bufobj == bo,
1290 ("bp %p wrong b_bufobj %p should be %p",
1291 bp, bp->b_bufobj, bo));
1292 if (bp->b_bufobj != bo) { /* XXX: necessary ? */
1298 * XXX Since there are no node locks for NFS, I
1299 * believe there is a slight chance that a delayed
1300 * write will occur while sleeping just above, so
1303 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1308 bp->b_flags |= B_ASYNC;
1311 return (EAGAIN); /* XXX: why not loop ? */
1316 bp->b_flags |= (B_INVAL | B_RELBUF);
1317 bp->b_flags &= ~B_ASYNC;
1321 (nbp->b_bufobj != bo ||
1322 nbp->b_lblkno != lblkno ||
1324 (BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN)) != xflags))
1325 break; /* nbp invalid */
1331 * Truncate a file's buffer and pages to a specified length. This
1332 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
1336 vtruncbuf(struct vnode *vp, struct ucred *cred, struct thread *td,
1337 off_t length, int blksize)
1339 struct buf *bp, *nbp;
1344 CTR5(KTR_VFS, "%s: vp %p with cred %p and block %d:%ju", __func__,
1345 vp, cred, blksize, (uintmax_t)length);
1348 * Round up to the *next* lbn.
1350 trunclbn = (length + blksize - 1) / blksize;
1352 ASSERT_VOP_LOCKED(vp, "vtruncbuf");
1359 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
1360 if (bp->b_lblkno < trunclbn)
1363 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1364 BO_MTX(bo)) == ENOLCK)
1370 bp->b_flags |= (B_INVAL | B_RELBUF);
1371 bp->b_flags &= ~B_ASYNC;
1377 (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
1378 (nbp->b_vp != vp) ||
1379 (nbp->b_flags & B_DELWRI))) {
1385 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1386 if (bp->b_lblkno < trunclbn)
1389 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1390 BO_MTX(bo)) == ENOLCK)
1395 bp->b_flags |= (B_INVAL | B_RELBUF);
1396 bp->b_flags &= ~B_ASYNC;
1402 (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
1403 (nbp->b_vp != vp) ||
1404 (nbp->b_flags & B_DELWRI) == 0)) {
1413 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1414 if (bp->b_lblkno > 0)
1417 * Since we hold the vnode lock this should only
1418 * fail if we're racing with the buf daemon.
1421 LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1422 BO_MTX(bo)) == ENOLCK) {
1425 VNASSERT((bp->b_flags & B_DELWRI), vp,
1426 ("buf(%p) on dirty queue without DELWRI", bp));
1437 bufobj_wwait(bo, 0, 0);
1439 vnode_pager_setsize(vp, length);
1445 * buf_splay() - splay tree core for the clean/dirty list of buffers in
1448 * NOTE: We have to deal with the special case of a background bitmap
1449 * buffer, a situation where two buffers will have the same logical
1450 * block offset. We want (1) only the foreground buffer to be accessed
1451 * in a lookup and (2) must differentiate between the foreground and
1452 * background buffer in the splay tree algorithm because the splay
1453 * tree cannot normally handle multiple entities with the same 'index'.
1454 * We accomplish this by adding differentiating flags to the splay tree's
1459 buf_splay(daddr_t lblkno, b_xflags_t xflags, struct buf *root)
1462 struct buf *lefttreemax, *righttreemin, *y;
1466 lefttreemax = righttreemin = &dummy;
1468 if (lblkno < root->b_lblkno ||
1469 (lblkno == root->b_lblkno &&
1470 (xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
1471 if ((y = root->b_left) == NULL)
1473 if (lblkno < y->b_lblkno) {
1475 root->b_left = y->b_right;
1478 if ((y = root->b_left) == NULL)
1481 /* Link into the new root's right tree. */
1482 righttreemin->b_left = root;
1483 righttreemin = root;
1484 } else if (lblkno > root->b_lblkno ||
1485 (lblkno == root->b_lblkno &&
1486 (xflags & BX_BKGRDMARKER) > (root->b_xflags & BX_BKGRDMARKER))) {
1487 if ((y = root->b_right) == NULL)
1489 if (lblkno > y->b_lblkno) {
1491 root->b_right = y->b_left;
1494 if ((y = root->b_right) == NULL)
1497 /* Link into the new root's left tree. */
1498 lefttreemax->b_right = root;
1505 /* Assemble the new root. */
1506 lefttreemax->b_right = root->b_left;
1507 righttreemin->b_left = root->b_right;
1508 root->b_left = dummy.b_right;
1509 root->b_right = dummy.b_left;
1514 buf_vlist_remove(struct buf *bp)
1519 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1520 ASSERT_BO_LOCKED(bp->b_bufobj);
1521 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
1522 (BX_VNDIRTY|BX_VNCLEAN),
1523 ("buf_vlist_remove: Buf %p is on two lists", bp));
1524 if (bp->b_xflags & BX_VNDIRTY)
1525 bv = &bp->b_bufobj->bo_dirty;
1527 bv = &bp->b_bufobj->bo_clean;
1528 if (bp != bv->bv_root) {
1529 root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1530 KASSERT(root == bp, ("splay lookup failed in remove"));
1532 if (bp->b_left == NULL) {
1535 root = buf_splay(bp->b_lblkno, bp->b_xflags, bp->b_left);
1536 root->b_right = bp->b_right;
1539 TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
1541 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1545 * Add the buffer to the sorted clean or dirty block list using a
1546 * splay tree algorithm.
1548 * NOTE: xflags is passed as a constant, optimizing this inline function!
1551 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
1556 ASSERT_BO_LOCKED(bo);
1557 KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
1558 ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
1559 bp->b_xflags |= xflags;
1560 if (xflags & BX_VNDIRTY)
1565 root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1569 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
1570 } else if (bp->b_lblkno < root->b_lblkno ||
1571 (bp->b_lblkno == root->b_lblkno &&
1572 (bp->b_xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
1573 bp->b_left = root->b_left;
1575 root->b_left = NULL;
1576 TAILQ_INSERT_BEFORE(root, bp, b_bobufs);
1578 bp->b_right = root->b_right;
1580 root->b_right = NULL;
1581 TAILQ_INSERT_AFTER(&bv->bv_hd, root, bp, b_bobufs);
1588 * Lookup a buffer using the splay tree. Note that we specifically avoid
1589 * shadow buffers used in background bitmap writes.
1591 * This code isn't quite efficient as it could be because we are maintaining
1592 * two sorted lists and do not know which list the block resides in.
1594 * During a "make buildworld" the desired buffer is found at one of
1595 * the roots more than 60% of the time. Thus, checking both roots
1596 * before performing either splay eliminates unnecessary splays on the
1597 * first tree splayed.
1600 gbincore(struct bufobj *bo, daddr_t lblkno)
1604 ASSERT_BO_LOCKED(bo);
1605 if ((bp = bo->bo_clean.bv_root) != NULL &&
1606 bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1608 if ((bp = bo->bo_dirty.bv_root) != NULL &&
1609 bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1611 if ((bp = bo->bo_clean.bv_root) != NULL) {
1612 bo->bo_clean.bv_root = bp = buf_splay(lblkno, 0, bp);
1613 if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1616 if ((bp = bo->bo_dirty.bv_root) != NULL) {
1617 bo->bo_dirty.bv_root = bp = buf_splay(lblkno, 0, bp);
1618 if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1625 * Associate a buffer with a vnode.
1628 bgetvp(struct vnode *vp, struct buf *bp)
1633 ASSERT_BO_LOCKED(bo);
1634 VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
1636 CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
1637 VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
1638 ("bgetvp: bp already attached! %p", bp));
1641 if (VFS_NEEDSGIANT(vp->v_mount) || bo->bo_flag & BO_NEEDSGIANT)
1642 bp->b_flags |= B_NEEDSGIANT;
1646 * Insert onto list for new vnode.
1648 buf_vlist_add(bp, bo, BX_VNCLEAN);
1652 * Disassociate a buffer from a vnode.
1655 brelvp(struct buf *bp)
1660 CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1661 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1664 * Delete from old vnode list, if on one.
1666 vp = bp->b_vp; /* XXX */
1669 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1670 buf_vlist_remove(bp);
1672 panic("brelvp: Buffer %p not on queue.", bp);
1673 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1674 bo->bo_flag &= ~BO_ONWORKLST;
1675 mtx_lock(&sync_mtx);
1676 LIST_REMOVE(bo, bo_synclist);
1677 syncer_worklist_len--;
1678 mtx_unlock(&sync_mtx);
1680 bp->b_flags &= ~B_NEEDSGIANT;
1682 bp->b_bufobj = NULL;
1688 * Add an item to the syncer work queue.
1691 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
1695 ASSERT_BO_LOCKED(bo);
1697 mtx_lock(&sync_mtx);
1698 if (bo->bo_flag & BO_ONWORKLST)
1699 LIST_REMOVE(bo, bo_synclist);
1701 bo->bo_flag |= BO_ONWORKLST;
1702 syncer_worklist_len++;
1705 if (delay > syncer_maxdelay - 2)
1706 delay = syncer_maxdelay - 2;
1707 slot = (syncer_delayno + delay) & syncer_mask;
1709 queue = VFS_NEEDSGIANT(bo->__bo_vnode->v_mount) ? WI_GIANTQ :
1711 LIST_INSERT_HEAD(&syncer_workitem_pending[queue][slot], bo,
1713 mtx_unlock(&sync_mtx);
1717 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
1721 mtx_lock(&sync_mtx);
1722 len = syncer_worklist_len - sync_vnode_count;
1723 mtx_unlock(&sync_mtx);
1724 error = SYSCTL_OUT(req, &len, sizeof(len));
1728 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
1729 sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
1731 static struct proc *updateproc;
1732 static void sched_sync(void);
1733 static struct kproc_desc up_kp = {
1738 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
1741 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
1746 *bo = LIST_FIRST(slp);
1749 vp = (*bo)->__bo_vnode; /* XXX */
1750 if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
1753 * We use vhold in case the vnode does not
1754 * successfully sync. vhold prevents the vnode from
1755 * going away when we unlock the sync_mtx so that
1756 * we can acquire the vnode interlock.
1759 mtx_unlock(&sync_mtx);
1761 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1763 mtx_lock(&sync_mtx);
1764 return (*bo == LIST_FIRST(slp));
1766 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1767 (void) VOP_FSYNC(vp, MNT_LAZY, td);
1769 vn_finished_write(mp);
1771 if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
1773 * Put us back on the worklist. The worklist
1774 * routine will remove us from our current
1775 * position and then add us back in at a later
1778 vn_syncer_add_to_worklist(*bo, syncdelay);
1782 mtx_lock(&sync_mtx);
1787 * System filesystem synchronizer daemon.
1792 struct synclist *gnext, *next;
1793 struct synclist *gslp, *slp;
1796 struct thread *td = curthread;
1798 int net_worklist_len;
1799 int syncer_final_iter;
1804 syncer_final_iter = 0;
1806 syncer_state = SYNCER_RUNNING;
1807 starttime = time_uptime;
1808 td->td_pflags |= TDP_NORUNNINGBUF;
1810 EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
1813 mtx_lock(&sync_mtx);
1815 if (syncer_state == SYNCER_FINAL_DELAY &&
1816 syncer_final_iter == 0) {
1817 mtx_unlock(&sync_mtx);
1818 kproc_suspend_check(td->td_proc);
1819 mtx_lock(&sync_mtx);
1821 net_worklist_len = syncer_worklist_len - sync_vnode_count;
1822 if (syncer_state != SYNCER_RUNNING &&
1823 starttime != time_uptime) {
1825 printf("\nSyncing disks, vnodes remaining...");
1828 printf("%d ", net_worklist_len);
1830 starttime = time_uptime;
1833 * Push files whose dirty time has expired. Be careful
1834 * of interrupt race on slp queue.
1836 * Skip over empty worklist slots when shutting down.
1839 slp = &syncer_workitem_pending[WI_MPSAFEQ][syncer_delayno];
1840 gslp = &syncer_workitem_pending[WI_GIANTQ][syncer_delayno];
1841 syncer_delayno += 1;
1842 if (syncer_delayno == syncer_maxdelay)
1844 next = &syncer_workitem_pending[WI_MPSAFEQ][syncer_delayno];
1845 gnext = &syncer_workitem_pending[WI_GIANTQ][syncer_delayno];
1847 * If the worklist has wrapped since the
1848 * it was emptied of all but syncer vnodes,
1849 * switch to the FINAL_DELAY state and run
1850 * for one more second.
1852 if (syncer_state == SYNCER_SHUTTING_DOWN &&
1853 net_worklist_len == 0 &&
1854 last_work_seen == syncer_delayno) {
1855 syncer_state = SYNCER_FINAL_DELAY;
1856 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
1858 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
1859 LIST_EMPTY(gslp) && syncer_worklist_len > 0);
1862 * Keep track of the last time there was anything
1863 * on the worklist other than syncer vnodes.
1864 * Return to the SHUTTING_DOWN state if any
1867 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
1868 last_work_seen = syncer_delayno;
1869 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
1870 syncer_state = SYNCER_SHUTTING_DOWN;
1871 while (!LIST_EMPTY(slp)) {
1872 error = sync_vnode(slp, &bo, td);
1874 LIST_REMOVE(bo, bo_synclist);
1875 LIST_INSERT_HEAD(next, bo, bo_synclist);
1879 if (first_printf == 0)
1880 wdog_kern_pat(WD_LASTVAL);
1883 if (!LIST_EMPTY(gslp)) {
1884 mtx_unlock(&sync_mtx);
1886 mtx_lock(&sync_mtx);
1887 while (!LIST_EMPTY(gslp)) {
1888 error = sync_vnode(gslp, &bo, td);
1890 LIST_REMOVE(bo, bo_synclist);
1891 LIST_INSERT_HEAD(gnext, bo,
1898 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
1899 syncer_final_iter--;
1901 * The variable rushjob allows the kernel to speed up the
1902 * processing of the filesystem syncer process. A rushjob
1903 * value of N tells the filesystem syncer to process the next
1904 * N seconds worth of work on its queue ASAP. Currently rushjob
1905 * is used by the soft update code to speed up the filesystem
1906 * syncer process when the incore state is getting so far
1907 * ahead of the disk that the kernel memory pool is being
1908 * threatened with exhaustion.
1915 * Just sleep for a short period of time between
1916 * iterations when shutting down to allow some I/O
1919 * If it has taken us less than a second to process the
1920 * current work, then wait. Otherwise start right over
1921 * again. We can still lose time if any single round
1922 * takes more than two seconds, but it does not really
1923 * matter as we are just trying to generally pace the
1924 * filesystem activity.
1926 if (syncer_state != SYNCER_RUNNING ||
1927 time_uptime == starttime) {
1929 sched_prio(td, PPAUSE);
1932 if (syncer_state != SYNCER_RUNNING)
1933 cv_timedwait(&sync_wakeup, &sync_mtx,
1934 hz / SYNCER_SHUTDOWN_SPEEDUP);
1935 else if (time_uptime == starttime)
1936 cv_timedwait(&sync_wakeup, &sync_mtx, hz);
1941 * Request the syncer daemon to speed up its work.
1942 * We never push it to speed up more than half of its
1943 * normal turn time, otherwise it could take over the cpu.
1946 speedup_syncer(void)
1950 mtx_lock(&sync_mtx);
1951 if (rushjob < syncdelay / 2) {
1953 stat_rush_requests += 1;
1956 mtx_unlock(&sync_mtx);
1957 cv_broadcast(&sync_wakeup);
1962 * Tell the syncer to speed up its work and run though its work
1963 * list several times, then tell it to shut down.
1966 syncer_shutdown(void *arg, int howto)
1969 if (howto & RB_NOSYNC)
1971 mtx_lock(&sync_mtx);
1972 syncer_state = SYNCER_SHUTTING_DOWN;
1974 mtx_unlock(&sync_mtx);
1975 cv_broadcast(&sync_wakeup);
1976 kproc_shutdown(arg, howto);
1980 * Reassign a buffer from one vnode to another.
1981 * Used to assign file specific control information
1982 * (indirect blocks) to the vnode to which they belong.
1985 reassignbuf(struct buf *bp)
1998 CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
1999 bp, bp->b_vp, bp->b_flags);
2001 * B_PAGING flagged buffers cannot be reassigned because their vp
2002 * is not fully linked in.
2004 if (bp->b_flags & B_PAGING)
2005 panic("cannot reassign paging buffer");
2008 * Delete from old vnode list, if on one.
2011 if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2012 buf_vlist_remove(bp);
2014 panic("reassignbuf: Buffer %p not on queue.", bp);
2016 * If dirty, put on list of dirty buffers; otherwise insert onto list
2019 if (bp->b_flags & B_DELWRI) {
2020 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2021 switch (vp->v_type) {
2031 vn_syncer_add_to_worklist(bo, delay);
2033 buf_vlist_add(bp, bo, BX_VNDIRTY);
2035 buf_vlist_add(bp, bo, BX_VNCLEAN);
2037 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2038 mtx_lock(&sync_mtx);
2039 LIST_REMOVE(bo, bo_synclist);
2040 syncer_worklist_len--;
2041 mtx_unlock(&sync_mtx);
2042 bo->bo_flag &= ~BO_ONWORKLST;
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));
2054 bp = TAILQ_FIRST(&bv->bv_hd);
2055 KASSERT(bp == NULL || bp->b_bufobj == bo,
2056 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2057 bp = TAILQ_LAST(&bv->bv_hd, buflists);
2058 KASSERT(bp == NULL || bp->b_bufobj == bo,
2059 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2065 * Increment the use and hold counts on the vnode, taking care to reference
2066 * the driver's usecount if this is a chardev. The vholdl() will remove
2067 * the vnode from the free list if it is presently free. Requires the
2068 * vnode interlock and returns with it held.
2071 v_incr_usecount(struct vnode *vp)
2074 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2076 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2078 vp->v_rdev->si_usecount++;
2085 * Turn a holdcnt into a use+holdcnt such that only one call to
2086 * v_decr_usecount is needed.
2089 v_upgrade_usecount(struct vnode *vp)
2092 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2094 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2096 vp->v_rdev->si_usecount++;
2102 * Decrement the vnode use and hold count along with the driver's usecount
2103 * if this is a chardev. The vdropl() below releases the vnode interlock
2104 * as it may free the vnode.
2107 v_decr_usecount(struct vnode *vp)
2110 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2111 VNASSERT(vp->v_usecount > 0, vp,
2112 ("v_decr_usecount: negative usecount"));
2113 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2115 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2117 vp->v_rdev->si_usecount--;
2124 * Decrement only the use count and driver use count. This is intended to
2125 * be paired with a follow on vdropl() to release the remaining hold count.
2126 * In this way we may vgone() a vnode with a 0 usecount without risk of
2127 * having it end up on a free list because the hold count is kept above 0.
2130 v_decr_useonly(struct vnode *vp)
2133 ASSERT_VI_LOCKED(vp, __FUNCTION__);
2134 VNASSERT(vp->v_usecount > 0, vp,
2135 ("v_decr_useonly: negative usecount"));
2136 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2138 if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2140 vp->v_rdev->si_usecount--;
2146 * Grab a particular vnode from the free list, increment its
2147 * reference count and lock it. VI_DOOMED is set if the vnode
2148 * is being destroyed. Only callers who specify LK_RETRY will
2149 * see doomed vnodes. If inactive processing was delayed in
2150 * vput try to do it here.
2153 vget(struct vnode *vp, int flags, struct thread *td)
2158 VFS_ASSERT_GIANT(vp->v_mount);
2159 VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2160 ("vget: invalid lock operation"));
2161 CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2163 if ((flags & LK_INTERLOCK) == 0)
2166 if ((error = vn_lock(vp, flags | LK_INTERLOCK)) != 0) {
2168 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2172 if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0)
2173 panic("vget: vn_lock failed to return ENOENT\n");
2175 /* Upgrade our holdcnt to a usecount. */
2176 v_upgrade_usecount(vp);
2178 * We don't guarantee that any particular close will
2179 * trigger inactive processing so just make a best effort
2180 * here at preventing a reference to a removed file. If
2181 * we don't succeed no harm is done.
2183 if (vp->v_iflag & VI_OWEINACT) {
2184 if (VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2185 (flags & LK_NOWAIT) == 0)
2187 vp->v_iflag &= ~VI_OWEINACT;
2194 * Increase the reference count of a vnode.
2197 vref(struct vnode *vp)
2200 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2202 v_incr_usecount(vp);
2207 * Return reference count of a vnode.
2209 * The results of this call are only guaranteed when some mechanism other
2210 * than the VI lock is used to stop other processes from gaining references
2211 * to the vnode. This may be the case if the caller holds the only reference.
2212 * This is also useful when stale data is acceptable as race conditions may
2213 * be accounted for by some other means.
2216 vrefcnt(struct vnode *vp)
2221 usecnt = vp->v_usecount;
2227 #define VPUTX_VRELE 1
2228 #define VPUTX_VPUT 2
2229 #define VPUTX_VUNREF 3
2232 vputx(struct vnode *vp, int func)
2236 KASSERT(vp != NULL, ("vputx: null vp"));
2237 if (func == VPUTX_VUNREF)
2238 ASSERT_VOP_LOCKED(vp, "vunref");
2239 else if (func == VPUTX_VPUT)
2240 ASSERT_VOP_LOCKED(vp, "vput");
2242 KASSERT(func == VPUTX_VRELE, ("vputx: wrong func"));
2243 VFS_ASSERT_GIANT(vp->v_mount);
2244 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2247 /* Skip this v_writecount check if we're going to panic below. */
2248 VNASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1, vp,
2249 ("vputx: missed vn_close"));
2252 if (vp->v_usecount > 1 || ((vp->v_iflag & VI_DOINGINACT) &&
2253 vp->v_usecount == 1)) {
2254 if (func == VPUTX_VPUT)
2256 v_decr_usecount(vp);
2260 if (vp->v_usecount != 1) {
2261 vprint("vputx: negative ref count", vp);
2262 panic("vputx: negative ref cnt");
2264 CTR2(KTR_VFS, "%s: return vnode %p to the freelist", __func__, vp);
2266 * We want to hold the vnode until the inactive finishes to
2267 * prevent vgone() races. We drop the use count here and the
2268 * hold count below when we're done.
2272 * We must call VOP_INACTIVE with the node locked. Mark
2273 * as VI_DOINGINACT to avoid recursion.
2275 vp->v_iflag |= VI_OWEINACT;
2278 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
2282 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2283 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
2289 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
2293 if (vp->v_usecount > 0)
2294 vp->v_iflag &= ~VI_OWEINACT;
2296 if (vp->v_iflag & VI_OWEINACT)
2297 vinactive(vp, curthread);
2298 if (func != VPUTX_VUNREF)
2305 * Vnode put/release.
2306 * If count drops to zero, call inactive routine and return to freelist.
2309 vrele(struct vnode *vp)
2312 vputx(vp, VPUTX_VRELE);
2316 * Release an already locked vnode. This give the same effects as
2317 * unlock+vrele(), but takes less time and avoids releasing and
2318 * re-aquiring the lock (as vrele() acquires the lock internally.)
2321 vput(struct vnode *vp)
2324 vputx(vp, VPUTX_VPUT);
2328 * Release an exclusively locked vnode. Do not unlock the vnode lock.
2331 vunref(struct vnode *vp)
2334 vputx(vp, VPUTX_VUNREF);
2338 * Somebody doesn't want the vnode recycled.
2341 vhold(struct vnode *vp)
2350 vholdl(struct vnode *vp)
2353 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2355 if (VSHOULDBUSY(vp))
2360 * Note that there is one less who cares about this vnode. vdrop() is the
2361 * opposite of vhold().
2364 vdrop(struct vnode *vp)
2372 * Drop the hold count of the vnode. If this is the last reference to
2373 * the vnode we will free it if it has been vgone'd otherwise it is
2374 * placed on the free list.
2377 vdropl(struct vnode *vp)
2380 ASSERT_VI_LOCKED(vp, "vdropl");
2381 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2382 if (vp->v_holdcnt <= 0)
2383 panic("vdrop: holdcnt %d", vp->v_holdcnt);
2385 if (vp->v_holdcnt == 0) {
2386 if (vp->v_iflag & VI_DOOMED) {
2387 CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__,
2398 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
2399 * flags. DOINGINACT prevents us from recursing in calls to vinactive.
2400 * OWEINACT tracks whether a vnode missed a call to inactive due to a
2401 * failed lock upgrade.
2404 vinactive(struct vnode *vp, struct thread *td)
2407 ASSERT_VOP_ELOCKED(vp, "vinactive");
2408 ASSERT_VI_LOCKED(vp, "vinactive");
2409 VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
2410 ("vinactive: recursed on VI_DOINGINACT"));
2411 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2412 vp->v_iflag |= VI_DOINGINACT;
2413 vp->v_iflag &= ~VI_OWEINACT;
2415 VOP_INACTIVE(vp, td);
2417 VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
2418 ("vinactive: lost VI_DOINGINACT"));
2419 vp->v_iflag &= ~VI_DOINGINACT;
2423 * Remove any vnodes in the vnode table belonging to mount point mp.
2425 * If FORCECLOSE is not specified, there should not be any active ones,
2426 * return error if any are found (nb: this is a user error, not a
2427 * system error). If FORCECLOSE is specified, detach any active vnodes
2430 * If WRITECLOSE is set, only flush out regular file vnodes open for
2433 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
2435 * `rootrefs' specifies the base reference count for the root vnode
2436 * of this filesystem. The root vnode is considered busy if its
2437 * v_usecount exceeds this value. On a successful return, vflush(, td)
2438 * will call vrele() on the root vnode exactly rootrefs times.
2439 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
2443 static int busyprt = 0; /* print out busy vnodes */
2444 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
2448 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
2450 struct vnode *vp, *mvp, *rootvp = NULL;
2452 int busy = 0, error;
2454 CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
2457 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
2458 ("vflush: bad args"));
2460 * Get the filesystem root vnode. We can vput() it
2461 * immediately, since with rootrefs > 0, it won't go away.
2463 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
2464 CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
2472 MNT_VNODE_FOREACH(vp, mp, mvp) {
2476 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
2480 MNT_VNODE_FOREACH_ABORT_ILOCKED(mp, mvp);
2484 * Skip over a vnodes marked VV_SYSTEM.
2486 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
2493 * If WRITECLOSE is set, flush out unlinked but still open
2494 * files (even if open only for reading) and regular file
2495 * vnodes open for writing.
2497 if (flags & WRITECLOSE) {
2498 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
2501 if ((vp->v_type == VNON ||
2502 (error == 0 && vattr.va_nlink > 0)) &&
2503 (vp->v_writecount == 0 || vp->v_type != VREG)) {
2512 * With v_usecount == 0, all we need to do is clear out the
2513 * vnode data structures and we are done.
2515 * If FORCECLOSE is set, forcibly close the vnode.
2517 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
2518 VNASSERT(vp->v_usecount == 0 ||
2519 (vp->v_type != VCHR && vp->v_type != VBLK), vp,
2520 ("device VNODE %p is FORCECLOSED", vp));
2526 vprint("vflush: busy vnode", vp);
2534 if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
2536 * If just the root vnode is busy, and if its refcount
2537 * is equal to `rootrefs', then go ahead and kill it.
2540 KASSERT(busy > 0, ("vflush: not busy"));
2541 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
2542 ("vflush: usecount %d < rootrefs %d",
2543 rootvp->v_usecount, rootrefs));
2544 if (busy == 1 && rootvp->v_usecount == rootrefs) {
2545 VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
2547 VOP_UNLOCK(rootvp, 0);
2553 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
2557 for (; rootrefs > 0; rootrefs--)
2563 * Recycle an unused vnode to the front of the free list.
2566 vrecycle(struct vnode *vp, struct thread *td)
2570 ASSERT_VOP_ELOCKED(vp, "vrecycle");
2571 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2574 if (vp->v_usecount == 0) {
2583 * Eliminate all activity associated with a vnode
2584 * in preparation for reuse.
2587 vgone(struct vnode *vp)
2595 * vgone, with the vp interlock held.
2598 vgonel(struct vnode *vp)
2605 ASSERT_VOP_ELOCKED(vp, "vgonel");
2606 ASSERT_VI_LOCKED(vp, "vgonel");
2607 VNASSERT(vp->v_holdcnt, vp,
2608 ("vgonel: vp %p has no reference.", vp));
2609 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2613 * Don't vgonel if we're already doomed.
2615 if (vp->v_iflag & VI_DOOMED)
2617 vp->v_iflag |= VI_DOOMED;
2619 * Check to see if the vnode is in use. If so, we have to call
2620 * VOP_CLOSE() and VOP_INACTIVE().
2622 active = vp->v_usecount;
2623 oweinact = (vp->v_iflag & VI_OWEINACT);
2626 * Clean out any buffers associated with the vnode.
2627 * If the flush fails, just toss the buffers.
2630 if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
2631 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
2632 if (vinvalbuf(vp, V_SAVE, 0, 0) != 0)
2633 vinvalbuf(vp, 0, 0, 0);
2636 * If purging an active vnode, it must be closed and
2637 * deactivated before being reclaimed.
2640 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
2641 if (oweinact || active) {
2643 if ((vp->v_iflag & VI_DOINGINACT) == 0)
2648 * Reclaim the vnode.
2650 if (VOP_RECLAIM(vp, td))
2651 panic("vgone: cannot reclaim");
2653 vn_finished_secondary_write(mp);
2654 VNASSERT(vp->v_object == NULL, vp,
2655 ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
2657 * Clear the advisory locks and wake up waiting threads.
2659 (void)VOP_ADVLOCKPURGE(vp);
2661 * Delete from old mount point vnode list.
2666 * Done with purge, reset to the standard lock and invalidate
2670 vp->v_vnlock = &vp->v_lock;
2671 vp->v_op = &dead_vnodeops;
2677 * Calculate the total number of references to a special device.
2680 vcount(struct vnode *vp)
2685 count = vp->v_rdev->si_usecount;
2691 * Same as above, but using the struct cdev *as argument
2694 count_dev(struct cdev *dev)
2699 count = dev->si_usecount;
2705 * Print out a description of a vnode.
2707 static char *typename[] =
2708 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
2712 vn_printf(struct vnode *vp, const char *fmt, ...)
2715 char buf[256], buf2[16];
2721 printf("%p: ", (void *)vp);
2722 printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
2723 printf(" usecount %d, writecount %d, refcount %d mountedhere %p\n",
2724 vp->v_usecount, vp->v_writecount, vp->v_holdcnt, vp->v_mountedhere);
2727 if (vp->v_vflag & VV_ROOT)
2728 strlcat(buf, "|VV_ROOT", sizeof(buf));
2729 if (vp->v_vflag & VV_ISTTY)
2730 strlcat(buf, "|VV_ISTTY", sizeof(buf));
2731 if (vp->v_vflag & VV_NOSYNC)
2732 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
2733 if (vp->v_vflag & VV_CACHEDLABEL)
2734 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
2735 if (vp->v_vflag & VV_TEXT)
2736 strlcat(buf, "|VV_TEXT", sizeof(buf));
2737 if (vp->v_vflag & VV_COPYONWRITE)
2738 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
2739 if (vp->v_vflag & VV_SYSTEM)
2740 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
2741 if (vp->v_vflag & VV_PROCDEP)
2742 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
2743 if (vp->v_vflag & VV_NOKNOTE)
2744 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
2745 if (vp->v_vflag & VV_DELETED)
2746 strlcat(buf, "|VV_DELETED", sizeof(buf));
2747 if (vp->v_vflag & VV_MD)
2748 strlcat(buf, "|VV_MD", sizeof(buf));
2749 flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC |
2750 VV_CACHEDLABEL | VV_TEXT | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
2751 VV_NOKNOTE | VV_DELETED | VV_MD);
2753 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
2754 strlcat(buf, buf2, sizeof(buf));
2756 if (vp->v_iflag & VI_MOUNT)
2757 strlcat(buf, "|VI_MOUNT", sizeof(buf));
2758 if (vp->v_iflag & VI_AGE)
2759 strlcat(buf, "|VI_AGE", sizeof(buf));
2760 if (vp->v_iflag & VI_DOOMED)
2761 strlcat(buf, "|VI_DOOMED", sizeof(buf));
2762 if (vp->v_iflag & VI_FREE)
2763 strlcat(buf, "|VI_FREE", sizeof(buf));
2764 if (vp->v_iflag & VI_DOINGINACT)
2765 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
2766 if (vp->v_iflag & VI_OWEINACT)
2767 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
2768 flags = vp->v_iflag & ~(VI_MOUNT | VI_AGE | VI_DOOMED | VI_FREE |
2769 VI_DOINGINACT | VI_OWEINACT);
2771 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
2772 strlcat(buf, buf2, sizeof(buf));
2774 printf(" flags (%s)\n", buf + 1);
2775 if (mtx_owned(VI_MTX(vp)))
2776 printf(" VI_LOCKed");
2777 if (vp->v_object != NULL)
2778 printf(" v_object %p ref %d pages %d\n",
2779 vp->v_object, vp->v_object->ref_count,
2780 vp->v_object->resident_page_count);
2782 lockmgr_printinfo(vp->v_vnlock);
2783 if (vp->v_data != NULL)
2789 * List all of the locked vnodes in the system.
2790 * Called when debugging the kernel.
2792 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
2794 struct mount *mp, *nmp;
2798 * Note: because this is DDB, we can't obey the locking semantics
2799 * for these structures, which means we could catch an inconsistent
2800 * state and dereference a nasty pointer. Not much to be done
2803 db_printf("Locked vnodes\n");
2804 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2805 nmp = TAILQ_NEXT(mp, mnt_list);
2806 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2807 if (vp->v_type != VMARKER &&
2811 nmp = TAILQ_NEXT(mp, mnt_list);
2816 * Show details about the given vnode.
2818 DB_SHOW_COMMAND(vnode, db_show_vnode)
2824 vp = (struct vnode *)addr;
2825 vn_printf(vp, "vnode ");
2829 * Show details about the given mount point.
2831 DB_SHOW_COMMAND(mount, db_show_mount)
2841 /* No address given, print short info about all mount points. */
2842 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2843 db_printf("%p %s on %s (%s)\n", mp,
2844 mp->mnt_stat.f_mntfromname,
2845 mp->mnt_stat.f_mntonname,
2846 mp->mnt_stat.f_fstypename);
2850 db_printf("\nMore info: show mount <addr>\n");
2854 mp = (struct mount *)addr;
2855 db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
2856 mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
2859 flags = mp->mnt_flag;
2860 #define MNT_FLAG(flag) do { \
2861 if (flags & (flag)) { \
2862 if (buf[0] != '\0') \
2863 strlcat(buf, ", ", sizeof(buf)); \
2864 strlcat(buf, (#flag) + 4, sizeof(buf)); \
2868 MNT_FLAG(MNT_RDONLY);
2869 MNT_FLAG(MNT_SYNCHRONOUS);
2870 MNT_FLAG(MNT_NOEXEC);
2871 MNT_FLAG(MNT_NOSUID);
2872 MNT_FLAG(MNT_UNION);
2873 MNT_FLAG(MNT_ASYNC);
2874 MNT_FLAG(MNT_SUIDDIR);
2875 MNT_FLAG(MNT_SOFTDEP);
2877 MNT_FLAG(MNT_NOSYMFOLLOW);
2878 MNT_FLAG(MNT_GJOURNAL);
2879 MNT_FLAG(MNT_MULTILABEL);
2881 MNT_FLAG(MNT_NOATIME);
2882 MNT_FLAG(MNT_NOCLUSTERR);
2883 MNT_FLAG(MNT_NOCLUSTERW);
2884 MNT_FLAG(MNT_NFS4ACLS);
2885 MNT_FLAG(MNT_EXRDONLY);
2886 MNT_FLAG(MNT_EXPORTED);
2887 MNT_FLAG(MNT_DEFEXPORTED);
2888 MNT_FLAG(MNT_EXPORTANON);
2889 MNT_FLAG(MNT_EXKERB);
2890 MNT_FLAG(MNT_EXPUBLIC);
2891 MNT_FLAG(MNT_LOCAL);
2892 MNT_FLAG(MNT_QUOTA);
2893 MNT_FLAG(MNT_ROOTFS);
2895 MNT_FLAG(MNT_IGNORE);
2896 MNT_FLAG(MNT_UPDATE);
2897 MNT_FLAG(MNT_DELEXPORT);
2898 MNT_FLAG(MNT_RELOAD);
2899 MNT_FLAG(MNT_FORCE);
2900 MNT_FLAG(MNT_SNAPSHOT);
2901 MNT_FLAG(MNT_BYFSID);
2905 strlcat(buf, ", ", sizeof(buf));
2906 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2909 db_printf(" mnt_flag = %s\n", buf);
2912 flags = mp->mnt_kern_flag;
2913 #define MNT_KERN_FLAG(flag) do { \
2914 if (flags & (flag)) { \
2915 if (buf[0] != '\0') \
2916 strlcat(buf, ", ", sizeof(buf)); \
2917 strlcat(buf, (#flag) + 5, sizeof(buf)); \
2921 MNT_KERN_FLAG(MNTK_UNMOUNTF);
2922 MNT_KERN_FLAG(MNTK_ASYNC);
2923 MNT_KERN_FLAG(MNTK_SOFTDEP);
2924 MNT_KERN_FLAG(MNTK_NOINSMNTQ);
2925 MNT_KERN_FLAG(MNTK_DRAINING);
2926 MNT_KERN_FLAG(MNTK_REFEXPIRE);
2927 MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
2928 MNT_KERN_FLAG(MNTK_SHARED_WRITES);
2929 MNT_KERN_FLAG(MNTK_UNMOUNT);
2930 MNT_KERN_FLAG(MNTK_MWAIT);
2931 MNT_KERN_FLAG(MNTK_SUSPEND);
2932 MNT_KERN_FLAG(MNTK_SUSPEND2);
2933 MNT_KERN_FLAG(MNTK_SUSPENDED);
2934 MNT_KERN_FLAG(MNTK_MPSAFE);
2935 MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
2936 MNT_KERN_FLAG(MNTK_NOKNOTE);
2937 #undef MNT_KERN_FLAG
2940 strlcat(buf, ", ", sizeof(buf));
2941 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2944 db_printf(" mnt_kern_flag = %s\n", buf);
2946 db_printf(" mnt_opt = ");
2947 opt = TAILQ_FIRST(mp->mnt_opt);
2949 db_printf("%s", opt->name);
2950 opt = TAILQ_NEXT(opt, link);
2951 while (opt != NULL) {
2952 db_printf(", %s", opt->name);
2953 opt = TAILQ_NEXT(opt, link);
2959 db_printf(" mnt_stat = { version=%u type=%u flags=0x%016jx "
2960 "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
2961 "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
2962 "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
2963 (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
2964 (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
2965 (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
2966 (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
2967 (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
2968 (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
2969 (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
2970 (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
2972 db_printf(" mnt_cred = { uid=%u ruid=%u",
2973 (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
2974 if (jailed(mp->mnt_cred))
2975 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
2977 db_printf(" mnt_ref = %d\n", mp->mnt_ref);
2978 db_printf(" mnt_gen = %d\n", mp->mnt_gen);
2979 db_printf(" mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
2980 db_printf(" mnt_writeopcount = %d\n", mp->mnt_writeopcount);
2981 db_printf(" mnt_noasync = %u\n", mp->mnt_noasync);
2982 db_printf(" mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
2983 db_printf(" mnt_iosize_max = %d\n", mp->mnt_iosize_max);
2984 db_printf(" mnt_hashseed = %u\n", mp->mnt_hashseed);
2985 db_printf(" mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
2986 db_printf(" mnt_secondary_accwrites = %d\n",
2987 mp->mnt_secondary_accwrites);
2988 db_printf(" mnt_gjprovider = %s\n",
2989 mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
2992 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2993 if (vp->v_type != VMARKER) {
2994 vn_printf(vp, "vnode ");
3003 * Fill in a struct xvfsconf based on a struct vfsconf.
3006 vfsconf2x(struct vfsconf *vfsp, struct xvfsconf *xvfsp)
3009 strcpy(xvfsp->vfc_name, vfsp->vfc_name);
3010 xvfsp->vfc_typenum = vfsp->vfc_typenum;
3011 xvfsp->vfc_refcount = vfsp->vfc_refcount;
3012 xvfsp->vfc_flags = vfsp->vfc_flags;
3014 * These are unused in userland, we keep them
3015 * to not break binary compatibility.
3017 xvfsp->vfc_vfsops = NULL;
3018 xvfsp->vfc_next = NULL;
3022 * Top level filesystem related information gathering.
3025 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
3027 struct vfsconf *vfsp;
3028 struct xvfsconf xvfsp;
3032 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3033 bzero(&xvfsp, sizeof(xvfsp));
3034 vfsconf2x(vfsp, &xvfsp);
3035 error = SYSCTL_OUT(req, &xvfsp, sizeof xvfsp);
3042 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD,
3043 NULL, 0, sysctl_vfs_conflist,
3044 "S,xvfsconf", "List of all configured filesystems");
3046 #ifndef BURN_BRIDGES
3047 static int sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
3050 vfs_sysctl(SYSCTL_HANDLER_ARGS)
3052 int *name = (int *)arg1 - 1; /* XXX */
3053 u_int namelen = arg2 + 1; /* XXX */
3054 struct vfsconf *vfsp;
3055 struct xvfsconf xvfsp;
3057 printf("WARNING: userland calling deprecated sysctl, "
3058 "please rebuild world\n");
3060 #if 1 || defined(COMPAT_PRELITE2)
3061 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
3063 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
3067 case VFS_MAXTYPENUM:
3070 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
3073 return (ENOTDIR); /* overloaded */
3074 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list)
3075 if (vfsp->vfc_typenum == name[2])
3078 return (EOPNOTSUPP);
3079 bzero(&xvfsp, sizeof(xvfsp));
3080 vfsconf2x(vfsp, &xvfsp);
3081 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3083 return (EOPNOTSUPP);
3086 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP,
3087 vfs_sysctl, "Generic filesystem");
3089 #if 1 || defined(COMPAT_PRELITE2)
3092 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
3095 struct vfsconf *vfsp;
3096 struct ovfsconf ovfs;
3098 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3099 bzero(&ovfs, sizeof(ovfs));
3100 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
3101 strcpy(ovfs.vfc_name, vfsp->vfc_name);
3102 ovfs.vfc_index = vfsp->vfc_typenum;
3103 ovfs.vfc_refcount = vfsp->vfc_refcount;
3104 ovfs.vfc_flags = vfsp->vfc_flags;
3105 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
3112 #endif /* 1 || COMPAT_PRELITE2 */
3113 #endif /* !BURN_BRIDGES */
3115 #define KINFO_VNODESLOP 10
3118 * Dump vnode list (via sysctl).
3122 sysctl_vnode(SYSCTL_HANDLER_ARGS)
3130 * Stale numvnodes access is not fatal here.
3133 len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
3135 /* Make an estimate */
3136 return (SYSCTL_OUT(req, 0, len));
3138 error = sysctl_wire_old_buffer(req, 0);
3141 xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
3143 mtx_lock(&mountlist_mtx);
3144 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3145 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
3148 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3152 xvn[n].xv_size = sizeof *xvn;
3153 xvn[n].xv_vnode = vp;
3154 xvn[n].xv_id = 0; /* XXX compat */
3155 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
3157 XV_COPY(writecount);
3163 xvn[n].xv_flag = vp->v_vflag;
3165 switch (vp->v_type) {
3172 if (vp->v_rdev == NULL) {
3176 xvn[n].xv_dev = dev2udev(vp->v_rdev);
3179 xvn[n].xv_socket = vp->v_socket;
3182 xvn[n].xv_fifo = vp->v_fifoinfo;
3187 /* shouldn't happen? */
3195 mtx_lock(&mountlist_mtx);
3200 mtx_unlock(&mountlist_mtx);
3202 error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
3207 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
3208 0, 0, sysctl_vnode, "S,xvnode", "");
3212 * Unmount all filesystems. The list is traversed in reverse order
3213 * of mounting to avoid dependencies.
3216 vfs_unmountall(void)
3222 KASSERT(curthread != NULL, ("vfs_unmountall: NULL curthread"));
3223 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
3227 * Since this only runs when rebooting, it is not interlocked.
3229 while(!TAILQ_EMPTY(&mountlist)) {
3230 mp = TAILQ_LAST(&mountlist, mntlist);
3231 error = dounmount(mp, MNT_FORCE, td);
3233 TAILQ_REMOVE(&mountlist, mp, mnt_list);
3235 * XXX: Due to the way in which we mount the root
3236 * file system off of devfs, devfs will generate a
3237 * "busy" warning when we try to unmount it before
3238 * the root. Don't print a warning as a result in
3239 * order to avoid false positive errors that may
3240 * cause needless upset.
3242 if (strcmp(mp->mnt_vfc->vfc_name, "devfs") != 0) {
3243 printf("unmount of %s failed (",
3244 mp->mnt_stat.f_mntonname);
3248 printf("%d)\n", error);
3251 /* The unmount has removed mp from the mountlist */
3257 * perform msync on all vnodes under a mount point
3258 * the mount point must be locked.
3261 vfs_msync(struct mount *mp, int flags)
3263 struct vnode *vp, *mvp;
3264 struct vm_object *obj;
3266 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
3268 MNT_VNODE_FOREACH(vp, mp, mvp) {
3271 if (obj != NULL && (obj->flags & OBJ_MIGHTBEDIRTY) != 0 &&
3272 (flags == MNT_WAIT || VOP_ISLOCKED(vp) == 0)) {
3275 LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
3277 if (vp->v_vflag & VV_NOSYNC) { /* unlinked */
3285 VM_OBJECT_LOCK(obj);
3286 vm_object_page_clean(obj, 0, 0,
3288 OBJPC_SYNC : OBJPC_NOSYNC);
3289 VM_OBJECT_UNLOCK(obj);
3301 * Mark a vnode as free, putting it up for recycling.
3304 vfree(struct vnode *vp)
3307 ASSERT_VI_LOCKED(vp, "vfree");
3308 mtx_lock(&vnode_free_list_mtx);
3309 VNASSERT(vp->v_op != NULL, vp, ("vfree: vnode already reclaimed."));
3310 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp, ("vnode already free"));
3311 VNASSERT(VSHOULDFREE(vp), vp, ("vfree: freeing when we shouldn't"));
3312 VNASSERT((vp->v_iflag & VI_DOOMED) == 0, vp,
3313 ("vfree: Freeing doomed vnode"));
3314 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3315 if (vp->v_iflag & VI_AGE) {
3316 TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
3318 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
3321 vp->v_iflag &= ~VI_AGE;
3322 vp->v_iflag |= VI_FREE;
3323 mtx_unlock(&vnode_free_list_mtx);
3327 * Opposite of vfree() - mark a vnode as in use.
3330 vbusy(struct vnode *vp)
3332 ASSERT_VI_LOCKED(vp, "vbusy");
3333 VNASSERT((vp->v_iflag & VI_FREE) != 0, vp, ("vnode not free"));
3334 VNASSERT(vp->v_op != NULL, vp, ("vbusy: vnode already reclaimed."));
3335 CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3337 mtx_lock(&vnode_free_list_mtx);
3338 TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
3340 vp->v_iflag &= ~(VI_FREE|VI_AGE);
3341 mtx_unlock(&vnode_free_list_mtx);
3345 destroy_vpollinfo(struct vpollinfo *vi)
3347 seldrain(&vi->vpi_selinfo);
3348 knlist_destroy(&vi->vpi_selinfo.si_note);
3349 mtx_destroy(&vi->vpi_lock);
3350 uma_zfree(vnodepoll_zone, vi);
3354 * Initalize per-vnode helper structure to hold poll-related state.
3357 v_addpollinfo(struct vnode *vp)
3359 struct vpollinfo *vi;
3361 if (vp->v_pollinfo != NULL)
3363 vi = uma_zalloc(vnodepoll_zone, M_WAITOK);
3364 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
3365 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
3366 vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
3368 if (vp->v_pollinfo != NULL) {
3370 destroy_vpollinfo(vi);
3373 vp->v_pollinfo = vi;
3378 * Record a process's interest in events which might happen to
3379 * a vnode. Because poll uses the historic select-style interface
3380 * internally, this routine serves as both the ``check for any
3381 * pending events'' and the ``record my interest in future events''
3382 * functions. (These are done together, while the lock is held,
3383 * to avoid race conditions.)
3386 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
3390 mtx_lock(&vp->v_pollinfo->vpi_lock);
3391 if (vp->v_pollinfo->vpi_revents & events) {
3393 * This leaves events we are not interested
3394 * in available for the other process which
3395 * which presumably had requested them
3396 * (otherwise they would never have been
3399 events &= vp->v_pollinfo->vpi_revents;
3400 vp->v_pollinfo->vpi_revents &= ~events;
3402 mtx_unlock(&vp->v_pollinfo->vpi_lock);
3405 vp->v_pollinfo->vpi_events |= events;
3406 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
3407 mtx_unlock(&vp->v_pollinfo->vpi_lock);
3412 * Routine to create and manage a filesystem syncer vnode.
3414 #define sync_close ((int (*)(struct vop_close_args *))nullop)
3415 static int sync_fsync(struct vop_fsync_args *);
3416 static int sync_inactive(struct vop_inactive_args *);
3417 static int sync_reclaim(struct vop_reclaim_args *);
3419 static struct vop_vector sync_vnodeops = {
3420 .vop_bypass = VOP_EOPNOTSUPP,
3421 .vop_close = sync_close, /* close */
3422 .vop_fsync = sync_fsync, /* fsync */
3423 .vop_inactive = sync_inactive, /* inactive */
3424 .vop_reclaim = sync_reclaim, /* reclaim */
3425 .vop_lock1 = vop_stdlock, /* lock */
3426 .vop_unlock = vop_stdunlock, /* unlock */
3427 .vop_islocked = vop_stdislocked, /* islocked */
3431 * Create a new filesystem syncer vnode for the specified mount point.
3434 vfs_allocate_syncvnode(struct mount *mp)
3438 static long start, incr, next;
3441 /* Allocate a new vnode */
3442 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
3444 panic("vfs_allocate_syncvnode: getnewvnode() failed");
3446 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3447 vp->v_vflag |= VV_FORCEINSMQ;
3448 error = insmntque(vp, mp);
3450 panic("vfs_allocate_syncvnode: insmntque() failed");
3451 vp->v_vflag &= ~VV_FORCEINSMQ;
3454 * Place the vnode onto the syncer worklist. We attempt to
3455 * scatter them about on the list so that they will go off
3456 * at evenly distributed times even if all the filesystems
3457 * are mounted at once.
3460 if (next == 0 || next > syncer_maxdelay) {
3464 start = syncer_maxdelay / 2;
3465 incr = syncer_maxdelay;
3471 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
3472 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
3473 mtx_lock(&sync_mtx);
3475 if (mp->mnt_syncer == NULL) {
3476 mp->mnt_syncer = vp;
3479 mtx_unlock(&sync_mtx);
3482 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3489 vfs_deallocate_syncvnode(struct mount *mp)
3493 mtx_lock(&sync_mtx);
3494 vp = mp->mnt_syncer;
3496 mp->mnt_syncer = NULL;
3497 mtx_unlock(&sync_mtx);
3503 * Do a lazy sync of the filesystem.
3506 sync_fsync(struct vop_fsync_args *ap)
3508 struct vnode *syncvp = ap->a_vp;
3509 struct mount *mp = syncvp->v_mount;
3514 * We only need to do something if this is a lazy evaluation.
3516 if (ap->a_waitfor != MNT_LAZY)
3520 * Move ourselves to the back of the sync list.
3522 bo = &syncvp->v_bufobj;
3524 vn_syncer_add_to_worklist(bo, syncdelay);
3528 * Walk the list of vnodes pushing all that are dirty and
3529 * not already on the sync list.
3531 mtx_lock(&mountlist_mtx);
3532 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK) != 0) {
3533 mtx_unlock(&mountlist_mtx);
3536 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
3542 mp->mnt_kern_flag &= ~MNTK_ASYNC;
3544 vfs_msync(mp, MNT_NOWAIT);
3545 error = VFS_SYNC(mp, MNT_LAZY);
3548 if ((mp->mnt_flag & MNT_ASYNC) != 0 && mp->mnt_noasync == 0)
3549 mp->mnt_kern_flag |= MNTK_ASYNC;
3551 vn_finished_write(mp);
3557 * The syncer vnode is no referenced.
3560 sync_inactive(struct vop_inactive_args *ap)
3568 * The syncer vnode is no longer needed and is being decommissioned.
3570 * Modifications to the worklist must be protected by sync_mtx.
3573 sync_reclaim(struct vop_reclaim_args *ap)
3575 struct vnode *vp = ap->a_vp;
3580 mtx_lock(&sync_mtx);
3581 if (vp->v_mount->mnt_syncer == vp)
3582 vp->v_mount->mnt_syncer = NULL;
3583 if (bo->bo_flag & BO_ONWORKLST) {
3584 LIST_REMOVE(bo, bo_synclist);
3585 syncer_worklist_len--;
3587 bo->bo_flag &= ~BO_ONWORKLST;
3589 mtx_unlock(&sync_mtx);
3596 * Check if vnode represents a disk device
3599 vn_isdisk(struct vnode *vp, int *errp)
3605 if (vp->v_type != VCHR)
3607 else if (vp->v_rdev == NULL)
3609 else if (vp->v_rdev->si_devsw == NULL)
3611 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
3616 return (error == 0);
3620 * Common filesystem object access control check routine. Accepts a
3621 * vnode's type, "mode", uid and gid, requested access mode, credentials,
3622 * and optional call-by-reference privused argument allowing vaccess()
3623 * to indicate to the caller whether privilege was used to satisfy the
3624 * request (obsoleted). Returns 0 on success, or an errno on failure.
3627 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
3628 accmode_t accmode, struct ucred *cred, int *privused)
3630 accmode_t dac_granted;
3631 accmode_t priv_granted;
3633 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
3634 ("invalid bit in accmode"));
3635 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
3636 ("VAPPEND without VWRITE"));
3639 * Look for a normal, non-privileged way to access the file/directory
3640 * as requested. If it exists, go with that.
3643 if (privused != NULL)
3648 /* Check the owner. */
3649 if (cred->cr_uid == file_uid) {
3650 dac_granted |= VADMIN;
3651 if (file_mode & S_IXUSR)
3652 dac_granted |= VEXEC;
3653 if (file_mode & S_IRUSR)
3654 dac_granted |= VREAD;
3655 if (file_mode & S_IWUSR)
3656 dac_granted |= (VWRITE | VAPPEND);
3658 if ((accmode & dac_granted) == accmode)
3664 /* Otherwise, check the groups (first match) */
3665 if (groupmember(file_gid, cred)) {
3666 if (file_mode & S_IXGRP)
3667 dac_granted |= VEXEC;
3668 if (file_mode & S_IRGRP)
3669 dac_granted |= VREAD;
3670 if (file_mode & S_IWGRP)
3671 dac_granted |= (VWRITE | VAPPEND);
3673 if ((accmode & dac_granted) == accmode)
3679 /* Otherwise, check everyone else. */
3680 if (file_mode & S_IXOTH)
3681 dac_granted |= VEXEC;
3682 if (file_mode & S_IROTH)
3683 dac_granted |= VREAD;
3684 if (file_mode & S_IWOTH)
3685 dac_granted |= (VWRITE | VAPPEND);
3686 if ((accmode & dac_granted) == accmode)
3691 * Build a privilege mask to determine if the set of privileges
3692 * satisfies the requirements when combined with the granted mask
3693 * from above. For each privilege, if the privilege is required,
3694 * bitwise or the request type onto the priv_granted mask.
3700 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
3701 * requests, instead of PRIV_VFS_EXEC.
3703 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3704 !priv_check_cred(cred, PRIV_VFS_LOOKUP, 0))
3705 priv_granted |= VEXEC;
3708 * Ensure that at least one execute bit is on. Otherwise,
3709 * a privileged user will always succeed, and we don't want
3710 * this to happen unless the file really is executable.
3712 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3713 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
3714 !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
3715 priv_granted |= VEXEC;
3718 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
3719 !priv_check_cred(cred, PRIV_VFS_READ, 0))
3720 priv_granted |= VREAD;
3722 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
3723 !priv_check_cred(cred, PRIV_VFS_WRITE, 0))
3724 priv_granted |= (VWRITE | VAPPEND);
3726 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
3727 !priv_check_cred(cred, PRIV_VFS_ADMIN, 0))
3728 priv_granted |= VADMIN;
3730 if ((accmode & (priv_granted | dac_granted)) == accmode) {
3731 /* XXX audit: privilege used */
3732 if (privused != NULL)
3737 return ((accmode & VADMIN) ? EPERM : EACCES);
3741 * Credential check based on process requesting service, and per-attribute
3745 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
3746 struct thread *td, accmode_t accmode)
3750 * Kernel-invoked always succeeds.
3756 * Do not allow privileged processes in jail to directly manipulate
3757 * system attributes.
3759 switch (attrnamespace) {
3760 case EXTATTR_NAMESPACE_SYSTEM:
3761 /* Potentially should be: return (EPERM); */
3762 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM, 0));
3763 case EXTATTR_NAMESPACE_USER:
3764 return (VOP_ACCESS(vp, accmode, cred, td));
3770 #ifdef DEBUG_VFS_LOCKS
3772 * This only exists to supress warnings from unlocked specfs accesses. It is
3773 * no longer ok to have an unlocked VFS.
3775 #define IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL || \
3776 (vp)->v_type == VCHR || (vp)->v_type == VBAD)
3778 int vfs_badlock_ddb = 1; /* Drop into debugger on violation. */
3779 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
3780 "Drop into debugger on lock violation");
3782 int vfs_badlock_mutex = 1; /* Check for interlock across VOPs. */
3783 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
3784 0, "Check for interlock across VOPs");
3786 int vfs_badlock_print = 1; /* Print lock violations. */
3787 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
3788 0, "Print lock violations");
3791 int vfs_badlock_backtrace = 1; /* Print backtrace at lock violations. */
3792 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
3793 &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
3797 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
3801 if (vfs_badlock_backtrace)
3804 if (vfs_badlock_print)
3805 printf("%s: %p %s\n", str, (void *)vp, msg);
3806 if (vfs_badlock_ddb)
3807 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
3811 assert_vi_locked(struct vnode *vp, const char *str)
3814 if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
3815 vfs_badlock("interlock is not locked but should be", str, vp);
3819 assert_vi_unlocked(struct vnode *vp, const char *str)
3822 if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
3823 vfs_badlock("interlock is locked but should not be", str, vp);
3827 assert_vop_locked(struct vnode *vp, const char *str)
3830 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == 0)
3831 vfs_badlock("is not locked but should be", str, vp);
3835 assert_vop_unlocked(struct vnode *vp, const char *str)
3838 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
3839 vfs_badlock("is locked but should not be", str, vp);
3843 assert_vop_elocked(struct vnode *vp, const char *str)
3846 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
3847 vfs_badlock("is not exclusive locked but should be", str, vp);
3852 assert_vop_elocked_other(struct vnode *vp, const char *str)
3855 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLOTHER)
3856 vfs_badlock("is not exclusive locked by another thread",
3861 assert_vop_slocked(struct vnode *vp, const char *str)
3864 if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_SHARED)
3865 vfs_badlock("is not locked shared but should be", str, vp);
3868 #endif /* DEBUG_VFS_LOCKS */
3871 vop_rename_fail(struct vop_rename_args *ap)
3874 if (ap->a_tvp != NULL)
3876 if (ap->a_tdvp == ap->a_tvp)
3885 vop_rename_pre(void *ap)
3887 struct vop_rename_args *a = ap;
3889 #ifdef DEBUG_VFS_LOCKS
3891 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
3892 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
3893 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
3894 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
3896 /* Check the source (from). */
3897 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
3898 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
3899 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
3900 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
3901 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
3903 /* Check the target. */
3905 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
3906 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
3908 if (a->a_tdvp != a->a_fdvp)
3910 if (a->a_tvp != a->a_fvp)
3918 vop_strategy_pre(void *ap)
3920 #ifdef DEBUG_VFS_LOCKS
3921 struct vop_strategy_args *a;
3928 * Cluster ops lock their component buffers but not the IO container.
3930 if ((bp->b_flags & B_CLUSTER) != 0)
3933 if (panicstr == NULL && !BUF_ISLOCKED(bp)) {
3934 if (vfs_badlock_print)
3936 "VOP_STRATEGY: bp is not locked but should be\n");
3937 if (vfs_badlock_ddb)
3938 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
3944 vop_lookup_pre(void *ap)
3946 #ifdef DEBUG_VFS_LOCKS
3947 struct vop_lookup_args *a;
3952 ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
3953 ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
3958 vop_lookup_post(void *ap, int rc)
3960 #ifdef DEBUG_VFS_LOCKS
3961 struct vop_lookup_args *a;
3969 ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
3970 ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
3973 ASSERT_VOP_LOCKED(vp, "VOP_LOOKUP (child)");
3978 vop_lock_pre(void *ap)
3980 #ifdef DEBUG_VFS_LOCKS
3981 struct vop_lock1_args *a = ap;
3983 if ((a->a_flags & LK_INTERLOCK) == 0)
3984 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
3986 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
3991 vop_lock_post(void *ap, int rc)
3993 #ifdef DEBUG_VFS_LOCKS
3994 struct vop_lock1_args *a = ap;
3996 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
3998 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
4003 vop_unlock_pre(void *ap)
4005 #ifdef DEBUG_VFS_LOCKS
4006 struct vop_unlock_args *a = ap;
4008 if (a->a_flags & LK_INTERLOCK)
4009 ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
4010 ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
4015 vop_unlock_post(void *ap, int rc)
4017 #ifdef DEBUG_VFS_LOCKS
4018 struct vop_unlock_args *a = ap;
4020 if (a->a_flags & LK_INTERLOCK)
4021 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
4026 vop_create_post(void *ap, int rc)
4028 struct vop_create_args *a = ap;
4031 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4035 vop_link_post(void *ap, int rc)
4037 struct vop_link_args *a = ap;
4040 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
4041 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
4046 vop_mkdir_post(void *ap, int rc)
4048 struct vop_mkdir_args *a = ap;
4051 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4055 vop_mknod_post(void *ap, int rc)
4057 struct vop_mknod_args *a = ap;
4060 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4064 vop_remove_post(void *ap, int rc)
4066 struct vop_remove_args *a = ap;
4069 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4070 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4075 vop_rename_post(void *ap, int rc)
4077 struct vop_rename_args *a = ap;
4080 VFS_KNOTE_UNLOCKED(a->a_fdvp, NOTE_WRITE);
4081 VFS_KNOTE_UNLOCKED(a->a_tdvp, NOTE_WRITE);
4082 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
4084 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
4086 if (a->a_tdvp != a->a_fdvp)
4088 if (a->a_tvp != a->a_fvp)
4096 vop_rmdir_post(void *ap, int rc)
4098 struct vop_rmdir_args *a = ap;
4101 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4102 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4107 vop_setattr_post(void *ap, int rc)
4109 struct vop_setattr_args *a = ap;
4112 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4116 vop_symlink_post(void *ap, int rc)
4118 struct vop_symlink_args *a = ap;
4121 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4124 static struct knlist fs_knlist;
4127 vfs_event_init(void *arg)
4129 knlist_init_mtx(&fs_knlist, NULL);
4131 /* XXX - correct order? */
4132 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
4135 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
4138 KNOTE_UNLOCKED(&fs_knlist, event);
4141 static int filt_fsattach(struct knote *kn);
4142 static void filt_fsdetach(struct knote *kn);
4143 static int filt_fsevent(struct knote *kn, long hint);
4145 struct filterops fs_filtops = {
4147 .f_attach = filt_fsattach,
4148 .f_detach = filt_fsdetach,
4149 .f_event = filt_fsevent
4153 filt_fsattach(struct knote *kn)
4156 kn->kn_flags |= EV_CLEAR;
4157 knlist_add(&fs_knlist, kn, 0);
4162 filt_fsdetach(struct knote *kn)
4165 knlist_remove(&fs_knlist, kn, 0);
4169 filt_fsevent(struct knote *kn, long hint)
4172 kn->kn_fflags |= hint;
4173 return (kn->kn_fflags != 0);
4177 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
4183 error = SYSCTL_IN(req, &vc, sizeof(vc));
4186 if (vc.vc_vers != VFS_CTL_VERS1)
4188 mp = vfs_getvfs(&vc.vc_fsid);
4191 /* ensure that a specific sysctl goes to the right filesystem. */
4192 if (strcmp(vc.vc_fstypename, "*") != 0 &&
4193 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
4197 VCTLTOREQ(&vc, req);
4198 error = VFS_SYSCTL(mp, vc.vc_op, req);
4203 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_WR,
4204 NULL, 0, sysctl_vfs_ctl, "",
4208 * Function to initialize a va_filerev field sensibly.
4209 * XXX: Wouldn't a random number make a lot more sense ??
4212 init_va_filerev(void)
4217 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
4220 static int filt_vfsread(struct knote *kn, long hint);
4221 static int filt_vfswrite(struct knote *kn, long hint);
4222 static int filt_vfsvnode(struct knote *kn, long hint);
4223 static void filt_vfsdetach(struct knote *kn);
4224 static struct filterops vfsread_filtops = {
4226 .f_detach = filt_vfsdetach,
4227 .f_event = filt_vfsread
4229 static struct filterops vfswrite_filtops = {
4231 .f_detach = filt_vfsdetach,
4232 .f_event = filt_vfswrite
4234 static struct filterops vfsvnode_filtops = {
4236 .f_detach = filt_vfsdetach,
4237 .f_event = filt_vfsvnode
4241 vfs_knllock(void *arg)
4243 struct vnode *vp = arg;
4245 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4249 vfs_knlunlock(void *arg)
4251 struct vnode *vp = arg;
4257 vfs_knl_assert_locked(void *arg)
4259 #ifdef DEBUG_VFS_LOCKS
4260 struct vnode *vp = arg;
4262 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
4267 vfs_knl_assert_unlocked(void *arg)
4269 #ifdef DEBUG_VFS_LOCKS
4270 struct vnode *vp = arg;
4272 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
4277 vfs_kqfilter(struct vop_kqfilter_args *ap)
4279 struct vnode *vp = ap->a_vp;
4280 struct knote *kn = ap->a_kn;
4283 switch (kn->kn_filter) {
4285 kn->kn_fop = &vfsread_filtops;
4288 kn->kn_fop = &vfswrite_filtops;
4291 kn->kn_fop = &vfsvnode_filtops;
4297 kn->kn_hook = (caddr_t)vp;
4300 if (vp->v_pollinfo == NULL)
4302 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
4303 knlist_add(knl, kn, 0);
4309 * Detach knote from vnode
4312 filt_vfsdetach(struct knote *kn)
4314 struct vnode *vp = (struct vnode *)kn->kn_hook;
4316 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
4317 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
4322 filt_vfsread(struct knote *kn, long hint)
4324 struct vnode *vp = (struct vnode *)kn->kn_hook;
4329 * filesystem is gone, so set the EOF flag and schedule
4330 * the knote for deletion.
4332 if (hint == NOTE_REVOKE) {
4334 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
4339 if (VOP_GETATTR(vp, &va, curthread->td_ucred))
4343 kn->kn_data = va.va_size - kn->kn_fp->f_offset;
4344 res = (kn->kn_data != 0);
4351 filt_vfswrite(struct knote *kn, long hint)
4353 struct vnode *vp = (struct vnode *)kn->kn_hook;
4358 * filesystem is gone, so set the EOF flag and schedule
4359 * the knote for deletion.
4361 if (hint == NOTE_REVOKE)
4362 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
4370 filt_vfsvnode(struct knote *kn, long hint)
4372 struct vnode *vp = (struct vnode *)kn->kn_hook;
4376 if (kn->kn_sfflags & hint)
4377 kn->kn_fflags |= hint;
4378 if (hint == NOTE_REVOKE) {
4379 kn->kn_flags |= EV_EOF;
4383 res = (kn->kn_fflags != 0);
4389 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
4393 if (dp->d_reclen > ap->a_uio->uio_resid)
4394 return (ENAMETOOLONG);
4395 error = uiomove(dp, dp->d_reclen, ap->a_uio);
4397 if (ap->a_ncookies != NULL) {
4398 if (ap->a_cookies != NULL)
4399 free(ap->a_cookies, M_TEMP);
4400 ap->a_cookies = NULL;
4401 *ap->a_ncookies = 0;
4405 if (ap->a_ncookies == NULL)
4408 KASSERT(ap->a_cookies,
4409 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
4411 *ap->a_cookies = realloc(*ap->a_cookies,
4412 (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
4413 (*ap->a_cookies)[*ap->a_ncookies] = off;
4418 * Mark for update the access time of the file if the filesystem
4419 * supports VOP_MARKATIME. This functionality is used by execve and
4420 * mmap, so we want to avoid the I/O implied by directly setting
4421 * va_atime for the sake of efficiency.
4424 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
4429 VFS_ASSERT_GIANT(mp);
4430 ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
4431 if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
4432 (void)VOP_MARKATIME(vp);
4436 * The purpose of this routine is to remove granularity from accmode_t,
4437 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
4438 * VADMIN and VAPPEND.
4440 * If it returns 0, the caller is supposed to continue with the usual
4441 * access checks using 'accmode' as modified by this routine. If it
4442 * returns nonzero value, the caller is supposed to return that value
4445 * Note that after this routine runs, accmode may be zero.
4448 vfs_unixify_accmode(accmode_t *accmode)
4451 * There is no way to specify explicit "deny" rule using
4452 * file mode or POSIX.1e ACLs.
4454 if (*accmode & VEXPLICIT_DENY) {
4460 * None of these can be translated into usual access bits.
4461 * Also, the common case for NFSv4 ACLs is to not contain
4462 * either of these bits. Caller should check for VWRITE
4463 * on the containing directory instead.
4465 if (*accmode & (VDELETE_CHILD | VDELETE))
4468 if (*accmode & VADMIN_PERMS) {
4469 *accmode &= ~VADMIN_PERMS;
4474 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
4475 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
4477 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);