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 * 4. 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>
86 #include <sys/mplock2.h>
88 #define MAX_RECURSION_DEPTH 64
91 * Random lookups in the cache are accomplished with a hash table using
92 * a hash key of (nc_src_vp, name). Each hash chain has its own spin lock.
94 * Negative entries may exist and correspond to resolved namecache
95 * structures where nc_vp is NULL. In a negative entry, NCF_WHITEOUT
96 * will be set if the entry corresponds to a whited-out directory entry
97 * (verses simply not finding the entry at all). ncneglist is locked
98 * with a global spinlock (ncspin).
102 * (1) A ncp must be referenced before it can be locked.
104 * (2) A ncp must be locked in order to modify it.
106 * (3) ncp locks are always ordered child -> parent. That may seem
107 * backwards but forward scans use the hash table and thus can hold
108 * the parent unlocked when traversing downward.
110 * This allows insert/rename/delete/dot-dot and other operations
111 * to use ncp->nc_parent links.
113 * This also prevents a locked up e.g. NFS node from creating a
114 * chain reaction all the way back to the root vnode / namecache.
116 * (4) parent linkages require both the parent and child to be locked.
120 * Structures associated with name cacheing.
122 #define NCHHASH(hash) (&nchashtbl[(hash) & nchash])
125 #define NCMOUNT_NUMCACHE 1009 /* prime number */
127 MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
129 LIST_HEAD(nchash_list, namecache);
132 struct nchash_list list;
133 struct spinlock spin;
136 struct ncmount_cache {
137 struct spinlock spin;
138 struct namecache *ncp;
140 int isneg; /* if != 0 mp is originator and not target */
143 static struct nchash_head *nchashtbl;
144 static struct namecache_list ncneglist;
145 static struct spinlock ncspin;
146 static struct ncmount_cache ncmount_cache[NCMOUNT_NUMCACHE];
149 * ncvp_debug - debug cache_fromvp(). This is used by the NFS server
150 * to create the namecache infrastructure leading to a dangling vnode.
152 * 0 Only errors are reported
153 * 1 Successes are reported
154 * 2 Successes + the whole directory scan is reported
155 * 3 Force the directory scan code run as if the parent vnode did not
156 * have a namecache record, even if it does have one.
158 static int ncvp_debug;
159 SYSCTL_INT(_debug, OID_AUTO, ncvp_debug, CTLFLAG_RW, &ncvp_debug, 0,
160 "Namecache debug level (0-3)");
162 static u_long nchash; /* size of hash table */
163 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
164 "Size of namecache hash table");
166 static int ncnegflush = 10; /* burst for negative flush */
167 SYSCTL_INT(_debug, OID_AUTO, ncnegflush, CTLFLAG_RW, &ncnegflush, 0,
168 "Batch flush negative entries");
170 static int ncposflush = 10; /* burst for positive flush */
171 SYSCTL_INT(_debug, OID_AUTO, ncposflush, CTLFLAG_RW, &ncposflush, 0,
172 "Batch flush positive entries");
174 static int ncnegfactor = 16; /* ratio of negative entries */
175 SYSCTL_INT(_debug, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0,
176 "Ratio of namecache negative entries");
178 static int nclockwarn; /* warn on locked entries in ticks */
179 SYSCTL_INT(_debug, OID_AUTO, nclockwarn, CTLFLAG_RW, &nclockwarn, 0,
180 "Warn on locked namecache entries in ticks");
182 static int numdefered; /* number of cache entries allocated */
183 SYSCTL_INT(_debug, OID_AUTO, numdefered, CTLFLAG_RD, &numdefered, 0,
184 "Number of cache entries allocated");
186 static int ncposlimit; /* number of cache entries allocated */
187 SYSCTL_INT(_debug, OID_AUTO, ncposlimit, CTLFLAG_RW, &ncposlimit, 0,
188 "Number of cache entries allocated");
190 static int ncp_shared_lock_disable = 1;
191 SYSCTL_INT(_debug, OID_AUTO, ncp_shared_lock_disable, CTLFLAG_RW,
192 &ncp_shared_lock_disable, 0, "Disable shared namecache locks");
194 SYSCTL_INT(_debug, OID_AUTO, vnsize, CTLFLAG_RD, 0, sizeof(struct vnode),
195 "sizeof(struct vnode)");
196 SYSCTL_INT(_debug, OID_AUTO, ncsize, CTLFLAG_RD, 0, sizeof(struct namecache),
197 "sizeof(struct namecache)");
199 static int ncmount_cache_enable = 1;
200 SYSCTL_INT(_debug, OID_AUTO, ncmount_cache_enable, CTLFLAG_RW,
201 &ncmount_cache_enable, 0, "mount point cache");
202 static long ncmount_cache_hit;
203 SYSCTL_LONG(_debug, OID_AUTO, ncmount_cache_hit, CTLFLAG_RW,
204 &ncmount_cache_hit, 0, "mpcache hits");
205 static long ncmount_cache_miss;
206 SYSCTL_LONG(_debug, OID_AUTO, ncmount_cache_miss, CTLFLAG_RW,
207 &ncmount_cache_miss, 0, "mpcache misses");
208 static long ncmount_cache_overwrite;
209 SYSCTL_LONG(_debug, OID_AUTO, ncmount_cache_overwrite, CTLFLAG_RW,
210 &ncmount_cache_overwrite, 0, "mpcache entry overwrites");
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");
231 static u_long numcalls;
232 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcalls, CTLFLAG_RD, &numcalls, 0,
233 "Number of namecache lookups");
234 static u_long numchecks;
235 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numchecks, CTLFLAG_RD, &numchecks, 0,
236 "Number of checked entries in namecache lookups");
238 struct nchstats nchstats[SMP_MAXCPU];
240 * Export VFS cache effectiveness statistics to user-land.
242 * The statistics are left for aggregation to user-land so
243 * neat things can be achieved, like observing per-CPU cache
247 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
249 struct globaldata *gd;
253 for (i = 0; i < ncpus; ++i) {
254 gd = globaldata_find(i);
255 if ((error = SYSCTL_OUT(req, (void *)&(*gd->gd_nchstats),
256 sizeof(struct nchstats))))
262 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE|CTLFLAG_RD,
263 0, 0, sysctl_nchstats, "S,nchstats", "VFS cache effectiveness statistics");
265 static struct namecache *cache_zap(struct namecache *ncp, int nonblock);
268 * Namespace locking. The caller must already hold a reference to the
269 * namecache structure in order to lock/unlock it. This function prevents
270 * the namespace from being created or destroyed by accessors other then
273 * Note that holding a locked namecache structure prevents other threads
274 * from making namespace changes (e.g. deleting or creating), prevents
275 * vnode association state changes by other threads, and prevents the
276 * namecache entry from being resolved or unresolved by other threads.
278 * An exclusive lock owner has full authority to associate/disassociate
279 * vnodes and resolve/unresolve the locked ncp.
281 * A shared lock owner only has authority to acquire the underlying vnode,
284 * The primary lock field is nc_lockstatus. nc_locktd is set after the
285 * fact (when locking) or cleared prior to unlocking.
287 * WARNING! Holding a locked ncp will prevent a vnode from being destroyed
288 * or recycled, but it does NOT help you if the vnode had already
289 * initiated a recyclement. If this is important, use cache_get()
290 * rather then cache_lock() (and deal with the differences in the
291 * way the refs counter is handled). Or, alternatively, make an
292 * unconditional call to cache_validate() or cache_resolve()
293 * after cache_lock() returns.
297 _cache_lock(struct namecache *ncp)
304 KKASSERT(ncp->nc_refs != 0);
309 count = ncp->nc_lockstatus;
312 if ((count & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 0) {
313 if (atomic_cmpset_int(&ncp->nc_lockstatus,
316 * The vp associated with a locked ncp must
317 * be held to prevent it from being recycled.
319 * WARNING! If VRECLAIMED is set the vnode
320 * could already be in the middle of a recycle.
321 * Callers must use cache_vref() or
322 * cache_vget() on the locked ncp to
323 * validate the vp or set the cache entry
326 * NOTE! vhold() is allowed if we hold a
327 * lock on the ncp (which we do).
337 if (ncp->nc_locktd == td) {
338 KKASSERT((count & NC_SHLOCK_FLAG) == 0);
339 if (atomic_cmpset_int(&ncp->nc_lockstatus,
346 tsleep_interlock(&ncp->nc_locktd, 0);
347 if (atomic_cmpset_int(&ncp->nc_lockstatus, count,
348 count | NC_EXLOCK_REQ) == 0) {
352 error = tsleep(&ncp->nc_locktd, PINTERLOCKED,
353 "clock", nclockwarn);
354 if (error == EWOULDBLOCK) {
357 kprintf("[diagnostic] cache_lock: "
358 "blocked on %p %08x",
360 kprintf(" \"%*.*s\"\n",
361 ncp->nc_nlen, ncp->nc_nlen,
368 kprintf("[diagnostic] cache_lock: unblocked %*.*s after "
370 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name,
371 (int)(ticks - didwarn) / hz);
376 * The shared lock works similarly to the exclusive lock except
377 * nc_locktd is left NULL and we need an interlock (VHOLD) to
378 * prevent vhold() races, since the moment our cmpset_int succeeds
379 * another cpu can come in and get its own shared lock.
381 * A critical section is needed to prevent interruption during the
386 _cache_lock_shared(struct namecache *ncp)
392 KKASSERT(ncp->nc_refs != 0);
396 count = ncp->nc_lockstatus;
399 if ((count & ~NC_SHLOCK_REQ) == 0) {
401 if (atomic_cmpset_int(&ncp->nc_lockstatus,
403 (count + 1) | NC_SHLOCK_FLAG |
406 * The vp associated with a locked ncp must
407 * be held to prevent it from being recycled.
409 * WARNING! If VRECLAIMED is set the vnode
410 * could already be in the middle of a recycle.
411 * Callers must use cache_vref() or
412 * cache_vget() on the locked ncp to
413 * validate the vp or set the cache entry
416 * NOTE! vhold() is allowed if we hold a
417 * lock on the ncp (which we do).
421 atomic_clear_int(&ncp->nc_lockstatus,
432 * If already held shared we can just bump the count, but
433 * only allow this if nobody is trying to get the lock
436 * VHOLD is a bit of a hack. Even though we successfully
437 * added another shared ref, the cpu that got the first
438 * shared ref might not yet have held the vnode.
440 if ((count & (NC_EXLOCK_REQ|NC_SHLOCK_FLAG)) ==
442 KKASSERT((count & ~(NC_EXLOCK_REQ |
444 NC_SHLOCK_FLAG)) > 0);
445 if (atomic_cmpset_int(&ncp->nc_lockstatus,
447 while (ncp->nc_lockstatus & NC_SHLOCK_VHOLD)
453 tsleep_interlock(ncp, 0);
454 if (atomic_cmpset_int(&ncp->nc_lockstatus, count,
455 count | NC_SHLOCK_REQ) == 0) {
459 error = tsleep(ncp, PINTERLOCKED, "clocksh", nclockwarn);
460 if (error == EWOULDBLOCK) {
463 kprintf("[diagnostic] cache_lock_shared: "
464 "blocked on %p %08x",
466 kprintf(" \"%*.*s\"\n",
467 ncp->nc_nlen, ncp->nc_nlen,
474 kprintf("[diagnostic] cache_lock_shared: "
475 "unblocked %*.*s after %d secs\n",
476 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name,
477 (int)(ticks - didwarn) / hz);
482 * NOTE: nc_refs may be zero if the ncp is interlocked by circumstance,
483 * such as the case where one of its children is locked.
487 _cache_lock_nonblock(struct namecache *ncp)
495 count = ncp->nc_lockstatus;
497 if ((count & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 0) {
498 if (atomic_cmpset_int(&ncp->nc_lockstatus,
501 * The vp associated with a locked ncp must
502 * be held to prevent it from being recycled.
504 * WARNING! If VRECLAIMED is set the vnode
505 * could already be in the middle of a recycle.
506 * Callers must use cache_vref() or
507 * cache_vget() on the locked ncp to
508 * validate the vp or set the cache entry
511 * NOTE! vhold() is allowed if we hold a
512 * lock on the ncp (which we do).
522 if (ncp->nc_locktd == td) {
523 if (atomic_cmpset_int(&ncp->nc_lockstatus,
536 * The shared lock works similarly to the exclusive lock except
537 * nc_locktd is left NULL and we need an interlock (VHOLD) to
538 * prevent vhold() races, since the moment our cmpset_int succeeds
539 * another cpu can come in and get its own shared lock.
541 * A critical section is needed to prevent interruption during the
546 _cache_lock_shared_nonblock(struct namecache *ncp)
551 count = ncp->nc_lockstatus;
553 if ((count & ~NC_SHLOCK_REQ) == 0) {
555 if (atomic_cmpset_int(&ncp->nc_lockstatus,
557 (count + 1) | NC_SHLOCK_FLAG |
560 * The vp associated with a locked ncp must
561 * be held to prevent it from being recycled.
563 * WARNING! If VRECLAIMED is set the vnode
564 * could already be in the middle of a recycle.
565 * Callers must use cache_vref() or
566 * cache_vget() on the locked ncp to
567 * validate the vp or set the cache entry
570 * NOTE! vhold() is allowed if we hold a
571 * lock on the ncp (which we do).
575 atomic_clear_int(&ncp->nc_lockstatus,
586 * If already held shared we can just bump the count, but
587 * only allow this if nobody is trying to get the lock
590 * VHOLD is a bit of a hack. Even though we successfully
591 * added another shared ref, the cpu that got the first
592 * shared ref might not yet have held the vnode.
594 if ((count & (NC_EXLOCK_REQ|NC_SHLOCK_FLAG)) ==
596 KKASSERT((count & ~(NC_EXLOCK_REQ |
598 NC_SHLOCK_FLAG)) > 0);
599 if (atomic_cmpset_int(&ncp->nc_lockstatus,
601 while (ncp->nc_lockstatus & NC_SHLOCK_VHOLD)
615 * NOTE: nc_refs can be 0 (degenerate case during _cache_drop).
617 * nc_locktd must be NULLed out prior to nc_lockstatus getting cleared.
621 _cache_unlock(struct namecache *ncp)
623 thread_t td __debugvar = curthread;
626 struct vnode *dropvp;
628 KKASSERT(ncp->nc_refs >= 0);
629 KKASSERT((ncp->nc_lockstatus & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) > 0);
630 KKASSERT((ncp->nc_lockstatus & NC_SHLOCK_FLAG) || ncp->nc_locktd == td);
632 count = ncp->nc_lockstatus;
636 * Clear nc_locktd prior to the atomic op (excl lock only)
638 if ((count & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 1)
639 ncp->nc_locktd = NULL;
644 ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ|NC_SHLOCK_FLAG)) == 1) {
646 if (count & NC_EXLOCK_REQ)
647 ncount = count & NC_SHLOCK_REQ; /* cnt->0 */
651 if (atomic_cmpset_int(&ncp->nc_lockstatus,
653 if (count & NC_EXLOCK_REQ)
654 wakeup(&ncp->nc_locktd);
655 else if (count & NC_SHLOCK_REQ)
661 KKASSERT((count & NC_SHLOCK_VHOLD) == 0);
662 KKASSERT((count & ~(NC_EXLOCK_REQ |
664 NC_SHLOCK_FLAG)) > 1);
665 if (atomic_cmpset_int(&ncp->nc_lockstatus,
670 count = ncp->nc_lockstatus;
675 * Don't actually drop the vp until we successfully clean out
676 * the lock, otherwise we may race another shared lock.
684 _cache_lockstatus(struct namecache *ncp)
686 if (ncp->nc_locktd == curthread)
687 return(LK_EXCLUSIVE);
688 if (ncp->nc_lockstatus & NC_SHLOCK_FLAG)
694 * cache_hold() and cache_drop() prevent the premature deletion of a
695 * namecache entry but do not prevent operations (such as zapping) on
696 * that namecache entry.
698 * This routine may only be called from outside this source module if
699 * nc_refs is already at least 1.
701 * This is a rare case where callers are allowed to hold a spinlock,
702 * so we can't ourselves.
706 _cache_hold(struct namecache *ncp)
708 atomic_add_int(&ncp->nc_refs, 1);
713 * Drop a cache entry, taking care to deal with races.
715 * For potential 1->0 transitions we must hold the ncp lock to safely
716 * test its flags. An unresolved entry with no children must be zapped
719 * The call to cache_zap() itself will handle all remaining races and
720 * will decrement the ncp's refs regardless. If we are resolved or
721 * have children nc_refs can safely be dropped to 0 without having to
724 * NOTE: cache_zap() will re-check nc_refs and nc_list in a MPSAFE fashion.
726 * NOTE: cache_zap() may return a non-NULL referenced parent which must
727 * be dropped in a loop.
731 _cache_drop(struct namecache *ncp)
736 KKASSERT(ncp->nc_refs > 0);
740 if (_cache_lock_nonblock(ncp) == 0) {
741 ncp->nc_flag &= ~NCF_DEFEREDZAP;
742 if ((ncp->nc_flag & NCF_UNRESOLVED) &&
743 TAILQ_EMPTY(&ncp->nc_list)) {
744 ncp = cache_zap(ncp, 1);
747 if (atomic_cmpset_int(&ncp->nc_refs, 1, 0)) {
754 if (atomic_cmpset_int(&ncp->nc_refs, refs, refs - 1))
762 * Link a new namecache entry to its parent and to the hash table. Be
763 * careful to avoid races if vhold() blocks in the future.
765 * Both ncp and par must be referenced and locked.
767 * NOTE: The hash table spinlock is held during this call, we can't do
771 _cache_link_parent(struct namecache *ncp, struct namecache *par,
772 struct nchash_head *nchpp)
774 KKASSERT(ncp->nc_parent == NULL);
775 ncp->nc_parent = par;
776 ncp->nc_head = nchpp;
779 * Set inheritance flags. Note that the parent flags may be
780 * stale due to getattr potentially not having been run yet
781 * (it gets run during nlookup()'s).
783 ncp->nc_flag &= ~(NCF_SF_PNOCACHE | NCF_UF_PCACHE);
784 if (par->nc_flag & (NCF_SF_NOCACHE | NCF_SF_PNOCACHE))
785 ncp->nc_flag |= NCF_SF_PNOCACHE;
786 if (par->nc_flag & (NCF_UF_CACHE | NCF_UF_PCACHE))
787 ncp->nc_flag |= NCF_UF_PCACHE;
789 LIST_INSERT_HEAD(&nchpp->list, ncp, nc_hash);
791 if (TAILQ_EMPTY(&par->nc_list)) {
792 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
794 * Any vp associated with an ncp which has children must
795 * be held to prevent it from being recycled.
800 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
805 * Remove the parent and hash associations from a namecache structure.
806 * If this is the last child of the parent the cache_drop(par) will
807 * attempt to recursively zap the parent.
809 * ncp must be locked. This routine will acquire a temporary lock on
810 * the parent as wlel as the appropriate hash chain.
813 _cache_unlink_parent(struct namecache *ncp)
815 struct namecache *par;
816 struct vnode *dropvp;
818 if ((par = ncp->nc_parent) != NULL) {
819 KKASSERT(ncp->nc_parent == par);
822 spin_lock(&ncp->nc_head->spin);
823 LIST_REMOVE(ncp, nc_hash);
824 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
826 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
828 spin_unlock(&ncp->nc_head->spin);
829 ncp->nc_parent = NULL;
835 * We can only safely vdrop with no spinlocks held.
843 * Allocate a new namecache structure. Most of the code does not require
844 * zero-termination of the string but it makes vop_compat_ncreate() easier.
846 static struct namecache *
847 cache_alloc(int nlen)
849 struct namecache *ncp;
851 ncp = kmalloc(sizeof(*ncp), M_VFSCACHE, M_WAITOK|M_ZERO);
853 ncp->nc_name = kmalloc(nlen + 1, M_VFSCACHE, M_WAITOK);
855 ncp->nc_flag = NCF_UNRESOLVED;
856 ncp->nc_error = ENOTCONN; /* needs to be resolved */
859 TAILQ_INIT(&ncp->nc_list);
865 * Can only be called for the case where the ncp has never been
866 * associated with anything (so no spinlocks are needed).
869 _cache_free(struct namecache *ncp)
871 KKASSERT(ncp->nc_refs == 1 && ncp->nc_lockstatus == 1);
873 kfree(ncp->nc_name, M_VFSCACHE);
874 kfree(ncp, M_VFSCACHE);
878 * [re]initialize a nchandle.
881 cache_zero(struct nchandle *nch)
888 * Ref and deref a namecache structure.
890 * The caller must specify a stable ncp pointer, typically meaning the
891 * ncp is already referenced but this can also occur indirectly through
892 * e.g. holding a lock on a direct child.
894 * WARNING: Caller may hold an unrelated read spinlock, which means we can't
895 * use read spinlocks here.
900 cache_hold(struct nchandle *nch)
902 _cache_hold(nch->ncp);
903 atomic_add_int(&nch->mount->mnt_refs, 1);
908 * Create a copy of a namecache handle for an already-referenced
914 cache_copy(struct nchandle *nch, struct nchandle *target)
918 _cache_hold(target->ncp);
919 atomic_add_int(&nch->mount->mnt_refs, 1);
926 cache_changemount(struct nchandle *nch, struct mount *mp)
928 atomic_add_int(&nch->mount->mnt_refs, -1);
930 atomic_add_int(&nch->mount->mnt_refs, 1);
934 cache_drop(struct nchandle *nch)
936 atomic_add_int(&nch->mount->mnt_refs, -1);
937 _cache_drop(nch->ncp);
943 cache_lockstatus(struct nchandle *nch)
945 return(_cache_lockstatus(nch->ncp));
949 cache_lock(struct nchandle *nch)
951 _cache_lock(nch->ncp);
955 cache_lock_maybe_shared(struct nchandle *nch, int excl)
957 struct namecache *ncp = nch->ncp;
959 if (ncp_shared_lock_disable || excl ||
960 (ncp->nc_flag & NCF_UNRESOLVED)) {
963 _cache_lock_shared(ncp);
964 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
965 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED)) {
977 * Relock nch1 given an unlocked nch1 and a locked nch2. The caller
978 * is responsible for checking both for validity on return as they
979 * may have become invalid.
981 * We have to deal with potential deadlocks here, just ping pong
982 * the lock until we get it (we will always block somewhere when
983 * looping so this is not cpu-intensive).
985 * which = 0 nch1 not locked, nch2 is locked
986 * which = 1 nch1 is locked, nch2 is not locked
989 cache_relock(struct nchandle *nch1, struct ucred *cred1,
990 struct nchandle *nch2, struct ucred *cred2)
998 if (cache_lock_nonblock(nch1) == 0) {
999 cache_resolve(nch1, cred1);
1004 cache_resolve(nch1, cred1);
1007 if (cache_lock_nonblock(nch2) == 0) {
1008 cache_resolve(nch2, cred2);
1013 cache_resolve(nch2, cred2);
1020 cache_lock_nonblock(struct nchandle *nch)
1022 return(_cache_lock_nonblock(nch->ncp));
1026 cache_unlock(struct nchandle *nch)
1028 _cache_unlock(nch->ncp);
1032 * ref-and-lock, unlock-and-deref functions.
1034 * This function is primarily used by nlookup. Even though cache_lock
1035 * holds the vnode, it is possible that the vnode may have already
1036 * initiated a recyclement.
1038 * We want cache_get() to return a definitively usable vnode or a
1039 * definitively unresolved ncp.
1043 _cache_get(struct namecache *ncp)
1047 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
1048 _cache_setunresolved(ncp);
1053 * Attempt to obtain a shared lock on the ncp. A shared lock will only
1054 * be obtained if the ncp is resolved and the vnode (if not ENOENT) is
1055 * valid. Otherwise an exclusive lock will be acquired instead.
1059 _cache_get_maybe_shared(struct namecache *ncp, int excl)
1061 if (ncp_shared_lock_disable || excl ||
1062 (ncp->nc_flag & NCF_UNRESOLVED)) {
1063 return(_cache_get(ncp));
1066 _cache_lock_shared(ncp);
1067 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1068 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED)) {
1070 ncp = _cache_get(ncp);
1075 ncp = _cache_get(ncp);
1082 * This is a special form of _cache_lock() which only succeeds if
1083 * it can get a pristine, non-recursive lock. The caller must have
1084 * already ref'd the ncp.
1086 * On success the ncp will be locked, on failure it will not. The
1087 * ref count does not change either way.
1089 * We want _cache_lock_special() (on success) to return a definitively
1090 * usable vnode or a definitively unresolved ncp.
1093 _cache_lock_special(struct namecache *ncp)
1095 if (_cache_lock_nonblock(ncp) == 0) {
1096 if ((ncp->nc_lockstatus &
1097 ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 1) {
1098 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
1099 _cache_setunresolved(ncp);
1104 return(EWOULDBLOCK);
1108 _cache_lock_shared_special(struct namecache *ncp)
1110 if (_cache_lock_shared_nonblock(ncp) == 0) {
1111 if ((ncp->nc_lockstatus &
1112 ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == (NC_SHLOCK_FLAG | 1)) {
1113 if (ncp->nc_vp == NULL ||
1114 (ncp->nc_vp->v_flag & VRECLAIMED) == 0) {
1120 return(EWOULDBLOCK);
1125 * NOTE: The same nchandle can be passed for both arguments.
1128 cache_get(struct nchandle *nch, struct nchandle *target)
1130 KKASSERT(nch->ncp->nc_refs > 0);
1131 target->mount = nch->mount;
1132 target->ncp = _cache_get(nch->ncp);
1133 atomic_add_int(&target->mount->mnt_refs, 1);
1137 cache_get_maybe_shared(struct nchandle *nch, struct nchandle *target, int excl)
1139 KKASSERT(nch->ncp->nc_refs > 0);
1140 target->mount = nch->mount;
1141 target->ncp = _cache_get_maybe_shared(nch->ncp, excl);
1142 atomic_add_int(&target->mount->mnt_refs, 1);
1150 _cache_put(struct namecache *ncp)
1160 cache_put(struct nchandle *nch)
1162 atomic_add_int(&nch->mount->mnt_refs, -1);
1163 _cache_put(nch->ncp);
1169 * Resolve an unresolved ncp by associating a vnode with it. If the
1170 * vnode is NULL, a negative cache entry is created.
1172 * The ncp should be locked on entry and will remain locked on return.
1176 _cache_setvp(struct mount *mp, struct namecache *ncp, struct vnode *vp)
1178 KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
1179 KKASSERT(_cache_lockstatus(ncp) == LK_EXCLUSIVE);
1183 * Any vp associated with an ncp which has children must
1184 * be held. Any vp associated with a locked ncp must be held.
1186 if (!TAILQ_EMPTY(&ncp->nc_list))
1188 spin_lock(&vp->v_spin);
1190 TAILQ_INSERT_HEAD(&vp->v_namecache, ncp, nc_vnode);
1191 spin_unlock(&vp->v_spin);
1192 if (ncp->nc_lockstatus & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ))
1196 * Set auxiliary flags
1198 switch(vp->v_type) {
1200 ncp->nc_flag |= NCF_ISDIR;
1203 ncp->nc_flag |= NCF_ISSYMLINK;
1204 /* XXX cache the contents of the symlink */
1209 atomic_add_int(&numcache, 1);
1211 /* XXX: this is a hack to work-around the lack of a real pfs vfs
1214 if (strncmp(mp->mnt_stat.f_fstypename, "null", 5) == 0)
1218 * When creating a negative cache hit we set the
1219 * namecache_gen. A later resolve will clean out the
1220 * negative cache hit if the mount point's namecache_gen
1221 * has changed. Used by devfs, could also be used by
1226 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
1228 spin_unlock(&ncspin);
1229 ncp->nc_error = ENOENT;
1231 VFS_NCPGEN_SET(mp, ncp);
1233 ncp->nc_flag &= ~(NCF_UNRESOLVED | NCF_DEFEREDZAP);
1240 cache_setvp(struct nchandle *nch, struct vnode *vp)
1242 _cache_setvp(nch->mount, nch->ncp, vp);
1249 cache_settimeout(struct nchandle *nch, int nticks)
1251 struct namecache *ncp = nch->ncp;
1253 if ((ncp->nc_timeout = ticks + nticks) == 0)
1254 ncp->nc_timeout = 1;
1258 * Disassociate the vnode or negative-cache association and mark a
1259 * namecache entry as unresolved again. Note that the ncp is still
1260 * left in the hash table and still linked to its parent.
1262 * The ncp should be locked and refd on entry and will remain locked and refd
1265 * This routine is normally never called on a directory containing children.
1266 * However, NFS often does just that in its rename() code as a cop-out to
1267 * avoid complex namespace operations. This disconnects a directory vnode
1268 * from its namecache and can cause the OLDAPI and NEWAPI to get out of
1274 _cache_setunresolved(struct namecache *ncp)
1278 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1279 ncp->nc_flag |= NCF_UNRESOLVED;
1280 ncp->nc_timeout = 0;
1281 ncp->nc_error = ENOTCONN;
1282 if ((vp = ncp->nc_vp) != NULL) {
1283 atomic_add_int(&numcache, -1);
1284 spin_lock(&vp->v_spin);
1286 TAILQ_REMOVE(&vp->v_namecache, ncp, nc_vnode);
1287 spin_unlock(&vp->v_spin);
1290 * Any vp associated with an ncp with children is
1291 * held by that ncp. Any vp associated with a locked
1292 * ncp is held by that ncp. These conditions must be
1293 * undone when the vp is cleared out from the ncp.
1295 if (!TAILQ_EMPTY(&ncp->nc_list))
1297 if (ncp->nc_lockstatus & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ))
1301 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
1303 spin_unlock(&ncspin);
1305 ncp->nc_flag &= ~(NCF_WHITEOUT|NCF_ISDIR|NCF_ISSYMLINK);
1310 * The cache_nresolve() code calls this function to automatically
1311 * set a resolved cache element to unresolved if it has timed out
1312 * or if it is a negative cache hit and the mount point namecache_gen
1316 _cache_auto_unresolve_test(struct mount *mp, struct namecache *ncp)
1319 * Try to zap entries that have timed out. We have
1320 * to be careful here because locked leafs may depend
1321 * on the vnode remaining intact in a parent, so only
1322 * do this under very specific conditions.
1324 if (ncp->nc_timeout && (int)(ncp->nc_timeout - ticks) < 0 &&
1325 TAILQ_EMPTY(&ncp->nc_list)) {
1330 * If a resolved negative cache hit is invalid due to
1331 * the mount's namecache generation being bumped, zap it.
1333 if (ncp->nc_vp == NULL && VFS_NCPGEN_TEST(mp, ncp)) {
1338 * Otherwise we are good
1343 static __inline void
1344 _cache_auto_unresolve(struct mount *mp, struct namecache *ncp)
1347 * Already in an unresolved state, nothing to do.
1349 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1350 if (_cache_auto_unresolve_test(mp, ncp))
1351 _cache_setunresolved(ncp);
1359 cache_setunresolved(struct nchandle *nch)
1361 _cache_setunresolved(nch->ncp);
1365 * Determine if we can clear NCF_ISMOUNTPT by scanning the mountlist
1366 * looking for matches. This flag tells the lookup code when it must
1367 * check for a mount linkage and also prevents the directories in question
1368 * from being deleted or renamed.
1372 cache_clrmountpt_callback(struct mount *mp, void *data)
1374 struct nchandle *nch = data;
1376 if (mp->mnt_ncmounton.ncp == nch->ncp)
1378 if (mp->mnt_ncmountpt.ncp == nch->ncp)
1387 cache_clrmountpt(struct nchandle *nch)
1391 count = mountlist_scan(cache_clrmountpt_callback, nch,
1392 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1394 nch->ncp->nc_flag &= ~NCF_ISMOUNTPT;
1398 * Invalidate portions of the namecache topology given a starting entry.
1399 * The passed ncp is set to an unresolved state and:
1401 * The passed ncp must be referencxed and locked. The routine may unlock
1402 * and relock ncp several times, and will recheck the children and loop
1403 * to catch races. When done the passed ncp will be returned with the
1404 * reference and lock intact.
1406 * CINV_DESTROY - Set a flag in the passed ncp entry indicating
1407 * that the physical underlying nodes have been
1408 * destroyed... as in deleted. For example, when
1409 * a directory is removed. This will cause record
1410 * lookups on the name to no longer be able to find
1411 * the record and tells the resolver to return failure
1412 * rather then trying to resolve through the parent.
1414 * The topology itself, including ncp->nc_name,
1417 * This only applies to the passed ncp, if CINV_CHILDREN
1418 * is specified the children are not flagged.
1420 * CINV_CHILDREN - Set all children (recursively) to an unresolved
1423 * Note that this will also have the side effect of
1424 * cleaning out any unreferenced nodes in the topology
1425 * from the leaves up as the recursion backs out.
1427 * Note that the topology for any referenced nodes remains intact, but
1428 * the nodes will be marked as having been destroyed and will be set
1429 * to an unresolved state.
1431 * It is possible for cache_inval() to race a cache_resolve(), meaning that
1432 * the namecache entry may not actually be invalidated on return if it was
1433 * revalidated while recursing down into its children. This code guarentees
1434 * that the node(s) will go through an invalidation cycle, but does not
1435 * guarentee that they will remain in an invalidated state.
1437 * Returns non-zero if a revalidation was detected during the invalidation
1438 * recursion, zero otherwise. Note that since only the original ncp is
1439 * locked the revalidation ultimately can only indicate that the original ncp
1440 * *MIGHT* no have been reresolved.
1442 * DEEP RECURSION HANDLING - If a recursive invalidation recurses deeply we
1443 * have to avoid blowing out the kernel stack. We do this by saving the
1444 * deep namecache node and aborting the recursion, then re-recursing at that
1445 * node using a depth-first algorithm in order to allow multiple deep
1446 * recursions to chain through each other, then we restart the invalidation
1451 struct namecache *resume_ncp;
1455 static int _cache_inval_internal(struct namecache *, int, struct cinvtrack *);
1459 _cache_inval(struct namecache *ncp, int flags)
1461 struct cinvtrack track;
1462 struct namecache *ncp2;
1466 track.resume_ncp = NULL;
1469 r = _cache_inval_internal(ncp, flags, &track);
1470 if (track.resume_ncp == NULL)
1472 kprintf("Warning: deep namecache recursion at %s\n",
1475 while ((ncp2 = track.resume_ncp) != NULL) {
1476 track.resume_ncp = NULL;
1478 _cache_inval_internal(ncp2, flags & ~CINV_DESTROY,
1488 cache_inval(struct nchandle *nch, int flags)
1490 return(_cache_inval(nch->ncp, flags));
1494 * Helper for _cache_inval(). The passed ncp is refd and locked and
1495 * remains that way on return, but may be unlocked/relocked multiple
1496 * times by the routine.
1499 _cache_inval_internal(struct namecache *ncp, int flags, struct cinvtrack *track)
1501 struct namecache *kid;
1502 struct namecache *nextkid;
1505 KKASSERT(_cache_lockstatus(ncp) == LK_EXCLUSIVE);
1507 _cache_setunresolved(ncp);
1508 if (flags & CINV_DESTROY)
1509 ncp->nc_flag |= NCF_DESTROYED;
1510 if ((flags & CINV_CHILDREN) &&
1511 (kid = TAILQ_FIRST(&ncp->nc_list)) != NULL
1514 if (++track->depth > MAX_RECURSION_DEPTH) {
1515 track->resume_ncp = ncp;
1521 if (track->resume_ncp) {
1525 if ((nextkid = TAILQ_NEXT(kid, nc_entry)) != NULL)
1526 _cache_hold(nextkid);
1527 if ((kid->nc_flag & NCF_UNRESOLVED) == 0 ||
1528 TAILQ_FIRST(&kid->nc_list)
1531 rcnt += _cache_inval_internal(kid, flags & ~CINV_DESTROY, track);
1542 * Someone could have gotten in there while ncp was unlocked,
1545 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
1551 * Invalidate a vnode's namecache associations. To avoid races against
1552 * the resolver we do not invalidate a node which we previously invalidated
1553 * but which was then re-resolved while we were in the invalidation loop.
1555 * Returns non-zero if any namecache entries remain after the invalidation
1558 * NOTE: Unlike the namecache topology which guarentees that ncp's will not
1559 * be ripped out of the topology while held, the vnode's v_namecache
1560 * list has no such restriction. NCP's can be ripped out of the list
1561 * at virtually any time if not locked, even if held.
1563 * In addition, the v_namecache list itself must be locked via
1564 * the vnode's spinlock.
1567 cache_inval_vp(struct vnode *vp, int flags)
1569 struct namecache *ncp;
1570 struct namecache *next;
1573 spin_lock(&vp->v_spin);
1574 ncp = TAILQ_FIRST(&vp->v_namecache);
1578 /* loop entered with ncp held and vp spin-locked */
1579 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1581 spin_unlock(&vp->v_spin);
1583 if (ncp->nc_vp != vp) {
1584 kprintf("Warning: cache_inval_vp: race-A detected on "
1585 "%s\n", ncp->nc_name);
1591 _cache_inval(ncp, flags);
1592 _cache_put(ncp); /* also releases reference */
1594 spin_lock(&vp->v_spin);
1595 if (ncp && ncp->nc_vp != vp) {
1596 spin_unlock(&vp->v_spin);
1597 kprintf("Warning: cache_inval_vp: race-B detected on "
1598 "%s\n", ncp->nc_name);
1603 spin_unlock(&vp->v_spin);
1604 return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1608 * This routine is used instead of the normal cache_inval_vp() when we
1609 * are trying to recycle otherwise good vnodes.
1611 * Return 0 on success, non-zero if not all namecache records could be
1612 * disassociated from the vnode (for various reasons).
1615 cache_inval_vp_nonblock(struct vnode *vp)
1617 struct namecache *ncp;
1618 struct namecache *next;
1620 spin_lock(&vp->v_spin);
1621 ncp = TAILQ_FIRST(&vp->v_namecache);
1625 /* loop entered with ncp held */
1626 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1628 spin_unlock(&vp->v_spin);
1629 if (_cache_lock_nonblock(ncp)) {
1635 if (ncp->nc_vp != vp) {
1636 kprintf("Warning: cache_inval_vp: race-A detected on "
1637 "%s\n", ncp->nc_name);
1643 _cache_inval(ncp, 0);
1644 _cache_put(ncp); /* also releases reference */
1646 spin_lock(&vp->v_spin);
1647 if (ncp && ncp->nc_vp != vp) {
1648 spin_unlock(&vp->v_spin);
1649 kprintf("Warning: cache_inval_vp: race-B detected on "
1650 "%s\n", ncp->nc_name);
1655 spin_unlock(&vp->v_spin);
1657 return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1661 * The source ncp has been renamed to the target ncp. Both fncp and tncp
1662 * must be locked. The target ncp is destroyed (as a normal rename-over
1663 * would destroy the target file or directory).
1665 * Because there may be references to the source ncp we cannot copy its
1666 * contents to the target. Instead the source ncp is relinked as the target
1667 * and the target ncp is removed from the namecache topology.
1670 cache_rename(struct nchandle *fnch, struct nchandle *tnch)
1672 struct namecache *fncp = fnch->ncp;
1673 struct namecache *tncp = tnch->ncp;
1674 struct namecache *tncp_par;
1675 struct nchash_head *nchpp;
1680 if (tncp->nc_nlen) {
1681 nname = kmalloc(tncp->nc_nlen + 1, M_VFSCACHE, M_WAITOK);
1682 bcopy(tncp->nc_name, nname, tncp->nc_nlen);
1683 nname[tncp->nc_nlen] = 0;
1689 * Rename fncp (unlink)
1691 _cache_unlink_parent(fncp);
1692 oname = fncp->nc_name;
1693 fncp->nc_name = nname;
1694 fncp->nc_nlen = tncp->nc_nlen;
1696 kfree(oname, M_VFSCACHE);
1698 tncp_par = tncp->nc_parent;
1699 _cache_hold(tncp_par);
1700 _cache_lock(tncp_par);
1703 * Rename fncp (relink)
1705 hash = fnv_32_buf(fncp->nc_name, fncp->nc_nlen, FNV1_32_INIT);
1706 hash = fnv_32_buf(&tncp_par, sizeof(tncp_par), hash);
1707 nchpp = NCHHASH(hash);
1709 spin_lock(&nchpp->spin);
1710 _cache_link_parent(fncp, tncp_par, nchpp);
1711 spin_unlock(&nchpp->spin);
1713 _cache_put(tncp_par);
1716 * Get rid of the overwritten tncp (unlink)
1718 _cache_unlink(tncp);
1722 * Perform actions consistent with unlinking a file. The passed-in ncp
1725 * The ncp is marked DESTROYED so it no longer shows up in searches,
1726 * and will be physically deleted when the vnode goes away.
1728 * If the related vnode has no refs then we cycle it through vget()/vput()
1729 * to (possibly if we don't have a ref race) trigger a deactivation,
1730 * allowing the VFS to trivially detect and recycle the deleted vnode
1731 * via VOP_INACTIVE().
1733 * NOTE: _cache_rename() will automatically call _cache_unlink() on the
1737 cache_unlink(struct nchandle *nch)
1739 _cache_unlink(nch->ncp);
1743 _cache_unlink(struct namecache *ncp)
1748 * Causes lookups to fail and allows another ncp with the same
1749 * name to be created under ncp->nc_parent.
1751 ncp->nc_flag |= NCF_DESTROYED;
1754 * Attempt to trigger a deactivation.
1756 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
1757 (vp = ncp->nc_vp) != NULL &&
1758 !sysref_isactive(&vp->v_sysref)) {
1759 if (vget(vp, LK_SHARED) == 0)
1765 * vget the vnode associated with the namecache entry. Resolve the namecache
1766 * entry if necessary. The passed ncp must be referenced and locked.
1768 * lk_type may be LK_SHARED, LK_EXCLUSIVE. A ref'd, possibly locked
1769 * (depending on the passed lk_type) will be returned in *vpp with an error
1770 * of 0, or NULL will be returned in *vpp with a non-0 error code. The
1771 * most typical error is ENOENT, meaning that the ncp represents a negative
1772 * cache hit and there is no vnode to retrieve, but other errors can occur
1775 * The vget() can race a reclaim. If this occurs we re-resolve the
1778 * There are numerous places in the kernel where vget() is called on a
1779 * vnode while one or more of its namecache entries is locked. Releasing
1780 * a vnode never deadlocks against locked namecache entries (the vnode
1781 * will not get recycled while referenced ncp's exist). This means we
1782 * can safely acquire the vnode. In fact, we MUST NOT release the ncp
1783 * lock when acquiring the vp lock or we might cause a deadlock.
1785 * NOTE: The passed-in ncp must be locked exclusively if it is initially
1786 * unresolved. If a reclaim race occurs the passed-in ncp will be
1787 * relocked exclusively before being re-resolved.
1790 cache_vget(struct nchandle *nch, struct ucred *cred,
1791 int lk_type, struct vnode **vpp)
1793 struct namecache *ncp;
1800 if (ncp->nc_flag & NCF_UNRESOLVED)
1801 error = cache_resolve(nch, cred);
1805 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1806 error = vget(vp, lk_type);
1811 if (error == ENOENT) {
1812 kprintf("Warning: vnode reclaim race detected "
1813 "in cache_vget on %p (%s)\n",
1817 _cache_setunresolved(ncp);
1822 * Not a reclaim race, some other error.
1824 KKASSERT(ncp->nc_vp == vp);
1827 KKASSERT(ncp->nc_vp == vp);
1828 KKASSERT((vp->v_flag & VRECLAIMED) == 0);
1831 if (error == 0 && vp == NULL)
1838 * Similar to cache_vget() but only acquires a ref on the vnode.
1840 * NOTE: The passed-in ncp must be locked exclusively if it is initially
1841 * unresolved. If a reclaim race occurs the passed-in ncp will be
1842 * relocked exclusively before being re-resolved.
1845 cache_vref(struct nchandle *nch, struct ucred *cred, struct vnode **vpp)
1847 struct namecache *ncp;
1854 if (ncp->nc_flag & NCF_UNRESOLVED)
1855 error = cache_resolve(nch, cred);
1859 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1860 error = vget(vp, LK_SHARED);
1865 if (error == ENOENT) {
1866 kprintf("Warning: vnode reclaim race detected "
1867 "in cache_vget on %p (%s)\n",
1871 _cache_setunresolved(ncp);
1876 * Not a reclaim race, some other error.
1878 KKASSERT(ncp->nc_vp == vp);
1881 KKASSERT(ncp->nc_vp == vp);
1882 KKASSERT((vp->v_flag & VRECLAIMED) == 0);
1883 /* caller does not want a lock */
1887 if (error == 0 && vp == NULL)
1894 * Return a referenced vnode representing the parent directory of
1897 * Because the caller has locked the ncp it should not be possible for
1898 * the parent ncp to go away. However, the parent can unresolve its
1899 * dvp at any time so we must be able to acquire a lock on the parent
1900 * to safely access nc_vp.
1902 * We have to leave par unlocked when vget()ing dvp to avoid a deadlock,
1903 * so use vhold()/vdrop() while holding the lock to prevent dvp from
1904 * getting destroyed.
1906 * NOTE: vhold() is allowed when dvp has 0 refs if we hold a
1907 * lock on the ncp in question..
1909 static struct vnode *
1910 cache_dvpref(struct namecache *ncp)
1912 struct namecache *par;
1916 if ((par = ncp->nc_parent) != NULL) {
1919 if ((par->nc_flag & NCF_UNRESOLVED) == 0) {
1920 if ((dvp = par->nc_vp) != NULL)
1925 if (vget(dvp, LK_SHARED) == 0) {
1928 /* return refd, unlocked dvp */
1940 * Convert a directory vnode to a namecache record without any other
1941 * knowledge of the topology. This ONLY works with directory vnodes and
1942 * is ONLY used by the NFS server. dvp must be refd but unlocked, and the
1943 * returned ncp (if not NULL) will be held and unlocked.
1945 * If 'makeit' is 0 and dvp has no existing namecache record, NULL is returned.
1946 * If 'makeit' is 1 we attempt to track-down and create the namecache topology
1947 * for dvp. This will fail only if the directory has been deleted out from
1950 * Callers must always check for a NULL return no matter the value of 'makeit'.
1952 * To avoid underflowing the kernel stack each recursive call increments
1953 * the makeit variable.
1956 static int cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1957 struct vnode *dvp, char *fakename);
1958 static int cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1959 struct vnode **saved_dvp);
1962 cache_fromdvp(struct vnode *dvp, struct ucred *cred, int makeit,
1963 struct nchandle *nch)
1965 struct vnode *saved_dvp;
1971 nch->mount = dvp->v_mount;
1976 * Handle the makeit == 0 degenerate case
1979 spin_lock(&dvp->v_spin);
1980 nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
1983 spin_unlock(&dvp->v_spin);
1987 * Loop until resolution, inside code will break out on error.
1991 * Break out if we successfully acquire a working ncp.
1993 spin_lock(&dvp->v_spin);
1994 nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
1997 spin_unlock(&dvp->v_spin);
2000 spin_unlock(&dvp->v_spin);
2003 * If dvp is the root of its filesystem it should already
2004 * have a namecache pointer associated with it as a side
2005 * effect of the mount, but it may have been disassociated.
2007 if (dvp->v_flag & VROOT) {
2008 nch->ncp = _cache_get(nch->mount->mnt_ncmountpt.ncp);
2009 error = cache_resolve_mp(nch->mount);
2010 _cache_put(nch->ncp);
2012 kprintf("cache_fromdvp: resolve root of mount %p error %d",
2013 dvp->v_mount, error);
2017 kprintf(" failed\n");
2022 kprintf(" succeeded\n");
2027 * If we are recursed too deeply resort to an O(n^2)
2028 * algorithm to resolve the namecache topology. The
2029 * resolved pvp is left referenced in saved_dvp to
2030 * prevent the tree from being destroyed while we loop.
2033 error = cache_fromdvp_try(dvp, cred, &saved_dvp);
2035 kprintf("lookupdotdot(longpath) failed %d "
2036 "dvp %p\n", error, dvp);
2044 * Get the parent directory and resolve its ncp.
2047 kfree(fakename, M_TEMP);
2050 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
2053 kprintf("lookupdotdot failed %d dvp %p\n", error, dvp);
2059 * Reuse makeit as a recursion depth counter. On success
2060 * nch will be fully referenced.
2062 cache_fromdvp(pvp, cred, makeit + 1, nch);
2064 if (nch->ncp == NULL)
2068 * Do an inefficient scan of pvp (embodied by ncp) to look
2069 * for dvp. This will create a namecache record for dvp on
2070 * success. We loop up to recheck on success.
2072 * ncp and dvp are both held but not locked.
2074 error = cache_inefficient_scan(nch, cred, dvp, fakename);
2076 kprintf("cache_fromdvp: scan %p (%s) failed on dvp=%p\n",
2077 pvp, nch->ncp->nc_name, dvp);
2079 /* nch was NULLed out, reload mount */
2080 nch->mount = dvp->v_mount;
2084 kprintf("cache_fromdvp: scan %p (%s) succeeded\n",
2085 pvp, nch->ncp->nc_name);
2088 /* nch was NULLed out, reload mount */
2089 nch->mount = dvp->v_mount;
2093 * If nch->ncp is non-NULL it will have been held already.
2096 kfree(fakename, M_TEMP);
2105 * Go up the chain of parent directories until we find something
2106 * we can resolve into the namecache. This is very inefficient.
2110 cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
2111 struct vnode **saved_dvp)
2113 struct nchandle nch;
2116 static time_t last_fromdvp_report;
2120 * Loop getting the parent directory vnode until we get something we
2121 * can resolve in the namecache.
2124 nch.mount = dvp->v_mount;
2130 kfree(fakename, M_TEMP);
2133 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
2140 spin_lock(&pvp->v_spin);
2141 if ((nch.ncp = TAILQ_FIRST(&pvp->v_namecache)) != NULL) {
2142 _cache_hold(nch.ncp);
2143 spin_unlock(&pvp->v_spin);
2147 spin_unlock(&pvp->v_spin);
2148 if (pvp->v_flag & VROOT) {
2149 nch.ncp = _cache_get(pvp->v_mount->mnt_ncmountpt.ncp);
2150 error = cache_resolve_mp(nch.mount);
2151 _cache_unlock(nch.ncp);
2154 _cache_drop(nch.ncp);
2164 if (last_fromdvp_report != time_second) {
2165 last_fromdvp_report = time_second;
2166 kprintf("Warning: extremely inefficient path "
2167 "resolution on %s\n",
2170 error = cache_inefficient_scan(&nch, cred, dvp, fakename);
2173 * Hopefully dvp now has a namecache record associated with
2174 * it. Leave it referenced to prevent the kernel from
2175 * recycling the vnode. Otherwise extremely long directory
2176 * paths could result in endless recycling.
2181 _cache_drop(nch.ncp);
2184 kfree(fakename, M_TEMP);
2189 * Do an inefficient scan of the directory represented by ncp looking for
2190 * the directory vnode dvp. ncp must be held but not locked on entry and
2191 * will be held on return. dvp must be refd but not locked on entry and
2192 * will remain refd on return.
2194 * Why do this at all? Well, due to its stateless nature the NFS server
2195 * converts file handles directly to vnodes without necessarily going through
2196 * the namecache ops that would otherwise create the namecache topology
2197 * leading to the vnode. We could either (1) Change the namecache algorithms
2198 * to allow disconnect namecache records that are re-merged opportunistically,
2199 * or (2) Make the NFS server backtrack and scan to recover a connected
2200 * namecache topology in order to then be able to issue new API lookups.
2202 * It turns out that (1) is a huge mess. It takes a nice clean set of
2203 * namecache algorithms and introduces a lot of complication in every subsystem
2204 * that calls into the namecache to deal with the re-merge case, especially
2205 * since we are using the namecache to placehold negative lookups and the
2206 * vnode might not be immediately assigned. (2) is certainly far less
2207 * efficient then (1), but since we are only talking about directories here
2208 * (which are likely to remain cached), the case does not actually run all
2209 * that often and has the supreme advantage of not polluting the namecache
2212 * If a fakename is supplied just construct a namecache entry using the
2216 cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
2217 struct vnode *dvp, char *fakename)
2219 struct nlcomponent nlc;
2220 struct nchandle rncp;
2232 vat.va_blocksize = 0;
2233 if ((error = VOP_GETATTR(dvp, &vat)) != 0)
2236 error = cache_vref(nch, cred, &pvp);
2241 kprintf("inefficient_scan: directory iosize %ld "
2242 "vattr fileid = %lld\n",
2244 (long long)vat.va_fileid);
2248 * Use the supplied fakename if not NULL. Fake names are typically
2249 * not in the actual filesystem hierarchy. This is used by HAMMER
2250 * to glue @@timestamp recursions together.
2253 nlc.nlc_nameptr = fakename;
2254 nlc.nlc_namelen = strlen(fakename);
2255 rncp = cache_nlookup(nch, &nlc);
2259 if ((blksize = vat.va_blocksize) == 0)
2260 blksize = DEV_BSIZE;
2261 rbuf = kmalloc(blksize, M_TEMP, M_WAITOK);
2267 iov.iov_base = rbuf;
2268 iov.iov_len = blksize;
2271 uio.uio_resid = blksize;
2272 uio.uio_segflg = UIO_SYSSPACE;
2273 uio.uio_rw = UIO_READ;
2274 uio.uio_td = curthread;
2276 if (ncvp_debug >= 2)
2277 kprintf("cache_inefficient_scan: readdir @ %08x\n", (int)uio.uio_offset);
2278 error = VOP_READDIR(pvp, &uio, cred, &eofflag, NULL, NULL);
2280 den = (struct dirent *)rbuf;
2281 bytes = blksize - uio.uio_resid;
2284 if (ncvp_debug >= 2) {
2285 kprintf("cache_inefficient_scan: %*.*s\n",
2286 den->d_namlen, den->d_namlen,
2289 if (den->d_type != DT_WHT &&
2290 den->d_ino == vat.va_fileid) {
2292 kprintf("cache_inefficient_scan: "
2293 "MATCHED inode %lld path %s/%*.*s\n",
2294 (long long)vat.va_fileid,
2296 den->d_namlen, den->d_namlen,
2299 nlc.nlc_nameptr = den->d_name;
2300 nlc.nlc_namelen = den->d_namlen;
2301 rncp = cache_nlookup(nch, &nlc);
2302 KKASSERT(rncp.ncp != NULL);
2305 bytes -= _DIRENT_DIRSIZ(den);
2306 den = _DIRENT_NEXT(den);
2308 if (rncp.ncp == NULL && eofflag == 0 && uio.uio_resid != blksize)
2311 kfree(rbuf, M_TEMP);
2315 if (rncp.ncp->nc_flag & NCF_UNRESOLVED) {
2316 _cache_setvp(rncp.mount, rncp.ncp, dvp);
2317 if (ncvp_debug >= 2) {
2318 kprintf("cache_inefficient_scan: setvp %s/%s = %p\n",
2319 nch->ncp->nc_name, rncp.ncp->nc_name, dvp);
2322 if (ncvp_debug >= 2) {
2323 kprintf("cache_inefficient_scan: setvp %s/%s already set %p/%p\n",
2324 nch->ncp->nc_name, rncp.ncp->nc_name, dvp,
2328 if (rncp.ncp->nc_vp == NULL)
2329 error = rncp.ncp->nc_error;
2331 * Release rncp after a successful nlookup. rncp was fully
2336 kprintf("cache_inefficient_scan: dvp %p NOT FOUND in %s\n",
2337 dvp, nch->ncp->nc_name);
2344 * Zap a namecache entry. The ncp is unconditionally set to an unresolved
2345 * state, which disassociates it from its vnode or ncneglist.
2347 * Then, if there are no additional references to the ncp and no children,
2348 * the ncp is removed from the topology and destroyed.
2350 * References and/or children may exist if the ncp is in the middle of the
2351 * topology, preventing the ncp from being destroyed.
2353 * This function must be called with the ncp held and locked and will unlock
2354 * and drop it during zapping.
2356 * If nonblock is non-zero and the parent ncp cannot be locked we give up.
2357 * This case can occur in the cache_drop() path.
2359 * This function may returned a held (but NOT locked) parent node which the
2360 * caller must drop. We do this so _cache_drop() can loop, to avoid
2361 * blowing out the kernel stack.
2363 * WARNING! For MPSAFE operation this routine must acquire up to three
2364 * spin locks to be able to safely test nc_refs. Lock order is
2367 * hash spinlock if on hash list
2368 * parent spinlock if child of parent
2369 * (the ncp is unresolved so there is no vnode association)
2371 static struct namecache *
2372 cache_zap(struct namecache *ncp, int nonblock)
2374 struct namecache *par;
2375 struct vnode *dropvp;
2379 * Disassociate the vnode or negative cache ref and set NCF_UNRESOLVED.
2381 _cache_setunresolved(ncp);
2384 * Try to scrap the entry and possibly tail-recurse on its parent.
2385 * We only scrap unref'd (other then our ref) unresolved entries,
2386 * we do not scrap 'live' entries.
2388 * Note that once the spinlocks are acquired if nc_refs == 1 no
2389 * other references are possible. If it isn't, however, we have
2390 * to decrement but also be sure to avoid a 1->0 transition.
2392 KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
2393 KKASSERT(ncp->nc_refs > 0);
2396 * Acquire locks. Note that the parent can't go away while we hold
2399 if ((par = ncp->nc_parent) != NULL) {
2402 if (_cache_lock_nonblock(par) == 0)
2404 refs = ncp->nc_refs;
2405 ncp->nc_flag |= NCF_DEFEREDZAP;
2406 ++numdefered; /* MP race ok */
2407 if (atomic_cmpset_int(&ncp->nc_refs,
2419 spin_lock(&ncp->nc_head->spin);
2423 * If someone other then us has a ref or we have children
2424 * we cannot zap the entry. The 1->0 transition and any
2425 * further list operation is protected by the spinlocks
2426 * we have acquired but other transitions are not.
2429 refs = ncp->nc_refs;
2430 if (refs == 1 && TAILQ_EMPTY(&ncp->nc_list))
2432 if (atomic_cmpset_int(&ncp->nc_refs, refs, refs - 1)) {
2434 spin_unlock(&ncp->nc_head->spin);
2444 * We are the only ref and with the spinlocks held no further
2445 * refs can be acquired by others.
2447 * Remove us from the hash list and parent list. We have to
2448 * drop a ref on the parent's vp if the parent's list becomes
2453 struct nchash_head *nchpp = ncp->nc_head;
2455 KKASSERT(nchpp != NULL);
2456 LIST_REMOVE(ncp, nc_hash);
2457 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
2458 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
2459 dropvp = par->nc_vp;
2460 ncp->nc_head = NULL;
2461 ncp->nc_parent = NULL;
2462 spin_unlock(&nchpp->spin);
2465 KKASSERT(ncp->nc_head == NULL);
2469 * ncp should not have picked up any refs. Physically
2472 KKASSERT(ncp->nc_refs == 1);
2473 /* _cache_unlock(ncp) not required */
2474 ncp->nc_refs = -1; /* safety */
2476 kfree(ncp->nc_name, M_VFSCACHE);
2477 kfree(ncp, M_VFSCACHE);
2480 * Delayed drop (we had to release our spinlocks)
2482 * The refed parent (if not NULL) must be dropped. The
2483 * caller is responsible for looping.
2491 * Clean up dangling negative cache and defered-drop entries in the
2494 * This routine is called in the critical path and also called from
2495 * vnlru(). When called from vnlru we use a lower limit to try to
2496 * deal with the negative cache before the critical path has to start
2499 typedef enum { CHI_LOW, CHI_HIGH } cache_hs_t;
2501 static cache_hs_t neg_cache_hysteresis_state[2] = { CHI_LOW, CHI_LOW };
2502 static cache_hs_t pos_cache_hysteresis_state[2] = { CHI_LOW, CHI_LOW };
2505 cache_hysteresis(int critpath)
2508 int neglimit = desiredvnodes / ncnegfactor;
2509 int xnumcache = numcache;
2512 neglimit = neglimit * 8 / 10;
2515 * Don't cache too many negative hits. We use hysteresis to reduce
2516 * the impact on the critical path.
2518 switch(neg_cache_hysteresis_state[critpath]) {
2520 if (numneg > MINNEG && numneg > neglimit) {
2522 _cache_cleanneg(ncnegflush);
2524 _cache_cleanneg(ncnegflush +
2526 neg_cache_hysteresis_state[critpath] = CHI_HIGH;
2530 if (numneg > MINNEG * 9 / 10 &&
2531 numneg * 9 / 10 > neglimit
2534 _cache_cleanneg(ncnegflush);
2536 _cache_cleanneg(ncnegflush +
2537 numneg * 9 / 10 - neglimit);
2539 neg_cache_hysteresis_state[critpath] = CHI_LOW;
2545 * Don't cache too many positive hits. We use hysteresis to reduce
2546 * the impact on the critical path.
2548 * Excessive positive hits can accumulate due to large numbers of
2549 * hardlinks (the vnode cache will not prevent hl ncps from growing
2552 if ((poslimit = ncposlimit) == 0)
2553 poslimit = desiredvnodes * 2;
2555 poslimit = poslimit * 8 / 10;
2557 switch(pos_cache_hysteresis_state[critpath]) {
2559 if (xnumcache > poslimit && xnumcache > MINPOS) {
2561 _cache_cleanpos(ncposflush);
2563 _cache_cleanpos(ncposflush +
2564 xnumcache - poslimit);
2565 pos_cache_hysteresis_state[critpath] = CHI_HIGH;
2569 if (xnumcache > poslimit * 5 / 6 && xnumcache > MINPOS) {
2571 _cache_cleanpos(ncposflush);
2573 _cache_cleanpos(ncposflush +
2574 xnumcache - poslimit * 5 / 6);
2576 pos_cache_hysteresis_state[critpath] = CHI_LOW;
2582 * Clean out dangling defered-zap ncps which could not
2583 * be cleanly dropped if too many build up. Note
2584 * that numdefered is not an exact number as such ncps
2585 * can be reused and the counter is not handled in a MP
2586 * safe manner by design.
2588 if (numdefered > neglimit) {
2589 _cache_cleandefered();
2594 * NEW NAMECACHE LOOKUP API
2596 * Lookup an entry in the namecache. The passed par_nch must be referenced
2597 * and unlocked. A referenced and locked nchandle with a non-NULL nch.ncp
2598 * is ALWAYS returned, eve if the supplied component is illegal.
2600 * The resulting namecache entry should be returned to the system with
2601 * cache_put() or cache_unlock() + cache_drop().
2603 * namecache locks are recursive but care must be taken to avoid lock order
2604 * reversals (hence why the passed par_nch must be unlocked). Locking
2605 * rules are to order for parent traversals, not for child traversals.
2607 * Nobody else will be able to manipulate the associated namespace (e.g.
2608 * create, delete, rename, rename-target) until the caller unlocks the
2611 * The returned entry will be in one of three states: positive hit (non-null
2612 * vnode), negative hit (null vnode), or unresolved (NCF_UNRESOLVED is set).
2613 * Unresolved entries must be resolved through the filesystem to associate the
2614 * vnode and/or determine whether a positive or negative hit has occured.
2616 * It is not necessary to lock a directory in order to lock namespace under
2617 * that directory. In fact, it is explicitly not allowed to do that. A
2618 * directory is typically only locked when being created, renamed, or
2621 * The directory (par) may be unresolved, in which case any returned child
2622 * will likely also be marked unresolved. Likely but not guarenteed. Since
2623 * the filesystem lookup requires a resolved directory vnode the caller is
2624 * responsible for resolving the namecache chain top-down. This API
2625 * specifically allows whole chains to be created in an unresolved state.
2628 cache_nlookup(struct nchandle *par_nch, struct nlcomponent *nlc)
2630 struct nchandle nch;
2631 struct namecache *ncp;
2632 struct namecache *new_ncp;
2633 struct nchash_head *nchpp;
2641 mp = par_nch->mount;
2645 * This is a good time to call it, no ncp's are locked by
2648 cache_hysteresis(1);
2651 * Try to locate an existing entry
2653 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
2654 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
2656 nchpp = NCHHASH(hash);
2658 spin_lock(&nchpp->spin);
2659 LIST_FOREACH(ncp, &nchpp->list, nc_hash) {
2663 * Break out if we find a matching entry. Note that
2664 * UNRESOLVED entries may match, but DESTROYED entries
2667 if (ncp->nc_parent == par_nch->ncp &&
2668 ncp->nc_nlen == nlc->nlc_namelen &&
2669 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
2670 (ncp->nc_flag & NCF_DESTROYED) == 0
2673 spin_unlock(&nchpp->spin);
2675 _cache_unlock(par_nch->ncp);
2678 if (_cache_lock_special(ncp) == 0) {
2679 _cache_auto_unresolve(mp, ncp);
2681 _cache_free(new_ncp);
2692 * We failed to locate an entry, create a new entry and add it to
2693 * the cache. The parent ncp must also be locked so we
2696 * We have to relookup after possibly blocking in kmalloc or
2697 * when locking par_nch.
2699 * NOTE: nlc_namelen can be 0 and nlc_nameptr NULL as a special
2700 * mount case, in which case nc_name will be NULL.
2702 if (new_ncp == NULL) {
2703 spin_unlock(&nchpp->spin);
2704 new_ncp = cache_alloc(nlc->nlc_namelen);
2705 if (nlc->nlc_namelen) {
2706 bcopy(nlc->nlc_nameptr, new_ncp->nc_name,
2708 new_ncp->nc_name[nlc->nlc_namelen] = 0;
2712 if (par_locked == 0) {
2713 spin_unlock(&nchpp->spin);
2714 _cache_lock(par_nch->ncp);
2720 * WARNING! We still hold the spinlock. We have to set the hash
2721 * table entry atomically.
2724 _cache_link_parent(ncp, par_nch->ncp, nchpp);
2725 spin_unlock(&nchpp->spin);
2726 _cache_unlock(par_nch->ncp);
2727 /* par_locked = 0 - not used */
2730 * stats and namecache size management
2732 if (ncp->nc_flag & NCF_UNRESOLVED)
2733 ++gd->gd_nchstats->ncs_miss;
2734 else if (ncp->nc_vp)
2735 ++gd->gd_nchstats->ncs_goodhits;
2737 ++gd->gd_nchstats->ncs_neghits;
2740 atomic_add_int(&nch.mount->mnt_refs, 1);
2745 * Attempt to lookup a namecache entry and return with a shared namecache
2749 cache_nlookup_maybe_shared(struct nchandle *par_nch, struct nlcomponent *nlc,
2750 int excl, struct nchandle *res_nch)
2752 struct namecache *ncp;
2753 struct nchash_head *nchpp;
2759 * If exclusive requested or shared namecache locks are disabled,
2762 if (ncp_shared_lock_disable || excl)
2763 return(EWOULDBLOCK);
2767 mp = par_nch->mount;
2770 * This is a good time to call it, no ncp's are locked by
2773 cache_hysteresis(1);
2776 * Try to locate an existing entry
2778 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
2779 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
2780 nchpp = NCHHASH(hash);
2782 spin_lock(&nchpp->spin);
2784 LIST_FOREACH(ncp, &nchpp->list, nc_hash) {
2788 * Break out if we find a matching entry. Note that
2789 * UNRESOLVED entries may match, but DESTROYED entries
2792 if (ncp->nc_parent == par_nch->ncp &&
2793 ncp->nc_nlen == nlc->nlc_namelen &&
2794 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
2795 (ncp->nc_flag & NCF_DESTROYED) == 0
2798 spin_unlock(&nchpp->spin);
2799 if (_cache_lock_shared_special(ncp) == 0) {
2800 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
2801 (ncp->nc_flag & NCF_DESTROYED) == 0 &&
2802 _cache_auto_unresolve_test(mp, ncp) == 0) {
2808 spin_lock(&nchpp->spin);
2816 spin_unlock(&nchpp->spin);
2817 return(EWOULDBLOCK);
2822 * Note that nc_error might be non-zero (e.g ENOENT).
2825 res_nch->mount = mp;
2827 ++gd->gd_nchstats->ncs_goodhits;
2828 atomic_add_int(&res_nch->mount->mnt_refs, 1);
2830 KKASSERT(ncp->nc_error != EWOULDBLOCK);
2831 return(ncp->nc_error);
2835 * This is a non-blocking verison of cache_nlookup() used by
2836 * nfs_readdirplusrpc_uio(). It can fail for any reason and
2837 * will return nch.ncp == NULL in that case.
2840 cache_nlookup_nonblock(struct nchandle *par_nch, struct nlcomponent *nlc)
2842 struct nchandle nch;
2843 struct namecache *ncp;
2844 struct namecache *new_ncp;
2845 struct nchash_head *nchpp;
2853 mp = par_nch->mount;
2857 * Try to locate an existing entry
2859 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
2860 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
2862 nchpp = NCHHASH(hash);
2864 spin_lock(&nchpp->spin);
2865 LIST_FOREACH(ncp, &nchpp->list, nc_hash) {
2869 * Break out if we find a matching entry. Note that
2870 * UNRESOLVED entries may match, but DESTROYED entries
2873 if (ncp->nc_parent == par_nch->ncp &&
2874 ncp->nc_nlen == nlc->nlc_namelen &&
2875 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
2876 (ncp->nc_flag & NCF_DESTROYED) == 0
2879 spin_unlock(&nchpp->spin);
2881 _cache_unlock(par_nch->ncp);
2884 if (_cache_lock_special(ncp) == 0) {
2885 _cache_auto_unresolve(mp, ncp);
2887 _cache_free(new_ncp);
2898 * We failed to locate an entry, create a new entry and add it to
2899 * the cache. The parent ncp must also be locked so we
2902 * We have to relookup after possibly blocking in kmalloc or
2903 * when locking par_nch.
2905 * NOTE: nlc_namelen can be 0 and nlc_nameptr NULL as a special
2906 * mount case, in which case nc_name will be NULL.
2908 if (new_ncp == NULL) {
2909 spin_unlock(&nchpp->spin);
2910 new_ncp = cache_alloc(nlc->nlc_namelen);
2911 if (nlc->nlc_namelen) {
2912 bcopy(nlc->nlc_nameptr, new_ncp->nc_name,
2914 new_ncp->nc_name[nlc->nlc_namelen] = 0;
2918 if (par_locked == 0) {
2919 spin_unlock(&nchpp->spin);
2920 if (_cache_lock_nonblock(par_nch->ncp) == 0) {
2928 * WARNING! We still hold the spinlock. We have to set the hash
2929 * table entry atomically.
2932 _cache_link_parent(ncp, par_nch->ncp, nchpp);
2933 spin_unlock(&nchpp->spin);
2934 _cache_unlock(par_nch->ncp);
2935 /* par_locked = 0 - not used */
2938 * stats and namecache size management
2940 if (ncp->nc_flag & NCF_UNRESOLVED)
2941 ++gd->gd_nchstats->ncs_miss;
2942 else if (ncp->nc_vp)
2943 ++gd->gd_nchstats->ncs_goodhits;
2945 ++gd->gd_nchstats->ncs_neghits;
2948 atomic_add_int(&nch.mount->mnt_refs, 1);
2952 _cache_free(new_ncp);
2961 * The namecache entry is marked as being used as a mount point.
2962 * Locate the mount if it is visible to the caller. The DragonFly
2963 * mount system allows arbitrary loops in the topology and disentangles
2964 * those loops by matching against (mp, ncp) rather than just (ncp).
2965 * This means any given ncp can dive any number of mounts, depending
2966 * on the relative mount (e.g. nullfs) the caller is at in the topology.
2968 * We use a very simple frontend cache to reduce SMP conflicts,
2969 * which we have to do because the mountlist scan needs an exclusive
2970 * lock around its ripout info list. Not to mention that there might
2971 * be a lot of mounts.
2973 struct findmount_info {
2974 struct mount *result;
2975 struct mount *nch_mount;
2976 struct namecache *nch_ncp;
2980 struct ncmount_cache *
2981 ncmount_cache_lookup(struct mount *mp, struct namecache *ncp)
2985 hash = ((int)(intptr_t)mp / sizeof(*mp)) ^
2986 ((int)(intptr_t)ncp / sizeof(*ncp));
2987 hash = (hash & 0x7FFFFFFF) % NCMOUNT_NUMCACHE;
2988 return (&ncmount_cache[hash]);
2993 cache_findmount_callback(struct mount *mp, void *data)
2995 struct findmount_info *info = data;
2998 * Check the mount's mounted-on point against the passed nch.
3000 if (mp->mnt_ncmounton.mount == info->nch_mount &&
3001 mp->mnt_ncmounton.ncp == info->nch_ncp
3004 atomic_add_int(&mp->mnt_refs, 1);
3011 cache_findmount(struct nchandle *nch)
3013 struct findmount_info info;
3014 struct ncmount_cache *ncc;
3020 if (ncmount_cache_enable == 0) {
3024 ncc = ncmount_cache_lookup(nch->mount, nch->ncp);
3025 if (ncc->ncp == nch->ncp) {
3026 spin_lock_shared(&ncc->spin);
3027 if (ncc->isneg == 0 &&
3028 ncc->ncp == nch->ncp && (mp = ncc->mp) != NULL) {
3029 if (mp->mnt_ncmounton.mount == nch->mount &&
3030 mp->mnt_ncmounton.ncp == nch->ncp) {
3032 * Cache hit (positive)
3034 atomic_add_int(&mp->mnt_refs, 1);
3035 spin_unlock_shared(&ncc->spin);
3036 ++ncmount_cache_hit;
3039 /* else cache miss */
3042 ncc->ncp == nch->ncp && ncc->mp == nch->mount) {
3044 * Cache hit (negative)
3046 spin_unlock_shared(&ncc->spin);
3047 ++ncmount_cache_hit;
3050 spin_unlock_shared(&ncc->spin);
3058 info.nch_mount = nch->mount;
3059 info.nch_ncp = nch->ncp;
3060 mountlist_scan(cache_findmount_callback, &info,
3061 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
3066 * Negative lookups: We cache the originating {ncp,mp}. (mp) is
3067 * only used for pointer comparisons and is not
3068 * referenced (otherwise there would be dangling
3071 * Positive lookups: We cache the originating {ncp} and the target
3072 * (mp). (mp) is referenced.
3074 * Indeterminant: If the match is undergoing an unmount we do
3075 * not cache it to avoid racing cache_unmounting(),
3076 * but still return the match.
3079 spin_lock(&ncc->spin);
3080 if (info.result == NULL) {
3081 if (ncc->isneg == 0 && ncc->mp)
3082 atomic_add_int(&ncc->mp->mnt_refs, -1);
3083 ncc->ncp = nch->ncp;
3084 ncc->mp = nch->mount;
3086 spin_unlock(&ncc->spin);
3087 ++ncmount_cache_overwrite;
3088 } else if ((info.result->mnt_kern_flag & MNTK_UNMOUNT) == 0) {
3089 if (ncc->isneg == 0 && ncc->mp)
3090 atomic_add_int(&ncc->mp->mnt_refs, -1);
3091 atomic_add_int(&info.result->mnt_refs, 1);
3092 ncc->ncp = nch->ncp;
3093 ncc->mp = info.result;
3095 spin_unlock(&ncc->spin);
3096 ++ncmount_cache_overwrite;
3098 spin_unlock(&ncc->spin);
3100 ++ncmount_cache_miss;
3102 return(info.result);
3106 cache_dropmount(struct mount *mp)
3108 atomic_add_int(&mp->mnt_refs, -1);
3112 cache_ismounting(struct mount *mp)
3114 struct nchandle *nch = &mp->mnt_ncmounton;
3115 struct ncmount_cache *ncc;
3117 ncc = ncmount_cache_lookup(nch->mount, nch->ncp);
3119 ncc->ncp == nch->ncp && ncc->mp == nch->mount) {
3120 spin_lock(&ncc->spin);
3122 ncc->ncp == nch->ncp && ncc->mp == nch->mount) {
3126 spin_unlock(&ncc->spin);
3131 cache_unmounting(struct mount *mp)
3133 struct nchandle *nch = &mp->mnt_ncmounton;
3134 struct ncmount_cache *ncc;
3136 ncc = ncmount_cache_lookup(nch->mount, nch->ncp);
3137 if (ncc->isneg == 0 &&
3138 ncc->ncp == nch->ncp && ncc->mp == mp) {
3139 spin_lock(&ncc->spin);
3140 if (ncc->isneg == 0 &&
3141 ncc->ncp == nch->ncp && ncc->mp == mp) {
3142 atomic_add_int(&mp->mnt_refs, -1);
3146 spin_unlock(&ncc->spin);
3151 * Resolve an unresolved namecache entry, generally by looking it up.
3152 * The passed ncp must be locked and refd.
3154 * Theoretically since a vnode cannot be recycled while held, and since
3155 * the nc_parent chain holds its vnode as long as children exist, the
3156 * direct parent of the cache entry we are trying to resolve should
3157 * have a valid vnode. If not then generate an error that we can
3158 * determine is related to a resolver bug.
3160 * However, if a vnode was in the middle of a recyclement when the NCP
3161 * got locked, ncp->nc_vp might point to a vnode that is about to become
3162 * invalid. cache_resolve() handles this case by unresolving the entry
3163 * and then re-resolving it.
3165 * Note that successful resolution does not necessarily return an error
3166 * code of 0. If the ncp resolves to a negative cache hit then ENOENT
3170 cache_resolve(struct nchandle *nch, struct ucred *cred)
3172 struct namecache *par_tmp;
3173 struct namecache *par;
3174 struct namecache *ncp;
3175 struct nchandle nctmp;
3182 KKASSERT(_cache_lockstatus(ncp) == LK_EXCLUSIVE);
3185 * If the ncp is already resolved we have nothing to do. However,
3186 * we do want to guarentee that a usable vnode is returned when
3187 * a vnode is present, so make sure it hasn't been reclaimed.
3189 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
3190 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
3191 _cache_setunresolved(ncp);
3192 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
3193 return (ncp->nc_error);
3197 * If the ncp was destroyed it will never resolve again. This
3198 * can basically only happen when someone is chdir'd into an
3199 * empty directory which is then rmdir'd. We want to catch this
3200 * here and not dive the VFS because the VFS might actually
3201 * have a way to re-resolve the disconnected ncp, which will
3202 * result in inconsistencies in the cdir/nch for proc->p_fd.
3204 if (ncp->nc_flag & NCF_DESTROYED) {
3205 kprintf("Warning: cache_resolve: ncp '%s' was unlinked\n",
3211 * Mount points need special handling because the parent does not
3212 * belong to the same filesystem as the ncp.
3214 if (ncp == mp->mnt_ncmountpt.ncp)
3215 return (cache_resolve_mp(mp));
3218 * We expect an unbroken chain of ncps to at least the mount point,
3219 * and even all the way to root (but this code doesn't have to go
3220 * past the mount point).
3222 if (ncp->nc_parent == NULL) {
3223 kprintf("EXDEV case 1 %p %*.*s\n", ncp,
3224 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
3225 ncp->nc_error = EXDEV;
3226 return(ncp->nc_error);
3230 * The vp's of the parent directories in the chain are held via vhold()
3231 * due to the existance of the child, and should not disappear.
3232 * However, there are cases where they can disappear:
3234 * - due to filesystem I/O errors.
3235 * - due to NFS being stupid about tracking the namespace and
3236 * destroys the namespace for entire directories quite often.
3237 * - due to forced unmounts.
3238 * - due to an rmdir (parent will be marked DESTROYED)
3240 * When this occurs we have to track the chain backwards and resolve
3241 * it, looping until the resolver catches up to the current node. We
3242 * could recurse here but we might run ourselves out of kernel stack
3243 * so we do it in a more painful manner. This situation really should
3244 * not occur all that often, or if it does not have to go back too
3245 * many nodes to resolve the ncp.
3247 while ((dvp = cache_dvpref(ncp)) == NULL) {
3249 * This case can occur if a process is CD'd into a
3250 * directory which is then rmdir'd. If the parent is marked
3251 * destroyed there is no point trying to resolve it.
3253 if (ncp->nc_parent->nc_flag & NCF_DESTROYED)
3255 par = ncp->nc_parent;
3258 while ((par_tmp = par->nc_parent) != NULL &&
3259 par_tmp->nc_vp == NULL) {
3260 _cache_hold(par_tmp);
3261 _cache_lock(par_tmp);
3265 if (par->nc_parent == NULL) {
3266 kprintf("EXDEV case 2 %*.*s\n",
3267 par->nc_nlen, par->nc_nlen, par->nc_name);
3271 kprintf("[diagnostic] cache_resolve: had to recurse on %*.*s\n",
3272 par->nc_nlen, par->nc_nlen, par->nc_name);
3274 * The parent is not set in stone, ref and lock it to prevent
3275 * it from disappearing. Also note that due to renames it
3276 * is possible for our ncp to move and for par to no longer
3277 * be one of its parents. We resolve it anyway, the loop
3278 * will handle any moves.
3280 _cache_get(par); /* additional hold/lock */
3281 _cache_put(par); /* from earlier hold/lock */
3282 if (par == nch->mount->mnt_ncmountpt.ncp) {
3283 cache_resolve_mp(nch->mount);
3284 } else if ((dvp = cache_dvpref(par)) == NULL) {
3285 kprintf("[diagnostic] cache_resolve: raced on %*.*s\n", par->nc_nlen, par->nc_nlen, par->nc_name);
3289 if (par->nc_flag & NCF_UNRESOLVED) {
3292 par->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
3296 if ((error = par->nc_error) != 0) {
3297 if (par->nc_error != EAGAIN) {
3298 kprintf("EXDEV case 3 %*.*s error %d\n",
3299 par->nc_nlen, par->nc_nlen, par->nc_name,
3304 kprintf("[diagnostic] cache_resolve: EAGAIN par %p %*.*s\n",
3305 par, par->nc_nlen, par->nc_nlen, par->nc_name);
3312 * Call VOP_NRESOLVE() to get the vp, then scan for any disconnected
3313 * ncp's and reattach them. If this occurs the original ncp is marked
3314 * EAGAIN to force a relookup.
3316 * NOTE: in order to call VOP_NRESOLVE(), the parent of the passed
3317 * ncp must already be resolved.
3322 ncp->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
3325 ncp->nc_error = EPERM;
3327 if (ncp->nc_error == EAGAIN) {
3328 kprintf("[diagnostic] cache_resolve: EAGAIN ncp %p %*.*s\n",
3329 ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
3332 return(ncp->nc_error);
3336 * Resolve the ncp associated with a mount point. Such ncp's almost always
3337 * remain resolved and this routine is rarely called. NFS MPs tends to force
3338 * re-resolution more often due to its mac-truck-smash-the-namecache
3339 * method of tracking namespace changes.
3341 * The semantics for this call is that the passed ncp must be locked on
3342 * entry and will be locked on return. However, if we actually have to
3343 * resolve the mount point we temporarily unlock the entry in order to
3344 * avoid race-to-root deadlocks due to e.g. dead NFS mounts. Because of
3345 * the unlock we have to recheck the flags after we relock.
3348 cache_resolve_mp(struct mount *mp)
3350 struct namecache *ncp = mp->mnt_ncmountpt.ncp;
3354 KKASSERT(mp != NULL);
3357 * If the ncp is already resolved we have nothing to do. However,
3358 * we do want to guarentee that a usable vnode is returned when
3359 * a vnode is present, so make sure it hasn't been reclaimed.
3361 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
3362 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
3363 _cache_setunresolved(ncp);
3366 if (ncp->nc_flag & NCF_UNRESOLVED) {
3368 while (vfs_busy(mp, 0))
3370 error = VFS_ROOT(mp, &vp);
3374 * recheck the ncp state after relocking.
3376 if (ncp->nc_flag & NCF_UNRESOLVED) {
3377 ncp->nc_error = error;
3379 _cache_setvp(mp, ncp, vp);
3382 kprintf("[diagnostic] cache_resolve_mp: failed"
3383 " to resolve mount %p err=%d ncp=%p\n",
3385 _cache_setvp(mp, ncp, NULL);
3387 } else if (error == 0) {
3392 return(ncp->nc_error);
3396 * Clean out negative cache entries when too many have accumulated.
3399 _cache_cleanneg(int count)
3401 struct namecache *ncp;
3404 * Attempt to clean out the specified number of negative cache
3409 ncp = TAILQ_FIRST(&ncneglist);
3411 spin_unlock(&ncspin);
3414 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
3415 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
3417 spin_unlock(&ncspin);
3420 * This can race, so we must re-check that the ncp
3421 * is on the ncneglist after successfully locking it.
3423 if (_cache_lock_special(ncp) == 0) {
3424 if (ncp->nc_vp == NULL &&
3425 (ncp->nc_flag & NCF_UNRESOLVED) == 0) {
3426 ncp = cache_zap(ncp, 1);
3430 kprintf("cache_cleanneg: race avoided\n");
3441 * Clean out positive cache entries when too many have accumulated.
3444 _cache_cleanpos(int count)
3446 static volatile int rover;
3447 struct nchash_head *nchpp;
3448 struct namecache *ncp;
3452 * Attempt to clean out the specified number of negative cache
3456 rover_copy = ++rover; /* MPSAFEENOUGH */
3458 nchpp = NCHHASH(rover_copy);
3460 spin_lock(&nchpp->spin);
3461 ncp = LIST_FIRST(&nchpp->list);
3462 while (ncp && (ncp->nc_flag & NCF_DESTROYED))
3463 ncp = LIST_NEXT(ncp, nc_hash);
3466 spin_unlock(&nchpp->spin);
3469 if (_cache_lock_special(ncp) == 0) {
3470 ncp = cache_zap(ncp, 1);
3482 * This is a kitchen sink function to clean out ncps which we
3483 * tried to zap from cache_drop() but failed because we were
3484 * unable to acquire the parent lock.
3486 * Such entries can also be removed via cache_inval_vp(), such
3487 * as when unmounting.
3490 _cache_cleandefered(void)
3492 struct nchash_head *nchpp;
3493 struct namecache *ncp;
3494 struct namecache dummy;
3498 bzero(&dummy, sizeof(dummy));
3499 dummy.nc_flag = NCF_DESTROYED;
3502 for (i = 0; i <= nchash; ++i) {
3503 nchpp = &nchashtbl[i];
3505 spin_lock(&nchpp->spin);
3506 LIST_INSERT_HEAD(&nchpp->list, &dummy, nc_hash);
3508 while ((ncp = LIST_NEXT(ncp, nc_hash)) != NULL) {
3509 if ((ncp->nc_flag & NCF_DEFEREDZAP) == 0)
3511 LIST_REMOVE(&dummy, nc_hash);
3512 LIST_INSERT_AFTER(ncp, &dummy, nc_hash);
3514 spin_unlock(&nchpp->spin);
3515 if (_cache_lock_nonblock(ncp) == 0) {
3516 ncp->nc_flag &= ~NCF_DEFEREDZAP;
3520 spin_lock(&nchpp->spin);
3523 LIST_REMOVE(&dummy, nc_hash);
3524 spin_unlock(&nchpp->spin);
3529 * Name cache initialization, from vfsinit() when we are booting
3537 /* initialise per-cpu namecache effectiveness statistics. */
3538 for (i = 0; i < ncpus; ++i) {
3539 gd = globaldata_find(i);
3540 gd->gd_nchstats = &nchstats[i];
3542 TAILQ_INIT(&ncneglist);
3544 nchashtbl = hashinit_ext(desiredvnodes / 2,
3545 sizeof(struct nchash_head),
3546 M_VFSCACHE, &nchash);
3547 for (i = 0; i <= (int)nchash; ++i) {
3548 LIST_INIT(&nchashtbl[i].list);
3549 spin_init(&nchashtbl[i].spin);
3551 for (i = 0; i < NCMOUNT_NUMCACHE; ++i)
3552 spin_init(&ncmount_cache[i].spin);
3553 nclockwarn = 5 * hz;
3557 * Called from start_init() to bootstrap the root filesystem. Returns
3558 * a referenced, unlocked namecache record.
3561 cache_allocroot(struct nchandle *nch, struct mount *mp, struct vnode *vp)
3563 nch->ncp = cache_alloc(0);
3565 atomic_add_int(&mp->mnt_refs, 1);
3567 _cache_setvp(nch->mount, nch->ncp, vp);
3571 * vfs_cache_setroot()
3573 * Create an association between the root of our namecache and
3574 * the root vnode. This routine may be called several times during
3577 * If the caller intends to save the returned namecache pointer somewhere
3578 * it must cache_hold() it.
3581 vfs_cache_setroot(struct vnode *nvp, struct nchandle *nch)
3584 struct nchandle onch;
3592 cache_zero(&rootnch);
3600 * XXX OLD API COMPAT FUNCTION. This really messes up the new namecache
3601 * topology and is being removed as quickly as possible. The new VOP_N*()
3602 * API calls are required to make specific adjustments using the supplied
3603 * ncp pointers rather then just bogusly purging random vnodes.
3605 * Invalidate all namecache entries to a particular vnode as well as
3606 * any direct children of that vnode in the namecache. This is a
3607 * 'catch all' purge used by filesystems that do not know any better.
3609 * Note that the linkage between the vnode and its namecache entries will
3610 * be removed, but the namecache entries themselves might stay put due to
3611 * active references from elsewhere in the system or due to the existance of
3612 * the children. The namecache topology is left intact even if we do not
3613 * know what the vnode association is. Such entries will be marked
3617 cache_purge(struct vnode *vp)
3619 cache_inval_vp(vp, CINV_DESTROY | CINV_CHILDREN);
3623 * Flush all entries referencing a particular filesystem.
3625 * Since we need to check it anyway, we will flush all the invalid
3626 * entries at the same time.
3631 cache_purgevfs(struct mount *mp)
3633 struct nchash_head *nchpp;
3634 struct namecache *ncp, *nnp;
3637 * Scan hash tables for applicable entries.
3639 for (nchpp = &nchashtbl[nchash]; nchpp >= nchashtbl; nchpp--) {
3640 spin_lock_wr(&nchpp->spin); XXX
3641 ncp = LIST_FIRST(&nchpp->list);
3645 nnp = LIST_NEXT(ncp, nc_hash);
3648 if (ncp->nc_mount == mp) {
3650 ncp = cache_zap(ncp, 0);
3658 spin_unlock_wr(&nchpp->spin); XXX
3664 static int disablecwd;
3665 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0,
3668 static u_long numcwdcalls;
3669 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdcalls, CTLFLAG_RD, &numcwdcalls, 0,
3670 "Number of current directory resolution calls");
3671 static u_long numcwdfailnf;
3672 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfailnf, CTLFLAG_RD, &numcwdfailnf, 0,
3673 "Number of current directory failures due to lack of file");
3674 static u_long numcwdfailsz;
3675 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfailsz, CTLFLAG_RD, &numcwdfailsz, 0,
3676 "Number of current directory failures due to large result");
3677 static u_long numcwdfound;
3678 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfound, CTLFLAG_RD, &numcwdfound, 0,
3679 "Number of current directory resolution successes");
3685 sys___getcwd(struct __getcwd_args *uap)
3695 buflen = uap->buflen;
3698 if (buflen > MAXPATHLEN)
3699 buflen = MAXPATHLEN;
3701 buf = kmalloc(buflen, M_TEMP, M_WAITOK);
3702 bp = kern_getcwd(buf, buflen, &error);
3704 error = copyout(bp, uap->buf, strlen(bp) + 1);
3710 kern_getcwd(char *buf, size_t buflen, int *error)
3712 struct proc *p = curproc;
3714 int i, slash_prefixed;
3715 struct filedesc *fdp;
3716 struct nchandle nch;
3717 struct namecache *ncp;
3726 nch = fdp->fd_ncdir;
3731 while (ncp && (ncp != fdp->fd_nrdir.ncp ||
3732 nch.mount != fdp->fd_nrdir.mount)
3735 * While traversing upwards if we encounter the root
3736 * of the current mount we have to skip to the mount point
3737 * in the underlying filesystem.
3739 if (ncp == nch.mount->mnt_ncmountpt.ncp) {
3740 nch = nch.mount->mnt_ncmounton;
3749 * Prepend the path segment
3751 for (i = ncp->nc_nlen - 1; i >= 0; i--) {
3758 *--bp = ncp->nc_name[i];
3770 * Go up a directory. This isn't a mount point so we don't
3771 * have to check again.
3773 while ((nch.ncp = ncp->nc_parent) != NULL) {
3774 if (ncp_shared_lock_disable)
3777 _cache_lock_shared(ncp);
3778 if (nch.ncp != ncp->nc_parent) {
3782 _cache_hold(nch.ncp);
3795 if (!slash_prefixed) {
3813 * Thus begins the fullpath magic.
3815 * The passed nchp is referenced but not locked.
3817 static int disablefullpath;
3818 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW,
3819 &disablefullpath, 0,
3820 "Disable fullpath lookups");
3822 static u_int numfullpathcalls;
3823 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathcalls, CTLFLAG_RD,
3824 &numfullpathcalls, 0,
3825 "Number of full path resolutions in progress");
3826 static u_int numfullpathfailnf;
3827 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathfailnf, CTLFLAG_RD,
3828 &numfullpathfailnf, 0,
3829 "Number of full path resolution failures due to lack of file");
3830 static u_int numfullpathfailsz;
3831 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathfailsz, CTLFLAG_RD,
3832 &numfullpathfailsz, 0,
3833 "Number of full path resolution failures due to insufficient memory");
3834 static u_int numfullpathfound;
3835 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathfound, CTLFLAG_RD,
3836 &numfullpathfound, 0,
3837 "Number of full path resolution successes");
3840 cache_fullpath(struct proc *p, struct nchandle *nchp, struct nchandle *nchbase,
3841 char **retbuf, char **freebuf, int guess)
3843 struct nchandle fd_nrdir;
3844 struct nchandle nch;
3845 struct namecache *ncp;
3846 struct mount *mp, *new_mp;
3852 atomic_add_int(&numfullpathcalls, -1);
3857 buf = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
3858 bp = buf + MAXPATHLEN - 1;
3861 fd_nrdir = *nchbase;
3863 fd_nrdir = p->p_fd->fd_nrdir;
3873 while (ncp && (ncp != fd_nrdir.ncp || mp != fd_nrdir.mount)) {
3877 * If we are asked to guess the upwards path, we do so whenever
3878 * we encounter an ncp marked as a mountpoint. We try to find
3879 * the actual mountpoint by finding the mountpoint with this
3882 if (guess && (ncp->nc_flag & NCF_ISMOUNTPT)) {
3883 new_mp = mount_get_by_nc(ncp);
3886 * While traversing upwards if we encounter the root
3887 * of the current mount we have to skip to the mount point.
3889 if (ncp == mp->mnt_ncmountpt.ncp) {
3893 nch = new_mp->mnt_ncmounton;
3903 * Prepend the path segment
3905 for (i = ncp->nc_nlen - 1; i >= 0; i--) {
3907 numfullpathfailsz++;
3912 *--bp = ncp->nc_name[i];
3915 numfullpathfailsz++;
3924 * Go up a directory. This isn't a mount point so we don't
3925 * have to check again.
3927 * We can only safely access nc_parent with ncp held locked.
3929 while ((nch.ncp = ncp->nc_parent) != NULL) {
3931 if (nch.ncp != ncp->nc_parent) {
3935 _cache_hold(nch.ncp);
3943 numfullpathfailnf++;
3949 if (!slash_prefixed) {
3951 numfullpathfailsz++;
3969 vn_fullpath(struct proc *p, struct vnode *vn, char **retbuf, char **freebuf,
3972 struct namecache *ncp;
3973 struct nchandle nch;
3977 atomic_add_int(&numfullpathcalls, 1);
3978 if (disablefullpath)
3984 /* vn is NULL, client wants us to use p->p_textvp */
3986 if ((vn = p->p_textvp) == NULL)
3989 spin_lock(&vn->v_spin);
3990 TAILQ_FOREACH(ncp, &vn->v_namecache, nc_vnode) {
3995 spin_unlock(&vn->v_spin);
3999 spin_unlock(&vn->v_spin);
4001 atomic_add_int(&numfullpathcalls, -1);
4003 nch.mount = vn->v_mount;
4004 error = cache_fullpath(p, &nch, NULL, retbuf, freebuf, guess);