2 * Copyright (c) 2003,2004 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
68 * @(#)vfs_cache.c 8.5 (Berkeley) 3/22/95
69 * $FreeBSD: src/sys/kern/vfs_cache.c,v 1.42.2.6 2001/10/05 20:07:03 dillon Exp $
70 * $DragonFly: src/sys/kern/vfs_cache.c,v 1.80 2006/12/23 00:35:04 swildner Exp $
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/kernel.h>
76 #include <sys/sysctl.h>
77 #include <sys/mount.h>
78 #include <sys/vnode.h>
79 #include <sys/malloc.h>
80 #include <sys/sysproto.h>
82 #include <sys/namei.h>
83 #include <sys/nlookup.h>
84 #include <sys/filedesc.h>
85 #include <sys/fnv_hash.h>
86 #include <sys/globaldata.h>
87 #include <sys/kern_syscall.h>
88 #include <sys/dirent.h>
91 #define MAX_RECURSION_DEPTH 64
94 * Random lookups in the cache are accomplished with a hash table using
95 * a hash key of (nc_src_vp, name).
97 * Negative entries may exist and correspond to structures where nc_vp
98 * is NULL. In a negative entry, NCF_WHITEOUT will be set if the entry
99 * corresponds to a whited-out directory entry (verses simply not finding the
102 * Upon reaching the last segment of a path, if the reference is for DELETE,
103 * or NOCACHE is set (rewrite), and the name is located in the cache, it
108 * Structures associated with name cacheing.
110 #define NCHHASH(hash) (&nchashtbl[(hash) & nchash])
113 MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
115 static LIST_HEAD(nchashhead, namecache) *nchashtbl; /* Hash Table */
116 static struct namecache_list ncneglist; /* instead of vnode */
119 * ncvp_debug - debug cache_fromvp(). This is used by the NFS server
120 * to create the namecache infrastructure leading to a dangling vnode.
122 * 0 Only errors are reported
123 * 1 Successes are reported
124 * 2 Successes + the whole directory scan is reported
125 * 3 Force the directory scan code run as if the parent vnode did not
126 * have a namecache record, even if it does have one.
128 static int ncvp_debug;
129 SYSCTL_INT(_debug, OID_AUTO, ncvp_debug, CTLFLAG_RW, &ncvp_debug, 0, "");
131 static u_long nchash; /* size of hash table */
132 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0, "");
134 static u_long ncnegfactor = 16; /* ratio of negative entries */
135 SYSCTL_ULONG(_debug, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0, "");
137 static int nclockwarn; /* warn on locked entries in ticks */
138 SYSCTL_INT(_debug, OID_AUTO, nclockwarn, CTLFLAG_RW, &nclockwarn, 0, "");
140 static u_long numneg; /* number of cache entries allocated */
141 SYSCTL_ULONG(_debug, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0, "");
143 static u_long numcache; /* number of cache entries allocated */
144 SYSCTL_ULONG(_debug, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0, "");
146 static u_long numunres; /* number of unresolved entries */
147 SYSCTL_ULONG(_debug, OID_AUTO, numunres, CTLFLAG_RD, &numunres, 0, "");
149 SYSCTL_INT(_debug, OID_AUTO, vnsize, CTLFLAG_RD, 0, sizeof(struct vnode), "");
150 SYSCTL_INT(_debug, OID_AUTO, ncsize, CTLFLAG_RD, 0, sizeof(struct namecache), "");
152 static int cache_resolve_mp(struct mount *mp);
153 static void _cache_rehash(struct namecache *ncp);
154 static void _cache_lock(struct namecache *ncp);
155 static void _cache_setunresolved(struct namecache *ncp);
158 * The new name cache statistics
160 SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0, "Name cache statistics");
161 #define STATNODE(mode, name, var) \
162 SYSCTL_ULONG(_vfs_cache, OID_AUTO, name, mode, var, 0, "");
163 STATNODE(CTLFLAG_RD, numneg, &numneg);
164 STATNODE(CTLFLAG_RD, numcache, &numcache);
165 static u_long numcalls; STATNODE(CTLFLAG_RD, numcalls, &numcalls);
166 static u_long dothits; STATNODE(CTLFLAG_RD, dothits, &dothits);
167 static u_long dotdothits; STATNODE(CTLFLAG_RD, dotdothits, &dotdothits);
168 static u_long numchecks; STATNODE(CTLFLAG_RD, numchecks, &numchecks);
169 static u_long nummiss; STATNODE(CTLFLAG_RD, nummiss, &nummiss);
170 static u_long nummisszap; STATNODE(CTLFLAG_RD, nummisszap, &nummisszap);
171 static u_long numposzaps; STATNODE(CTLFLAG_RD, numposzaps, &numposzaps);
172 static u_long numposhits; STATNODE(CTLFLAG_RD, numposhits, &numposhits);
173 static u_long numnegzaps; STATNODE(CTLFLAG_RD, numnegzaps, &numnegzaps);
174 static u_long numneghits; STATNODE(CTLFLAG_RD, numneghits, &numneghits);
176 struct nchstats nchstats[SMP_MAXCPU];
178 * Export VFS cache effectiveness statistics to user-land.
180 * The statistics are left for aggregation to user-land so
181 * neat things can be achieved, like observing per-CPU cache
185 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
187 struct globaldata *gd;
191 for (i = 0; i < ncpus; ++i) {
192 gd = globaldata_find(i);
193 if ((error = SYSCTL_OUT(req, (void *)&(*gd->gd_nchstats),
194 sizeof(struct nchstats))))
200 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE|CTLFLAG_RD,
201 0, 0, sysctl_nchstats, "S,nchstats", "VFS cache effectiveness statistics");
203 static void cache_zap(struct namecache *ncp);
206 * cache_hold() and cache_drop() prevent the premature deletion of a
207 * namecache entry but do not prevent operations (such as zapping) on
208 * that namecache entry.
210 * This routine may only be called from outside this source module if
211 * nc_refs is already at least 1.
213 * This is a rare case where callers are allowed to hold a spinlock,
214 * so we can't ourselves.
218 _cache_hold(struct namecache *ncp)
220 atomic_add_int(&ncp->nc_refs, 1);
225 * When dropping an entry, if only one ref remains and the entry has not
226 * been resolved, zap it. Since the one reference is being dropped the
227 * entry had better not be locked.
231 _cache_drop(struct namecache *ncp)
233 KKASSERT(ncp->nc_refs > 0);
234 if (ncp->nc_refs == 1 &&
235 (ncp->nc_flag & NCF_UNRESOLVED) &&
236 TAILQ_EMPTY(&ncp->nc_list)
238 KKASSERT(ncp->nc_exlocks == 0);
242 atomic_subtract_int(&ncp->nc_refs, 1);
247 * Link a new namecache entry to its parent. Be careful to avoid races
248 * if vhold() blocks in the future.
251 cache_link_parent(struct namecache *ncp, struct namecache *par)
253 KKASSERT(ncp->nc_parent == NULL);
254 ncp->nc_parent = par;
255 if (TAILQ_EMPTY(&par->nc_list)) {
256 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
258 * Any vp associated with an ncp which has children must
259 * be held to prevent it from being recycled.
264 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
269 * Remove the parent association from a namecache structure. If this is
270 * the last child of the parent the cache_drop(par) will attempt to
271 * recursively zap the parent.
274 cache_unlink_parent(struct namecache *ncp)
276 struct namecache *par;
278 if ((par = ncp->nc_parent) != NULL) {
279 ncp->nc_parent = NULL;
280 par = _cache_hold(par);
281 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
282 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
289 * Allocate a new namecache structure. Most of the code does not require
290 * zero-termination of the string but it makes vop_compat_ncreate() easier.
292 static struct namecache *
293 cache_alloc(int nlen)
295 struct namecache *ncp;
297 ncp = kmalloc(sizeof(*ncp), M_VFSCACHE, M_WAITOK|M_ZERO);
299 ncp->nc_name = kmalloc(nlen + 1, M_VFSCACHE, M_WAITOK);
301 ncp->nc_flag = NCF_UNRESOLVED;
302 ncp->nc_error = ENOTCONN; /* needs to be resolved */
306 * Construct a fake FSMID based on the time of day and a 32 bit
307 * roller for uniqueness. This is used to generate a useful
308 * FSMID for filesystems which do not support it.
310 ncp->nc_fsmid = cache_getnewfsmid();
311 TAILQ_INIT(&ncp->nc_list);
317 _cache_free(struct namecache *ncp)
319 KKASSERT(ncp->nc_refs == 1 && ncp->nc_exlocks == 1);
321 kfree(ncp->nc_name, M_VFSCACHE);
322 kfree(ncp, M_VFSCACHE);
326 cache_zero(struct nchandle *nch)
333 * Ref and deref a namecache structure.
335 * Warning: caller may hold an unrelated read spinlock, which means we can't
336 * use read spinlocks here.
339 cache_hold(struct nchandle *nch)
341 _cache_hold(nch->ncp);
342 ++nch->mount->mnt_refs;
347 cache_copy(struct nchandle *nch, struct nchandle *target)
350 _cache_hold(target->ncp);
351 ++nch->mount->mnt_refs;
355 cache_changemount(struct nchandle *nch, struct mount *mp)
357 --nch->mount->mnt_refs;
359 ++nch->mount->mnt_refs;
363 cache_drop(struct nchandle *nch)
365 --nch->mount->mnt_refs;
366 _cache_drop(nch->ncp);
372 * Namespace locking. The caller must already hold a reference to the
373 * namecache structure in order to lock/unlock it. This function prevents
374 * the namespace from being created or destroyed by accessors other then
377 * Note that holding a locked namecache structure prevents other threads
378 * from making namespace changes (e.g. deleting or creating), prevents
379 * vnode association state changes by other threads, and prevents the
380 * namecache entry from being resolved or unresolved by other threads.
382 * The lock owner has full authority to associate/disassociate vnodes
383 * and resolve/unresolve the locked ncp.
385 * WARNING! Holding a locked ncp will prevent a vnode from being destroyed
386 * or recycled, but it does NOT help you if the vnode had already initiated
387 * a recyclement. If this is important, use cache_get() rather then
388 * cache_lock() (and deal with the differences in the way the refs counter
389 * is handled). Or, alternatively, make an unconditional call to
390 * cache_validate() or cache_resolve() after cache_lock() returns.
394 _cache_lock(struct namecache *ncp)
399 KKASSERT(ncp->nc_refs != 0);
404 if (ncp->nc_exlocks == 0) {
408 * The vp associated with a locked ncp must be held
409 * to prevent it from being recycled (which would
410 * cause the ncp to become unresolved).
412 * WARNING! If VRECLAIMED is set the vnode could
413 * already be in the middle of a recycle. Callers
414 * should not assume that nc_vp is usable when
415 * not NULL. cache_vref() or cache_vget() must be
418 * XXX loop on race for later MPSAFE work.
424 if (ncp->nc_locktd == td) {
428 ncp->nc_flag |= NCF_LOCKREQ;
429 if (tsleep(ncp, 0, "clock", nclockwarn) == EWOULDBLOCK) {
433 kprintf("[diagnostic] cache_lock: blocked on %p", ncp);
434 kprintf(" \"%*.*s\"\n",
435 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
440 kprintf("[diagnostic] cache_lock: unblocked %*.*s\n",
441 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
446 cache_lock(struct nchandle *nch)
448 _cache_lock(nch->ncp);
453 _cache_lock_nonblock(struct namecache *ncp)
457 KKASSERT(ncp->nc_refs != 0);
459 if (ncp->nc_exlocks == 0) {
463 * The vp associated with a locked ncp must be held
464 * to prevent it from being recycled (which would
465 * cause the ncp to become unresolved).
467 * WARNING! If VRECLAIMED is set the vnode could
468 * already be in the middle of a recycle. Callers
469 * should not assume that nc_vp is usable when
470 * not NULL. cache_vref() or cache_vget() must be
473 * XXX loop on race for later MPSAFE work.
484 cache_lock_nonblock(struct nchandle *nch)
486 return(_cache_lock_nonblock(nch->ncp));
491 _cache_unlock(struct namecache *ncp)
493 thread_t td = curthread;
495 KKASSERT(ncp->nc_refs > 0);
496 KKASSERT(ncp->nc_exlocks > 0);
497 KKASSERT(ncp->nc_locktd == td);
498 if (--ncp->nc_exlocks == 0) {
501 ncp->nc_locktd = NULL;
502 if (ncp->nc_flag & NCF_LOCKREQ) {
503 ncp->nc_flag &= ~NCF_LOCKREQ;
510 cache_unlock(struct nchandle *nch)
512 _cache_unlock(nch->ncp);
516 * ref-and-lock, unlock-and-deref functions.
518 * This function is primarily used by nlookup. Even though cache_lock
519 * holds the vnode, it is possible that the vnode may have already
520 * initiated a recyclement. We want cache_get() to return a definitively
521 * usable vnode or a definitively unresolved ncp.
525 _cache_get(struct namecache *ncp)
529 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
530 _cache_setunresolved(ncp);
535 * note: the same nchandle can be passed for both arguments.
538 cache_get(struct nchandle *nch, struct nchandle *target)
540 target->mount = nch->mount;
541 target->ncp = _cache_get(nch->ncp);
542 ++target->mount->mnt_refs;
546 _cache_get_nonblock(struct namecache *ncp)
549 if (ncp->nc_exlocks == 0 || ncp->nc_locktd == curthread) {
552 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
553 _cache_setunresolved(ncp);
560 cache_get_nonblock(struct nchandle *nch)
562 return(_cache_get_nonblock(nch->ncp));
567 _cache_put(struct namecache *ncp)
574 cache_put(struct nchandle *nch)
576 --nch->mount->mnt_refs;
577 _cache_put(nch->ncp);
583 * Resolve an unresolved ncp by associating a vnode with it. If the
584 * vnode is NULL, a negative cache entry is created.
586 * The ncp should be locked on entry and will remain locked on return.
590 _cache_setvp(struct namecache *ncp, struct vnode *vp)
592 KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
596 * Any vp associated with an ncp which has children must
597 * be held. Any vp associated with a locked ncp must be held.
599 if (!TAILQ_EMPTY(&ncp->nc_list))
601 TAILQ_INSERT_HEAD(&vp->v_namecache, ncp, nc_vnode);
606 * Set auxillary flags
610 ncp->nc_flag |= NCF_ISDIR;
613 ncp->nc_flag |= NCF_ISSYMLINK;
614 /* XXX cache the contents of the symlink */
622 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
624 ncp->nc_error = ENOENT;
626 ncp->nc_flag &= ~NCF_UNRESOLVED;
630 cache_setvp(struct nchandle *nch, struct vnode *vp)
632 _cache_setvp(nch->ncp, vp);
636 cache_settimeout(struct nchandle *nch, int nticks)
638 struct namecache *ncp = nch->ncp;
640 if ((ncp->nc_timeout = ticks + nticks) == 0)
645 * Disassociate the vnode or negative-cache association and mark a
646 * namecache entry as unresolved again. Note that the ncp is still
647 * left in the hash table and still linked to its parent.
649 * The ncp should be locked and refd on entry and will remain locked and refd
652 * This routine is normally never called on a directory containing children.
653 * However, NFS often does just that in its rename() code as a cop-out to
654 * avoid complex namespace operations. This disconnects a directory vnode
655 * from its namecache and can cause the OLDAPI and NEWAPI to get out of
658 * NOTE: NCF_FSMID must be cleared so a refurbishment of the ncp, such as
659 * in a create, properly propogates flag up the chain.
663 _cache_setunresolved(struct namecache *ncp)
667 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
668 ncp->nc_flag |= NCF_UNRESOLVED;
670 ncp->nc_error = ENOTCONN;
672 if ((vp = ncp->nc_vp) != NULL) {
675 TAILQ_REMOVE(&vp->v_namecache, ncp, nc_vnode);
678 * Any vp associated with an ncp with children is
679 * held by that ncp. Any vp associated with a locked
680 * ncp is held by that ncp. These conditions must be
681 * undone when the vp is cleared out from the ncp.
683 if (ncp->nc_flag & NCF_FSMID)
685 if (!TAILQ_EMPTY(&ncp->nc_list))
690 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
693 ncp->nc_flag &= ~(NCF_WHITEOUT|NCF_ISDIR|NCF_ISSYMLINK|
699 cache_setunresolved(struct nchandle *nch)
701 _cache_setunresolved(nch->ncp);
705 * Determine if we can clear NCF_ISMOUNTPT by scanning the mountlist
706 * looking for matches. This flag tells the lookup code when it must
707 * check for a mount linkage and also prevents the directories in question
708 * from being deleted or renamed.
712 cache_clrmountpt_callback(struct mount *mp, void *data)
714 struct nchandle *nch = data;
716 if (mp->mnt_ncmounton.ncp == nch->ncp)
718 if (mp->mnt_ncmountpt.ncp == nch->ncp)
724 cache_clrmountpt(struct nchandle *nch)
728 count = mountlist_scan(cache_clrmountpt_callback, nch,
729 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
731 nch->ncp->nc_flag &= ~NCF_ISMOUNTPT;
735 * Invalidate portions of the namecache topology given a starting entry.
736 * The passed ncp is set to an unresolved state and:
738 * The passed ncp must be locked.
740 * CINV_DESTROY - Set a flag in the passed ncp entry indicating
741 * that the physical underlying nodes have been
742 * destroyed... as in deleted. For example, when
743 * a directory is removed. This will cause record
744 * lookups on the name to no longer be able to find
745 * the record and tells the resolver to return failure
746 * rather then trying to resolve through the parent.
748 * The topology itself, including ncp->nc_name,
751 * This only applies to the passed ncp, if CINV_CHILDREN
752 * is specified the children are not flagged.
754 * CINV_CHILDREN - Set all children (recursively) to an unresolved
757 * Note that this will also have the side effect of
758 * cleaning out any unreferenced nodes in the topology
759 * from the leaves up as the recursion backs out.
761 * Note that the topology for any referenced nodes remains intact.
763 * It is possible for cache_inval() to race a cache_resolve(), meaning that
764 * the namecache entry may not actually be invalidated on return if it was
765 * revalidated while recursing down into its children. This code guarentees
766 * that the node(s) will go through an invalidation cycle, but does not
767 * guarentee that they will remain in an invalidated state.
769 * Returns non-zero if a revalidation was detected during the invalidation
770 * recursion, zero otherwise. Note that since only the original ncp is
771 * locked the revalidation ultimately can only indicate that the original ncp
772 * *MIGHT* no have been reresolved.
774 * DEEP RECURSION HANDLING - If a recursive invalidation recurses deeply we
775 * have to avoid blowing out the kernel stack. We do this by saving the
776 * deep namecache node and aborting the recursion, then re-recursing at that
777 * node using a depth-first algorithm in order to allow multiple deep
778 * recursions to chain through each other, then we restart the invalidation
783 struct namecache *resume_ncp;
787 static int _cache_inval_internal(struct namecache *, int, struct cinvtrack *);
791 _cache_inval(struct namecache *ncp, int flags)
793 struct cinvtrack track;
794 struct namecache *ncp2;
798 track.resume_ncp = NULL;
801 r = _cache_inval_internal(ncp, flags, &track);
802 if (track.resume_ncp == NULL)
804 kprintf("Warning: deep namecache recursion at %s\n",
807 while ((ncp2 = track.resume_ncp) != NULL) {
808 track.resume_ncp = NULL;
810 _cache_inval_internal(ncp2, flags & ~CINV_DESTROY,
820 cache_inval(struct nchandle *nch, int flags)
822 return(_cache_inval(nch->ncp, flags));
826 _cache_inval_internal(struct namecache *ncp, int flags, struct cinvtrack *track)
828 struct namecache *kid;
829 struct namecache *nextkid;
832 KKASSERT(ncp->nc_exlocks);
834 _cache_setunresolved(ncp);
835 if (flags & CINV_DESTROY)
836 ncp->nc_flag |= NCF_DESTROYED;
838 if ((flags & CINV_CHILDREN) &&
839 (kid = TAILQ_FIRST(&ncp->nc_list)) != NULL
841 if (++track->depth > MAX_RECURSION_DEPTH) {
842 track->resume_ncp = ncp;
849 if (track->resume_ncp) {
853 if ((nextkid = TAILQ_NEXT(kid, nc_entry)) != NULL)
854 _cache_hold(nextkid);
855 if ((kid->nc_flag & NCF_UNRESOLVED) == 0 ||
856 TAILQ_FIRST(&kid->nc_list)
859 rcnt += _cache_inval_internal(kid, flags & ~CINV_DESTROY, track);
870 * Someone could have gotten in there while ncp was unlocked,
873 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
879 * Invalidate a vnode's namecache associations. To avoid races against
880 * the resolver we do not invalidate a node which we previously invalidated
881 * but which was then re-resolved while we were in the invalidation loop.
883 * Returns non-zero if any namecache entries remain after the invalidation
886 * NOTE: unlike the namecache topology which guarentees that ncp's will not
887 * be ripped out of the topology while held, the vnode's v_namecache list
888 * has no such restriction. NCP's can be ripped out of the list at virtually
889 * any time if not locked, even if held.
892 cache_inval_vp(struct vnode *vp, int flags)
894 struct namecache *ncp;
895 struct namecache *next;
898 ncp = TAILQ_FIRST(&vp->v_namecache);
902 /* loop entered with ncp held */
903 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
906 if (ncp->nc_vp != vp) {
907 kprintf("Warning: cache_inval_vp: race-A detected on "
908 "%s\n", ncp->nc_name);
914 _cache_inval(ncp, flags);
915 _cache_put(ncp); /* also releases reference */
917 if (ncp && ncp->nc_vp != vp) {
918 kprintf("Warning: cache_inval_vp: race-B detected on "
919 "%s\n", ncp->nc_name);
924 return(TAILQ_FIRST(&vp->v_namecache) != NULL);
928 * The source ncp has been renamed to the target ncp. Both fncp and tncp
929 * must be locked. Both will be set to unresolved, any children of tncp
930 * will be disconnected (the prior contents of the target is assumed to be
931 * destroyed by the rename operation, e.g. renaming over an empty directory),
932 * and all children of fncp will be moved to tncp.
934 * XXX the disconnection could pose a problem, check code paths to make
935 * sure any code that blocks can handle the parent being changed out from
936 * under it. Maybe we should lock the children (watch out for deadlocks) ?
938 * After we return the caller has the option of calling cache_setvp() if
939 * the vnode of the new target ncp is known.
941 * Any process CD'd into any of the children will no longer be able to ".."
942 * back out. An rm -rf can cause this situation to occur.
945 cache_rename(struct nchandle *fnch, struct nchandle *tnch)
947 struct namecache *fncp = fnch->ncp;
948 struct namecache *tncp = tnch->ncp;
949 struct namecache *scan;
952 _cache_setunresolved(fncp);
953 _cache_setunresolved(tncp);
954 while (_cache_inval(tncp, CINV_CHILDREN) != 0) {
955 if (didwarn++ % 10 == 0) {
956 kprintf("Warning: cache_rename: race during "
958 fncp->nc_name, tncp->nc_name);
960 tsleep(tncp, 0, "mvrace", hz / 10);
961 _cache_setunresolved(tncp);
963 while ((scan = TAILQ_FIRST(&fncp->nc_list)) != NULL) {
965 cache_unlink_parent(scan);
966 cache_link_parent(scan, tncp);
967 if (scan->nc_flag & NCF_HASHED)
974 * vget the vnode associated with the namecache entry. Resolve the namecache
975 * entry if necessary and deal with namecache/vp races. The passed ncp must
976 * be referenced and may be locked. The ncp's ref/locking state is not
977 * effected by this call.
979 * lk_type may be LK_SHARED, LK_EXCLUSIVE. A ref'd, possibly locked
980 * (depending on the passed lk_type) will be returned in *vpp with an error
981 * of 0, or NULL will be returned in *vpp with a non-0 error code. The
982 * most typical error is ENOENT, meaning that the ncp represents a negative
983 * cache hit and there is no vnode to retrieve, but other errors can occur
986 * The main race we have to deal with are namecache zaps. The ncp itself
987 * will not disappear since it is referenced, and it turns out that the
988 * validity of the vp pointer can be checked simply by rechecking the
989 * contents of ncp->nc_vp.
992 cache_vget(struct nchandle *nch, struct ucred *cred,
993 int lk_type, struct vnode **vpp)
995 struct namecache *ncp;
1002 if (ncp->nc_flag & NCF_UNRESOLVED) {
1004 error = cache_resolve(nch, cred);
1009 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1011 * Accessing the vnode from the namecache is a bit
1012 * dangerous. Because there are no refs on the vnode, it
1013 * could be in the middle of a reclaim.
1015 if (vp->v_flag & VRECLAIMED) {
1016 kprintf("Warning: vnode reclaim race detected in cache_vget on %p (%s)\n", vp, ncp->nc_name);
1018 _cache_setunresolved(ncp);
1022 error = vget(vp, lk_type);
1024 if (vp != ncp->nc_vp)
1027 } else if (vp != ncp->nc_vp) {
1030 } else if (vp->v_flag & VRECLAIMED) {
1031 panic("vget succeeded on a VRECLAIMED node! vp %p", vp);
1034 if (error == 0 && vp == NULL)
1041 cache_vref(struct nchandle *nch, struct ucred *cred, struct vnode **vpp)
1043 struct namecache *ncp;
1051 if (ncp->nc_flag & NCF_UNRESOLVED) {
1053 error = cache_resolve(nch, cred);
1058 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1060 * Since we did not obtain any locks, a cache zap
1061 * race can occur here if the vnode is in the middle
1062 * of being reclaimed and has not yet been able to
1063 * clean out its cache node. If that case occurs,
1064 * we must lock and unresolve the cache, then loop
1067 if (vp->v_flag & VRECLAIMED) {
1068 kprintf("Warning: vnode reclaim race detected on cache_vref %p (%s)\n", vp, ncp->nc_name);
1070 _cache_setunresolved(ncp);
1074 vref_initial(vp, 1);
1076 if (error == 0 && vp == NULL)
1083 * Recursively set the FSMID update flag for namecache nodes leading
1084 * to root. This will cause the next getattr or reclaim to increment the
1085 * fsmid and mark the inode for lazy updating.
1087 * Stop recursing when we hit a node whos NCF_FSMID flag is already set.
1088 * This makes FSMIDs work in an Einsteinian fashion - where the observation
1089 * effects the result. In this case a program monitoring a higher level
1090 * node will have detected some prior change and started its scan (clearing
1091 * NCF_FSMID in higher level nodes), but since it has not yet observed the
1092 * node where we find NCF_FSMID still set, we can safely make the related
1093 * modification without interfering with the theorized program.
1095 * This also means that FSMIDs cannot represent time-domain quantities
1096 * in a hierarchical sense. But the main reason for doing it this way
1097 * is to reduce the amount of recursion that occurs in the critical path
1098 * when e.g. a program is writing to a file that sits deep in a directory
1102 cache_update_fsmid(struct nchandle *nch)
1104 struct namecache *ncp;
1105 struct namecache *scan;
1111 * Warning: even if we get a non-NULL vp it could still be in the
1112 * middle of a recyclement. Don't do anything fancy, just set
1115 if ((vp = ncp->nc_vp) != NULL) {
1116 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1117 for (scan = ncp; scan; scan = scan->nc_parent) {
1118 if (scan->nc_flag & NCF_FSMID)
1120 scan->nc_flag |= NCF_FSMID;
1124 while (ncp && (ncp->nc_flag & NCF_FSMID) == 0) {
1125 ncp->nc_flag |= NCF_FSMID;
1126 ncp = ncp->nc_parent;
1132 cache_update_fsmid_vp(struct vnode *vp)
1134 struct namecache *ncp;
1135 struct namecache *scan;
1137 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1138 for (scan = ncp; scan; scan = scan->nc_parent) {
1139 if (scan->nc_flag & NCF_FSMID)
1141 scan->nc_flag |= NCF_FSMID;
1147 * If getattr is called on a vnode (e.g. a stat call), the filesystem
1148 * may call this routine to determine if the namecache has the hierarchical
1149 * change flag set, requiring the fsmid to be updated.
1151 * Since 0 indicates no support, make sure the filesystem fsmid is at least
1155 cache_check_fsmid_vp(struct vnode *vp, int64_t *fsmid)
1157 struct namecache *ncp;
1160 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1161 if (ncp->nc_flag & NCF_FSMID) {
1162 ncp->nc_flag &= ~NCF_FSMID;
1174 * Obtain the FSMID for a vnode for filesystems which do not support
1178 cache_sync_fsmid_vp(struct vnode *vp)
1180 struct namecache *ncp;
1182 if ((ncp = TAILQ_FIRST(&vp->v_namecache)) != NULL) {
1183 if (ncp->nc_flag & NCF_FSMID) {
1184 ncp->nc_flag &= ~NCF_FSMID;
1187 return(ncp->nc_fsmid);
1193 * Convert a directory vnode to a namecache record without any other
1194 * knowledge of the topology. This ONLY works with directory vnodes and
1195 * is ONLY used by the NFS server. dvp must be refd but unlocked, and the
1196 * returned ncp (if not NULL) will be held and unlocked.
1198 * If 'makeit' is 0 and dvp has no existing namecache record, NULL is returned.
1199 * If 'makeit' is 1 we attempt to track-down and create the namecache topology
1200 * for dvp. This will fail only if the directory has been deleted out from
1203 * Callers must always check for a NULL return no matter the value of 'makeit'.
1205 * To avoid underflowing the kernel stack each recursive call increments
1206 * the makeit variable.
1209 static int cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1211 static int cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1212 struct vnode **saved_dvp);
1215 cache_fromdvp(struct vnode *dvp, struct ucred *cred, int makeit,
1216 struct nchandle *nch)
1218 struct vnode *saved_dvp;
1223 nch->mount = dvp->v_mount;
1227 * Temporary debugging code to force the directory scanning code
1230 if (ncvp_debug >= 3 && makeit && TAILQ_FIRST(&dvp->v_namecache)) {
1231 nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
1232 kprintf("cache_fromdvp: forcing %s\n", nch->ncp->nc_name);
1237 * Loop until resolution, inside code will break out on error.
1239 while ((nch->ncp = TAILQ_FIRST(&dvp->v_namecache)) == NULL && makeit) {
1242 * If dvp is the root of its filesystem it should already
1243 * have a namecache pointer associated with it as a side
1244 * effect of the mount, but it may have been disassociated.
1246 if (dvp->v_flag & VROOT) {
1247 nch->ncp = _cache_get(nch->mount->mnt_ncmountpt.ncp);
1248 error = cache_resolve_mp(nch->mount);
1249 _cache_put(nch->ncp);
1251 kprintf("cache_fromdvp: resolve root of mount %p error %d",
1252 dvp->v_mount, error);
1256 kprintf(" failed\n");
1261 kprintf(" succeeded\n");
1266 * If we are recursed too deeply resort to an O(n^2)
1267 * algorithm to resolve the namecache topology. The
1268 * resolved pvp is left referenced in saved_dvp to
1269 * prevent the tree from being destroyed while we loop.
1272 error = cache_fromdvp_try(dvp, cred, &saved_dvp);
1274 kprintf("lookupdotdot(longpath) failed %d "
1275 "dvp %p\n", error, dvp);
1282 * Get the parent directory and resolve its ncp.
1284 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred);
1286 kprintf("lookupdotdot failed %d dvp %p\n", error, dvp);
1292 * Reuse makeit as a recursion depth counter.
1294 cache_fromdvp(pvp, cred, makeit + 1, nch);
1296 if (nch->ncp == NULL)
1300 * Do an inefficient scan of pvp (embodied by ncp) to look
1301 * for dvp. This will create a namecache record for dvp on
1302 * success. We loop up to recheck on success.
1304 * ncp and dvp are both held but not locked.
1306 error = cache_inefficient_scan(nch, cred, dvp);
1307 _cache_drop(nch->ncp);
1309 kprintf("cache_fromdvp: scan %p (%s) failed on dvp=%p\n",
1310 pvp, nch->ncp->nc_name, dvp);
1315 kprintf("cache_fromdvp: scan %p (%s) succeeded\n",
1316 pvp, nch->ncp->nc_name);
1321 * hold it for real so the mount gets a ref
1333 * Go up the chain of parent directories until we find something
1334 * we can resolve into the namecache. This is very inefficient.
1338 cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1339 struct vnode **saved_dvp)
1341 struct nchandle nch;
1344 static time_t last_fromdvp_report;
1347 * Loop getting the parent directory vnode until we get something we
1348 * can resolve in the namecache.
1351 nch.mount = dvp->v_mount;
1354 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred);
1360 if ((nch.ncp = TAILQ_FIRST(&pvp->v_namecache)) != NULL) {
1361 _cache_hold(nch.ncp);
1365 if (pvp->v_flag & VROOT) {
1366 nch.ncp = _cache_get(pvp->v_mount->mnt_ncmountpt.ncp);
1367 error = cache_resolve_mp(nch.mount);
1368 _cache_unlock(nch.ncp);
1371 _cache_drop(nch.ncp);
1380 if (last_fromdvp_report != time_second) {
1381 last_fromdvp_report = time_second;
1382 kprintf("Warning: extremely inefficient path resolution on %s\n",
1385 error = cache_inefficient_scan(&nch, cred, dvp);
1388 * Hopefully dvp now has a namecache record associated with it.
1389 * Leave it referenced to prevent the kernel from recycling the
1390 * vnode. Otherwise extremely long directory paths could result
1391 * in endless recycling.
1401 * Do an inefficient scan of the directory represented by ncp looking for
1402 * the directory vnode dvp. ncp must be held but not locked on entry and
1403 * will be held on return. dvp must be refd but not locked on entry and
1404 * will remain refd on return.
1406 * Why do this at all? Well, due to its stateless nature the NFS server
1407 * converts file handles directly to vnodes without necessarily going through
1408 * the namecache ops that would otherwise create the namecache topology
1409 * leading to the vnode. We could either (1) Change the namecache algorithms
1410 * to allow disconnect namecache records that are re-merged opportunistically,
1411 * or (2) Make the NFS server backtrack and scan to recover a connected
1412 * namecache topology in order to then be able to issue new API lookups.
1414 * It turns out that (1) is a huge mess. It takes a nice clean set of
1415 * namecache algorithms and introduces a lot of complication in every subsystem
1416 * that calls into the namecache to deal with the re-merge case, especially
1417 * since we are using the namecache to placehold negative lookups and the
1418 * vnode might not be immediately assigned. (2) is certainly far less
1419 * efficient then (1), but since we are only talking about directories here
1420 * (which are likely to remain cached), the case does not actually run all
1421 * that often and has the supreme advantage of not polluting the namecache
1425 cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1428 struct nlcomponent nlc;
1429 struct nchandle rncp;
1441 vat.va_blocksize = 0;
1442 if ((error = VOP_GETATTR(dvp, &vat)) != 0)
1444 if ((error = cache_vref(nch, cred, &pvp)) != 0)
1447 kprintf("inefficient_scan: directory iosize %ld vattr fileid = %ld\n", vat.va_blocksize, (long)vat.va_fileid);
1448 if ((blksize = vat.va_blocksize) == 0)
1449 blksize = DEV_BSIZE;
1450 rbuf = kmalloc(blksize, M_TEMP, M_WAITOK);
1456 iov.iov_base = rbuf;
1457 iov.iov_len = blksize;
1460 uio.uio_resid = blksize;
1461 uio.uio_segflg = UIO_SYSSPACE;
1462 uio.uio_rw = UIO_READ;
1463 uio.uio_td = curthread;
1465 if (ncvp_debug >= 2)
1466 kprintf("cache_inefficient_scan: readdir @ %08x\n", (int)uio.uio_offset);
1467 error = VOP_READDIR(pvp, &uio, cred, &eofflag, NULL, NULL);
1469 den = (struct dirent *)rbuf;
1470 bytes = blksize - uio.uio_resid;
1473 if (ncvp_debug >= 2) {
1474 kprintf("cache_inefficient_scan: %*.*s\n",
1475 den->d_namlen, den->d_namlen,
1478 if (den->d_type != DT_WHT &&
1479 den->d_ino == vat.va_fileid) {
1481 kprintf("cache_inefficient_scan: "
1482 "MATCHED inode %ld path %s/%*.*s\n",
1483 vat.va_fileid, nch->ncp->nc_name,
1484 den->d_namlen, den->d_namlen,
1487 nlc.nlc_nameptr = den->d_name;
1488 nlc.nlc_namelen = den->d_namlen;
1489 rncp = cache_nlookup(nch, &nlc);
1490 KKASSERT(rncp.ncp != NULL);
1493 bytes -= _DIRENT_DIRSIZ(den);
1494 den = _DIRENT_NEXT(den);
1496 if (rncp.ncp == NULL && eofflag == 0 && uio.uio_resid != blksize)
1501 if (rncp.ncp->nc_flag & NCF_UNRESOLVED) {
1502 _cache_setvp(rncp.ncp, dvp);
1503 if (ncvp_debug >= 2) {
1504 kprintf("cache_inefficient_scan: setvp %s/%s = %p\n",
1505 nch->ncp->nc_name, rncp.ncp->nc_name, dvp);
1508 if (ncvp_debug >= 2) {
1509 kprintf("cache_inefficient_scan: setvp %s/%s already set %p/%p\n",
1510 nch->ncp->nc_name, rncp.ncp->nc_name, dvp,
1514 if (rncp.ncp->nc_vp == NULL)
1515 error = rncp.ncp->nc_error;
1516 _cache_put(rncp.ncp);
1518 kprintf("cache_inefficient_scan: dvp %p NOT FOUND in %s\n",
1519 dvp, nch->ncp->nc_name);
1522 kfree(rbuf, M_TEMP);
1527 * Zap a namecache entry. The ncp is unconditionally set to an unresolved
1528 * state, which disassociates it from its vnode or ncneglist.
1530 * Then, if there are no additional references to the ncp and no children,
1531 * the ncp is removed from the topology and destroyed. This function will
1532 * also run through the nc_parent chain and destroy parent ncps if possible.
1533 * As a side benefit, it turns out the only conditions that allow running
1534 * up the chain are also the conditions to ensure no deadlock will occur.
1536 * References and/or children may exist if the ncp is in the middle of the
1537 * topology, preventing the ncp from being destroyed.
1539 * This function must be called with the ncp held and locked and will unlock
1540 * and drop it during zapping.
1543 cache_zap(struct namecache *ncp)
1545 struct namecache *par;
1548 * Disassociate the vnode or negative cache ref and set NCF_UNRESOLVED.
1550 _cache_setunresolved(ncp);
1553 * Try to scrap the entry and possibly tail-recurse on its parent.
1554 * We only scrap unref'd (other then our ref) unresolved entries,
1555 * we do not scrap 'live' entries.
1557 while (ncp->nc_flag & NCF_UNRESOLVED) {
1559 * Someone other then us has a ref, stop.
1561 if (ncp->nc_refs > 1)
1565 * We have children, stop.
1567 if (!TAILQ_EMPTY(&ncp->nc_list))
1571 * Remove ncp from the topology: hash table and parent linkage.
1573 if (ncp->nc_flag & NCF_HASHED) {
1574 ncp->nc_flag &= ~NCF_HASHED;
1575 LIST_REMOVE(ncp, nc_hash);
1577 if ((par = ncp->nc_parent) != NULL) {
1578 par = _cache_hold(par);
1579 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
1580 ncp->nc_parent = NULL;
1581 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
1586 * ncp should not have picked up any refs. Physically
1589 KKASSERT(ncp->nc_refs == 1);
1591 /* _cache_unlock(ncp) not required */
1592 ncp->nc_refs = -1; /* safety */
1594 kfree(ncp->nc_name, M_VFSCACHE);
1595 kfree(ncp, M_VFSCACHE);
1598 * Loop on the parent (it may be NULL). Only bother looping
1599 * if the parent has a single ref (ours), which also means
1600 * we can lock it trivially.
1605 if (ncp->nc_refs != 1) {
1609 KKASSERT(par->nc_exlocks == 0);
1614 atomic_subtract_int(&ncp->nc_refs, 1);
1617 static enum { CHI_LOW, CHI_HIGH } cache_hysteresis_state = CHI_LOW;
1621 cache_hysteresis(void)
1624 * Don't cache too many negative hits. We use hysteresis to reduce
1625 * the impact on the critical path.
1627 switch(cache_hysteresis_state) {
1629 if (numneg > MINNEG && numneg * ncnegfactor > numcache) {
1631 cache_hysteresis_state = CHI_HIGH;
1635 if (numneg > MINNEG * 9 / 10 &&
1636 numneg * ncnegfactor * 9 / 10 > numcache
1640 cache_hysteresis_state = CHI_LOW;
1647 * NEW NAMECACHE LOOKUP API
1649 * Lookup an entry in the cache. A locked, referenced, non-NULL
1650 * entry is *always* returned, even if the supplied component is illegal.
1651 * The resulting namecache entry should be returned to the system with
1652 * cache_put() or _cache_unlock() + cache_drop().
1654 * namecache locks are recursive but care must be taken to avoid lock order
1657 * Nobody else will be able to manipulate the associated namespace (e.g.
1658 * create, delete, rename, rename-target) until the caller unlocks the
1661 * The returned entry will be in one of three states: positive hit (non-null
1662 * vnode), negative hit (null vnode), or unresolved (NCF_UNRESOLVED is set).
1663 * Unresolved entries must be resolved through the filesystem to associate the
1664 * vnode and/or determine whether a positive or negative hit has occured.
1666 * It is not necessary to lock a directory in order to lock namespace under
1667 * that directory. In fact, it is explicitly not allowed to do that. A
1668 * directory is typically only locked when being created, renamed, or
1671 * The directory (par) may be unresolved, in which case any returned child
1672 * will likely also be marked unresolved. Likely but not guarenteed. Since
1673 * the filesystem lookup requires a resolved directory vnode the caller is
1674 * responsible for resolving the namecache chain top-down. This API
1675 * specifically allows whole chains to be created in an unresolved state.
1678 cache_nlookup(struct nchandle *par_nch, struct nlcomponent *nlc)
1680 struct nchandle nch;
1681 struct namecache *ncp;
1682 struct namecache *new_ncp;
1683 struct nchashhead *nchpp;
1691 * Try to locate an existing entry
1693 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
1694 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
1697 LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1701 * Zap entries that have timed out.
1703 if (ncp->nc_timeout &&
1704 (int)(ncp->nc_timeout - ticks) < 0 &&
1705 (ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
1706 ncp->nc_exlocks == 0
1708 cache_zap(_cache_get(ncp));
1713 * Break out if we find a matching entry. Note that
1714 * UNRESOLVED entries may match, but DESTROYED entries
1717 if (ncp->nc_parent == par_nch->ncp &&
1718 ncp->nc_nlen == nlc->nlc_namelen &&
1719 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
1720 (ncp->nc_flag & NCF_DESTROYED) == 0
1722 if (_cache_get_nonblock(ncp) == 0) {
1724 _cache_free(new_ncp);
1734 * We failed to locate an entry, create a new entry and add it to
1735 * the cache. We have to relookup after possibly blocking in
1738 if (new_ncp == NULL) {
1739 new_ncp = cache_alloc(nlc->nlc_namelen);
1746 * Initialize as a new UNRESOLVED entry, lock (non-blocking),
1747 * and link to the parent. The mount point is usually inherited
1748 * from the parent unless this is a special case such as a mount
1749 * point where nlc_namelen is 0. If nlc_namelen is 0 nc_name will
1752 if (nlc->nlc_namelen) {
1753 bcopy(nlc->nlc_nameptr, ncp->nc_name, nlc->nlc_namelen);
1754 ncp->nc_name[nlc->nlc_namelen] = 0;
1756 nchpp = NCHHASH(hash);
1757 LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
1758 ncp->nc_flag |= NCF_HASHED;
1759 cache_link_parent(ncp, par_nch->ncp);
1762 * stats and namecache size management
1764 if (ncp->nc_flag & NCF_UNRESOLVED)
1765 ++gd->gd_nchstats->ncs_miss;
1766 else if (ncp->nc_vp)
1767 ++gd->gd_nchstats->ncs_goodhits;
1769 ++gd->gd_nchstats->ncs_neghits;
1771 nch.mount = par_nch->mount;
1773 ++nch.mount->mnt_refs;
1778 * The namecache entry is marked as being used as a mount point.
1779 * Locate the mount if it is visible to the caller.
1781 struct findmount_info {
1782 struct mount *result;
1783 struct mount *nch_mount;
1784 struct namecache *nch_ncp;
1789 cache_findmount_callback(struct mount *mp, void *data)
1791 struct findmount_info *info = data;
1794 * Check the mount's mounted-on point against the passed nch.
1796 if (mp->mnt_ncmounton.mount == info->nch_mount &&
1797 mp->mnt_ncmounton.ncp == info->nch_ncp
1806 cache_findmount(struct nchandle *nch)
1808 struct findmount_info info;
1811 info.nch_mount = nch->mount;
1812 info.nch_ncp = nch->ncp;
1813 mountlist_scan(cache_findmount_callback, &info,
1814 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1815 return(info.result);
1819 * Resolve an unresolved namecache entry, generally by looking it up.
1820 * The passed ncp must be locked and refd.
1822 * Theoretically since a vnode cannot be recycled while held, and since
1823 * the nc_parent chain holds its vnode as long as children exist, the
1824 * direct parent of the cache entry we are trying to resolve should
1825 * have a valid vnode. If not then generate an error that we can
1826 * determine is related to a resolver bug.
1828 * However, if a vnode was in the middle of a recyclement when the NCP
1829 * got locked, ncp->nc_vp might point to a vnode that is about to become
1830 * invalid. cache_resolve() handles this case by unresolving the entry
1831 * and then re-resolving it.
1833 * Note that successful resolution does not necessarily return an error
1834 * code of 0. If the ncp resolves to a negative cache hit then ENOENT
1838 cache_resolve(struct nchandle *nch, struct ucred *cred)
1840 struct namecache *par;
1841 struct namecache *ncp;
1842 struct nchandle nctmp;
1850 * If the ncp is already resolved we have nothing to do. However,
1851 * we do want to guarentee that a usable vnode is returned when
1852 * a vnode is present, so make sure it hasn't been reclaimed.
1854 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1855 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
1856 _cache_setunresolved(ncp);
1857 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
1858 return (ncp->nc_error);
1862 * Mount points need special handling because the parent does not
1863 * belong to the same filesystem as the ncp.
1865 if (ncp == mp->mnt_ncmountpt.ncp)
1866 return (cache_resolve_mp(mp));
1869 * We expect an unbroken chain of ncps to at least the mount point,
1870 * and even all the way to root (but this code doesn't have to go
1871 * past the mount point).
1873 if (ncp->nc_parent == NULL) {
1874 kprintf("EXDEV case 1 %p %*.*s\n", ncp,
1875 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
1876 ncp->nc_error = EXDEV;
1877 return(ncp->nc_error);
1881 * The vp's of the parent directories in the chain are held via vhold()
1882 * due to the existance of the child, and should not disappear.
1883 * However, there are cases where they can disappear:
1885 * - due to filesystem I/O errors.
1886 * - due to NFS being stupid about tracking the namespace and
1887 * destroys the namespace for entire directories quite often.
1888 * - due to forced unmounts.
1889 * - due to an rmdir (parent will be marked DESTROYED)
1891 * When this occurs we have to track the chain backwards and resolve
1892 * it, looping until the resolver catches up to the current node. We
1893 * could recurse here but we might run ourselves out of kernel stack
1894 * so we do it in a more painful manner. This situation really should
1895 * not occur all that often, or if it does not have to go back too
1896 * many nodes to resolve the ncp.
1898 while (ncp->nc_parent->nc_vp == NULL) {
1900 * This case can occur if a process is CD'd into a
1901 * directory which is then rmdir'd. If the parent is marked
1902 * destroyed there is no point trying to resolve it.
1904 if (ncp->nc_parent->nc_flag & NCF_DESTROYED)
1907 par = ncp->nc_parent;
1908 while (par->nc_parent && par->nc_parent->nc_vp == NULL)
1909 par = par->nc_parent;
1910 if (par->nc_parent == NULL) {
1911 kprintf("EXDEV case 2 %*.*s\n",
1912 par->nc_nlen, par->nc_nlen, par->nc_name);
1915 kprintf("[diagnostic] cache_resolve: had to recurse on %*.*s\n",
1916 par->nc_nlen, par->nc_nlen, par->nc_name);
1918 * The parent is not set in stone, ref and lock it to prevent
1919 * it from disappearing. Also note that due to renames it
1920 * is possible for our ncp to move and for par to no longer
1921 * be one of its parents. We resolve it anyway, the loop
1922 * will handle any moves.
1925 if (par == nch->mount->mnt_ncmountpt.ncp) {
1926 cache_resolve_mp(nch->mount);
1927 } else if (par->nc_parent->nc_vp == NULL) {
1928 kprintf("[diagnostic] cache_resolve: raced on %*.*s\n", par->nc_nlen, par->nc_nlen, par->nc_name);
1931 } else if (par->nc_flag & NCF_UNRESOLVED) {
1934 par->nc_error = VOP_NRESOLVE(&nctmp, cred);
1936 if ((error = par->nc_error) != 0) {
1937 if (par->nc_error != EAGAIN) {
1938 kprintf("EXDEV case 3 %*.*s error %d\n",
1939 par->nc_nlen, par->nc_nlen, par->nc_name,
1944 kprintf("[diagnostic] cache_resolve: EAGAIN par %p %*.*s\n",
1945 par, par->nc_nlen, par->nc_nlen, par->nc_name);
1952 * Call VOP_NRESOLVE() to get the vp, then scan for any disconnected
1953 * ncp's and reattach them. If this occurs the original ncp is marked
1954 * EAGAIN to force a relookup.
1956 * NOTE: in order to call VOP_NRESOLVE(), the parent of the passed
1957 * ncp must already be resolved.
1961 ncp->nc_error = VOP_NRESOLVE(&nctmp, cred);
1962 /*vop_nresolve(*ncp->nc_parent->nc_vp->v_ops, ncp, cred);*/
1963 if (ncp->nc_error == EAGAIN) {
1964 kprintf("[diagnostic] cache_resolve: EAGAIN ncp %p %*.*s\n",
1965 ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
1968 return(ncp->nc_error);
1972 * Resolve the ncp associated with a mount point. Such ncp's almost always
1973 * remain resolved and this routine is rarely called. NFS MPs tends to force
1974 * re-resolution more often due to its mac-truck-smash-the-namecache
1975 * method of tracking namespace changes.
1977 * The semantics for this call is that the passed ncp must be locked on
1978 * entry and will be locked on return. However, if we actually have to
1979 * resolve the mount point we temporarily unlock the entry in order to
1980 * avoid race-to-root deadlocks due to e.g. dead NFS mounts. Because of
1981 * the unlock we have to recheck the flags after we relock.
1984 cache_resolve_mp(struct mount *mp)
1986 struct namecache *ncp = mp->mnt_ncmountpt.ncp;
1990 KKASSERT(mp != NULL);
1993 * If the ncp is already resolved we have nothing to do. However,
1994 * we do want to guarentee that a usable vnode is returned when
1995 * a vnode is present, so make sure it hasn't been reclaimed.
1997 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1998 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
1999 _cache_setunresolved(ncp);
2002 if (ncp->nc_flag & NCF_UNRESOLVED) {
2004 while (vfs_busy(mp, 0))
2006 error = VFS_ROOT(mp, &vp);
2010 * recheck the ncp state after relocking.
2012 if (ncp->nc_flag & NCF_UNRESOLVED) {
2013 ncp->nc_error = error;
2015 _cache_setvp(ncp, vp);
2018 kprintf("[diagnostic] cache_resolve_mp: failed to resolve mount %p\n", mp);
2019 _cache_setvp(ncp, NULL);
2021 } else if (error == 0) {
2026 return(ncp->nc_error);
2030 cache_cleanneg(int count)
2032 struct namecache *ncp;
2035 * Automode from the vnlru proc - clean out 10% of the negative cache
2039 count = numneg / 10 + 1;
2042 * Attempt to clean out the specified number of negative cache
2046 ncp = TAILQ_FIRST(&ncneglist);
2048 KKASSERT(numneg == 0);
2051 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
2052 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
2053 if (_cache_get_nonblock(ncp) == 0)
2060 * Rehash a ncp. Rehashing is typically required if the name changes (should
2061 * not generally occur) or the parent link changes. This function will
2062 * unhash the ncp if the ncp is no longer hashable.
2065 _cache_rehash(struct namecache *ncp)
2067 struct nchashhead *nchpp;
2070 if (ncp->nc_flag & NCF_HASHED) {
2071 ncp->nc_flag &= ~NCF_HASHED;
2072 LIST_REMOVE(ncp, nc_hash);
2074 if (ncp->nc_nlen && ncp->nc_parent) {
2075 hash = fnv_32_buf(ncp->nc_name, ncp->nc_nlen, FNV1_32_INIT);
2076 hash = fnv_32_buf(&ncp->nc_parent,
2077 sizeof(ncp->nc_parent), hash);
2078 nchpp = NCHHASH(hash);
2079 LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
2080 ncp->nc_flag |= NCF_HASHED;
2085 * Name cache initialization, from vfsinit() when we are booting
2093 /* initialise per-cpu namecache effectiveness statistics. */
2094 for (i = 0; i < ncpus; ++i) {
2095 gd = globaldata_find(i);
2096 gd->gd_nchstats = &nchstats[i];
2098 TAILQ_INIT(&ncneglist);
2099 nchashtbl = hashinit(desiredvnodes*2, M_VFSCACHE, &nchash);
2100 nclockwarn = 1 * hz;
2104 * Called from start_init() to bootstrap the root filesystem. Returns
2105 * a referenced, unlocked namecache record.
2108 cache_allocroot(struct nchandle *nch, struct mount *mp, struct vnode *vp)
2110 nch->ncp = cache_alloc(0);
2114 _cache_setvp(nch->ncp, vp);
2118 * vfs_cache_setroot()
2120 * Create an association between the root of our namecache and
2121 * the root vnode. This routine may be called several times during
2124 * If the caller intends to save the returned namecache pointer somewhere
2125 * it must cache_hold() it.
2128 vfs_cache_setroot(struct vnode *nvp, struct nchandle *nch)
2131 struct nchandle onch;
2139 cache_zero(&rootnch);
2147 * XXX OLD API COMPAT FUNCTION. This really messes up the new namecache
2148 * topology and is being removed as quickly as possible. The new VOP_N*()
2149 * API calls are required to make specific adjustments using the supplied
2150 * ncp pointers rather then just bogusly purging random vnodes.
2152 * Invalidate all namecache entries to a particular vnode as well as
2153 * any direct children of that vnode in the namecache. This is a
2154 * 'catch all' purge used by filesystems that do not know any better.
2156 * Note that the linkage between the vnode and its namecache entries will
2157 * be removed, but the namecache entries themselves might stay put due to
2158 * active references from elsewhere in the system or due to the existance of
2159 * the children. The namecache topology is left intact even if we do not
2160 * know what the vnode association is. Such entries will be marked
2164 cache_purge(struct vnode *vp)
2166 cache_inval_vp(vp, CINV_DESTROY | CINV_CHILDREN);
2170 * Flush all entries referencing a particular filesystem.
2172 * Since we need to check it anyway, we will flush all the invalid
2173 * entries at the same time.
2178 cache_purgevfs(struct mount *mp)
2180 struct nchashhead *nchpp;
2181 struct namecache *ncp, *nnp;
2184 * Scan hash tables for applicable entries.
2186 for (nchpp = &nchashtbl[nchash]; nchpp >= nchashtbl; nchpp--) {
2187 ncp = LIST_FIRST(nchpp);
2191 nnp = LIST_NEXT(ncp, nc_hash);
2194 if (ncp->nc_mount == mp) {
2208 * Create a new (theoretically) unique fsmid
2211 cache_getnewfsmid(void)
2213 static int fsmid_roller;
2217 fsmid = ((int64_t)time_second << 32) |
2218 (fsmid_roller & 0x7FFFFFFF);
2223 static int disablecwd;
2224 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0, "");
2226 static u_long numcwdcalls; STATNODE(CTLFLAG_RD, numcwdcalls, &numcwdcalls);
2227 static u_long numcwdfail1; STATNODE(CTLFLAG_RD, numcwdfail1, &numcwdfail1);
2228 static u_long numcwdfail2; STATNODE(CTLFLAG_RD, numcwdfail2, &numcwdfail2);
2229 static u_long numcwdfail3; STATNODE(CTLFLAG_RD, numcwdfail3, &numcwdfail3);
2230 static u_long numcwdfail4; STATNODE(CTLFLAG_RD, numcwdfail4, &numcwdfail4);
2231 static u_long numcwdfound; STATNODE(CTLFLAG_RD, numcwdfound, &numcwdfound);
2234 sys___getcwd(struct __getcwd_args *uap)
2244 buflen = uap->buflen;
2247 if (buflen > MAXPATHLEN)
2248 buflen = MAXPATHLEN;
2250 buf = kmalloc(buflen, M_TEMP, M_WAITOK);
2251 bp = kern_getcwd(buf, buflen, &error);
2253 error = copyout(bp, uap->buf, strlen(bp) + 1);
2259 kern_getcwd(char *buf, size_t buflen, int *error)
2261 struct proc *p = curproc;
2263 int i, slash_prefixed;
2264 struct filedesc *fdp;
2265 struct nchandle nch;
2274 nch = fdp->fd_ncdir;
2275 while (nch.ncp && (nch.ncp != fdp->fd_nrdir.ncp ||
2276 nch.mount != fdp->fd_nrdir.mount)
2279 * While traversing upwards if we encounter the root
2280 * of the current mount we have to skip to the mount point
2281 * in the underlying filesystem.
2283 if (nch.ncp == nch.mount->mnt_ncmountpt.ncp) {
2284 nch = nch.mount->mnt_ncmounton;
2289 * Prepend the path segment
2291 for (i = nch.ncp->nc_nlen - 1; i >= 0; i--) {
2297 *--bp = nch.ncp->nc_name[i];
2308 * Go up a directory. This isn't a mount point so we don't
2309 * have to check again.
2311 nch.ncp = nch.ncp->nc_parent;
2313 if (nch.ncp == NULL) {
2318 if (!slash_prefixed) {
2332 * Thus begins the fullpath magic.
2336 #define STATNODE(name) \
2337 static u_int name; \
2338 SYSCTL_UINT(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, "")
2340 static int disablefullpath;
2341 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW,
2342 &disablefullpath, 0, "");
2344 STATNODE(numfullpathcalls);
2345 STATNODE(numfullpathfail1);
2346 STATNODE(numfullpathfail2);
2347 STATNODE(numfullpathfail3);
2348 STATNODE(numfullpathfail4);
2349 STATNODE(numfullpathfound);
2352 cache_fullpath(struct proc *p, struct nchandle *nchp, char **retbuf, char **freebuf)
2355 int i, slash_prefixed;
2356 struct nchandle fd_nrdir;
2357 struct nchandle nch;
2364 buf = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
2365 bp = buf + MAXPATHLEN - 1;
2368 fd_nrdir = p->p_fd->fd_nrdir;
2375 (nch.ncp != fd_nrdir.ncp || nch.mount != fd_nrdir.mount)
2378 * While traversing upwards if we encounter the root
2379 * of the current mount we have to skip to the mount point.
2381 if (nch.ncp == nch.mount->mnt_ncmountpt.ncp) {
2382 nch = nch.mount->mnt_ncmounton;
2387 * Prepend the path segment
2389 for (i = nch.ncp->nc_nlen - 1; i >= 0; i--) {
2395 *--bp = nch.ncp->nc_name[i];
2406 * Go up a directory. This isn't a mount point so we don't
2407 * have to check again.
2409 nch.ncp = nch.ncp->nc_parent;
2411 if (nch.ncp == NULL) {
2417 if (!slash_prefixed) {
2433 vn_fullpath(struct proc *p, struct vnode *vn, char **retbuf, char **freebuf)
2435 struct namecache *ncp;
2436 struct nchandle nch;
2439 if (disablefullpath)
2445 /* vn is NULL, client wants us to use p->p_textvp */
2447 if ((vn = p->p_textvp) == NULL)
2450 TAILQ_FOREACH(ncp, &vn->v_namecache, nc_vnode) {
2459 nch.mount = vn->v_mount;
2460 return(cache_fullpath(p, &nch, retbuf, freebuf));