2 * Copyright (c) 2003,2004,2009 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
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/kernel.h>
72 #include <sys/sysctl.h>
73 #include <sys/mount.h>
74 #include <sys/vnode.h>
75 #include <sys/malloc.h>
76 #include <sys/sysproto.h>
77 #include <sys/spinlock.h>
79 #include <sys/namei.h>
80 #include <sys/nlookup.h>
81 #include <sys/filedesc.h>
82 #include <sys/fnv_hash.h>
83 #include <sys/globaldata.h>
84 #include <sys/kern_syscall.h>
85 #include <sys/dirent.h>
88 #include <sys/sysref2.h>
89 #include <sys/spinlock2.h>
90 #include <sys/mplock2.h>
92 #define MAX_RECURSION_DEPTH 64
95 * Random lookups in the cache are accomplished with a hash table using
96 * a hash key of (nc_src_vp, name). Each hash chain has its own spin lock.
98 * Negative entries may exist and correspond to resolved namecache
99 * structures where nc_vp is NULL. In a negative entry, NCF_WHITEOUT
100 * will be set if the entry corresponds to a whited-out directory entry
101 * (verses simply not finding the entry at all). ncneglist is locked
102 * with a global spinlock (ncspin).
106 * (1) A ncp must be referenced before it can be locked.
108 * (2) A ncp must be locked in order to modify it.
110 * (3) ncp locks are always ordered child -> parent. That may seem
111 * backwards but forward scans use the hash table and thus can hold
112 * the parent unlocked when traversing downward.
114 * This allows insert/rename/delete/dot-dot and other operations
115 * to use ncp->nc_parent links.
117 * This also prevents a locked up e.g. NFS node from creating a
118 * chain reaction all the way back to the root vnode / namecache.
120 * (4) parent linkages require both the parent and child to be locked.
124 * Structures associated with name cacheing.
126 #define NCHHASH(hash) (&nchashtbl[(hash) & nchash])
129 #define NCMOUNT_NUMCACHE 1009 /* prime number */
131 MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
133 LIST_HEAD(nchash_list, namecache);
136 struct nchash_list list;
137 struct spinlock spin;
140 struct ncmount_cache {
141 struct spinlock spin;
142 struct namecache *ncp;
144 int isneg; /* if != 0 mp is originator and not target */
147 static struct nchash_head *nchashtbl;
148 static struct namecache_list ncneglist;
149 static struct spinlock ncspin;
150 static struct ncmount_cache ncmount_cache[NCMOUNT_NUMCACHE];
153 * ncvp_debug - debug cache_fromvp(). This is used by the NFS server
154 * to create the namecache infrastructure leading to a dangling vnode.
156 * 0 Only errors are reported
157 * 1 Successes are reported
158 * 2 Successes + the whole directory scan is reported
159 * 3 Force the directory scan code run as if the parent vnode did not
160 * have a namecache record, even if it does have one.
162 static int ncvp_debug;
163 SYSCTL_INT(_debug, OID_AUTO, ncvp_debug, CTLFLAG_RW, &ncvp_debug, 0,
164 "Namecache debug level (0-3)");
166 static u_long nchash; /* size of hash table */
167 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
168 "Size of namecache hash table");
170 static int ncnegfactor = 16; /* ratio of negative entries */
171 SYSCTL_INT(_debug, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0,
172 "Ratio of namecache negative entries");
174 static int nclockwarn; /* warn on locked entries in ticks */
175 SYSCTL_INT(_debug, OID_AUTO, nclockwarn, CTLFLAG_RW, &nclockwarn, 0,
176 "Warn on locked namecache entries in ticks");
178 static int numdefered; /* number of cache entries allocated */
179 SYSCTL_INT(_debug, OID_AUTO, numdefered, CTLFLAG_RD, &numdefered, 0,
180 "Number of cache entries allocated");
182 static int ncposlimit; /* number of cache entries allocated */
183 SYSCTL_INT(_debug, OID_AUTO, ncposlimit, CTLFLAG_RW, &ncposlimit, 0,
184 "Number of cache entries allocated");
186 SYSCTL_INT(_debug, OID_AUTO, vnsize, CTLFLAG_RD, 0, sizeof(struct vnode),
187 "sizeof(struct vnode)");
188 SYSCTL_INT(_debug, OID_AUTO, ncsize, CTLFLAG_RD, 0, sizeof(struct namecache),
189 "sizeof(struct namecache)");
191 static int ncmount_cache_enable = 1;
192 SYSCTL_INT(_debug, OID_AUTO, ncmount_cache_enable, CTLFLAG_RW,
193 &ncmount_cache_enable, 0, "mount point cache");
194 static long ncmount_cache_hit;
195 SYSCTL_LONG(_debug, OID_AUTO, ncmount_cache_hit, CTLFLAG_RW,
196 &ncmount_cache_hit, 0, "mpcache hits");
197 static long ncmount_cache_miss;
198 SYSCTL_LONG(_debug, OID_AUTO, ncmount_cache_miss, CTLFLAG_RW,
199 &ncmount_cache_miss, 0, "mpcache misses");
200 static long ncmount_cache_overwrite;
201 SYSCTL_LONG(_debug, OID_AUTO, ncmount_cache_overwrite, CTLFLAG_RW,
202 &ncmount_cache_overwrite, 0, "mpcache entry overwrites");
204 static int cache_resolve_mp(struct mount *mp);
205 static struct vnode *cache_dvpref(struct namecache *ncp);
206 static void _cache_lock(struct namecache *ncp);
207 static void _cache_setunresolved(struct namecache *ncp);
208 static void _cache_cleanneg(int count);
209 static void _cache_cleanpos(int count);
210 static void _cache_cleandefered(void);
211 static void _cache_unlink(struct namecache *ncp);
214 * The new name cache statistics
216 SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0, "Name cache statistics");
218 SYSCTL_INT(_vfs_cache, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0,
219 "Number of negative namecache entries");
221 SYSCTL_INT(_vfs_cache, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0,
222 "Number of namecaches entries");
223 static u_long numcalls;
224 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcalls, CTLFLAG_RD, &numcalls, 0,
225 "Number of namecache lookups");
226 static u_long numchecks;
227 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numchecks, CTLFLAG_RD, &numchecks, 0,
228 "Number of checked entries in namecache lookups");
230 struct nchstats nchstats[SMP_MAXCPU];
232 * Export VFS cache effectiveness statistics to user-land.
234 * The statistics are left for aggregation to user-land so
235 * neat things can be achieved, like observing per-CPU cache
239 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
241 struct globaldata *gd;
245 for (i = 0; i < ncpus; ++i) {
246 gd = globaldata_find(i);
247 if ((error = SYSCTL_OUT(req, (void *)&(*gd->gd_nchstats),
248 sizeof(struct nchstats))))
254 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE|CTLFLAG_RD,
255 0, 0, sysctl_nchstats, "S,nchstats", "VFS cache effectiveness statistics");
257 static struct namecache *cache_zap(struct namecache *ncp, int nonblock);
260 * Namespace locking. The caller must already hold a reference to the
261 * namecache structure in order to lock/unlock it. This function prevents
262 * the namespace from being created or destroyed by accessors other then
265 * Note that holding a locked namecache structure prevents other threads
266 * from making namespace changes (e.g. deleting or creating), prevents
267 * vnode association state changes by other threads, and prevents the
268 * namecache entry from being resolved or unresolved by other threads.
270 * The lock owner has full authority to associate/disassociate vnodes
271 * and resolve/unresolve the locked ncp.
273 * The primary lock field is nc_exlocks. nc_locktd is set after the
274 * fact (when locking) or cleared prior to unlocking.
276 * WARNING! Holding a locked ncp will prevent a vnode from being destroyed
277 * or recycled, but it does NOT help you if the vnode had already
278 * initiated a recyclement. If this is important, use cache_get()
279 * rather then cache_lock() (and deal with the differences in the
280 * way the refs counter is handled). Or, alternatively, make an
281 * unconditional call to cache_validate() or cache_resolve()
282 * after cache_lock() returns.
288 _cache_lock(struct namecache *ncp)
295 KKASSERT(ncp->nc_refs != 0);
300 count = ncp->nc_exlocks;
303 if (atomic_cmpset_int(&ncp->nc_exlocks, 0, 1)) {
305 * The vp associated with a locked ncp must
306 * be held to prevent it from being recycled.
308 * WARNING! If VRECLAIMED is set the vnode
309 * could already be in the middle of a recycle.
310 * Callers must use cache_vref() or
311 * cache_vget() on the locked ncp to
312 * validate the vp or set the cache entry
315 * NOTE! vhold() is allowed if we hold a
316 * lock on the ncp (which we do).
320 vhold(ncp->nc_vp); /* MPSAFE */
326 if (ncp->nc_locktd == td) {
327 if (atomic_cmpset_int(&ncp->nc_exlocks, count,
334 tsleep_interlock(ncp, 0);
335 if (atomic_cmpset_int(&ncp->nc_exlocks, count,
336 count | NC_EXLOCK_REQ) == 0) {
340 error = tsleep(ncp, PINTERLOCKED, "clock", nclockwarn);
341 if (error == EWOULDBLOCK) {
344 kprintf("[diagnostic] cache_lock: blocked "
347 kprintf(" \"%*.*s\"\n",
348 ncp->nc_nlen, ncp->nc_nlen,
354 kprintf("[diagnostic] cache_lock: unblocked %*.*s after "
356 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name,
357 (int)(ticks - didwarn) / hz);
362 * NOTE: nc_refs may be zero if the ncp is interlocked by circumstance,
363 * such as the case where one of its children is locked.
369 _cache_lock_nonblock(struct namecache *ncp)
377 count = ncp->nc_exlocks;
380 if (atomic_cmpset_int(&ncp->nc_exlocks, 0, 1)) {
382 * The vp associated with a locked ncp must
383 * be held to prevent it from being recycled.
385 * WARNING! If VRECLAIMED is set the vnode
386 * could already be in the middle of a recycle.
387 * Callers must use cache_vref() or
388 * cache_vget() on the locked ncp to
389 * validate the vp or set the cache entry
392 * NOTE! vhold() is allowed if we hold a
393 * lock on the ncp (which we do).
397 vhold(ncp->nc_vp); /* MPSAFE */
403 if (ncp->nc_locktd == td) {
404 if (atomic_cmpset_int(&ncp->nc_exlocks, count,
419 * NOTE: nc_refs can be 0 (degenerate case during _cache_drop).
421 * nc_locktd must be NULLed out prior to nc_exlocks getting cleared.
427 _cache_unlock(struct namecache *ncp)
429 thread_t td __debugvar = curthread;
432 KKASSERT(ncp->nc_refs >= 0);
433 KKASSERT(ncp->nc_exlocks > 0);
434 KKASSERT(ncp->nc_locktd == td);
436 count = ncp->nc_exlocks;
437 if ((count & ~NC_EXLOCK_REQ) == 1) {
438 ncp->nc_locktd = NULL;
443 if ((count & ~NC_EXLOCK_REQ) == 1) {
444 if (atomic_cmpset_int(&ncp->nc_exlocks, count, 0)) {
445 if (count & NC_EXLOCK_REQ)
450 if (atomic_cmpset_int(&ncp->nc_exlocks, count,
455 count = ncp->nc_exlocks;
461 * cache_hold() and cache_drop() prevent the premature deletion of a
462 * namecache entry but do not prevent operations (such as zapping) on
463 * that namecache entry.
465 * This routine may only be called from outside this source module if
466 * nc_refs is already at least 1.
468 * This is a rare case where callers are allowed to hold a spinlock,
469 * so we can't ourselves.
475 _cache_hold(struct namecache *ncp)
477 atomic_add_int(&ncp->nc_refs, 1);
482 * Drop a cache entry, taking care to deal with races.
484 * For potential 1->0 transitions we must hold the ncp lock to safely
485 * test its flags. An unresolved entry with no children must be zapped
488 * The call to cache_zap() itself will handle all remaining races and
489 * will decrement the ncp's refs regardless. If we are resolved or
490 * have children nc_refs can safely be dropped to 0 without having to
493 * NOTE: cache_zap() will re-check nc_refs and nc_list in a MPSAFE fashion.
495 * NOTE: cache_zap() may return a non-NULL referenced parent which must
496 * be dropped in a loop.
502 _cache_drop(struct namecache *ncp)
507 KKASSERT(ncp->nc_refs > 0);
511 if (_cache_lock_nonblock(ncp) == 0) {
512 ncp->nc_flag &= ~NCF_DEFEREDZAP;
513 if ((ncp->nc_flag & NCF_UNRESOLVED) &&
514 TAILQ_EMPTY(&ncp->nc_list)) {
515 ncp = cache_zap(ncp, 1);
518 if (atomic_cmpset_int(&ncp->nc_refs, 1, 0)) {
525 if (atomic_cmpset_int(&ncp->nc_refs, refs, refs - 1))
533 * Link a new namecache entry to its parent and to the hash table. Be
534 * careful to avoid races if vhold() blocks in the future.
536 * Both ncp and par must be referenced and locked.
538 * NOTE: The hash table spinlock is likely held during this call, we
539 * can't do anything fancy.
544 _cache_link_parent(struct namecache *ncp, struct namecache *par,
545 struct nchash_head *nchpp)
547 KKASSERT(ncp->nc_parent == NULL);
548 ncp->nc_parent = par;
549 ncp->nc_head = nchpp;
552 * Set inheritance flags. Note that the parent flags may be
553 * stale due to getattr potentially not having been run yet
554 * (it gets run during nlookup()'s).
556 ncp->nc_flag &= ~(NCF_SF_PNOCACHE | NCF_UF_PCACHE);
557 if (par->nc_flag & (NCF_SF_NOCACHE | NCF_SF_PNOCACHE))
558 ncp->nc_flag |= NCF_SF_PNOCACHE;
559 if (par->nc_flag & (NCF_UF_CACHE | NCF_UF_PCACHE))
560 ncp->nc_flag |= NCF_UF_PCACHE;
562 LIST_INSERT_HEAD(&nchpp->list, ncp, nc_hash);
564 if (TAILQ_EMPTY(&par->nc_list)) {
565 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
567 * Any vp associated with an ncp which has children must
568 * be held to prevent it from being recycled.
573 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
578 * Remove the parent and hash associations from a namecache structure.
579 * If this is the last child of the parent the cache_drop(par) will
580 * attempt to recursively zap the parent.
582 * ncp must be locked. This routine will acquire a temporary lock on
583 * the parent as wlel as the appropriate hash chain.
588 _cache_unlink_parent(struct namecache *ncp)
590 struct namecache *par;
591 struct vnode *dropvp;
593 if ((par = ncp->nc_parent) != NULL) {
594 KKASSERT(ncp->nc_parent == par);
597 spin_lock(&ncp->nc_head->spin);
598 LIST_REMOVE(ncp, nc_hash);
599 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
601 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
603 spin_unlock(&ncp->nc_head->spin);
604 ncp->nc_parent = NULL;
610 * We can only safely vdrop with no spinlocks held.
618 * Allocate a new namecache structure. Most of the code does not require
619 * zero-termination of the string but it makes vop_compat_ncreate() easier.
623 static struct namecache *
624 cache_alloc(int nlen)
626 struct namecache *ncp;
628 ncp = kmalloc(sizeof(*ncp), M_VFSCACHE, M_WAITOK|M_ZERO);
630 ncp->nc_name = kmalloc(nlen + 1, M_VFSCACHE, M_WAITOK);
632 ncp->nc_flag = NCF_UNRESOLVED;
633 ncp->nc_error = ENOTCONN; /* needs to be resolved */
636 TAILQ_INIT(&ncp->nc_list);
642 * Can only be called for the case where the ncp has never been
643 * associated with anything (so no spinlocks are needed).
648 _cache_free(struct namecache *ncp)
650 KKASSERT(ncp->nc_refs == 1 && ncp->nc_exlocks == 1);
652 kfree(ncp->nc_name, M_VFSCACHE);
653 kfree(ncp, M_VFSCACHE);
660 cache_zero(struct nchandle *nch)
667 * Ref and deref a namecache structure.
669 * The caller must specify a stable ncp pointer, typically meaning the
670 * ncp is already referenced but this can also occur indirectly through
671 * e.g. holding a lock on a direct child.
673 * WARNING: Caller may hold an unrelated read spinlock, which means we can't
674 * use read spinlocks here.
679 cache_hold(struct nchandle *nch)
681 _cache_hold(nch->ncp);
682 atomic_add_int(&nch->mount->mnt_refs, 1);
687 * Create a copy of a namecache handle for an already-referenced
693 cache_copy(struct nchandle *nch, struct nchandle *target)
697 _cache_hold(target->ncp);
698 atomic_add_int(&nch->mount->mnt_refs, 1);
705 cache_changemount(struct nchandle *nch, struct mount *mp)
707 atomic_add_int(&nch->mount->mnt_refs, -1);
709 atomic_add_int(&nch->mount->mnt_refs, 1);
716 cache_drop(struct nchandle *nch)
718 atomic_add_int(&nch->mount->mnt_refs, -1);
719 _cache_drop(nch->ncp);
728 cache_lock(struct nchandle *nch)
730 _cache_lock(nch->ncp);
734 * Relock nch1 given an unlocked nch1 and a locked nch2. The caller
735 * is responsible for checking both for validity on return as they
736 * may have become invalid.
738 * We have to deal with potential deadlocks here, just ping pong
739 * the lock until we get it (we will always block somewhere when
740 * looping so this is not cpu-intensive).
742 * which = 0 nch1 not locked, nch2 is locked
743 * which = 1 nch1 is locked, nch2 is not locked
746 cache_relock(struct nchandle *nch1, struct ucred *cred1,
747 struct nchandle *nch2, struct ucred *cred2)
755 if (cache_lock_nonblock(nch1) == 0) {
756 cache_resolve(nch1, cred1);
761 cache_resolve(nch1, cred1);
764 if (cache_lock_nonblock(nch2) == 0) {
765 cache_resolve(nch2, cred2);
770 cache_resolve(nch2, cred2);
780 cache_lock_nonblock(struct nchandle *nch)
782 return(_cache_lock_nonblock(nch->ncp));
790 cache_unlock(struct nchandle *nch)
792 _cache_unlock(nch->ncp);
796 * ref-and-lock, unlock-and-deref functions.
798 * This function is primarily used by nlookup. Even though cache_lock
799 * holds the vnode, it is possible that the vnode may have already
800 * initiated a recyclement.
802 * We want cache_get() to return a definitively usable vnode or a
803 * definitively unresolved ncp.
809 _cache_get(struct namecache *ncp)
813 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
814 _cache_setunresolved(ncp);
819 * This is a special form of _cache_lock() which only succeeds if
820 * it can get a pristine, non-recursive lock. The caller must have
821 * already ref'd the ncp.
823 * On success the ncp will be locked, on failure it will not. The
824 * ref count does not change either way.
826 * We want _cache_lock_special() (on success) to return a definitively
827 * usable vnode or a definitively unresolved ncp.
832 _cache_lock_special(struct namecache *ncp)
834 if (_cache_lock_nonblock(ncp) == 0) {
835 if ((ncp->nc_exlocks & ~NC_EXLOCK_REQ) == 1) {
836 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
837 _cache_setunresolved(ncp);
847 * NOTE: The same nchandle can be passed for both arguments.
852 cache_get(struct nchandle *nch, struct nchandle *target)
854 KKASSERT(nch->ncp->nc_refs > 0);
855 target->mount = nch->mount;
856 target->ncp = _cache_get(nch->ncp);
857 atomic_add_int(&target->mount->mnt_refs, 1);
865 _cache_put(struct namecache *ncp)
875 cache_put(struct nchandle *nch)
877 atomic_add_int(&nch->mount->mnt_refs, -1);
878 _cache_put(nch->ncp);
884 * Resolve an unresolved ncp by associating a vnode with it. If the
885 * vnode is NULL, a negative cache entry is created.
887 * The ncp should be locked on entry and will remain locked on return.
893 _cache_setvp(struct mount *mp, struct namecache *ncp, struct vnode *vp)
895 KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
899 * Any vp associated with an ncp which has children must
900 * be held. Any vp associated with a locked ncp must be held.
902 if (!TAILQ_EMPTY(&ncp->nc_list))
904 spin_lock(&vp->v_spin);
906 TAILQ_INSERT_HEAD(&vp->v_namecache, ncp, nc_vnode);
907 spin_unlock(&vp->v_spin);
912 * Set auxiliary flags
916 ncp->nc_flag |= NCF_ISDIR;
919 ncp->nc_flag |= NCF_ISSYMLINK;
920 /* XXX cache the contents of the symlink */
925 atomic_add_int(&numcache, 1);
927 /* XXX: this is a hack to work-around the lack of a real pfs vfs
930 if (strncmp(mp->mnt_stat.f_fstypename, "null", 5) == 0)
934 * When creating a negative cache hit we set the
935 * namecache_gen. A later resolve will clean out the
936 * negative cache hit if the mount point's namecache_gen
937 * has changed. Used by devfs, could also be used by
942 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
944 spin_unlock(&ncspin);
945 ncp->nc_error = ENOENT;
947 VFS_NCPGEN_SET(mp, ncp);
949 ncp->nc_flag &= ~(NCF_UNRESOLVED | NCF_DEFEREDZAP);
956 cache_setvp(struct nchandle *nch, struct vnode *vp)
958 _cache_setvp(nch->mount, nch->ncp, vp);
965 cache_settimeout(struct nchandle *nch, int nticks)
967 struct namecache *ncp = nch->ncp;
969 if ((ncp->nc_timeout = ticks + nticks) == 0)
974 * Disassociate the vnode or negative-cache association and mark a
975 * namecache entry as unresolved again. Note that the ncp is still
976 * left in the hash table and still linked to its parent.
978 * The ncp should be locked and refd on entry and will remain locked and refd
981 * This routine is normally never called on a directory containing children.
982 * However, NFS often does just that in its rename() code as a cop-out to
983 * avoid complex namespace operations. This disconnects a directory vnode
984 * from its namecache and can cause the OLDAPI and NEWAPI to get out of
991 _cache_setunresolved(struct namecache *ncp)
995 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
996 ncp->nc_flag |= NCF_UNRESOLVED;
998 ncp->nc_error = ENOTCONN;
999 if ((vp = ncp->nc_vp) != NULL) {
1000 atomic_add_int(&numcache, -1);
1001 spin_lock(&vp->v_spin);
1003 TAILQ_REMOVE(&vp->v_namecache, ncp, nc_vnode);
1004 spin_unlock(&vp->v_spin);
1007 * Any vp associated with an ncp with children is
1008 * held by that ncp. Any vp associated with a locked
1009 * ncp is held by that ncp. These conditions must be
1010 * undone when the vp is cleared out from the ncp.
1012 if (!TAILQ_EMPTY(&ncp->nc_list))
1014 if (ncp->nc_exlocks)
1018 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
1020 spin_unlock(&ncspin);
1022 ncp->nc_flag &= ~(NCF_WHITEOUT|NCF_ISDIR|NCF_ISSYMLINK);
1027 * The cache_nresolve() code calls this function to automatically
1028 * set a resolved cache element to unresolved if it has timed out
1029 * or if it is a negative cache hit and the mount point namecache_gen
1034 static __inline void
1035 _cache_auto_unresolve(struct mount *mp, struct namecache *ncp)
1038 * Already in an unresolved state, nothing to do.
1040 if (ncp->nc_flag & NCF_UNRESOLVED)
1044 * Try to zap entries that have timed out. We have
1045 * to be careful here because locked leafs may depend
1046 * on the vnode remaining intact in a parent, so only
1047 * do this under very specific conditions.
1049 if (ncp->nc_timeout && (int)(ncp->nc_timeout - ticks) < 0 &&
1050 TAILQ_EMPTY(&ncp->nc_list)) {
1051 _cache_setunresolved(ncp);
1056 * If a resolved negative cache hit is invalid due to
1057 * the mount's namecache generation being bumped, zap it.
1059 if (ncp->nc_vp == NULL && VFS_NCPGEN_TEST(mp, ncp)) {
1060 _cache_setunresolved(ncp);
1069 cache_setunresolved(struct nchandle *nch)
1071 _cache_setunresolved(nch->ncp);
1075 * Determine if we can clear NCF_ISMOUNTPT by scanning the mountlist
1076 * looking for matches. This flag tells the lookup code when it must
1077 * check for a mount linkage and also prevents the directories in question
1078 * from being deleted or renamed.
1084 cache_clrmountpt_callback(struct mount *mp, void *data)
1086 struct nchandle *nch = data;
1088 if (mp->mnt_ncmounton.ncp == nch->ncp)
1090 if (mp->mnt_ncmountpt.ncp == nch->ncp)
1099 cache_clrmountpt(struct nchandle *nch)
1103 count = mountlist_scan(cache_clrmountpt_callback, nch,
1104 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1106 nch->ncp->nc_flag &= ~NCF_ISMOUNTPT;
1110 * Invalidate portions of the namecache topology given a starting entry.
1111 * The passed ncp is set to an unresolved state and:
1113 * The passed ncp must be referencxed and locked. The routine may unlock
1114 * and relock ncp several times, and will recheck the children and loop
1115 * to catch races. When done the passed ncp will be returned with the
1116 * reference and lock intact.
1118 * CINV_DESTROY - Set a flag in the passed ncp entry indicating
1119 * that the physical underlying nodes have been
1120 * destroyed... as in deleted. For example, when
1121 * a directory is removed. This will cause record
1122 * lookups on the name to no longer be able to find
1123 * the record and tells the resolver to return failure
1124 * rather then trying to resolve through the parent.
1126 * The topology itself, including ncp->nc_name,
1129 * This only applies to the passed ncp, if CINV_CHILDREN
1130 * is specified the children are not flagged.
1132 * CINV_CHILDREN - Set all children (recursively) to an unresolved
1135 * Note that this will also have the side effect of
1136 * cleaning out any unreferenced nodes in the topology
1137 * from the leaves up as the recursion backs out.
1139 * Note that the topology for any referenced nodes remains intact, but
1140 * the nodes will be marked as having been destroyed and will be set
1141 * to an unresolved state.
1143 * It is possible for cache_inval() to race a cache_resolve(), meaning that
1144 * the namecache entry may not actually be invalidated on return if it was
1145 * revalidated while recursing down into its children. This code guarentees
1146 * that the node(s) will go through an invalidation cycle, but does not
1147 * guarentee that they will remain in an invalidated state.
1149 * Returns non-zero if a revalidation was detected during the invalidation
1150 * recursion, zero otherwise. Note that since only the original ncp is
1151 * locked the revalidation ultimately can only indicate that the original ncp
1152 * *MIGHT* no have been reresolved.
1154 * DEEP RECURSION HANDLING - If a recursive invalidation recurses deeply we
1155 * have to avoid blowing out the kernel stack. We do this by saving the
1156 * deep namecache node and aborting the recursion, then re-recursing at that
1157 * node using a depth-first algorithm in order to allow multiple deep
1158 * recursions to chain through each other, then we restart the invalidation
1165 struct namecache *resume_ncp;
1169 static int _cache_inval_internal(struct namecache *, int, struct cinvtrack *);
1173 _cache_inval(struct namecache *ncp, int flags)
1175 struct cinvtrack track;
1176 struct namecache *ncp2;
1180 track.resume_ncp = NULL;
1183 r = _cache_inval_internal(ncp, flags, &track);
1184 if (track.resume_ncp == NULL)
1186 kprintf("Warning: deep namecache recursion at %s\n",
1189 while ((ncp2 = track.resume_ncp) != NULL) {
1190 track.resume_ncp = NULL;
1192 _cache_inval_internal(ncp2, flags & ~CINV_DESTROY,
1202 cache_inval(struct nchandle *nch, int flags)
1204 return(_cache_inval(nch->ncp, flags));
1208 * Helper for _cache_inval(). The passed ncp is refd and locked and
1209 * remains that way on return, but may be unlocked/relocked multiple
1210 * times by the routine.
1213 _cache_inval_internal(struct namecache *ncp, int flags, struct cinvtrack *track)
1215 struct namecache *kid;
1216 struct namecache *nextkid;
1219 KKASSERT(ncp->nc_exlocks);
1221 _cache_setunresolved(ncp);
1222 if (flags & CINV_DESTROY)
1223 ncp->nc_flag |= NCF_DESTROYED;
1224 if ((flags & CINV_CHILDREN) &&
1225 (kid = TAILQ_FIRST(&ncp->nc_list)) != NULL
1228 if (++track->depth > MAX_RECURSION_DEPTH) {
1229 track->resume_ncp = ncp;
1235 if (track->resume_ncp) {
1239 if ((nextkid = TAILQ_NEXT(kid, nc_entry)) != NULL)
1240 _cache_hold(nextkid);
1241 if ((kid->nc_flag & NCF_UNRESOLVED) == 0 ||
1242 TAILQ_FIRST(&kid->nc_list)
1245 rcnt += _cache_inval_internal(kid, flags & ~CINV_DESTROY, track);
1256 * Someone could have gotten in there while ncp was unlocked,
1259 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
1265 * Invalidate a vnode's namecache associations. To avoid races against
1266 * the resolver we do not invalidate a node which we previously invalidated
1267 * but which was then re-resolved while we were in the invalidation loop.
1269 * Returns non-zero if any namecache entries remain after the invalidation
1272 * NOTE: Unlike the namecache topology which guarentees that ncp's will not
1273 * be ripped out of the topology while held, the vnode's v_namecache
1274 * list has no such restriction. NCP's can be ripped out of the list
1275 * at virtually any time if not locked, even if held.
1277 * In addition, the v_namecache list itself must be locked via
1278 * the vnode's spinlock.
1283 cache_inval_vp(struct vnode *vp, int flags)
1285 struct namecache *ncp;
1286 struct namecache *next;
1289 spin_lock(&vp->v_spin);
1290 ncp = TAILQ_FIRST(&vp->v_namecache);
1294 /* loop entered with ncp held and vp spin-locked */
1295 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1297 spin_unlock(&vp->v_spin);
1299 if (ncp->nc_vp != vp) {
1300 kprintf("Warning: cache_inval_vp: race-A detected on "
1301 "%s\n", ncp->nc_name);
1307 _cache_inval(ncp, flags);
1308 _cache_put(ncp); /* also releases reference */
1310 spin_lock(&vp->v_spin);
1311 if (ncp && ncp->nc_vp != vp) {
1312 spin_unlock(&vp->v_spin);
1313 kprintf("Warning: cache_inval_vp: race-B detected on "
1314 "%s\n", ncp->nc_name);
1319 spin_unlock(&vp->v_spin);
1320 return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1324 * This routine is used instead of the normal cache_inval_vp() when we
1325 * are trying to recycle otherwise good vnodes.
1327 * Return 0 on success, non-zero if not all namecache records could be
1328 * disassociated from the vnode (for various reasons).
1333 cache_inval_vp_nonblock(struct vnode *vp)
1335 struct namecache *ncp;
1336 struct namecache *next;
1338 spin_lock(&vp->v_spin);
1339 ncp = TAILQ_FIRST(&vp->v_namecache);
1343 /* loop entered with ncp held */
1344 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1346 spin_unlock(&vp->v_spin);
1347 if (_cache_lock_nonblock(ncp)) {
1353 if (ncp->nc_vp != vp) {
1354 kprintf("Warning: cache_inval_vp: race-A detected on "
1355 "%s\n", ncp->nc_name);
1361 _cache_inval(ncp, 0);
1362 _cache_put(ncp); /* also releases reference */
1364 spin_lock(&vp->v_spin);
1365 if (ncp && ncp->nc_vp != vp) {
1366 spin_unlock(&vp->v_spin);
1367 kprintf("Warning: cache_inval_vp: race-B detected on "
1368 "%s\n", ncp->nc_name);
1373 spin_unlock(&vp->v_spin);
1375 return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1379 * The source ncp has been renamed to the target ncp. Both fncp and tncp
1380 * must be locked. The target ncp is destroyed (as a normal rename-over
1381 * would destroy the target file or directory).
1383 * Because there may be references to the source ncp we cannot copy its
1384 * contents to the target. Instead the source ncp is relinked as the target
1385 * and the target ncp is removed from the namecache topology.
1390 cache_rename(struct nchandle *fnch, struct nchandle *tnch)
1392 struct namecache *fncp = fnch->ncp;
1393 struct namecache *tncp = tnch->ncp;
1394 struct namecache *tncp_par;
1395 struct nchash_head *nchpp;
1400 if (tncp->nc_nlen) {
1401 nname = kmalloc(tncp->nc_nlen + 1, M_VFSCACHE, M_WAITOK);
1402 bcopy(tncp->nc_name, nname, tncp->nc_nlen);
1403 nname[tncp->nc_nlen] = 0;
1409 * Rename fncp (unlink)
1411 _cache_unlink_parent(fncp);
1412 oname = fncp->nc_name;
1413 fncp->nc_name = nname;
1414 fncp->nc_nlen = tncp->nc_nlen;
1416 kfree(oname, M_VFSCACHE);
1418 tncp_par = tncp->nc_parent;
1419 _cache_hold(tncp_par);
1420 _cache_lock(tncp_par);
1423 * Rename fncp (relink)
1425 hash = fnv_32_buf(fncp->nc_name, fncp->nc_nlen, FNV1_32_INIT);
1426 hash = fnv_32_buf(&tncp_par, sizeof(tncp_par), hash);
1427 nchpp = NCHHASH(hash);
1429 spin_lock(&nchpp->spin);
1430 _cache_link_parent(fncp, tncp_par, nchpp);
1431 spin_unlock(&nchpp->spin);
1433 _cache_put(tncp_par);
1436 * Get rid of the overwritten tncp (unlink)
1438 _cache_unlink(tncp);
1442 * Perform actions consistent with unlinking a file. The passed-in ncp
1445 * The ncp is marked DESTROYED so it no longer shows up in searches,
1446 * and will be physically deleted when the vnode goes away.
1448 * If the related vnode has no refs then we cycle it through vget()/vput()
1449 * to (possibly if we don't have a ref race) trigger a deactivation,
1450 * allowing the VFS to trivially detect and recycle the deleted vnode
1451 * via VOP_INACTIVE().
1453 * NOTE: _cache_rename() will automatically call _cache_unlink() on the
1457 cache_unlink(struct nchandle *nch)
1459 _cache_unlink(nch->ncp);
1463 _cache_unlink(struct namecache *ncp)
1468 * Causes lookups to fail and allows another ncp with the same
1469 * name to be created under ncp->nc_parent.
1471 ncp->nc_flag |= NCF_DESTROYED;
1474 * Attempt to trigger a deactivation.
1476 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
1477 (vp = ncp->nc_vp) != NULL &&
1478 !sysref_isactive(&vp->v_sysref)) {
1479 if (vget(vp, LK_SHARED) == 0)
1485 * vget the vnode associated with the namecache entry. Resolve the namecache
1486 * entry if necessary. The passed ncp must be referenced and locked.
1488 * lk_type may be LK_SHARED, LK_EXCLUSIVE. A ref'd, possibly locked
1489 * (depending on the passed lk_type) will be returned in *vpp with an error
1490 * of 0, or NULL will be returned in *vpp with a non-0 error code. The
1491 * most typical error is ENOENT, meaning that the ncp represents a negative
1492 * cache hit and there is no vnode to retrieve, but other errors can occur
1495 * The vget() can race a reclaim. If this occurs we re-resolve the
1498 * There are numerous places in the kernel where vget() is called on a
1499 * vnode while one or more of its namecache entries is locked. Releasing
1500 * a vnode never deadlocks against locked namecache entries (the vnode
1501 * will not get recycled while referenced ncp's exist). This means we
1502 * can safely acquire the vnode. In fact, we MUST NOT release the ncp
1503 * lock when acquiring the vp lock or we might cause a deadlock.
1508 cache_vget(struct nchandle *nch, struct ucred *cred,
1509 int lk_type, struct vnode **vpp)
1511 struct namecache *ncp;
1516 KKASSERT(ncp->nc_locktd == curthread);
1519 if (ncp->nc_flag & NCF_UNRESOLVED)
1520 error = cache_resolve(nch, cred);
1524 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1525 error = vget(vp, lk_type);
1530 if (error == ENOENT) {
1531 kprintf("Warning: vnode reclaim race detected "
1532 "in cache_vget on %p (%s)\n",
1534 _cache_setunresolved(ncp);
1539 * Not a reclaim race, some other error.
1541 KKASSERT(ncp->nc_vp == vp);
1544 KKASSERT(ncp->nc_vp == vp);
1545 KKASSERT((vp->v_flag & VRECLAIMED) == 0);
1548 if (error == 0 && vp == NULL)
1555 cache_vref(struct nchandle *nch, struct ucred *cred, struct vnode **vpp)
1557 struct namecache *ncp;
1562 KKASSERT(ncp->nc_locktd == curthread);
1565 if (ncp->nc_flag & NCF_UNRESOLVED)
1566 error = cache_resolve(nch, cred);
1570 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1571 error = vget(vp, LK_SHARED);
1576 if (error == ENOENT) {
1577 kprintf("Warning: vnode reclaim race detected "
1578 "in cache_vget on %p (%s)\n",
1580 _cache_setunresolved(ncp);
1585 * Not a reclaim race, some other error.
1587 KKASSERT(ncp->nc_vp == vp);
1590 KKASSERT(ncp->nc_vp == vp);
1591 KKASSERT((vp->v_flag & VRECLAIMED) == 0);
1592 /* caller does not want a lock */
1596 if (error == 0 && vp == NULL)
1603 * Return a referenced vnode representing the parent directory of
1606 * Because the caller has locked the ncp it should not be possible for
1607 * the parent ncp to go away. However, the parent can unresolve its
1608 * dvp at any time so we must be able to acquire a lock on the parent
1609 * to safely access nc_vp.
1611 * We have to leave par unlocked when vget()ing dvp to avoid a deadlock,
1612 * so use vhold()/vdrop() while holding the lock to prevent dvp from
1613 * getting destroyed.
1615 * MPSAFE - Note vhold() is allowed when dvp has 0 refs if we hold a
1616 * lock on the ncp in question..
1618 static struct vnode *
1619 cache_dvpref(struct namecache *ncp)
1621 struct namecache *par;
1625 if ((par = ncp->nc_parent) != NULL) {
1628 if ((par->nc_flag & NCF_UNRESOLVED) == 0) {
1629 if ((dvp = par->nc_vp) != NULL)
1634 if (vget(dvp, LK_SHARED) == 0) {
1637 /* return refd, unlocked dvp */
1649 * Convert a directory vnode to a namecache record without any other
1650 * knowledge of the topology. This ONLY works with directory vnodes and
1651 * is ONLY used by the NFS server. dvp must be refd but unlocked, and the
1652 * returned ncp (if not NULL) will be held and unlocked.
1654 * If 'makeit' is 0 and dvp has no existing namecache record, NULL is returned.
1655 * If 'makeit' is 1 we attempt to track-down and create the namecache topology
1656 * for dvp. This will fail only if the directory has been deleted out from
1659 * Callers must always check for a NULL return no matter the value of 'makeit'.
1661 * To avoid underflowing the kernel stack each recursive call increments
1662 * the makeit variable.
1665 static int cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1666 struct vnode *dvp, char *fakename);
1667 static int cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1668 struct vnode **saved_dvp);
1671 cache_fromdvp(struct vnode *dvp, struct ucred *cred, int makeit,
1672 struct nchandle *nch)
1674 struct vnode *saved_dvp;
1680 nch->mount = dvp->v_mount;
1685 * Handle the makeit == 0 degenerate case
1688 spin_lock(&dvp->v_spin);
1689 nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
1692 spin_unlock(&dvp->v_spin);
1696 * Loop until resolution, inside code will break out on error.
1700 * Break out if we successfully acquire a working ncp.
1702 spin_lock(&dvp->v_spin);
1703 nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
1706 spin_unlock(&dvp->v_spin);
1709 spin_unlock(&dvp->v_spin);
1712 * If dvp is the root of its filesystem it should already
1713 * have a namecache pointer associated with it as a side
1714 * effect of the mount, but it may have been disassociated.
1716 if (dvp->v_flag & VROOT) {
1717 nch->ncp = _cache_get(nch->mount->mnt_ncmountpt.ncp);
1718 error = cache_resolve_mp(nch->mount);
1719 _cache_put(nch->ncp);
1721 kprintf("cache_fromdvp: resolve root of mount %p error %d",
1722 dvp->v_mount, error);
1726 kprintf(" failed\n");
1731 kprintf(" succeeded\n");
1736 * If we are recursed too deeply resort to an O(n^2)
1737 * algorithm to resolve the namecache topology. The
1738 * resolved pvp is left referenced in saved_dvp to
1739 * prevent the tree from being destroyed while we loop.
1742 error = cache_fromdvp_try(dvp, cred, &saved_dvp);
1744 kprintf("lookupdotdot(longpath) failed %d "
1745 "dvp %p\n", error, dvp);
1753 * Get the parent directory and resolve its ncp.
1756 kfree(fakename, M_TEMP);
1759 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
1762 kprintf("lookupdotdot failed %d dvp %p\n", error, dvp);
1768 * Reuse makeit as a recursion depth counter. On success
1769 * nch will be fully referenced.
1771 cache_fromdvp(pvp, cred, makeit + 1, nch);
1773 if (nch->ncp == NULL)
1777 * Do an inefficient scan of pvp (embodied by ncp) to look
1778 * for dvp. This will create a namecache record for dvp on
1779 * success. We loop up to recheck on success.
1781 * ncp and dvp are both held but not locked.
1783 error = cache_inefficient_scan(nch, cred, dvp, fakename);
1785 kprintf("cache_fromdvp: scan %p (%s) failed on dvp=%p\n",
1786 pvp, nch->ncp->nc_name, dvp);
1788 /* nch was NULLed out, reload mount */
1789 nch->mount = dvp->v_mount;
1793 kprintf("cache_fromdvp: scan %p (%s) succeeded\n",
1794 pvp, nch->ncp->nc_name);
1797 /* nch was NULLed out, reload mount */
1798 nch->mount = dvp->v_mount;
1802 * If nch->ncp is non-NULL it will have been held already.
1805 kfree(fakename, M_TEMP);
1814 * Go up the chain of parent directories until we find something
1815 * we can resolve into the namecache. This is very inefficient.
1819 cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1820 struct vnode **saved_dvp)
1822 struct nchandle nch;
1825 static time_t last_fromdvp_report;
1829 * Loop getting the parent directory vnode until we get something we
1830 * can resolve in the namecache.
1833 nch.mount = dvp->v_mount;
1839 kfree(fakename, M_TEMP);
1842 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
1849 spin_lock(&pvp->v_spin);
1850 if ((nch.ncp = TAILQ_FIRST(&pvp->v_namecache)) != NULL) {
1851 _cache_hold(nch.ncp);
1852 spin_unlock(&pvp->v_spin);
1856 spin_unlock(&pvp->v_spin);
1857 if (pvp->v_flag & VROOT) {
1858 nch.ncp = _cache_get(pvp->v_mount->mnt_ncmountpt.ncp);
1859 error = cache_resolve_mp(nch.mount);
1860 _cache_unlock(nch.ncp);
1863 _cache_drop(nch.ncp);
1873 if (last_fromdvp_report != time_second) {
1874 last_fromdvp_report = time_second;
1875 kprintf("Warning: extremely inefficient path "
1876 "resolution on %s\n",
1879 error = cache_inefficient_scan(&nch, cred, dvp, fakename);
1882 * Hopefully dvp now has a namecache record associated with
1883 * it. Leave it referenced to prevent the kernel from
1884 * recycling the vnode. Otherwise extremely long directory
1885 * paths could result in endless recycling.
1890 _cache_drop(nch.ncp);
1893 kfree(fakename, M_TEMP);
1898 * Do an inefficient scan of the directory represented by ncp looking for
1899 * the directory vnode dvp. ncp must be held but not locked on entry and
1900 * will be held on return. dvp must be refd but not locked on entry and
1901 * will remain refd on return.
1903 * Why do this at all? Well, due to its stateless nature the NFS server
1904 * converts file handles directly to vnodes without necessarily going through
1905 * the namecache ops that would otherwise create the namecache topology
1906 * leading to the vnode. We could either (1) Change the namecache algorithms
1907 * to allow disconnect namecache records that are re-merged opportunistically,
1908 * or (2) Make the NFS server backtrack and scan to recover a connected
1909 * namecache topology in order to then be able to issue new API lookups.
1911 * It turns out that (1) is a huge mess. It takes a nice clean set of
1912 * namecache algorithms and introduces a lot of complication in every subsystem
1913 * that calls into the namecache to deal with the re-merge case, especially
1914 * since we are using the namecache to placehold negative lookups and the
1915 * vnode might not be immediately assigned. (2) is certainly far less
1916 * efficient then (1), but since we are only talking about directories here
1917 * (which are likely to remain cached), the case does not actually run all
1918 * that often and has the supreme advantage of not polluting the namecache
1921 * If a fakename is supplied just construct a namecache entry using the
1925 cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1926 struct vnode *dvp, char *fakename)
1928 struct nlcomponent nlc;
1929 struct nchandle rncp;
1941 vat.va_blocksize = 0;
1942 if ((error = VOP_GETATTR(dvp, &vat)) != 0)
1945 error = cache_vref(nch, cred, &pvp);
1950 kprintf("inefficient_scan: directory iosize %ld "
1951 "vattr fileid = %lld\n",
1953 (long long)vat.va_fileid);
1957 * Use the supplied fakename if not NULL. Fake names are typically
1958 * not in the actual filesystem hierarchy. This is used by HAMMER
1959 * to glue @@timestamp recursions together.
1962 nlc.nlc_nameptr = fakename;
1963 nlc.nlc_namelen = strlen(fakename);
1964 rncp = cache_nlookup(nch, &nlc);
1968 if ((blksize = vat.va_blocksize) == 0)
1969 blksize = DEV_BSIZE;
1970 rbuf = kmalloc(blksize, M_TEMP, M_WAITOK);
1976 iov.iov_base = rbuf;
1977 iov.iov_len = blksize;
1980 uio.uio_resid = blksize;
1981 uio.uio_segflg = UIO_SYSSPACE;
1982 uio.uio_rw = UIO_READ;
1983 uio.uio_td = curthread;
1985 if (ncvp_debug >= 2)
1986 kprintf("cache_inefficient_scan: readdir @ %08x\n", (int)uio.uio_offset);
1987 error = VOP_READDIR(pvp, &uio, cred, &eofflag, NULL, NULL);
1989 den = (struct dirent *)rbuf;
1990 bytes = blksize - uio.uio_resid;
1993 if (ncvp_debug >= 2) {
1994 kprintf("cache_inefficient_scan: %*.*s\n",
1995 den->d_namlen, den->d_namlen,
1998 if (den->d_type != DT_WHT &&
1999 den->d_ino == vat.va_fileid) {
2001 kprintf("cache_inefficient_scan: "
2002 "MATCHED inode %lld path %s/%*.*s\n",
2003 (long long)vat.va_fileid,
2005 den->d_namlen, den->d_namlen,
2008 nlc.nlc_nameptr = den->d_name;
2009 nlc.nlc_namelen = den->d_namlen;
2010 rncp = cache_nlookup(nch, &nlc);
2011 KKASSERT(rncp.ncp != NULL);
2014 bytes -= _DIRENT_DIRSIZ(den);
2015 den = _DIRENT_NEXT(den);
2017 if (rncp.ncp == NULL && eofflag == 0 && uio.uio_resid != blksize)
2020 kfree(rbuf, M_TEMP);
2024 if (rncp.ncp->nc_flag & NCF_UNRESOLVED) {
2025 _cache_setvp(rncp.mount, rncp.ncp, dvp);
2026 if (ncvp_debug >= 2) {
2027 kprintf("cache_inefficient_scan: setvp %s/%s = %p\n",
2028 nch->ncp->nc_name, rncp.ncp->nc_name, dvp);
2031 if (ncvp_debug >= 2) {
2032 kprintf("cache_inefficient_scan: setvp %s/%s already set %p/%p\n",
2033 nch->ncp->nc_name, rncp.ncp->nc_name, dvp,
2037 if (rncp.ncp->nc_vp == NULL)
2038 error = rncp.ncp->nc_error;
2040 * Release rncp after a successful nlookup. rncp was fully
2045 kprintf("cache_inefficient_scan: dvp %p NOT FOUND in %s\n",
2046 dvp, nch->ncp->nc_name);
2053 * Zap a namecache entry. The ncp is unconditionally set to an unresolved
2054 * state, which disassociates it from its vnode or ncneglist.
2056 * Then, if there are no additional references to the ncp and no children,
2057 * the ncp is removed from the topology and destroyed.
2059 * References and/or children may exist if the ncp is in the middle of the
2060 * topology, preventing the ncp from being destroyed.
2062 * This function must be called with the ncp held and locked and will unlock
2063 * and drop it during zapping.
2065 * If nonblock is non-zero and the parent ncp cannot be locked we give up.
2066 * This case can occur in the cache_drop() path.
2068 * This function may returned a held (but NOT locked) parent node which the
2069 * caller must drop. We do this so _cache_drop() can loop, to avoid
2070 * blowing out the kernel stack.
2072 * WARNING! For MPSAFE operation this routine must acquire up to three
2073 * spin locks to be able to safely test nc_refs. Lock order is
2076 * hash spinlock if on hash list
2077 * parent spinlock if child of parent
2078 * (the ncp is unresolved so there is no vnode association)
2080 static struct namecache *
2081 cache_zap(struct namecache *ncp, int nonblock)
2083 struct namecache *par;
2084 struct vnode *dropvp;
2088 * Disassociate the vnode or negative cache ref and set NCF_UNRESOLVED.
2090 _cache_setunresolved(ncp);
2093 * Try to scrap the entry and possibly tail-recurse on its parent.
2094 * We only scrap unref'd (other then our ref) unresolved entries,
2095 * we do not scrap 'live' entries.
2097 * Note that once the spinlocks are acquired if nc_refs == 1 no
2098 * other references are possible. If it isn't, however, we have
2099 * to decrement but also be sure to avoid a 1->0 transition.
2101 KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
2102 KKASSERT(ncp->nc_refs > 0);
2105 * Acquire locks. Note that the parent can't go away while we hold
2108 if ((par = ncp->nc_parent) != NULL) {
2111 if (_cache_lock_nonblock(par) == 0)
2113 refs = ncp->nc_refs;
2114 ncp->nc_flag |= NCF_DEFEREDZAP;
2115 ++numdefered; /* MP race ok */
2116 if (atomic_cmpset_int(&ncp->nc_refs,
2128 spin_lock(&ncp->nc_head->spin);
2132 * If someone other then us has a ref or we have children
2133 * we cannot zap the entry. The 1->0 transition and any
2134 * further list operation is protected by the spinlocks
2135 * we have acquired but other transitions are not.
2138 refs = ncp->nc_refs;
2139 if (refs == 1 && TAILQ_EMPTY(&ncp->nc_list))
2141 if (atomic_cmpset_int(&ncp->nc_refs, refs, refs - 1)) {
2143 spin_unlock(&ncp->nc_head->spin);
2153 * We are the only ref and with the spinlocks held no further
2154 * refs can be acquired by others.
2156 * Remove us from the hash list and parent list. We have to
2157 * drop a ref on the parent's vp if the parent's list becomes
2162 struct nchash_head *nchpp = ncp->nc_head;
2164 KKASSERT(nchpp != NULL);
2165 LIST_REMOVE(ncp, nc_hash);
2166 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
2167 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
2168 dropvp = par->nc_vp;
2169 ncp->nc_head = NULL;
2170 ncp->nc_parent = NULL;
2171 spin_unlock(&nchpp->spin);
2174 KKASSERT(ncp->nc_head == NULL);
2178 * ncp should not have picked up any refs. Physically
2181 KKASSERT(ncp->nc_refs == 1);
2182 /* _cache_unlock(ncp) not required */
2183 ncp->nc_refs = -1; /* safety */
2185 kfree(ncp->nc_name, M_VFSCACHE);
2186 kfree(ncp, M_VFSCACHE);
2189 * Delayed drop (we had to release our spinlocks)
2191 * The refed parent (if not NULL) must be dropped. The
2192 * caller is responsible for looping.
2200 * Clean up dangling negative cache and defered-drop entries in the
2203 typedef enum { CHI_LOW, CHI_HIGH } cache_hs_t;
2205 static cache_hs_t neg_cache_hysteresis_state = CHI_LOW;
2206 static cache_hs_t pos_cache_hysteresis_state = CHI_LOW;
2209 cache_hysteresis(void)
2214 * Don't cache too many negative hits. We use hysteresis to reduce
2215 * the impact on the critical path.
2217 switch(neg_cache_hysteresis_state) {
2219 if (numneg > MINNEG && numneg * ncnegfactor > numcache) {
2220 _cache_cleanneg(10);
2221 neg_cache_hysteresis_state = CHI_HIGH;
2225 if (numneg > MINNEG * 9 / 10 &&
2226 numneg * ncnegfactor * 9 / 10 > numcache
2228 _cache_cleanneg(10);
2230 neg_cache_hysteresis_state = CHI_LOW;
2236 * Don't cache too many positive hits. We use hysteresis to reduce
2237 * the impact on the critical path.
2239 * Excessive positive hits can accumulate due to large numbers of
2240 * hardlinks (the vnode cache will not prevent hl ncps from growing
2243 if ((poslimit = ncposlimit) == 0)
2244 poslimit = desiredvnodes * 2;
2246 switch(pos_cache_hysteresis_state) {
2248 if (numcache > poslimit && numcache > MINPOS) {
2249 _cache_cleanpos(10);
2250 pos_cache_hysteresis_state = CHI_HIGH;
2254 if (numcache > poslimit * 5 / 6 && numcache > MINPOS) {
2255 _cache_cleanpos(10);
2257 pos_cache_hysteresis_state = CHI_LOW;
2263 * Clean out dangling defered-zap ncps which could not
2264 * be cleanly dropped if too many build up. Note
2265 * that numdefered is not an exact number as such ncps
2266 * can be reused and the counter is not handled in a MP
2267 * safe manner by design.
2269 if (numdefered * ncnegfactor > numcache) {
2270 _cache_cleandefered();
2275 * NEW NAMECACHE LOOKUP API
2277 * Lookup an entry in the namecache. The passed par_nch must be referenced
2278 * and unlocked. A referenced and locked nchandle with a non-NULL nch.ncp
2279 * is ALWAYS returned, eve if the supplied component is illegal.
2281 * The resulting namecache entry should be returned to the system with
2282 * cache_put() or cache_unlock() + cache_drop().
2284 * namecache locks are recursive but care must be taken to avoid lock order
2285 * reversals (hence why the passed par_nch must be unlocked). Locking
2286 * rules are to order for parent traversals, not for child traversals.
2288 * Nobody else will be able to manipulate the associated namespace (e.g.
2289 * create, delete, rename, rename-target) until the caller unlocks the
2292 * The returned entry will be in one of three states: positive hit (non-null
2293 * vnode), negative hit (null vnode), or unresolved (NCF_UNRESOLVED is set).
2294 * Unresolved entries must be resolved through the filesystem to associate the
2295 * vnode and/or determine whether a positive or negative hit has occured.
2297 * It is not necessary to lock a directory in order to lock namespace under
2298 * that directory. In fact, it is explicitly not allowed to do that. A
2299 * directory is typically only locked when being created, renamed, or
2302 * The directory (par) may be unresolved, in which case any returned child
2303 * will likely also be marked unresolved. Likely but not guarenteed. Since
2304 * the filesystem lookup requires a resolved directory vnode the caller is
2305 * responsible for resolving the namecache chain top-down. This API
2306 * specifically allows whole chains to be created in an unresolved state.
2309 cache_nlookup(struct nchandle *par_nch, struct nlcomponent *nlc)
2311 struct nchandle nch;
2312 struct namecache *ncp;
2313 struct namecache *new_ncp;
2314 struct nchash_head *nchpp;
2322 mp = par_nch->mount;
2326 * This is a good time to call it, no ncp's are locked by
2332 * Try to locate an existing entry
2334 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
2335 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
2337 nchpp = NCHHASH(hash);
2339 spin_lock(&nchpp->spin);
2340 LIST_FOREACH(ncp, &nchpp->list, nc_hash) {
2344 * Break out if we find a matching entry. Note that
2345 * UNRESOLVED entries may match, but DESTROYED entries
2348 if (ncp->nc_parent == par_nch->ncp &&
2349 ncp->nc_nlen == nlc->nlc_namelen &&
2350 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
2351 (ncp->nc_flag & NCF_DESTROYED) == 0
2354 spin_unlock(&nchpp->spin);
2356 _cache_unlock(par_nch->ncp);
2359 if (_cache_lock_special(ncp) == 0) {
2360 _cache_auto_unresolve(mp, ncp);
2362 _cache_free(new_ncp);
2373 * We failed to locate an entry, create a new entry and add it to
2374 * the cache. The parent ncp must also be locked so we
2377 * We have to relookup after possibly blocking in kmalloc or
2378 * when locking par_nch.
2380 * NOTE: nlc_namelen can be 0 and nlc_nameptr NULL as a special
2381 * mount case, in which case nc_name will be NULL.
2383 if (new_ncp == NULL) {
2384 spin_unlock(&nchpp->spin);
2385 new_ncp = cache_alloc(nlc->nlc_namelen);
2386 if (nlc->nlc_namelen) {
2387 bcopy(nlc->nlc_nameptr, new_ncp->nc_name,
2389 new_ncp->nc_name[nlc->nlc_namelen] = 0;
2393 if (par_locked == 0) {
2394 spin_unlock(&nchpp->spin);
2395 _cache_lock(par_nch->ncp);
2401 * WARNING! We still hold the spinlock. We have to set the hash
2402 * table entry atomically.
2405 _cache_link_parent(ncp, par_nch->ncp, nchpp);
2406 spin_unlock(&nchpp->spin);
2407 _cache_unlock(par_nch->ncp);
2408 /* par_locked = 0 - not used */
2411 * stats and namecache size management
2413 if (ncp->nc_flag & NCF_UNRESOLVED)
2414 ++gd->gd_nchstats->ncs_miss;
2415 else if (ncp->nc_vp)
2416 ++gd->gd_nchstats->ncs_goodhits;
2418 ++gd->gd_nchstats->ncs_neghits;
2421 atomic_add_int(&nch.mount->mnt_refs, 1);
2426 * This is a non-blocking verison of cache_nlookup() used by
2427 * nfs_readdirplusrpc_uio(). It can fail for any reason and
2428 * will return nch.ncp == NULL in that case.
2431 cache_nlookup_nonblock(struct nchandle *par_nch, struct nlcomponent *nlc)
2433 struct nchandle nch;
2434 struct namecache *ncp;
2435 struct namecache *new_ncp;
2436 struct nchash_head *nchpp;
2444 mp = par_nch->mount;
2448 * Try to locate an existing entry
2450 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
2451 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
2453 nchpp = NCHHASH(hash);
2455 spin_lock(&nchpp->spin);
2456 LIST_FOREACH(ncp, &nchpp->list, nc_hash) {
2460 * Break out if we find a matching entry. Note that
2461 * UNRESOLVED entries may match, but DESTROYED entries
2464 if (ncp->nc_parent == par_nch->ncp &&
2465 ncp->nc_nlen == nlc->nlc_namelen &&
2466 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
2467 (ncp->nc_flag & NCF_DESTROYED) == 0
2470 spin_unlock(&nchpp->spin);
2472 _cache_unlock(par_nch->ncp);
2475 if (_cache_lock_special(ncp) == 0) {
2476 _cache_auto_unresolve(mp, ncp);
2478 _cache_free(new_ncp);
2489 * We failed to locate an entry, create a new entry and add it to
2490 * the cache. The parent ncp must also be locked so we
2493 * We have to relookup after possibly blocking in kmalloc or
2494 * when locking par_nch.
2496 * NOTE: nlc_namelen can be 0 and nlc_nameptr NULL as a special
2497 * mount case, in which case nc_name will be NULL.
2499 if (new_ncp == NULL) {
2500 spin_unlock(&nchpp->spin);
2501 new_ncp = cache_alloc(nlc->nlc_namelen);
2502 if (nlc->nlc_namelen) {
2503 bcopy(nlc->nlc_nameptr, new_ncp->nc_name,
2505 new_ncp->nc_name[nlc->nlc_namelen] = 0;
2509 if (par_locked == 0) {
2510 spin_unlock(&nchpp->spin);
2511 if (_cache_lock_nonblock(par_nch->ncp) == 0) {
2519 * WARNING! We still hold the spinlock. We have to set the hash
2520 * table entry atomically.
2523 _cache_link_parent(ncp, par_nch->ncp, nchpp);
2524 spin_unlock(&nchpp->spin);
2525 _cache_unlock(par_nch->ncp);
2526 /* par_locked = 0 - not used */
2529 * stats and namecache size management
2531 if (ncp->nc_flag & NCF_UNRESOLVED)
2532 ++gd->gd_nchstats->ncs_miss;
2533 else if (ncp->nc_vp)
2534 ++gd->gd_nchstats->ncs_goodhits;
2536 ++gd->gd_nchstats->ncs_neghits;
2539 atomic_add_int(&nch.mount->mnt_refs, 1);
2543 _cache_free(new_ncp);
2552 * The namecache entry is marked as being used as a mount point.
2553 * Locate the mount if it is visible to the caller. The DragonFly
2554 * mount system allows arbitrary loops in the topology and disentangles
2555 * those loops by matching against (mp, ncp) rather than just (ncp).
2556 * This means any given ncp can dive any number of mounts, depending
2557 * on the relative mount (e.g. nullfs) the caller is at in the topology.
2559 * We use a very simple frontend cache to reduce SMP conflicts,
2560 * which we have to do because the mountlist scan needs an exclusive
2561 * lock around its ripout info list. Not to mention that there might
2562 * be a lot of mounts.
2564 struct findmount_info {
2565 struct mount *result;
2566 struct mount *nch_mount;
2567 struct namecache *nch_ncp;
2571 struct ncmount_cache *
2572 ncmount_cache_lookup(struct mount *mp, struct namecache *ncp)
2576 hash = ((int)(intptr_t)mp / sizeof(*mp)) ^
2577 ((int)(intptr_t)ncp / sizeof(*ncp));
2578 hash = (hash & 0x7FFFFFFF) % NCMOUNT_NUMCACHE;
2579 return (&ncmount_cache[hash]);
2584 cache_findmount_callback(struct mount *mp, void *data)
2586 struct findmount_info *info = data;
2589 * Check the mount's mounted-on point against the passed nch.
2591 if (mp->mnt_ncmounton.mount == info->nch_mount &&
2592 mp->mnt_ncmounton.ncp == info->nch_ncp
2595 atomic_add_int(&mp->mnt_refs, 1);
2602 cache_findmount(struct nchandle *nch)
2604 struct findmount_info info;
2605 struct ncmount_cache *ncc;
2611 if (ncmount_cache_enable == 0) {
2615 ncc = ncmount_cache_lookup(nch->mount, nch->ncp);
2616 if (ncc->ncp == nch->ncp) {
2617 spin_lock_shared(&ncc->spin);
2618 if (ncc->isneg == 0 &&
2619 ncc->ncp == nch->ncp && (mp = ncc->mp) != NULL) {
2620 if (mp->mnt_ncmounton.mount == nch->mount &&
2621 mp->mnt_ncmounton.ncp == nch->ncp) {
2623 * Cache hit (positive)
2625 atomic_add_int(&mp->mnt_refs, 1);
2626 spin_unlock_shared(&ncc->spin);
2627 ++ncmount_cache_hit;
2630 /* else cache miss */
2633 ncc->ncp == nch->ncp && ncc->mp == nch->mount) {
2635 * Cache hit (negative)
2637 spin_unlock_shared(&ncc->spin);
2638 ++ncmount_cache_hit;
2641 spin_unlock_shared(&ncc->spin);
2649 info.nch_mount = nch->mount;
2650 info.nch_ncp = nch->ncp;
2651 mountlist_scan(cache_findmount_callback, &info,
2652 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
2657 * Negative lookups: We cache the originating {ncp,mp}. (mp) is
2658 * only used for pointer comparisons and is not
2659 * referenced (otherwise there would be dangling
2662 * Positive lookups: We cache the originating {ncp} and the target
2663 * (mp). (mp) is referenced.
2665 * Indeterminant: If the match is undergoing an unmount we do
2666 * not cache it to avoid racing cache_unmounting(),
2667 * but still return the match.
2670 spin_lock(&ncc->spin);
2671 if (info.result == NULL) {
2672 if (ncc->isneg == 0 && ncc->mp)
2673 atomic_add_int(&ncc->mp->mnt_refs, -1);
2674 ncc->ncp = nch->ncp;
2675 ncc->mp = nch->mount;
2677 spin_unlock(&ncc->spin);
2678 ++ncmount_cache_overwrite;
2679 } else if ((info.result->mnt_kern_flag & MNTK_UNMOUNT) == 0) {
2680 if (ncc->isneg == 0 && ncc->mp)
2681 atomic_add_int(&ncc->mp->mnt_refs, -1);
2682 atomic_add_int(&info.result->mnt_refs, 1);
2683 ncc->ncp = nch->ncp;
2684 ncc->mp = info.result;
2686 spin_unlock(&ncc->spin);
2687 ++ncmount_cache_overwrite;
2689 spin_unlock(&ncc->spin);
2691 ++ncmount_cache_miss;
2693 return(info.result);
2697 cache_dropmount(struct mount *mp)
2699 atomic_add_int(&mp->mnt_refs, -1);
2703 cache_ismounting(struct mount *mp)
2705 struct nchandle *nch = &mp->mnt_ncmounton;
2706 struct ncmount_cache *ncc;
2708 ncc = ncmount_cache_lookup(nch->mount, nch->ncp);
2710 ncc->ncp == nch->ncp && ncc->mp == nch->mount) {
2711 spin_lock(&ncc->spin);
2713 ncc->ncp == nch->ncp && ncc->mp == nch->mount) {
2717 spin_unlock(&ncc->spin);
2722 cache_unmounting(struct mount *mp)
2724 struct nchandle *nch = &mp->mnt_ncmounton;
2725 struct ncmount_cache *ncc;
2727 ncc = ncmount_cache_lookup(nch->mount, nch->ncp);
2728 if (ncc->isneg == 0 &&
2729 ncc->ncp == nch->ncp && ncc->mp == mp) {
2730 spin_lock(&ncc->spin);
2731 if (ncc->isneg == 0 &&
2732 ncc->ncp == nch->ncp && ncc->mp == mp) {
2733 atomic_add_int(&mp->mnt_refs, -1);
2737 spin_unlock(&ncc->spin);
2742 * Resolve an unresolved namecache entry, generally by looking it up.
2743 * The passed ncp must be locked and refd.
2745 * Theoretically since a vnode cannot be recycled while held, and since
2746 * the nc_parent chain holds its vnode as long as children exist, the
2747 * direct parent of the cache entry we are trying to resolve should
2748 * have a valid vnode. If not then generate an error that we can
2749 * determine is related to a resolver bug.
2751 * However, if a vnode was in the middle of a recyclement when the NCP
2752 * got locked, ncp->nc_vp might point to a vnode that is about to become
2753 * invalid. cache_resolve() handles this case by unresolving the entry
2754 * and then re-resolving it.
2756 * Note that successful resolution does not necessarily return an error
2757 * code of 0. If the ncp resolves to a negative cache hit then ENOENT
2763 cache_resolve(struct nchandle *nch, struct ucred *cred)
2765 struct namecache *par_tmp;
2766 struct namecache *par;
2767 struct namecache *ncp;
2768 struct nchandle nctmp;
2777 * If the ncp is already resolved we have nothing to do. However,
2778 * we do want to guarentee that a usable vnode is returned when
2779 * a vnode is present, so make sure it hasn't been reclaimed.
2781 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
2782 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
2783 _cache_setunresolved(ncp);
2784 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
2785 return (ncp->nc_error);
2789 * If the ncp was destroyed it will never resolve again. This
2790 * can basically only happen when someone is chdir'd into an
2791 * empty directory which is then rmdir'd. We want to catch this
2792 * here and not dive the VFS because the VFS might actually
2793 * have a way to re-resolve the disconnected ncp, which will
2794 * result in inconsistencies in the cdir/nch for proc->p_fd.
2796 if (ncp->nc_flag & NCF_DESTROYED) {
2797 kprintf("Warning: cache_resolve: ncp '%s' was unlinked\n",
2803 * Mount points need special handling because the parent does not
2804 * belong to the same filesystem as the ncp.
2806 if (ncp == mp->mnt_ncmountpt.ncp)
2807 return (cache_resolve_mp(mp));
2810 * We expect an unbroken chain of ncps to at least the mount point,
2811 * and even all the way to root (but this code doesn't have to go
2812 * past the mount point).
2814 if (ncp->nc_parent == NULL) {
2815 kprintf("EXDEV case 1 %p %*.*s\n", ncp,
2816 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
2817 ncp->nc_error = EXDEV;
2818 return(ncp->nc_error);
2822 * The vp's of the parent directories in the chain are held via vhold()
2823 * due to the existance of the child, and should not disappear.
2824 * However, there are cases where they can disappear:
2826 * - due to filesystem I/O errors.
2827 * - due to NFS being stupid about tracking the namespace and
2828 * destroys the namespace for entire directories quite often.
2829 * - due to forced unmounts.
2830 * - due to an rmdir (parent will be marked DESTROYED)
2832 * When this occurs we have to track the chain backwards and resolve
2833 * it, looping until the resolver catches up to the current node. We
2834 * could recurse here but we might run ourselves out of kernel stack
2835 * so we do it in a more painful manner. This situation really should
2836 * not occur all that often, or if it does not have to go back too
2837 * many nodes to resolve the ncp.
2839 while ((dvp = cache_dvpref(ncp)) == NULL) {
2841 * This case can occur if a process is CD'd into a
2842 * directory which is then rmdir'd. If the parent is marked
2843 * destroyed there is no point trying to resolve it.
2845 if (ncp->nc_parent->nc_flag & NCF_DESTROYED)
2847 par = ncp->nc_parent;
2850 while ((par_tmp = par->nc_parent) != NULL &&
2851 par_tmp->nc_vp == NULL) {
2852 _cache_hold(par_tmp);
2853 _cache_lock(par_tmp);
2857 if (par->nc_parent == NULL) {
2858 kprintf("EXDEV case 2 %*.*s\n",
2859 par->nc_nlen, par->nc_nlen, par->nc_name);
2863 kprintf("[diagnostic] cache_resolve: had to recurse on %*.*s\n",
2864 par->nc_nlen, par->nc_nlen, par->nc_name);
2866 * The parent is not set in stone, ref and lock it to prevent
2867 * it from disappearing. Also note that due to renames it
2868 * is possible for our ncp to move and for par to no longer
2869 * be one of its parents. We resolve it anyway, the loop
2870 * will handle any moves.
2872 _cache_get(par); /* additional hold/lock */
2873 _cache_put(par); /* from earlier hold/lock */
2874 if (par == nch->mount->mnt_ncmountpt.ncp) {
2875 cache_resolve_mp(nch->mount);
2876 } else if ((dvp = cache_dvpref(par)) == NULL) {
2877 kprintf("[diagnostic] cache_resolve: raced on %*.*s\n", par->nc_nlen, par->nc_nlen, par->nc_name);
2881 if (par->nc_flag & NCF_UNRESOLVED) {
2884 par->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
2888 if ((error = par->nc_error) != 0) {
2889 if (par->nc_error != EAGAIN) {
2890 kprintf("EXDEV case 3 %*.*s error %d\n",
2891 par->nc_nlen, par->nc_nlen, par->nc_name,
2896 kprintf("[diagnostic] cache_resolve: EAGAIN par %p %*.*s\n",
2897 par, par->nc_nlen, par->nc_nlen, par->nc_name);
2904 * Call VOP_NRESOLVE() to get the vp, then scan for any disconnected
2905 * ncp's and reattach them. If this occurs the original ncp is marked
2906 * EAGAIN to force a relookup.
2908 * NOTE: in order to call VOP_NRESOLVE(), the parent of the passed
2909 * ncp must already be resolved.
2914 ncp->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
2917 ncp->nc_error = EPERM;
2919 if (ncp->nc_error == EAGAIN) {
2920 kprintf("[diagnostic] cache_resolve: EAGAIN ncp %p %*.*s\n",
2921 ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
2924 return(ncp->nc_error);
2928 * Resolve the ncp associated with a mount point. Such ncp's almost always
2929 * remain resolved and this routine is rarely called. NFS MPs tends to force
2930 * re-resolution more often due to its mac-truck-smash-the-namecache
2931 * method of tracking namespace changes.
2933 * The semantics for this call is that the passed ncp must be locked on
2934 * entry and will be locked on return. However, if we actually have to
2935 * resolve the mount point we temporarily unlock the entry in order to
2936 * avoid race-to-root deadlocks due to e.g. dead NFS mounts. Because of
2937 * the unlock we have to recheck the flags after we relock.
2940 cache_resolve_mp(struct mount *mp)
2942 struct namecache *ncp = mp->mnt_ncmountpt.ncp;
2946 KKASSERT(mp != NULL);
2949 * If the ncp is already resolved we have nothing to do. However,
2950 * we do want to guarentee that a usable vnode is returned when
2951 * a vnode is present, so make sure it hasn't been reclaimed.
2953 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
2954 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
2955 _cache_setunresolved(ncp);
2958 if (ncp->nc_flag & NCF_UNRESOLVED) {
2960 while (vfs_busy(mp, 0))
2962 error = VFS_ROOT(mp, &vp);
2966 * recheck the ncp state after relocking.
2968 if (ncp->nc_flag & NCF_UNRESOLVED) {
2969 ncp->nc_error = error;
2971 _cache_setvp(mp, ncp, vp);
2974 kprintf("[diagnostic] cache_resolve_mp: failed"
2975 " to resolve mount %p err=%d ncp=%p\n",
2977 _cache_setvp(mp, ncp, NULL);
2979 } else if (error == 0) {
2984 return(ncp->nc_error);
2988 * Clean out negative cache entries when too many have accumulated.
2993 _cache_cleanneg(int count)
2995 struct namecache *ncp;
2998 * Attempt to clean out the specified number of negative cache
3003 ncp = TAILQ_FIRST(&ncneglist);
3005 spin_unlock(&ncspin);
3008 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
3009 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
3011 spin_unlock(&ncspin);
3014 * This can race, so we must re-check that the ncp
3015 * is on the ncneglist after successfully locking it.
3017 if (_cache_lock_special(ncp) == 0) {
3018 if (ncp->nc_vp == NULL &&
3019 (ncp->nc_flag & NCF_UNRESOLVED) == 0) {
3020 ncp = cache_zap(ncp, 1);
3024 kprintf("cache_cleanneg: race avoided\n");
3035 * Clean out positive cache entries when too many have accumulated.
3040 _cache_cleanpos(int count)
3042 static volatile int rover;
3043 struct nchash_head *nchpp;
3044 struct namecache *ncp;
3048 * Attempt to clean out the specified number of negative cache
3052 rover_copy = ++rover; /* MPSAFEENOUGH */
3054 nchpp = NCHHASH(rover_copy);
3056 spin_lock(&nchpp->spin);
3057 ncp = LIST_FIRST(&nchpp->list);
3060 spin_unlock(&nchpp->spin);
3063 if (_cache_lock_special(ncp) == 0) {
3064 ncp = cache_zap(ncp, 1);
3076 * This is a kitchen sink function to clean out ncps which we
3077 * tried to zap from cache_drop() but failed because we were
3078 * unable to acquire the parent lock.
3080 * Such entries can also be removed via cache_inval_vp(), such
3081 * as when unmounting.
3086 _cache_cleandefered(void)
3088 struct nchash_head *nchpp;
3089 struct namecache *ncp;
3090 struct namecache dummy;
3094 bzero(&dummy, sizeof(dummy));
3095 dummy.nc_flag = NCF_DESTROYED;
3097 for (i = 0; i <= nchash; ++i) {
3098 nchpp = &nchashtbl[i];
3100 spin_lock(&nchpp->spin);
3101 LIST_INSERT_HEAD(&nchpp->list, &dummy, nc_hash);
3103 while ((ncp = LIST_NEXT(ncp, nc_hash)) != NULL) {
3104 if ((ncp->nc_flag & NCF_DEFEREDZAP) == 0)
3106 LIST_REMOVE(&dummy, nc_hash);
3107 LIST_INSERT_AFTER(ncp, &dummy, nc_hash);
3109 spin_unlock(&nchpp->spin);
3110 if (_cache_lock_nonblock(ncp) == 0) {
3111 ncp->nc_flag &= ~NCF_DEFEREDZAP;
3115 spin_lock(&nchpp->spin);
3118 LIST_REMOVE(&dummy, nc_hash);
3119 spin_unlock(&nchpp->spin);
3124 * Name cache initialization, from vfsinit() when we are booting
3132 /* initialise per-cpu namecache effectiveness statistics. */
3133 for (i = 0; i < ncpus; ++i) {
3134 gd = globaldata_find(i);
3135 gd->gd_nchstats = &nchstats[i];
3137 TAILQ_INIT(&ncneglist);
3139 nchashtbl = hashinit_ext(desiredvnodes / 2,
3140 sizeof(struct nchash_head),
3141 M_VFSCACHE, &nchash);
3142 for (i = 0; i <= (int)nchash; ++i) {
3143 LIST_INIT(&nchashtbl[i].list);
3144 spin_init(&nchashtbl[i].spin);
3146 for (i = 0; i < NCMOUNT_NUMCACHE; ++i)
3147 spin_init(&ncmount_cache[i].spin);
3148 nclockwarn = 5 * hz;
3152 * Called from start_init() to bootstrap the root filesystem. Returns
3153 * a referenced, unlocked namecache record.
3156 cache_allocroot(struct nchandle *nch, struct mount *mp, struct vnode *vp)
3158 nch->ncp = cache_alloc(0);
3160 atomic_add_int(&mp->mnt_refs, 1);
3162 _cache_setvp(nch->mount, nch->ncp, vp);
3166 * vfs_cache_setroot()
3168 * Create an association between the root of our namecache and
3169 * the root vnode. This routine may be called several times during
3172 * If the caller intends to save the returned namecache pointer somewhere
3173 * it must cache_hold() it.
3176 vfs_cache_setroot(struct vnode *nvp, struct nchandle *nch)
3179 struct nchandle onch;
3187 cache_zero(&rootnch);
3195 * XXX OLD API COMPAT FUNCTION. This really messes up the new namecache
3196 * topology and is being removed as quickly as possible. The new VOP_N*()
3197 * API calls are required to make specific adjustments using the supplied
3198 * ncp pointers rather then just bogusly purging random vnodes.
3200 * Invalidate all namecache entries to a particular vnode as well as
3201 * any direct children of that vnode in the namecache. This is a
3202 * 'catch all' purge used by filesystems that do not know any better.
3204 * Note that the linkage between the vnode and its namecache entries will
3205 * be removed, but the namecache entries themselves might stay put due to
3206 * active references from elsewhere in the system or due to the existance of
3207 * the children. The namecache topology is left intact even if we do not
3208 * know what the vnode association is. Such entries will be marked
3212 cache_purge(struct vnode *vp)
3214 cache_inval_vp(vp, CINV_DESTROY | CINV_CHILDREN);
3218 * Flush all entries referencing a particular filesystem.
3220 * Since we need to check it anyway, we will flush all the invalid
3221 * entries at the same time.
3226 cache_purgevfs(struct mount *mp)
3228 struct nchash_head *nchpp;
3229 struct namecache *ncp, *nnp;
3232 * Scan hash tables for applicable entries.
3234 for (nchpp = &nchashtbl[nchash]; nchpp >= nchashtbl; nchpp--) {
3235 spin_lock_wr(&nchpp->spin); XXX
3236 ncp = LIST_FIRST(&nchpp->list);
3240 nnp = LIST_NEXT(ncp, nc_hash);
3243 if (ncp->nc_mount == mp) {
3245 ncp = cache_zap(ncp, 0);
3253 spin_unlock_wr(&nchpp->spin); XXX
3259 static int disablecwd;
3260 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0,
3263 static u_long numcwdcalls;
3264 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdcalls, CTLFLAG_RD, &numcwdcalls, 0,
3265 "Number of current directory resolution calls");
3266 static u_long numcwdfailnf;
3267 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfailnf, CTLFLAG_RD, &numcwdfailnf, 0,
3268 "Number of current directory failures due to lack of file");
3269 static u_long numcwdfailsz;
3270 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfailsz, CTLFLAG_RD, &numcwdfailsz, 0,
3271 "Number of current directory failures due to large result");
3272 static u_long numcwdfound;
3273 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfound, CTLFLAG_RD, &numcwdfound, 0,
3274 "Number of current directory resolution successes");
3280 sys___getcwd(struct __getcwd_args *uap)
3290 buflen = uap->buflen;
3293 if (buflen > MAXPATHLEN)
3294 buflen = MAXPATHLEN;
3296 buf = kmalloc(buflen, M_TEMP, M_WAITOK);
3297 bp = kern_getcwd(buf, buflen, &error);
3299 error = copyout(bp, uap->buf, strlen(bp) + 1);
3305 kern_getcwd(char *buf, size_t buflen, int *error)
3307 struct proc *p = curproc;
3309 int i, slash_prefixed;
3310 struct filedesc *fdp;
3311 struct nchandle nch;
3312 struct namecache *ncp;
3321 nch = fdp->fd_ncdir;
3326 while (ncp && (ncp != fdp->fd_nrdir.ncp ||
3327 nch.mount != fdp->fd_nrdir.mount)
3330 * While traversing upwards if we encounter the root
3331 * of the current mount we have to skip to the mount point
3332 * in the underlying filesystem.
3334 if (ncp == nch.mount->mnt_ncmountpt.ncp) {
3335 nch = nch.mount->mnt_ncmounton;
3344 * Prepend the path segment
3346 for (i = ncp->nc_nlen - 1; i >= 0; i--) {
3353 *--bp = ncp->nc_name[i];
3365 * Go up a directory. This isn't a mount point so we don't
3366 * have to check again.
3368 while ((nch.ncp = ncp->nc_parent) != NULL) {
3370 if (nch.ncp != ncp->nc_parent) {
3374 _cache_hold(nch.ncp);
3387 if (!slash_prefixed) {
3405 * Thus begins the fullpath magic.
3407 * The passed nchp is referenced but not locked.
3409 static int disablefullpath;
3410 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW,
3411 &disablefullpath, 0,
3412 "Disable fullpath lookups");
3414 static u_int numfullpathcalls;
3415 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathcalls, CTLFLAG_RD,
3416 &numfullpathcalls, 0,
3417 "Number of full path resolutions in progress");
3418 static u_int numfullpathfailnf;
3419 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathfailnf, CTLFLAG_RD,
3420 &numfullpathfailnf, 0,
3421 "Number of full path resolution failures due to lack of file");
3422 static u_int numfullpathfailsz;
3423 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathfailsz, CTLFLAG_RD,
3424 &numfullpathfailsz, 0,
3425 "Number of full path resolution failures due to insufficient memory");
3426 static u_int numfullpathfound;
3427 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathfound, CTLFLAG_RD,
3428 &numfullpathfound, 0,
3429 "Number of full path resolution successes");
3432 cache_fullpath(struct proc *p, struct nchandle *nchp, struct nchandle *nchbase,
3433 char **retbuf, char **freebuf, int guess)
3435 struct nchandle fd_nrdir;
3436 struct nchandle nch;
3437 struct namecache *ncp;
3438 struct mount *mp, *new_mp;
3444 atomic_add_int(&numfullpathcalls, -1);
3449 buf = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
3450 bp = buf + MAXPATHLEN - 1;
3453 fd_nrdir = *nchbase;
3455 fd_nrdir = p->p_fd->fd_nrdir;
3465 while (ncp && (ncp != fd_nrdir.ncp || mp != fd_nrdir.mount)) {
3469 * If we are asked to guess the upwards path, we do so whenever
3470 * we encounter an ncp marked as a mountpoint. We try to find
3471 * the actual mountpoint by finding the mountpoint with this
3474 if (guess && (ncp->nc_flag & NCF_ISMOUNTPT)) {
3475 new_mp = mount_get_by_nc(ncp);
3478 * While traversing upwards if we encounter the root
3479 * of the current mount we have to skip to the mount point.
3481 if (ncp == mp->mnt_ncmountpt.ncp) {
3485 nch = new_mp->mnt_ncmounton;
3495 * Prepend the path segment
3497 for (i = ncp->nc_nlen - 1; i >= 0; i--) {
3499 numfullpathfailsz++;
3504 *--bp = ncp->nc_name[i];
3507 numfullpathfailsz++;
3516 * Go up a directory. This isn't a mount point so we don't
3517 * have to check again.
3519 * We can only safely access nc_parent with ncp held locked.
3521 while ((nch.ncp = ncp->nc_parent) != NULL) {
3523 if (nch.ncp != ncp->nc_parent) {
3527 _cache_hold(nch.ncp);
3535 numfullpathfailnf++;
3541 if (!slash_prefixed) {
3543 numfullpathfailsz++;
3561 vn_fullpath(struct proc *p, struct vnode *vn, char **retbuf, char **freebuf,
3564 struct namecache *ncp;
3565 struct nchandle nch;
3569 atomic_add_int(&numfullpathcalls, 1);
3570 if (disablefullpath)
3576 /* vn is NULL, client wants us to use p->p_textvp */
3578 if ((vn = p->p_textvp) == NULL)
3581 spin_lock(&vn->v_spin);
3582 TAILQ_FOREACH(ncp, &vn->v_namecache, nc_vnode) {
3587 spin_unlock(&vn->v_spin);
3591 spin_unlock(&vn->v_spin);
3593 atomic_add_int(&numfullpathcalls, -1);
3595 nch.mount = vn->v_mount;
3596 error = cache_fullpath(p, &nch, NULL, retbuf, freebuf, guess);