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])
130 MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
132 LIST_HEAD(nchash_list, namecache);
135 struct nchash_list list;
136 struct spinlock spin;
139 static struct nchash_head *nchashtbl;
140 static struct namecache_list ncneglist;
141 static struct spinlock ncspin;
144 * ncvp_debug - debug cache_fromvp(). This is used by the NFS server
145 * to create the namecache infrastructure leading to a dangling vnode.
147 * 0 Only errors are reported
148 * 1 Successes are reported
149 * 2 Successes + the whole directory scan is reported
150 * 3 Force the directory scan code run as if the parent vnode did not
151 * have a namecache record, even if it does have one.
153 static int ncvp_debug;
154 SYSCTL_INT(_debug, OID_AUTO, ncvp_debug, CTLFLAG_RW, &ncvp_debug, 0,
155 "Namecache debug level (0-3)");
157 static u_long nchash; /* size of hash table */
158 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
159 "Size of namecache hash table");
161 static int ncnegfactor = 16; /* ratio of negative entries */
162 SYSCTL_INT(_debug, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0,
163 "Ratio of namecache negative entries");
165 static int nclockwarn; /* warn on locked entries in ticks */
166 SYSCTL_INT(_debug, OID_AUTO, nclockwarn, CTLFLAG_RW, &nclockwarn, 0,
167 "Warn on locked namecache entries in ticks");
169 static int numdefered; /* number of cache entries allocated */
170 SYSCTL_INT(_debug, OID_AUTO, numdefered, CTLFLAG_RD, &numdefered, 0,
171 "Number of cache entries allocated");
173 static int ncposlimit; /* number of cache entries allocated */
174 SYSCTL_INT(_debug, OID_AUTO, ncposlimit, CTLFLAG_RW, &ncposlimit, 0,
175 "Number of cache entries allocated");
177 SYSCTL_INT(_debug, OID_AUTO, vnsize, CTLFLAG_RD, 0, sizeof(struct vnode),
178 "sizeof(struct vnode)");
179 SYSCTL_INT(_debug, OID_AUTO, ncsize, CTLFLAG_RD, 0, sizeof(struct namecache),
180 "sizeof(struct namecache)");
182 static int cache_resolve_mp(struct mount *mp);
183 static struct vnode *cache_dvpref(struct namecache *ncp);
184 static void _cache_lock(struct namecache *ncp);
185 static void _cache_setunresolved(struct namecache *ncp);
186 static void _cache_cleanneg(int count);
187 static void _cache_cleanpos(int count);
188 static void _cache_cleandefered(void);
191 * The new name cache statistics
193 SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0, "Name cache statistics");
195 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0,
196 "Number of negative namecache entries");
198 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0,
199 "Number of namecaches entries");
200 static u_long numcalls;
201 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcalls, CTLFLAG_RD, &numcalls, 0,
202 "Number of namecache lookups");
203 static u_long numchecks;
204 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numchecks, CTLFLAG_RD, &numchecks, 0,
205 "Number of checked entries in namecache lookups");
207 struct nchstats nchstats[SMP_MAXCPU];
209 * Export VFS cache effectiveness statistics to user-land.
211 * The statistics are left for aggregation to user-land so
212 * neat things can be achieved, like observing per-CPU cache
216 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
218 struct globaldata *gd;
222 for (i = 0; i < ncpus; ++i) {
223 gd = globaldata_find(i);
224 if ((error = SYSCTL_OUT(req, (void *)&(*gd->gd_nchstats),
225 sizeof(struct nchstats))))
231 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE|CTLFLAG_RD,
232 0, 0, sysctl_nchstats, "S,nchstats", "VFS cache effectiveness statistics");
234 static struct namecache *cache_zap(struct namecache *ncp, int nonblock);
237 * Namespace locking. The caller must already hold a reference to the
238 * namecache structure in order to lock/unlock it. This function prevents
239 * the namespace from being created or destroyed by accessors other then
242 * Note that holding a locked namecache structure prevents other threads
243 * from making namespace changes (e.g. deleting or creating), prevents
244 * vnode association state changes by other threads, and prevents the
245 * namecache entry from being resolved or unresolved by other threads.
247 * The lock owner has full authority to associate/disassociate vnodes
248 * and resolve/unresolve the locked ncp.
250 * The primary lock field is nc_exlocks. nc_locktd is set after the
251 * fact (when locking) or cleared prior to unlocking.
253 * WARNING! Holding a locked ncp will prevent a vnode from being destroyed
254 * or recycled, but it does NOT help you if the vnode had already
255 * initiated a recyclement. If this is important, use cache_get()
256 * rather then cache_lock() (and deal with the differences in the
257 * way the refs counter is handled). Or, alternatively, make an
258 * unconditional call to cache_validate() or cache_resolve()
259 * after cache_lock() returns.
265 _cache_lock(struct namecache *ncp)
272 KKASSERT(ncp->nc_refs != 0);
277 count = ncp->nc_exlocks;
280 if (atomic_cmpset_int(&ncp->nc_exlocks, 0, 1)) {
282 * The vp associated with a locked ncp must
283 * be held to prevent it from being recycled.
285 * WARNING! If VRECLAIMED is set the vnode
286 * could already be in the middle of a recycle.
287 * Callers must use cache_vref() or
288 * cache_vget() on the locked ncp to
289 * validate the vp or set the cache entry
292 * NOTE! vhold() is allowed if we hold a
293 * lock on the ncp (which we do).
297 vhold(ncp->nc_vp); /* MPSAFE */
303 if (ncp->nc_locktd == td) {
304 if (atomic_cmpset_int(&ncp->nc_exlocks, count,
311 tsleep_interlock(ncp, 0);
312 if (atomic_cmpset_int(&ncp->nc_exlocks, count,
313 count | NC_EXLOCK_REQ) == 0) {
317 error = tsleep(ncp, PINTERLOCKED, "clock", nclockwarn);
318 if (error == EWOULDBLOCK) {
321 kprintf("[diagnostic] cache_lock: blocked "
324 kprintf(" \"%*.*s\"\n",
325 ncp->nc_nlen, ncp->nc_nlen,
331 kprintf("[diagnostic] cache_lock: unblocked %*.*s after "
333 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name,
334 (int)(ticks - didwarn) / hz);
339 * NOTE: nc_refs may be zero if the ncp is interlocked by circumstance,
340 * such as the case where one of its children is locked.
346 _cache_lock_nonblock(struct namecache *ncp)
354 count = ncp->nc_exlocks;
357 if (atomic_cmpset_int(&ncp->nc_exlocks, 0, 1)) {
359 * The vp associated with a locked ncp must
360 * be held to prevent it from being recycled.
362 * WARNING! If VRECLAIMED is set the vnode
363 * could already be in the middle of a recycle.
364 * Callers must use cache_vref() or
365 * cache_vget() on the locked ncp to
366 * validate the vp or set the cache entry
369 * NOTE! vhold() is allowed if we hold a
370 * lock on the ncp (which we do).
374 vhold(ncp->nc_vp); /* MPSAFE */
380 if (ncp->nc_locktd == td) {
381 if (atomic_cmpset_int(&ncp->nc_exlocks, count,
396 * NOTE: nc_refs can be 0 (degenerate case during _cache_drop).
398 * nc_locktd must be NULLed out prior to nc_exlocks getting cleared.
404 _cache_unlock(struct namecache *ncp)
406 thread_t td __debugvar = curthread;
409 KKASSERT(ncp->nc_refs >= 0);
410 KKASSERT(ncp->nc_exlocks > 0);
411 KKASSERT(ncp->nc_locktd == td);
413 count = ncp->nc_exlocks;
414 if ((count & ~NC_EXLOCK_REQ) == 1) {
415 ncp->nc_locktd = NULL;
420 if ((count & ~NC_EXLOCK_REQ) == 1) {
421 if (atomic_cmpset_int(&ncp->nc_exlocks, count, 0)) {
422 if (count & NC_EXLOCK_REQ)
427 if (atomic_cmpset_int(&ncp->nc_exlocks, count,
432 count = ncp->nc_exlocks;
438 * cache_hold() and cache_drop() prevent the premature deletion of a
439 * namecache entry but do not prevent operations (such as zapping) on
440 * that namecache entry.
442 * This routine may only be called from outside this source module if
443 * nc_refs is already at least 1.
445 * This is a rare case where callers are allowed to hold a spinlock,
446 * so we can't ourselves.
452 _cache_hold(struct namecache *ncp)
454 atomic_add_int(&ncp->nc_refs, 1);
459 * Drop a cache entry, taking care to deal with races.
461 * For potential 1->0 transitions we must hold the ncp lock to safely
462 * test its flags. An unresolved entry with no children must be zapped
465 * The call to cache_zap() itself will handle all remaining races and
466 * will decrement the ncp's refs regardless. If we are resolved or
467 * have children nc_refs can safely be dropped to 0 without having to
470 * NOTE: cache_zap() will re-check nc_refs and nc_list in a MPSAFE fashion.
472 * NOTE: cache_zap() may return a non-NULL referenced parent which must
473 * be dropped in a loop.
479 _cache_drop(struct namecache *ncp)
484 KKASSERT(ncp->nc_refs > 0);
488 if (_cache_lock_nonblock(ncp) == 0) {
489 ncp->nc_flag &= ~NCF_DEFEREDZAP;
490 if ((ncp->nc_flag & NCF_UNRESOLVED) &&
491 TAILQ_EMPTY(&ncp->nc_list)) {
492 ncp = cache_zap(ncp, 1);
495 if (atomic_cmpset_int(&ncp->nc_refs, 1, 0)) {
502 if (atomic_cmpset_int(&ncp->nc_refs, refs, refs - 1))
510 * Link a new namecache entry to its parent and to the hash table. Be
511 * careful to avoid races if vhold() blocks in the future.
513 * Both ncp and par must be referenced and locked.
515 * NOTE: The hash table spinlock is likely held during this call, we
516 * can't do anything fancy.
521 _cache_link_parent(struct namecache *ncp, struct namecache *par,
522 struct nchash_head *nchpp)
524 KKASSERT(ncp->nc_parent == NULL);
525 ncp->nc_parent = par;
526 ncp->nc_head = nchpp;
529 * Set inheritance flags. Note that the parent flags may be
530 * stale due to getattr potentially not having been run yet
531 * (it gets run during nlookup()'s).
533 ncp->nc_flag &= ~(NCF_SF_PNOCACHE | NCF_UF_PCACHE);
534 if (par->nc_flag & (NCF_SF_NOCACHE | NCF_SF_PNOCACHE))
535 ncp->nc_flag |= NCF_SF_PNOCACHE;
536 if (par->nc_flag & (NCF_UF_CACHE | NCF_UF_PCACHE))
537 ncp->nc_flag |= NCF_UF_PCACHE;
539 LIST_INSERT_HEAD(&nchpp->list, ncp, nc_hash);
541 if (TAILQ_EMPTY(&par->nc_list)) {
542 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
544 * Any vp associated with an ncp which has children must
545 * be held to prevent it from being recycled.
550 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
555 * Remove the parent and hash associations from a namecache structure.
556 * If this is the last child of the parent the cache_drop(par) will
557 * attempt to recursively zap the parent.
559 * ncp must be locked. This routine will acquire a temporary lock on
560 * the parent as wlel as the appropriate hash chain.
565 _cache_unlink_parent(struct namecache *ncp)
567 struct namecache *par;
568 struct vnode *dropvp;
570 if ((par = ncp->nc_parent) != NULL) {
571 KKASSERT(ncp->nc_parent == par);
574 spin_lock(&ncp->nc_head->spin);
575 LIST_REMOVE(ncp, nc_hash);
576 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
578 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
580 spin_unlock(&ncp->nc_head->spin);
581 ncp->nc_parent = NULL;
587 * We can only safely vdrop with no spinlocks held.
595 * Allocate a new namecache structure. Most of the code does not require
596 * zero-termination of the string but it makes vop_compat_ncreate() easier.
600 static struct namecache *
601 cache_alloc(int nlen)
603 struct namecache *ncp;
605 ncp = kmalloc(sizeof(*ncp), M_VFSCACHE, M_WAITOK|M_ZERO);
607 ncp->nc_name = kmalloc(nlen + 1, M_VFSCACHE, M_WAITOK);
609 ncp->nc_flag = NCF_UNRESOLVED;
610 ncp->nc_error = ENOTCONN; /* needs to be resolved */
613 TAILQ_INIT(&ncp->nc_list);
619 * Can only be called for the case where the ncp has never been
620 * associated with anything (so no spinlocks are needed).
625 _cache_free(struct namecache *ncp)
627 KKASSERT(ncp->nc_refs == 1 && ncp->nc_exlocks == 1);
629 kfree(ncp->nc_name, M_VFSCACHE);
630 kfree(ncp, M_VFSCACHE);
637 cache_zero(struct nchandle *nch)
644 * Ref and deref a namecache structure.
646 * The caller must specify a stable ncp pointer, typically meaning the
647 * ncp is already referenced but this can also occur indirectly through
648 * e.g. holding a lock on a direct child.
650 * WARNING: Caller may hold an unrelated read spinlock, which means we can't
651 * use read spinlocks here.
656 cache_hold(struct nchandle *nch)
658 _cache_hold(nch->ncp);
659 atomic_add_int(&nch->mount->mnt_refs, 1);
664 * Create a copy of a namecache handle for an already-referenced
670 cache_copy(struct nchandle *nch, struct nchandle *target)
674 _cache_hold(target->ncp);
675 atomic_add_int(&nch->mount->mnt_refs, 1);
682 cache_changemount(struct nchandle *nch, struct mount *mp)
684 atomic_add_int(&nch->mount->mnt_refs, -1);
686 atomic_add_int(&nch->mount->mnt_refs, 1);
693 cache_drop(struct nchandle *nch)
695 atomic_add_int(&nch->mount->mnt_refs, -1);
696 _cache_drop(nch->ncp);
705 cache_lock(struct nchandle *nch)
707 _cache_lock(nch->ncp);
711 * Relock nch1 given an unlocked nch1 and a locked nch2. The caller
712 * is responsible for checking both for validity on return as they
713 * may have become invalid.
715 * We have to deal with potential deadlocks here, just ping pong
716 * the lock until we get it (we will always block somewhere when
717 * looping so this is not cpu-intensive).
719 * which = 0 nch1 not locked, nch2 is locked
720 * which = 1 nch1 is locked, nch2 is not locked
723 cache_relock(struct nchandle *nch1, struct ucred *cred1,
724 struct nchandle *nch2, struct ucred *cred2)
732 if (cache_lock_nonblock(nch1) == 0) {
733 cache_resolve(nch1, cred1);
738 cache_resolve(nch1, cred1);
741 if (cache_lock_nonblock(nch2) == 0) {
742 cache_resolve(nch2, cred2);
747 cache_resolve(nch2, cred2);
757 cache_lock_nonblock(struct nchandle *nch)
759 return(_cache_lock_nonblock(nch->ncp));
767 cache_unlock(struct nchandle *nch)
769 _cache_unlock(nch->ncp);
773 * ref-and-lock, unlock-and-deref functions.
775 * This function is primarily used by nlookup. Even though cache_lock
776 * holds the vnode, it is possible that the vnode may have already
777 * initiated a recyclement.
779 * We want cache_get() to return a definitively usable vnode or a
780 * definitively unresolved ncp.
786 _cache_get(struct namecache *ncp)
790 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
791 _cache_setunresolved(ncp);
796 * This is a special form of _cache_lock() which only succeeds if
797 * it can get a pristine, non-recursive lock. The caller must have
798 * already ref'd the ncp.
800 * On success the ncp will be locked, on failure it will not. The
801 * ref count does not change either way.
803 * We want _cache_lock_special() (on success) to return a definitively
804 * usable vnode or a definitively unresolved ncp.
809 _cache_lock_special(struct namecache *ncp)
811 if (_cache_lock_nonblock(ncp) == 0) {
812 if ((ncp->nc_exlocks & ~NC_EXLOCK_REQ) == 1) {
813 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
814 _cache_setunresolved(ncp);
824 * NOTE: The same nchandle can be passed for both arguments.
829 cache_get(struct nchandle *nch, struct nchandle *target)
831 KKASSERT(nch->ncp->nc_refs > 0);
832 target->mount = nch->mount;
833 target->ncp = _cache_get(nch->ncp);
834 atomic_add_int(&target->mount->mnt_refs, 1);
842 _cache_put(struct namecache *ncp)
852 cache_put(struct nchandle *nch)
854 atomic_add_int(&nch->mount->mnt_refs, -1);
855 _cache_put(nch->ncp);
861 * Resolve an unresolved ncp by associating a vnode with it. If the
862 * vnode is NULL, a negative cache entry is created.
864 * The ncp should be locked on entry and will remain locked on return.
870 _cache_setvp(struct mount *mp, struct namecache *ncp, struct vnode *vp)
872 KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
876 * Any vp associated with an ncp which has children must
877 * be held. Any vp associated with a locked ncp must be held.
879 if (!TAILQ_EMPTY(&ncp->nc_list))
881 spin_lock(&vp->v_spin);
883 TAILQ_INSERT_HEAD(&vp->v_namecache, ncp, nc_vnode);
884 spin_unlock(&vp->v_spin);
889 * Set auxiliary flags
893 ncp->nc_flag |= NCF_ISDIR;
896 ncp->nc_flag |= NCF_ISSYMLINK;
897 /* XXX cache the contents of the symlink */
902 atomic_add_int(&numcache, 1);
904 /* XXX: this is a hack to work-around the lack of a real pfs vfs
910 * When creating a negative cache hit we set the
911 * namecache_gen. A later resolve will clean out the
912 * negative cache hit if the mount point's namecache_gen
913 * has changed. Used by devfs, could also be used by
918 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
920 spin_unlock(&ncspin);
921 ncp->nc_error = ENOENT;
923 VFS_NCPGEN_SET(mp, ncp);
925 ncp->nc_flag &= ~(NCF_UNRESOLVED | NCF_DEFEREDZAP);
932 cache_setvp(struct nchandle *nch, struct vnode *vp)
934 _cache_setvp(nch->mount, nch->ncp, vp);
941 cache_settimeout(struct nchandle *nch, int nticks)
943 struct namecache *ncp = nch->ncp;
945 if ((ncp->nc_timeout = ticks + nticks) == 0)
950 * Disassociate the vnode or negative-cache association and mark a
951 * namecache entry as unresolved again. Note that the ncp is still
952 * left in the hash table and still linked to its parent.
954 * The ncp should be locked and refd on entry and will remain locked and refd
957 * This routine is normally never called on a directory containing children.
958 * However, NFS often does just that in its rename() code as a cop-out to
959 * avoid complex namespace operations. This disconnects a directory vnode
960 * from its namecache and can cause the OLDAPI and NEWAPI to get out of
967 _cache_setunresolved(struct namecache *ncp)
971 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
972 ncp->nc_flag |= NCF_UNRESOLVED;
974 ncp->nc_error = ENOTCONN;
975 if ((vp = ncp->nc_vp) != NULL) {
976 atomic_add_int(&numcache, -1);
977 spin_lock(&vp->v_spin);
979 TAILQ_REMOVE(&vp->v_namecache, ncp, nc_vnode);
980 spin_unlock(&vp->v_spin);
983 * Any vp associated with an ncp with children is
984 * held by that ncp. Any vp associated with a locked
985 * ncp is held by that ncp. These conditions must be
986 * undone when the vp is cleared out from the ncp.
988 if (!TAILQ_EMPTY(&ncp->nc_list))
994 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
996 spin_unlock(&ncspin);
998 ncp->nc_flag &= ~(NCF_WHITEOUT|NCF_ISDIR|NCF_ISSYMLINK);
1003 * The cache_nresolve() code calls this function to automatically
1004 * set a resolved cache element to unresolved if it has timed out
1005 * or if it is a negative cache hit and the mount point namecache_gen
1010 static __inline void
1011 _cache_auto_unresolve(struct mount *mp, struct namecache *ncp)
1014 * Already in an unresolved state, nothing to do.
1016 if (ncp->nc_flag & NCF_UNRESOLVED)
1020 * Try to zap entries that have timed out. We have
1021 * to be careful here because locked leafs may depend
1022 * on the vnode remaining intact in a parent, so only
1023 * do this under very specific conditions.
1025 if (ncp->nc_timeout && (int)(ncp->nc_timeout - ticks) < 0 &&
1026 TAILQ_EMPTY(&ncp->nc_list)) {
1027 _cache_setunresolved(ncp);
1032 * If a resolved negative cache hit is invalid due to
1033 * the mount's namecache generation being bumped, zap it.
1035 if (ncp->nc_vp == NULL && VFS_NCPGEN_TEST(mp, ncp)) {
1036 _cache_setunresolved(ncp);
1045 cache_setunresolved(struct nchandle *nch)
1047 _cache_setunresolved(nch->ncp);
1051 * Determine if we can clear NCF_ISMOUNTPT by scanning the mountlist
1052 * looking for matches. This flag tells the lookup code when it must
1053 * check for a mount linkage and also prevents the directories in question
1054 * from being deleted or renamed.
1060 cache_clrmountpt_callback(struct mount *mp, void *data)
1062 struct nchandle *nch = data;
1064 if (mp->mnt_ncmounton.ncp == nch->ncp)
1066 if (mp->mnt_ncmountpt.ncp == nch->ncp)
1075 cache_clrmountpt(struct nchandle *nch)
1079 count = mountlist_scan(cache_clrmountpt_callback, nch,
1080 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1082 nch->ncp->nc_flag &= ~NCF_ISMOUNTPT;
1086 * Invalidate portions of the namecache topology given a starting entry.
1087 * The passed ncp is set to an unresolved state and:
1089 * The passed ncp must be referencxed and locked. The routine may unlock
1090 * and relock ncp several times, and will recheck the children and loop
1091 * to catch races. When done the passed ncp will be returned with the
1092 * reference and lock intact.
1094 * CINV_DESTROY - Set a flag in the passed ncp entry indicating
1095 * that the physical underlying nodes have been
1096 * destroyed... as in deleted. For example, when
1097 * a directory is removed. This will cause record
1098 * lookups on the name to no longer be able to find
1099 * the record and tells the resolver to return failure
1100 * rather then trying to resolve through the parent.
1102 * The topology itself, including ncp->nc_name,
1105 * This only applies to the passed ncp, if CINV_CHILDREN
1106 * is specified the children are not flagged.
1108 * CINV_CHILDREN - Set all children (recursively) to an unresolved
1111 * Note that this will also have the side effect of
1112 * cleaning out any unreferenced nodes in the topology
1113 * from the leaves up as the recursion backs out.
1115 * Note that the topology for any referenced nodes remains intact, but
1116 * the nodes will be marked as having been destroyed and will be set
1117 * to an unresolved state.
1119 * It is possible for cache_inval() to race a cache_resolve(), meaning that
1120 * the namecache entry may not actually be invalidated on return if it was
1121 * revalidated while recursing down into its children. This code guarentees
1122 * that the node(s) will go through an invalidation cycle, but does not
1123 * guarentee that they will remain in an invalidated state.
1125 * Returns non-zero if a revalidation was detected during the invalidation
1126 * recursion, zero otherwise. Note that since only the original ncp is
1127 * locked the revalidation ultimately can only indicate that the original ncp
1128 * *MIGHT* no have been reresolved.
1130 * DEEP RECURSION HANDLING - If a recursive invalidation recurses deeply we
1131 * have to avoid blowing out the kernel stack. We do this by saving the
1132 * deep namecache node and aborting the recursion, then re-recursing at that
1133 * node using a depth-first algorithm in order to allow multiple deep
1134 * recursions to chain through each other, then we restart the invalidation
1141 struct namecache *resume_ncp;
1145 static int _cache_inval_internal(struct namecache *, int, struct cinvtrack *);
1149 _cache_inval(struct namecache *ncp, int flags)
1151 struct cinvtrack track;
1152 struct namecache *ncp2;
1156 track.resume_ncp = NULL;
1159 r = _cache_inval_internal(ncp, flags, &track);
1160 if (track.resume_ncp == NULL)
1162 kprintf("Warning: deep namecache recursion at %s\n",
1165 while ((ncp2 = track.resume_ncp) != NULL) {
1166 track.resume_ncp = NULL;
1168 _cache_inval_internal(ncp2, flags & ~CINV_DESTROY,
1178 cache_inval(struct nchandle *nch, int flags)
1180 return(_cache_inval(nch->ncp, flags));
1184 * Helper for _cache_inval(). The passed ncp is refd and locked and
1185 * remains that way on return, but may be unlocked/relocked multiple
1186 * times by the routine.
1189 _cache_inval_internal(struct namecache *ncp, int flags, struct cinvtrack *track)
1191 struct namecache *kid;
1192 struct namecache *nextkid;
1195 KKASSERT(ncp->nc_exlocks);
1197 _cache_setunresolved(ncp);
1198 if (flags & CINV_DESTROY)
1199 ncp->nc_flag |= NCF_DESTROYED;
1200 if ((flags & CINV_CHILDREN) &&
1201 (kid = TAILQ_FIRST(&ncp->nc_list)) != NULL
1204 if (++track->depth > MAX_RECURSION_DEPTH) {
1205 track->resume_ncp = ncp;
1211 if (track->resume_ncp) {
1215 if ((nextkid = TAILQ_NEXT(kid, nc_entry)) != NULL)
1216 _cache_hold(nextkid);
1217 if ((kid->nc_flag & NCF_UNRESOLVED) == 0 ||
1218 TAILQ_FIRST(&kid->nc_list)
1221 rcnt += _cache_inval_internal(kid, flags & ~CINV_DESTROY, track);
1232 * Someone could have gotten in there while ncp was unlocked,
1235 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
1241 * Invalidate a vnode's namecache associations. To avoid races against
1242 * the resolver we do not invalidate a node which we previously invalidated
1243 * but which was then re-resolved while we were in the invalidation loop.
1245 * Returns non-zero if any namecache entries remain after the invalidation
1248 * NOTE: Unlike the namecache topology which guarentees that ncp's will not
1249 * be ripped out of the topology while held, the vnode's v_namecache
1250 * list has no such restriction. NCP's can be ripped out of the list
1251 * at virtually any time if not locked, even if held.
1253 * In addition, the v_namecache list itself must be locked via
1254 * the vnode's spinlock.
1259 cache_inval_vp(struct vnode *vp, int flags)
1261 struct namecache *ncp;
1262 struct namecache *next;
1265 spin_lock(&vp->v_spin);
1266 ncp = TAILQ_FIRST(&vp->v_namecache);
1270 /* loop entered with ncp held and vp spin-locked */
1271 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1273 spin_unlock(&vp->v_spin);
1275 if (ncp->nc_vp != vp) {
1276 kprintf("Warning: cache_inval_vp: race-A detected on "
1277 "%s\n", ncp->nc_name);
1283 _cache_inval(ncp, flags);
1284 _cache_put(ncp); /* also releases reference */
1286 spin_lock(&vp->v_spin);
1287 if (ncp && ncp->nc_vp != vp) {
1288 spin_unlock(&vp->v_spin);
1289 kprintf("Warning: cache_inval_vp: race-B detected on "
1290 "%s\n", ncp->nc_name);
1295 spin_unlock(&vp->v_spin);
1296 return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1300 * This routine is used instead of the normal cache_inval_vp() when we
1301 * are trying to recycle otherwise good vnodes.
1303 * Return 0 on success, non-zero if not all namecache records could be
1304 * disassociated from the vnode (for various reasons).
1309 cache_inval_vp_nonblock(struct vnode *vp)
1311 struct namecache *ncp;
1312 struct namecache *next;
1314 spin_lock(&vp->v_spin);
1315 ncp = TAILQ_FIRST(&vp->v_namecache);
1319 /* loop entered with ncp held */
1320 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1322 spin_unlock(&vp->v_spin);
1323 if (_cache_lock_nonblock(ncp)) {
1329 if (ncp->nc_vp != vp) {
1330 kprintf("Warning: cache_inval_vp: race-A detected on "
1331 "%s\n", ncp->nc_name);
1337 _cache_inval(ncp, 0);
1338 _cache_put(ncp); /* also releases reference */
1340 spin_lock(&vp->v_spin);
1341 if (ncp && ncp->nc_vp != vp) {
1342 spin_unlock(&vp->v_spin);
1343 kprintf("Warning: cache_inval_vp: race-B detected on "
1344 "%s\n", ncp->nc_name);
1349 spin_unlock(&vp->v_spin);
1351 return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1355 * The source ncp has been renamed to the target ncp. Both fncp and tncp
1356 * must be locked. The target ncp is destroyed (as a normal rename-over
1357 * would destroy the target file or directory).
1359 * Because there may be references to the source ncp we cannot copy its
1360 * contents to the target. Instead the source ncp is relinked as the target
1361 * and the target ncp is removed from the namecache topology.
1366 cache_rename(struct nchandle *fnch, struct nchandle *tnch)
1368 struct namecache *fncp = fnch->ncp;
1369 struct namecache *tncp = tnch->ncp;
1370 struct namecache *tncp_par;
1371 struct nchash_head *nchpp;
1376 * Rename fncp (unlink)
1378 _cache_unlink_parent(fncp);
1379 oname = fncp->nc_name;
1380 fncp->nc_name = tncp->nc_name;
1381 fncp->nc_nlen = tncp->nc_nlen;
1382 tncp_par = tncp->nc_parent;
1383 _cache_hold(tncp_par);
1384 _cache_lock(tncp_par);
1387 * Rename fncp (relink)
1389 hash = fnv_32_buf(fncp->nc_name, fncp->nc_nlen, FNV1_32_INIT);
1390 hash = fnv_32_buf(&tncp_par, sizeof(tncp_par), hash);
1391 nchpp = NCHHASH(hash);
1393 spin_lock(&nchpp->spin);
1394 _cache_link_parent(fncp, tncp_par, nchpp);
1395 spin_unlock(&nchpp->spin);
1397 _cache_put(tncp_par);
1400 * Get rid of the overwritten tncp (unlink)
1402 _cache_setunresolved(tncp);
1403 _cache_unlink_parent(tncp);
1404 tncp->nc_name = NULL;
1408 kfree(oname, M_VFSCACHE);
1412 * vget the vnode associated with the namecache entry. Resolve the namecache
1413 * entry if necessary. The passed ncp must be referenced and locked.
1415 * lk_type may be LK_SHARED, LK_EXCLUSIVE. A ref'd, possibly locked
1416 * (depending on the passed lk_type) will be returned in *vpp with an error
1417 * of 0, or NULL will be returned in *vpp with a non-0 error code. The
1418 * most typical error is ENOENT, meaning that the ncp represents a negative
1419 * cache hit and there is no vnode to retrieve, but other errors can occur
1422 * The vget() can race a reclaim. If this occurs we re-resolve the
1425 * There are numerous places in the kernel where vget() is called on a
1426 * vnode while one or more of its namecache entries is locked. Releasing
1427 * a vnode never deadlocks against locked namecache entries (the vnode
1428 * will not get recycled while referenced ncp's exist). This means we
1429 * can safely acquire the vnode. In fact, we MUST NOT release the ncp
1430 * lock when acquiring the vp lock or we might cause a deadlock.
1435 cache_vget(struct nchandle *nch, struct ucred *cred,
1436 int lk_type, struct vnode **vpp)
1438 struct namecache *ncp;
1443 KKASSERT(ncp->nc_locktd == curthread);
1446 if (ncp->nc_flag & NCF_UNRESOLVED)
1447 error = cache_resolve(nch, cred);
1451 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1452 error = vget(vp, lk_type);
1457 if (error == ENOENT) {
1458 kprintf("Warning: vnode reclaim race detected "
1459 "in cache_vget on %p (%s)\n",
1461 _cache_setunresolved(ncp);
1466 * Not a reclaim race, some other error.
1468 KKASSERT(ncp->nc_vp == vp);
1471 KKASSERT(ncp->nc_vp == vp);
1472 KKASSERT((vp->v_flag & VRECLAIMED) == 0);
1475 if (error == 0 && vp == NULL)
1482 cache_vref(struct nchandle *nch, struct ucred *cred, struct vnode **vpp)
1484 struct namecache *ncp;
1489 KKASSERT(ncp->nc_locktd == curthread);
1492 if (ncp->nc_flag & NCF_UNRESOLVED)
1493 error = cache_resolve(nch, cred);
1497 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1498 error = vget(vp, LK_SHARED);
1503 if (error == ENOENT) {
1504 kprintf("Warning: vnode reclaim race detected "
1505 "in cache_vget on %p (%s)\n",
1507 _cache_setunresolved(ncp);
1512 * Not a reclaim race, some other error.
1514 KKASSERT(ncp->nc_vp == vp);
1517 KKASSERT(ncp->nc_vp == vp);
1518 KKASSERT((vp->v_flag & VRECLAIMED) == 0);
1519 /* caller does not want a lock */
1523 if (error == 0 && vp == NULL)
1530 * Return a referenced vnode representing the parent directory of
1533 * Because the caller has locked the ncp it should not be possible for
1534 * the parent ncp to go away. However, the parent can unresolve its
1535 * dvp at any time so we must be able to acquire a lock on the parent
1536 * to safely access nc_vp.
1538 * We have to leave par unlocked when vget()ing dvp to avoid a deadlock,
1539 * so use vhold()/vdrop() while holding the lock to prevent dvp from
1540 * getting destroyed.
1542 * MPSAFE - Note vhold() is allowed when dvp has 0 refs if we hold a
1543 * lock on the ncp in question..
1545 static struct vnode *
1546 cache_dvpref(struct namecache *ncp)
1548 struct namecache *par;
1552 if ((par = ncp->nc_parent) != NULL) {
1555 if ((par->nc_flag & NCF_UNRESOLVED) == 0) {
1556 if ((dvp = par->nc_vp) != NULL)
1561 if (vget(dvp, LK_SHARED) == 0) {
1564 /* return refd, unlocked dvp */
1576 * Convert a directory vnode to a namecache record without any other
1577 * knowledge of the topology. This ONLY works with directory vnodes and
1578 * is ONLY used by the NFS server. dvp must be refd but unlocked, and the
1579 * returned ncp (if not NULL) will be held and unlocked.
1581 * If 'makeit' is 0 and dvp has no existing namecache record, NULL is returned.
1582 * If 'makeit' is 1 we attempt to track-down and create the namecache topology
1583 * for dvp. This will fail only if the directory has been deleted out from
1586 * Callers must always check for a NULL return no matter the value of 'makeit'.
1588 * To avoid underflowing the kernel stack each recursive call increments
1589 * the makeit variable.
1592 static int cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1593 struct vnode *dvp, char *fakename);
1594 static int cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1595 struct vnode **saved_dvp);
1598 cache_fromdvp(struct vnode *dvp, struct ucred *cred, int makeit,
1599 struct nchandle *nch)
1601 struct vnode *saved_dvp;
1607 nch->mount = dvp->v_mount;
1612 * Handle the makeit == 0 degenerate case
1615 spin_lock(&dvp->v_spin);
1616 nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
1619 spin_unlock(&dvp->v_spin);
1623 * Loop until resolution, inside code will break out on error.
1627 * Break out if we successfully acquire a working ncp.
1629 spin_lock(&dvp->v_spin);
1630 nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
1633 spin_unlock(&dvp->v_spin);
1636 spin_unlock(&dvp->v_spin);
1639 * If dvp is the root of its filesystem it should already
1640 * have a namecache pointer associated with it as a side
1641 * effect of the mount, but it may have been disassociated.
1643 if (dvp->v_flag & VROOT) {
1644 nch->ncp = _cache_get(nch->mount->mnt_ncmountpt.ncp);
1645 error = cache_resolve_mp(nch->mount);
1646 _cache_put(nch->ncp);
1648 kprintf("cache_fromdvp: resolve root of mount %p error %d",
1649 dvp->v_mount, error);
1653 kprintf(" failed\n");
1658 kprintf(" succeeded\n");
1663 * If we are recursed too deeply resort to an O(n^2)
1664 * algorithm to resolve the namecache topology. The
1665 * resolved pvp is left referenced in saved_dvp to
1666 * prevent the tree from being destroyed while we loop.
1669 error = cache_fromdvp_try(dvp, cred, &saved_dvp);
1671 kprintf("lookupdotdot(longpath) failed %d "
1672 "dvp %p\n", error, dvp);
1680 * Get the parent directory and resolve its ncp.
1683 kfree(fakename, M_TEMP);
1686 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
1689 kprintf("lookupdotdot failed %d dvp %p\n", error, dvp);
1695 * Reuse makeit as a recursion depth counter. On success
1696 * nch will be fully referenced.
1698 cache_fromdvp(pvp, cred, makeit + 1, nch);
1700 if (nch->ncp == NULL)
1704 * Do an inefficient scan of pvp (embodied by ncp) to look
1705 * for dvp. This will create a namecache record for dvp on
1706 * success. We loop up to recheck on success.
1708 * ncp and dvp are both held but not locked.
1710 error = cache_inefficient_scan(nch, cred, dvp, fakename);
1712 kprintf("cache_fromdvp: scan %p (%s) failed on dvp=%p\n",
1713 pvp, nch->ncp->nc_name, dvp);
1715 /* nch was NULLed out, reload mount */
1716 nch->mount = dvp->v_mount;
1720 kprintf("cache_fromdvp: scan %p (%s) succeeded\n",
1721 pvp, nch->ncp->nc_name);
1724 /* nch was NULLed out, reload mount */
1725 nch->mount = dvp->v_mount;
1729 * If nch->ncp is non-NULL it will have been held already.
1732 kfree(fakename, M_TEMP);
1741 * Go up the chain of parent directories until we find something
1742 * we can resolve into the namecache. This is very inefficient.
1746 cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1747 struct vnode **saved_dvp)
1749 struct nchandle nch;
1752 static time_t last_fromdvp_report;
1756 * Loop getting the parent directory vnode until we get something we
1757 * can resolve in the namecache.
1760 nch.mount = dvp->v_mount;
1766 kfree(fakename, M_TEMP);
1769 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
1776 spin_lock(&pvp->v_spin);
1777 if ((nch.ncp = TAILQ_FIRST(&pvp->v_namecache)) != NULL) {
1778 _cache_hold(nch.ncp);
1779 spin_unlock(&pvp->v_spin);
1783 spin_unlock(&pvp->v_spin);
1784 if (pvp->v_flag & VROOT) {
1785 nch.ncp = _cache_get(pvp->v_mount->mnt_ncmountpt.ncp);
1786 error = cache_resolve_mp(nch.mount);
1787 _cache_unlock(nch.ncp);
1790 _cache_drop(nch.ncp);
1800 if (last_fromdvp_report != time_second) {
1801 last_fromdvp_report = time_second;
1802 kprintf("Warning: extremely inefficient path "
1803 "resolution on %s\n",
1806 error = cache_inefficient_scan(&nch, cred, dvp, fakename);
1809 * Hopefully dvp now has a namecache record associated with
1810 * it. Leave it referenced to prevent the kernel from
1811 * recycling the vnode. Otherwise extremely long directory
1812 * paths could result in endless recycling.
1817 _cache_drop(nch.ncp);
1820 kfree(fakename, M_TEMP);
1825 * Do an inefficient scan of the directory represented by ncp looking for
1826 * the directory vnode dvp. ncp must be held but not locked on entry and
1827 * will be held on return. dvp must be refd but not locked on entry and
1828 * will remain refd on return.
1830 * Why do this at all? Well, due to its stateless nature the NFS server
1831 * converts file handles directly to vnodes without necessarily going through
1832 * the namecache ops that would otherwise create the namecache topology
1833 * leading to the vnode. We could either (1) Change the namecache algorithms
1834 * to allow disconnect namecache records that are re-merged opportunistically,
1835 * or (2) Make the NFS server backtrack and scan to recover a connected
1836 * namecache topology in order to then be able to issue new API lookups.
1838 * It turns out that (1) is a huge mess. It takes a nice clean set of
1839 * namecache algorithms and introduces a lot of complication in every subsystem
1840 * that calls into the namecache to deal with the re-merge case, especially
1841 * since we are using the namecache to placehold negative lookups and the
1842 * vnode might not be immediately assigned. (2) is certainly far less
1843 * efficient then (1), but since we are only talking about directories here
1844 * (which are likely to remain cached), the case does not actually run all
1845 * that often and has the supreme advantage of not polluting the namecache
1848 * If a fakename is supplied just construct a namecache entry using the
1852 cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1853 struct vnode *dvp, char *fakename)
1855 struct nlcomponent nlc;
1856 struct nchandle rncp;
1868 vat.va_blocksize = 0;
1869 if ((error = VOP_GETATTR(dvp, &vat)) != 0)
1872 error = cache_vref(nch, cred, &pvp);
1877 kprintf("inefficient_scan: directory iosize %ld "
1878 "vattr fileid = %lld\n",
1880 (long long)vat.va_fileid);
1884 * Use the supplied fakename if not NULL. Fake names are typically
1885 * not in the actual filesystem hierarchy. This is used by HAMMER
1886 * to glue @@timestamp recursions together.
1889 nlc.nlc_nameptr = fakename;
1890 nlc.nlc_namelen = strlen(fakename);
1891 rncp = cache_nlookup(nch, &nlc);
1895 if ((blksize = vat.va_blocksize) == 0)
1896 blksize = DEV_BSIZE;
1897 rbuf = kmalloc(blksize, M_TEMP, M_WAITOK);
1903 iov.iov_base = rbuf;
1904 iov.iov_len = blksize;
1907 uio.uio_resid = blksize;
1908 uio.uio_segflg = UIO_SYSSPACE;
1909 uio.uio_rw = UIO_READ;
1910 uio.uio_td = curthread;
1912 if (ncvp_debug >= 2)
1913 kprintf("cache_inefficient_scan: readdir @ %08x\n", (int)uio.uio_offset);
1914 error = VOP_READDIR(pvp, &uio, cred, &eofflag, NULL, NULL);
1916 den = (struct dirent *)rbuf;
1917 bytes = blksize - uio.uio_resid;
1920 if (ncvp_debug >= 2) {
1921 kprintf("cache_inefficient_scan: %*.*s\n",
1922 den->d_namlen, den->d_namlen,
1925 if (den->d_type != DT_WHT &&
1926 den->d_ino == vat.va_fileid) {
1928 kprintf("cache_inefficient_scan: "
1929 "MATCHED inode %lld path %s/%*.*s\n",
1930 (long long)vat.va_fileid,
1932 den->d_namlen, den->d_namlen,
1935 nlc.nlc_nameptr = den->d_name;
1936 nlc.nlc_namelen = den->d_namlen;
1937 rncp = cache_nlookup(nch, &nlc);
1938 KKASSERT(rncp.ncp != NULL);
1941 bytes -= _DIRENT_DIRSIZ(den);
1942 den = _DIRENT_NEXT(den);
1944 if (rncp.ncp == NULL && eofflag == 0 && uio.uio_resid != blksize)
1947 kfree(rbuf, M_TEMP);
1951 if (rncp.ncp->nc_flag & NCF_UNRESOLVED) {
1952 _cache_setvp(rncp.mount, rncp.ncp, dvp);
1953 if (ncvp_debug >= 2) {
1954 kprintf("cache_inefficient_scan: setvp %s/%s = %p\n",
1955 nch->ncp->nc_name, rncp.ncp->nc_name, dvp);
1958 if (ncvp_debug >= 2) {
1959 kprintf("cache_inefficient_scan: setvp %s/%s already set %p/%p\n",
1960 nch->ncp->nc_name, rncp.ncp->nc_name, dvp,
1964 if (rncp.ncp->nc_vp == NULL)
1965 error = rncp.ncp->nc_error;
1967 * Release rncp after a successful nlookup. rncp was fully
1972 kprintf("cache_inefficient_scan: dvp %p NOT FOUND in %s\n",
1973 dvp, nch->ncp->nc_name);
1980 * Zap a namecache entry. The ncp is unconditionally set to an unresolved
1981 * state, which disassociates it from its vnode or ncneglist.
1983 * Then, if there are no additional references to the ncp and no children,
1984 * the ncp is removed from the topology and destroyed.
1986 * References and/or children may exist if the ncp is in the middle of the
1987 * topology, preventing the ncp from being destroyed.
1989 * This function must be called with the ncp held and locked and will unlock
1990 * and drop it during zapping.
1992 * If nonblock is non-zero and the parent ncp cannot be locked we give up.
1993 * This case can occur in the cache_drop() path.
1995 * This function may returned a held (but NOT locked) parent node which the
1996 * caller must drop. We do this so _cache_drop() can loop, to avoid
1997 * blowing out the kernel stack.
1999 * WARNING! For MPSAFE operation this routine must acquire up to three
2000 * spin locks to be able to safely test nc_refs. Lock order is
2003 * hash spinlock if on hash list
2004 * parent spinlock if child of parent
2005 * (the ncp is unresolved so there is no vnode association)
2007 static struct namecache *
2008 cache_zap(struct namecache *ncp, int nonblock)
2010 struct namecache *par;
2011 struct vnode *dropvp;
2015 * Disassociate the vnode or negative cache ref and set NCF_UNRESOLVED.
2017 _cache_setunresolved(ncp);
2020 * Try to scrap the entry and possibly tail-recurse on its parent.
2021 * We only scrap unref'd (other then our ref) unresolved entries,
2022 * we do not scrap 'live' entries.
2024 * Note that once the spinlocks are acquired if nc_refs == 1 no
2025 * other references are possible. If it isn't, however, we have
2026 * to decrement but also be sure to avoid a 1->0 transition.
2028 KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
2029 KKASSERT(ncp->nc_refs > 0);
2032 * Acquire locks. Note that the parent can't go away while we hold
2035 if ((par = ncp->nc_parent) != NULL) {
2038 if (_cache_lock_nonblock(par) == 0)
2040 refs = ncp->nc_refs;
2041 ncp->nc_flag |= NCF_DEFEREDZAP;
2042 ++numdefered; /* MP race ok */
2043 if (atomic_cmpset_int(&ncp->nc_refs,
2055 spin_lock(&ncp->nc_head->spin);
2059 * If someone other then us has a ref or we have children
2060 * we cannot zap the entry. The 1->0 transition and any
2061 * further list operation is protected by the spinlocks
2062 * we have acquired but other transitions are not.
2065 refs = ncp->nc_refs;
2066 if (refs == 1 && TAILQ_EMPTY(&ncp->nc_list))
2068 if (atomic_cmpset_int(&ncp->nc_refs, refs, refs - 1)) {
2070 spin_unlock(&ncp->nc_head->spin);
2080 * We are the only ref and with the spinlocks held no further
2081 * refs can be acquired by others.
2083 * Remove us from the hash list and parent list. We have to
2084 * drop a ref on the parent's vp if the parent's list becomes
2089 struct nchash_head *nchpp = ncp->nc_head;
2091 KKASSERT(nchpp != NULL);
2092 LIST_REMOVE(ncp, nc_hash);
2093 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
2094 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
2095 dropvp = par->nc_vp;
2096 ncp->nc_head = NULL;
2097 ncp->nc_parent = NULL;
2098 spin_unlock(&nchpp->spin);
2101 KKASSERT(ncp->nc_head == NULL);
2105 * ncp should not have picked up any refs. Physically
2108 KKASSERT(ncp->nc_refs == 1);
2109 /* _cache_unlock(ncp) not required */
2110 ncp->nc_refs = -1; /* safety */
2112 kfree(ncp->nc_name, M_VFSCACHE);
2113 kfree(ncp, M_VFSCACHE);
2116 * Delayed drop (we had to release our spinlocks)
2118 * The refed parent (if not NULL) must be dropped. The
2119 * caller is responsible for looping.
2127 * Clean up dangling negative cache and defered-drop entries in the
2130 typedef enum { CHI_LOW, CHI_HIGH } cache_hs_t;
2132 static cache_hs_t neg_cache_hysteresis_state = CHI_LOW;
2133 static cache_hs_t pos_cache_hysteresis_state = CHI_LOW;
2136 cache_hysteresis(void)
2141 * Don't cache too many negative hits. We use hysteresis to reduce
2142 * the impact on the critical path.
2144 switch(neg_cache_hysteresis_state) {
2146 if (numneg > MINNEG && numneg * ncnegfactor > numcache) {
2147 _cache_cleanneg(10);
2148 neg_cache_hysteresis_state = CHI_HIGH;
2152 if (numneg > MINNEG * 9 / 10 &&
2153 numneg * ncnegfactor * 9 / 10 > numcache
2155 _cache_cleanneg(10);
2157 neg_cache_hysteresis_state = CHI_LOW;
2163 * Don't cache too many positive hits. We use hysteresis to reduce
2164 * the impact on the critical path.
2166 * Excessive positive hits can accumulate due to large numbers of
2167 * hardlinks (the vnode cache will not prevent hl ncps from growing
2170 if ((poslimit = ncposlimit) == 0)
2171 poslimit = desiredvnodes * 2;
2173 switch(pos_cache_hysteresis_state) {
2175 if (numcache > poslimit && numcache > MINPOS) {
2176 _cache_cleanpos(10);
2177 pos_cache_hysteresis_state = CHI_HIGH;
2181 if (numcache > poslimit * 5 / 6 && numcache > MINPOS) {
2182 _cache_cleanpos(10);
2184 pos_cache_hysteresis_state = CHI_LOW;
2190 * Clean out dangling defered-zap ncps which could not
2191 * be cleanly dropped if too many build up. Note
2192 * that numdefered is not an exact number as such ncps
2193 * can be reused and the counter is not handled in a MP
2194 * safe manner by design.
2196 if (numdefered * ncnegfactor > numcache) {
2197 _cache_cleandefered();
2202 * NEW NAMECACHE LOOKUP API
2204 * Lookup an entry in the namecache. The passed par_nch must be referenced
2205 * and unlocked. A referenced and locked nchandle with a non-NULL nch.ncp
2206 * is ALWAYS returned, eve if the supplied component is illegal.
2208 * The resulting namecache entry should be returned to the system with
2209 * cache_put() or cache_unlock() + cache_drop().
2211 * namecache locks are recursive but care must be taken to avoid lock order
2212 * reversals (hence why the passed par_nch must be unlocked). Locking
2213 * rules are to order for parent traversals, not for child traversals.
2215 * Nobody else will be able to manipulate the associated namespace (e.g.
2216 * create, delete, rename, rename-target) until the caller unlocks the
2219 * The returned entry will be in one of three states: positive hit (non-null
2220 * vnode), negative hit (null vnode), or unresolved (NCF_UNRESOLVED is set).
2221 * Unresolved entries must be resolved through the filesystem to associate the
2222 * vnode and/or determine whether a positive or negative hit has occured.
2224 * It is not necessary to lock a directory in order to lock namespace under
2225 * that directory. In fact, it is explicitly not allowed to do that. A
2226 * directory is typically only locked when being created, renamed, or
2229 * The directory (par) may be unresolved, in which case any returned child
2230 * will likely also be marked unresolved. Likely but not guarenteed. Since
2231 * the filesystem lookup requires a resolved directory vnode the caller is
2232 * responsible for resolving the namecache chain top-down. This API
2233 * specifically allows whole chains to be created in an unresolved state.
2236 cache_nlookup(struct nchandle *par_nch, struct nlcomponent *nlc)
2238 struct nchandle nch;
2239 struct namecache *ncp;
2240 struct namecache *new_ncp;
2241 struct nchash_head *nchpp;
2249 mp = par_nch->mount;
2253 * This is a good time to call it, no ncp's are locked by
2259 * Try to locate an existing entry
2261 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
2262 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
2264 nchpp = NCHHASH(hash);
2266 spin_lock(&nchpp->spin);
2267 LIST_FOREACH(ncp, &nchpp->list, nc_hash) {
2271 * Break out if we find a matching entry. Note that
2272 * UNRESOLVED entries may match, but DESTROYED entries
2275 if (ncp->nc_parent == par_nch->ncp &&
2276 ncp->nc_nlen == nlc->nlc_namelen &&
2277 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
2278 (ncp->nc_flag & NCF_DESTROYED) == 0
2281 spin_unlock(&nchpp->spin);
2283 _cache_unlock(par_nch->ncp);
2286 if (_cache_lock_special(ncp) == 0) {
2287 _cache_auto_unresolve(mp, ncp);
2289 _cache_free(new_ncp);
2300 * We failed to locate an entry, create a new entry and add it to
2301 * the cache. The parent ncp must also be locked so we
2304 * We have to relookup after possibly blocking in kmalloc or
2305 * when locking par_nch.
2307 * NOTE: nlc_namelen can be 0 and nlc_nameptr NULL as a special
2308 * mount case, in which case nc_name will be NULL.
2310 if (new_ncp == NULL) {
2311 spin_unlock(&nchpp->spin);
2312 new_ncp = cache_alloc(nlc->nlc_namelen);
2313 if (nlc->nlc_namelen) {
2314 bcopy(nlc->nlc_nameptr, new_ncp->nc_name,
2316 new_ncp->nc_name[nlc->nlc_namelen] = 0;
2320 if (par_locked == 0) {
2321 spin_unlock(&nchpp->spin);
2322 _cache_lock(par_nch->ncp);
2328 * WARNING! We still hold the spinlock. We have to set the hash
2329 * table entry atomically.
2332 _cache_link_parent(ncp, par_nch->ncp, nchpp);
2333 spin_unlock(&nchpp->spin);
2334 _cache_unlock(par_nch->ncp);
2335 /* par_locked = 0 - not used */
2338 * stats and namecache size management
2340 if (ncp->nc_flag & NCF_UNRESOLVED)
2341 ++gd->gd_nchstats->ncs_miss;
2342 else if (ncp->nc_vp)
2343 ++gd->gd_nchstats->ncs_goodhits;
2345 ++gd->gd_nchstats->ncs_neghits;
2348 atomic_add_int(&nch.mount->mnt_refs, 1);
2353 * This is a non-blocking verison of cache_nlookup() used by
2354 * nfs_readdirplusrpc_uio(). It can fail for any reason and
2355 * will return nch.ncp == NULL in that case.
2358 cache_nlookup_nonblock(struct nchandle *par_nch, struct nlcomponent *nlc)
2360 struct nchandle nch;
2361 struct namecache *ncp;
2362 struct namecache *new_ncp;
2363 struct nchash_head *nchpp;
2371 mp = par_nch->mount;
2375 * Try to locate an existing entry
2377 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
2378 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
2380 nchpp = NCHHASH(hash);
2382 spin_lock(&nchpp->spin);
2383 LIST_FOREACH(ncp, &nchpp->list, nc_hash) {
2387 * Break out if we find a matching entry. Note that
2388 * UNRESOLVED entries may match, but DESTROYED entries
2391 if (ncp->nc_parent == par_nch->ncp &&
2392 ncp->nc_nlen == nlc->nlc_namelen &&
2393 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
2394 (ncp->nc_flag & NCF_DESTROYED) == 0
2397 spin_unlock(&nchpp->spin);
2399 _cache_unlock(par_nch->ncp);
2402 if (_cache_lock_special(ncp) == 0) {
2403 _cache_auto_unresolve(mp, ncp);
2405 _cache_free(new_ncp);
2416 * We failed to locate an entry, create a new entry and add it to
2417 * the cache. The parent ncp must also be locked so we
2420 * We have to relookup after possibly blocking in kmalloc or
2421 * when locking par_nch.
2423 * NOTE: nlc_namelen can be 0 and nlc_nameptr NULL as a special
2424 * mount case, in which case nc_name will be NULL.
2426 if (new_ncp == NULL) {
2427 spin_unlock(&nchpp->spin);
2428 new_ncp = cache_alloc(nlc->nlc_namelen);
2429 if (nlc->nlc_namelen) {
2430 bcopy(nlc->nlc_nameptr, new_ncp->nc_name,
2432 new_ncp->nc_name[nlc->nlc_namelen] = 0;
2436 if (par_locked == 0) {
2437 spin_unlock(&nchpp->spin);
2438 if (_cache_lock_nonblock(par_nch->ncp) == 0) {
2446 * WARNING! We still hold the spinlock. We have to set the hash
2447 * table entry atomically.
2450 _cache_link_parent(ncp, par_nch->ncp, nchpp);
2451 spin_unlock(&nchpp->spin);
2452 _cache_unlock(par_nch->ncp);
2453 /* par_locked = 0 - not used */
2456 * stats and namecache size management
2458 if (ncp->nc_flag & NCF_UNRESOLVED)
2459 ++gd->gd_nchstats->ncs_miss;
2460 else if (ncp->nc_vp)
2461 ++gd->gd_nchstats->ncs_goodhits;
2463 ++gd->gd_nchstats->ncs_neghits;
2466 atomic_add_int(&nch.mount->mnt_refs, 1);
2470 _cache_free(new_ncp);
2479 * The namecache entry is marked as being used as a mount point.
2480 * Locate the mount if it is visible to the caller.
2482 struct findmount_info {
2483 struct mount *result;
2484 struct mount *nch_mount;
2485 struct namecache *nch_ncp;
2490 cache_findmount_callback(struct mount *mp, void *data)
2492 struct findmount_info *info = data;
2495 * Check the mount's mounted-on point against the passed nch.
2497 if (mp->mnt_ncmounton.mount == info->nch_mount &&
2498 mp->mnt_ncmounton.ncp == info->nch_ncp
2501 atomic_add_int(&mp->mnt_refs, 1);
2508 cache_findmount(struct nchandle *nch)
2510 struct findmount_info info;
2513 info.nch_mount = nch->mount;
2514 info.nch_ncp = nch->ncp;
2515 mountlist_scan(cache_findmount_callback, &info,
2516 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
2517 return(info.result);
2521 cache_dropmount(struct mount *mp)
2523 atomic_add_int(&mp->mnt_refs, -1);
2527 * Resolve an unresolved namecache entry, generally by looking it up.
2528 * The passed ncp must be locked and refd.
2530 * Theoretically since a vnode cannot be recycled while held, and since
2531 * the nc_parent chain holds its vnode as long as children exist, the
2532 * direct parent of the cache entry we are trying to resolve should
2533 * have a valid vnode. If not then generate an error that we can
2534 * determine is related to a resolver bug.
2536 * However, if a vnode was in the middle of a recyclement when the NCP
2537 * got locked, ncp->nc_vp might point to a vnode that is about to become
2538 * invalid. cache_resolve() handles this case by unresolving the entry
2539 * and then re-resolving it.
2541 * Note that successful resolution does not necessarily return an error
2542 * code of 0. If the ncp resolves to a negative cache hit then ENOENT
2548 cache_resolve(struct nchandle *nch, struct ucred *cred)
2550 struct namecache *par_tmp;
2551 struct namecache *par;
2552 struct namecache *ncp;
2553 struct nchandle nctmp;
2562 * If the ncp is already resolved we have nothing to do. However,
2563 * we do want to guarentee that a usable vnode is returned when
2564 * a vnode is present, so make sure it hasn't been reclaimed.
2566 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
2567 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
2568 _cache_setunresolved(ncp);
2569 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
2570 return (ncp->nc_error);
2574 * Mount points need special handling because the parent does not
2575 * belong to the same filesystem as the ncp.
2577 if (ncp == mp->mnt_ncmountpt.ncp)
2578 return (cache_resolve_mp(mp));
2581 * We expect an unbroken chain of ncps to at least the mount point,
2582 * and even all the way to root (but this code doesn't have to go
2583 * past the mount point).
2585 if (ncp->nc_parent == NULL) {
2586 kprintf("EXDEV case 1 %p %*.*s\n", ncp,
2587 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
2588 ncp->nc_error = EXDEV;
2589 return(ncp->nc_error);
2593 * The vp's of the parent directories in the chain are held via vhold()
2594 * due to the existance of the child, and should not disappear.
2595 * However, there are cases where they can disappear:
2597 * - due to filesystem I/O errors.
2598 * - due to NFS being stupid about tracking the namespace and
2599 * destroys the namespace for entire directories quite often.
2600 * - due to forced unmounts.
2601 * - due to an rmdir (parent will be marked DESTROYED)
2603 * When this occurs we have to track the chain backwards and resolve
2604 * it, looping until the resolver catches up to the current node. We
2605 * could recurse here but we might run ourselves out of kernel stack
2606 * so we do it in a more painful manner. This situation really should
2607 * not occur all that often, or if it does not have to go back too
2608 * many nodes to resolve the ncp.
2610 while ((dvp = cache_dvpref(ncp)) == NULL) {
2612 * This case can occur if a process is CD'd into a
2613 * directory which is then rmdir'd. If the parent is marked
2614 * destroyed there is no point trying to resolve it.
2616 if (ncp->nc_parent->nc_flag & NCF_DESTROYED)
2618 par = ncp->nc_parent;
2621 while ((par_tmp = par->nc_parent) != NULL &&
2622 par_tmp->nc_vp == NULL) {
2623 _cache_hold(par_tmp);
2624 _cache_lock(par_tmp);
2628 if (par->nc_parent == NULL) {
2629 kprintf("EXDEV case 2 %*.*s\n",
2630 par->nc_nlen, par->nc_nlen, par->nc_name);
2634 kprintf("[diagnostic] cache_resolve: had to recurse on %*.*s\n",
2635 par->nc_nlen, par->nc_nlen, par->nc_name);
2637 * The parent is not set in stone, ref and lock it to prevent
2638 * it from disappearing. Also note that due to renames it
2639 * is possible for our ncp to move and for par to no longer
2640 * be one of its parents. We resolve it anyway, the loop
2641 * will handle any moves.
2643 _cache_get(par); /* additional hold/lock */
2644 _cache_put(par); /* from earlier hold/lock */
2645 if (par == nch->mount->mnt_ncmountpt.ncp) {
2646 cache_resolve_mp(nch->mount);
2647 } else if ((dvp = cache_dvpref(par)) == NULL) {
2648 kprintf("[diagnostic] cache_resolve: raced on %*.*s\n", par->nc_nlen, par->nc_nlen, par->nc_name);
2652 if (par->nc_flag & NCF_UNRESOLVED) {
2655 par->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
2659 if ((error = par->nc_error) != 0) {
2660 if (par->nc_error != EAGAIN) {
2661 kprintf("EXDEV case 3 %*.*s error %d\n",
2662 par->nc_nlen, par->nc_nlen, par->nc_name,
2667 kprintf("[diagnostic] cache_resolve: EAGAIN par %p %*.*s\n",
2668 par, par->nc_nlen, par->nc_nlen, par->nc_name);
2675 * Call VOP_NRESOLVE() to get the vp, then scan for any disconnected
2676 * ncp's and reattach them. If this occurs the original ncp is marked
2677 * EAGAIN to force a relookup.
2679 * NOTE: in order to call VOP_NRESOLVE(), the parent of the passed
2680 * ncp must already be resolved.
2685 ncp->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
2688 ncp->nc_error = EPERM;
2690 if (ncp->nc_error == EAGAIN) {
2691 kprintf("[diagnostic] cache_resolve: EAGAIN ncp %p %*.*s\n",
2692 ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
2695 return(ncp->nc_error);
2699 * Resolve the ncp associated with a mount point. Such ncp's almost always
2700 * remain resolved and this routine is rarely called. NFS MPs tends to force
2701 * re-resolution more often due to its mac-truck-smash-the-namecache
2702 * method of tracking namespace changes.
2704 * The semantics for this call is that the passed ncp must be locked on
2705 * entry and will be locked on return. However, if we actually have to
2706 * resolve the mount point we temporarily unlock the entry in order to
2707 * avoid race-to-root deadlocks due to e.g. dead NFS mounts. Because of
2708 * the unlock we have to recheck the flags after we relock.
2711 cache_resolve_mp(struct mount *mp)
2713 struct namecache *ncp = mp->mnt_ncmountpt.ncp;
2717 KKASSERT(mp != NULL);
2720 * If the ncp is already resolved we have nothing to do. However,
2721 * we do want to guarentee that a usable vnode is returned when
2722 * a vnode is present, so make sure it hasn't been reclaimed.
2724 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
2725 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
2726 _cache_setunresolved(ncp);
2729 if (ncp->nc_flag & NCF_UNRESOLVED) {
2731 while (vfs_busy(mp, 0))
2733 error = VFS_ROOT(mp, &vp);
2737 * recheck the ncp state after relocking.
2739 if (ncp->nc_flag & NCF_UNRESOLVED) {
2740 ncp->nc_error = error;
2742 _cache_setvp(mp, ncp, vp);
2745 kprintf("[diagnostic] cache_resolve_mp: failed"
2746 " to resolve mount %p err=%d ncp=%p\n",
2748 _cache_setvp(mp, ncp, NULL);
2750 } else if (error == 0) {
2755 return(ncp->nc_error);
2759 * Clean out negative cache entries when too many have accumulated.
2764 _cache_cleanneg(int count)
2766 struct namecache *ncp;
2769 * Attempt to clean out the specified number of negative cache
2774 ncp = TAILQ_FIRST(&ncneglist);
2776 spin_unlock(&ncspin);
2779 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
2780 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
2782 spin_unlock(&ncspin);
2783 if (_cache_lock_special(ncp) == 0) {
2784 ncp = cache_zap(ncp, 1);
2795 * Clean out positive cache entries when too many have accumulated.
2800 _cache_cleanpos(int count)
2802 static volatile int rover;
2803 struct nchash_head *nchpp;
2804 struct namecache *ncp;
2808 * Attempt to clean out the specified number of negative cache
2812 rover_copy = ++rover; /* MPSAFEENOUGH */
2814 nchpp = NCHHASH(rover_copy);
2816 spin_lock(&nchpp->spin);
2817 ncp = LIST_FIRST(&nchpp->list);
2820 spin_unlock(&nchpp->spin);
2823 if (_cache_lock_special(ncp) == 0) {
2824 ncp = cache_zap(ncp, 1);
2836 * This is a kitchen sink function to clean out ncps which we
2837 * tried to zap from cache_drop() but failed because we were
2838 * unable to acquire the parent lock.
2840 * Such entries can also be removed via cache_inval_vp(), such
2841 * as when unmounting.
2846 _cache_cleandefered(void)
2848 struct nchash_head *nchpp;
2849 struct namecache *ncp;
2850 struct namecache dummy;
2854 bzero(&dummy, sizeof(dummy));
2855 dummy.nc_flag = NCF_DESTROYED;
2857 for (i = 0; i <= nchash; ++i) {
2858 nchpp = &nchashtbl[i];
2860 spin_lock(&nchpp->spin);
2861 LIST_INSERT_HEAD(&nchpp->list, &dummy, nc_hash);
2863 while ((ncp = LIST_NEXT(ncp, nc_hash)) != NULL) {
2864 if ((ncp->nc_flag & NCF_DEFEREDZAP) == 0)
2866 LIST_REMOVE(&dummy, nc_hash);
2867 LIST_INSERT_AFTER(ncp, &dummy, nc_hash);
2869 spin_unlock(&nchpp->spin);
2870 if (_cache_lock_nonblock(ncp) == 0) {
2871 ncp->nc_flag &= ~NCF_DEFEREDZAP;
2875 spin_lock(&nchpp->spin);
2878 LIST_REMOVE(&dummy, nc_hash);
2879 spin_unlock(&nchpp->spin);
2884 * Name cache initialization, from vfsinit() when we are booting
2892 /* initialise per-cpu namecache effectiveness statistics. */
2893 for (i = 0; i < ncpus; ++i) {
2894 gd = globaldata_find(i);
2895 gd->gd_nchstats = &nchstats[i];
2897 TAILQ_INIT(&ncneglist);
2899 nchashtbl = hashinit_ext(desiredvnodes / 2,
2900 sizeof(struct nchash_head),
2901 M_VFSCACHE, &nchash);
2902 for (i = 0; i <= (int)nchash; ++i) {
2903 LIST_INIT(&nchashtbl[i].list);
2904 spin_init(&nchashtbl[i].spin);
2906 nclockwarn = 5 * hz;
2910 * Called from start_init() to bootstrap the root filesystem. Returns
2911 * a referenced, unlocked namecache record.
2914 cache_allocroot(struct nchandle *nch, struct mount *mp, struct vnode *vp)
2916 nch->ncp = cache_alloc(0);
2918 atomic_add_int(&mp->mnt_refs, 1);
2920 _cache_setvp(nch->mount, nch->ncp, vp);
2924 * vfs_cache_setroot()
2926 * Create an association between the root of our namecache and
2927 * the root vnode. This routine may be called several times during
2930 * If the caller intends to save the returned namecache pointer somewhere
2931 * it must cache_hold() it.
2934 vfs_cache_setroot(struct vnode *nvp, struct nchandle *nch)
2937 struct nchandle onch;
2945 cache_zero(&rootnch);
2953 * XXX OLD API COMPAT FUNCTION. This really messes up the new namecache
2954 * topology and is being removed as quickly as possible. The new VOP_N*()
2955 * API calls are required to make specific adjustments using the supplied
2956 * ncp pointers rather then just bogusly purging random vnodes.
2958 * Invalidate all namecache entries to a particular vnode as well as
2959 * any direct children of that vnode in the namecache. This is a
2960 * 'catch all' purge used by filesystems that do not know any better.
2962 * Note that the linkage between the vnode and its namecache entries will
2963 * be removed, but the namecache entries themselves might stay put due to
2964 * active references from elsewhere in the system or due to the existance of
2965 * the children. The namecache topology is left intact even if we do not
2966 * know what the vnode association is. Such entries will be marked
2970 cache_purge(struct vnode *vp)
2972 cache_inval_vp(vp, CINV_DESTROY | CINV_CHILDREN);
2976 * Flush all entries referencing a particular filesystem.
2978 * Since we need to check it anyway, we will flush all the invalid
2979 * entries at the same time.
2984 cache_purgevfs(struct mount *mp)
2986 struct nchash_head *nchpp;
2987 struct namecache *ncp, *nnp;
2990 * Scan hash tables for applicable entries.
2992 for (nchpp = &nchashtbl[nchash]; nchpp >= nchashtbl; nchpp--) {
2993 spin_lock_wr(&nchpp->spin); XXX
2994 ncp = LIST_FIRST(&nchpp->list);
2998 nnp = LIST_NEXT(ncp, nc_hash);
3001 if (ncp->nc_mount == mp) {
3003 ncp = cache_zap(ncp, 0);
3011 spin_unlock_wr(&nchpp->spin); XXX
3017 static int disablecwd;
3018 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0,
3021 static u_long numcwdcalls;
3022 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdcalls, CTLFLAG_RD, &numcwdcalls, 0,
3023 "Number of current directory resolution calls");
3024 static u_long numcwdfailnf;
3025 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfailnf, CTLFLAG_RD, &numcwdfailnf, 0,
3026 "Number of current directory failures due to lack of file");
3027 static u_long numcwdfailsz;
3028 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfailsz, CTLFLAG_RD, &numcwdfailsz, 0,
3029 "Number of current directory failures due to large result");
3030 static u_long numcwdfound;
3031 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfound, CTLFLAG_RD, &numcwdfound, 0,
3032 "Number of current directory resolution successes");
3038 sys___getcwd(struct __getcwd_args *uap)
3048 buflen = uap->buflen;
3051 if (buflen > MAXPATHLEN)
3052 buflen = MAXPATHLEN;
3054 buf = kmalloc(buflen, M_TEMP, M_WAITOK);
3056 bp = kern_getcwd(buf, buflen, &error);
3059 error = copyout(bp, uap->buf, strlen(bp) + 1);
3065 kern_getcwd(char *buf, size_t buflen, int *error)
3067 struct proc *p = curproc;
3069 int i, slash_prefixed;
3070 struct filedesc *fdp;
3071 struct nchandle nch;
3072 struct namecache *ncp;
3081 nch = fdp->fd_ncdir;
3086 while (ncp && (ncp != fdp->fd_nrdir.ncp ||
3087 nch.mount != fdp->fd_nrdir.mount)
3090 * While traversing upwards if we encounter the root
3091 * of the current mount we have to skip to the mount point
3092 * in the underlying filesystem.
3094 if (ncp == nch.mount->mnt_ncmountpt.ncp) {
3095 nch = nch.mount->mnt_ncmounton;
3104 * Prepend the path segment
3106 for (i = ncp->nc_nlen - 1; i >= 0; i--) {
3113 *--bp = ncp->nc_name[i];
3125 * Go up a directory. This isn't a mount point so we don't
3126 * have to check again.
3128 while ((nch.ncp = ncp->nc_parent) != NULL) {
3130 if (nch.ncp != ncp->nc_parent) {
3134 _cache_hold(nch.ncp);
3147 if (!slash_prefixed) {
3165 * Thus begins the fullpath magic.
3167 * The passed nchp is referenced but not locked.
3169 static int disablefullpath;
3170 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW,
3171 &disablefullpath, 0,
3172 "Disable fullpath lookups");
3174 static u_int numfullpathcalls;
3175 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathcalls, CTLFLAG_RD,
3176 &numfullpathcalls, 0,
3177 "Number of full path resolutions in progress");
3178 static u_int numfullpathfailnf;
3179 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathfailnf, CTLFLAG_RD,
3180 &numfullpathfailnf, 0,
3181 "Number of full path resolution failures due to lack of file");
3182 static u_int numfullpathfailsz;
3183 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathfailsz, CTLFLAG_RD,
3184 &numfullpathfailsz, 0,
3185 "Number of full path resolution failures due to insufficient memory");
3186 static u_int numfullpathfound;
3187 SYSCTL_UINT(_vfs_cache, OID_AUTO, numfullpathfound, CTLFLAG_RD,
3188 &numfullpathfound, 0,
3189 "Number of full path resolution successes");
3192 cache_fullpath(struct proc *p, struct nchandle *nchp,
3193 char **retbuf, char **freebuf, int guess)
3195 struct nchandle fd_nrdir;
3196 struct nchandle nch;
3197 struct namecache *ncp;
3198 struct mount *mp, *new_mp;
3204 atomic_add_int(&numfullpathcalls, -1);
3209 buf = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
3210 bp = buf + MAXPATHLEN - 1;
3213 fd_nrdir = p->p_fd->fd_nrdir;
3223 while (ncp && (ncp != fd_nrdir.ncp || mp != fd_nrdir.mount)) {
3227 * If we are asked to guess the upwards path, we do so whenever
3228 * we encounter an ncp marked as a mountpoint. We try to find
3229 * the actual mountpoint by finding the mountpoint with this ncp.
3231 if (guess && (ncp->nc_flag & NCF_ISMOUNTPT)) {
3232 new_mp = mount_get_by_nc(ncp);
3235 * While traversing upwards if we encounter the root
3236 * of the current mount we have to skip to the mount point.
3238 if (ncp == mp->mnt_ncmountpt.ncp) {
3242 nch = new_mp->mnt_ncmounton;
3252 * Prepend the path segment
3254 for (i = ncp->nc_nlen - 1; i >= 0; i--) {
3256 numfullpathfailsz++;
3261 *--bp = ncp->nc_name[i];
3264 numfullpathfailsz++;
3273 * Go up a directory. This isn't a mount point so we don't
3274 * have to check again.
3276 * We can only safely access nc_parent with ncp held locked.
3278 while ((nch.ncp = ncp->nc_parent) != NULL) {
3280 if (nch.ncp != ncp->nc_parent) {
3284 _cache_hold(nch.ncp);
3292 numfullpathfailnf++;
3298 if (!slash_prefixed) {
3300 numfullpathfailsz++;
3318 vn_fullpath(struct proc *p, struct vnode *vn, char **retbuf, char **freebuf,
3321 struct namecache *ncp;
3322 struct nchandle nch;
3326 atomic_add_int(&numfullpathcalls, 1);
3327 if (disablefullpath)
3333 /* vn is NULL, client wants us to use p->p_textvp */
3335 if ((vn = p->p_textvp) == NULL)
3338 spin_lock(&vn->v_spin);
3339 TAILQ_FOREACH(ncp, &vn->v_namecache, nc_vnode) {
3344 spin_unlock(&vn->v_spin);
3348 spin_unlock(&vn->v_spin);
3350 atomic_add_int(&numfullpathcalls, -1);
3352 nch.mount = vn->v_mount;
3353 error = cache_fullpath(p, &nch, retbuf, freebuf, guess);