2 * Copyright (c) 2003,2004,2009 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@backplane.com>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
17 * 3. Neither the name of The DragonFly Project nor the names of its
18 * contributors may be used to endorse or promote products derived
19 * from this software without specific, prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * Copyright (c) 1989, 1993, 1995
35 * The Regents of the University of California. All rights reserved.
37 * This code is derived from software contributed to Berkeley by
38 * Poul-Henning Kamp of the FreeBSD Project.
40 * Redistribution and use in source and binary forms, with or without
41 * modification, are permitted provided that the following conditions
43 * 1. Redistributions of source code must retain the above copyright
44 * notice, this list of conditions and the following disclaimer.
45 * 2. Redistributions in binary form must reproduce the above copyright
46 * notice, this list of conditions and the following disclaimer in the
47 * documentation and/or other materials provided with the distribution.
48 * 3. All advertising materials mentioning features or use of this software
49 * must display the following acknowledgement:
50 * This product includes software developed by the University of
51 * California, Berkeley and its contributors.
52 * 4. Neither the name of the University nor the names of its contributors
53 * may be used to endorse or promote products derived from this software
54 * without specific prior written permission.
56 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
57 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
58 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
59 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
60 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
61 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
62 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
64 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
65 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/kernel.h>
72 #include <sys/sysctl.h>
73 #include <sys/mount.h>
74 #include <sys/vnode.h>
75 #include <sys/malloc.h>
76 #include <sys/sysproto.h>
77 #include <sys/spinlock.h>
79 #include <sys/namei.h>
80 #include <sys/nlookup.h>
81 #include <sys/filedesc.h>
82 #include <sys/fnv_hash.h>
83 #include <sys/globaldata.h>
84 #include <sys/kern_syscall.h>
85 #include <sys/dirent.h>
88 #include <sys/sysref2.h>
89 #include <sys/spinlock2.h>
90 #include <sys/mplock2.h>
92 #define MAX_RECURSION_DEPTH 64
95 * Random lookups in the cache are accomplished with a hash table using
96 * a hash key of (nc_src_vp, name). Each hash chain has its own spin lock.
98 * Negative entries may exist and correspond to resolved namecache
99 * structures where nc_vp is NULL. In a negative entry, NCF_WHITEOUT
100 * will be set if the entry corresponds to a whited-out directory entry
101 * (verses simply not finding the entry at all). ncneglist is locked
102 * with a global spinlock (ncspin).
106 * (1) A ncp must be referenced before it can be locked.
108 * (2) A ncp must be locked in order to modify it.
110 * (3) ncp locks are always ordered child -> parent. That may seem
111 * backwards but forward scans use the hash table and thus can hold
112 * the parent unlocked when traversing downward.
114 * This allows insert/rename/delete/dot-dot and other operations
115 * to use ncp->nc_parent links.
117 * This also prevents a locked up e.g. NFS node from creating a
118 * chain reaction all the way back to the root vnode / namecache.
120 * (4) parent linkages require both the parent and child to be locked.
124 * Structures associated with name cacheing.
126 #define NCHHASH(hash) (&nchashtbl[(hash) & nchash])
129 #define NCMOUNT_NUMCACHE 1009 /* prime number */
131 MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
133 LIST_HEAD(nchash_list, namecache);
136 struct nchash_list list;
137 struct spinlock spin;
140 struct ncmount_cache {
141 struct spinlock spin;
142 struct namecache *ncp;
144 int isneg; /* if != 0 mp is originator and not target */
147 static struct nchash_head *nchashtbl;
148 static struct namecache_list ncneglist;
149 static struct spinlock ncspin;
150 static struct ncmount_cache ncmount_cache[NCMOUNT_NUMCACHE];
153 * ncvp_debug - debug cache_fromvp(). This is used by the NFS server
154 * to create the namecache infrastructure leading to a dangling vnode.
156 * 0 Only errors are reported
157 * 1 Successes are reported
158 * 2 Successes + the whole directory scan is reported
159 * 3 Force the directory scan code run as if the parent vnode did not
160 * have a namecache record, even if it does have one.
162 static int ncvp_debug;
163 SYSCTL_INT(_debug, OID_AUTO, ncvp_debug, CTLFLAG_RW, &ncvp_debug, 0,
164 "Namecache debug level (0-3)");
166 static u_long nchash; /* size of hash table */
167 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
168 "Size of namecache hash table");
170 static int ncnegflush = 10; /* burst for negative flush */
171 SYSCTL_INT(_debug, OID_AUTO, ncnegflush, CTLFLAG_RW, &ncnegflush, 0,
172 "Batch flush negative entries");
174 static int ncposflush = 10; /* burst for positive flush */
175 SYSCTL_INT(_debug, OID_AUTO, ncposflush, CTLFLAG_RW, &ncposflush, 0,
176 "Batch flush positive entries");
178 static int ncnegfactor = 16; /* ratio of negative entries */
179 SYSCTL_INT(_debug, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0,
180 "Ratio of namecache negative entries");
182 static int nclockwarn; /* warn on locked entries in ticks */
183 SYSCTL_INT(_debug, OID_AUTO, nclockwarn, CTLFLAG_RW, &nclockwarn, 0,
184 "Warn on locked namecache entries in ticks");
186 static int numdefered; /* number of cache entries allocated */
187 SYSCTL_INT(_debug, OID_AUTO, numdefered, CTLFLAG_RD, &numdefered, 0,
188 "Number of cache entries allocated");
190 static int ncposlimit; /* number of cache entries allocated */
191 SYSCTL_INT(_debug, OID_AUTO, ncposlimit, CTLFLAG_RW, &ncposlimit, 0,
192 "Number of cache entries allocated");
194 static int ncp_shared_lock_disable = 1;
195 SYSCTL_INT(_debug, OID_AUTO, ncp_shared_lock_disable, CTLFLAG_RW,
196 &ncp_shared_lock_disable, 0, "Disable shared namecache locks");
198 SYSCTL_INT(_debug, OID_AUTO, vnsize, CTLFLAG_RD, 0, sizeof(struct vnode),
199 "sizeof(struct vnode)");
200 SYSCTL_INT(_debug, OID_AUTO, ncsize, CTLFLAG_RD, 0, sizeof(struct namecache),
201 "sizeof(struct namecache)");
203 static int ncmount_cache_enable = 1;
204 SYSCTL_INT(_debug, OID_AUTO, ncmount_cache_enable, CTLFLAG_RW,
205 &ncmount_cache_enable, 0, "mount point cache");
206 static long ncmount_cache_hit;
207 SYSCTL_LONG(_debug, OID_AUTO, ncmount_cache_hit, CTLFLAG_RW,
208 &ncmount_cache_hit, 0, "mpcache hits");
209 static long ncmount_cache_miss;
210 SYSCTL_LONG(_debug, OID_AUTO, ncmount_cache_miss, CTLFLAG_RW,
211 &ncmount_cache_miss, 0, "mpcache misses");
212 static long ncmount_cache_overwrite;
213 SYSCTL_LONG(_debug, OID_AUTO, ncmount_cache_overwrite, CTLFLAG_RW,
214 &ncmount_cache_overwrite, 0, "mpcache entry overwrites");
216 static int cache_resolve_mp(struct mount *mp);
217 static struct vnode *cache_dvpref(struct namecache *ncp);
218 static void _cache_lock(struct namecache *ncp);
219 static void _cache_setunresolved(struct namecache *ncp);
220 static void _cache_cleanneg(int count);
221 static void _cache_cleanpos(int count);
222 static void _cache_cleandefered(void);
223 static void _cache_unlink(struct namecache *ncp);
226 * The new name cache statistics
228 SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0, "Name cache statistics");
230 SYSCTL_INT(_vfs_cache, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0,
231 "Number of negative namecache entries");
233 SYSCTL_INT(_vfs_cache, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0,
234 "Number of namecaches entries");
235 static u_long numcalls;
236 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcalls, CTLFLAG_RD, &numcalls, 0,
237 "Number of namecache lookups");
238 static u_long numchecks;
239 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numchecks, CTLFLAG_RD, &numchecks, 0,
240 "Number of checked entries in namecache lookups");
242 struct nchstats nchstats[SMP_MAXCPU];
244 * Export VFS cache effectiveness statistics to user-land.
246 * The statistics are left for aggregation to user-land so
247 * neat things can be achieved, like observing per-CPU cache
251 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
253 struct globaldata *gd;
257 for (i = 0; i < ncpus; ++i) {
258 gd = globaldata_find(i);
259 if ((error = SYSCTL_OUT(req, (void *)&(*gd->gd_nchstats),
260 sizeof(struct nchstats))))
266 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE|CTLFLAG_RD,
267 0, 0, sysctl_nchstats, "S,nchstats", "VFS cache effectiveness statistics");
269 static struct namecache *cache_zap(struct namecache *ncp, int nonblock);
272 * Namespace locking. The caller must already hold a reference to the
273 * namecache structure in order to lock/unlock it. This function prevents
274 * the namespace from being created or destroyed by accessors other then
277 * Note that holding a locked namecache structure prevents other threads
278 * from making namespace changes (e.g. deleting or creating), prevents
279 * vnode association state changes by other threads, and prevents the
280 * namecache entry from being resolved or unresolved by other threads.
282 * An exclusive lock owner has full authority to associate/disassociate
283 * vnodes and resolve/unresolve the locked ncp.
285 * A shared lock owner only has authority to acquire the underlying vnode,
288 * The primary lock field is nc_lockstatus. nc_locktd is set after the
289 * fact (when locking) or cleared prior to unlocking.
291 * WARNING! Holding a locked ncp will prevent a vnode from being destroyed
292 * or recycled, but it does NOT help you if the vnode had already
293 * initiated a recyclement. If this is important, use cache_get()
294 * rather then cache_lock() (and deal with the differences in the
295 * way the refs counter is handled). Or, alternatively, make an
296 * unconditional call to cache_validate() or cache_resolve()
297 * after cache_lock() returns.
301 _cache_lock(struct namecache *ncp)
308 KKASSERT(ncp->nc_refs != 0);
313 count = ncp->nc_lockstatus;
316 if ((count & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 0) {
317 if (atomic_cmpset_int(&ncp->nc_lockstatus,
320 * The vp associated with a locked ncp must
321 * be held to prevent it from being recycled.
323 * WARNING! If VRECLAIMED is set the vnode
324 * could already be in the middle of a recycle.
325 * Callers must use cache_vref() or
326 * cache_vget() on the locked ncp to
327 * validate the vp or set the cache entry
330 * NOTE! vhold() is allowed if we hold a
331 * lock on the ncp (which we do).
341 if (ncp->nc_locktd == td) {
342 KKASSERT((count & NC_SHLOCK_FLAG) == 0);
343 if (atomic_cmpset_int(&ncp->nc_lockstatus,
350 tsleep_interlock(&ncp->nc_locktd, 0);
351 if (atomic_cmpset_int(&ncp->nc_lockstatus, count,
352 count | NC_EXLOCK_REQ) == 0) {
356 error = tsleep(&ncp->nc_locktd, PINTERLOCKED,
357 "clock", nclockwarn);
358 if (error == EWOULDBLOCK) {
361 kprintf("[diagnostic] cache_lock: "
362 "blocked on %p %08x",
364 kprintf(" \"%*.*s\"\n",
365 ncp->nc_nlen, ncp->nc_nlen,
372 kprintf("[diagnostic] cache_lock: unblocked %*.*s after "
374 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name,
375 (int)(ticks - didwarn) / hz);
380 * The shared lock works similarly to the exclusive lock except
381 * nc_locktd is left NULL and we need an interlock (VHOLD) to
382 * prevent vhold() races, since the moment our cmpset_int succeeds
383 * another cpu can come in and get its own shared lock.
385 * A critical section is needed to prevent interruption during the
390 _cache_lock_shared(struct namecache *ncp)
396 KKASSERT(ncp->nc_refs != 0);
400 count = ncp->nc_lockstatus;
403 if ((count & ~NC_SHLOCK_REQ) == 0) {
405 if (atomic_cmpset_int(&ncp->nc_lockstatus,
407 (count + 1) | NC_SHLOCK_FLAG |
410 * The vp associated with a locked ncp must
411 * be held to prevent it from being recycled.
413 * WARNING! If VRECLAIMED is set the vnode
414 * could already be in the middle of a recycle.
415 * Callers must use cache_vref() or
416 * cache_vget() on the locked ncp to
417 * validate the vp or set the cache entry
420 * NOTE! vhold() is allowed if we hold a
421 * lock on the ncp (which we do).
425 atomic_clear_int(&ncp->nc_lockstatus,
436 * If already held shared we can just bump the count, but
437 * only allow this if nobody is trying to get the lock
440 * VHOLD is a bit of a hack. Even though we successfully
441 * added another shared ref, the cpu that got the first
442 * shared ref might not yet have held the vnode.
444 if ((count & (NC_EXLOCK_REQ|NC_SHLOCK_FLAG)) ==
446 KKASSERT((count & ~(NC_EXLOCK_REQ |
448 NC_SHLOCK_FLAG)) > 0);
449 if (atomic_cmpset_int(&ncp->nc_lockstatus,
451 while (ncp->nc_lockstatus & NC_SHLOCK_VHOLD)
457 tsleep_interlock(ncp, 0);
458 if (atomic_cmpset_int(&ncp->nc_lockstatus, count,
459 count | NC_SHLOCK_REQ) == 0) {
463 error = tsleep(ncp, PINTERLOCKED, "clocksh", nclockwarn);
464 if (error == EWOULDBLOCK) {
467 kprintf("[diagnostic] cache_lock_shared: "
468 "blocked on %p %08x",
470 kprintf(" \"%*.*s\"\n",
471 ncp->nc_nlen, ncp->nc_nlen,
478 kprintf("[diagnostic] cache_lock_shared: "
479 "unblocked %*.*s after %d secs\n",
480 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name,
481 (int)(ticks - didwarn) / hz);
486 * NOTE: nc_refs may be zero if the ncp is interlocked by circumstance,
487 * such as the case where one of its children is locked.
491 _cache_lock_nonblock(struct namecache *ncp)
499 count = ncp->nc_lockstatus;
501 if ((count & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 0) {
502 if (atomic_cmpset_int(&ncp->nc_lockstatus,
505 * The vp associated with a locked ncp must
506 * be held to prevent it from being recycled.
508 * WARNING! If VRECLAIMED is set the vnode
509 * could already be in the middle of a recycle.
510 * Callers must use cache_vref() or
511 * cache_vget() on the locked ncp to
512 * validate the vp or set the cache entry
515 * NOTE! vhold() is allowed if we hold a
516 * lock on the ncp (which we do).
526 if (ncp->nc_locktd == td) {
527 if (atomic_cmpset_int(&ncp->nc_lockstatus,
540 * The shared lock works similarly to the exclusive lock except
541 * nc_locktd is left NULL and we need an interlock (VHOLD) to
542 * prevent vhold() races, since the moment our cmpset_int succeeds
543 * another cpu can come in and get its own shared lock.
545 * A critical section is needed to prevent interruption during the
550 _cache_lock_shared_nonblock(struct namecache *ncp)
555 count = ncp->nc_lockstatus;
557 if ((count & ~NC_SHLOCK_REQ) == 0) {
559 if (atomic_cmpset_int(&ncp->nc_lockstatus,
561 (count + 1) | NC_SHLOCK_FLAG |
564 * The vp associated with a locked ncp must
565 * be held to prevent it from being recycled.
567 * WARNING! If VRECLAIMED is set the vnode
568 * could already be in the middle of a recycle.
569 * Callers must use cache_vref() or
570 * cache_vget() on the locked ncp to
571 * validate the vp or set the cache entry
574 * NOTE! vhold() is allowed if we hold a
575 * lock on the ncp (which we do).
579 atomic_clear_int(&ncp->nc_lockstatus,
590 * If already held shared we can just bump the count, but
591 * only allow this if nobody is trying to get the lock
594 * VHOLD is a bit of a hack. Even though we successfully
595 * added another shared ref, the cpu that got the first
596 * shared ref might not yet have held the vnode.
598 if ((count & (NC_EXLOCK_REQ|NC_SHLOCK_FLAG)) ==
600 KKASSERT((count & ~(NC_EXLOCK_REQ |
602 NC_SHLOCK_FLAG)) > 0);
603 if (atomic_cmpset_int(&ncp->nc_lockstatus,
605 while (ncp->nc_lockstatus & NC_SHLOCK_VHOLD)
619 * NOTE: nc_refs can be 0 (degenerate case during _cache_drop).
621 * nc_locktd must be NULLed out prior to nc_lockstatus getting cleared.
625 _cache_unlock(struct namecache *ncp)
627 thread_t td __debugvar = curthread;
630 struct vnode *dropvp;
632 KKASSERT(ncp->nc_refs >= 0);
633 KKASSERT((ncp->nc_lockstatus & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) > 0);
634 KKASSERT((ncp->nc_lockstatus & NC_SHLOCK_FLAG) || ncp->nc_locktd == td);
636 count = ncp->nc_lockstatus;
640 * Clear nc_locktd prior to the atomic op (excl lock only)
642 if ((count & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 1)
643 ncp->nc_locktd = NULL;
648 ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ|NC_SHLOCK_FLAG)) == 1) {
650 if (count & NC_EXLOCK_REQ)
651 ncount = count & NC_SHLOCK_REQ; /* cnt->0 */
655 if (atomic_cmpset_int(&ncp->nc_lockstatus,
657 if (count & NC_EXLOCK_REQ)
658 wakeup(&ncp->nc_locktd);
659 else if (count & NC_SHLOCK_REQ)
665 KKASSERT((count & NC_SHLOCK_VHOLD) == 0);
666 KKASSERT((count & ~(NC_EXLOCK_REQ |
668 NC_SHLOCK_FLAG)) > 1);
669 if (atomic_cmpset_int(&ncp->nc_lockstatus,
674 count = ncp->nc_lockstatus;
679 * Don't actually drop the vp until we successfully clean out
680 * the lock, otherwise we may race another shared lock.
688 _cache_lockstatus(struct namecache *ncp)
690 if (ncp->nc_locktd == curthread)
691 return(LK_EXCLUSIVE);
692 if (ncp->nc_lockstatus & NC_SHLOCK_FLAG)
698 * cache_hold() and cache_drop() prevent the premature deletion of a
699 * namecache entry but do not prevent operations (such as zapping) on
700 * that namecache entry.
702 * This routine may only be called from outside this source module if
703 * nc_refs is already at least 1.
705 * This is a rare case where callers are allowed to hold a spinlock,
706 * so we can't ourselves.
710 _cache_hold(struct namecache *ncp)
712 atomic_add_int(&ncp->nc_refs, 1);
717 * Drop a cache entry, taking care to deal with races.
719 * For potential 1->0 transitions we must hold the ncp lock to safely
720 * test its flags. An unresolved entry with no children must be zapped
723 * The call to cache_zap() itself will handle all remaining races and
724 * will decrement the ncp's refs regardless. If we are resolved or
725 * have children nc_refs can safely be dropped to 0 without having to
728 * NOTE: cache_zap() will re-check nc_refs and nc_list in a MPSAFE fashion.
730 * NOTE: cache_zap() may return a non-NULL referenced parent which must
731 * be dropped in a loop.
735 _cache_drop(struct namecache *ncp)
740 KKASSERT(ncp->nc_refs > 0);
744 if (_cache_lock_nonblock(ncp) == 0) {
745 ncp->nc_flag &= ~NCF_DEFEREDZAP;
746 if ((ncp->nc_flag & NCF_UNRESOLVED) &&
747 TAILQ_EMPTY(&ncp->nc_list)) {
748 ncp = cache_zap(ncp, 1);
751 if (atomic_cmpset_int(&ncp->nc_refs, 1, 0)) {
758 if (atomic_cmpset_int(&ncp->nc_refs, refs, refs - 1))
766 * Link a new namecache entry to its parent and to the hash table. Be
767 * careful to avoid races if vhold() blocks in the future.
769 * Both ncp and par must be referenced and locked.
771 * NOTE: The hash table spinlock is held during this call, we can't do
775 _cache_link_parent(struct namecache *ncp, struct namecache *par,
776 struct nchash_head *nchpp)
778 KKASSERT(ncp->nc_parent == NULL);
779 ncp->nc_parent = par;
780 ncp->nc_head = nchpp;
783 * Set inheritance flags. Note that the parent flags may be
784 * stale due to getattr potentially not having been run yet
785 * (it gets run during nlookup()'s).
787 ncp->nc_flag &= ~(NCF_SF_PNOCACHE | NCF_UF_PCACHE);
788 if (par->nc_flag & (NCF_SF_NOCACHE | NCF_SF_PNOCACHE))
789 ncp->nc_flag |= NCF_SF_PNOCACHE;
790 if (par->nc_flag & (NCF_UF_CACHE | NCF_UF_PCACHE))
791 ncp->nc_flag |= NCF_UF_PCACHE;
793 LIST_INSERT_HEAD(&nchpp->list, ncp, nc_hash);
795 if (TAILQ_EMPTY(&par->nc_list)) {
796 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
798 * Any vp associated with an ncp which has children must
799 * be held to prevent it from being recycled.
804 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
809 * Remove the parent and hash associations from a namecache structure.
810 * If this is the last child of the parent the cache_drop(par) will
811 * attempt to recursively zap the parent.
813 * ncp must be locked. This routine will acquire a temporary lock on
814 * the parent as wlel as the appropriate hash chain.
817 _cache_unlink_parent(struct namecache *ncp)
819 struct namecache *par;
820 struct vnode *dropvp;
822 if ((par = ncp->nc_parent) != NULL) {
823 KKASSERT(ncp->nc_parent == par);
826 spin_lock(&ncp->nc_head->spin);
827 LIST_REMOVE(ncp, nc_hash);
828 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
830 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
832 spin_unlock(&ncp->nc_head->spin);
833 ncp->nc_parent = NULL;
839 * We can only safely vdrop with no spinlocks held.
847 * Allocate a new namecache structure. Most of the code does not require
848 * zero-termination of the string but it makes vop_compat_ncreate() easier.
850 static struct namecache *
851 cache_alloc(int nlen)
853 struct namecache *ncp;
855 ncp = kmalloc(sizeof(*ncp), M_VFSCACHE, M_WAITOK|M_ZERO);
857 ncp->nc_name = kmalloc(nlen + 1, M_VFSCACHE, M_WAITOK);
859 ncp->nc_flag = NCF_UNRESOLVED;
860 ncp->nc_error = ENOTCONN; /* needs to be resolved */
863 TAILQ_INIT(&ncp->nc_list);
869 * Can only be called for the case where the ncp has never been
870 * associated with anything (so no spinlocks are needed).
873 _cache_free(struct namecache *ncp)
875 KKASSERT(ncp->nc_refs == 1 && ncp->nc_lockstatus == 1);
877 kfree(ncp->nc_name, M_VFSCACHE);
878 kfree(ncp, M_VFSCACHE);
882 * [re]initialize a nchandle.
885 cache_zero(struct nchandle *nch)
892 * Ref and deref a namecache structure.
894 * The caller must specify a stable ncp pointer, typically meaning the
895 * ncp is already referenced but this can also occur indirectly through
896 * e.g. holding a lock on a direct child.
898 * WARNING: Caller may hold an unrelated read spinlock, which means we can't
899 * use read spinlocks here.
904 cache_hold(struct nchandle *nch)
906 _cache_hold(nch->ncp);
907 atomic_add_int(&nch->mount->mnt_refs, 1);
912 * Create a copy of a namecache handle for an already-referenced
918 cache_copy(struct nchandle *nch, struct nchandle *target)
922 _cache_hold(target->ncp);
923 atomic_add_int(&nch->mount->mnt_refs, 1);
930 cache_changemount(struct nchandle *nch, struct mount *mp)
932 atomic_add_int(&nch->mount->mnt_refs, -1);
934 atomic_add_int(&nch->mount->mnt_refs, 1);
938 cache_drop(struct nchandle *nch)
940 atomic_add_int(&nch->mount->mnt_refs, -1);
941 _cache_drop(nch->ncp);
947 cache_lockstatus(struct nchandle *nch)
949 return(_cache_lockstatus(nch->ncp));
953 cache_lock(struct nchandle *nch)
955 _cache_lock(nch->ncp);
959 cache_lock_maybe_shared(struct nchandle *nch, int excl)
961 struct namecache *ncp = nch->ncp;
963 if (ncp_shared_lock_disable || excl ||
964 (ncp->nc_flag & NCF_UNRESOLVED)) {
967 _cache_lock_shared(ncp);
968 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
969 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED)) {
981 * Relock nch1 given an unlocked nch1 and a locked nch2. The caller
982 * is responsible for checking both for validity on return as they
983 * may have become invalid.
985 * We have to deal with potential deadlocks here, just ping pong
986 * the lock until we get it (we will always block somewhere when
987 * looping so this is not cpu-intensive).
989 * which = 0 nch1 not locked, nch2 is locked
990 * which = 1 nch1 is locked, nch2 is not locked
993 cache_relock(struct nchandle *nch1, struct ucred *cred1,
994 struct nchandle *nch2, struct ucred *cred2)
1002 if (cache_lock_nonblock(nch1) == 0) {
1003 cache_resolve(nch1, cred1);
1008 cache_resolve(nch1, cred1);
1011 if (cache_lock_nonblock(nch2) == 0) {
1012 cache_resolve(nch2, cred2);
1017 cache_resolve(nch2, cred2);
1024 cache_lock_nonblock(struct nchandle *nch)
1026 return(_cache_lock_nonblock(nch->ncp));
1030 cache_unlock(struct nchandle *nch)
1032 _cache_unlock(nch->ncp);
1036 * ref-and-lock, unlock-and-deref functions.
1038 * This function is primarily used by nlookup. Even though cache_lock
1039 * holds the vnode, it is possible that the vnode may have already
1040 * initiated a recyclement.
1042 * We want cache_get() to return a definitively usable vnode or a
1043 * definitively unresolved ncp.
1047 _cache_get(struct namecache *ncp)
1051 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
1052 _cache_setunresolved(ncp);
1057 * Attempt to obtain a shared lock on the ncp. A shared lock will only
1058 * be obtained if the ncp is resolved and the vnode (if not ENOENT) is
1059 * valid. Otherwise an exclusive lock will be acquired instead.
1063 _cache_get_maybe_shared(struct namecache *ncp, int excl)
1065 if (ncp_shared_lock_disable || excl ||
1066 (ncp->nc_flag & NCF_UNRESOLVED)) {
1067 return(_cache_get(ncp));
1070 _cache_lock_shared(ncp);
1071 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1072 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED)) {
1074 ncp = _cache_get(ncp);
1079 ncp = _cache_get(ncp);
1086 * This is a special form of _cache_lock() which only succeeds if
1087 * it can get a pristine, non-recursive lock. The caller must have
1088 * already ref'd the ncp.
1090 * On success the ncp will be locked, on failure it will not. The
1091 * ref count does not change either way.
1093 * We want _cache_lock_special() (on success) to return a definitively
1094 * usable vnode or a definitively unresolved ncp.
1097 _cache_lock_special(struct namecache *ncp)
1099 if (_cache_lock_nonblock(ncp) == 0) {
1100 if ((ncp->nc_lockstatus &
1101 ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 1) {
1102 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
1103 _cache_setunresolved(ncp);
1108 return(EWOULDBLOCK);
1112 _cache_lock_shared_special(struct namecache *ncp)
1114 if (_cache_lock_shared_nonblock(ncp) == 0) {
1115 if ((ncp->nc_lockstatus &
1116 ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == (NC_SHLOCK_FLAG | 1)) {
1117 if (ncp->nc_vp == NULL ||
1118 (ncp->nc_vp->v_flag & VRECLAIMED) == 0) {
1124 return(EWOULDBLOCK);
1129 * NOTE: The same nchandle can be passed for both arguments.
1132 cache_get(struct nchandle *nch, struct nchandle *target)
1134 KKASSERT(nch->ncp->nc_refs > 0);
1135 target->mount = nch->mount;
1136 target->ncp = _cache_get(nch->ncp);
1137 atomic_add_int(&target->mount->mnt_refs, 1);
1141 cache_get_maybe_shared(struct nchandle *nch, struct nchandle *target, int excl)
1143 KKASSERT(nch->ncp->nc_refs > 0);
1144 target->mount = nch->mount;
1145 target->ncp = _cache_get_maybe_shared(nch->ncp, excl);
1146 atomic_add_int(&target->mount->mnt_refs, 1);
1154 _cache_put(struct namecache *ncp)
1164 cache_put(struct nchandle *nch)
1166 atomic_add_int(&nch->mount->mnt_refs, -1);
1167 _cache_put(nch->ncp);
1173 * Resolve an unresolved ncp by associating a vnode with it. If the
1174 * vnode is NULL, a negative cache entry is created.
1176 * The ncp should be locked on entry and will remain locked on return.
1180 _cache_setvp(struct mount *mp, struct namecache *ncp, struct vnode *vp)
1182 KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
1183 KKASSERT(_cache_lockstatus(ncp) == LK_EXCLUSIVE);
1187 * Any vp associated with an ncp which has children must
1188 * be held. Any vp associated with a locked ncp must be held.
1190 if (!TAILQ_EMPTY(&ncp->nc_list))
1192 spin_lock(&vp->v_spin);
1194 TAILQ_INSERT_HEAD(&vp->v_namecache, ncp, nc_vnode);
1195 spin_unlock(&vp->v_spin);
1196 if (ncp->nc_lockstatus & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ))
1200 * Set auxiliary flags
1202 switch(vp->v_type) {
1204 ncp->nc_flag |= NCF_ISDIR;
1207 ncp->nc_flag |= NCF_ISSYMLINK;
1208 /* XXX cache the contents of the symlink */
1213 atomic_add_int(&numcache, 1);
1215 /* XXX: this is a hack to work-around the lack of a real pfs vfs
1218 if (strncmp(mp->mnt_stat.f_fstypename, "null", 5) == 0)
1222 * When creating a negative cache hit we set the
1223 * namecache_gen. A later resolve will clean out the
1224 * negative cache hit if the mount point's namecache_gen
1225 * has changed. Used by devfs, could also be used by
1230 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
1232 spin_unlock(&ncspin);
1233 ncp->nc_error = ENOENT;
1235 VFS_NCPGEN_SET(mp, ncp);
1237 ncp->nc_flag &= ~(NCF_UNRESOLVED | NCF_DEFEREDZAP);
1244 cache_setvp(struct nchandle *nch, struct vnode *vp)
1246 _cache_setvp(nch->mount, nch->ncp, vp);
1253 cache_settimeout(struct nchandle *nch, int nticks)
1255 struct namecache *ncp = nch->ncp;
1257 if ((ncp->nc_timeout = ticks + nticks) == 0)
1258 ncp->nc_timeout = 1;
1262 * Disassociate the vnode or negative-cache association and mark a
1263 * namecache entry as unresolved again. Note that the ncp is still
1264 * left in the hash table and still linked to its parent.
1266 * The ncp should be locked and refd on entry and will remain locked and refd
1269 * This routine is normally never called on a directory containing children.
1270 * However, NFS often does just that in its rename() code as a cop-out to
1271 * avoid complex namespace operations. This disconnects a directory vnode
1272 * from its namecache and can cause the OLDAPI and NEWAPI to get out of
1278 _cache_setunresolved(struct namecache *ncp)
1282 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1283 ncp->nc_flag |= NCF_UNRESOLVED;
1284 ncp->nc_timeout = 0;
1285 ncp->nc_error = ENOTCONN;
1286 if ((vp = ncp->nc_vp) != NULL) {
1287 atomic_add_int(&numcache, -1);
1288 spin_lock(&vp->v_spin);
1290 TAILQ_REMOVE(&vp->v_namecache, ncp, nc_vnode);
1291 spin_unlock(&vp->v_spin);
1294 * Any vp associated with an ncp with children is
1295 * held by that ncp. Any vp associated with a locked
1296 * ncp is held by that ncp. These conditions must be
1297 * undone when the vp is cleared out from the ncp.
1299 if (!TAILQ_EMPTY(&ncp->nc_list))
1301 if (ncp->nc_lockstatus & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ))
1305 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
1307 spin_unlock(&ncspin);
1309 ncp->nc_flag &= ~(NCF_WHITEOUT|NCF_ISDIR|NCF_ISSYMLINK);
1314 * The cache_nresolve() code calls this function to automatically
1315 * set a resolved cache element to unresolved if it has timed out
1316 * or if it is a negative cache hit and the mount point namecache_gen
1320 _cache_auto_unresolve_test(struct mount *mp, struct namecache *ncp)
1323 * Try to zap entries that have timed out. We have
1324 * to be careful here because locked leafs may depend
1325 * on the vnode remaining intact in a parent, so only
1326 * do this under very specific conditions.
1328 if (ncp->nc_timeout && (int)(ncp->nc_timeout - ticks) < 0 &&
1329 TAILQ_EMPTY(&ncp->nc_list)) {
1334 * If a resolved negative cache hit is invalid due to
1335 * the mount's namecache generation being bumped, zap it.
1337 if (ncp->nc_vp == NULL && VFS_NCPGEN_TEST(mp, ncp)) {
1342 * Otherwise we are good
1347 static __inline void
1348 _cache_auto_unresolve(struct mount *mp, struct namecache *ncp)
1351 * Already in an unresolved state, nothing to do.
1353 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1354 if (_cache_auto_unresolve_test(mp, ncp))
1355 _cache_setunresolved(ncp);
1363 cache_setunresolved(struct nchandle *nch)
1365 _cache_setunresolved(nch->ncp);
1369 * Determine if we can clear NCF_ISMOUNTPT by scanning the mountlist
1370 * looking for matches. This flag tells the lookup code when it must
1371 * check for a mount linkage and also prevents the directories in question
1372 * from being deleted or renamed.
1376 cache_clrmountpt_callback(struct mount *mp, void *data)
1378 struct nchandle *nch = data;
1380 if (mp->mnt_ncmounton.ncp == nch->ncp)
1382 if (mp->mnt_ncmountpt.ncp == nch->ncp)
1391 cache_clrmountpt(struct nchandle *nch)
1395 count = mountlist_scan(cache_clrmountpt_callback, nch,
1396 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1398 nch->ncp->nc_flag &= ~NCF_ISMOUNTPT;
1402 * Invalidate portions of the namecache topology given a starting entry.
1403 * The passed ncp is set to an unresolved state and:
1405 * The passed ncp must be referencxed and locked. The routine may unlock
1406 * and relock ncp several times, and will recheck the children and loop
1407 * to catch races. When done the passed ncp will be returned with the
1408 * reference and lock intact.
1410 * CINV_DESTROY - Set a flag in the passed ncp entry indicating
1411 * that the physical underlying nodes have been
1412 * destroyed... as in deleted. For example, when
1413 * a directory is removed. This will cause record
1414 * lookups on the name to no longer be able to find
1415 * the record and tells the resolver to return failure
1416 * rather then trying to resolve through the parent.
1418 * The topology itself, including ncp->nc_name,
1421 * This only applies to the passed ncp, if CINV_CHILDREN
1422 * is specified the children are not flagged.
1424 * CINV_CHILDREN - Set all children (recursively) to an unresolved
1427 * Note that this will also have the side effect of
1428 * cleaning out any unreferenced nodes in the topology
1429 * from the leaves up as the recursion backs out.
1431 * Note that the topology for any referenced nodes remains intact, but
1432 * the nodes will be marked as having been destroyed and will be set
1433 * to an unresolved state.
1435 * It is possible for cache_inval() to race a cache_resolve(), meaning that
1436 * the namecache entry may not actually be invalidated on return if it was
1437 * revalidated while recursing down into its children. This code guarentees
1438 * that the node(s) will go through an invalidation cycle, but does not
1439 * guarentee that they will remain in an invalidated state.
1441 * Returns non-zero if a revalidation was detected during the invalidation
1442 * recursion, zero otherwise. Note that since only the original ncp is
1443 * locked the revalidation ultimately can only indicate that the original ncp
1444 * *MIGHT* no have been reresolved.
1446 * DEEP RECURSION HANDLING - If a recursive invalidation recurses deeply we
1447 * have to avoid blowing out the kernel stack. We do this by saving the
1448 * deep namecache node and aborting the recursion, then re-recursing at that
1449 * node using a depth-first algorithm in order to allow multiple deep
1450 * recursions to chain through each other, then we restart the invalidation
1455 struct namecache *resume_ncp;
1459 static int _cache_inval_internal(struct namecache *, int, struct cinvtrack *);
1463 _cache_inval(struct namecache *ncp, int flags)
1465 struct cinvtrack track;
1466 struct namecache *ncp2;
1470 track.resume_ncp = NULL;
1473 r = _cache_inval_internal(ncp, flags, &track);
1474 if (track.resume_ncp == NULL)
1476 kprintf("Warning: deep namecache recursion at %s\n",
1479 while ((ncp2 = track.resume_ncp) != NULL) {
1480 track.resume_ncp = NULL;
1482 _cache_inval_internal(ncp2, flags & ~CINV_DESTROY,
1492 cache_inval(struct nchandle *nch, int flags)
1494 return(_cache_inval(nch->ncp, flags));
1498 * Helper for _cache_inval(). The passed ncp is refd and locked and
1499 * remains that way on return, but may be unlocked/relocked multiple
1500 * times by the routine.
1503 _cache_inval_internal(struct namecache *ncp, int flags, struct cinvtrack *track)
1505 struct namecache *kid;
1506 struct namecache *nextkid;
1509 KKASSERT(_cache_lockstatus(ncp) == LK_EXCLUSIVE);
1511 _cache_setunresolved(ncp);
1512 if (flags & CINV_DESTROY)
1513 ncp->nc_flag |= NCF_DESTROYED;
1514 if ((flags & CINV_CHILDREN) &&
1515 (kid = TAILQ_FIRST(&ncp->nc_list)) != NULL
1518 if (++track->depth > MAX_RECURSION_DEPTH) {
1519 track->resume_ncp = ncp;
1525 if (track->resume_ncp) {
1529 if ((nextkid = TAILQ_NEXT(kid, nc_entry)) != NULL)
1530 _cache_hold(nextkid);
1531 if ((kid->nc_flag & NCF_UNRESOLVED) == 0 ||
1532 TAILQ_FIRST(&kid->nc_list)
1535 rcnt += _cache_inval_internal(kid, flags & ~CINV_DESTROY, track);
1546 * Someone could have gotten in there while ncp was unlocked,
1549 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
1555 * Invalidate a vnode's namecache associations. To avoid races against
1556 * the resolver we do not invalidate a node which we previously invalidated
1557 * but which was then re-resolved while we were in the invalidation loop.
1559 * Returns non-zero if any namecache entries remain after the invalidation
1562 * NOTE: Unlike the namecache topology which guarentees that ncp's will not
1563 * be ripped out of the topology while held, the vnode's v_namecache
1564 * list has no such restriction. NCP's can be ripped out of the list
1565 * at virtually any time if not locked, even if held.
1567 * In addition, the v_namecache list itself must be locked via
1568 * the vnode's spinlock.
1571 cache_inval_vp(struct vnode *vp, int flags)
1573 struct namecache *ncp;
1574 struct namecache *next;
1577 spin_lock(&vp->v_spin);
1578 ncp = TAILQ_FIRST(&vp->v_namecache);
1582 /* loop entered with ncp held and vp spin-locked */
1583 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1585 spin_unlock(&vp->v_spin);
1587 if (ncp->nc_vp != vp) {
1588 kprintf("Warning: cache_inval_vp: race-A detected on "
1589 "%s\n", ncp->nc_name);
1595 _cache_inval(ncp, flags);
1596 _cache_put(ncp); /* also releases reference */
1598 spin_lock(&vp->v_spin);
1599 if (ncp && ncp->nc_vp != vp) {
1600 spin_unlock(&vp->v_spin);
1601 kprintf("Warning: cache_inval_vp: race-B detected on "
1602 "%s\n", ncp->nc_name);
1607 spin_unlock(&vp->v_spin);
1608 return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1612 * This routine is used instead of the normal cache_inval_vp() when we
1613 * are trying to recycle otherwise good vnodes.
1615 * Return 0 on success, non-zero if not all namecache records could be
1616 * disassociated from the vnode (for various reasons).
1619 cache_inval_vp_nonblock(struct vnode *vp)
1621 struct namecache *ncp;
1622 struct namecache *next;
1624 spin_lock(&vp->v_spin);
1625 ncp = TAILQ_FIRST(&vp->v_namecache);
1629 /* loop entered with ncp held */
1630 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1632 spin_unlock(&vp->v_spin);
1633 if (_cache_lock_nonblock(ncp)) {
1639 if (ncp->nc_vp != vp) {
1640 kprintf("Warning: cache_inval_vp: race-A detected on "
1641 "%s\n", ncp->nc_name);
1647 _cache_inval(ncp, 0);
1648 _cache_put(ncp); /* also releases reference */
1650 spin_lock(&vp->v_spin);
1651 if (ncp && ncp->nc_vp != vp) {
1652 spin_unlock(&vp->v_spin);
1653 kprintf("Warning: cache_inval_vp: race-B detected on "
1654 "%s\n", ncp->nc_name);
1659 spin_unlock(&vp->v_spin);
1661 return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1665 * The source ncp has been renamed to the target ncp. Both fncp and tncp
1666 * must be locked. The target ncp is destroyed (as a normal rename-over
1667 * would destroy the target file or directory).
1669 * Because there may be references to the source ncp we cannot copy its
1670 * contents to the target. Instead the source ncp is relinked as the target
1671 * and the target ncp is removed from the namecache topology.
1674 cache_rename(struct nchandle *fnch, struct nchandle *tnch)
1676 struct namecache *fncp = fnch->ncp;
1677 struct namecache *tncp = tnch->ncp;
1678 struct namecache *tncp_par;
1679 struct nchash_head *nchpp;
1684 if (tncp->nc_nlen) {
1685 nname = kmalloc(tncp->nc_nlen + 1, M_VFSCACHE, M_WAITOK);
1686 bcopy(tncp->nc_name, nname, tncp->nc_nlen);
1687 nname[tncp->nc_nlen] = 0;
1693 * Rename fncp (unlink)
1695 _cache_unlink_parent(fncp);
1696 oname = fncp->nc_name;
1697 fncp->nc_name = nname;
1698 fncp->nc_nlen = tncp->nc_nlen;
1700 kfree(oname, M_VFSCACHE);
1702 tncp_par = tncp->nc_parent;
1703 _cache_hold(tncp_par);
1704 _cache_lock(tncp_par);
1707 * Rename fncp (relink)
1709 hash = fnv_32_buf(fncp->nc_name, fncp->nc_nlen, FNV1_32_INIT);
1710 hash = fnv_32_buf(&tncp_par, sizeof(tncp_par), hash);
1711 nchpp = NCHHASH(hash);
1713 spin_lock(&nchpp->spin);
1714 _cache_link_parent(fncp, tncp_par, nchpp);
1715 spin_unlock(&nchpp->spin);
1717 _cache_put(tncp_par);
1720 * Get rid of the overwritten tncp (unlink)
1722 _cache_unlink(tncp);
1726 * Perform actions consistent with unlinking a file. The passed-in ncp
1729 * The ncp is marked DESTROYED so it no longer shows up in searches,
1730 * and will be physically deleted when the vnode goes away.
1732 * If the related vnode has no refs then we cycle it through vget()/vput()
1733 * to (possibly if we don't have a ref race) trigger a deactivation,
1734 * allowing the VFS to trivially detect and recycle the deleted vnode
1735 * via VOP_INACTIVE().
1737 * NOTE: _cache_rename() will automatically call _cache_unlink() on the
1741 cache_unlink(struct nchandle *nch)
1743 _cache_unlink(nch->ncp);
1747 _cache_unlink(struct namecache *ncp)
1752 * Causes lookups to fail and allows another ncp with the same
1753 * name to be created under ncp->nc_parent.
1755 ncp->nc_flag |= NCF_DESTROYED;
1758 * Attempt to trigger a deactivation.
1760 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
1761 (vp = ncp->nc_vp) != NULL &&
1762 !sysref_isactive(&vp->v_sysref)) {
1763 if (vget(vp, LK_SHARED) == 0)
1769 * vget the vnode associated with the namecache entry. Resolve the namecache
1770 * entry if necessary. The passed ncp must be referenced and locked.
1772 * lk_type may be LK_SHARED, LK_EXCLUSIVE. A ref'd, possibly locked
1773 * (depending on the passed lk_type) will be returned in *vpp with an error
1774 * of 0, or NULL will be returned in *vpp with a non-0 error code. The
1775 * most typical error is ENOENT, meaning that the ncp represents a negative
1776 * cache hit and there is no vnode to retrieve, but other errors can occur
1779 * The vget() can race a reclaim. If this occurs we re-resolve the
1782 * There are numerous places in the kernel where vget() is called on a
1783 * vnode while one or more of its namecache entries is locked. Releasing
1784 * a vnode never deadlocks against locked namecache entries (the vnode
1785 * will not get recycled while referenced ncp's exist). This means we
1786 * can safely acquire the vnode. In fact, we MUST NOT release the ncp
1787 * lock when acquiring the vp lock or we might cause a deadlock.
1789 * NOTE: The passed-in ncp must be locked exclusively if it is initially
1790 * unresolved. If a reclaim race occurs the passed-in ncp will be
1791 * relocked exclusively before being re-resolved.
1794 cache_vget(struct nchandle *nch, struct ucred *cred,
1795 int lk_type, struct vnode **vpp)
1797 struct namecache *ncp;
1804 if (ncp->nc_flag & NCF_UNRESOLVED)
1805 error = cache_resolve(nch, cred);
1809 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1810 error = vget(vp, lk_type);
1815 if (error == ENOENT) {
1816 kprintf("Warning: vnode reclaim race detected "
1817 "in cache_vget on %p (%s)\n",
1821 _cache_setunresolved(ncp);
1826 * Not a reclaim race, some other error.
1828 KKASSERT(ncp->nc_vp == vp);
1831 KKASSERT(ncp->nc_vp == vp);
1832 KKASSERT((vp->v_flag & VRECLAIMED) == 0);
1835 if (error == 0 && vp == NULL)
1842 * Similar to cache_vget() but only acquires a ref on the vnode.
1844 * NOTE: The passed-in ncp must be locked exclusively if it is initially
1845 * unresolved. If a reclaim race occurs the passed-in ncp will be
1846 * relocked exclusively before being re-resolved.
1849 cache_vref(struct nchandle *nch, struct ucred *cred, struct vnode **vpp)
1851 struct namecache *ncp;
1858 if (ncp->nc_flag & NCF_UNRESOLVED)
1859 error = cache_resolve(nch, cred);
1863 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1864 error = vget(vp, LK_SHARED);
1869 if (error == ENOENT) {
1870 kprintf("Warning: vnode reclaim race detected "
1871 "in cache_vget on %p (%s)\n",
1875 _cache_setunresolved(ncp);
1880 * Not a reclaim race, some other error.
1882 KKASSERT(ncp->nc_vp == vp);
1885 KKASSERT(ncp->nc_vp == vp);
1886 KKASSERT((vp->v_flag & VRECLAIMED) == 0);
1887 /* caller does not want a lock */
1891 if (error == 0 && vp == NULL)
1898 * Return a referenced vnode representing the parent directory of
1901 * Because the caller has locked the ncp it should not be possible for
1902 * the parent ncp to go away. However, the parent can unresolve its
1903 * dvp at any time so we must be able to acquire a lock on the parent
1904 * to safely access nc_vp.
1906 * We have to leave par unlocked when vget()ing dvp to avoid a deadlock,
1907 * so use vhold()/vdrop() while holding the lock to prevent dvp from
1908 * getting destroyed.
1910 * NOTE: vhold() is allowed when dvp has 0 refs if we hold a
1911 * lock on the ncp in question..
1913 static struct vnode *
1914 cache_dvpref(struct namecache *ncp)
1916 struct namecache *par;
1920 if ((par = ncp->nc_parent) != NULL) {
1923 if ((par->nc_flag & NCF_UNRESOLVED) == 0) {
1924 if ((dvp = par->nc_vp) != NULL)
1929 if (vget(dvp, LK_SHARED) == 0) {
1932 /* return refd, unlocked dvp */
1944 * Convert a directory vnode to a namecache record without any other
1945 * knowledge of the topology. This ONLY works with directory vnodes and
1946 * is ONLY used by the NFS server. dvp must be refd but unlocked, and the
1947 * returned ncp (if not NULL) will be held and unlocked.
1949 * If 'makeit' is 0 and dvp has no existing namecache record, NULL is returned.
1950 * If 'makeit' is 1 we attempt to track-down and create the namecache topology
1951 * for dvp. This will fail only if the directory has been deleted out from
1954 * Callers must always check for a NULL return no matter the value of 'makeit'.
1956 * To avoid underflowing the kernel stack each recursive call increments
1957 * the makeit variable.
1960 static int cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1961 struct vnode *dvp, char *fakename);
1962 static int cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1963 struct vnode **saved_dvp);
1966 cache_fromdvp(struct vnode *dvp, struct ucred *cred, int makeit,
1967 struct nchandle *nch)
1969 struct vnode *saved_dvp;
1975 nch->mount = dvp->v_mount;
1980 * Handle the makeit == 0 degenerate case
1983 spin_lock(&dvp->v_spin);
1984 nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
1987 spin_unlock(&dvp->v_spin);
1991 * Loop until resolution, inside code will break out on error.
1995 * Break out if we successfully acquire a working ncp.
1997 spin_lock(&dvp->v_spin);
1998 nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
2001 spin_unlock(&dvp->v_spin);
2004 spin_unlock(&dvp->v_spin);
2007 * If dvp is the root of its filesystem it should already
2008 * have a namecache pointer associated with it as a side
2009 * effect of the mount, but it may have been disassociated.
2011 if (dvp->v_flag & VROOT) {
2012 nch->ncp = _cache_get(nch->mount->mnt_ncmountpt.ncp);
2013 error = cache_resolve_mp(nch->mount);
2014 _cache_put(nch->ncp);
2016 kprintf("cache_fromdvp: resolve root of mount %p error %d",
2017 dvp->v_mount, error);
2021 kprintf(" failed\n");
2026 kprintf(" succeeded\n");
2031 * If we are recursed too deeply resort to an O(n^2)
2032 * algorithm to resolve the namecache topology. The
2033 * resolved pvp is left referenced in saved_dvp to
2034 * prevent the tree from being destroyed while we loop.
2037 error = cache_fromdvp_try(dvp, cred, &saved_dvp);
2039 kprintf("lookupdotdot(longpath) failed %d "
2040 "dvp %p\n", error, dvp);
2048 * Get the parent directory and resolve its ncp.
2051 kfree(fakename, M_TEMP);
2054 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
2057 kprintf("lookupdotdot failed %d dvp %p\n", error, dvp);
2063 * Reuse makeit as a recursion depth counter. On success
2064 * nch will be fully referenced.
2066 cache_fromdvp(pvp, cred, makeit + 1, nch);
2068 if (nch->ncp == NULL)
2072 * Do an inefficient scan of pvp (embodied by ncp) to look
2073 * for dvp. This will create a namecache record for dvp on
2074 * success. We loop up to recheck on success.
2076 * ncp and dvp are both held but not locked.
2078 error = cache_inefficient_scan(nch, cred, dvp, fakename);
2080 kprintf("cache_fromdvp: scan %p (%s) failed on dvp=%p\n",
2081 pvp, nch->ncp->nc_name, dvp);
2083 /* nch was NULLed out, reload mount */
2084 nch->mount = dvp->v_mount;
2088 kprintf("cache_fromdvp: scan %p (%s) succeeded\n",
2089 pvp, nch->ncp->nc_name);
2092 /* nch was NULLed out, reload mount */
2093 nch->mount = dvp->v_mount;
2097 * If nch->ncp is non-NULL it will have been held already.
2100 kfree(fakename, M_TEMP);
2109 * Go up the chain of parent directories until we find something
2110 * we can resolve into the namecache. This is very inefficient.
2114 cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
2115 struct vnode **saved_dvp)
2117 struct nchandle nch;
2120 static time_t last_fromdvp_report;
2124 * Loop getting the parent directory vnode until we get something we
2125 * can resolve in the namecache.
2128 nch.mount = dvp->v_mount;
2134 kfree(fakename, M_TEMP);
2137 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
2144 spin_lock(&pvp->v_spin);
2145 if ((nch.ncp = TAILQ_FIRST(&pvp->v_namecache)) != NULL) {
2146 _cache_hold(nch.ncp);
2147 spin_unlock(&pvp->v_spin);
2151 spin_unlock(&pvp->v_spin);
2152 if (pvp->v_flag & VROOT) {
2153 nch.ncp = _cache_get(pvp->v_mount->mnt_ncmountpt.ncp);
2154 error = cache_resolve_mp(nch.mount);
2155 _cache_unlock(nch.ncp);
2158 _cache_drop(nch.ncp);
2168 if (last_fromdvp_report != time_second) {
2169 last_fromdvp_report = time_second;
2170 kprintf("Warning: extremely inefficient path "
2171 "resolution on %s\n",
2174 error = cache_inefficient_scan(&nch, cred, dvp, fakename);
2177 * Hopefully dvp now has a namecache record associated with
2178 * it. Leave it referenced to prevent the kernel from
2179 * recycling the vnode. Otherwise extremely long directory
2180 * paths could result in endless recycling.
2185 _cache_drop(nch.ncp);
2188 kfree(fakename, M_TEMP);
2193 * Do an inefficient scan of the directory represented by ncp looking for
2194 * the directory vnode dvp. ncp must be held but not locked on entry and
2195 * will be held on return. dvp must be refd but not locked on entry and
2196 * will remain refd on return.
2198 * Why do this at all? Well, due to its stateless nature the NFS server
2199 * converts file handles directly to vnodes without necessarily going through
2200 * the namecache ops that would otherwise create the namecache topology
2201 * leading to the vnode. We could either (1) Change the namecache algorithms
2202 * to allow disconnect namecache records that are re-merged opportunistically,
2203 * or (2) Make the NFS server backtrack and scan to recover a connected
2204 * namecache topology in order to then be able to issue new API lookups.
2206 * It turns out that (1) is a huge mess. It takes a nice clean set of
2207 * namecache algorithms and introduces a lot of complication in every subsystem
2208 * that calls into the namecache to deal with the re-merge case, especially
2209 * since we are using the namecache to placehold negative lookups and the
2210 * vnode might not be immediately assigned. (2) is certainly far less
2211 * efficient then (1), but since we are only talking about directories here
2212 * (which are likely to remain cached), the case does not actually run all
2213 * that often and has the supreme advantage of not polluting the namecache
2216 * If a fakename is supplied just construct a namecache entry using the
2220 cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
2221 struct vnode *dvp, char *fakename)
2223 struct nlcomponent nlc;
2224 struct nchandle rncp;
2236 vat.va_blocksize = 0;
2237 if ((error = VOP_GETATTR(dvp, &vat)) != 0)
2240 error = cache_vref(nch, cred, &pvp);
2245 kprintf("inefficient_scan: directory iosize %ld "
2246 "vattr fileid = %lld\n",
2248 (long long)vat.va_fileid);
2252 * Use the supplied fakename if not NULL. Fake names are typically
2253 * not in the actual filesystem hierarchy. This is used by HAMMER
2254 * to glue @@timestamp recursions together.
2257 nlc.nlc_nameptr = fakename;
2258 nlc.nlc_namelen = strlen(fakename);
2259 rncp = cache_nlookup(nch, &nlc);
2263 if ((blksize = vat.va_blocksize) == 0)
2264 blksize = DEV_BSIZE;
2265 rbuf = kmalloc(blksize, M_TEMP, M_WAITOK);
2271 iov.iov_base = rbuf;
2272 iov.iov_len = blksize;
2275 uio.uio_resid = blksize;
2276 uio.uio_segflg = UIO_SYSSPACE;
2277 uio.uio_rw = UIO_READ;
2278 uio.uio_td = curthread;
2280 if (ncvp_debug >= 2)
2281 kprintf("cache_inefficient_scan: readdir @ %08x\n", (int)uio.uio_offset);
2282 error = VOP_READDIR(pvp, &uio, cred, &eofflag, NULL, NULL);
2284 den = (struct dirent *)rbuf;
2285 bytes = blksize - uio.uio_resid;
2288 if (ncvp_debug >= 2) {
2289 kprintf("cache_inefficient_scan: %*.*s\n",
2290 den->d_namlen, den->d_namlen,
2293 if (den->d_type != DT_WHT &&
2294 den->d_ino == vat.va_fileid) {
2296 kprintf("cache_inefficient_scan: "
2297 "MATCHED inode %lld path %s/%*.*s\n",
2298 (long long)vat.va_fileid,
2300 den->d_namlen, den->d_namlen,
2303 nlc.nlc_nameptr = den->d_name;
2304 nlc.nlc_namelen = den->d_namlen;
2305 rncp = cache_nlookup(nch, &nlc);
2306 KKASSERT(rncp.ncp != NULL);
2309 bytes -= _DIRENT_DIRSIZ(den);
2310 den = _DIRENT_NEXT(den);
2312 if (rncp.ncp == NULL && eofflag == 0 && uio.uio_resid != blksize)
2315 kfree(rbuf, M_TEMP);
2319 if (rncp.ncp->nc_flag & NCF_UNRESOLVED) {
2320 _cache_setvp(rncp.mount, rncp.ncp, dvp);
2321 if (ncvp_debug >= 2) {
2322 kprintf("cache_inefficient_scan: setvp %s/%s = %p\n",
2323 nch->ncp->nc_name, rncp.ncp->nc_name, dvp);
2326 if (ncvp_debug >= 2) {
2327 kprintf("cache_inefficient_scan: setvp %s/%s already set %p/%p\n",
2328 nch->ncp->nc_name, rncp.ncp->nc_name, dvp,
2332 if (rncp.ncp->nc_vp == NULL)
2333 error = rncp.ncp->nc_error;
2335 * Release rncp after a successful nlookup. rncp was fully
2340 kprintf("cache_inefficient_scan: dvp %p NOT FOUND in %s\n",
2341 dvp, nch->ncp->nc_name);
2348 * Zap a namecache entry. The ncp is unconditionally set to an unresolved
2349 * state, which disassociates it from its vnode or ncneglist.
2351 * Then, if there are no additional references to the ncp and no children,
2352 * the ncp is removed from the topology and destroyed.
2354 * References and/or children may exist if the ncp is in the middle of the
2355 * topology, preventing the ncp from being destroyed.
2357 * This function must be called with the ncp held and locked and will unlock
2358 * and drop it during zapping.
2360 * If nonblock is non-zero and the parent ncp cannot be locked we give up.
2361 * This case can occur in the cache_drop() path.
2363 * This function may returned a held (but NOT locked) parent node which the
2364 * caller must drop. We do this so _cache_drop() can loop, to avoid
2365 * blowing out the kernel stack.
2367 * WARNING! For MPSAFE operation this routine must acquire up to three
2368 * spin locks to be able to safely test nc_refs. Lock order is
2371 * hash spinlock if on hash list
2372 * parent spinlock if child of parent
2373 * (the ncp is unresolved so there is no vnode association)
2375 static struct namecache *
2376 cache_zap(struct namecache *ncp, int nonblock)
2378 struct namecache *par;
2379 struct vnode *dropvp;
2383 * Disassociate the vnode or negative cache ref and set NCF_UNRESOLVED.
2385 _cache_setunresolved(ncp);
2388 * Try to scrap the entry and possibly tail-recurse on its parent.
2389 * We only scrap unref'd (other then our ref) unresolved entries,
2390 * we do not scrap 'live' entries.
2392 * Note that once the spinlocks are acquired if nc_refs == 1 no
2393 * other references are possible. If it isn't, however, we have
2394 * to decrement but also be sure to avoid a 1->0 transition.
2396 KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
2397 KKASSERT(ncp->nc_refs > 0);
2400 * Acquire locks. Note that the parent can't go away while we hold
2403 if ((par = ncp->nc_parent) != NULL) {
2406 if (_cache_lock_nonblock(par) == 0)
2408 refs = ncp->nc_refs;
2409 ncp->nc_flag |= NCF_DEFEREDZAP;
2410 ++numdefered; /* MP race ok */
2411 if (atomic_cmpset_int(&ncp->nc_refs,
2423 spin_lock(&ncp->nc_head->spin);
2427 * If someone other then us has a ref or we have children
2428 * we cannot zap the entry. The 1->0 transition and any
2429 * further list operation is protected by the spinlocks
2430 * we have acquired but other transitions are not.
2433 refs = ncp->nc_refs;
2434 if (refs == 1 && TAILQ_EMPTY(&ncp->nc_list))
2436 if (atomic_cmpset_int(&ncp->nc_refs, refs, refs - 1)) {
2438 spin_unlock(&ncp->nc_head->spin);
2448 * We are the only ref and with the spinlocks held no further
2449 * refs can be acquired by others.
2451 * Remove us from the hash list and parent list. We have to
2452 * drop a ref on the parent's vp if the parent's list becomes
2457 struct nchash_head *nchpp = ncp->nc_head;
2459 KKASSERT(nchpp != NULL);
2460 LIST_REMOVE(ncp, nc_hash);
2461 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
2462 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
2463 dropvp = par->nc_vp;
2464 ncp->nc_head = NULL;
2465 ncp->nc_parent = NULL;
2466 spin_unlock(&nchpp->spin);
2469 KKASSERT(ncp->nc_head == NULL);
2473 * ncp should not have picked up any refs. Physically
2476 KKASSERT(ncp->nc_refs == 1);
2477 /* _cache_unlock(ncp) not required */
2478 ncp->nc_refs = -1; /* safety */
2480 kfree(ncp->nc_name, M_VFSCACHE);
2481 kfree(ncp, M_VFSCACHE);
2484 * Delayed drop (we had to release our spinlocks)
2486 * The refed parent (if not NULL) must be dropped. The
2487 * caller is responsible for looping.
2495 * Clean up dangling negative cache and defered-drop entries in the
2498 * This routine is called in the critical path and also called from
2499 * vnlru(). When called from vnlru we use a lower limit to try to
2500 * deal with the negative cache before the critical path has to start
2503 typedef enum { CHI_LOW, CHI_HIGH } cache_hs_t;
2505 static cache_hs_t neg_cache_hysteresis_state[2] = { CHI_LOW, CHI_LOW };
2506 static cache_hs_t pos_cache_hysteresis_state[2] = { CHI_LOW, CHI_LOW };
2509 cache_hysteresis(int critpath)
2512 int neglimit = desiredvnodes / ncnegfactor;
2513 int xnumcache = numcache;
2516 neglimit = neglimit * 8 / 10;
2519 * Don't cache too many negative hits. We use hysteresis to reduce
2520 * the impact on the critical path.
2522 switch(neg_cache_hysteresis_state[critpath]) {
2524 if (numneg > MINNEG && numneg > neglimit) {
2526 _cache_cleanneg(ncnegflush);
2528 _cache_cleanneg(ncnegflush +
2530 neg_cache_hysteresis_state[critpath] = CHI_HIGH;
2534 if (numneg > MINNEG * 9 / 10 &&
2535 numneg * 9 / 10 > neglimit
2538 _cache_cleanneg(ncnegflush);
2540 _cache_cleanneg(ncnegflush +
2541 numneg * 9 / 10 - neglimit);
2543 neg_cache_hysteresis_state[critpath] = CHI_LOW;
2549 * Don't cache too many positive hits. We use hysteresis to reduce
2550 * the impact on the critical path.
2552 * Excessive positive hits can accumulate due to large numbers of
2553 * hardlinks (the vnode cache will not prevent hl ncps from growing
2556 if ((poslimit = ncposlimit) == 0)
2557 poslimit = desiredvnodes * 2;
2559 poslimit = poslimit * 8 / 10;
2561 switch(pos_cache_hysteresis_state[critpath]) {
2563 if (xnumcache > poslimit && xnumcache > MINPOS) {
2565 _cache_cleanpos(ncposflush);
2567 _cache_cleanpos(ncposflush +
2568 xnumcache - poslimit);
2569 pos_cache_hysteresis_state[critpath] = CHI_HIGH;
2573 if (xnumcache > poslimit * 5 / 6 && xnumcache > MINPOS) {
2575 _cache_cleanpos(ncposflush);
2577 _cache_cleanpos(ncposflush +
2578 xnumcache - poslimit * 5 / 6);
2580 pos_cache_hysteresis_state[critpath] = CHI_LOW;
2586 * Clean out dangling defered-zap ncps which could not
2587 * be cleanly dropped if too many build up. Note
2588 * that numdefered is not an exact number as such ncps
2589 * can be reused and the counter is not handled in a MP
2590 * safe manner by design.
2592 if (numdefered > neglimit) {
2593 _cache_cleandefered();
2598 * NEW NAMECACHE LOOKUP API
2600 * Lookup an entry in the namecache. The passed par_nch must be referenced
2601 * and unlocked. A referenced and locked nchandle with a non-NULL nch.ncp
2602 * is ALWAYS returned, eve if the supplied component is illegal.
2604 * The resulting namecache entry should be returned to the system with
2605 * cache_put() or cache_unlock() + cache_drop().
2607 * namecache locks are recursive but care must be taken to avoid lock order
2608 * reversals (hence why the passed par_nch must be unlocked). Locking
2609 * rules are to order for parent traversals, not for child traversals.
2611 * Nobody else will be able to manipulate the associated namespace (e.g.
2612 * create, delete, rename, rename-target) until the caller unlocks the
2615 * The returned entry will be in one of three states: positive hit (non-null
2616 * vnode), negative hit (null vnode), or unresolved (NCF_UNRESOLVED is set).
2617 * Unresolved entries must be resolved through the filesystem to associate the
2618 * vnode and/or determine whether a positive or negative hit has occured.
2620 * It is not necessary to lock a directory in order to lock namespace under
2621 * that directory. In fact, it is explicitly not allowed to do that. A
2622 * directory is typically only locked when being created, renamed, or
2625 * The directory (par) may be unresolved, in which case any returned child
2626 * will likely also be marked unresolved. Likely but not guarenteed. Since
2627 * the filesystem lookup requires a resolved directory vnode the caller is
2628 * responsible for resolving the namecache chain top-down. This API
2629 * specifically allows whole chains to be created in an unresolved state.
2632 cache_nlookup(struct nchandle *par_nch, struct nlcomponent *nlc)
2634 struct nchandle nch;
2635 struct namecache *ncp;
2636 struct namecache *new_ncp;
2637 struct nchash_head *nchpp;
2645 mp = par_nch->mount;
2649 * This is a good time to call it, no ncp's are locked by
2652 cache_hysteresis(1);
2655 * Try to locate an existing entry
2657 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
2658 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
2660 nchpp = NCHHASH(hash);
2662 spin_lock(&nchpp->spin);
2663 LIST_FOREACH(ncp, &nchpp->list, nc_hash) {
2667 * Break out if we find a matching entry. Note that
2668 * UNRESOLVED entries may match, but DESTROYED entries
2671 if (ncp->nc_parent == par_nch->ncp &&
2672 ncp->nc_nlen == nlc->nlc_namelen &&
2673 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
2674 (ncp->nc_flag & NCF_DESTROYED) == 0
2677 spin_unlock(&nchpp->spin);
2679 _cache_unlock(par_nch->ncp);
2682 if (_cache_lock_special(ncp) == 0) {
2683 _cache_auto_unresolve(mp, ncp);
2685 _cache_free(new_ncp);
2696 * We failed to locate an entry, create a new entry and add it to
2697 * the cache. The parent ncp must also be locked so we
2700 * We have to relookup after possibly blocking in kmalloc or
2701 * when locking par_nch.
2703 * NOTE: nlc_namelen can be 0 and nlc_nameptr NULL as a special
2704 * mount case, in which case nc_name will be NULL.
2706 if (new_ncp == NULL) {
2707 spin_unlock(&nchpp->spin);
2708 new_ncp = cache_alloc(nlc->nlc_namelen);
2709 if (nlc->nlc_namelen) {
2710 bcopy(nlc->nlc_nameptr, new_ncp->nc_name,
2712 new_ncp->nc_name[nlc->nlc_namelen] = 0;
2716 if (par_locked == 0) {
2717 spin_unlock(&nchpp->spin);
2718 _cache_lock(par_nch->ncp);
2724 * WARNING! We still hold the spinlock. We have to set the hash
2725 * table entry atomically.
2728 _cache_link_parent(ncp, par_nch->ncp, nchpp);
2729 spin_unlock(&nchpp->spin);
2730 _cache_unlock(par_nch->ncp);
2731 /* par_locked = 0 - not used */
2734 * stats and namecache size management
2736 if (ncp->nc_flag & NCF_UNRESOLVED)
2737 ++gd->gd_nchstats->ncs_miss;
2738 else if (ncp->nc_vp)
2739 ++gd->gd_nchstats->ncs_goodhits;
2741 ++gd->gd_nchstats->ncs_neghits;
2744 atomic_add_int(&nch.mount->mnt_refs, 1);
2749 * Attempt to lookup a namecache entry and return with a shared namecache
2753 cache_nlookup_maybe_shared(struct nchandle *par_nch, struct nlcomponent *nlc,
2754 int excl, struct nchandle *res_nch)
2756 struct namecache *ncp;
2757 struct nchash_head *nchpp;
2763 * If exclusive requested or shared namecache locks are disabled,
2766 if (ncp_shared_lock_disable || excl)
2767 return(EWOULDBLOCK);
2771 mp = par_nch->mount;
2774 * This is a good time to call it, no ncp's are locked by
2777 cache_hysteresis(1);
2780 * Try to locate an existing entry
2782 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
2783 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
2784 nchpp = NCHHASH(hash);
2786 spin_lock(&nchpp->spin);
2788 LIST_FOREACH(ncp, &nchpp->list, nc_hash) {
2792 * Break out if we find a matching entry. Note that
2793 * UNRESOLVED entries may match, but DESTROYED entries
2796 if (ncp->nc_parent == par_nch->ncp &&
2797 ncp->nc_nlen == nlc->nlc_namelen &&
2798 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
2799 (ncp->nc_flag & NCF_DESTROYED) == 0
2802 spin_unlock(&nchpp->spin);
2803 if (_cache_lock_shared_special(ncp) == 0) {
2804 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
2805 (ncp->nc_flag & NCF_DESTROYED) == 0 &&
2806 _cache_auto_unresolve_test(mp, ncp) == 0) {
2812 spin_lock(&nchpp->spin);
2820 spin_unlock(&nchpp->spin);
2821 return(EWOULDBLOCK);
2826 * Note that nc_error might be non-zero (e.g ENOENT).
2829 res_nch->mount = mp;
2831 ++gd->gd_nchstats->ncs_goodhits;
2832 atomic_add_int(&res_nch->mount->mnt_refs, 1);
2834 KKASSERT(ncp->nc_error != EWOULDBLOCK);
2835 return(ncp->nc_error);
2839 * This is a non-blocking verison of cache_nlookup() used by
2840 * nfs_readdirplusrpc_uio(). It can fail for any reason and
2841 * will return nch.ncp == NULL in that case.
2844 cache_nlookup_nonblock(struct nchandle *par_nch, struct nlcomponent *nlc)
2846 struct nchandle nch;
2847 struct namecache *ncp;
2848 struct namecache *new_ncp;
2849 struct nchash_head *nchpp;
2857 mp = par_nch->mount;
2861 * Try to locate an existing entry
2863 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
2864 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
2866 nchpp = NCHHASH(hash);
2868 spin_lock(&nchpp->spin);
2869 LIST_FOREACH(ncp, &nchpp->list, nc_hash) {
2873 * Break out if we find a matching entry. Note that
2874 * UNRESOLVED entries may match, but DESTROYED entries
2877 if (ncp->nc_parent == par_nch->ncp &&
2878 ncp->nc_nlen == nlc->nlc_namelen &&
2879 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
2880 (ncp->nc_flag & NCF_DESTROYED) == 0
2883 spin_unlock(&nchpp->spin);
2885 _cache_unlock(par_nch->ncp);
2888 if (_cache_lock_special(ncp) == 0) {
2889 _cache_auto_unresolve(mp, ncp);
2891 _cache_free(new_ncp);
2902 * We failed to locate an entry, create a new entry and add it to
2903 * the cache. The parent ncp must also be locked so we
2906 * We have to relookup after possibly blocking in kmalloc or
2907 * when locking par_nch.
2909 * NOTE: nlc_namelen can be 0 and nlc_nameptr NULL as a special
2910 * mount case, in which case nc_name will be NULL.
2912 if (new_ncp == NULL) {
2913 spin_unlock(&nchpp->spin);
2914 new_ncp = cache_alloc(nlc->nlc_namelen);
2915 if (nlc->nlc_namelen) {
2916 bcopy(nlc->nlc_nameptr, new_ncp->nc_name,
2918 new_ncp->nc_name[nlc->nlc_namelen] = 0;
2922 if (par_locked == 0) {
2923 spin_unlock(&nchpp->spin);
2924 if (_cache_lock_nonblock(par_nch->ncp) == 0) {
2932 * WARNING! We still hold the spinlock. We have to set the hash
2933 * table entry atomically.
2936 _cache_link_parent(ncp, par_nch->ncp, nchpp);
2937 spin_unlock(&nchpp->spin);
2938 _cache_unlock(par_nch->ncp);
2939 /* par_locked = 0 - not used */
2942 * stats and namecache size management
2944 if (ncp->nc_flag & NCF_UNRESOLVED)
2945 ++gd->gd_nchstats->ncs_miss;
2946 else if (ncp->nc_vp)
2947 ++gd->gd_nchstats->ncs_goodhits;
2949 ++gd->gd_nchstats->ncs_neghits;
2952 atomic_add_int(&nch.mount->mnt_refs, 1);
2956 _cache_free(new_ncp);
2965 * The namecache entry is marked as being used as a mount point.
2966 * Locate the mount if it is visible to the caller. The DragonFly
2967 * mount system allows arbitrary loops in the topology and disentangles
2968 * those loops by matching against (mp, ncp) rather than just (ncp).
2969 * This means any given ncp can dive any number of mounts, depending
2970 * on the relative mount (e.g. nullfs) the caller is at in the topology.
2972 * We use a very simple frontend cache to reduce SMP conflicts,
2973 * which we have to do because the mountlist scan needs an exclusive
2974 * lock around its ripout info list. Not to mention that there might
2975 * be a lot of mounts.
2977 struct findmount_info {
2978 struct mount *result;
2979 struct mount *nch_mount;
2980 struct namecache *nch_ncp;
2984 struct ncmount_cache *
2985 ncmount_cache_lookup(struct mount *mp, struct namecache *ncp)
2989 hash = ((int)(intptr_t)mp / sizeof(*mp)) ^
2990 ((int)(intptr_t)ncp / sizeof(*ncp));
2991 hash = (hash & 0x7FFFFFFF) % NCMOUNT_NUMCACHE;
2992 return (&ncmount_cache[hash]);
2997 cache_findmount_callback(struct mount *mp, void *data)
2999 struct findmount_info *info = data;
3002 * Check the mount's mounted-on point against the passed nch.
3004 if (mp->mnt_ncmounton.mount == info->nch_mount &&
3005 mp->mnt_ncmounton.ncp == info->nch_ncp
3008 atomic_add_int(&mp->mnt_refs, 1);
3015 cache_findmount(struct nchandle *nch)
3017 struct findmount_info info;
3018 struct ncmount_cache *ncc;
3024 if (ncmount_cache_enable == 0) {
3028 ncc = ncmount_cache_lookup(nch->mount, nch->ncp);
3029 if (ncc->ncp == nch->ncp) {
3030 spin_lock_shared(&ncc->spin);
3031 if (ncc->isneg == 0 &&
3032 ncc->ncp == nch->ncp && (mp = ncc->mp) != NULL) {
3033 if (mp->mnt_ncmounton.mount == nch->mount &&
3034 mp->mnt_ncmounton.ncp == nch->ncp) {
3036 * Cache hit (positive)
3038 atomic_add_int(&mp->mnt_refs, 1);
3039 spin_unlock_shared(&ncc->spin);
3040 ++ncmount_cache_hit;
3043 /* else cache miss */
3046 ncc->ncp == nch->ncp && ncc->mp == nch->mount) {
3048 * Cache hit (negative)
3050 spin_unlock_shared(&ncc->spin);
3051 ++ncmount_cache_hit;
3054 spin_unlock_shared(&ncc->spin);
3062 info.nch_mount = nch->mount;
3063 info.nch_ncp = nch->ncp;
3064 mountlist_scan(cache_findmount_callback, &info,
3065 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
3070 * Negative lookups: We cache the originating {ncp,mp}. (mp) is
3071 * only used for pointer comparisons and is not
3072 * referenced (otherwise there would be dangling
3075 * Positive lookups: We cache the originating {ncp} and the target
3076 * (mp). (mp) is referenced.
3078 * Indeterminant: If the match is undergoing an unmount we do
3079 * not cache it to avoid racing cache_unmounting(),
3080 * but still return the match.
3083 spin_lock(&ncc->spin);
3084 if (info.result == NULL) {
3085 if (ncc->isneg == 0 && ncc->mp)
3086 atomic_add_int(&ncc->mp->mnt_refs, -1);
3087 ncc->ncp = nch->ncp;
3088 ncc->mp = nch->mount;
3090 spin_unlock(&ncc->spin);
3091 ++ncmount_cache_overwrite;
3092 } else if ((info.result->mnt_kern_flag & MNTK_UNMOUNT) == 0) {
3093 if (ncc->isneg == 0 && ncc->mp)
3094 atomic_add_int(&ncc->mp->mnt_refs, -1);
3095 atomic_add_int(&info.result->mnt_refs, 1);
3096 ncc->ncp = nch->ncp;
3097 ncc->mp = info.result;
3099 spin_unlock(&ncc->spin);
3100 ++ncmount_cache_overwrite;
3102 spin_unlock(&ncc->spin);
3104 ++ncmount_cache_miss;
3106 return(info.result);
3110 cache_dropmount(struct mount *mp)
3112 atomic_add_int(&mp->mnt_refs, -1);
3116 cache_ismounting(struct mount *mp)
3118 struct nchandle *nch = &mp->mnt_ncmounton;
3119 struct ncmount_cache *ncc;
3121 ncc = ncmount_cache_lookup(nch->mount, nch->ncp);
3123 ncc->ncp == nch->ncp && ncc->mp == nch->mount) {
3124 spin_lock(&ncc->spin);
3126 ncc->ncp == nch->ncp && ncc->mp == nch->mount) {
3130 spin_unlock(&ncc->spin);
3135 cache_unmounting(struct mount *mp)
3137 struct nchandle *nch = &mp->mnt_ncmounton;
3138 struct ncmount_cache *ncc;
3140 ncc = ncmount_cache_lookup(nch->mount, nch->ncp);
3141 if (ncc->isneg == 0 &&
3142 ncc->ncp == nch->ncp && ncc->mp == mp) {
3143 spin_lock(&ncc->spin);
3144 if (ncc->isneg == 0 &&
3145 ncc->ncp == nch->ncp && ncc->mp == mp) {
3146 atomic_add_int(&mp->mnt_refs, -1);
3150 spin_unlock(&ncc->spin);
3155 * Resolve an unresolved namecache entry, generally by looking it up.
3156 * The passed ncp must be locked and refd.
3158 * Theoretically since a vnode cannot be recycled while held, and since
3159 * the nc_parent chain holds its vnode as long as children exist, the
3160 * direct parent of the cache entry we are trying to resolve should
3161 * have a valid vnode. If not then generate an error that we can
3162 * determine is related to a resolver bug.
3164 * However, if a vnode was in the middle of a recyclement when the NCP
3165 * got locked, ncp->nc_vp might point to a vnode that is about to become
3166 * invalid. cache_resolve() handles this case by unresolving the entry
3167 * and then re-resolving it.
3169 * Note that successful resolution does not necessarily return an error
3170 * code of 0. If the ncp resolves to a negative cache hit then ENOENT
3174 cache_resolve(struct nchandle *nch, struct ucred *cred)
3176 struct namecache *par_tmp;
3177 struct namecache *par;
3178 struct namecache *ncp;
3179 struct nchandle nctmp;
3186 KKASSERT(_cache_lockstatus(ncp) == LK_EXCLUSIVE);
3189 * If the ncp is already resolved we have nothing to do. However,
3190 * we do want to guarentee that a usable vnode is returned when
3191 * a vnode is present, so make sure it hasn't been reclaimed.
3193 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
3194 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
3195 _cache_setunresolved(ncp);
3196 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
3197 return (ncp->nc_error);
3201 * If the ncp was destroyed it will never resolve again. This
3202 * can basically only happen when someone is chdir'd into an
3203 * empty directory which is then rmdir'd. We want to catch this
3204 * here and not dive the VFS because the VFS might actually
3205 * have a way to re-resolve the disconnected ncp, which will
3206 * result in inconsistencies in the cdir/nch for proc->p_fd.
3208 if (ncp->nc_flag & NCF_DESTROYED) {
3209 kprintf("Warning: cache_resolve: ncp '%s' was unlinked\n",
3215 * Mount points need special handling because the parent does not
3216 * belong to the same filesystem as the ncp.
3218 if (ncp == mp->mnt_ncmountpt.ncp)
3219 return (cache_resolve_mp(mp));
3222 * We expect an unbroken chain of ncps to at least the mount point,
3223 * and even all the way to root (but this code doesn't have to go
3224 * past the mount point).
3226 if (ncp->nc_parent == NULL) {
3227 kprintf("EXDEV case 1 %p %*.*s\n", ncp,
3228 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
3229 ncp->nc_error = EXDEV;
3230 return(ncp->nc_error);
3234 * The vp's of the parent directories in the chain are held via vhold()
3235 * due to the existance of the child, and should not disappear.
3236 * However, there are cases where they can disappear:
3238 * - due to filesystem I/O errors.
3239 * - due to NFS being stupid about tracking the namespace and
3240 * destroys the namespace for entire directories quite often.
3241 * - due to forced unmounts.
3242 * - due to an rmdir (parent will be marked DESTROYED)
3244 * When this occurs we have to track the chain backwards and resolve
3245 * it, looping until the resolver catches up to the current node. We
3246 * could recurse here but we might run ourselves out of kernel stack
3247 * so we do it in a more painful manner. This situation really should
3248 * not occur all that often, or if it does not have to go back too
3249 * many nodes to resolve the ncp.
3251 while ((dvp = cache_dvpref(ncp)) == NULL) {
3253 * This case can occur if a process is CD'd into a
3254 * directory which is then rmdir'd. If the parent is marked
3255 * destroyed there is no point trying to resolve it.
3257 if (ncp->nc_parent->nc_flag & NCF_DESTROYED)
3259 par = ncp->nc_parent;
3262 while ((par_tmp = par->nc_parent) != NULL &&
3263 par_tmp->nc_vp == NULL) {
3264 _cache_hold(par_tmp);
3265 _cache_lock(par_tmp);
3269 if (par->nc_parent == NULL) {
3270 kprintf("EXDEV case 2 %*.*s\n",
3271 par->nc_nlen, par->nc_nlen, par->nc_name);
3275 kprintf("[diagnostic] cache_resolve: had to recurse on %*.*s\n",
3276 par->nc_nlen, par->nc_nlen, par->nc_name);
3278 * The parent is not set in stone, ref and lock it to prevent
3279 * it from disappearing. Also note that due to renames it
3280 * is possible for our ncp to move and for par to no longer
3281 * be one of its parents. We resolve it anyway, the loop
3282 * will handle any moves.
3284 _cache_get(par); /* additional hold/lock */
3285 _cache_put(par); /* from earlier hold/lock */
3286 if (par == nch->mount->mnt_ncmountpt.ncp) {
3287 cache_resolve_mp(nch->mount);
3288 } else if ((dvp = cache_dvpref(par)) == NULL) {
3289 kprintf("[diagnostic] cache_resolve: raced on %*.*s\n", par->nc_nlen, par->nc_nlen, par->nc_name);
3293 if (par->nc_flag & NCF_UNRESOLVED) {
3296 par->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
3300 if ((error = par->nc_error) != 0) {
3301 if (par->nc_error != EAGAIN) {
3302 kprintf("EXDEV case 3 %*.*s error %d\n",
3303 par->nc_nlen, par->nc_nlen, par->nc_name,
3308 kprintf("[diagnostic] cache_resolve: EAGAIN par %p %*.*s\n",
3309 par, par->nc_nlen, par->nc_nlen, par->nc_name);
3316 * Call VOP_NRESOLVE() to get the vp, then scan for any disconnected
3317 * ncp's and reattach them. If this occurs the original ncp is marked
3318 * EAGAIN to force a relookup.
3320 * NOTE: in order to call VOP_NRESOLVE(), the parent of the passed
3321 * ncp must already be resolved.
3326 ncp->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
3329 ncp->nc_error = EPERM;
3331 if (ncp->nc_error == EAGAIN) {
3332 kprintf("[diagnostic] cache_resolve: EAGAIN ncp %p %*.*s\n",
3333 ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
3336 return(ncp->nc_error);
3340 * Resolve the ncp associated with a mount point. Such ncp's almost always
3341 * remain resolved and this routine is rarely called. NFS MPs tends to force
3342 * re-resolution more often due to its mac-truck-smash-the-namecache
3343 * method of tracking namespace changes.
3345 * The semantics for this call is that the passed ncp must be locked on
3346 * entry and will be locked on return. However, if we actually have to
3347 * resolve the mount point we temporarily unlock the entry in order to
3348 * avoid race-to-root deadlocks due to e.g. dead NFS mounts. Because of
3349 * the unlock we have to recheck the flags after we relock.
3352 cache_resolve_mp(struct mount *mp)
3354 struct namecache *ncp = mp->mnt_ncmountpt.ncp;
3358 KKASSERT(mp != NULL);
3361 * If the ncp is already resolved we have nothing to do. However,
3362 * we do want to guarentee that a usable vnode is returned when
3363 * a vnode is present, so make sure it hasn't been reclaimed.
3365 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
3366 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
3367 _cache_setunresolved(ncp);
3370 if (ncp->nc_flag & NCF_UNRESOLVED) {
3372 while (vfs_busy(mp, 0))
3374 error = VFS_ROOT(mp, &vp);
3378 * recheck the ncp state after relocking.
3380 if (ncp->nc_flag & NCF_UNRESOLVED) {
3381 ncp->nc_error = error;
3383 _cache_setvp(mp, ncp, vp);
3386 kprintf("[diagnostic] cache_resolve_mp: failed"
3387 " to resolve mount %p err=%d ncp=%p\n",
3389 _cache_setvp(mp, ncp, NULL);
3391 } else if (error == 0) {
3396 return(ncp->nc_error);
3400 * Clean out negative cache entries when too many have accumulated.
3403 _cache_cleanneg(int count)
3405 struct namecache *ncp;
3408 * Attempt to clean out the specified number of negative cache
3413 ncp = TAILQ_FIRST(&ncneglist);
3415 spin_unlock(&ncspin);
3418 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
3419 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
3421 spin_unlock(&ncspin);
3424 * This can race, so we must re-check that the ncp
3425 * is on the ncneglist after successfully locking it.
3427 if (_cache_lock_special(ncp) == 0) {
3428 if (ncp->nc_vp == NULL &&
3429 (ncp->nc_flag & NCF_UNRESOLVED) == 0) {
3430 ncp = cache_zap(ncp, 1);
3434 kprintf("cache_cleanneg: race avoided\n");
3445 * Clean out positive cache entries when too many have accumulated.
3448 _cache_cleanpos(int count)
3450 static volatile int rover;
3451 struct nchash_head *nchpp;
3452 struct namecache *ncp;
3456 * Attempt to clean out the specified number of negative cache
3460 rover_copy = ++rover; /* MPSAFEENOUGH */
3462 nchpp = NCHHASH(rover_copy);
3464 spin_lock(&nchpp->spin);
3465 ncp = LIST_FIRST(&nchpp->list);
3466 while (ncp && (ncp->nc_flag & NCF_DESTROYED))
3467 ncp = LIST_NEXT(ncp, nc_hash);
3470 spin_unlock(&nchpp->spin);
3473 if (_cache_lock_special(ncp) == 0) {
3474 ncp = cache_zap(ncp, 1);
3486 * This is a kitchen sink function to clean out ncps which we
3487 * tried to zap from cache_drop() but failed because we were
3488 * unable to acquire the parent lock.
3490 * Such entries can also be removed via cache_inval_vp(), such
3491 * as when unmounting.
3494 _cache_cleandefered(void)
3496 struct nchash_head *nchpp;
3497 struct namecache *ncp;
3498 struct namecache dummy;
3502 bzero(&dummy, sizeof(dummy));
3503 dummy.nc_flag = NCF_DESTROYED;
3506 for (i = 0; i <= nchash; ++i) {
3507 nchpp = &nchashtbl[i];
3509 spin_lock(&nchpp->spin);
3510 LIST_INSERT_HEAD(&nchpp->list, &dummy, nc_hash);
3512 while ((ncp = LIST_NEXT(ncp, nc_hash)) != NULL) {
3513 if ((ncp->nc_flag & NCF_DEFEREDZAP) == 0)
3515 LIST_REMOVE(&dummy, nc_hash);
3516 LIST_INSERT_AFTER(ncp, &dummy, nc_hash);
3518 spin_unlock(&nchpp->spin);
3519 if (_cache_lock_nonblock(ncp) == 0) {
3520 ncp->nc_flag &= ~NCF_DEFEREDZAP;
3524 spin_lock(&nchpp->spin);
3527 LIST_REMOVE(&dummy, nc_hash);
3528 spin_unlock(&nchpp->spin);
3533 * Name cache initialization, from vfsinit() when we are booting
3541 /* initialise per-cpu namecache effectiveness statistics. */
3542 for (i = 0; i < ncpus; ++i) {
3543 gd = globaldata_find(i);
3544 gd->gd_nchstats = &nchstats[i];
3546 TAILQ_INIT(&ncneglist);
3548 nchashtbl = hashinit_ext(desiredvnodes / 2,
3549 sizeof(struct nchash_head),
3550 M_VFSCACHE, &nchash);
3551 for (i = 0; i <= (int)nchash; ++i) {
3552 LIST_INIT(&nchashtbl[i].list);
3553 spin_init(&nchashtbl[i].spin);
3555 for (i = 0; i < NCMOUNT_NUMCACHE; ++i)
3556 spin_init(&ncmount_cache[i].spin);
3557 nclockwarn = 5 * hz;
3561 * Called from start_init() to bootstrap the root filesystem. Returns
3562 * a referenced, unlocked namecache record.
3565 cache_allocroot(struct nchandle *nch, struct mount *mp, struct vnode *vp)
3567 nch->ncp = cache_alloc(0);
3569 atomic_add_int(&mp->mnt_refs, 1);
3571 _cache_setvp(nch->mount, nch->ncp, vp);
3575 * vfs_cache_setroot()
3577 * Create an association between the root of our namecache and
3578 * the root vnode. This routine may be called several times during
3581 * If the caller intends to save the returned namecache pointer somewhere
3582 * it must cache_hold() it.
3585 vfs_cache_setroot(struct vnode *nvp, struct nchandle *nch)
3588 struct nchandle onch;
3596 cache_zero(&rootnch);
3604 * XXX OLD API COMPAT FUNCTION. This really messes up the new namecache
3605 * topology and is being removed as quickly as possible. The new VOP_N*()
3606 * API calls are required to make specific adjustments using the supplied
3607 * ncp pointers rather then just bogusly purging random vnodes.
3609 * Invalidate all namecache entries to a particular vnode as well as
3610 * any direct children of that vnode in the namecache. This is a
3611 * 'catch all' purge used by filesystems that do not know any better.
3613 * Note that the linkage between the vnode and its namecache entries will
3614 * be removed, but the namecache entries themselves might stay put due to
3615 * active references from elsewhere in the system or due to the existance of
3616 * the children. The namecache topology is left intact even if we do not
3617 * know what the vnode association is. Such entries will be marked
3621 cache_purge(struct vnode *vp)
3623 cache_inval_vp(vp, CINV_DESTROY | CINV_CHILDREN);
3627 * Flush all entries referencing a particular filesystem.
3629 * Since we need to check it anyway, we will flush all the invalid
3630 * entries at the same time.
3635 cache_purgevfs(struct mount *mp)
3637 struct nchash_head *nchpp;
3638 struct namecache *ncp, *nnp;
3641 * Scan hash tables for applicable entries.
3643 for (nchpp = &nchashtbl[nchash]; nchpp >= nchashtbl; nchpp--) {
3644 spin_lock_wr(&nchpp->spin); XXX
3645 ncp = LIST_FIRST(&nchpp->list);
3649 nnp = LIST_NEXT(ncp, nc_hash);
3652 if (ncp->nc_mount == mp) {
3654 ncp = cache_zap(ncp, 0);
3662 spin_unlock_wr(&nchpp->spin); XXX
3668 static int disablecwd;
3669 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0,
3672 static u_long numcwdcalls;
3673 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdcalls, CTLFLAG_RD, &numcwdcalls, 0,
3674 "Number of current directory resolution calls");
3675 static u_long numcwdfailnf;
3676 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfailnf, CTLFLAG_RD, &numcwdfailnf, 0,
3677 "Number of current directory failures due to lack of file");
3678 static u_long numcwdfailsz;
3679 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfailsz, CTLFLAG_RD, &numcwdfailsz, 0,
3680 "Number of current directory failures due to large result");
3681 static u_long numcwdfound;
3682 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfound, CTLFLAG_RD, &numcwdfound, 0,
3683 "Number of current directory resolution successes");
3689 sys___getcwd(struct __getcwd_args *uap)
3699 buflen = uap->buflen;
3702 if (buflen > MAXPATHLEN)
3703 buflen = MAXPATHLEN;
3705 buf = kmalloc(buflen, M_TEMP, M_WAITOK);
3706 bp = kern_getcwd(buf, buflen, &error);
3708 error = copyout(bp, uap->buf, strlen(bp) + 1);
3714 kern_getcwd(char *buf, size_t buflen, int *error)
3716 struct proc *p = curproc;
3718 int i, slash_prefixed;
3719 struct filedesc *fdp;
3720 struct nchandle nch;
3721 struct namecache *ncp;
3730 nch = fdp->fd_ncdir;
3735 while (ncp && (ncp != fdp->fd_nrdir.ncp ||
3736 nch.mount != fdp->fd_nrdir.mount)
3739 * While traversing upwards if we encounter the root
3740 * of the current mount we have to skip to the mount point
3741 * in the underlying filesystem.
3743 if (ncp == nch.mount->mnt_ncmountpt.ncp) {
3744 nch = nch.mount->mnt_ncmounton;
3753 * Prepend the path segment
3755 for (i = ncp->nc_nlen - 1; i >= 0; i--) {
3762 *--bp = ncp->nc_name[i];
3774 * Go up a directory. This isn't a mount point so we don't
3775 * have to check again.
3777 while ((nch.ncp = ncp->nc_parent) != NULL) {
3778 if (ncp_shared_lock_disable)
3781 _cache_lock_shared(ncp);
3782 if (nch.ncp != ncp->nc_parent) {
3786 _cache_hold(nch.ncp);
3799 if (!slash_prefixed) {
3817 * Thus begins the fullpath magic.
3819 * The passed nchp is referenced but not locked.
3821 static int disablefullpath;
3822 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW,
3823 &disablefullpath, 0,
3824 "Disable fullpath lookups");
3826 static u_int numfullpathcalls;
3827 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathcalls, CTLFLAG_RD,
3828 &numfullpathcalls, 0,
3829 "Number of full path resolutions in progress");
3830 static u_int numfullpathfailnf;
3831 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathfailnf, CTLFLAG_RD,
3832 &numfullpathfailnf, 0,
3833 "Number of full path resolution failures due to lack of file");
3834 static u_int numfullpathfailsz;
3835 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathfailsz, CTLFLAG_RD,
3836 &numfullpathfailsz, 0,
3837 "Number of full path resolution failures due to insufficient memory");
3838 static u_int numfullpathfound;
3839 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathfound, CTLFLAG_RD,
3840 &numfullpathfound, 0,
3841 "Number of full path resolution successes");
3844 cache_fullpath(struct proc *p, struct nchandle *nchp, struct nchandle *nchbase,
3845 char **retbuf, char **freebuf, int guess)
3847 struct nchandle fd_nrdir;
3848 struct nchandle nch;
3849 struct namecache *ncp;
3850 struct mount *mp, *new_mp;
3856 atomic_add_int(&numfullpathcalls, -1);
3861 buf = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
3862 bp = buf + MAXPATHLEN - 1;
3865 fd_nrdir = *nchbase;
3867 fd_nrdir = p->p_fd->fd_nrdir;
3877 while (ncp && (ncp != fd_nrdir.ncp || mp != fd_nrdir.mount)) {
3881 * If we are asked to guess the upwards path, we do so whenever
3882 * we encounter an ncp marked as a mountpoint. We try to find
3883 * the actual mountpoint by finding the mountpoint with this
3886 if (guess && (ncp->nc_flag & NCF_ISMOUNTPT)) {
3887 new_mp = mount_get_by_nc(ncp);
3890 * While traversing upwards if we encounter the root
3891 * of the current mount we have to skip to the mount point.
3893 if (ncp == mp->mnt_ncmountpt.ncp) {
3897 nch = new_mp->mnt_ncmounton;
3907 * Prepend the path segment
3909 for (i = ncp->nc_nlen - 1; i >= 0; i--) {
3911 numfullpathfailsz++;
3916 *--bp = ncp->nc_name[i];
3919 numfullpathfailsz++;
3928 * Go up a directory. This isn't a mount point so we don't
3929 * have to check again.
3931 * We can only safely access nc_parent with ncp held locked.
3933 while ((nch.ncp = ncp->nc_parent) != NULL) {
3935 if (nch.ncp != ncp->nc_parent) {
3939 _cache_hold(nch.ncp);
3947 numfullpathfailnf++;
3953 if (!slash_prefixed) {
3955 numfullpathfailsz++;
3973 vn_fullpath(struct proc *p, struct vnode *vn, char **retbuf, char **freebuf,
3976 struct namecache *ncp;
3977 struct nchandle nch;
3981 atomic_add_int(&numfullpathcalls, 1);
3982 if (disablefullpath)
3988 /* vn is NULL, client wants us to use p->p_textvp */
3990 if ((vn = p->p_textvp) == NULL)
3993 spin_lock(&vn->v_spin);
3994 TAILQ_FOREACH(ncp, &vn->v_namecache, nc_vnode) {
3999 spin_unlock(&vn->v_spin);
4003 spin_unlock(&vn->v_spin);
4005 atomic_add_int(&numfullpathcalls, -1);
4007 nch.mount = vn->v_mount;
4008 error = cache_fullpath(p, &nch, NULL, retbuf, freebuf, guess);