2 * Copyright (c) 2003,2004 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@backplane.com>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
17 * 3. Neither the name of The DragonFly Project nor the names of its
18 * contributors may be used to endorse or promote products derived
19 * from this software without specific, prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * Copyright (c) 1989, 1993, 1995
35 * The Regents of the University of California. All rights reserved.
37 * This code is derived from software contributed to Berkeley by
38 * Poul-Henning Kamp of the FreeBSD Project.
40 * Redistribution and use in source and binary forms, with or without
41 * modification, are permitted provided that the following conditions
43 * 1. Redistributions of source code must retain the above copyright
44 * notice, this list of conditions and the following disclaimer.
45 * 2. Redistributions in binary form must reproduce the above copyright
46 * notice, this list of conditions and the following disclaimer in the
47 * documentation and/or other materials provided with the distribution.
48 * 3. All advertising materials mentioning features or use of this software
49 * must display the following acknowledgement:
50 * This product includes software developed by the University of
51 * California, Berkeley and its contributors.
52 * 4. Neither the name of the University nor the names of its contributors
53 * may be used to endorse or promote products derived from this software
54 * without specific prior written permission.
56 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
57 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
58 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
59 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
60 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
61 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
62 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
64 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
65 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * @(#)vfs_cache.c 8.5 (Berkeley) 3/22/95
69 * $FreeBSD: src/sys/kern/vfs_cache.c,v 1.42.2.6 2001/10/05 20:07:03 dillon Exp $
70 * $DragonFly: src/sys/kern/vfs_cache.c,v 1.91 2008/06/14 05:34:06 dillon Exp $
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/kernel.h>
76 #include <sys/sysctl.h>
77 #include <sys/mount.h>
78 #include <sys/vnode.h>
79 #include <sys/malloc.h>
80 #include <sys/sysproto.h>
82 #include <sys/namei.h>
83 #include <sys/nlookup.h>
84 #include <sys/filedesc.h>
85 #include <sys/fnv_hash.h>
86 #include <sys/globaldata.h>
87 #include <sys/kern_syscall.h>
88 #include <sys/dirent.h>
91 #include <sys/sysref2.h>
92 #include <sys/mplock2.h>
94 #define MAX_RECURSION_DEPTH 64
97 * Random lookups in the cache are accomplished with a hash table using
98 * a hash key of (nc_src_vp, name).
100 * Negative entries may exist and correspond to structures where nc_vp
101 * is NULL. In a negative entry, NCF_WHITEOUT will be set if the entry
102 * corresponds to a whited-out directory entry (verses simply not finding the
105 * Upon reaching the last segment of a path, if the reference is for DELETE,
106 * or NOCACHE is set (rewrite), and the name is located in the cache, it
111 * Structures associated with name cacheing.
113 #define NCHHASH(hash) (&nchashtbl[(hash) & nchash])
116 MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
118 static LIST_HEAD(nchashhead, namecache) *nchashtbl; /* Hash Table */
119 static struct namecache_list ncneglist; /* instead of vnode */
122 * ncvp_debug - debug cache_fromvp(). This is used by the NFS server
123 * to create the namecache infrastructure leading to a dangling vnode.
125 * 0 Only errors are reported
126 * 1 Successes are reported
127 * 2 Successes + the whole directory scan is reported
128 * 3 Force the directory scan code run as if the parent vnode did not
129 * have a namecache record, even if it does have one.
131 static int ncvp_debug;
132 SYSCTL_INT(_debug, OID_AUTO, ncvp_debug, CTLFLAG_RW, &ncvp_debug, 0, "");
134 static u_long nchash; /* size of hash table */
135 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0, "");
137 static u_long ncnegfactor = 16; /* ratio of negative entries */
138 SYSCTL_ULONG(_debug, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0, "");
140 static int nclockwarn; /* warn on locked entries in ticks */
141 SYSCTL_INT(_debug, OID_AUTO, nclockwarn, CTLFLAG_RW, &nclockwarn, 0, "");
143 static u_long numneg; /* number of cache entries allocated */
144 SYSCTL_ULONG(_debug, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0, "");
146 static u_long numcache; /* number of cache entries allocated */
147 SYSCTL_ULONG(_debug, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0, "");
149 static u_long numunres; /* number of unresolved entries */
150 SYSCTL_ULONG(_debug, OID_AUTO, numunres, CTLFLAG_RD, &numunres, 0, "");
152 SYSCTL_INT(_debug, OID_AUTO, vnsize, CTLFLAG_RD, 0, sizeof(struct vnode), "");
153 SYSCTL_INT(_debug, OID_AUTO, ncsize, CTLFLAG_RD, 0, sizeof(struct namecache), "");
155 static int cache_resolve_mp(struct mount *mp);
156 static struct vnode *cache_dvpref(struct namecache *ncp);
157 static void _cache_rehash(struct namecache *ncp);
158 static void _cache_lock(struct namecache *ncp);
159 static void _cache_setunresolved(struct namecache *ncp);
162 * The new name cache statistics
164 SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0, "Name cache statistics");
165 #define STATNODE(mode, name, var) \
166 SYSCTL_ULONG(_vfs_cache, OID_AUTO, name, mode, var, 0, "");
167 STATNODE(CTLFLAG_RD, numneg, &numneg);
168 STATNODE(CTLFLAG_RD, numcache, &numcache);
169 static u_long numcalls; STATNODE(CTLFLAG_RD, numcalls, &numcalls);
170 static u_long dothits; STATNODE(CTLFLAG_RD, dothits, &dothits);
171 static u_long dotdothits; STATNODE(CTLFLAG_RD, dotdothits, &dotdothits);
172 static u_long numchecks; STATNODE(CTLFLAG_RD, numchecks, &numchecks);
173 static u_long nummiss; STATNODE(CTLFLAG_RD, nummiss, &nummiss);
174 static u_long nummisszap; STATNODE(CTLFLAG_RD, nummisszap, &nummisszap);
175 static u_long numposzaps; STATNODE(CTLFLAG_RD, numposzaps, &numposzaps);
176 static u_long numposhits; STATNODE(CTLFLAG_RD, numposhits, &numposhits);
177 static u_long numnegzaps; STATNODE(CTLFLAG_RD, numnegzaps, &numnegzaps);
178 static u_long numneghits; STATNODE(CTLFLAG_RD, numneghits, &numneghits);
180 struct nchstats nchstats[SMP_MAXCPU];
182 * Export VFS cache effectiveness statistics to user-land.
184 * The statistics are left for aggregation to user-land so
185 * neat things can be achieved, like observing per-CPU cache
189 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
191 struct globaldata *gd;
195 for (i = 0; i < ncpus; ++i) {
196 gd = globaldata_find(i);
197 if ((error = SYSCTL_OUT(req, (void *)&(*gd->gd_nchstats),
198 sizeof(struct nchstats))))
204 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE|CTLFLAG_RD,
205 0, 0, sysctl_nchstats, "S,nchstats", "VFS cache effectiveness statistics");
207 static void cache_zap(struct namecache *ncp);
210 * cache_hold() and cache_drop() prevent the premature deletion of a
211 * namecache entry but do not prevent operations (such as zapping) on
212 * that namecache entry.
214 * This routine may only be called from outside this source module if
215 * nc_refs is already at least 1.
217 * This is a rare case where callers are allowed to hold a spinlock,
218 * so we can't ourselves.
222 _cache_hold(struct namecache *ncp)
224 atomic_add_int(&ncp->nc_refs, 1);
229 * When dropping an entry, if only one ref remains and the entry has not
230 * been resolved, zap it. Since the one reference is being dropped the
231 * entry had better not be locked.
235 _cache_drop(struct namecache *ncp)
237 KKASSERT(ncp->nc_refs > 0);
238 if (ncp->nc_refs == 1 &&
239 (ncp->nc_flag & NCF_UNRESOLVED) &&
240 TAILQ_EMPTY(&ncp->nc_list)
242 KKASSERT(ncp->nc_exlocks == 0);
246 atomic_subtract_int(&ncp->nc_refs, 1);
251 * Link a new namecache entry to its parent. Be careful to avoid races
252 * if vhold() blocks in the future.
255 cache_link_parent(struct namecache *ncp, struct namecache *par)
257 KKASSERT(ncp->nc_parent == NULL);
258 ncp->nc_parent = par;
259 if (TAILQ_EMPTY(&par->nc_list)) {
260 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
262 * Any vp associated with an ncp which has children must
263 * be held to prevent it from being recycled.
268 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
273 * Remove the parent association from a namecache structure. If this is
274 * the last child of the parent the cache_drop(par) will attempt to
275 * recursively zap the parent.
278 cache_unlink_parent(struct namecache *ncp)
280 struct namecache *par;
282 if ((par = ncp->nc_parent) != NULL) {
283 ncp->nc_parent = NULL;
284 par = _cache_hold(par);
285 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
286 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
293 * Allocate a new namecache structure. Most of the code does not require
294 * zero-termination of the string but it makes vop_compat_ncreate() easier.
296 static struct namecache *
297 cache_alloc(int nlen)
299 struct namecache *ncp;
301 ncp = kmalloc(sizeof(*ncp), M_VFSCACHE, M_WAITOK|M_ZERO);
303 ncp->nc_name = kmalloc(nlen + 1, M_VFSCACHE, M_WAITOK);
305 ncp->nc_flag = NCF_UNRESOLVED;
306 ncp->nc_error = ENOTCONN; /* needs to be resolved */
310 * Construct a fake FSMID based on the time of day and a 32 bit
311 * roller for uniqueness. This is used to generate a useful
312 * FSMID for filesystems which do not support it.
314 ncp->nc_fsmid = cache_getnewfsmid();
315 TAILQ_INIT(&ncp->nc_list);
321 _cache_free(struct namecache *ncp)
323 KKASSERT(ncp->nc_refs == 1 && ncp->nc_exlocks == 1);
325 kfree(ncp->nc_name, M_VFSCACHE);
326 kfree(ncp, M_VFSCACHE);
330 cache_zero(struct nchandle *nch)
337 * Ref and deref a namecache structure.
339 * Warning: caller may hold an unrelated read spinlock, which means we can't
340 * use read spinlocks here.
343 cache_hold(struct nchandle *nch)
345 _cache_hold(nch->ncp);
346 ++nch->mount->mnt_refs;
351 cache_copy(struct nchandle *nch, struct nchandle *target)
354 _cache_hold(target->ncp);
355 ++nch->mount->mnt_refs;
359 cache_changemount(struct nchandle *nch, struct mount *mp)
361 --nch->mount->mnt_refs;
363 ++nch->mount->mnt_refs;
367 cache_drop(struct nchandle *nch)
369 --nch->mount->mnt_refs;
370 _cache_drop(nch->ncp);
376 * Namespace locking. The caller must already hold a reference to the
377 * namecache structure in order to lock/unlock it. This function prevents
378 * the namespace from being created or destroyed by accessors other then
381 * Note that holding a locked namecache structure prevents other threads
382 * from making namespace changes (e.g. deleting or creating), prevents
383 * vnode association state changes by other threads, and prevents the
384 * namecache entry from being resolved or unresolved by other threads.
386 * The lock owner has full authority to associate/disassociate vnodes
387 * and resolve/unresolve the locked ncp.
389 * WARNING! Holding a locked ncp will prevent a vnode from being destroyed
390 * or recycled, but it does NOT help you if the vnode had already initiated
391 * a recyclement. If this is important, use cache_get() rather then
392 * cache_lock() (and deal with the differences in the way the refs counter
393 * is handled). Or, alternatively, make an unconditional call to
394 * cache_validate() or cache_resolve() after cache_lock() returns.
398 _cache_lock(struct namecache *ncp)
403 KKASSERT(ncp->nc_refs != 0);
408 if (ncp->nc_exlocks == 0) {
412 * The vp associated with a locked ncp must be held
413 * to prevent it from being recycled (which would
414 * cause the ncp to become unresolved).
416 * WARNING! If VRECLAIMED is set the vnode could
417 * already be in the middle of a recycle. Callers
418 * should not assume that nc_vp is usable when
419 * not NULL. cache_vref() or cache_vget() must be
422 * XXX loop on race for later MPSAFE work.
428 if (ncp->nc_locktd == td) {
432 ncp->nc_flag |= NCF_LOCKREQ;
433 if (tsleep(ncp, 0, "clock", nclockwarn) == EWOULDBLOCK) {
437 kprintf("[diagnostic] cache_lock: blocked on %p", ncp);
438 kprintf(" \"%*.*s\"\n",
439 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
444 kprintf("[diagnostic] cache_lock: unblocked %*.*s\n",
445 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
450 cache_lock(struct nchandle *nch)
452 _cache_lock(nch->ncp);
457 _cache_lock_nonblock(struct namecache *ncp)
461 KKASSERT(ncp->nc_refs != 0);
463 if (ncp->nc_exlocks == 0) {
467 * The vp associated with a locked ncp must be held
468 * to prevent it from being recycled (which would
469 * cause the ncp to become unresolved).
471 * WARNING! If VRECLAIMED is set the vnode could
472 * already be in the middle of a recycle. Callers
473 * should not assume that nc_vp is usable when
474 * not NULL. cache_vref() or cache_vget() must be
477 * XXX loop on race for later MPSAFE work.
488 cache_lock_nonblock(struct nchandle *nch)
490 return(_cache_lock_nonblock(nch->ncp));
495 _cache_unlock(struct namecache *ncp)
497 thread_t td __debugvar = curthread;
499 KKASSERT(ncp->nc_refs > 0);
500 KKASSERT(ncp->nc_exlocks > 0);
501 KKASSERT(ncp->nc_locktd == td);
502 if (--ncp->nc_exlocks == 0) {
505 ncp->nc_locktd = NULL;
506 if (ncp->nc_flag & NCF_LOCKREQ) {
507 ncp->nc_flag &= ~NCF_LOCKREQ;
514 cache_unlock(struct nchandle *nch)
516 _cache_unlock(nch->ncp);
520 * ref-and-lock, unlock-and-deref functions.
522 * This function is primarily used by nlookup. Even though cache_lock
523 * holds the vnode, it is possible that the vnode may have already
524 * initiated a recyclement. We want cache_get() to return a definitively
525 * usable vnode or a definitively unresolved ncp.
529 _cache_get(struct namecache *ncp)
533 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
534 _cache_setunresolved(ncp);
539 * note: the same nchandle can be passed for both arguments.
542 cache_get(struct nchandle *nch, struct nchandle *target)
544 target->mount = nch->mount;
545 target->ncp = _cache_get(nch->ncp);
546 ++target->mount->mnt_refs;
550 _cache_get_nonblock(struct namecache *ncp)
553 if (ncp->nc_exlocks == 0 || ncp->nc_locktd == curthread) {
556 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
557 _cache_setunresolved(ncp);
564 cache_get_nonblock(struct nchandle *nch)
568 if ((error = _cache_get_nonblock(nch->ncp)) == 0)
569 ++nch->mount->mnt_refs;
575 _cache_put(struct namecache *ncp)
582 cache_put(struct nchandle *nch)
584 --nch->mount->mnt_refs;
585 _cache_put(nch->ncp);
591 * Resolve an unresolved ncp by associating a vnode with it. If the
592 * vnode is NULL, a negative cache entry is created.
594 * The ncp should be locked on entry and will remain locked on return.
598 _cache_setvp(struct mount *mp, struct namecache *ncp, struct vnode *vp)
600 KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
604 * Any vp associated with an ncp which has children must
605 * be held. Any vp associated with a locked ncp must be held.
607 if (!TAILQ_EMPTY(&ncp->nc_list))
609 TAILQ_INSERT_HEAD(&vp->v_namecache, ncp, nc_vnode);
614 * Set auxiliary flags
618 ncp->nc_flag |= NCF_ISDIR;
621 ncp->nc_flag |= NCF_ISSYMLINK;
622 /* XXX cache the contents of the symlink */
631 * When creating a negative cache hit we set the
632 * namecache_gen. A later resolve will clean out the
633 * negative cache hit if the mount point's namecache_gen
634 * has changed. Used by devfs, could also be used by
637 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
639 ncp->nc_error = ENOENT;
641 ncp->nc_namecache_gen = mp->mnt_namecache_gen;
643 ncp->nc_flag &= ~NCF_UNRESOLVED;
647 cache_setvp(struct nchandle *nch, struct vnode *vp)
649 _cache_setvp(nch->mount, nch->ncp, vp);
653 cache_settimeout(struct nchandle *nch, int nticks)
655 struct namecache *ncp = nch->ncp;
657 if ((ncp->nc_timeout = ticks + nticks) == 0)
662 * Disassociate the vnode or negative-cache association and mark a
663 * namecache entry as unresolved again. Note that the ncp is still
664 * left in the hash table and still linked to its parent.
666 * The ncp should be locked and refd on entry and will remain locked and refd
669 * This routine is normally never called on a directory containing children.
670 * However, NFS often does just that in its rename() code as a cop-out to
671 * avoid complex namespace operations. This disconnects a directory vnode
672 * from its namecache and can cause the OLDAPI and NEWAPI to get out of
675 * NOTE: NCF_FSMID must be cleared so a refurbishment of the ncp, such as
676 * in a create, properly propogates flag up the chain.
680 _cache_setunresolved(struct namecache *ncp)
684 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
685 ncp->nc_flag |= NCF_UNRESOLVED;
687 ncp->nc_error = ENOTCONN;
689 if ((vp = ncp->nc_vp) != NULL) {
692 TAILQ_REMOVE(&vp->v_namecache, ncp, nc_vnode);
695 * Any vp associated with an ncp with children is
696 * held by that ncp. Any vp associated with a locked
697 * ncp is held by that ncp. These conditions must be
698 * undone when the vp is cleared out from the ncp.
700 if (ncp->nc_flag & NCF_FSMID)
702 if (!TAILQ_EMPTY(&ncp->nc_list))
707 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
710 ncp->nc_flag &= ~(NCF_WHITEOUT|NCF_ISDIR|NCF_ISSYMLINK|
716 * The cache_nresolve() code calls this function to automatically
717 * set a resolved cache element to unresolved if it has timed out
718 * or if it is a negative cache hit and the mount point namecache_gen
722 _cache_auto_unresolve(struct mount *mp, struct namecache *ncp)
725 * Already in an unresolved state, nothing to do.
727 if (ncp->nc_flag & NCF_UNRESOLVED)
731 * Try to zap entries that have timed out. We have
732 * to be careful here because locked leafs may depend
733 * on the vnode remaining intact in a parent, so only
734 * do this under very specific conditions.
736 if (ncp->nc_timeout && (int)(ncp->nc_timeout - ticks) < 0 &&
737 TAILQ_EMPTY(&ncp->nc_list)) {
738 _cache_setunresolved(ncp);
743 * If a resolved negative cache hit is invalid due to
744 * the mount's namecache generation being bumped, zap it.
746 if (ncp->nc_vp == NULL &&
747 ncp->nc_namecache_gen != mp->mnt_namecache_gen) {
748 _cache_setunresolved(ncp);
754 cache_setunresolved(struct nchandle *nch)
756 _cache_setunresolved(nch->ncp);
760 * Determine if we can clear NCF_ISMOUNTPT by scanning the mountlist
761 * looking for matches. This flag tells the lookup code when it must
762 * check for a mount linkage and also prevents the directories in question
763 * from being deleted or renamed.
767 cache_clrmountpt_callback(struct mount *mp, void *data)
769 struct nchandle *nch = data;
771 if (mp->mnt_ncmounton.ncp == nch->ncp)
773 if (mp->mnt_ncmountpt.ncp == nch->ncp)
779 cache_clrmountpt(struct nchandle *nch)
783 count = mountlist_scan(cache_clrmountpt_callback, nch,
784 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
786 nch->ncp->nc_flag &= ~NCF_ISMOUNTPT;
790 * Invalidate portions of the namecache topology given a starting entry.
791 * The passed ncp is set to an unresolved state and:
793 * The passed ncp must be locked.
795 * CINV_DESTROY - Set a flag in the passed ncp entry indicating
796 * that the physical underlying nodes have been
797 * destroyed... as in deleted. For example, when
798 * a directory is removed. This will cause record
799 * lookups on the name to no longer be able to find
800 * the record and tells the resolver to return failure
801 * rather then trying to resolve through the parent.
803 * The topology itself, including ncp->nc_name,
806 * This only applies to the passed ncp, if CINV_CHILDREN
807 * is specified the children are not flagged.
809 * CINV_CHILDREN - Set all children (recursively) to an unresolved
812 * Note that this will also have the side effect of
813 * cleaning out any unreferenced nodes in the topology
814 * from the leaves up as the recursion backs out.
816 * Note that the topology for any referenced nodes remains intact.
818 * It is possible for cache_inval() to race a cache_resolve(), meaning that
819 * the namecache entry may not actually be invalidated on return if it was
820 * revalidated while recursing down into its children. This code guarentees
821 * that the node(s) will go through an invalidation cycle, but does not
822 * guarentee that they will remain in an invalidated state.
824 * Returns non-zero if a revalidation was detected during the invalidation
825 * recursion, zero otherwise. Note that since only the original ncp is
826 * locked the revalidation ultimately can only indicate that the original ncp
827 * *MIGHT* no have been reresolved.
829 * DEEP RECURSION HANDLING - If a recursive invalidation recurses deeply we
830 * have to avoid blowing out the kernel stack. We do this by saving the
831 * deep namecache node and aborting the recursion, then re-recursing at that
832 * node using a depth-first algorithm in order to allow multiple deep
833 * recursions to chain through each other, then we restart the invalidation
838 struct namecache *resume_ncp;
842 static int _cache_inval_internal(struct namecache *, int, struct cinvtrack *);
846 _cache_inval(struct namecache *ncp, int flags)
848 struct cinvtrack track;
849 struct namecache *ncp2;
853 track.resume_ncp = NULL;
856 r = _cache_inval_internal(ncp, flags, &track);
857 if (track.resume_ncp == NULL)
859 kprintf("Warning: deep namecache recursion at %s\n",
862 while ((ncp2 = track.resume_ncp) != NULL) {
863 track.resume_ncp = NULL;
865 _cache_inval_internal(ncp2, flags & ~CINV_DESTROY,
875 cache_inval(struct nchandle *nch, int flags)
877 return(_cache_inval(nch->ncp, flags));
881 _cache_inval_internal(struct namecache *ncp, int flags, struct cinvtrack *track)
883 struct namecache *kid;
884 struct namecache *nextkid;
887 KKASSERT(ncp->nc_exlocks);
889 _cache_setunresolved(ncp);
890 if (flags & CINV_DESTROY)
891 ncp->nc_flag |= NCF_DESTROYED;
893 if ((flags & CINV_CHILDREN) &&
894 (kid = TAILQ_FIRST(&ncp->nc_list)) != NULL
896 if (++track->depth > MAX_RECURSION_DEPTH) {
897 track->resume_ncp = ncp;
904 if (track->resume_ncp) {
908 if ((nextkid = TAILQ_NEXT(kid, nc_entry)) != NULL)
909 _cache_hold(nextkid);
910 if ((kid->nc_flag & NCF_UNRESOLVED) == 0 ||
911 TAILQ_FIRST(&kid->nc_list)
914 rcnt += _cache_inval_internal(kid, flags & ~CINV_DESTROY, track);
925 * Someone could have gotten in there while ncp was unlocked,
928 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
934 * Invalidate a vnode's namecache associations. To avoid races against
935 * the resolver we do not invalidate a node which we previously invalidated
936 * but which was then re-resolved while we were in the invalidation loop.
938 * Returns non-zero if any namecache entries remain after the invalidation
941 * NOTE: unlike the namecache topology which guarentees that ncp's will not
942 * be ripped out of the topology while held, the vnode's v_namecache list
943 * has no such restriction. NCP's can be ripped out of the list at virtually
944 * any time if not locked, even if held.
947 cache_inval_vp(struct vnode *vp, int flags)
949 struct namecache *ncp;
950 struct namecache *next;
953 ncp = TAILQ_FIRST(&vp->v_namecache);
957 /* loop entered with ncp held */
958 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
961 if (ncp->nc_vp != vp) {
962 kprintf("Warning: cache_inval_vp: race-A detected on "
963 "%s\n", ncp->nc_name);
969 _cache_inval(ncp, flags);
970 _cache_put(ncp); /* also releases reference */
972 if (ncp && ncp->nc_vp != vp) {
973 kprintf("Warning: cache_inval_vp: race-B detected on "
974 "%s\n", ncp->nc_name);
979 return(TAILQ_FIRST(&vp->v_namecache) != NULL);
983 * This routine is used instead of the normal cache_inval_vp() when we
984 * are trying to recycle otherwise good vnodes.
986 * Return 0 on success, non-zero if not all namecache records could be
987 * disassociated from the vnode (for various reasons).
990 cache_inval_vp_nonblock(struct vnode *vp)
992 struct namecache *ncp;
993 struct namecache *next;
995 ncp = TAILQ_FIRST(&vp->v_namecache);
999 /* loop entered with ncp held */
1000 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1002 if (_cache_lock_nonblock(ncp)) {
1008 if (ncp->nc_vp != vp) {
1009 kprintf("Warning: cache_inval_vp: race-A detected on "
1010 "%s\n", ncp->nc_name);
1016 _cache_inval(ncp, 0);
1017 _cache_put(ncp); /* also releases reference */
1019 if (ncp && ncp->nc_vp != vp) {
1020 kprintf("Warning: cache_inval_vp: race-B detected on "
1021 "%s\n", ncp->nc_name);
1026 return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1030 * The source ncp has been renamed to the target ncp. Both fncp and tncp
1031 * must be locked. The target ncp is destroyed (as a normal rename-over
1032 * would destroy the target file or directory).
1034 * Because there may be references to the source ncp we cannot copy its
1035 * contents to the target. Instead the source ncp is relinked as the target
1036 * and the target ncp is removed from the namecache topology.
1039 cache_rename(struct nchandle *fnch, struct nchandle *tnch)
1041 struct namecache *fncp = fnch->ncp;
1042 struct namecache *tncp = tnch->ncp;
1045 _cache_setunresolved(tncp);
1046 cache_unlink_parent(fncp);
1047 cache_link_parent(fncp, tncp->nc_parent);
1048 cache_unlink_parent(tncp);
1049 oname = fncp->nc_name;
1050 fncp->nc_name = tncp->nc_name;
1051 fncp->nc_nlen = tncp->nc_nlen;
1052 tncp->nc_name = NULL;
1054 if (fncp->nc_flag & NCF_HASHED)
1055 _cache_rehash(fncp);
1056 if (tncp->nc_flag & NCF_HASHED)
1057 _cache_rehash(tncp);
1059 kfree(oname, M_VFSCACHE);
1063 * vget the vnode associated with the namecache entry. Resolve the namecache
1064 * entry if necessary and deal with namecache/vp races. The passed ncp must
1065 * be referenced and may be locked. The ncp's ref/locking state is not
1066 * effected by this call.
1068 * lk_type may be LK_SHARED, LK_EXCLUSIVE. A ref'd, possibly locked
1069 * (depending on the passed lk_type) will be returned in *vpp with an error
1070 * of 0, or NULL will be returned in *vpp with a non-0 error code. The
1071 * most typical error is ENOENT, meaning that the ncp represents a negative
1072 * cache hit and there is no vnode to retrieve, but other errors can occur
1075 * The main race we have to deal with are namecache zaps. The ncp itself
1076 * will not disappear since it is referenced, and it turns out that the
1077 * validity of the vp pointer can be checked simply by rechecking the
1078 * contents of ncp->nc_vp.
1081 cache_vget(struct nchandle *nch, struct ucred *cred,
1082 int lk_type, struct vnode **vpp)
1084 struct namecache *ncp;
1091 if (ncp->nc_flag & NCF_UNRESOLVED) {
1093 error = cache_resolve(nch, cred);
1098 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1100 * Accessing the vnode from the namecache is a bit
1101 * dangerous. Because there are no refs on the vnode, it
1102 * could be in the middle of a reclaim.
1104 if (vp->v_flag & VRECLAIMED) {
1105 kprintf("Warning: vnode reclaim race detected in cache_vget on %p (%s)\n", vp, ncp->nc_name);
1107 _cache_setunresolved(ncp);
1111 error = vget(vp, lk_type);
1113 if (vp != ncp->nc_vp)
1116 } else if (vp != ncp->nc_vp) {
1119 } else if (vp->v_flag & VRECLAIMED) {
1120 panic("vget succeeded on a VRECLAIMED node! vp %p", vp);
1123 if (error == 0 && vp == NULL)
1130 cache_vref(struct nchandle *nch, struct ucred *cred, struct vnode **vpp)
1132 struct namecache *ncp;
1140 if (ncp->nc_flag & NCF_UNRESOLVED) {
1142 error = cache_resolve(nch, cred);
1147 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1149 * Since we did not obtain any locks, a cache zap
1150 * race can occur here if the vnode is in the middle
1151 * of being reclaimed and has not yet been able to
1152 * clean out its cache node. If that case occurs,
1153 * we must lock and unresolve the cache, then loop
1156 if ((error = vget(vp, LK_SHARED)) != 0) {
1157 if (error == ENOENT) {
1158 kprintf("Warning: vnode reclaim race detected on cache_vref %p (%s)\n", vp, ncp->nc_name);
1160 _cache_setunresolved(ncp);
1166 /* caller does not want a lock */
1170 if (error == 0 && vp == NULL)
1177 * Return a referenced vnode representing the parent directory of
1178 * ncp. Because the caller has locked the ncp it should not be possible for
1179 * the parent ncp to go away.
1181 * However, we might race against the parent dvp and not be able to
1182 * reference it. If we race, return NULL.
1184 static struct vnode *
1185 cache_dvpref(struct namecache *ncp)
1187 struct namecache *par;
1191 if ((par = ncp->nc_parent) != NULL) {
1192 if ((par->nc_flag & NCF_UNRESOLVED) == 0) {
1193 if ((dvp = par->nc_vp) != NULL) {
1194 if (vget(dvp, LK_SHARED) == 0) {
1196 /* return referenced, unlocked dvp */
1207 * Recursively set the FSMID update flag for namecache nodes leading
1208 * to root. This will cause the next getattr or reclaim to increment the
1209 * fsmid and mark the inode for lazy updating.
1211 * Stop recursing when we hit a node whos NCF_FSMID flag is already set.
1212 * This makes FSMIDs work in an Einsteinian fashion - where the observation
1213 * effects the result. In this case a program monitoring a higher level
1214 * node will have detected some prior change and started its scan (clearing
1215 * NCF_FSMID in higher level nodes), but since it has not yet observed the
1216 * node where we find NCF_FSMID still set, we can safely make the related
1217 * modification without interfering with the theorized program.
1219 * This also means that FSMIDs cannot represent time-domain quantities
1220 * in a hierarchical sense. But the main reason for doing it this way
1221 * is to reduce the amount of recursion that occurs in the critical path
1222 * when e.g. a program is writing to a file that sits deep in a directory
1226 cache_update_fsmid(struct nchandle *nch)
1228 struct namecache *ncp;
1229 struct namecache *scan;
1235 * Warning: even if we get a non-NULL vp it could still be in the
1236 * middle of a recyclement. Don't do anything fancy, just set
1239 if ((vp = ncp->nc_vp) != NULL) {
1240 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1241 for (scan = ncp; scan; scan = scan->nc_parent) {
1242 if (scan->nc_flag & NCF_FSMID)
1244 scan->nc_flag |= NCF_FSMID;
1248 while (ncp && (ncp->nc_flag & NCF_FSMID) == 0) {
1249 ncp->nc_flag |= NCF_FSMID;
1250 ncp = ncp->nc_parent;
1256 cache_update_fsmid_vp(struct vnode *vp)
1258 struct namecache *ncp;
1259 struct namecache *scan;
1261 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1262 for (scan = ncp; scan; scan = scan->nc_parent) {
1263 if (scan->nc_flag & NCF_FSMID)
1265 scan->nc_flag |= NCF_FSMID;
1271 * If getattr is called on a vnode (e.g. a stat call), the filesystem
1272 * may call this routine to determine if the namecache has the hierarchical
1273 * change flag set, requiring the fsmid to be updated.
1275 * Since 0 indicates no support, make sure the filesystem fsmid is at least
1279 cache_check_fsmid_vp(struct vnode *vp, int64_t *fsmid)
1281 struct namecache *ncp;
1284 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1285 if (ncp->nc_flag & NCF_FSMID) {
1286 ncp->nc_flag &= ~NCF_FSMID;
1298 * Obtain the FSMID for a vnode for filesystems which do not support
1302 cache_sync_fsmid_vp(struct vnode *vp)
1304 struct namecache *ncp;
1306 if ((ncp = TAILQ_FIRST(&vp->v_namecache)) != NULL) {
1307 if (ncp->nc_flag & NCF_FSMID) {
1308 ncp->nc_flag &= ~NCF_FSMID;
1311 return(ncp->nc_fsmid);
1317 * Convert a directory vnode to a namecache record without any other
1318 * knowledge of the topology. This ONLY works with directory vnodes and
1319 * is ONLY used by the NFS server. dvp must be refd but unlocked, and the
1320 * returned ncp (if not NULL) will be held and unlocked.
1322 * If 'makeit' is 0 and dvp has no existing namecache record, NULL is returned.
1323 * If 'makeit' is 1 we attempt to track-down and create the namecache topology
1324 * for dvp. This will fail only if the directory has been deleted out from
1327 * Callers must always check for a NULL return no matter the value of 'makeit'.
1329 * To avoid underflowing the kernel stack each recursive call increments
1330 * the makeit variable.
1333 static int cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1334 struct vnode *dvp, char *fakename);
1335 static int cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1336 struct vnode **saved_dvp);
1339 cache_fromdvp(struct vnode *dvp, struct ucred *cred, int makeit,
1340 struct nchandle *nch)
1342 struct vnode *saved_dvp;
1348 nch->mount = dvp->v_mount;
1353 * Temporary debugging code to force the directory scanning code
1356 if (ncvp_debug >= 3 && makeit && TAILQ_FIRST(&dvp->v_namecache)) {
1357 nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
1358 kprintf("cache_fromdvp: forcing %s\n", nch->ncp->nc_name);
1363 * Loop until resolution, inside code will break out on error.
1365 while ((nch->ncp = TAILQ_FIRST(&dvp->v_namecache)) == NULL && makeit) {
1368 * If dvp is the root of its filesystem it should already
1369 * have a namecache pointer associated with it as a side
1370 * effect of the mount, but it may have been disassociated.
1372 if (dvp->v_flag & VROOT) {
1373 nch->ncp = _cache_get(nch->mount->mnt_ncmountpt.ncp);
1374 error = cache_resolve_mp(nch->mount);
1375 _cache_put(nch->ncp);
1377 kprintf("cache_fromdvp: resolve root of mount %p error %d",
1378 dvp->v_mount, error);
1382 kprintf(" failed\n");
1387 kprintf(" succeeded\n");
1392 * If we are recursed too deeply resort to an O(n^2)
1393 * algorithm to resolve the namecache topology. The
1394 * resolved pvp is left referenced in saved_dvp to
1395 * prevent the tree from being destroyed while we loop.
1398 error = cache_fromdvp_try(dvp, cred, &saved_dvp);
1400 kprintf("lookupdotdot(longpath) failed %d "
1401 "dvp %p\n", error, dvp);
1409 * Get the parent directory and resolve its ncp.
1412 kfree(fakename, M_TEMP);
1415 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
1418 kprintf("lookupdotdot failed %d dvp %p\n", error, dvp);
1424 * Reuse makeit as a recursion depth counter. On success
1425 * nch will be fully referenced.
1427 cache_fromdvp(pvp, cred, makeit + 1, nch);
1429 if (nch->ncp == NULL)
1433 * Do an inefficient scan of pvp (embodied by ncp) to look
1434 * for dvp. This will create a namecache record for dvp on
1435 * success. We loop up to recheck on success.
1437 * ncp and dvp are both held but not locked.
1439 error = cache_inefficient_scan(nch, cred, dvp, fakename);
1441 kprintf("cache_fromdvp: scan %p (%s) failed on dvp=%p\n",
1442 pvp, nch->ncp->nc_name, dvp);
1444 /* nch was NULLed out, reload mount */
1445 nch->mount = dvp->v_mount;
1449 kprintf("cache_fromdvp: scan %p (%s) succeeded\n",
1450 pvp, nch->ncp->nc_name);
1453 /* nch was NULLed out, reload mount */
1454 nch->mount = dvp->v_mount;
1458 kfree(fakename, M_TEMP);
1461 * hold it for real so the mount gets a ref
1473 * Go up the chain of parent directories until we find something
1474 * we can resolve into the namecache. This is very inefficient.
1478 cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1479 struct vnode **saved_dvp)
1481 struct nchandle nch;
1484 static time_t last_fromdvp_report;
1488 * Loop getting the parent directory vnode until we get something we
1489 * can resolve in the namecache.
1492 nch.mount = dvp->v_mount;
1498 kfree(fakename, M_TEMP);
1501 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
1508 if ((nch.ncp = TAILQ_FIRST(&pvp->v_namecache)) != NULL) {
1509 _cache_hold(nch.ncp);
1513 if (pvp->v_flag & VROOT) {
1514 nch.ncp = _cache_get(pvp->v_mount->mnt_ncmountpt.ncp);
1515 error = cache_resolve_mp(nch.mount);
1516 _cache_unlock(nch.ncp);
1519 _cache_drop(nch.ncp);
1529 if (last_fromdvp_report != time_second) {
1530 last_fromdvp_report = time_second;
1531 kprintf("Warning: extremely inefficient path "
1532 "resolution on %s\n",
1535 error = cache_inefficient_scan(&nch, cred, dvp, fakename);
1538 * Hopefully dvp now has a namecache record associated with
1539 * it. Leave it referenced to prevent the kernel from
1540 * recycling the vnode. Otherwise extremely long directory
1541 * paths could result in endless recycling.
1546 _cache_drop(nch.ncp);
1549 kfree(fakename, M_TEMP);
1554 * Do an inefficient scan of the directory represented by ncp looking for
1555 * the directory vnode dvp. ncp must be held but not locked on entry and
1556 * will be held on return. dvp must be refd but not locked on entry and
1557 * will remain refd on return.
1559 * Why do this at all? Well, due to its stateless nature the NFS server
1560 * converts file handles directly to vnodes without necessarily going through
1561 * the namecache ops that would otherwise create the namecache topology
1562 * leading to the vnode. We could either (1) Change the namecache algorithms
1563 * to allow disconnect namecache records that are re-merged opportunistically,
1564 * or (2) Make the NFS server backtrack and scan to recover a connected
1565 * namecache topology in order to then be able to issue new API lookups.
1567 * It turns out that (1) is a huge mess. It takes a nice clean set of
1568 * namecache algorithms and introduces a lot of complication in every subsystem
1569 * that calls into the namecache to deal with the re-merge case, especially
1570 * since we are using the namecache to placehold negative lookups and the
1571 * vnode might not be immediately assigned. (2) is certainly far less
1572 * efficient then (1), but since we are only talking about directories here
1573 * (which are likely to remain cached), the case does not actually run all
1574 * that often and has the supreme advantage of not polluting the namecache
1577 * If a fakename is supplied just construct a namecache entry using the
1581 cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1582 struct vnode *dvp, char *fakename)
1584 struct nlcomponent nlc;
1585 struct nchandle rncp;
1597 vat.va_blocksize = 0;
1598 if ((error = VOP_GETATTR(dvp, &vat)) != 0)
1600 if ((error = cache_vref(nch, cred, &pvp)) != 0)
1603 kprintf("inefficient_scan: directory iosize %ld "
1604 "vattr fileid = %lld\n",
1606 (long long)vat.va_fileid);
1610 * Use the supplied fakename if not NULL. Fake names are typically
1611 * not in the actual filesystem hierarchy. This is used by HAMMER
1612 * to glue @@timestamp recursions together.
1615 nlc.nlc_nameptr = fakename;
1616 nlc.nlc_namelen = strlen(fakename);
1617 rncp = cache_nlookup(nch, &nlc);
1621 if ((blksize = vat.va_blocksize) == 0)
1622 blksize = DEV_BSIZE;
1623 rbuf = kmalloc(blksize, M_TEMP, M_WAITOK);
1629 iov.iov_base = rbuf;
1630 iov.iov_len = blksize;
1633 uio.uio_resid = blksize;
1634 uio.uio_segflg = UIO_SYSSPACE;
1635 uio.uio_rw = UIO_READ;
1636 uio.uio_td = curthread;
1638 if (ncvp_debug >= 2)
1639 kprintf("cache_inefficient_scan: readdir @ %08x\n", (int)uio.uio_offset);
1640 error = VOP_READDIR(pvp, &uio, cred, &eofflag, NULL, NULL);
1642 den = (struct dirent *)rbuf;
1643 bytes = blksize - uio.uio_resid;
1646 if (ncvp_debug >= 2) {
1647 kprintf("cache_inefficient_scan: %*.*s\n",
1648 den->d_namlen, den->d_namlen,
1651 if (den->d_type != DT_WHT &&
1652 den->d_ino == vat.va_fileid) {
1654 kprintf("cache_inefficient_scan: "
1655 "MATCHED inode %lld path %s/%*.*s\n",
1656 (long long)vat.va_fileid,
1658 den->d_namlen, den->d_namlen,
1661 nlc.nlc_nameptr = den->d_name;
1662 nlc.nlc_namelen = den->d_namlen;
1663 rncp = cache_nlookup(nch, &nlc);
1664 KKASSERT(rncp.ncp != NULL);
1667 bytes -= _DIRENT_DIRSIZ(den);
1668 den = _DIRENT_NEXT(den);
1670 if (rncp.ncp == NULL && eofflag == 0 && uio.uio_resid != blksize)
1673 kfree(rbuf, M_TEMP);
1677 if (rncp.ncp->nc_flag & NCF_UNRESOLVED) {
1678 _cache_setvp(rncp.mount, rncp.ncp, dvp);
1679 if (ncvp_debug >= 2) {
1680 kprintf("cache_inefficient_scan: setvp %s/%s = %p\n",
1681 nch->ncp->nc_name, rncp.ncp->nc_name, dvp);
1684 if (ncvp_debug >= 2) {
1685 kprintf("cache_inefficient_scan: setvp %s/%s already set %p/%p\n",
1686 nch->ncp->nc_name, rncp.ncp->nc_name, dvp,
1690 if (rncp.ncp->nc_vp == NULL)
1691 error = rncp.ncp->nc_error;
1693 * Release rncp after a successful nlookup. rncp was fully
1698 kprintf("cache_inefficient_scan: dvp %p NOT FOUND in %s\n",
1699 dvp, nch->ncp->nc_name);
1706 * Zap a namecache entry. The ncp is unconditionally set to an unresolved
1707 * state, which disassociates it from its vnode or ncneglist.
1709 * Then, if there are no additional references to the ncp and no children,
1710 * the ncp is removed from the topology and destroyed. This function will
1711 * also run through the nc_parent chain and destroy parent ncps if possible.
1712 * As a side benefit, it turns out the only conditions that allow running
1713 * up the chain are also the conditions to ensure no deadlock will occur.
1715 * References and/or children may exist if the ncp is in the middle of the
1716 * topology, preventing the ncp from being destroyed.
1718 * This function must be called with the ncp held and locked and will unlock
1719 * and drop it during zapping.
1722 cache_zap(struct namecache *ncp)
1724 struct namecache *par;
1727 * Disassociate the vnode or negative cache ref and set NCF_UNRESOLVED.
1729 _cache_setunresolved(ncp);
1732 * Try to scrap the entry and possibly tail-recurse on its parent.
1733 * We only scrap unref'd (other then our ref) unresolved entries,
1734 * we do not scrap 'live' entries.
1736 while (ncp->nc_flag & NCF_UNRESOLVED) {
1738 * Someone other then us has a ref, stop.
1740 if (ncp->nc_refs > 1)
1744 * We have children, stop.
1746 if (!TAILQ_EMPTY(&ncp->nc_list))
1750 * Remove ncp from the topology: hash table and parent linkage.
1752 if (ncp->nc_flag & NCF_HASHED) {
1753 ncp->nc_flag &= ~NCF_HASHED;
1754 LIST_REMOVE(ncp, nc_hash);
1756 if ((par = ncp->nc_parent) != NULL) {
1757 par = _cache_hold(par);
1758 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
1759 ncp->nc_parent = NULL;
1760 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
1765 * ncp should not have picked up any refs. Physically
1768 KKASSERT(ncp->nc_refs == 1);
1770 /* _cache_unlock(ncp) not required */
1771 ncp->nc_refs = -1; /* safety */
1773 kfree(ncp->nc_name, M_VFSCACHE);
1774 kfree(ncp, M_VFSCACHE);
1777 * Loop on the parent (it may be NULL). Only bother looping
1778 * if the parent has a single ref (ours), which also means
1779 * we can lock it trivially.
1784 if (ncp->nc_refs != 1) {
1788 KKASSERT(par->nc_exlocks == 0);
1793 atomic_subtract_int(&ncp->nc_refs, 1);
1796 static enum { CHI_LOW, CHI_HIGH } cache_hysteresis_state = CHI_LOW;
1800 cache_hysteresis(void)
1803 * Don't cache too many negative hits. We use hysteresis to reduce
1804 * the impact on the critical path.
1806 switch(cache_hysteresis_state) {
1808 if (numneg > MINNEG && numneg * ncnegfactor > numcache) {
1810 cache_hysteresis_state = CHI_HIGH;
1814 if (numneg > MINNEG * 9 / 10 &&
1815 numneg * ncnegfactor * 9 / 10 > numcache
1819 cache_hysteresis_state = CHI_LOW;
1826 * NEW NAMECACHE LOOKUP API
1828 * Lookup an entry in the cache. A locked, referenced, non-NULL
1829 * entry is *always* returned, even if the supplied component is illegal.
1830 * The resulting namecache entry should be returned to the system with
1831 * cache_put() or _cache_unlock() + cache_drop().
1833 * namecache locks are recursive but care must be taken to avoid lock order
1836 * Nobody else will be able to manipulate the associated namespace (e.g.
1837 * create, delete, rename, rename-target) until the caller unlocks the
1840 * The returned entry will be in one of three states: positive hit (non-null
1841 * vnode), negative hit (null vnode), or unresolved (NCF_UNRESOLVED is set).
1842 * Unresolved entries must be resolved through the filesystem to associate the
1843 * vnode and/or determine whether a positive or negative hit has occured.
1845 * It is not necessary to lock a directory in order to lock namespace under
1846 * that directory. In fact, it is explicitly not allowed to do that. A
1847 * directory is typically only locked when being created, renamed, or
1850 * The directory (par) may be unresolved, in which case any returned child
1851 * will likely also be marked unresolved. Likely but not guarenteed. Since
1852 * the filesystem lookup requires a resolved directory vnode the caller is
1853 * responsible for resolving the namecache chain top-down. This API
1854 * specifically allows whole chains to be created in an unresolved state.
1857 cache_nlookup(struct nchandle *par_nch, struct nlcomponent *nlc)
1859 struct nchandle nch;
1860 struct namecache *ncp;
1861 struct namecache *new_ncp;
1862 struct nchashhead *nchpp;
1869 mp = par_nch->mount;
1872 * Try to locate an existing entry
1874 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
1875 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
1878 LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1882 * Break out if we find a matching entry. Note that
1883 * UNRESOLVED entries may match, but DESTROYED entries
1886 if (ncp->nc_parent == par_nch->ncp &&
1887 ncp->nc_nlen == nlc->nlc_namelen &&
1888 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
1889 (ncp->nc_flag & NCF_DESTROYED) == 0
1891 if (_cache_get_nonblock(ncp) == 0) {
1892 _cache_auto_unresolve(mp, ncp);
1894 _cache_free(new_ncp);
1904 * We failed to locate an entry, create a new entry and add it to
1905 * the cache. We have to relookup after possibly blocking in
1908 if (new_ncp == NULL) {
1909 new_ncp = cache_alloc(nlc->nlc_namelen);
1916 * Initialize as a new UNRESOLVED entry, lock (non-blocking),
1917 * and link to the parent. The mount point is usually inherited
1918 * from the parent unless this is a special case such as a mount
1919 * point where nlc_namelen is 0. If nlc_namelen is 0 nc_name will
1922 if (nlc->nlc_namelen) {
1923 bcopy(nlc->nlc_nameptr, ncp->nc_name, nlc->nlc_namelen);
1924 ncp->nc_name[nlc->nlc_namelen] = 0;
1926 nchpp = NCHHASH(hash);
1927 LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
1928 ncp->nc_flag |= NCF_HASHED;
1929 cache_link_parent(ncp, par_nch->ncp);
1932 * stats and namecache size management
1934 if (ncp->nc_flag & NCF_UNRESOLVED)
1935 ++gd->gd_nchstats->ncs_miss;
1936 else if (ncp->nc_vp)
1937 ++gd->gd_nchstats->ncs_goodhits;
1939 ++gd->gd_nchstats->ncs_neghits;
1943 ++nch.mount->mnt_refs;
1948 * The namecache entry is marked as being used as a mount point.
1949 * Locate the mount if it is visible to the caller.
1951 struct findmount_info {
1952 struct mount *result;
1953 struct mount *nch_mount;
1954 struct namecache *nch_ncp;
1959 cache_findmount_callback(struct mount *mp, void *data)
1961 struct findmount_info *info = data;
1964 * Check the mount's mounted-on point against the passed nch.
1966 if (mp->mnt_ncmounton.mount == info->nch_mount &&
1967 mp->mnt_ncmounton.ncp == info->nch_ncp
1976 cache_findmount(struct nchandle *nch)
1978 struct findmount_info info;
1981 info.nch_mount = nch->mount;
1982 info.nch_ncp = nch->ncp;
1983 mountlist_scan(cache_findmount_callback, &info,
1984 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1985 return(info.result);
1989 * Resolve an unresolved namecache entry, generally by looking it up.
1990 * The passed ncp must be locked and refd.
1992 * Theoretically since a vnode cannot be recycled while held, and since
1993 * the nc_parent chain holds its vnode as long as children exist, the
1994 * direct parent of the cache entry we are trying to resolve should
1995 * have a valid vnode. If not then generate an error that we can
1996 * determine is related to a resolver bug.
1998 * However, if a vnode was in the middle of a recyclement when the NCP
1999 * got locked, ncp->nc_vp might point to a vnode that is about to become
2000 * invalid. cache_resolve() handles this case by unresolving the entry
2001 * and then re-resolving it.
2003 * Note that successful resolution does not necessarily return an error
2004 * code of 0. If the ncp resolves to a negative cache hit then ENOENT
2008 cache_resolve(struct nchandle *nch, struct ucred *cred)
2010 struct namecache *par;
2011 struct namecache *ncp;
2012 struct nchandle nctmp;
2021 * If the ncp is already resolved we have nothing to do. However,
2022 * we do want to guarentee that a usable vnode is returned when
2023 * a vnode is present, so make sure it hasn't been reclaimed.
2025 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
2026 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
2027 _cache_setunresolved(ncp);
2028 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
2029 return (ncp->nc_error);
2033 * Mount points need special handling because the parent does not
2034 * belong to the same filesystem as the ncp.
2036 if (ncp == mp->mnt_ncmountpt.ncp)
2037 return (cache_resolve_mp(mp));
2040 * We expect an unbroken chain of ncps to at least the mount point,
2041 * and even all the way to root (but this code doesn't have to go
2042 * past the mount point).
2044 if (ncp->nc_parent == NULL) {
2045 kprintf("EXDEV case 1 %p %*.*s\n", ncp,
2046 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
2047 ncp->nc_error = EXDEV;
2048 return(ncp->nc_error);
2052 * The vp's of the parent directories in the chain are held via vhold()
2053 * due to the existance of the child, and should not disappear.
2054 * However, there are cases where they can disappear:
2056 * - due to filesystem I/O errors.
2057 * - due to NFS being stupid about tracking the namespace and
2058 * destroys the namespace for entire directories quite often.
2059 * - due to forced unmounts.
2060 * - due to an rmdir (parent will be marked DESTROYED)
2062 * When this occurs we have to track the chain backwards and resolve
2063 * it, looping until the resolver catches up to the current node. We
2064 * could recurse here but we might run ourselves out of kernel stack
2065 * so we do it in a more painful manner. This situation really should
2066 * not occur all that often, or if it does not have to go back too
2067 * many nodes to resolve the ncp.
2069 while ((dvp = cache_dvpref(ncp)) == NULL) {
2071 * This case can occur if a process is CD'd into a
2072 * directory which is then rmdir'd. If the parent is marked
2073 * destroyed there is no point trying to resolve it.
2075 if (ncp->nc_parent->nc_flag & NCF_DESTROYED)
2078 par = ncp->nc_parent;
2079 while (par->nc_parent && par->nc_parent->nc_vp == NULL)
2080 par = par->nc_parent;
2081 if (par->nc_parent == NULL) {
2082 kprintf("EXDEV case 2 %*.*s\n",
2083 par->nc_nlen, par->nc_nlen, par->nc_name);
2086 kprintf("[diagnostic] cache_resolve: had to recurse on %*.*s\n",
2087 par->nc_nlen, par->nc_nlen, par->nc_name);
2089 * The parent is not set in stone, ref and lock it to prevent
2090 * it from disappearing. Also note that due to renames it
2091 * is possible for our ncp to move and for par to no longer
2092 * be one of its parents. We resolve it anyway, the loop
2093 * will handle any moves.
2096 if (par == nch->mount->mnt_ncmountpt.ncp) {
2097 cache_resolve_mp(nch->mount);
2098 } else if ((dvp = cache_dvpref(par)) == NULL) {
2099 kprintf("[diagnostic] cache_resolve: raced on %*.*s\n", par->nc_nlen, par->nc_nlen, par->nc_name);
2103 if (par->nc_flag & NCF_UNRESOLVED) {
2106 par->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
2110 if ((error = par->nc_error) != 0) {
2111 if (par->nc_error != EAGAIN) {
2112 kprintf("EXDEV case 3 %*.*s error %d\n",
2113 par->nc_nlen, par->nc_nlen, par->nc_name,
2118 kprintf("[diagnostic] cache_resolve: EAGAIN par %p %*.*s\n",
2119 par, par->nc_nlen, par->nc_nlen, par->nc_name);
2126 * Call VOP_NRESOLVE() to get the vp, then scan for any disconnected
2127 * ncp's and reattach them. If this occurs the original ncp is marked
2128 * EAGAIN to force a relookup.
2130 * NOTE: in order to call VOP_NRESOLVE(), the parent of the passed
2131 * ncp must already be resolved.
2136 ncp->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
2139 ncp->nc_error = EPERM;
2141 if (ncp->nc_error == EAGAIN) {
2142 kprintf("[diagnostic] cache_resolve: EAGAIN ncp %p %*.*s\n",
2143 ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
2146 return(ncp->nc_error);
2150 * Resolve the ncp associated with a mount point. Such ncp's almost always
2151 * remain resolved and this routine is rarely called. NFS MPs tends to force
2152 * re-resolution more often due to its mac-truck-smash-the-namecache
2153 * method of tracking namespace changes.
2155 * The semantics for this call is that the passed ncp must be locked on
2156 * entry and will be locked on return. However, if we actually have to
2157 * resolve the mount point we temporarily unlock the entry in order to
2158 * avoid race-to-root deadlocks due to e.g. dead NFS mounts. Because of
2159 * the unlock we have to recheck the flags after we relock.
2162 cache_resolve_mp(struct mount *mp)
2164 struct namecache *ncp = mp->mnt_ncmountpt.ncp;
2168 KKASSERT(mp != NULL);
2171 * If the ncp is already resolved we have nothing to do. However,
2172 * we do want to guarentee that a usable vnode is returned when
2173 * a vnode is present, so make sure it hasn't been reclaimed.
2175 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
2176 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
2177 _cache_setunresolved(ncp);
2180 if (ncp->nc_flag & NCF_UNRESOLVED) {
2182 while (vfs_busy(mp, 0))
2184 error = VFS_ROOT(mp, &vp);
2188 * recheck the ncp state after relocking.
2190 if (ncp->nc_flag & NCF_UNRESOLVED) {
2191 ncp->nc_error = error;
2193 _cache_setvp(mp, ncp, vp);
2196 kprintf("[diagnostic] cache_resolve_mp: failed"
2197 " to resolve mount %p err=%d ncp=%p\n",
2199 _cache_setvp(mp, ncp, NULL);
2201 } else if (error == 0) {
2206 return(ncp->nc_error);
2210 cache_cleanneg(int count)
2212 struct namecache *ncp;
2215 * Automode from the vnlru proc - clean out 10% of the negative cache
2219 count = numneg / 10 + 1;
2222 * Attempt to clean out the specified number of negative cache
2226 ncp = TAILQ_FIRST(&ncneglist);
2228 KKASSERT(numneg == 0);
2231 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
2232 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
2233 if (_cache_get_nonblock(ncp) == 0)
2240 * Rehash a ncp. Rehashing is typically required if the name changes (should
2241 * not generally occur) or the parent link changes. This function will
2242 * unhash the ncp if the ncp is no longer hashable.
2245 _cache_rehash(struct namecache *ncp)
2247 struct nchashhead *nchpp;
2250 if (ncp->nc_flag & NCF_HASHED) {
2251 ncp->nc_flag &= ~NCF_HASHED;
2252 LIST_REMOVE(ncp, nc_hash);
2254 if (ncp->nc_nlen && ncp->nc_parent) {
2255 hash = fnv_32_buf(ncp->nc_name, ncp->nc_nlen, FNV1_32_INIT);
2256 hash = fnv_32_buf(&ncp->nc_parent,
2257 sizeof(ncp->nc_parent), hash);
2258 nchpp = NCHHASH(hash);
2259 LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
2260 ncp->nc_flag |= NCF_HASHED;
2265 * Name cache initialization, from vfsinit() when we are booting
2273 /* initialise per-cpu namecache effectiveness statistics. */
2274 for (i = 0; i < ncpus; ++i) {
2275 gd = globaldata_find(i);
2276 gd->gd_nchstats = &nchstats[i];
2278 TAILQ_INIT(&ncneglist);
2279 nchashtbl = hashinit(desiredvnodes*2, M_VFSCACHE, &nchash);
2280 nclockwarn = 5 * hz;
2284 * Called from start_init() to bootstrap the root filesystem. Returns
2285 * a referenced, unlocked namecache record.
2288 cache_allocroot(struct nchandle *nch, struct mount *mp, struct vnode *vp)
2290 nch->ncp = cache_alloc(0);
2294 _cache_setvp(nch->mount, nch->ncp, vp);
2298 * vfs_cache_setroot()
2300 * Create an association between the root of our namecache and
2301 * the root vnode. This routine may be called several times during
2304 * If the caller intends to save the returned namecache pointer somewhere
2305 * it must cache_hold() it.
2308 vfs_cache_setroot(struct vnode *nvp, struct nchandle *nch)
2311 struct nchandle onch;
2319 cache_zero(&rootnch);
2327 * XXX OLD API COMPAT FUNCTION. This really messes up the new namecache
2328 * topology and is being removed as quickly as possible. The new VOP_N*()
2329 * API calls are required to make specific adjustments using the supplied
2330 * ncp pointers rather then just bogusly purging random vnodes.
2332 * Invalidate all namecache entries to a particular vnode as well as
2333 * any direct children of that vnode in the namecache. This is a
2334 * 'catch all' purge used by filesystems that do not know any better.
2336 * Note that the linkage between the vnode and its namecache entries will
2337 * be removed, but the namecache entries themselves might stay put due to
2338 * active references from elsewhere in the system or due to the existance of
2339 * the children. The namecache topology is left intact even if we do not
2340 * know what the vnode association is. Such entries will be marked
2344 cache_purge(struct vnode *vp)
2346 cache_inval_vp(vp, CINV_DESTROY | CINV_CHILDREN);
2350 * Flush all entries referencing a particular filesystem.
2352 * Since we need to check it anyway, we will flush all the invalid
2353 * entries at the same time.
2358 cache_purgevfs(struct mount *mp)
2360 struct nchashhead *nchpp;
2361 struct namecache *ncp, *nnp;
2364 * Scan hash tables for applicable entries.
2366 for (nchpp = &nchashtbl[nchash]; nchpp >= nchashtbl; nchpp--) {
2367 ncp = LIST_FIRST(nchpp);
2371 nnp = LIST_NEXT(ncp, nc_hash);
2374 if (ncp->nc_mount == mp) {
2388 * Create a new (theoretically) unique fsmid
2391 cache_getnewfsmid(void)
2393 static int fsmid_roller;
2397 fsmid = ((int64_t)time_second << 32) |
2398 (fsmid_roller & 0x7FFFFFFF);
2403 static int disablecwd;
2404 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0, "");
2406 static u_long numcwdcalls; STATNODE(CTLFLAG_RD, numcwdcalls, &numcwdcalls);
2407 static u_long numcwdfail1; STATNODE(CTLFLAG_RD, numcwdfail1, &numcwdfail1);
2408 static u_long numcwdfail2; STATNODE(CTLFLAG_RD, numcwdfail2, &numcwdfail2);
2409 static u_long numcwdfail3; STATNODE(CTLFLAG_RD, numcwdfail3, &numcwdfail3);
2410 static u_long numcwdfail4; STATNODE(CTLFLAG_RD, numcwdfail4, &numcwdfail4);
2411 static u_long numcwdfound; STATNODE(CTLFLAG_RD, numcwdfound, &numcwdfound);
2417 sys___getcwd(struct __getcwd_args *uap)
2427 buflen = uap->buflen;
2430 if (buflen > MAXPATHLEN)
2431 buflen = MAXPATHLEN;
2433 buf = kmalloc(buflen, M_TEMP, M_WAITOK);
2435 bp = kern_getcwd(buf, buflen, &error);
2438 error = copyout(bp, uap->buf, strlen(bp) + 1);
2444 kern_getcwd(char *buf, size_t buflen, int *error)
2446 struct proc *p = curproc;
2448 int i, slash_prefixed;
2449 struct filedesc *fdp;
2450 struct nchandle nch;
2459 nch = fdp->fd_ncdir;
2460 while (nch.ncp && (nch.ncp != fdp->fd_nrdir.ncp ||
2461 nch.mount != fdp->fd_nrdir.mount)
2464 * While traversing upwards if we encounter the root
2465 * of the current mount we have to skip to the mount point
2466 * in the underlying filesystem.
2468 if (nch.ncp == nch.mount->mnt_ncmountpt.ncp) {
2469 nch = nch.mount->mnt_ncmounton;
2474 * Prepend the path segment
2476 for (i = nch.ncp->nc_nlen - 1; i >= 0; i--) {
2482 *--bp = nch.ncp->nc_name[i];
2493 * Go up a directory. This isn't a mount point so we don't
2494 * have to check again.
2496 nch.ncp = nch.ncp->nc_parent;
2498 if (nch.ncp == NULL) {
2503 if (!slash_prefixed) {
2517 * Thus begins the fullpath magic.
2521 #define STATNODE(name) \
2522 static u_int name; \
2523 SYSCTL_UINT(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, "")
2525 static int disablefullpath;
2526 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW,
2527 &disablefullpath, 0, "");
2529 STATNODE(numfullpathcalls);
2530 STATNODE(numfullpathfail1);
2531 STATNODE(numfullpathfail2);
2532 STATNODE(numfullpathfail3);
2533 STATNODE(numfullpathfail4);
2534 STATNODE(numfullpathfound);
2537 cache_fullpath(struct proc *p, struct nchandle *nchp, char **retbuf, char **freebuf)
2540 int i, slash_prefixed;
2541 struct nchandle fd_nrdir;
2542 struct nchandle nch;
2549 buf = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
2550 bp = buf + MAXPATHLEN - 1;
2553 fd_nrdir = p->p_fd->fd_nrdir;
2560 (nch.ncp != fd_nrdir.ncp || nch.mount != fd_nrdir.mount)
2563 * While traversing upwards if we encounter the root
2564 * of the current mount we have to skip to the mount point.
2566 if (nch.ncp == nch.mount->mnt_ncmountpt.ncp) {
2567 nch = nch.mount->mnt_ncmounton;
2572 * Prepend the path segment
2574 for (i = nch.ncp->nc_nlen - 1; i >= 0; i--) {
2580 *--bp = nch.ncp->nc_name[i];
2591 * Go up a directory. This isn't a mount point so we don't
2592 * have to check again.
2594 nch.ncp = nch.ncp->nc_parent;
2596 if (nch.ncp == NULL) {
2602 if (!slash_prefixed) {
2618 vn_fullpath(struct proc *p, struct vnode *vn, char **retbuf, char **freebuf)
2620 struct namecache *ncp;
2621 struct nchandle nch;
2624 if (disablefullpath)
2630 /* vn is NULL, client wants us to use p->p_textvp */
2632 if ((vn = p->p_textvp) == NULL)
2635 TAILQ_FOREACH(ncp, &vn->v_namecache, nc_vnode) {
2644 nch.mount = vn->v_mount;
2645 return(cache_fullpath(p, &nch, retbuf, freebuf));