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. Neither the name of the University nor the names of its contributors
49 * may be used to endorse or promote products derived from this software
50 * without specific prior written permission.
52 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65 #include <sys/param.h>
66 #include <sys/systm.h>
67 #include <sys/kernel.h>
68 #include <sys/sysctl.h>
69 #include <sys/mount.h>
70 #include <sys/vnode.h>
71 #include <sys/malloc.h>
72 #include <sys/sysproto.h>
73 #include <sys/spinlock.h>
75 #include <sys/namei.h>
76 #include <sys/nlookup.h>
77 #include <sys/filedesc.h>
78 #include <sys/fnv_hash.h>
79 #include <sys/globaldata.h>
80 #include <sys/kern_syscall.h>
81 #include <sys/dirent.h>
84 #include <sys/sysref2.h>
85 #include <sys/spinlock2.h>
87 #define MAX_RECURSION_DEPTH 64
90 * Random lookups in the cache are accomplished with a hash table using
91 * a hash key of (nc_src_vp, name). Each hash chain has its own spin lock.
93 * Negative entries may exist and correspond to resolved namecache
94 * structures where nc_vp is NULL. In a negative entry, NCF_WHITEOUT
95 * will be set if the entry corresponds to a whited-out directory entry
96 * (verses simply not finding the entry at all). ncneg.list is locked
97 * with a global spinlock (ncneg.spin).
101 * (1) A ncp must be referenced before it can be locked.
103 * (2) A ncp must be locked in order to modify it.
105 * (3) ncp locks are always ordered child -> parent. That may seem
106 * backwards but forward scans use the hash table and thus can hold
107 * the parent unlocked when traversing downward.
109 * This allows insert/rename/delete/dot-dot and other operations
110 * to use ncp->nc_parent links.
112 * This also prevents a locked up e.g. NFS node from creating a
113 * chain reaction all the way back to the root vnode / namecache.
115 * (4) parent linkages require both the parent and child to be locked.
119 * Structures associated with name cacheing.
121 #define NCHHASH(hash) (&nchashtbl[(hash) & nchash])
124 #define NCMOUNT_NUMCACHE 1009 /* prime number */
126 MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
128 LIST_HEAD(nchash_list, namecache);
131 * Don't cachealign, but at least pad to 32 bytes so entries
132 * don't cross a cache line.
135 struct nchash_list list; /* 16 bytes */
136 struct spinlock spin; /* 8 bytes */
137 long pad01; /* 8 bytes */
140 struct ncmount_cache {
141 struct spinlock spin;
142 struct namecache *ncp;
144 int isneg; /* if != 0 mp is originator and not target */
148 struct spinlock spin;
149 struct namecache_list list;
152 static struct nchash_head *nchashtbl;
153 static struct ncneg_cache ncneg;
154 static struct ncmount_cache ncmount_cache[NCMOUNT_NUMCACHE];
157 * ncvp_debug - debug cache_fromvp(). This is used by the NFS server
158 * to create the namecache infrastructure leading to a dangling vnode.
160 * 0 Only errors are reported
161 * 1 Successes are reported
162 * 2 Successes + the whole directory scan is reported
163 * 3 Force the directory scan code run as if the parent vnode did not
164 * have a namecache record, even if it does have one.
166 static int ncvp_debug;
167 SYSCTL_INT(_debug, OID_AUTO, ncvp_debug, CTLFLAG_RW, &ncvp_debug, 0,
168 "Namecache debug level (0-3)");
170 static u_long nchash; /* size of hash table */
171 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
172 "Size of namecache hash table");
174 static int ncnegflush = 10; /* burst for negative flush */
175 SYSCTL_INT(_debug, OID_AUTO, ncnegflush, CTLFLAG_RW, &ncnegflush, 0,
176 "Batch flush negative entries");
178 static int ncposflush = 10; /* burst for positive flush */
179 SYSCTL_INT(_debug, OID_AUTO, ncposflush, CTLFLAG_RW, &ncposflush, 0,
180 "Batch flush positive entries");
182 static int ncnegfactor = 16; /* ratio of negative entries */
183 SYSCTL_INT(_debug, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0,
184 "Ratio of namecache negative entries");
186 static int nclockwarn; /* warn on locked entries in ticks */
187 SYSCTL_INT(_debug, OID_AUTO, nclockwarn, CTLFLAG_RW, &nclockwarn, 0,
188 "Warn on locked namecache entries in ticks");
190 static int numdefered; /* number of cache entries allocated */
191 SYSCTL_INT(_debug, OID_AUTO, numdefered, CTLFLAG_RD, &numdefered, 0,
192 "Number of cache entries allocated");
194 static int ncposlimit; /* number of cache entries allocated */
195 SYSCTL_INT(_debug, OID_AUTO, ncposlimit, CTLFLAG_RW, &ncposlimit, 0,
196 "Number of cache entries allocated");
198 static int ncp_shared_lock_disable = 0;
199 SYSCTL_INT(_debug, OID_AUTO, ncp_shared_lock_disable, CTLFLAG_RW,
200 &ncp_shared_lock_disable, 0, "Disable shared namecache locks");
202 SYSCTL_INT(_debug, OID_AUTO, vnsize, CTLFLAG_RD, 0, sizeof(struct vnode),
203 "sizeof(struct vnode)");
204 SYSCTL_INT(_debug, OID_AUTO, ncsize, CTLFLAG_RD, 0, sizeof(struct namecache),
205 "sizeof(struct namecache)");
207 static int ncmount_cache_enable = 1;
208 SYSCTL_INT(_debug, OID_AUTO, ncmount_cache_enable, CTLFLAG_RW,
209 &ncmount_cache_enable, 0, "mount point cache");
211 static __inline void _cache_drop(struct namecache *ncp);
212 static int cache_resolve_mp(struct mount *mp);
213 static struct vnode *cache_dvpref(struct namecache *ncp);
214 static void _cache_lock(struct namecache *ncp);
215 static void _cache_setunresolved(struct namecache *ncp);
216 static void _cache_cleanneg(int count);
217 static void _cache_cleanpos(int count);
218 static void _cache_cleandefered(void);
219 static void _cache_unlink(struct namecache *ncp);
222 * The new name cache statistics
224 SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0, "Name cache statistics");
226 SYSCTL_INT(_vfs_cache, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0,
227 "Number of negative namecache entries");
229 SYSCTL_INT(_vfs_cache, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0,
230 "Number of namecaches entries");
232 struct nchstats nchstats[SMP_MAXCPU];
234 * Export VFS cache effectiveness statistics to user-land.
236 * The statistics are left for aggregation to user-land so
237 * neat things can be achieved, like observing per-CPU cache
241 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
243 struct globaldata *gd;
247 for (i = 0; i < ncpus; ++i) {
248 gd = globaldata_find(i);
249 if ((error = SYSCTL_OUT(req, (void *)&(*gd->gd_nchstats),
250 sizeof(struct nchstats))))
256 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE|CTLFLAG_RD,
257 0, 0, sysctl_nchstats, "S,nchstats", "VFS cache effectiveness statistics");
259 static struct namecache *cache_zap(struct namecache *ncp, int nonblock);
262 * Cache mount points and namecache records in order to avoid unnecessary
263 * atomic ops on mnt_refs and ncp->refs. This improves concurrent SMP
264 * performance and is particularly important on multi-socket systems to
265 * reduce cache-line ping-ponging.
267 * Try to keep the pcpu structure within one cache line (~64 bytes).
269 #define MNTCACHE_COUNT 5
272 struct mount *mntary[MNTCACHE_COUNT];
273 struct namecache *ncp1;
274 struct namecache *ncp2;
275 struct nchandle ncdir;
280 static struct mntcache pcpu_mntcache[MAXCPU];
284 _cache_mntref(struct mount *mp)
286 struct mntcache *cache = &pcpu_mntcache[mycpu->gd_cpuid];
289 for (i = 0; i < MNTCACHE_COUNT; ++i) {
290 if (cache->mntary[i] != mp)
292 if (atomic_cmpset_ptr((void *)&cache->mntary[i], mp, NULL))
295 atomic_add_int(&mp->mnt_refs, 1);
300 _cache_mntrel(struct mount *mp)
302 struct mntcache *cache = &pcpu_mntcache[mycpu->gd_cpuid];
305 for (i = 0; i < MNTCACHE_COUNT; ++i) {
306 if (cache->mntary[i] == NULL) {
307 mp = atomic_swap_ptr((void *)&cache->mntary[i], mp);
312 i = (int)((uint32_t)++cache->iter % (uint32_t)MNTCACHE_COUNT);
313 mp = atomic_swap_ptr((void *)&cache->mntary[i], mp);
315 atomic_add_int(&mp->mnt_refs, -1);
319 * Clears all cached mount points on all cpus. This routine should only
320 * be called when we are waiting for a mount to clear, e.g. so we can
324 cache_clearmntcache(void)
328 for (n = 0; n < ncpus; ++n) {
329 struct mntcache *cache = &pcpu_mntcache[n];
330 struct namecache *ncp;
334 for (i = 0; i < MNTCACHE_COUNT; ++i) {
335 if (cache->mntary[i]) {
336 mp = atomic_swap_ptr(
337 (void *)&cache->mntary[i], NULL);
339 atomic_add_int(&mp->mnt_refs, -1);
343 ncp = atomic_swap_ptr((void *)&cache->ncp1, NULL);
348 ncp = atomic_swap_ptr((void *)&cache->ncp2, NULL);
352 if (cache->ncdir.ncp) {
353 ncp = atomic_swap_ptr((void *)&cache->ncdir.ncp, NULL);
357 if (cache->ncdir.mount) {
358 mp = atomic_swap_ptr((void *)&cache->ncdir.mount, NULL);
360 atomic_add_int(&mp->mnt_refs, -1);
367 * Namespace locking. The caller must already hold a reference to the
368 * namecache structure in order to lock/unlock it. This function prevents
369 * the namespace from being created or destroyed by accessors other then
372 * Note that holding a locked namecache structure prevents other threads
373 * from making namespace changes (e.g. deleting or creating), prevents
374 * vnode association state changes by other threads, and prevents the
375 * namecache entry from being resolved or unresolved by other threads.
377 * An exclusive lock owner has full authority to associate/disassociate
378 * vnodes and resolve/unresolve the locked ncp.
380 * A shared lock owner only has authority to acquire the underlying vnode,
383 * The primary lock field is nc_lockstatus. nc_locktd is set after the
384 * fact (when locking) or cleared prior to unlocking.
386 * WARNING! Holding a locked ncp will prevent a vnode from being destroyed
387 * or recycled, but it does NOT help you if the vnode had already
388 * initiated a recyclement. If this is important, use cache_get()
389 * rather then cache_lock() (and deal with the differences in the
390 * way the refs counter is handled). Or, alternatively, make an
391 * unconditional call to cache_validate() or cache_resolve()
392 * after cache_lock() returns.
396 _cache_lock(struct namecache *ncp)
404 KKASSERT(ncp->nc_refs != 0);
410 count = ncp->nc_lockstatus;
413 if ((count & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 0) {
414 if (atomic_cmpset_int(&ncp->nc_lockstatus,
417 * The vp associated with a locked ncp must
418 * be held to prevent it from being recycled.
420 * WARNING! If VRECLAIMED is set the vnode
421 * could already be in the middle of a recycle.
422 * Callers must use cache_vref() or
423 * cache_vget() on the locked ncp to
424 * validate the vp or set the cache entry
427 * NOTE! vhold() is allowed if we hold a
428 * lock on the ncp (which we do).
438 if (ncp->nc_locktd == td) {
439 KKASSERT((count & NC_SHLOCK_FLAG) == 0);
440 if (atomic_cmpset_int(&ncp->nc_lockstatus,
447 tsleep_interlock(&ncp->nc_locktd, 0);
448 if (atomic_cmpset_int(&ncp->nc_lockstatus, count,
449 count | NC_EXLOCK_REQ) == 0) {
455 error = tsleep(&ncp->nc_locktd, PINTERLOCKED,
456 "clock", nclockwarn);
457 if (error == EWOULDBLOCK) {
460 kprintf("[diagnostic] cache_lock: "
461 "%s blocked on %p %08x",
462 td->td_comm, ncp, count);
463 kprintf(" \"%*.*s\"\n",
464 ncp->nc_nlen, ncp->nc_nlen,
471 kprintf("[diagnostic] cache_lock: %s unblocked %*.*s after "
474 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name,
475 (int)(ticks + (hz / 2) - begticks) / hz);
480 * The shared lock works similarly to the exclusive lock except
481 * nc_locktd is left NULL and we need an interlock (VHOLD) to
482 * prevent vhold() races, since the moment our cmpset_int succeeds
483 * another cpu can come in and get its own shared lock.
485 * A critical section is needed to prevent interruption during the
490 _cache_lock_shared(struct namecache *ncp)
495 u_int optreq = NC_EXLOCK_REQ;
497 KKASSERT(ncp->nc_refs != 0);
501 count = ncp->nc_lockstatus;
504 if ((count & ~NC_SHLOCK_REQ) == 0) {
506 if (atomic_cmpset_int(&ncp->nc_lockstatus,
508 (count + 1) | NC_SHLOCK_FLAG |
511 * The vp associated with a locked ncp must
512 * be held to prevent it from being recycled.
514 * WARNING! If VRECLAIMED is set the vnode
515 * could already be in the middle of a recycle.
516 * Callers must use cache_vref() or
517 * cache_vget() on the locked ncp to
518 * validate the vp or set the cache entry
521 * NOTE! vhold() is allowed if we hold a
522 * lock on the ncp (which we do).
526 atomic_clear_int(&ncp->nc_lockstatus,
537 * If already held shared we can just bump the count, but
538 * only allow this if nobody is trying to get the lock
539 * exclusively. If we are blocking too long ignore excl
540 * requests (which can race/deadlock us).
542 * VHOLD is a bit of a hack. Even though we successfully
543 * added another shared ref, the cpu that got the first
544 * shared ref might not yet have held the vnode.
546 if ((count & (optreq|NC_SHLOCK_FLAG)) == NC_SHLOCK_FLAG) {
547 KKASSERT((count & ~(NC_EXLOCK_REQ |
549 NC_SHLOCK_FLAG)) > 0);
550 if (atomic_cmpset_int(&ncp->nc_lockstatus,
552 while (ncp->nc_lockstatus & NC_SHLOCK_VHOLD)
558 tsleep_interlock(ncp, 0);
559 if (atomic_cmpset_int(&ncp->nc_lockstatus, count,
560 count | NC_SHLOCK_REQ) == 0) {
564 error = tsleep(ncp, PINTERLOCKED, "clocksh", nclockwarn);
565 if (error == EWOULDBLOCK) {
568 didwarn = ticks - nclockwarn;
569 kprintf("[diagnostic] cache_lock_shared: "
570 "%s blocked on %p %08x",
571 curthread->td_comm, ncp, count);
572 kprintf(" \"%*.*s\"\n",
573 ncp->nc_nlen, ncp->nc_nlen,
580 kprintf("[diagnostic] cache_lock_shared: "
581 "%s unblocked %*.*s after %d secs\n",
583 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name,
584 (int)(ticks - didwarn) / hz);
589 * Lock ncp exclusively, return 0 on success.
591 * NOTE: nc_refs may be zero if the ncp is interlocked by circumstance,
592 * such as the case where one of its children is locked.
596 _cache_lock_nonblock(struct namecache *ncp)
604 count = ncp->nc_lockstatus;
606 if ((count & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 0) {
607 if (atomic_cmpset_int(&ncp->nc_lockstatus,
610 * The vp associated with a locked ncp must
611 * be held to prevent it from being recycled.
613 * WARNING! If VRECLAIMED is set the vnode
614 * could already be in the middle of a recycle.
615 * Callers must use cache_vref() or
616 * cache_vget() on the locked ncp to
617 * validate the vp or set the cache entry
620 * NOTE! vhold() is allowed if we hold a
621 * lock on the ncp (which we do).
631 if (ncp->nc_locktd == td) {
632 if (atomic_cmpset_int(&ncp->nc_lockstatus,
645 * The shared lock works similarly to the exclusive lock except
646 * nc_locktd is left NULL and we need an interlock (VHOLD) to
647 * prevent vhold() races, since the moment our cmpset_int succeeds
648 * another cpu can come in and get its own shared lock.
650 * A critical section is needed to prevent interruption during the
655 _cache_lock_shared_nonblock(struct namecache *ncp)
660 count = ncp->nc_lockstatus;
662 if ((count & ~NC_SHLOCK_REQ) == 0) {
664 if (atomic_cmpset_int(&ncp->nc_lockstatus,
666 (count + 1) | NC_SHLOCK_FLAG |
669 * The vp associated with a locked ncp must
670 * be held to prevent it from being recycled.
672 * WARNING! If VRECLAIMED is set the vnode
673 * could already be in the middle of a recycle.
674 * Callers must use cache_vref() or
675 * cache_vget() on the locked ncp to
676 * validate the vp or set the cache entry
679 * NOTE! vhold() is allowed if we hold a
680 * lock on the ncp (which we do).
684 atomic_clear_int(&ncp->nc_lockstatus,
695 * If already held shared we can just bump the count, but
696 * only allow this if nobody is trying to get the lock
699 * VHOLD is a bit of a hack. Even though we successfully
700 * added another shared ref, the cpu that got the first
701 * shared ref might not yet have held the vnode.
703 if ((count & (NC_EXLOCK_REQ|NC_SHLOCK_FLAG)) ==
705 KKASSERT((count & ~(NC_EXLOCK_REQ |
707 NC_SHLOCK_FLAG)) > 0);
708 if (atomic_cmpset_int(&ncp->nc_lockstatus,
710 while (ncp->nc_lockstatus & NC_SHLOCK_VHOLD)
724 * NOTE: nc_refs can be 0 (degenerate case during _cache_drop).
726 * nc_locktd must be NULLed out prior to nc_lockstatus getting cleared.
730 _cache_unlock(struct namecache *ncp)
732 thread_t td __debugvar = curthread;
735 struct vnode *dropvp;
737 KKASSERT(ncp->nc_refs >= 0);
738 KKASSERT((ncp->nc_lockstatus & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) > 0);
739 KKASSERT((ncp->nc_lockstatus & NC_SHLOCK_FLAG) || ncp->nc_locktd == td);
741 count = ncp->nc_lockstatus;
745 * Clear nc_locktd prior to the atomic op (excl lock only)
747 if ((count & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 1)
748 ncp->nc_locktd = NULL;
753 ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ|NC_SHLOCK_FLAG)) == 1) {
755 if (count & NC_EXLOCK_REQ)
756 ncount = count & NC_SHLOCK_REQ; /* cnt->0 */
760 if (atomic_cmpset_int(&ncp->nc_lockstatus,
762 if (count & NC_EXLOCK_REQ)
763 wakeup(&ncp->nc_locktd);
764 else if (count & NC_SHLOCK_REQ)
770 KKASSERT((count & NC_SHLOCK_VHOLD) == 0);
771 KKASSERT((count & ~(NC_EXLOCK_REQ |
773 NC_SHLOCK_FLAG)) > 1);
774 if (atomic_cmpset_int(&ncp->nc_lockstatus,
779 count = ncp->nc_lockstatus;
784 * Don't actually drop the vp until we successfully clean out
785 * the lock, otherwise we may race another shared lock.
793 _cache_lockstatus(struct namecache *ncp)
795 if (ncp->nc_locktd == curthread)
796 return(LK_EXCLUSIVE);
797 if (ncp->nc_lockstatus & NC_SHLOCK_FLAG)
803 * cache_hold() and cache_drop() prevent the premature deletion of a
804 * namecache entry but do not prevent operations (such as zapping) on
805 * that namecache entry.
807 * This routine may only be called from outside this source module if
808 * nc_refs is already at least 1.
810 * This is a rare case where callers are allowed to hold a spinlock,
811 * so we can't ourselves.
815 _cache_hold(struct namecache *ncp)
817 atomic_add_int(&ncp->nc_refs, 1);
822 * Drop a cache entry, taking care to deal with races.
824 * For potential 1->0 transitions we must hold the ncp lock to safely
825 * test its flags. An unresolved entry with no children must be zapped
828 * The call to cache_zap() itself will handle all remaining races and
829 * will decrement the ncp's refs regardless. If we are resolved or
830 * have children nc_refs can safely be dropped to 0 without having to
833 * NOTE: cache_zap() will re-check nc_refs and nc_list in a MPSAFE fashion.
835 * NOTE: cache_zap() may return a non-NULL referenced parent which must
836 * be dropped in a loop.
840 _cache_drop(struct namecache *ncp)
845 KKASSERT(ncp->nc_refs > 0);
849 if (_cache_lock_nonblock(ncp) == 0) {
850 ncp->nc_flag &= ~NCF_DEFEREDZAP;
851 if ((ncp->nc_flag & NCF_UNRESOLVED) &&
852 TAILQ_EMPTY(&ncp->nc_list)) {
853 ncp = cache_zap(ncp, 1);
856 if (atomic_cmpset_int(&ncp->nc_refs, 1, 0)) {
863 if (atomic_cmpset_int(&ncp->nc_refs, refs, refs - 1))
871 * Link a new namecache entry to its parent and to the hash table. Be
872 * careful to avoid races if vhold() blocks in the future.
874 * Both ncp and par must be referenced and locked.
876 * NOTE: The hash table spinlock is held during this call, we can't do
880 _cache_link_parent(struct namecache *ncp, struct namecache *par,
881 struct nchash_head *nchpp)
883 KKASSERT(ncp->nc_parent == NULL);
884 ncp->nc_parent = par;
885 ncp->nc_head = nchpp;
888 * Set inheritance flags. Note that the parent flags may be
889 * stale due to getattr potentially not having been run yet
890 * (it gets run during nlookup()'s).
892 ncp->nc_flag &= ~(NCF_SF_PNOCACHE | NCF_UF_PCACHE);
893 if (par->nc_flag & (NCF_SF_NOCACHE | NCF_SF_PNOCACHE))
894 ncp->nc_flag |= NCF_SF_PNOCACHE;
895 if (par->nc_flag & (NCF_UF_CACHE | NCF_UF_PCACHE))
896 ncp->nc_flag |= NCF_UF_PCACHE;
898 LIST_INSERT_HEAD(&nchpp->list, ncp, nc_hash);
900 if (TAILQ_EMPTY(&par->nc_list)) {
901 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
903 * Any vp associated with an ncp which has children must
904 * be held to prevent it from being recycled.
909 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
914 * Remove the parent and hash associations from a namecache structure.
915 * If this is the last child of the parent the cache_drop(par) will
916 * attempt to recursively zap the parent.
918 * ncp must be locked. This routine will acquire a temporary lock on
919 * the parent as wlel as the appropriate hash chain.
922 _cache_unlink_parent(struct namecache *ncp)
924 struct namecache *par;
925 struct vnode *dropvp;
927 if ((par = ncp->nc_parent) != NULL) {
928 KKASSERT(ncp->nc_parent == par);
931 spin_lock(&ncp->nc_head->spin);
932 LIST_REMOVE(ncp, nc_hash);
933 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
935 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
937 spin_unlock(&ncp->nc_head->spin);
938 ncp->nc_parent = NULL;
944 * We can only safely vdrop with no spinlocks held.
952 * Allocate a new namecache structure. Most of the code does not require
953 * zero-termination of the string but it makes vop_compat_ncreate() easier.
955 static struct namecache *
956 cache_alloc(int nlen)
958 struct namecache *ncp;
960 ncp = kmalloc(sizeof(*ncp), M_VFSCACHE, M_WAITOK|M_ZERO);
962 ncp->nc_name = kmalloc(nlen + 1, M_VFSCACHE, M_WAITOK);
964 ncp->nc_flag = NCF_UNRESOLVED;
965 ncp->nc_error = ENOTCONN; /* needs to be resolved */
968 TAILQ_INIT(&ncp->nc_list);
974 * Can only be called for the case where the ncp has never been
975 * associated with anything (so no spinlocks are needed).
978 _cache_free(struct namecache *ncp)
980 KKASSERT(ncp->nc_refs == 1 && ncp->nc_lockstatus == 1);
982 kfree(ncp->nc_name, M_VFSCACHE);
983 kfree(ncp, M_VFSCACHE);
987 * [re]initialize a nchandle.
990 cache_zero(struct nchandle *nch)
997 * Ref and deref a namecache structure.
999 * The caller must specify a stable ncp pointer, typically meaning the
1000 * ncp is already referenced but this can also occur indirectly through
1001 * e.g. holding a lock on a direct child.
1003 * WARNING: Caller may hold an unrelated read spinlock, which means we can't
1004 * use read spinlocks here.
1007 cache_hold(struct nchandle *nch)
1009 _cache_hold(nch->ncp);
1010 _cache_mntref(nch->mount);
1015 * Create a copy of a namecache handle for an already-referenced
1019 cache_copy(struct nchandle *nch, struct nchandle *target)
1021 struct mntcache *cache = &pcpu_mntcache[mycpu->gd_cpuid];
1022 struct namecache *ncp;
1025 _cache_mntref(target->mount);
1028 if (ncp == cache->ncp1) {
1029 if (atomic_cmpset_ptr((void *)&cache->ncp1, ncp, NULL))
1032 if (ncp == cache->ncp2) {
1033 if (atomic_cmpset_ptr((void *)&cache->ncp2, ncp, NULL))
1041 * Caller wants to copy the current directory, copy it out from our
1042 * pcpu cache if possible (the entire critical path is just two localized
1043 * cmpset ops). If the pcpu cache has a snapshot at all it will be a
1044 * valid one, so we don't have to lock p->p_fd even though we are loading
1047 * This has a limited effect since nlookup must still ref and shlock the
1048 * vnode to check perms. We do avoid the per-proc spin-lock though, which
1049 * can aid threaded programs.
1052 cache_copy_ncdir(struct proc *p, struct nchandle *target)
1054 struct mntcache *cache = &pcpu_mntcache[mycpu->gd_cpuid];
1056 *target = p->p_fd->fd_ncdir;
1057 if (target->ncp == cache->ncdir.ncp &&
1058 target->mount == cache->ncdir.mount) {
1059 if (atomic_cmpset_ptr((void *)&cache->ncdir.ncp,
1060 target->ncp, NULL)) {
1061 if (atomic_cmpset_ptr((void *)&cache->ncdir.mount,
1062 target->mount, NULL)) {
1066 _cache_drop(target->ncp);
1069 spin_lock_shared(&p->p_fd->fd_spin);
1070 cache_copy(&p->p_fd->fd_ncdir, target);
1071 spin_unlock_shared(&p->p_fd->fd_spin);
1075 cache_changemount(struct nchandle *nch, struct mount *mp)
1078 _cache_mntrel(nch->mount);
1083 cache_drop(struct nchandle *nch)
1085 _cache_mntrel(nch->mount);
1086 _cache_drop(nch->ncp);
1092 * Drop the nchandle, but try to cache the ref to avoid global atomic
1093 * ops. This is typically done on the system root and jail root nchandles.
1096 cache_drop_and_cache(struct nchandle *nch)
1098 struct mntcache *cache = &pcpu_mntcache[mycpu->gd_cpuid];
1099 struct namecache *ncp;
1101 _cache_mntrel(nch->mount);
1103 if (cache->ncp1 == NULL) {
1104 ncp = atomic_swap_ptr((void *)&cache->ncp1, ncp);
1108 if (cache->ncp2 == NULL) {
1109 ncp = atomic_swap_ptr((void *)&cache->ncp2, ncp);
1113 if (++cache->iter & 1)
1114 ncp = atomic_swap_ptr((void *)&cache->ncp2, ncp);
1116 ncp = atomic_swap_ptr((void *)&cache->ncp1, ncp);
1125 * We are dropping what the caller believes is the current directory,
1126 * unconditionally store it in our pcpu cache. Anything already in
1127 * the cache will be discarded.
1130 cache_drop_ncdir(struct nchandle *nch)
1132 struct mntcache *cache = &pcpu_mntcache[mycpu->gd_cpuid];
1134 nch->ncp = atomic_swap_ptr((void *)&cache->ncdir.ncp, nch->ncp);
1135 nch->mount = atomic_swap_ptr((void *)&cache->ncdir.mount, nch->mount);
1137 _cache_drop(nch->ncp);
1139 _cache_mntrel(nch->mount);
1145 cache_lockstatus(struct nchandle *nch)
1147 return(_cache_lockstatus(nch->ncp));
1151 cache_lock(struct nchandle *nch)
1153 _cache_lock(nch->ncp);
1157 cache_lock_maybe_shared(struct nchandle *nch, int excl)
1159 struct namecache *ncp = nch->ncp;
1161 if (ncp_shared_lock_disable || excl ||
1162 (ncp->nc_flag & NCF_UNRESOLVED)) {
1165 _cache_lock_shared(ncp);
1166 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1167 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED)) {
1179 * Relock nch1 given an unlocked nch1 and a locked nch2. The caller
1180 * is responsible for checking both for validity on return as they
1181 * may have become invalid.
1183 * We have to deal with potential deadlocks here, just ping pong
1184 * the lock until we get it (we will always block somewhere when
1185 * looping so this is not cpu-intensive).
1187 * which = 0 nch1 not locked, nch2 is locked
1188 * which = 1 nch1 is locked, nch2 is not locked
1191 cache_relock(struct nchandle *nch1, struct ucred *cred1,
1192 struct nchandle *nch2, struct ucred *cred2)
1200 if (cache_lock_nonblock(nch1) == 0) {
1201 cache_resolve(nch1, cred1);
1206 cache_resolve(nch1, cred1);
1209 if (cache_lock_nonblock(nch2) == 0) {
1210 cache_resolve(nch2, cred2);
1215 cache_resolve(nch2, cred2);
1222 cache_lock_nonblock(struct nchandle *nch)
1224 return(_cache_lock_nonblock(nch->ncp));
1228 cache_unlock(struct nchandle *nch)
1230 _cache_unlock(nch->ncp);
1234 * ref-and-lock, unlock-and-deref functions.
1236 * This function is primarily used by nlookup. Even though cache_lock
1237 * holds the vnode, it is possible that the vnode may have already
1238 * initiated a recyclement.
1240 * We want cache_get() to return a definitively usable vnode or a
1241 * definitively unresolved ncp.
1245 _cache_get(struct namecache *ncp)
1249 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
1250 _cache_setunresolved(ncp);
1255 * Attempt to obtain a shared lock on the ncp. A shared lock will only
1256 * be obtained if the ncp is resolved and the vnode (if not ENOENT) is
1257 * valid. Otherwise an exclusive lock will be acquired instead.
1261 _cache_get_maybe_shared(struct namecache *ncp, int excl)
1263 if (ncp_shared_lock_disable || excl ||
1264 (ncp->nc_flag & NCF_UNRESOLVED)) {
1265 return(_cache_get(ncp));
1268 _cache_lock_shared(ncp);
1269 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1270 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED)) {
1272 ncp = _cache_get(ncp);
1277 ncp = _cache_get(ncp);
1284 * This is a special form of _cache_lock() which only succeeds if
1285 * it can get a pristine, non-recursive lock. The caller must have
1286 * already ref'd the ncp.
1288 * On success the ncp will be locked, on failure it will not. The
1289 * ref count does not change either way.
1291 * We want _cache_lock_special() (on success) to return a definitively
1292 * usable vnode or a definitively unresolved ncp.
1295 _cache_lock_special(struct namecache *ncp)
1297 if (_cache_lock_nonblock(ncp) == 0) {
1298 if ((ncp->nc_lockstatus &
1299 ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 1) {
1300 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
1301 _cache_setunresolved(ncp);
1306 return(EWOULDBLOCK);
1310 * This function tries to get a shared lock but will back-off to an exclusive
1313 * (1) Some other thread is trying to obtain an exclusive lock
1314 * (to prevent the exclusive requester from getting livelocked out
1315 * by many shared locks).
1317 * (2) The current thread already owns an exclusive lock (to avoid
1320 * WARNING! On machines with lots of cores we really want to try hard to
1321 * get a shared lock or concurrent path lookups can chain-react
1322 * into a very high-latency exclusive lock.
1325 _cache_lock_shared_special(struct namecache *ncp)
1328 * Only honor a successful shared lock (returning 0) if there is
1329 * no exclusive request pending and the vnode, if present, is not
1330 * in a reclaimed state.
1332 if (_cache_lock_shared_nonblock(ncp) == 0) {
1333 if ((ncp->nc_lockstatus & NC_EXLOCK_REQ) == 0) {
1334 if (ncp->nc_vp == NULL ||
1335 (ncp->nc_vp->v_flag & VRECLAIMED) == 0) {
1340 return(EWOULDBLOCK);
1344 * Non-blocking shared lock failed. If we already own the exclusive
1345 * lock just acquire another exclusive lock (instead of deadlocking).
1346 * Otherwise acquire a shared lock.
1348 if (ncp->nc_locktd == curthread) {
1352 _cache_lock_shared(ncp);
1358 * NOTE: The same nchandle can be passed for both arguments.
1361 cache_get(struct nchandle *nch, struct nchandle *target)
1363 KKASSERT(nch->ncp->nc_refs > 0);
1364 target->mount = nch->mount;
1365 target->ncp = _cache_get(nch->ncp);
1366 _cache_mntref(target->mount);
1370 cache_get_maybe_shared(struct nchandle *nch, struct nchandle *target, int excl)
1372 KKASSERT(nch->ncp->nc_refs > 0);
1373 target->mount = nch->mount;
1374 target->ncp = _cache_get_maybe_shared(nch->ncp, excl);
1375 _cache_mntref(target->mount);
1383 _cache_put(struct namecache *ncp)
1393 cache_put(struct nchandle *nch)
1395 _cache_mntrel(nch->mount);
1396 _cache_put(nch->ncp);
1402 * Resolve an unresolved ncp by associating a vnode with it. If the
1403 * vnode is NULL, a negative cache entry is created.
1405 * The ncp should be locked on entry and will remain locked on return.
1409 _cache_setvp(struct mount *mp, struct namecache *ncp, struct vnode *vp)
1411 KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
1412 KKASSERT(_cache_lockstatus(ncp) == LK_EXCLUSIVE);
1416 * Any vp associated with an ncp which has children must
1417 * be held. Any vp associated with a locked ncp must be held.
1419 if (!TAILQ_EMPTY(&ncp->nc_list))
1421 spin_lock(&vp->v_spin);
1423 TAILQ_INSERT_HEAD(&vp->v_namecache, ncp, nc_vnode);
1424 spin_unlock(&vp->v_spin);
1425 if (ncp->nc_lockstatus & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ))
1429 * Set auxiliary flags
1431 switch(vp->v_type) {
1433 ncp->nc_flag |= NCF_ISDIR;
1436 ncp->nc_flag |= NCF_ISSYMLINK;
1437 /* XXX cache the contents of the symlink */
1442 atomic_add_int(&numcache, 1);
1444 /* XXX: this is a hack to work-around the lack of a real pfs vfs
1447 if (strncmp(mp->mnt_stat.f_fstypename, "null", 5) == 0)
1451 * When creating a negative cache hit we set the
1452 * namecache_gen. A later resolve will clean out the
1453 * negative cache hit if the mount point's namecache_gen
1454 * has changed. Used by devfs, could also be used by
1458 spin_lock(&ncneg.spin);
1459 TAILQ_INSERT_TAIL(&ncneg.list, ncp, nc_vnode);
1461 spin_unlock(&ncneg.spin);
1462 ncp->nc_error = ENOENT;
1464 VFS_NCPGEN_SET(mp, ncp);
1466 ncp->nc_flag &= ~(NCF_UNRESOLVED | NCF_DEFEREDZAP);
1473 cache_setvp(struct nchandle *nch, struct vnode *vp)
1475 _cache_setvp(nch->mount, nch->ncp, vp);
1482 cache_settimeout(struct nchandle *nch, int nticks)
1484 struct namecache *ncp = nch->ncp;
1486 if ((ncp->nc_timeout = ticks + nticks) == 0)
1487 ncp->nc_timeout = 1;
1491 * Disassociate the vnode or negative-cache association and mark a
1492 * namecache entry as unresolved again. Note that the ncp is still
1493 * left in the hash table and still linked to its parent.
1495 * The ncp should be locked and refd on entry and will remain locked and refd
1498 * This routine is normally never called on a directory containing children.
1499 * However, NFS often does just that in its rename() code as a cop-out to
1500 * avoid complex namespace operations. This disconnects a directory vnode
1501 * from its namecache and can cause the OLDAPI and NEWAPI to get out of
1507 _cache_setunresolved(struct namecache *ncp)
1511 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1512 ncp->nc_flag |= NCF_UNRESOLVED;
1513 ncp->nc_timeout = 0;
1514 ncp->nc_error = ENOTCONN;
1515 if ((vp = ncp->nc_vp) != NULL) {
1516 atomic_add_int(&numcache, -1);
1517 spin_lock(&vp->v_spin);
1519 TAILQ_REMOVE(&vp->v_namecache, ncp, nc_vnode);
1520 spin_unlock(&vp->v_spin);
1523 * Any vp associated with an ncp with children is
1524 * held by that ncp. Any vp associated with a locked
1525 * ncp is held by that ncp. These conditions must be
1526 * undone when the vp is cleared out from the ncp.
1528 if (!TAILQ_EMPTY(&ncp->nc_list))
1530 if (ncp->nc_lockstatus & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ))
1533 spin_lock(&ncneg.spin);
1534 TAILQ_REMOVE(&ncneg.list, ncp, nc_vnode);
1536 spin_unlock(&ncneg.spin);
1538 ncp->nc_flag &= ~(NCF_WHITEOUT|NCF_ISDIR|NCF_ISSYMLINK);
1543 * The cache_nresolve() code calls this function to automatically
1544 * set a resolved cache element to unresolved if it has timed out
1545 * or if it is a negative cache hit and the mount point namecache_gen
1549 _cache_auto_unresolve_test(struct mount *mp, struct namecache *ncp)
1552 * Try to zap entries that have timed out. We have
1553 * to be careful here because locked leafs may depend
1554 * on the vnode remaining intact in a parent, so only
1555 * do this under very specific conditions.
1557 if (ncp->nc_timeout && (int)(ncp->nc_timeout - ticks) < 0 &&
1558 TAILQ_EMPTY(&ncp->nc_list)) {
1563 * If a resolved negative cache hit is invalid due to
1564 * the mount's namecache generation being bumped, zap it.
1566 if (ncp->nc_vp == NULL && VFS_NCPGEN_TEST(mp, ncp)) {
1571 * Otherwise we are good
1576 static __inline void
1577 _cache_auto_unresolve(struct mount *mp, struct namecache *ncp)
1580 * Already in an unresolved state, nothing to do.
1582 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1583 if (_cache_auto_unresolve_test(mp, ncp))
1584 _cache_setunresolved(ncp);
1592 cache_setunresolved(struct nchandle *nch)
1594 _cache_setunresolved(nch->ncp);
1598 * Determine if we can clear NCF_ISMOUNTPT by scanning the mountlist
1599 * looking for matches. This flag tells the lookup code when it must
1600 * check for a mount linkage and also prevents the directories in question
1601 * from being deleted or renamed.
1605 cache_clrmountpt_callback(struct mount *mp, void *data)
1607 struct nchandle *nch = data;
1609 if (mp->mnt_ncmounton.ncp == nch->ncp)
1611 if (mp->mnt_ncmountpt.ncp == nch->ncp)
1620 cache_clrmountpt(struct nchandle *nch)
1624 count = mountlist_scan(cache_clrmountpt_callback, nch,
1625 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1627 nch->ncp->nc_flag &= ~NCF_ISMOUNTPT;
1631 * Invalidate portions of the namecache topology given a starting entry.
1632 * The passed ncp is set to an unresolved state and:
1634 * The passed ncp must be referencxed and locked. The routine may unlock
1635 * and relock ncp several times, and will recheck the children and loop
1636 * to catch races. When done the passed ncp will be returned with the
1637 * reference and lock intact.
1639 * CINV_DESTROY - Set a flag in the passed ncp entry indicating
1640 * that the physical underlying nodes have been
1641 * destroyed... as in deleted. For example, when
1642 * a directory is removed. This will cause record
1643 * lookups on the name to no longer be able to find
1644 * the record and tells the resolver to return failure
1645 * rather then trying to resolve through the parent.
1647 * The topology itself, including ncp->nc_name,
1650 * This only applies to the passed ncp, if CINV_CHILDREN
1651 * is specified the children are not flagged.
1653 * CINV_CHILDREN - Set all children (recursively) to an unresolved
1656 * Note that this will also have the side effect of
1657 * cleaning out any unreferenced nodes in the topology
1658 * from the leaves up as the recursion backs out.
1660 * Note that the topology for any referenced nodes remains intact, but
1661 * the nodes will be marked as having been destroyed and will be set
1662 * to an unresolved state.
1664 * It is possible for cache_inval() to race a cache_resolve(), meaning that
1665 * the namecache entry may not actually be invalidated on return if it was
1666 * revalidated while recursing down into its children. This code guarentees
1667 * that the node(s) will go through an invalidation cycle, but does not
1668 * guarentee that they will remain in an invalidated state.
1670 * Returns non-zero if a revalidation was detected during the invalidation
1671 * recursion, zero otherwise. Note that since only the original ncp is
1672 * locked the revalidation ultimately can only indicate that the original ncp
1673 * *MIGHT* no have been reresolved.
1675 * DEEP RECURSION HANDLING - If a recursive invalidation recurses deeply we
1676 * have to avoid blowing out the kernel stack. We do this by saving the
1677 * deep namecache node and aborting the recursion, then re-recursing at that
1678 * node using a depth-first algorithm in order to allow multiple deep
1679 * recursions to chain through each other, then we restart the invalidation
1684 struct namecache *resume_ncp;
1688 static int _cache_inval_internal(struct namecache *, int, struct cinvtrack *);
1692 _cache_inval(struct namecache *ncp, int flags)
1694 struct cinvtrack track;
1695 struct namecache *ncp2;
1699 track.resume_ncp = NULL;
1702 r = _cache_inval_internal(ncp, flags, &track);
1703 if (track.resume_ncp == NULL)
1706 while ((ncp2 = track.resume_ncp) != NULL) {
1707 track.resume_ncp = NULL;
1709 _cache_inval_internal(ncp2, flags & ~CINV_DESTROY,
1719 cache_inval(struct nchandle *nch, int flags)
1721 return(_cache_inval(nch->ncp, flags));
1725 * Helper for _cache_inval(). The passed ncp is refd and locked and
1726 * remains that way on return, but may be unlocked/relocked multiple
1727 * times by the routine.
1730 _cache_inval_internal(struct namecache *ncp, int flags, struct cinvtrack *track)
1732 struct namecache *nextkid;
1735 KKASSERT(_cache_lockstatus(ncp) == LK_EXCLUSIVE);
1737 _cache_setunresolved(ncp);
1738 if (flags & CINV_DESTROY) {
1739 ncp->nc_flag |= NCF_DESTROYED;
1740 ++ncp->nc_generation;
1742 while ((flags & CINV_CHILDREN) &&
1743 (nextkid = TAILQ_FIRST(&ncp->nc_list)) != NULL
1745 struct namecache *kid;
1749 _cache_hold(nextkid);
1750 if (++track->depth > MAX_RECURSION_DEPTH) {
1751 track->resume_ncp = ncp;
1755 while ((kid = nextkid) != NULL) {
1757 * Parent (ncp) must be locked for the iteration.
1760 if (kid->nc_parent != ncp) {
1762 kprintf("cache_inval_internal restartA %s\n",
1767 if ((nextkid = TAILQ_NEXT(kid, nc_entry)) != NULL)
1768 _cache_hold(nextkid);
1771 * Parent unlocked for this section to avoid
1775 if (track->resume_ncp) {
1780 if ((kid->nc_flag & NCF_UNRESOLVED) == 0 ||
1781 TAILQ_FIRST(&kid->nc_list)
1784 if (kid->nc_parent != ncp) {
1785 kprintf("cache_inval_internal "
1795 rcnt += _cache_inval_internal(kid, flags & ~CINV_DESTROY, track);
1802 _cache_drop(nextkid);
1809 * Someone could have gotten in there while ncp was unlocked,
1812 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
1818 * Invalidate a vnode's namecache associations. To avoid races against
1819 * the resolver we do not invalidate a node which we previously invalidated
1820 * but which was then re-resolved while we were in the invalidation loop.
1822 * Returns non-zero if any namecache entries remain after the invalidation
1825 * NOTE: Unlike the namecache topology which guarentees that ncp's will not
1826 * be ripped out of the topology while held, the vnode's v_namecache
1827 * list has no such restriction. NCP's can be ripped out of the list
1828 * at virtually any time if not locked, even if held.
1830 * In addition, the v_namecache list itself must be locked via
1831 * the vnode's spinlock.
1834 cache_inval_vp(struct vnode *vp, int flags)
1836 struct namecache *ncp;
1837 struct namecache *next;
1840 spin_lock(&vp->v_spin);
1841 ncp = TAILQ_FIRST(&vp->v_namecache);
1845 /* loop entered with ncp held and vp spin-locked */
1846 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1848 spin_unlock(&vp->v_spin);
1850 if (ncp->nc_vp != vp) {
1851 kprintf("Warning: cache_inval_vp: race-A detected on "
1852 "%s\n", ncp->nc_name);
1858 _cache_inval(ncp, flags);
1859 _cache_put(ncp); /* also releases reference */
1861 spin_lock(&vp->v_spin);
1862 if (ncp && ncp->nc_vp != vp) {
1863 spin_unlock(&vp->v_spin);
1864 kprintf("Warning: cache_inval_vp: race-B detected on "
1865 "%s\n", ncp->nc_name);
1870 spin_unlock(&vp->v_spin);
1871 return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1875 * This routine is used instead of the normal cache_inval_vp() when we
1876 * are trying to recycle otherwise good vnodes.
1878 * Return 0 on success, non-zero if not all namecache records could be
1879 * disassociated from the vnode (for various reasons).
1882 cache_inval_vp_nonblock(struct vnode *vp)
1884 struct namecache *ncp;
1885 struct namecache *next;
1887 spin_lock(&vp->v_spin);
1888 ncp = TAILQ_FIRST(&vp->v_namecache);
1892 /* loop entered with ncp held */
1893 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1895 spin_unlock(&vp->v_spin);
1896 if (_cache_lock_nonblock(ncp)) {
1902 if (ncp->nc_vp != vp) {
1903 kprintf("Warning: cache_inval_vp: race-A detected on "
1904 "%s\n", ncp->nc_name);
1910 _cache_inval(ncp, 0);
1911 _cache_put(ncp); /* also releases reference */
1913 spin_lock(&vp->v_spin);
1914 if (ncp && ncp->nc_vp != vp) {
1915 spin_unlock(&vp->v_spin);
1916 kprintf("Warning: cache_inval_vp: race-B detected on "
1917 "%s\n", ncp->nc_name);
1922 spin_unlock(&vp->v_spin);
1924 return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1928 * Clears the universal directory search 'ok' flag. This flag allows
1929 * nlookup() to bypass normal vnode checks. This flag is a cached flag
1930 * so clearing it simply forces revalidation.
1933 cache_inval_wxok(struct vnode *vp)
1935 struct namecache *ncp;
1937 spin_lock(&vp->v_spin);
1938 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1939 if (ncp->nc_flag & NCF_WXOK)
1940 atomic_clear_short(&ncp->nc_flag, NCF_WXOK);
1942 spin_unlock(&vp->v_spin);
1946 * The source ncp has been renamed to the target ncp. Both fncp and tncp
1947 * must be locked. The target ncp is destroyed (as a normal rename-over
1948 * would destroy the target file or directory).
1950 * Because there may be references to the source ncp we cannot copy its
1951 * contents to the target. Instead the source ncp is relinked as the target
1952 * and the target ncp is removed from the namecache topology.
1955 cache_rename(struct nchandle *fnch, struct nchandle *tnch)
1957 struct namecache *fncp = fnch->ncp;
1958 struct namecache *tncp = tnch->ncp;
1959 struct namecache *tncp_par;
1960 struct nchash_head *nchpp;
1965 ++fncp->nc_generation;
1966 ++tncp->nc_generation;
1967 if (tncp->nc_nlen) {
1968 nname = kmalloc(tncp->nc_nlen + 1, M_VFSCACHE, M_WAITOK);
1969 bcopy(tncp->nc_name, nname, tncp->nc_nlen);
1970 nname[tncp->nc_nlen] = 0;
1976 * Rename fncp (unlink)
1978 _cache_unlink_parent(fncp);
1979 oname = fncp->nc_name;
1980 fncp->nc_name = nname;
1981 fncp->nc_nlen = tncp->nc_nlen;
1983 kfree(oname, M_VFSCACHE);
1985 tncp_par = tncp->nc_parent;
1986 _cache_hold(tncp_par);
1987 _cache_lock(tncp_par);
1990 * Rename fncp (relink)
1992 hash = fnv_32_buf(fncp->nc_name, fncp->nc_nlen, FNV1_32_INIT);
1993 hash = fnv_32_buf(&tncp_par, sizeof(tncp_par), hash);
1994 nchpp = NCHHASH(hash);
1996 spin_lock(&nchpp->spin);
1997 _cache_link_parent(fncp, tncp_par, nchpp);
1998 spin_unlock(&nchpp->spin);
2000 _cache_put(tncp_par);
2003 * Get rid of the overwritten tncp (unlink)
2005 _cache_unlink(tncp);
2009 * Perform actions consistent with unlinking a file. The passed-in ncp
2012 * The ncp is marked DESTROYED so it no longer shows up in searches,
2013 * and will be physically deleted when the vnode goes away.
2015 * If the related vnode has no refs then we cycle it through vget()/vput()
2016 * to (possibly if we don't have a ref race) trigger a deactivation,
2017 * allowing the VFS to trivially detect and recycle the deleted vnode
2018 * via VOP_INACTIVE().
2020 * NOTE: _cache_rename() will automatically call _cache_unlink() on the
2024 cache_unlink(struct nchandle *nch)
2026 _cache_unlink(nch->ncp);
2030 _cache_unlink(struct namecache *ncp)
2035 * Causes lookups to fail and allows another ncp with the same
2036 * name to be created under ncp->nc_parent.
2038 ncp->nc_flag |= NCF_DESTROYED;
2039 ++ncp->nc_generation;
2042 * Attempt to trigger a deactivation. Set VREF_FINALIZE to
2043 * force action on the 1->0 transition.
2045 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
2046 (vp = ncp->nc_vp) != NULL) {
2047 atomic_set_int(&vp->v_refcnt, VREF_FINALIZE);
2048 if (VREFCNT(vp) <= 0) {
2049 if (vget(vp, LK_SHARED) == 0)
2056 * Return non-zero if the nch might be associated with an open and/or mmap()'d
2057 * file. The easy solution is to just return non-zero if the vnode has refs.
2058 * Used to interlock hammer2 reclaims (VREF_FINALIZE should already be set to
2059 * force the reclaim).
2062 cache_isopen(struct nchandle *nch)
2065 struct namecache *ncp = nch->ncp;
2067 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
2068 (vp = ncp->nc_vp) != NULL &&
2077 * vget the vnode associated with the namecache entry. Resolve the namecache
2078 * entry if necessary. The passed ncp must be referenced and locked. If
2079 * the ncp is resolved it might be locked shared.
2081 * lk_type may be LK_SHARED, LK_EXCLUSIVE. A ref'd, possibly locked
2082 * (depending on the passed lk_type) will be returned in *vpp with an error
2083 * of 0, or NULL will be returned in *vpp with a non-0 error code. The
2084 * most typical error is ENOENT, meaning that the ncp represents a negative
2085 * cache hit and there is no vnode to retrieve, but other errors can occur
2088 * The vget() can race a reclaim. If this occurs we re-resolve the
2091 * There are numerous places in the kernel where vget() is called on a
2092 * vnode while one or more of its namecache entries is locked. Releasing
2093 * a vnode never deadlocks against locked namecache entries (the vnode
2094 * will not get recycled while referenced ncp's exist). This means we
2095 * can safely acquire the vnode. In fact, we MUST NOT release the ncp
2096 * lock when acquiring the vp lock or we might cause a deadlock.
2098 * NOTE: The passed-in ncp must be locked exclusively if it is initially
2099 * unresolved. If a reclaim race occurs the passed-in ncp will be
2100 * relocked exclusively before being re-resolved.
2103 cache_vget(struct nchandle *nch, struct ucred *cred,
2104 int lk_type, struct vnode **vpp)
2106 struct namecache *ncp;
2113 if (ncp->nc_flag & NCF_UNRESOLVED)
2114 error = cache_resolve(nch, cred);
2118 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
2119 error = vget(vp, lk_type);
2124 * The ncp may have been locked shared, we must relock
2125 * it exclusively before we can set it to unresolved.
2127 if (error == ENOENT) {
2128 kprintf("Warning: vnode reclaim race detected "
2129 "in cache_vget on %p (%s)\n",
2133 _cache_setunresolved(ncp);
2138 * Not a reclaim race, some other error.
2140 KKASSERT(ncp->nc_vp == vp);
2143 KKASSERT(ncp->nc_vp == vp);
2144 KKASSERT((vp->v_flag & VRECLAIMED) == 0);
2147 if (error == 0 && vp == NULL)
2154 * Similar to cache_vget() but only acquires a ref on the vnode.
2156 * NOTE: The passed-in ncp must be locked exclusively if it is initially
2157 * unresolved. If a reclaim race occurs the passed-in ncp will be
2158 * relocked exclusively before being re-resolved.
2161 cache_vref(struct nchandle *nch, struct ucred *cred, struct vnode **vpp)
2163 struct namecache *ncp;
2170 if (ncp->nc_flag & NCF_UNRESOLVED)
2171 error = cache_resolve(nch, cred);
2175 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
2176 error = vget(vp, LK_SHARED);
2181 if (error == ENOENT) {
2182 kprintf("Warning: vnode reclaim race detected "
2183 "in cache_vget on %p (%s)\n",
2187 _cache_setunresolved(ncp);
2192 * Not a reclaim race, some other error.
2194 KKASSERT(ncp->nc_vp == vp);
2197 KKASSERT(ncp->nc_vp == vp);
2198 KKASSERT((vp->v_flag & VRECLAIMED) == 0);
2199 /* caller does not want a lock */
2203 if (error == 0 && vp == NULL)
2210 * Return a referenced vnode representing the parent directory of
2213 * Because the caller has locked the ncp it should not be possible for
2214 * the parent ncp to go away. However, the parent can unresolve its
2215 * dvp at any time so we must be able to acquire a lock on the parent
2216 * to safely access nc_vp.
2218 * We have to leave par unlocked when vget()ing dvp to avoid a deadlock,
2219 * so use vhold()/vdrop() while holding the lock to prevent dvp from
2220 * getting destroyed.
2222 * NOTE: vhold() is allowed when dvp has 0 refs if we hold a
2223 * lock on the ncp in question..
2225 static struct vnode *
2226 cache_dvpref(struct namecache *ncp)
2228 struct namecache *par;
2232 if ((par = ncp->nc_parent) != NULL) {
2235 if ((par->nc_flag & NCF_UNRESOLVED) == 0) {
2236 if ((dvp = par->nc_vp) != NULL)
2241 if (vget(dvp, LK_SHARED) == 0) {
2244 /* return refd, unlocked dvp */
2256 * Convert a directory vnode to a namecache record without any other
2257 * knowledge of the topology. This ONLY works with directory vnodes and
2258 * is ONLY used by the NFS server. dvp must be refd but unlocked, and the
2259 * returned ncp (if not NULL) will be held and unlocked.
2261 * If 'makeit' is 0 and dvp has no existing namecache record, NULL is returned.
2262 * If 'makeit' is 1 we attempt to track-down and create the namecache topology
2263 * for dvp. This will fail only if the directory has been deleted out from
2266 * Callers must always check for a NULL return no matter the value of 'makeit'.
2268 * To avoid underflowing the kernel stack each recursive call increments
2269 * the makeit variable.
2272 static int cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
2273 struct vnode *dvp, char *fakename);
2274 static int cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
2275 struct vnode **saved_dvp);
2278 cache_fromdvp(struct vnode *dvp, struct ucred *cred, int makeit,
2279 struct nchandle *nch)
2281 struct vnode *saved_dvp;
2287 nch->mount = dvp->v_mount;
2292 * Handle the makeit == 0 degenerate case
2295 spin_lock_shared(&dvp->v_spin);
2296 nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
2299 spin_unlock_shared(&dvp->v_spin);
2303 * Loop until resolution, inside code will break out on error.
2307 * Break out if we successfully acquire a working ncp.
2309 spin_lock_shared(&dvp->v_spin);
2310 nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
2313 spin_unlock_shared(&dvp->v_spin);
2316 spin_unlock_shared(&dvp->v_spin);
2319 * If dvp is the root of its filesystem it should already
2320 * have a namecache pointer associated with it as a side
2321 * effect of the mount, but it may have been disassociated.
2323 if (dvp->v_flag & VROOT) {
2324 nch->ncp = _cache_get(nch->mount->mnt_ncmountpt.ncp);
2325 error = cache_resolve_mp(nch->mount);
2326 _cache_put(nch->ncp);
2328 kprintf("cache_fromdvp: resolve root of mount %p error %d",
2329 dvp->v_mount, error);
2333 kprintf(" failed\n");
2338 kprintf(" succeeded\n");
2343 * If we are recursed too deeply resort to an O(n^2)
2344 * algorithm to resolve the namecache topology. The
2345 * resolved pvp is left referenced in saved_dvp to
2346 * prevent the tree from being destroyed while we loop.
2349 error = cache_fromdvp_try(dvp, cred, &saved_dvp);
2351 kprintf("lookupdotdot(longpath) failed %d "
2352 "dvp %p\n", error, dvp);
2360 * Get the parent directory and resolve its ncp.
2363 kfree(fakename, M_TEMP);
2366 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
2369 kprintf("lookupdotdot failed %d dvp %p\n", error, dvp);
2375 * Reuse makeit as a recursion depth counter. On success
2376 * nch will be fully referenced.
2378 cache_fromdvp(pvp, cred, makeit + 1, nch);
2380 if (nch->ncp == NULL)
2384 * Do an inefficient scan of pvp (embodied by ncp) to look
2385 * for dvp. This will create a namecache record for dvp on
2386 * success. We loop up to recheck on success.
2388 * ncp and dvp are both held but not locked.
2390 error = cache_inefficient_scan(nch, cred, dvp, fakename);
2392 kprintf("cache_fromdvp: scan %p (%s) failed on dvp=%p\n",
2393 pvp, nch->ncp->nc_name, dvp);
2395 /* nch was NULLed out, reload mount */
2396 nch->mount = dvp->v_mount;
2400 kprintf("cache_fromdvp: scan %p (%s) succeeded\n",
2401 pvp, nch->ncp->nc_name);
2404 /* nch was NULLed out, reload mount */
2405 nch->mount = dvp->v_mount;
2409 * If nch->ncp is non-NULL it will have been held already.
2412 kfree(fakename, M_TEMP);
2421 * Go up the chain of parent directories until we find something
2422 * we can resolve into the namecache. This is very inefficient.
2426 cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
2427 struct vnode **saved_dvp)
2429 struct nchandle nch;
2432 static time_t last_fromdvp_report;
2436 * Loop getting the parent directory vnode until we get something we
2437 * can resolve in the namecache.
2440 nch.mount = dvp->v_mount;
2446 kfree(fakename, M_TEMP);
2449 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
2456 spin_lock_shared(&pvp->v_spin);
2457 if ((nch.ncp = TAILQ_FIRST(&pvp->v_namecache)) != NULL) {
2458 _cache_hold(nch.ncp);
2459 spin_unlock_shared(&pvp->v_spin);
2463 spin_unlock_shared(&pvp->v_spin);
2464 if (pvp->v_flag & VROOT) {
2465 nch.ncp = _cache_get(pvp->v_mount->mnt_ncmountpt.ncp);
2466 error = cache_resolve_mp(nch.mount);
2467 _cache_unlock(nch.ncp);
2470 _cache_drop(nch.ncp);
2480 if (last_fromdvp_report != time_uptime) {
2481 last_fromdvp_report = time_uptime;
2482 kprintf("Warning: extremely inefficient path "
2483 "resolution on %s\n",
2486 error = cache_inefficient_scan(&nch, cred, dvp, fakename);
2489 * Hopefully dvp now has a namecache record associated with
2490 * it. Leave it referenced to prevent the kernel from
2491 * recycling the vnode. Otherwise extremely long directory
2492 * paths could result in endless recycling.
2497 _cache_drop(nch.ncp);
2500 kfree(fakename, M_TEMP);
2505 * Do an inefficient scan of the directory represented by ncp looking for
2506 * the directory vnode dvp. ncp must be held but not locked on entry and
2507 * will be held on return. dvp must be refd but not locked on entry and
2508 * will remain refd on return.
2510 * Why do this at all? Well, due to its stateless nature the NFS server
2511 * converts file handles directly to vnodes without necessarily going through
2512 * the namecache ops that would otherwise create the namecache topology
2513 * leading to the vnode. We could either (1) Change the namecache algorithms
2514 * to allow disconnect namecache records that are re-merged opportunistically,
2515 * or (2) Make the NFS server backtrack and scan to recover a connected
2516 * namecache topology in order to then be able to issue new API lookups.
2518 * It turns out that (1) is a huge mess. It takes a nice clean set of
2519 * namecache algorithms and introduces a lot of complication in every subsystem
2520 * that calls into the namecache to deal with the re-merge case, especially
2521 * since we are using the namecache to placehold negative lookups and the
2522 * vnode might not be immediately assigned. (2) is certainly far less
2523 * efficient then (1), but since we are only talking about directories here
2524 * (which are likely to remain cached), the case does not actually run all
2525 * that often and has the supreme advantage of not polluting the namecache
2528 * If a fakename is supplied just construct a namecache entry using the
2532 cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
2533 struct vnode *dvp, char *fakename)
2535 struct nlcomponent nlc;
2536 struct nchandle rncp;
2548 vat.va_blocksize = 0;
2549 if ((error = VOP_GETATTR(dvp, &vat)) != 0)
2552 error = cache_vref(nch, cred, &pvp);
2557 kprintf("inefficient_scan of (%p,%s): directory iosize %ld "
2558 "vattr fileid = %lld\n",
2559 nch->ncp, nch->ncp->nc_name,
2561 (long long)vat.va_fileid);
2565 * Use the supplied fakename if not NULL. Fake names are typically
2566 * not in the actual filesystem hierarchy. This is used by HAMMER
2567 * to glue @@timestamp recursions together.
2570 nlc.nlc_nameptr = fakename;
2571 nlc.nlc_namelen = strlen(fakename);
2572 rncp = cache_nlookup(nch, &nlc);
2576 if ((blksize = vat.va_blocksize) == 0)
2577 blksize = DEV_BSIZE;
2578 rbuf = kmalloc(blksize, M_TEMP, M_WAITOK);
2584 iov.iov_base = rbuf;
2585 iov.iov_len = blksize;
2588 uio.uio_resid = blksize;
2589 uio.uio_segflg = UIO_SYSSPACE;
2590 uio.uio_rw = UIO_READ;
2591 uio.uio_td = curthread;
2593 if (ncvp_debug >= 2)
2594 kprintf("cache_inefficient_scan: readdir @ %08x\n", (int)uio.uio_offset);
2595 error = VOP_READDIR(pvp, &uio, cred, &eofflag, NULL, NULL);
2597 den = (struct dirent *)rbuf;
2598 bytes = blksize - uio.uio_resid;
2601 if (ncvp_debug >= 2) {
2602 kprintf("cache_inefficient_scan: %*.*s\n",
2603 den->d_namlen, den->d_namlen,
2606 if (den->d_type != DT_WHT &&
2607 den->d_ino == vat.va_fileid) {
2609 kprintf("cache_inefficient_scan: "
2610 "MATCHED inode %lld path %s/%*.*s\n",
2611 (long long)vat.va_fileid,
2613 den->d_namlen, den->d_namlen,
2616 nlc.nlc_nameptr = den->d_name;
2617 nlc.nlc_namelen = den->d_namlen;
2618 rncp = cache_nlookup(nch, &nlc);
2619 KKASSERT(rncp.ncp != NULL);
2622 bytes -= _DIRENT_DIRSIZ(den);
2623 den = _DIRENT_NEXT(den);
2625 if (rncp.ncp == NULL && eofflag == 0 && uio.uio_resid != blksize)
2628 kfree(rbuf, M_TEMP);
2632 if (rncp.ncp->nc_flag & NCF_UNRESOLVED) {
2633 _cache_setvp(rncp.mount, rncp.ncp, dvp);
2634 if (ncvp_debug >= 2) {
2635 kprintf("cache_inefficient_scan: setvp %s/%s = %p\n",
2636 nch->ncp->nc_name, rncp.ncp->nc_name, dvp);
2639 if (ncvp_debug >= 2) {
2640 kprintf("cache_inefficient_scan: setvp %s/%s already set %p/%p\n",
2641 nch->ncp->nc_name, rncp.ncp->nc_name, dvp,
2645 if (rncp.ncp->nc_vp == NULL)
2646 error = rncp.ncp->nc_error;
2648 * Release rncp after a successful nlookup. rncp was fully
2653 kprintf("cache_inefficient_scan: dvp %p NOT FOUND in %s\n",
2654 dvp, nch->ncp->nc_name);
2661 * Zap a namecache entry. The ncp is unconditionally set to an unresolved
2662 * state, which disassociates it from its vnode or ncneg.list.
2664 * Then, if there are no additional references to the ncp and no children,
2665 * the ncp is removed from the topology and destroyed.
2667 * References and/or children may exist if the ncp is in the middle of the
2668 * topology, preventing the ncp from being destroyed.
2670 * This function must be called with the ncp held and locked and will unlock
2671 * and drop it during zapping.
2673 * If nonblock is non-zero and the parent ncp cannot be locked we give up.
2674 * This case can occur in the cache_drop() path.
2676 * This function may returned a held (but NOT locked) parent node which the
2677 * caller must drop. We do this so _cache_drop() can loop, to avoid
2678 * blowing out the kernel stack.
2680 * WARNING! For MPSAFE operation this routine must acquire up to three
2681 * spin locks to be able to safely test nc_refs. Lock order is
2684 * hash spinlock if on hash list
2685 * parent spinlock if child of parent
2686 * (the ncp is unresolved so there is no vnode association)
2688 static struct namecache *
2689 cache_zap(struct namecache *ncp, int nonblock)
2691 struct namecache *par;
2692 struct vnode *dropvp;
2693 struct nchash_head *nchpp;
2697 * Disassociate the vnode or negative cache ref and set NCF_UNRESOLVED.
2699 _cache_setunresolved(ncp);
2702 * Try to scrap the entry and possibly tail-recurse on its parent.
2703 * We only scrap unref'd (other then our ref) unresolved entries,
2704 * we do not scrap 'live' entries.
2706 * Note that once the spinlocks are acquired if nc_refs == 1 no
2707 * other references are possible. If it isn't, however, we have
2708 * to decrement but also be sure to avoid a 1->0 transition.
2710 KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
2711 KKASSERT(ncp->nc_refs > 0);
2714 * Acquire locks. Note that the parent can't go away while we hold
2718 if ((par = ncp->nc_parent) != NULL) {
2721 if (_cache_lock_nonblock(par) == 0)
2723 refs = ncp->nc_refs;
2724 ncp->nc_flag |= NCF_DEFEREDZAP;
2725 ++numdefered; /* MP race ok */
2726 if (atomic_cmpset_int(&ncp->nc_refs,
2738 nchpp = ncp->nc_head;
2739 spin_lock(&nchpp->spin);
2743 * At this point if we find refs == 1 it should not be possible for
2744 * anyone else to have access to the ncp. We are holding the only
2745 * possible access point left (nchpp) spin-locked.
2747 * If someone other then us has a ref or we have children
2748 * we cannot zap the entry. The 1->0 transition and any
2749 * further list operation is protected by the spinlocks
2750 * we have acquired but other transitions are not.
2753 refs = ncp->nc_refs;
2755 if (refs == 1 && TAILQ_EMPTY(&ncp->nc_list))
2757 if (atomic_cmpset_int(&ncp->nc_refs, refs, refs - 1)) {
2759 spin_unlock(&nchpp->spin);
2769 * We are the only ref and with the spinlocks held no further
2770 * refs can be acquired by others.
2772 * Remove us from the hash list and parent list. We have to
2773 * drop a ref on the parent's vp if the parent's list becomes
2778 KKASSERT(nchpp == ncp->nc_head);
2779 LIST_REMOVE(ncp, nc_hash);
2780 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
2781 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
2782 dropvp = par->nc_vp;
2783 ncp->nc_head = NULL;
2784 ncp->nc_parent = NULL;
2785 spin_unlock(&nchpp->spin);
2788 KKASSERT(ncp->nc_head == NULL);
2792 * ncp should not have picked up any refs. Physically
2795 if (ncp->nc_refs != 1) {
2796 int save_refs = ncp->nc_refs;
2798 panic("cache_zap: %p bad refs %d (%d)\n",
2799 ncp, save_refs, atomic_fetchadd_int(&ncp->nc_refs, 0));
2801 KKASSERT(ncp->nc_refs == 1);
2802 /* _cache_unlock(ncp) not required */
2803 ncp->nc_refs = -1; /* safety */
2805 kfree(ncp->nc_name, M_VFSCACHE);
2806 kfree(ncp, M_VFSCACHE);
2809 * Delayed drop (we had to release our spinlocks)
2811 * The refed parent (if not NULL) must be dropped. The
2812 * caller is responsible for looping.
2820 * Clean up dangling negative cache and defered-drop entries in the
2823 * This routine is called in the critical path and also called from
2824 * vnlru(). When called from vnlru we use a lower limit to try to
2825 * deal with the negative cache before the critical path has to start
2828 typedef enum { CHI_LOW, CHI_HIGH } cache_hs_t;
2830 static cache_hs_t neg_cache_hysteresis_state[2] = { CHI_LOW, CHI_LOW };
2831 static cache_hs_t pos_cache_hysteresis_state[2] = { CHI_LOW, CHI_LOW };
2834 cache_hysteresis(int critpath)
2837 int neglimit = maxvnodes / ncnegfactor;
2838 int xnumcache = numcache;
2841 neglimit = neglimit * 8 / 10;
2844 * Don't cache too many negative hits. We use hysteresis to reduce
2845 * the impact on the critical path.
2847 switch(neg_cache_hysteresis_state[critpath]) {
2849 if (numneg > MINNEG && numneg > neglimit) {
2851 _cache_cleanneg(ncnegflush);
2853 _cache_cleanneg(ncnegflush +
2855 neg_cache_hysteresis_state[critpath] = CHI_HIGH;
2859 if (numneg > MINNEG * 9 / 10 &&
2860 numneg * 9 / 10 > neglimit
2863 _cache_cleanneg(ncnegflush);
2865 _cache_cleanneg(ncnegflush +
2866 numneg * 9 / 10 - neglimit);
2868 neg_cache_hysteresis_state[critpath] = CHI_LOW;
2874 * Don't cache too many positive hits. We use hysteresis to reduce
2875 * the impact on the critical path.
2877 * Excessive positive hits can accumulate due to large numbers of
2878 * hardlinks (the vnode cache will not prevent hl ncps from growing
2881 if ((poslimit = ncposlimit) == 0)
2882 poslimit = maxvnodes * 2;
2884 poslimit = poslimit * 8 / 10;
2886 switch(pos_cache_hysteresis_state[critpath]) {
2888 if (xnumcache > poslimit && xnumcache > MINPOS) {
2890 _cache_cleanpos(ncposflush);
2892 _cache_cleanpos(ncposflush +
2893 xnumcache - poslimit);
2894 pos_cache_hysteresis_state[critpath] = CHI_HIGH;
2898 if (xnumcache > poslimit * 5 / 6 && xnumcache > MINPOS) {
2900 _cache_cleanpos(ncposflush);
2902 _cache_cleanpos(ncposflush +
2903 xnumcache - poslimit * 5 / 6);
2905 pos_cache_hysteresis_state[critpath] = CHI_LOW;
2911 * Clean out dangling defered-zap ncps which could not
2912 * be cleanly dropped if too many build up. Note
2913 * that numdefered is not an exact number as such ncps
2914 * can be reused and the counter is not handled in a MP
2915 * safe manner by design.
2917 if (numdefered > neglimit) {
2918 _cache_cleandefered();
2923 * NEW NAMECACHE LOOKUP API
2925 * Lookup an entry in the namecache. The passed par_nch must be referenced
2926 * and unlocked. A referenced and locked nchandle with a non-NULL nch.ncp
2927 * is ALWAYS returned, eve if the supplied component is illegal.
2929 * The resulting namecache entry should be returned to the system with
2930 * cache_put() or cache_unlock() + cache_drop().
2932 * namecache locks are recursive but care must be taken to avoid lock order
2933 * reversals (hence why the passed par_nch must be unlocked). Locking
2934 * rules are to order for parent traversals, not for child traversals.
2936 * Nobody else will be able to manipulate the associated namespace (e.g.
2937 * create, delete, rename, rename-target) until the caller unlocks the
2940 * The returned entry will be in one of three states: positive hit (non-null
2941 * vnode), negative hit (null vnode), or unresolved (NCF_UNRESOLVED is set).
2942 * Unresolved entries must be resolved through the filesystem to associate the
2943 * vnode and/or determine whether a positive or negative hit has occured.
2945 * It is not necessary to lock a directory in order to lock namespace under
2946 * that directory. In fact, it is explicitly not allowed to do that. A
2947 * directory is typically only locked when being created, renamed, or
2950 * The directory (par) may be unresolved, in which case any returned child
2951 * will likely also be marked unresolved. Likely but not guarenteed. Since
2952 * the filesystem lookup requires a resolved directory vnode the caller is
2953 * responsible for resolving the namecache chain top-down. This API
2954 * specifically allows whole chains to be created in an unresolved state.
2957 cache_nlookup(struct nchandle *par_nch, struct nlcomponent *nlc)
2959 struct nchandle nch;
2960 struct namecache *ncp;
2961 struct namecache *new_ncp;
2962 struct nchash_head *nchpp;
2969 mp = par_nch->mount;
2973 * This is a good time to call it, no ncp's are locked by
2976 cache_hysteresis(1);
2979 * Try to locate an existing entry
2981 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
2982 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
2984 nchpp = NCHHASH(hash);
2987 spin_lock(&nchpp->spin);
2989 spin_lock_shared(&nchpp->spin);
2991 LIST_FOREACH(ncp, &nchpp->list, nc_hash) {
2993 * Break out if we find a matching entry. Note that
2994 * UNRESOLVED entries may match, but DESTROYED entries
2997 if (ncp->nc_parent == par_nch->ncp &&
2998 ncp->nc_nlen == nlc->nlc_namelen &&
2999 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
3000 (ncp->nc_flag & NCF_DESTROYED) == 0
3004 spin_unlock(&nchpp->spin);
3006 spin_unlock_shared(&nchpp->spin);
3008 _cache_unlock(par_nch->ncp);
3011 if (_cache_lock_special(ncp) == 0) {
3013 * Successfully locked but we must re-test
3014 * conditions that might have changed since
3015 * we did not have the lock before.
3017 if (ncp->nc_parent != par_nch->ncp ||
3018 ncp->nc_nlen != nlc->nlc_namelen ||
3019 bcmp(ncp->nc_name, nlc->nlc_nameptr,
3021 (ncp->nc_flag & NCF_DESTROYED)) {
3025 _cache_auto_unresolve(mp, ncp);
3027 _cache_free(new_ncp);
3030 _cache_get(ncp); /* cycle the lock to block */
3038 * We failed to locate an entry, create a new entry and add it to
3039 * the cache. The parent ncp must also be locked so we
3042 * We have to relookup after possibly blocking in kmalloc or
3043 * when locking par_nch.
3045 * NOTE: nlc_namelen can be 0 and nlc_nameptr NULL as a special
3046 * mount case, in which case nc_name will be NULL.
3048 if (new_ncp == NULL) {
3049 spin_unlock_shared(&nchpp->spin);
3050 new_ncp = cache_alloc(nlc->nlc_namelen);
3051 if (nlc->nlc_namelen) {
3052 bcopy(nlc->nlc_nameptr, new_ncp->nc_name,
3054 new_ncp->nc_name[nlc->nlc_namelen] = 0;
3060 * NOTE! The spinlock is held exclusively here because new_ncp
3063 if (par_locked == 0) {
3064 spin_unlock(&nchpp->spin);
3065 _cache_lock(par_nch->ncp);
3071 * WARNING! We still hold the spinlock. We have to set the hash
3072 * table entry atomically.
3075 _cache_link_parent(ncp, par_nch->ncp, nchpp);
3076 spin_unlock(&nchpp->spin);
3077 _cache_unlock(par_nch->ncp);
3078 /* par_locked = 0 - not used */
3081 * stats and namecache size management
3083 if (ncp->nc_flag & NCF_UNRESOLVED)
3084 ++gd->gd_nchstats->ncs_miss;
3085 else if (ncp->nc_vp)
3086 ++gd->gd_nchstats->ncs_goodhits;
3088 ++gd->gd_nchstats->ncs_neghits;
3091 _cache_mntref(nch.mount);
3097 * Attempt to lookup a namecache entry and return with a shared namecache
3101 cache_nlookup_maybe_shared(struct nchandle *par_nch, struct nlcomponent *nlc,
3102 int excl, struct nchandle *res_nch)
3104 struct namecache *ncp;
3105 struct nchash_head *nchpp;
3111 * If exclusive requested or shared namecache locks are disabled,
3114 if (ncp_shared_lock_disable || excl)
3115 return(EWOULDBLOCK);
3118 mp = par_nch->mount;
3121 * This is a good time to call it, no ncp's are locked by
3124 cache_hysteresis(1);
3127 * Try to locate an existing entry
3129 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
3130 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
3131 nchpp = NCHHASH(hash);
3133 spin_lock_shared(&nchpp->spin);
3135 LIST_FOREACH(ncp, &nchpp->list, nc_hash) {
3137 * Break out if we find a matching entry. Note that
3138 * UNRESOLVED entries may match, but DESTROYED entries
3141 if (ncp->nc_parent == par_nch->ncp &&
3142 ncp->nc_nlen == nlc->nlc_namelen &&
3143 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
3144 (ncp->nc_flag & NCF_DESTROYED) == 0
3147 spin_unlock_shared(&nchpp->spin);
3148 if (_cache_lock_shared_special(ncp) == 0) {
3149 if (ncp->nc_parent == par_nch->ncp &&
3150 ncp->nc_nlen == nlc->nlc_namelen &&
3151 bcmp(ncp->nc_name, nlc->nlc_nameptr,
3152 ncp->nc_nlen) == 0 &&
3153 (ncp->nc_flag & NCF_DESTROYED) == 0 &&
3154 (ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
3155 _cache_auto_unresolve_test(mp, ncp) == 0) {
3161 spin_lock_shared(&nchpp->spin);
3169 spin_unlock_shared(&nchpp->spin);
3170 return(EWOULDBLOCK);
3175 * Note that nc_error might be non-zero (e.g ENOENT).
3178 res_nch->mount = mp;
3180 ++gd->gd_nchstats->ncs_goodhits;
3181 _cache_mntref(res_nch->mount);
3183 KKASSERT(ncp->nc_error != EWOULDBLOCK);
3184 return(ncp->nc_error);
3188 * This is a non-blocking verison of cache_nlookup() used by
3189 * nfs_readdirplusrpc_uio(). It can fail for any reason and
3190 * will return nch.ncp == NULL in that case.
3193 cache_nlookup_nonblock(struct nchandle *par_nch, struct nlcomponent *nlc)
3195 struct nchandle nch;
3196 struct namecache *ncp;
3197 struct namecache *new_ncp;
3198 struct nchash_head *nchpp;
3205 mp = par_nch->mount;
3209 * Try to locate an existing entry
3211 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
3212 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
3214 nchpp = NCHHASH(hash);
3216 spin_lock(&nchpp->spin);
3217 LIST_FOREACH(ncp, &nchpp->list, nc_hash) {
3219 * Break out if we find a matching entry. Note that
3220 * UNRESOLVED entries may match, but DESTROYED entries
3223 if (ncp->nc_parent == par_nch->ncp &&
3224 ncp->nc_nlen == nlc->nlc_namelen &&
3225 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
3226 (ncp->nc_flag & NCF_DESTROYED) == 0
3229 spin_unlock(&nchpp->spin);
3231 _cache_unlock(par_nch->ncp);
3234 if (_cache_lock_special(ncp) == 0) {
3235 if (ncp->nc_parent != par_nch->ncp ||
3236 ncp->nc_nlen != nlc->nlc_namelen ||
3237 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) ||
3238 (ncp->nc_flag & NCF_DESTROYED)) {
3239 kprintf("cache_lookup_nonblock: "
3240 "ncp-race %p %*.*s\n",
3249 _cache_auto_unresolve(mp, ncp);
3251 _cache_free(new_ncp);
3262 * We failed to locate an entry, create a new entry and add it to
3263 * the cache. The parent ncp must also be locked so we
3266 * We have to relookup after possibly blocking in kmalloc or
3267 * when locking par_nch.
3269 * NOTE: nlc_namelen can be 0 and nlc_nameptr NULL as a special
3270 * mount case, in which case nc_name will be NULL.
3272 if (new_ncp == NULL) {
3273 spin_unlock(&nchpp->spin);
3274 new_ncp = cache_alloc(nlc->nlc_namelen);
3275 if (nlc->nlc_namelen) {
3276 bcopy(nlc->nlc_nameptr, new_ncp->nc_name,
3278 new_ncp->nc_name[nlc->nlc_namelen] = 0;
3282 if (par_locked == 0) {
3283 spin_unlock(&nchpp->spin);
3284 if (_cache_lock_nonblock(par_nch->ncp) == 0) {
3292 * WARNING! We still hold the spinlock. We have to set the hash
3293 * table entry atomically.
3296 _cache_link_parent(ncp, par_nch->ncp, nchpp);
3297 spin_unlock(&nchpp->spin);
3298 _cache_unlock(par_nch->ncp);
3299 /* par_locked = 0 - not used */
3302 * stats and namecache size management
3304 if (ncp->nc_flag & NCF_UNRESOLVED)
3305 ++gd->gd_nchstats->ncs_miss;
3306 else if (ncp->nc_vp)
3307 ++gd->gd_nchstats->ncs_goodhits;
3309 ++gd->gd_nchstats->ncs_neghits;
3312 _cache_mntref(nch.mount);
3317 _cache_free(new_ncp);
3326 * The namecache entry is marked as being used as a mount point.
3327 * Locate the mount if it is visible to the caller. The DragonFly
3328 * mount system allows arbitrary loops in the topology and disentangles
3329 * those loops by matching against (mp, ncp) rather than just (ncp).
3330 * This means any given ncp can dive any number of mounts, depending
3331 * on the relative mount (e.g. nullfs) the caller is at in the topology.
3333 * We use a very simple frontend cache to reduce SMP conflicts,
3334 * which we have to do because the mountlist scan needs an exclusive
3335 * lock around its ripout info list. Not to mention that there might
3336 * be a lot of mounts.
3338 struct findmount_info {
3339 struct mount *result;
3340 struct mount *nch_mount;
3341 struct namecache *nch_ncp;
3345 struct ncmount_cache *
3346 ncmount_cache_lookup(struct mount *mp, struct namecache *ncp)
3350 hash = ((int)(intptr_t)mp / sizeof(*mp)) ^
3351 ((int)(intptr_t)ncp / sizeof(*ncp));
3352 hash = (hash & 0x7FFFFFFF) % NCMOUNT_NUMCACHE;
3353 return (&ncmount_cache[hash]);
3358 cache_findmount_callback(struct mount *mp, void *data)
3360 struct findmount_info *info = data;
3363 * Check the mount's mounted-on point against the passed nch.
3365 if (mp->mnt_ncmounton.mount == info->nch_mount &&
3366 mp->mnt_ncmounton.ncp == info->nch_ncp
3376 cache_findmount(struct nchandle *nch)
3378 struct findmount_info info;
3379 struct ncmount_cache *ncc;
3385 if (ncmount_cache_enable == 0) {
3389 ncc = ncmount_cache_lookup(nch->mount, nch->ncp);
3390 if (ncc->ncp == nch->ncp) {
3391 spin_lock_shared(&ncc->spin);
3392 if (ncc->isneg == 0 &&
3393 ncc->ncp == nch->ncp && (mp = ncc->mp) != NULL) {
3394 if (mp->mnt_ncmounton.mount == nch->mount &&
3395 mp->mnt_ncmounton.ncp == nch->ncp) {
3397 * Cache hit (positive)
3400 spin_unlock_shared(&ncc->spin);
3403 /* else cache miss */
3406 ncc->ncp == nch->ncp && ncc->mp == nch->mount) {
3408 * Cache hit (negative)
3410 spin_unlock_shared(&ncc->spin);
3413 spin_unlock_shared(&ncc->spin);
3421 info.nch_mount = nch->mount;
3422 info.nch_ncp = nch->ncp;
3423 mountlist_scan(cache_findmount_callback, &info,
3424 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
3429 * Negative lookups: We cache the originating {ncp,mp}. (mp) is
3430 * only used for pointer comparisons and is not
3431 * referenced (otherwise there would be dangling
3434 * Positive lookups: We cache the originating {ncp} and the target
3435 * (mp). (mp) is referenced.
3437 * Indeterminant: If the match is undergoing an unmount we do
3438 * not cache it to avoid racing cache_unmounting(),
3439 * but still return the match.
3442 spin_lock(&ncc->spin);
3443 if (info.result == NULL) {
3444 if (ncc->isneg == 0 && ncc->mp)
3445 _cache_mntrel(ncc->mp);
3446 ncc->ncp = nch->ncp;
3447 ncc->mp = nch->mount;
3449 spin_unlock(&ncc->spin);
3450 } else if ((info.result->mnt_kern_flag & MNTK_UNMOUNT) == 0) {
3451 if (ncc->isneg == 0 && ncc->mp)
3452 _cache_mntrel(ncc->mp);
3453 _cache_mntref(info.result);
3454 ncc->ncp = nch->ncp;
3455 ncc->mp = info.result;
3457 spin_unlock(&ncc->spin);
3459 spin_unlock(&ncc->spin);
3462 return(info.result);
3466 cache_dropmount(struct mount *mp)
3472 cache_ismounting(struct mount *mp)
3474 struct nchandle *nch = &mp->mnt_ncmounton;
3475 struct ncmount_cache *ncc;
3477 ncc = ncmount_cache_lookup(nch->mount, nch->ncp);
3479 ncc->ncp == nch->ncp && ncc->mp == nch->mount) {
3480 spin_lock(&ncc->spin);
3482 ncc->ncp == nch->ncp && ncc->mp == nch->mount) {
3486 spin_unlock(&ncc->spin);
3491 cache_unmounting(struct mount *mp)
3493 struct nchandle *nch = &mp->mnt_ncmounton;
3494 struct ncmount_cache *ncc;
3496 ncc = ncmount_cache_lookup(nch->mount, nch->ncp);
3497 if (ncc->isneg == 0 &&
3498 ncc->ncp == nch->ncp && ncc->mp == mp) {
3499 spin_lock(&ncc->spin);
3500 if (ncc->isneg == 0 &&
3501 ncc->ncp == nch->ncp && ncc->mp == mp) {
3506 spin_unlock(&ncc->spin);
3511 * Resolve an unresolved namecache entry, generally by looking it up.
3512 * The passed ncp must be locked and refd.
3514 * Theoretically since a vnode cannot be recycled while held, and since
3515 * the nc_parent chain holds its vnode as long as children exist, the
3516 * direct parent of the cache entry we are trying to resolve should
3517 * have a valid vnode. If not then generate an error that we can
3518 * determine is related to a resolver bug.
3520 * However, if a vnode was in the middle of a recyclement when the NCP
3521 * got locked, ncp->nc_vp might point to a vnode that is about to become
3522 * invalid. cache_resolve() handles this case by unresolving the entry
3523 * and then re-resolving it.
3525 * Note that successful resolution does not necessarily return an error
3526 * code of 0. If the ncp resolves to a negative cache hit then ENOENT
3530 cache_resolve(struct nchandle *nch, struct ucred *cred)
3532 struct namecache *par_tmp;
3533 struct namecache *par;
3534 struct namecache *ncp;
3535 struct nchandle nctmp;
3542 KKASSERT(_cache_lockstatus(ncp) == LK_EXCLUSIVE);
3545 * If the ncp is already resolved we have nothing to do. However,
3546 * we do want to guarentee that a usable vnode is returned when
3547 * a vnode is present, so make sure it hasn't been reclaimed.
3549 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
3550 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
3551 _cache_setunresolved(ncp);
3552 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
3553 return (ncp->nc_error);
3557 * If the ncp was destroyed it will never resolve again. This
3558 * can basically only happen when someone is chdir'd into an
3559 * empty directory which is then rmdir'd. We want to catch this
3560 * here and not dive the VFS because the VFS might actually
3561 * have a way to re-resolve the disconnected ncp, which will
3562 * result in inconsistencies in the cdir/nch for proc->p_fd.
3564 if (ncp->nc_flag & NCF_DESTROYED)
3568 * Mount points need special handling because the parent does not
3569 * belong to the same filesystem as the ncp.
3571 if (ncp == mp->mnt_ncmountpt.ncp)
3572 return (cache_resolve_mp(mp));
3575 * We expect an unbroken chain of ncps to at least the mount point,
3576 * and even all the way to root (but this code doesn't have to go
3577 * past the mount point).
3579 if (ncp->nc_parent == NULL) {
3580 kprintf("EXDEV case 1 %p %*.*s\n", ncp,
3581 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
3582 ncp->nc_error = EXDEV;
3583 return(ncp->nc_error);
3587 * The vp's of the parent directories in the chain are held via vhold()
3588 * due to the existance of the child, and should not disappear.
3589 * However, there are cases where they can disappear:
3591 * - due to filesystem I/O errors.
3592 * - due to NFS being stupid about tracking the namespace and
3593 * destroys the namespace for entire directories quite often.
3594 * - due to forced unmounts.
3595 * - due to an rmdir (parent will be marked DESTROYED)
3597 * When this occurs we have to track the chain backwards and resolve
3598 * it, looping until the resolver catches up to the current node. We
3599 * could recurse here but we might run ourselves out of kernel stack
3600 * so we do it in a more painful manner. This situation really should
3601 * not occur all that often, or if it does not have to go back too
3602 * many nodes to resolve the ncp.
3604 while ((dvp = cache_dvpref(ncp)) == NULL) {
3606 * This case can occur if a process is CD'd into a
3607 * directory which is then rmdir'd. If the parent is marked
3608 * destroyed there is no point trying to resolve it.
3610 if (ncp->nc_parent->nc_flag & NCF_DESTROYED)
3612 par = ncp->nc_parent;
3615 while ((par_tmp = par->nc_parent) != NULL &&
3616 par_tmp->nc_vp == NULL) {
3617 _cache_hold(par_tmp);
3618 _cache_lock(par_tmp);
3622 if (par->nc_parent == NULL) {
3623 kprintf("EXDEV case 2 %*.*s\n",
3624 par->nc_nlen, par->nc_nlen, par->nc_name);
3629 * The parent is not set in stone, ref and lock it to prevent
3630 * it from disappearing. Also note that due to renames it
3631 * is possible for our ncp to move and for par to no longer
3632 * be one of its parents. We resolve it anyway, the loop
3633 * will handle any moves.
3635 _cache_get(par); /* additional hold/lock */
3636 _cache_put(par); /* from earlier hold/lock */
3637 if (par == nch->mount->mnt_ncmountpt.ncp) {
3638 cache_resolve_mp(nch->mount);
3639 } else if ((dvp = cache_dvpref(par)) == NULL) {
3640 kprintf("[diagnostic] cache_resolve: raced on %*.*s\n", par->nc_nlen, par->nc_nlen, par->nc_name);
3644 if (par->nc_flag & NCF_UNRESOLVED) {
3647 par->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
3651 if ((error = par->nc_error) != 0) {
3652 if (par->nc_error != EAGAIN) {
3653 kprintf("EXDEV case 3 %*.*s error %d\n",
3654 par->nc_nlen, par->nc_nlen, par->nc_name,
3659 kprintf("[diagnostic] cache_resolve: EAGAIN par %p %*.*s\n",
3660 par, par->nc_nlen, par->nc_nlen, par->nc_name);
3667 * Call VOP_NRESOLVE() to get the vp, then scan for any disconnected
3668 * ncp's and reattach them. If this occurs the original ncp is marked
3669 * EAGAIN to force a relookup.
3671 * NOTE: in order to call VOP_NRESOLVE(), the parent of the passed
3672 * ncp must already be resolved.
3677 ncp->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
3680 ncp->nc_error = EPERM;
3682 if (ncp->nc_error == EAGAIN) {
3683 kprintf("[diagnostic] cache_resolve: EAGAIN ncp %p %*.*s\n",
3684 ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
3687 return(ncp->nc_error);
3691 * Resolve the ncp associated with a mount point. Such ncp's almost always
3692 * remain resolved and this routine is rarely called. NFS MPs tends to force
3693 * re-resolution more often due to its mac-truck-smash-the-namecache
3694 * method of tracking namespace changes.
3696 * The semantics for this call is that the passed ncp must be locked on
3697 * entry and will be locked on return. However, if we actually have to
3698 * resolve the mount point we temporarily unlock the entry in order to
3699 * avoid race-to-root deadlocks due to e.g. dead NFS mounts. Because of
3700 * the unlock we have to recheck the flags after we relock.
3703 cache_resolve_mp(struct mount *mp)
3705 struct namecache *ncp = mp->mnt_ncmountpt.ncp;
3709 KKASSERT(mp != NULL);
3712 * If the ncp is already resolved we have nothing to do. However,
3713 * we do want to guarentee that a usable vnode is returned when
3714 * a vnode is present, so make sure it hasn't been reclaimed.
3716 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
3717 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
3718 _cache_setunresolved(ncp);
3721 if (ncp->nc_flag & NCF_UNRESOLVED) {
3723 while (vfs_busy(mp, 0))
3725 error = VFS_ROOT(mp, &vp);
3729 * recheck the ncp state after relocking.
3731 if (ncp->nc_flag & NCF_UNRESOLVED) {
3732 ncp->nc_error = error;
3734 _cache_setvp(mp, ncp, vp);
3737 kprintf("[diagnostic] cache_resolve_mp: failed"
3738 " to resolve mount %p err=%d ncp=%p\n",
3740 _cache_setvp(mp, ncp, NULL);
3742 } else if (error == 0) {
3747 return(ncp->nc_error);
3751 * Clean out negative cache entries when too many have accumulated.
3754 _cache_cleanneg(int count)
3756 struct namecache *ncp;
3759 * Attempt to clean out the specified number of negative cache
3763 spin_lock(&ncneg.spin);
3764 ncp = TAILQ_FIRST(&ncneg.list);
3766 spin_unlock(&ncneg.spin);
3769 TAILQ_REMOVE(&ncneg.list, ncp, nc_vnode);
3770 TAILQ_INSERT_TAIL(&ncneg.list, ncp, nc_vnode);
3772 spin_unlock(&ncneg.spin);
3775 * This can race, so we must re-check that the ncp
3776 * is on the ncneg.list after successfully locking it.
3778 if (_cache_lock_special(ncp) == 0) {
3779 if (ncp->nc_vp == NULL &&
3780 (ncp->nc_flag & NCF_UNRESOLVED) == 0) {
3781 ncp = cache_zap(ncp, 1);
3785 kprintf("cache_cleanneg: race avoided\n");
3796 * Clean out positive cache entries when too many have accumulated.
3799 _cache_cleanpos(int count)
3801 static volatile int rover;
3802 struct nchash_head *nchpp;
3803 struct namecache *ncp;
3807 * Attempt to clean out the specified number of negative cache
3811 rover_copy = ++rover; /* MPSAFEENOUGH */
3813 nchpp = NCHHASH(rover_copy);
3815 spin_lock_shared(&nchpp->spin);
3816 ncp = LIST_FIRST(&nchpp->list);
3817 while (ncp && (ncp->nc_flag & NCF_DESTROYED))
3818 ncp = LIST_NEXT(ncp, nc_hash);
3821 spin_unlock_shared(&nchpp->spin);
3824 if (_cache_lock_special(ncp) == 0) {
3825 ncp = cache_zap(ncp, 1);
3837 * This is a kitchen sink function to clean out ncps which we
3838 * tried to zap from cache_drop() but failed because we were
3839 * unable to acquire the parent lock.
3841 * Such entries can also be removed via cache_inval_vp(), such
3842 * as when unmounting.
3845 _cache_cleandefered(void)
3847 struct nchash_head *nchpp;
3848 struct namecache *ncp;
3849 struct namecache dummy;
3853 bzero(&dummy, sizeof(dummy));
3854 dummy.nc_flag = NCF_DESTROYED;
3857 for (i = 0; i <= nchash; ++i) {
3858 nchpp = &nchashtbl[i];
3860 spin_lock(&nchpp->spin);
3861 LIST_INSERT_HEAD(&nchpp->list, &dummy, nc_hash);
3863 while ((ncp = LIST_NEXT(ncp, nc_hash)) != NULL) {
3864 if ((ncp->nc_flag & NCF_DEFEREDZAP) == 0)
3866 LIST_REMOVE(&dummy, nc_hash);
3867 LIST_INSERT_AFTER(ncp, &dummy, nc_hash);
3869 spin_unlock(&nchpp->spin);
3870 if (_cache_lock_nonblock(ncp) == 0) {
3871 ncp->nc_flag &= ~NCF_DEFEREDZAP;
3875 spin_lock(&nchpp->spin);
3878 LIST_REMOVE(&dummy, nc_hash);
3879 spin_unlock(&nchpp->spin);
3884 * Name cache initialization, from vfsinit() when we are booting
3893 * Initialise per-cpu namecache effectiveness statistics.
3895 for (i = 0; i < ncpus; ++i) {
3896 gd = globaldata_find(i);
3897 gd->gd_nchstats = &nchstats[i];
3901 * Create a generous namecache hash table
3903 TAILQ_INIT(&ncneg.list);
3904 spin_init(&ncneg.spin, "nchinit");
3905 nchashtbl = hashinit_ext(vfs_inodehashsize(),
3906 sizeof(struct nchash_head),
3907 M_VFSCACHE, &nchash);
3908 for (i = 0; i <= (int)nchash; ++i) {
3909 LIST_INIT(&nchashtbl[i].list);
3910 spin_init(&nchashtbl[i].spin, "nchinit_hash");
3912 for (i = 0; i < NCMOUNT_NUMCACHE; ++i)
3913 spin_init(&ncmount_cache[i].spin, "nchinit_cache");
3914 nclockwarn = 5 * hz;
3918 * Called from start_init() to bootstrap the root filesystem. Returns
3919 * a referenced, unlocked namecache record.
3922 cache_allocroot(struct nchandle *nch, struct mount *mp, struct vnode *vp)
3924 nch->ncp = cache_alloc(0);
3928 _cache_setvp(nch->mount, nch->ncp, vp);
3932 * vfs_cache_setroot()
3934 * Create an association between the root of our namecache and
3935 * the root vnode. This routine may be called several times during
3938 * If the caller intends to save the returned namecache pointer somewhere
3939 * it must cache_hold() it.
3942 vfs_cache_setroot(struct vnode *nvp, struct nchandle *nch)
3945 struct nchandle onch;
3953 cache_zero(&rootnch);
3961 * XXX OLD API COMPAT FUNCTION. This really messes up the new namecache
3962 * topology and is being removed as quickly as possible. The new VOP_N*()
3963 * API calls are required to make specific adjustments using the supplied
3964 * ncp pointers rather then just bogusly purging random vnodes.
3966 * Invalidate all namecache entries to a particular vnode as well as
3967 * any direct children of that vnode in the namecache. This is a
3968 * 'catch all' purge used by filesystems that do not know any better.
3970 * Note that the linkage between the vnode and its namecache entries will
3971 * be removed, but the namecache entries themselves might stay put due to
3972 * active references from elsewhere in the system or due to the existance of
3973 * the children. The namecache topology is left intact even if we do not
3974 * know what the vnode association is. Such entries will be marked
3978 cache_purge(struct vnode *vp)
3980 cache_inval_vp(vp, CINV_DESTROY | CINV_CHILDREN);
3983 static int disablecwd;
3984 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0,
3987 static u_long numcwdcalls;
3988 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdcalls, CTLFLAG_RD, &numcwdcalls, 0,
3989 "Number of current directory resolution calls");
3990 static u_long numcwdfailnf;
3991 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfailnf, CTLFLAG_RD, &numcwdfailnf, 0,
3992 "Number of current directory failures due to lack of file");
3993 static u_long numcwdfailsz;
3994 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfailsz, CTLFLAG_RD, &numcwdfailsz, 0,
3995 "Number of current directory failures due to large result");
3996 static u_long numcwdfound;
3997 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfound, CTLFLAG_RD, &numcwdfound, 0,
3998 "Number of current directory resolution successes");
4004 sys___getcwd(struct __getcwd_args *uap)
4014 buflen = uap->buflen;
4017 if (buflen > MAXPATHLEN)
4018 buflen = MAXPATHLEN;
4020 buf = kmalloc(buflen, M_TEMP, M_WAITOK);
4021 bp = kern_getcwd(buf, buflen, &error);
4023 error = copyout(bp, uap->buf, strlen(bp) + 1);
4029 kern_getcwd(char *buf, size_t buflen, int *error)
4031 struct proc *p = curproc;
4033 int i, slash_prefixed;
4034 struct filedesc *fdp;
4035 struct nchandle nch;
4036 struct namecache *ncp;
4045 nch = fdp->fd_ncdir;
4050 while (ncp && (ncp != fdp->fd_nrdir.ncp ||
4051 nch.mount != fdp->fd_nrdir.mount)
4054 * While traversing upwards if we encounter the root
4055 * of the current mount we have to skip to the mount point
4056 * in the underlying filesystem.
4058 if (ncp == nch.mount->mnt_ncmountpt.ncp) {
4059 nch = nch.mount->mnt_ncmounton;
4068 * Prepend the path segment
4070 for (i = ncp->nc_nlen - 1; i >= 0; i--) {
4077 *--bp = ncp->nc_name[i];
4089 * Go up a directory. This isn't a mount point so we don't
4090 * have to check again.
4092 while ((nch.ncp = ncp->nc_parent) != NULL) {
4093 if (ncp_shared_lock_disable)
4096 _cache_lock_shared(ncp);
4097 if (nch.ncp != ncp->nc_parent) {
4101 _cache_hold(nch.ncp);
4114 if (!slash_prefixed) {
4132 * Thus begins the fullpath magic.
4134 * The passed nchp is referenced but not locked.
4136 static int disablefullpath;
4137 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW,
4138 &disablefullpath, 0,
4139 "Disable fullpath lookups");
4141 static u_int numfullpathcalls;
4142 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathcalls, CTLFLAG_RD,
4143 &numfullpathcalls, 0,
4144 "Number of full path resolutions in progress");
4145 static u_int numfullpathfailnf;
4146 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathfailnf, CTLFLAG_RD,
4147 &numfullpathfailnf, 0,
4148 "Number of full path resolution failures due to lack of file");
4149 static u_int numfullpathfailsz;
4150 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathfailsz, CTLFLAG_RD,
4151 &numfullpathfailsz, 0,
4152 "Number of full path resolution failures due to insufficient memory");
4153 static u_int numfullpathfound;
4154 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathfound, CTLFLAG_RD,
4155 &numfullpathfound, 0,
4156 "Number of full path resolution successes");
4159 cache_fullpath(struct proc *p, struct nchandle *nchp, struct nchandle *nchbase,
4160 char **retbuf, char **freebuf, int guess)
4162 struct nchandle fd_nrdir;
4163 struct nchandle nch;
4164 struct namecache *ncp;
4165 struct mount *mp, *new_mp;
4171 atomic_add_int(&numfullpathcalls, -1);
4176 buf = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
4177 bp = buf + MAXPATHLEN - 1;
4180 fd_nrdir = *nchbase;
4182 fd_nrdir = p->p_fd->fd_nrdir;
4192 while (ncp && (ncp != fd_nrdir.ncp || mp != fd_nrdir.mount)) {
4196 * If we are asked to guess the upwards path, we do so whenever
4197 * we encounter an ncp marked as a mountpoint. We try to find
4198 * the actual mountpoint by finding the mountpoint with this
4201 if (guess && (ncp->nc_flag & NCF_ISMOUNTPT)) {
4202 new_mp = mount_get_by_nc(ncp);
4205 * While traversing upwards if we encounter the root
4206 * of the current mount we have to skip to the mount point.
4208 if (ncp == mp->mnt_ncmountpt.ncp) {
4212 nch = new_mp->mnt_ncmounton;
4222 * Prepend the path segment
4224 for (i = ncp->nc_nlen - 1; i >= 0; i--) {
4226 numfullpathfailsz++;
4231 *--bp = ncp->nc_name[i];
4234 numfullpathfailsz++;
4243 * Go up a directory. This isn't a mount point so we don't
4244 * have to check again.
4246 * We can only safely access nc_parent with ncp held locked.
4248 while ((nch.ncp = ncp->nc_parent) != NULL) {
4250 if (nch.ncp != ncp->nc_parent) {
4254 _cache_hold(nch.ncp);
4262 numfullpathfailnf++;
4268 if (!slash_prefixed) {
4270 numfullpathfailsz++;
4288 vn_fullpath(struct proc *p, struct vnode *vn, char **retbuf,
4289 char **freebuf, int guess)
4291 struct namecache *ncp;
4292 struct nchandle nch;
4296 atomic_add_int(&numfullpathcalls, 1);
4297 if (disablefullpath)
4303 /* vn is NULL, client wants us to use p->p_textvp */
4305 if ((vn = p->p_textvp) == NULL)
4308 spin_lock_shared(&vn->v_spin);
4309 TAILQ_FOREACH(ncp, &vn->v_namecache, nc_vnode) {
4314 spin_unlock_shared(&vn->v_spin);
4318 spin_unlock_shared(&vn->v_spin);
4320 atomic_add_int(&numfullpathcalls, -1);
4322 nch.mount = vn->v_mount;
4323 error = cache_fullpath(p, &nch, NULL, retbuf, freebuf, guess);