xref: /freebsd/sys/kern/vfs_cache.c (revision cc349066556bcdeed0d6cc72aad340d0f383e35c)
1 /*-
2  * Copyright (c) 1989, 1993, 1995
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Poul-Henning Kamp of the FreeBSD Project.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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 the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)vfs_cache.c	8.5 (Berkeley) 3/22/95
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include "opt_ktrace.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/counter.h>
43 #include <sys/filedesc.h>
44 #include <sys/fnv_hash.h>
45 #include <sys/kernel.h>
46 #include <sys/lock.h>
47 #include <sys/malloc.h>
48 #include <sys/fcntl.h>
49 #include <sys/mount.h>
50 #include <sys/namei.h>
51 #include <sys/proc.h>
52 #include <sys/rwlock.h>
53 #include <sys/sdt.h>
54 #include <sys/smp.h>
55 #include <sys/syscallsubr.h>
56 #include <sys/sysctl.h>
57 #include <sys/sysproto.h>
58 #include <sys/vnode.h>
59 #ifdef KTRACE
60 #include <sys/ktrace.h>
61 #endif
62 
63 #include <vm/uma.h>
64 
65 SDT_PROVIDER_DECLARE(vfs);
66 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
67     "struct vnode *");
68 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
69     "char *");
70 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
71 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
72     "char *", "struct vnode *");
73 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
74 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
75     "struct vnode *", "char *");
76 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
77     "struct vnode *");
78 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
79     "struct vnode *", "char *");
80 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
81     "char *");
82 SDT_PROBE_DEFINE1(vfs, namecache, purge, done, "struct vnode *");
83 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
84 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
85 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
86     "struct vnode *");
87 SDT_PROBE_DEFINE3(vfs, namecache, zap_negative, done, "struct vnode *",
88     "char *", "int");
89 SDT_PROBE_DEFINE3(vfs, namecache, shrink_negative, done, "struct vnode *",
90     "char *", "int");
91 
92 /*
93  * This structure describes the elements in the cache of recent
94  * names looked up by namei.
95  */
96 
97 struct	namecache {
98 	LIST_ENTRY(namecache) nc_hash;	/* hash chain */
99 	LIST_ENTRY(namecache) nc_src;	/* source vnode list */
100 	TAILQ_ENTRY(namecache) nc_dst;	/* destination vnode list */
101 	struct	vnode *nc_dvp;		/* vnode of parent of name */
102 	union {
103 		struct	vnode *nu_vp;	/* vnode the name refers to */
104 		u_int	nu_neghits;	/* negative entry hits */
105 	} n_un;
106 	u_char	nc_flag;		/* flag bits */
107 	u_char	nc_nlen;		/* length of name */
108 	char	nc_name[0];		/* segment name + nul */
109 };
110 
111 /*
112  * struct namecache_ts repeats struct namecache layout up to the
113  * nc_nlen member.
114  * struct namecache_ts is used in place of struct namecache when time(s) need
115  * to be stored.  The nc_dotdottime field is used when a cache entry is mapping
116  * both a non-dotdot directory name plus dotdot for the directory's
117  * parent.
118  */
119 struct	namecache_ts {
120 	LIST_ENTRY(namecache) nc_hash;	/* hash chain */
121 	LIST_ENTRY(namecache) nc_src;	/* source vnode list */
122 	TAILQ_ENTRY(namecache) nc_dst;	/* destination vnode list */
123 	struct	vnode *nc_dvp;		/* vnode of parent of name */
124 	union {
125 		struct	vnode *nu_vp;	/* vnode the name refers to */
126 		u_int	nu_neghits;	/* negative entry hits */
127 	} n_un;
128 	u_char	nc_flag;		/* flag bits */
129 	u_char	nc_nlen;		/* length of name */
130 	struct	timespec nc_time;	/* timespec provided by fs */
131 	struct	timespec nc_dotdottime;	/* dotdot timespec provided by fs */
132 	int	nc_ticks;		/* ticks value when entry was added */
133 	char	nc_name[0];		/* segment name + nul */
134 };
135 
136 #define	nc_vp		n_un.nu_vp
137 #define	nc_neghits	n_un.nu_neghits
138 
139 /*
140  * Flags in namecache.nc_flag
141  */
142 #define NCF_WHITE	0x01
143 #define NCF_ISDOTDOT	0x02
144 #define	NCF_TS		0x04
145 #define	NCF_DTS		0x08
146 #define	NCF_DVDROP	0x10
147 #define	NCF_NEGATIVE	0x20
148 #define	NCF_HOTNEGATIVE	0x40
149 
150 /*
151  * Name caching works as follows:
152  *
153  * Names found by directory scans are retained in a cache
154  * for future reference.  It is managed LRU, so frequently
155  * used names will hang around.  Cache is indexed by hash value
156  * obtained from (vp, name) where vp refers to the directory
157  * containing name.
158  *
159  * If it is a "negative" entry, (i.e. for a name that is known NOT to
160  * exist) the vnode pointer will be NULL.
161  *
162  * Upon reaching the last segment of a path, if the reference
163  * is for DELETE, or NOCACHE is set (rewrite), and the
164  * name is located in the cache, it will be dropped.
165  *
166  * These locks are used (in the order in which they can be taken):
167  * NAME		TYPE	ROLE
168  * vnodelock	mtx	vnode lists and v_cache_dd field protection
169  * bucketlock	rwlock	for access to given set of hash buckets
170  * neglist	mtx	negative entry LRU management
171  *
172  * Additionally, ncneg_shrink_lock mtx is used to have at most one thread
173  * shrinking the LRU list.
174  *
175  * It is legal to take multiple vnodelock and bucketlock locks. The locking
176  * order is lower address first. Both are recursive.
177  *
178  * "." lookups are lockless.
179  *
180  * ".." and vnode -> name lookups require vnodelock.
181  *
182  * name -> vnode lookup requires the relevant bucketlock to be held for reading.
183  *
184  * Insertions and removals of entries require involved vnodes and bucketlocks
185  * to be write-locked to prevent other threads from seeing the entry.
186  *
187  * Some lookups result in removal of the found entry (e.g. getting rid of a
188  * negative entry with the intent to create a positive one), which poses a
189  * problem when multiple threads reach the state. Similarly, two different
190  * threads can purge two different vnodes and try to remove the same name.
191  *
192  * If the already held vnode lock is lower than the second required lock, we
193  * can just take the other lock. However, in the opposite case, this could
194  * deadlock. As such, this is resolved by trylocking and if that fails unlocking
195  * the first node, locking everything in order and revalidating the state.
196  */
197 
198 /*
199  * Structures associated with name caching.
200  */
201 #define NCHHASH(hash) \
202 	(&nchashtbl[(hash) & nchash])
203 static LIST_HEAD(nchashhead, namecache) *nchashtbl;	/* Hash Table */
204 static u_long	nchash;			/* size of hash table */
205 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
206     "Size of namecache hash table");
207 static u_long	ncnegfactor = 16;	/* ratio of negative entries */
208 SYSCTL_ULONG(_vfs, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0,
209     "Ratio of negative namecache entries");
210 static u_long	numneg;			/* number of negative entries allocated */
211 SYSCTL_ULONG(_debug, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0,
212     "Number of negative entries in namecache");
213 static u_long	numcache;		/* number of cache entries allocated */
214 SYSCTL_ULONG(_debug, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0,
215     "Number of namecache entries");
216 static u_long	numcachehv;		/* number of cache entries with vnodes held */
217 SYSCTL_ULONG(_debug, OID_AUTO, numcachehv, CTLFLAG_RD, &numcachehv, 0,
218     "Number of namecache entries with vnodes held");
219 u_int	ncsizefactor = 2;
220 SYSCTL_UINT(_vfs, OID_AUTO, ncsizefactor, CTLFLAG_RW, &ncsizefactor, 0,
221     "Size factor for namecache");
222 static u_int	ncpurgeminvnodes;
223 SYSCTL_UINT(_vfs, OID_AUTO, ncpurgeminvnodes, CTLFLAG_RW, &ncpurgeminvnodes, 0,
224     "Number of vnodes below which purgevfs ignores the request");
225 static u_int	ncneghitsrequeue = 8;
226 SYSCTL_UINT(_vfs, OID_AUTO, ncneghitsrequeue, CTLFLAG_RW, &ncneghitsrequeue, 0,
227     "Number of hits to requeue a negative entry in the LRU list");
228 
229 struct nchstats	nchstats;		/* cache effectiveness statistics */
230 
231 static struct mtx       ncneg_shrink_lock;
232 
233 struct neglist {
234 	struct mtx		nl_lock;
235 	TAILQ_HEAD(, namecache) nl_list;
236 } __aligned(CACHE_LINE_SIZE);
237 
238 static struct neglist *neglists;
239 static struct neglist ncneg_hot;
240 
241 static int	shrink_list_turn;
242 
243 #define	numneglists (ncneghash + 1)
244 static u_int	ncneghash;
245 static inline struct neglist *
246 NCP2NEGLIST(struct namecache *ncp)
247 {
248 
249 	return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
250 }
251 
252 #define	numbucketlocks (ncbuckethash + 1)
253 static u_int   ncbuckethash;
254 static struct rwlock_padalign  *bucketlocks;
255 #define	HASH2BUCKETLOCK(hash) \
256 	((struct rwlock *)(&bucketlocks[((hash) & ncbuckethash)]))
257 
258 #define	numvnodelocks (ncvnodehash + 1)
259 static u_int   ncvnodehash;
260 static struct mtx *vnodelocks;
261 static inline struct mtx *
262 VP2VNODELOCK(struct vnode *vp)
263 {
264 
265 	return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
266 }
267 
268 /*
269  * UMA zones for the VFS cache.
270  *
271  * The small cache is used for entries with short names, which are the
272  * most common.  The large cache is used for entries which are too big to
273  * fit in the small cache.
274  */
275 static uma_zone_t cache_zone_small;
276 static uma_zone_t cache_zone_small_ts;
277 static uma_zone_t cache_zone_large;
278 static uma_zone_t cache_zone_large_ts;
279 
280 #define	CACHE_PATH_CUTOFF	35
281 
282 static struct namecache *
283 cache_alloc(int len, int ts)
284 {
285 
286 	if (len > CACHE_PATH_CUTOFF) {
287 		if (ts)
288 			return (uma_zalloc(cache_zone_large_ts, M_WAITOK));
289 		else
290 			return (uma_zalloc(cache_zone_large, M_WAITOK));
291 	}
292 	if (ts)
293 		return (uma_zalloc(cache_zone_small_ts, M_WAITOK));
294 	else
295 		return (uma_zalloc(cache_zone_small, M_WAITOK));
296 }
297 
298 static void
299 cache_free(struct namecache *ncp)
300 {
301 	int ts;
302 
303 	if (ncp == NULL)
304 		return;
305 	ts = ncp->nc_flag & NCF_TS;
306 	if ((ncp->nc_flag & NCF_DVDROP) != 0)
307 		vdrop(ncp->nc_dvp);
308 	if (ncp->nc_nlen <= CACHE_PATH_CUTOFF) {
309 		if (ts)
310 			uma_zfree(cache_zone_small_ts, ncp);
311 		else
312 			uma_zfree(cache_zone_small, ncp);
313 	} else if (ts)
314 		uma_zfree(cache_zone_large_ts, ncp);
315 	else
316 		uma_zfree(cache_zone_large, ncp);
317 }
318 
319 static char *
320 nc_get_name(struct namecache *ncp)
321 {
322 	struct namecache_ts *ncp_ts;
323 
324 	if ((ncp->nc_flag & NCF_TS) == 0)
325 		return (ncp->nc_name);
326 	ncp_ts = (struct namecache_ts *)ncp;
327 	return (ncp_ts->nc_name);
328 }
329 
330 static void
331 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
332 {
333 
334 	KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
335 	    (tsp == NULL && ticksp == NULL),
336 	    ("No NCF_TS"));
337 
338 	if (tsp != NULL)
339 		*tsp = ((struct namecache_ts *)ncp)->nc_time;
340 	if (ticksp != NULL)
341 		*ticksp = ((struct namecache_ts *)ncp)->nc_ticks;
342 }
343 
344 static int	doingcache = 1;		/* 1 => enable the cache */
345 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
346     "VFS namecache enabled");
347 
348 /* Export size information to userland */
349 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
350     sizeof(struct namecache), "sizeof(struct namecache)");
351 
352 /*
353  * The new name cache statistics
354  */
355 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0,
356     "Name cache statistics");
357 #define STATNODE_ULONG(name, descr)	\
358 	SYSCTL_ULONG(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, descr);
359 #define STATNODE_COUNTER(name, descr)	\
360 	static counter_u64_t name;	\
361 	SYSCTL_COUNTER_U64(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, descr);
362 STATNODE_ULONG(numneg, "Number of negative cache entries");
363 STATNODE_ULONG(numcache, "Number of cache entries");
364 STATNODE_COUNTER(numcalls, "Number of cache lookups");
365 STATNODE_COUNTER(dothits, "Number of '.' hits");
366 STATNODE_COUNTER(dotdothits, "Number of '..' hits");
367 STATNODE_COUNTER(numchecks, "Number of checks in lookup");
368 STATNODE_COUNTER(nummiss, "Number of cache misses");
369 STATNODE_COUNTER(nummisszap, "Number of cache misses we do not want to cache");
370 STATNODE_COUNTER(numposzaps,
371     "Number of cache hits (positive) we do not want to cache");
372 STATNODE_COUNTER(numposhits, "Number of cache hits (positive)");
373 STATNODE_COUNTER(numnegzaps,
374     "Number of cache hits (negative) we do not want to cache");
375 STATNODE_COUNTER(numneghits, "Number of cache hits (negative)");
376 /* These count for kern___getcwd(), too. */
377 STATNODE_COUNTER(numfullpathcalls, "Number of fullpath search calls");
378 STATNODE_COUNTER(numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
379 STATNODE_COUNTER(numfullpathfail2,
380     "Number of fullpath search errors (VOP_VPTOCNP failures)");
381 STATNODE_COUNTER(numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
382 STATNODE_COUNTER(numfullpathfound, "Number of successful fullpath calls");
383 static long zap_and_exit_bucket_fail; STATNODE_ULONG(zap_and_exit_bucket_fail,
384     "Number of times zap_and_exit failed to lock");
385 static long cache_lock_vnodes_cel_3_failures;
386 STATNODE_ULONG(cache_lock_vnodes_cel_3_failures,
387     "Number of times 3-way vnode locking failed");
388 
389 static void cache_zap_locked(struct namecache *ncp, bool neg_locked);
390 static int vn_fullpath1(struct thread *td, struct vnode *vp, struct vnode *rdir,
391     char *buf, char **retbuf, u_int buflen);
392 
393 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
394 
395 static int cache_yield;
396 SYSCTL_INT(_vfs_cache, OID_AUTO, yield, CTLFLAG_RD, &cache_yield, 0,
397     "Number of times cache called yield");
398 
399 static void
400 cache_maybe_yield(void)
401 {
402 
403 	if (should_yield()) {
404 		cache_yield++;
405 		kern_yield(PRI_USER);
406 	}
407 }
408 
409 static inline void
410 cache_assert_vlp_locked(struct mtx *vlp)
411 {
412 
413 	if (vlp != NULL)
414 		mtx_assert(vlp, MA_OWNED);
415 }
416 
417 static inline void
418 cache_assert_vnode_locked(struct vnode *vp)
419 {
420 	struct mtx *vlp;
421 
422 	vlp = VP2VNODELOCK(vp);
423 	cache_assert_vlp_locked(vlp);
424 }
425 
426 static uint32_t
427 cache_get_hash(char *name, u_char len, struct vnode *dvp)
428 {
429 	uint32_t hash;
430 
431 	hash = fnv_32_buf(name, len, FNV1_32_INIT);
432 	hash = fnv_32_buf(&dvp, sizeof(dvp), hash);
433 	return (hash);
434 }
435 
436 static inline struct rwlock *
437 NCP2BUCKETLOCK(struct namecache *ncp)
438 {
439 	uint32_t hash;
440 
441 	hash = cache_get_hash(nc_get_name(ncp), ncp->nc_nlen, ncp->nc_dvp);
442 	return (HASH2BUCKETLOCK(hash));
443 }
444 
445 #ifdef INVARIANTS
446 static void
447 cache_assert_bucket_locked(struct namecache *ncp, int mode)
448 {
449 	struct rwlock *blp;
450 
451 	blp = NCP2BUCKETLOCK(ncp);
452 	rw_assert(blp, mode);
453 }
454 #else
455 #define cache_assert_bucket_locked(x, y) do { } while (0)
456 #endif
457 
458 #define cache_sort(x, y)	_cache_sort((void **)(x), (void **)(y))
459 static void
460 _cache_sort(void **p1, void **p2)
461 {
462 	void *tmp;
463 
464 	if (*p1 > *p2) {
465 		tmp = *p2;
466 		*p2 = *p1;
467 		*p1 = tmp;
468 	}
469 }
470 
471 static void
472 cache_lock_all_buckets(void)
473 {
474 	u_int i;
475 
476 	for (i = 0; i < numbucketlocks; i++)
477 		rw_wlock(&bucketlocks[i]);
478 }
479 
480 static void
481 cache_unlock_all_buckets(void)
482 {
483 	u_int i;
484 
485 	for (i = 0; i < numbucketlocks; i++)
486 		rw_wunlock(&bucketlocks[i]);
487 }
488 
489 static void
490 cache_lock_all_vnodes(void)
491 {
492 	u_int i;
493 
494 	for (i = 0; i < numvnodelocks; i++)
495 		mtx_lock(&vnodelocks[i]);
496 }
497 
498 static void
499 cache_unlock_all_vnodes(void)
500 {
501 	u_int i;
502 
503 	for (i = 0; i < numvnodelocks; i++)
504 		mtx_unlock(&vnodelocks[i]);
505 }
506 
507 static int
508 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
509 {
510 
511 	cache_sort(&vlp1, &vlp2);
512 	MPASS(vlp2 != NULL);
513 
514 	if (vlp1 != NULL) {
515 		if (!mtx_trylock(vlp1))
516 			return (EAGAIN);
517 	}
518 	if (!mtx_trylock(vlp2)) {
519 		if (vlp1 != NULL)
520 			mtx_unlock(vlp1);
521 		return (EAGAIN);
522 	}
523 
524 	return (0);
525 }
526 
527 static void
528 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
529 {
530 
531 	MPASS(vlp1 != NULL || vlp2 != NULL);
532 
533 	if (vlp1 != NULL)
534 		mtx_unlock(vlp1);
535 	if (vlp2 != NULL)
536 		mtx_unlock(vlp2);
537 }
538 
539 static int
540 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
541 {
542 	struct nchstats snap;
543 
544 	if (req->oldptr == NULL)
545 		return (SYSCTL_OUT(req, 0, sizeof(snap)));
546 
547 	snap = nchstats;
548 	snap.ncs_goodhits = counter_u64_fetch(numposhits);
549 	snap.ncs_neghits = counter_u64_fetch(numneghits);
550 	snap.ncs_badhits = counter_u64_fetch(numposzaps) +
551 	    counter_u64_fetch(numnegzaps);
552 	snap.ncs_miss = counter_u64_fetch(nummisszap) +
553 	    counter_u64_fetch(nummiss);
554 
555 	return (SYSCTL_OUT(req, &snap, sizeof(snap)));
556 }
557 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
558     CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
559     "VFS cache effectiveness statistics");
560 
561 #ifdef DIAGNOSTIC
562 /*
563  * Grab an atomic snapshot of the name cache hash chain lengths
564  */
565 static SYSCTL_NODE(_debug, OID_AUTO, hashstat, CTLFLAG_RW, NULL,
566     "hash table stats");
567 
568 static int
569 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
570 {
571 	struct nchashhead *ncpp;
572 	struct namecache *ncp;
573 	int i, error, n_nchash, *cntbuf;
574 
575 retry:
576 	n_nchash = nchash + 1;	/* nchash is max index, not count */
577 	if (req->oldptr == NULL)
578 		return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
579 	cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
580 	cache_lock_all_buckets();
581 	if (n_nchash != nchash + 1) {
582 		cache_unlock_all_buckets();
583 		free(cntbuf, M_TEMP);
584 		goto retry;
585 	}
586 	/* Scan hash tables counting entries */
587 	for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
588 		LIST_FOREACH(ncp, ncpp, nc_hash)
589 			cntbuf[i]++;
590 	cache_unlock_all_buckets();
591 	for (error = 0, i = 0; i < n_nchash; i++)
592 		if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
593 			break;
594 	free(cntbuf, M_TEMP);
595 	return (error);
596 }
597 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
598     CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
599     "nchash chain lengths");
600 
601 static int
602 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
603 {
604 	int error;
605 	struct nchashhead *ncpp;
606 	struct namecache *ncp;
607 	int n_nchash;
608 	int count, maxlength, used, pct;
609 
610 	if (!req->oldptr)
611 		return SYSCTL_OUT(req, 0, 4 * sizeof(int));
612 
613 	cache_lock_all_buckets();
614 	n_nchash = nchash + 1;	/* nchash is max index, not count */
615 	used = 0;
616 	maxlength = 0;
617 
618 	/* Scan hash tables for applicable entries */
619 	for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
620 		count = 0;
621 		LIST_FOREACH(ncp, ncpp, nc_hash) {
622 			count++;
623 		}
624 		if (count)
625 			used++;
626 		if (maxlength < count)
627 			maxlength = count;
628 	}
629 	n_nchash = nchash + 1;
630 	cache_unlock_all_buckets();
631 	pct = (used * 100) / (n_nchash / 100);
632 	error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
633 	if (error)
634 		return (error);
635 	error = SYSCTL_OUT(req, &used, sizeof(used));
636 	if (error)
637 		return (error);
638 	error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
639 	if (error)
640 		return (error);
641 	error = SYSCTL_OUT(req, &pct, sizeof(pct));
642 	if (error)
643 		return (error);
644 	return (0);
645 }
646 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
647     CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
648     "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
649 #endif
650 
651 /*
652  * Negative entries management
653  *
654  * A variation of LRU scheme is used. New entries are hashed into one of
655  * numneglists cold lists. Entries get promoted to the hot list on first hit.
656  * Partial LRU for the hot list is maintained by requeueing them every
657  * ncneghitsrequeue hits.
658  *
659  * The shrinker will demote hot list head and evict from the cold list in a
660  * round-robin manner.
661  */
662 static void
663 cache_negative_hit(struct namecache *ncp)
664 {
665 	struct neglist *neglist;
666 	u_int hits;
667 
668 	MPASS(ncp->nc_flag & NCF_NEGATIVE);
669 	hits = atomic_fetchadd_int(&ncp->nc_neghits, 1);
670 	if (ncp->nc_flag & NCF_HOTNEGATIVE) {
671 		if ((hits % ncneghitsrequeue) != 0)
672 			return;
673 		mtx_lock(&ncneg_hot.nl_lock);
674 		if (ncp->nc_flag & NCF_HOTNEGATIVE) {
675 			TAILQ_REMOVE(&ncneg_hot.nl_list, ncp, nc_dst);
676 			TAILQ_INSERT_TAIL(&ncneg_hot.nl_list, ncp, nc_dst);
677 			mtx_unlock(&ncneg_hot.nl_lock);
678 			return;
679 		}
680 		/*
681 		 * The shrinker cleared the flag and removed the entry from
682 		 * the hot list. Put it back.
683 		 */
684 	} else {
685 		mtx_lock(&ncneg_hot.nl_lock);
686 	}
687 	neglist = NCP2NEGLIST(ncp);
688 	mtx_lock(&neglist->nl_lock);
689 	if (!(ncp->nc_flag & NCF_HOTNEGATIVE)) {
690 		TAILQ_REMOVE(&neglist->nl_list, ncp, nc_dst);
691 		TAILQ_INSERT_TAIL(&ncneg_hot.nl_list, ncp, nc_dst);
692 		ncp->nc_flag |= NCF_HOTNEGATIVE;
693 	}
694 	mtx_unlock(&neglist->nl_lock);
695 	mtx_unlock(&ncneg_hot.nl_lock);
696 }
697 
698 static void
699 cache_negative_insert(struct namecache *ncp, bool neg_locked)
700 {
701 	struct neglist *neglist;
702 
703 	MPASS(ncp->nc_flag & NCF_NEGATIVE);
704 	cache_assert_bucket_locked(ncp, RA_WLOCKED);
705 	neglist = NCP2NEGLIST(ncp);
706 	if (!neg_locked) {
707 		mtx_lock(&neglist->nl_lock);
708 	} else {
709 		mtx_assert(&neglist->nl_lock, MA_OWNED);
710 	}
711 	TAILQ_INSERT_TAIL(&neglist->nl_list, ncp, nc_dst);
712 	if (!neg_locked)
713 		mtx_unlock(&neglist->nl_lock);
714 	atomic_add_rel_long(&numneg, 1);
715 }
716 
717 static void
718 cache_negative_remove(struct namecache *ncp, bool neg_locked)
719 {
720 	struct neglist *neglist;
721 	bool hot_locked = false;
722 	bool list_locked = false;
723 
724 	MPASS(ncp->nc_flag & NCF_NEGATIVE);
725 	cache_assert_bucket_locked(ncp, RA_WLOCKED);
726 	neglist = NCP2NEGLIST(ncp);
727 	if (!neg_locked) {
728 		if (ncp->nc_flag & NCF_HOTNEGATIVE) {
729 			hot_locked = true;
730 			mtx_lock(&ncneg_hot.nl_lock);
731 			if (!(ncp->nc_flag & NCF_HOTNEGATIVE)) {
732 				list_locked = true;
733 				mtx_lock(&neglist->nl_lock);
734 			}
735 		} else {
736 			list_locked = true;
737 			mtx_lock(&neglist->nl_lock);
738 		}
739 	} else {
740 		mtx_assert(&neglist->nl_lock, MA_OWNED);
741 		mtx_assert(&ncneg_hot.nl_lock, MA_OWNED);
742 	}
743 	if (ncp->nc_flag & NCF_HOTNEGATIVE) {
744 		TAILQ_REMOVE(&ncneg_hot.nl_list, ncp, nc_dst);
745 	} else {
746 		TAILQ_REMOVE(&neglist->nl_list, ncp, nc_dst);
747 	}
748 	if (list_locked)
749 		mtx_unlock(&neglist->nl_lock);
750 	if (hot_locked)
751 		mtx_unlock(&ncneg_hot.nl_lock);
752 	atomic_subtract_rel_long(&numneg, 1);
753 }
754 
755 static void
756 cache_negative_shrink_select(int start, struct namecache **ncpp,
757     struct neglist **neglistpp)
758 {
759 	struct neglist *neglist;
760 	struct namecache *ncp;
761 	int i;
762 
763 	*ncpp = ncp = NULL;
764 
765 	for (i = start; i < numneglists; i++) {
766 		neglist = &neglists[i];
767 		if (TAILQ_FIRST(&neglist->nl_list) == NULL)
768 			continue;
769 		mtx_lock(&neglist->nl_lock);
770 		ncp = TAILQ_FIRST(&neglist->nl_list);
771 		if (ncp != NULL)
772 			break;
773 		mtx_unlock(&neglist->nl_lock);
774 	}
775 
776 	*neglistpp = neglist;
777 	*ncpp = ncp;
778 }
779 
780 static void
781 cache_negative_zap_one(void)
782 {
783 	struct namecache *ncp, *ncp2;
784 	struct neglist *neglist;
785 	struct mtx *dvlp;
786 	struct rwlock *blp;
787 
788 	if (!mtx_trylock(&ncneg_shrink_lock))
789 		return;
790 
791 	mtx_lock(&ncneg_hot.nl_lock);
792 	ncp = TAILQ_FIRST(&ncneg_hot.nl_list);
793 	if (ncp != NULL) {
794 		neglist = NCP2NEGLIST(ncp);
795 		mtx_lock(&neglist->nl_lock);
796 		TAILQ_REMOVE(&ncneg_hot.nl_list, ncp, nc_dst);
797 		TAILQ_INSERT_TAIL(&neglist->nl_list, ncp, nc_dst);
798 		ncp->nc_flag &= ~NCF_HOTNEGATIVE;
799 		mtx_unlock(&neglist->nl_lock);
800 	}
801 
802 	cache_negative_shrink_select(shrink_list_turn, &ncp, &neglist);
803 	shrink_list_turn++;
804 	if (shrink_list_turn == numneglists)
805 		shrink_list_turn = 0;
806 	if (ncp == NULL && shrink_list_turn == 0)
807 		cache_negative_shrink_select(shrink_list_turn, &ncp, &neglist);
808 	if (ncp == NULL) {
809 		mtx_unlock(&ncneg_hot.nl_lock);
810 		goto out;
811 	}
812 
813 	MPASS(ncp->nc_flag & NCF_NEGATIVE);
814 	dvlp = VP2VNODELOCK(ncp->nc_dvp);
815 	blp = NCP2BUCKETLOCK(ncp);
816 	mtx_unlock(&neglist->nl_lock);
817 	mtx_unlock(&ncneg_hot.nl_lock);
818 	mtx_lock(dvlp);
819 	rw_wlock(blp);
820 	mtx_lock(&ncneg_hot.nl_lock);
821 	mtx_lock(&neglist->nl_lock);
822 	ncp2 = TAILQ_FIRST(&neglist->nl_list);
823 	if (ncp != ncp2 || dvlp != VP2VNODELOCK(ncp2->nc_dvp) ||
824 	    blp != NCP2BUCKETLOCK(ncp2) || !(ncp2->nc_flag & NCF_NEGATIVE)) {
825 		ncp = NULL;
826 		goto out_unlock_all;
827 	}
828 	SDT_PROBE3(vfs, namecache, shrink_negative, done, ncp->nc_dvp,
829 	    nc_get_name(ncp), ncp->nc_neghits);
830 
831 	cache_zap_locked(ncp, true);
832 out_unlock_all:
833 	mtx_unlock(&neglist->nl_lock);
834 	mtx_unlock(&ncneg_hot.nl_lock);
835 	rw_wunlock(blp);
836 	mtx_unlock(dvlp);
837 out:
838 	mtx_unlock(&ncneg_shrink_lock);
839 	cache_free(ncp);
840 }
841 
842 /*
843  * cache_zap_locked():
844  *
845  *   Removes a namecache entry from cache, whether it contains an actual
846  *   pointer to a vnode or if it is just a negative cache entry.
847  */
848 static void
849 cache_zap_locked(struct namecache *ncp, bool neg_locked)
850 {
851 
852 	if (!(ncp->nc_flag & NCF_NEGATIVE))
853 		cache_assert_vnode_locked(ncp->nc_vp);
854 	cache_assert_vnode_locked(ncp->nc_dvp);
855 	cache_assert_bucket_locked(ncp, RA_WLOCKED);
856 
857 	CTR2(KTR_VFS, "cache_zap(%p) vp %p", ncp,
858 	    (ncp->nc_flag & NCF_NEGATIVE) ? NULL : ncp->nc_vp);
859 	if (!(ncp->nc_flag & NCF_NEGATIVE)) {
860 		SDT_PROBE3(vfs, namecache, zap, done, ncp->nc_dvp,
861 		    nc_get_name(ncp), ncp->nc_vp);
862 	} else {
863 		SDT_PROBE3(vfs, namecache, zap_negative, done, ncp->nc_dvp,
864 		    nc_get_name(ncp), ncp->nc_neghits);
865 	}
866 	LIST_REMOVE(ncp, nc_hash);
867 	if (!(ncp->nc_flag & NCF_NEGATIVE)) {
868 		TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst, ncp, nc_dst);
869 		if (ncp == ncp->nc_vp->v_cache_dd)
870 			ncp->nc_vp->v_cache_dd = NULL;
871 	} else {
872 		cache_negative_remove(ncp, neg_locked);
873 	}
874 	if (ncp->nc_flag & NCF_ISDOTDOT) {
875 		if (ncp == ncp->nc_dvp->v_cache_dd)
876 			ncp->nc_dvp->v_cache_dd = NULL;
877 	} else {
878 		LIST_REMOVE(ncp, nc_src);
879 		if (LIST_EMPTY(&ncp->nc_dvp->v_cache_src)) {
880 			ncp->nc_flag |= NCF_DVDROP;
881 			atomic_subtract_rel_long(&numcachehv, 1);
882 		}
883 	}
884 	atomic_subtract_rel_long(&numcache, 1);
885 }
886 
887 static void
888 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
889 {
890 	struct rwlock *blp;
891 
892 	MPASS(ncp->nc_dvp == vp);
893 	MPASS(ncp->nc_flag & NCF_NEGATIVE);
894 	cache_assert_vnode_locked(vp);
895 
896 	blp = NCP2BUCKETLOCK(ncp);
897 	rw_wlock(blp);
898 	cache_zap_locked(ncp, false);
899 	rw_wunlock(blp);
900 }
901 
902 static bool
903 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
904     struct mtx **vlpp)
905 {
906 	struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
907 	struct rwlock *blp;
908 
909 	MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
910 	cache_assert_vnode_locked(vp);
911 
912 	if (ncp->nc_flag & NCF_NEGATIVE) {
913 		if (*vlpp != NULL) {
914 			mtx_unlock(*vlpp);
915 			*vlpp = NULL;
916 		}
917 		cache_zap_negative_locked_vnode_kl(ncp, vp);
918 		return (true);
919 	}
920 
921 	pvlp = VP2VNODELOCK(vp);
922 	blp = NCP2BUCKETLOCK(ncp);
923 	vlp1 = VP2VNODELOCK(ncp->nc_dvp);
924 	vlp2 = VP2VNODELOCK(ncp->nc_vp);
925 
926 	if (*vlpp == vlp1 || *vlpp == vlp2) {
927 		to_unlock = *vlpp;
928 		*vlpp = NULL;
929 	} else {
930 		if (*vlpp != NULL) {
931 			mtx_unlock(*vlpp);
932 			*vlpp = NULL;
933 		}
934 		cache_sort(&vlp1, &vlp2);
935 		if (vlp1 == pvlp) {
936 			mtx_lock(vlp2);
937 			to_unlock = vlp2;
938 		} else {
939 			if (!mtx_trylock(vlp1))
940 				goto out_relock;
941 			to_unlock = vlp1;
942 		}
943 	}
944 	rw_wlock(blp);
945 	cache_zap_locked(ncp, false);
946 	rw_wunlock(blp);
947 	if (to_unlock != NULL)
948 		mtx_unlock(to_unlock);
949 	return (true);
950 
951 out_relock:
952 	mtx_unlock(vlp2);
953 	mtx_lock(vlp1);
954 	mtx_lock(vlp2);
955 	MPASS(*vlpp == NULL);
956 	*vlpp = vlp1;
957 	return (false);
958 }
959 
960 static int
961 cache_zap_locked_vnode(struct namecache *ncp, struct vnode *vp)
962 {
963 	struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
964 	struct rwlock *blp;
965 	int error = 0;
966 
967 	MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
968 	cache_assert_vnode_locked(vp);
969 
970 	pvlp = VP2VNODELOCK(vp);
971 	if (ncp->nc_flag & NCF_NEGATIVE) {
972 		cache_zap_negative_locked_vnode_kl(ncp, vp);
973 		goto out;
974 	}
975 
976 	blp = NCP2BUCKETLOCK(ncp);
977 	vlp1 = VP2VNODELOCK(ncp->nc_dvp);
978 	vlp2 = VP2VNODELOCK(ncp->nc_vp);
979 	cache_sort(&vlp1, &vlp2);
980 	if (vlp1 == pvlp) {
981 		mtx_lock(vlp2);
982 		to_unlock = vlp2;
983 	} else {
984 		if (!mtx_trylock(vlp1)) {
985 			error = EAGAIN;
986 			goto out;
987 		}
988 		to_unlock = vlp1;
989 	}
990 	rw_wlock(blp);
991 	cache_zap_locked(ncp, false);
992 	rw_wunlock(blp);
993 	mtx_unlock(to_unlock);
994 out:
995 	mtx_unlock(pvlp);
996 	return (error);
997 }
998 
999 static int
1000 cache_zap_rlocked_bucket(struct namecache *ncp, struct rwlock *blp)
1001 {
1002 	struct mtx *dvlp, *vlp;
1003 
1004 	cache_assert_bucket_locked(ncp, RA_RLOCKED);
1005 
1006 	dvlp = VP2VNODELOCK(ncp->nc_dvp);
1007 	vlp = NULL;
1008 	if (!(ncp->nc_flag & NCF_NEGATIVE))
1009 		vlp = VP2VNODELOCK(ncp->nc_vp);
1010 	if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1011 		rw_runlock(blp);
1012 		rw_wlock(blp);
1013 		cache_zap_locked(ncp, false);
1014 		rw_wunlock(blp);
1015 		cache_unlock_vnodes(dvlp, vlp);
1016 		return (0);
1017 	}
1018 
1019 	rw_runlock(blp);
1020 	return (EAGAIN);
1021 }
1022 
1023 static int
1024 cache_zap_wlocked_bucket_kl(struct namecache *ncp, struct rwlock *blp,
1025     struct mtx **vlpp1, struct mtx **vlpp2)
1026 {
1027 	struct mtx *dvlp, *vlp;
1028 
1029 	cache_assert_bucket_locked(ncp, RA_WLOCKED);
1030 
1031 	dvlp = VP2VNODELOCK(ncp->nc_dvp);
1032 	vlp = NULL;
1033 	if (!(ncp->nc_flag & NCF_NEGATIVE))
1034 		vlp = VP2VNODELOCK(ncp->nc_vp);
1035 	cache_sort(&dvlp, &vlp);
1036 
1037 	if (*vlpp1 == dvlp && *vlpp2 == vlp) {
1038 		cache_zap_locked(ncp, false);
1039 		cache_unlock_vnodes(dvlp, vlp);
1040 		*vlpp1 = NULL;
1041 		*vlpp2 = NULL;
1042 		return (0);
1043 	}
1044 
1045 	if (*vlpp1 != NULL)
1046 		mtx_unlock(*vlpp1);
1047 	if (*vlpp2 != NULL)
1048 		mtx_unlock(*vlpp2);
1049 	*vlpp1 = NULL;
1050 	*vlpp2 = NULL;
1051 
1052 	if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1053 		cache_zap_locked(ncp, false);
1054 		cache_unlock_vnodes(dvlp, vlp);
1055 		return (0);
1056 	}
1057 
1058 	rw_wunlock(blp);
1059 	*vlpp1 = dvlp;
1060 	*vlpp2 = vlp;
1061 	if (*vlpp1 != NULL)
1062 		mtx_lock(*vlpp1);
1063 	mtx_lock(*vlpp2);
1064 	rw_wlock(blp);
1065 	return (EAGAIN);
1066 }
1067 
1068 static void
1069 cache_lookup_unlock(struct rwlock *blp, struct mtx *vlp)
1070 {
1071 
1072 	if (blp != NULL) {
1073 		rw_runlock(blp);
1074 		mtx_assert(vlp, MA_NOTOWNED);
1075 	} else {
1076 		mtx_unlock(vlp);
1077 	}
1078 }
1079 
1080 /*
1081  * Lookup an entry in the cache
1082  *
1083  * Lookup is called with dvp pointing to the directory to search,
1084  * cnp pointing to the name of the entry being sought. If the lookup
1085  * succeeds, the vnode is returned in *vpp, and a status of -1 is
1086  * returned. If the lookup determines that the name does not exist
1087  * (negative caching), a status of ENOENT is returned. If the lookup
1088  * fails, a status of zero is returned.  If the directory vnode is
1089  * recycled out from under us due to a forced unmount, a status of
1090  * ENOENT is returned.
1091  *
1092  * vpp is locked and ref'd on return.  If we're looking up DOTDOT, dvp is
1093  * unlocked.  If we're looking up . an extra ref is taken, but the lock is
1094  * not recursively acquired.
1095  */
1096 
1097 int
1098 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1099     struct timespec *tsp, int *ticksp)
1100 {
1101 	struct namecache *ncp;
1102 	struct rwlock *blp;
1103 	struct mtx *dvlp, *dvlp2;
1104 	uint32_t hash;
1105 	int error, ltype;
1106 
1107 	if (__predict_false(!doingcache)) {
1108 		cnp->cn_flags &= ~MAKEENTRY;
1109 		return (0);
1110 	}
1111 retry:
1112 	blp = NULL;
1113 	dvlp = VP2VNODELOCK(dvp);
1114 	error = 0;
1115 	counter_u64_add(numcalls, 1);
1116 
1117 	if (cnp->cn_nameptr[0] == '.') {
1118 		if (cnp->cn_namelen == 1) {
1119 			*vpp = dvp;
1120 			CTR2(KTR_VFS, "cache_lookup(%p, %s) found via .",
1121 			    dvp, cnp->cn_nameptr);
1122 			counter_u64_add(dothits, 1);
1123 			SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1124 			if (tsp != NULL)
1125 				timespecclear(tsp);
1126 			if (ticksp != NULL)
1127 				*ticksp = ticks;
1128 			VREF(*vpp);
1129 			/*
1130 			 * When we lookup "." we still can be asked to lock it
1131 			 * differently...
1132 			 */
1133 			ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1134 			if (ltype != VOP_ISLOCKED(*vpp)) {
1135 				if (ltype == LK_EXCLUSIVE) {
1136 					vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1137 					if ((*vpp)->v_iflag & VI_DOOMED) {
1138 						/* forced unmount */
1139 						vrele(*vpp);
1140 						*vpp = NULL;
1141 						return (ENOENT);
1142 					}
1143 				} else
1144 					vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1145 			}
1146 			return (-1);
1147 		}
1148 		if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
1149 			counter_u64_add(dotdothits, 1);
1150 			dvlp2 = NULL;
1151 			mtx_lock(dvlp);
1152 retry_dotdot:
1153 			ncp = dvp->v_cache_dd;
1154 			if (ncp == NULL) {
1155 				SDT_PROBE3(vfs, namecache, lookup, miss, dvp,
1156 				    "..", NULL);
1157 				mtx_unlock(dvlp);
1158 				return (0);
1159 			}
1160 			if ((cnp->cn_flags & MAKEENTRY) == 0) {
1161 				if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1162 					if (ncp->nc_dvp != dvp)
1163 						panic("dvp %p v_cache_dd %p\n", dvp, ncp);
1164 					if (!cache_zap_locked_vnode_kl2(ncp,
1165 					    dvp, &dvlp2))
1166 						goto retry_dotdot;
1167 					MPASS(dvp->v_cache_dd == NULL);
1168 					mtx_unlock(dvlp);
1169 					if (dvlp2 != NULL)
1170 						mtx_unlock(dvlp2);
1171 					cache_free(ncp);
1172 				} else {
1173 					dvp->v_cache_dd = NULL;
1174 					mtx_unlock(dvlp);
1175 					if (dvlp2 != NULL)
1176 						mtx_unlock(dvlp2);
1177 				}
1178 				return (0);
1179 			}
1180 			if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1181 				if (ncp->nc_flag & NCF_NEGATIVE)
1182 					*vpp = NULL;
1183 				else
1184 					*vpp = ncp->nc_vp;
1185 			} else
1186 				*vpp = ncp->nc_dvp;
1187 			/* Return failure if negative entry was found. */
1188 			if (*vpp == NULL)
1189 				goto negative_success;
1190 			CTR3(KTR_VFS, "cache_lookup(%p, %s) found %p via ..",
1191 			    dvp, cnp->cn_nameptr, *vpp);
1192 			SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..",
1193 			    *vpp);
1194 			cache_out_ts(ncp, tsp, ticksp);
1195 			if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1196 			    NCF_DTS && tsp != NULL)
1197 				*tsp = ((struct namecache_ts *)ncp)->
1198 				    nc_dotdottime;
1199 			goto success;
1200 		}
1201 	}
1202 
1203 	hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1204 	blp = HASH2BUCKETLOCK(hash);
1205 	rw_rlock(blp);
1206 
1207 	LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1208 		counter_u64_add(numchecks, 1);
1209 		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1210 		    !bcmp(nc_get_name(ncp), cnp->cn_nameptr, ncp->nc_nlen))
1211 			break;
1212 	}
1213 
1214 	/* We failed to find an entry */
1215 	if (ncp == NULL) {
1216 		SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
1217 		    NULL);
1218 		if ((cnp->cn_flags & MAKEENTRY) == 0) {
1219 			counter_u64_add(nummisszap, 1);
1220 		} else {
1221 			counter_u64_add(nummiss, 1);
1222 		}
1223 		goto unlock;
1224 	}
1225 
1226 	/* We don't want to have an entry, so dump it */
1227 	if ((cnp->cn_flags & MAKEENTRY) == 0) {
1228 		counter_u64_add(numposzaps, 1);
1229 		goto zap_and_exit;
1230 	}
1231 
1232 	/* We found a "positive" match, return the vnode */
1233 	if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1234 		counter_u64_add(numposhits, 1);
1235 		*vpp = ncp->nc_vp;
1236 		CTR4(KTR_VFS, "cache_lookup(%p, %s) found %p via ncp %p",
1237 		    dvp, cnp->cn_nameptr, *vpp, ncp);
1238 		SDT_PROBE3(vfs, namecache, lookup, hit, dvp, nc_get_name(ncp),
1239 		    *vpp);
1240 		cache_out_ts(ncp, tsp, ticksp);
1241 		goto success;
1242 	}
1243 
1244 negative_success:
1245 	/* We found a negative match, and want to create it, so purge */
1246 	if (cnp->cn_nameiop == CREATE) {
1247 		counter_u64_add(numnegzaps, 1);
1248 		goto zap_and_exit;
1249 	}
1250 
1251 	counter_u64_add(numneghits, 1);
1252 	cache_negative_hit(ncp);
1253 	if (ncp->nc_flag & NCF_WHITE)
1254 		cnp->cn_flags |= ISWHITEOUT;
1255 	SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp,
1256 	    nc_get_name(ncp));
1257 	cache_out_ts(ncp, tsp, ticksp);
1258 	cache_lookup_unlock(blp, dvlp);
1259 	return (ENOENT);
1260 
1261 success:
1262 	/*
1263 	 * On success we return a locked and ref'd vnode as per the lookup
1264 	 * protocol.
1265 	 */
1266 	MPASS(dvp != *vpp);
1267 	ltype = 0;	/* silence gcc warning */
1268 	if (cnp->cn_flags & ISDOTDOT) {
1269 		ltype = VOP_ISLOCKED(dvp);
1270 		VOP_UNLOCK(dvp, 0);
1271 	}
1272 	vhold(*vpp);
1273 	cache_lookup_unlock(blp, dvlp);
1274 	error = vget(*vpp, cnp->cn_lkflags | LK_VNHELD, cnp->cn_thread);
1275 	if (cnp->cn_flags & ISDOTDOT) {
1276 		vn_lock(dvp, ltype | LK_RETRY);
1277 		if (dvp->v_iflag & VI_DOOMED) {
1278 			if (error == 0)
1279 				vput(*vpp);
1280 			*vpp = NULL;
1281 			return (ENOENT);
1282 		}
1283 	}
1284 	if (error) {
1285 		*vpp = NULL;
1286 		goto retry;
1287 	}
1288 	if ((cnp->cn_flags & ISLASTCN) &&
1289 	    (cnp->cn_lkflags & LK_TYPE_MASK) == LK_EXCLUSIVE) {
1290 		ASSERT_VOP_ELOCKED(*vpp, "cache_lookup");
1291 	}
1292 	return (-1);
1293 
1294 unlock:
1295 	cache_lookup_unlock(blp, dvlp);
1296 	return (0);
1297 
1298 zap_and_exit:
1299 	if (blp != NULL)
1300 		error = cache_zap_rlocked_bucket(ncp, blp);
1301 	else
1302 		error = cache_zap_locked_vnode(ncp, dvp);
1303 	if (error != 0) {
1304 		zap_and_exit_bucket_fail++;
1305 		cache_maybe_yield();
1306 		goto retry;
1307 	}
1308 	cache_free(ncp);
1309 	return (0);
1310 }
1311 
1312 struct celockstate {
1313 	struct mtx *vlp[3];
1314 	struct rwlock *blp[2];
1315 };
1316 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
1317 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
1318 
1319 static inline void
1320 cache_celockstate_init(struct celockstate *cel)
1321 {
1322 
1323 	bzero(cel, sizeof(*cel));
1324 }
1325 
1326 static void
1327 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
1328     struct vnode *dvp)
1329 {
1330 	struct mtx *vlp1, *vlp2;
1331 
1332 	MPASS(cel->vlp[0] == NULL);
1333 	MPASS(cel->vlp[1] == NULL);
1334 	MPASS(cel->vlp[2] == NULL);
1335 
1336 	MPASS(vp != NULL || dvp != NULL);
1337 
1338 	vlp1 = VP2VNODELOCK(vp);
1339 	vlp2 = VP2VNODELOCK(dvp);
1340 	cache_sort(&vlp1, &vlp2);
1341 
1342 	if (vlp1 != NULL) {
1343 		mtx_lock(vlp1);
1344 		cel->vlp[0] = vlp1;
1345 	}
1346 	mtx_lock(vlp2);
1347 	cel->vlp[1] = vlp2;
1348 }
1349 
1350 static void
1351 cache_unlock_vnodes_cel(struct celockstate *cel)
1352 {
1353 
1354 	MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
1355 
1356 	if (cel->vlp[0] != NULL)
1357 		mtx_unlock(cel->vlp[0]);
1358 	if (cel->vlp[1] != NULL)
1359 		mtx_unlock(cel->vlp[1]);
1360 	if (cel->vlp[2] != NULL)
1361 		mtx_unlock(cel->vlp[2]);
1362 }
1363 
1364 static bool
1365 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
1366 {
1367 	struct mtx *vlp;
1368 	bool ret;
1369 
1370 	cache_assert_vlp_locked(cel->vlp[0]);
1371 	cache_assert_vlp_locked(cel->vlp[1]);
1372 	MPASS(cel->vlp[2] == NULL);
1373 
1374 	MPASS(vp != NULL);
1375 	vlp = VP2VNODELOCK(vp);
1376 
1377 	ret = true;
1378 	if (vlp >= cel->vlp[1]) {
1379 		mtx_lock(vlp);
1380 	} else {
1381 		if (mtx_trylock(vlp))
1382 			goto out;
1383 		cache_lock_vnodes_cel_3_failures++;
1384 		cache_unlock_vnodes_cel(cel);
1385 		if (vlp < cel->vlp[0]) {
1386 			mtx_lock(vlp);
1387 			mtx_lock(cel->vlp[0]);
1388 			mtx_lock(cel->vlp[1]);
1389 		} else {
1390 			if (cel->vlp[0] != NULL)
1391 				mtx_lock(cel->vlp[0]);
1392 			mtx_lock(vlp);
1393 			mtx_lock(cel->vlp[1]);
1394 		}
1395 		ret = false;
1396 	}
1397 out:
1398 	cel->vlp[2] = vlp;
1399 	return (ret);
1400 }
1401 
1402 static void
1403 cache_lock_buckets_cel(struct celockstate *cel, struct rwlock *blp1,
1404     struct rwlock *blp2)
1405 {
1406 
1407 	MPASS(cel->blp[0] == NULL);
1408 	MPASS(cel->blp[1] == NULL);
1409 
1410 	cache_sort(&blp1, &blp2);
1411 
1412 	if (blp1 != NULL) {
1413 		rw_wlock(blp1);
1414 		cel->blp[0] = blp1;
1415 	}
1416 	rw_wlock(blp2);
1417 	cel->blp[1] = blp2;
1418 }
1419 
1420 static void
1421 cache_unlock_buckets_cel(struct celockstate *cel)
1422 {
1423 
1424 	if (cel->blp[0] != NULL)
1425 		rw_wunlock(cel->blp[0]);
1426 	rw_wunlock(cel->blp[1]);
1427 }
1428 
1429 /*
1430  * Lock part of the cache affected by the insertion.
1431  *
1432  * This means vnodelocks for dvp, vp and the relevant bucketlock.
1433  * However, insertion can result in removal of an old entry. In this
1434  * case we have an additional vnode and bucketlock pair to lock. If the
1435  * entry is negative, ncelock is locked instead of the vnode.
1436  *
1437  * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
1438  * preserving the locking order (smaller address first).
1439  */
1440 static void
1441 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
1442     uint32_t hash)
1443 {
1444 	struct namecache *ncp;
1445 	struct rwlock *blps[2];
1446 
1447 	blps[0] = HASH2BUCKETLOCK(hash);
1448 	for (;;) {
1449 		blps[1] = NULL;
1450 		cache_lock_vnodes_cel(cel, dvp, vp);
1451 		if (vp == NULL || vp->v_type != VDIR)
1452 			break;
1453 		ncp = vp->v_cache_dd;
1454 		if (ncp == NULL)
1455 			break;
1456 		if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
1457 			break;
1458 		MPASS(ncp->nc_dvp == vp);
1459 		blps[1] = NCP2BUCKETLOCK(ncp);
1460 		if (ncp->nc_flag & NCF_NEGATIVE)
1461 			break;
1462 		if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
1463 			break;
1464 		/*
1465 		 * All vnodes got re-locked. Re-validate the state and if
1466 		 * nothing changed we are done. Otherwise restart.
1467 		 */
1468 		if (ncp == vp->v_cache_dd &&
1469 		    (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
1470 		    blps[1] == NCP2BUCKETLOCK(ncp) &&
1471 		    VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
1472 			break;
1473 		cache_unlock_vnodes_cel(cel);
1474 		cel->vlp[0] = NULL;
1475 		cel->vlp[1] = NULL;
1476 		cel->vlp[2] = NULL;
1477 	}
1478 	cache_lock_buckets_cel(cel, blps[0], blps[1]);
1479 }
1480 
1481 static void
1482 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
1483     uint32_t hash)
1484 {
1485 	struct namecache *ncp;
1486 	struct rwlock *blps[2];
1487 
1488 	blps[0] = HASH2BUCKETLOCK(hash);
1489 	for (;;) {
1490 		blps[1] = NULL;
1491 		cache_lock_vnodes_cel(cel, dvp, vp);
1492 		ncp = dvp->v_cache_dd;
1493 		if (ncp == NULL)
1494 			break;
1495 		if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
1496 			break;
1497 		MPASS(ncp->nc_dvp == dvp);
1498 		blps[1] = NCP2BUCKETLOCK(ncp);
1499 		if (ncp->nc_flag & NCF_NEGATIVE)
1500 			break;
1501 		if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
1502 			break;
1503 		if (ncp == dvp->v_cache_dd &&
1504 		    (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
1505 		    blps[1] == NCP2BUCKETLOCK(ncp) &&
1506 		    VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
1507 			break;
1508 		cache_unlock_vnodes_cel(cel);
1509 		cel->vlp[0] = NULL;
1510 		cel->vlp[1] = NULL;
1511 		cel->vlp[2] = NULL;
1512 	}
1513 	cache_lock_buckets_cel(cel, blps[0], blps[1]);
1514 }
1515 
1516 static void
1517 cache_enter_unlock(struct celockstate *cel)
1518 {
1519 
1520 	cache_unlock_buckets_cel(cel);
1521 	cache_unlock_vnodes_cel(cel);
1522 }
1523 
1524 /*
1525  * Add an entry to the cache.
1526  */
1527 void
1528 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
1529     struct timespec *tsp, struct timespec *dtsp)
1530 {
1531 	struct celockstate cel;
1532 	struct namecache *ncp, *n2, *ndd;
1533 	struct namecache_ts *n3;
1534 	struct nchashhead *ncpp;
1535 	struct neglist *neglist;
1536 	uint32_t hash;
1537 	int flag;
1538 	int len;
1539 	bool neg_locked;
1540 
1541 	CTR3(KTR_VFS, "cache_enter(%p, %p, %s)", dvp, vp, cnp->cn_nameptr);
1542 	VNASSERT(vp == NULL || (vp->v_iflag & VI_DOOMED) == 0, vp,
1543 	    ("cache_enter: Adding a doomed vnode"));
1544 	VNASSERT(dvp == NULL || (dvp->v_iflag & VI_DOOMED) == 0, dvp,
1545 	    ("cache_enter: Doomed vnode used as src"));
1546 
1547 	if (__predict_false(!doingcache))
1548 		return;
1549 
1550 	/*
1551 	 * Avoid blowout in namecache entries.
1552 	 */
1553 	if (__predict_false(numcache >= desiredvnodes * ncsizefactor))
1554 		return;
1555 
1556 	cache_celockstate_init(&cel);
1557 	ndd = NULL;
1558 	flag = 0;
1559 	if (cnp->cn_nameptr[0] == '.') {
1560 		if (cnp->cn_namelen == 1)
1561 			return;
1562 		if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
1563 			len = cnp->cn_namelen;
1564 			hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
1565 			cache_enter_lock_dd(&cel, dvp, vp, hash);
1566 			/*
1567 			 * If dotdot entry already exists, just retarget it
1568 			 * to new parent vnode, otherwise continue with new
1569 			 * namecache entry allocation.
1570 			 */
1571 			if ((ncp = dvp->v_cache_dd) != NULL &&
1572 			    ncp->nc_flag & NCF_ISDOTDOT) {
1573 				KASSERT(ncp->nc_dvp == dvp,
1574 				    ("wrong isdotdot parent"));
1575 				neg_locked = false;
1576 				if (ncp->nc_flag & NCF_NEGATIVE || vp == NULL) {
1577 					neglist = NCP2NEGLIST(ncp);
1578 					mtx_lock(&ncneg_hot.nl_lock);
1579 					mtx_lock(&neglist->nl_lock);
1580 					neg_locked = true;
1581 				}
1582 				if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1583 					TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst,
1584 					    ncp, nc_dst);
1585 				} else {
1586 					cache_negative_remove(ncp, true);
1587 				}
1588 				if (vp != NULL) {
1589 					TAILQ_INSERT_HEAD(&vp->v_cache_dst,
1590 					    ncp, nc_dst);
1591 					ncp->nc_flag &= ~(NCF_NEGATIVE|NCF_HOTNEGATIVE);
1592 				} else {
1593 					ncp->nc_flag &= ~(NCF_HOTNEGATIVE);
1594 					ncp->nc_flag |= NCF_NEGATIVE;
1595 					cache_negative_insert(ncp, true);
1596 				}
1597 				if (neg_locked) {
1598 					mtx_unlock(&neglist->nl_lock);
1599 					mtx_unlock(&ncneg_hot.nl_lock);
1600 				}
1601 				ncp->nc_vp = vp;
1602 				cache_enter_unlock(&cel);
1603 				return;
1604 			}
1605 			dvp->v_cache_dd = NULL;
1606 			cache_enter_unlock(&cel);
1607 			cache_celockstate_init(&cel);
1608 			SDT_PROBE3(vfs, namecache, enter, done, dvp, "..", vp);
1609 			flag = NCF_ISDOTDOT;
1610 		}
1611 	}
1612 
1613 	/*
1614 	 * Calculate the hash key and setup as much of the new
1615 	 * namecache entry as possible before acquiring the lock.
1616 	 */
1617 	ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
1618 	ncp->nc_flag = flag;
1619 	ncp->nc_vp = vp;
1620 	if (vp == NULL)
1621 		ncp->nc_flag |= NCF_NEGATIVE;
1622 	ncp->nc_dvp = dvp;
1623 	if (tsp != NULL) {
1624 		n3 = (struct namecache_ts *)ncp;
1625 		n3->nc_time = *tsp;
1626 		n3->nc_ticks = ticks;
1627 		n3->nc_flag |= NCF_TS;
1628 		if (dtsp != NULL) {
1629 			n3->nc_dotdottime = *dtsp;
1630 			n3->nc_flag |= NCF_DTS;
1631 		}
1632 	}
1633 	len = ncp->nc_nlen = cnp->cn_namelen;
1634 	hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
1635 	strlcpy(nc_get_name(ncp), cnp->cn_nameptr, len + 1);
1636 	cache_enter_lock(&cel, dvp, vp, hash);
1637 
1638 	/*
1639 	 * See if this vnode or negative entry is already in the cache
1640 	 * with this name.  This can happen with concurrent lookups of
1641 	 * the same path name.
1642 	 */
1643 	ncpp = NCHHASH(hash);
1644 	LIST_FOREACH(n2, ncpp, nc_hash) {
1645 		if (n2->nc_dvp == dvp &&
1646 		    n2->nc_nlen == cnp->cn_namelen &&
1647 		    !bcmp(nc_get_name(n2), cnp->cn_nameptr, n2->nc_nlen)) {
1648 			if (tsp != NULL) {
1649 				KASSERT((n2->nc_flag & NCF_TS) != 0,
1650 				    ("no NCF_TS"));
1651 				n3 = (struct namecache_ts *)n2;
1652 				n3->nc_time =
1653 				    ((struct namecache_ts *)ncp)->nc_time;
1654 				n3->nc_ticks =
1655 				    ((struct namecache_ts *)ncp)->nc_ticks;
1656 				if (dtsp != NULL) {
1657 					n3->nc_dotdottime =
1658 					    ((struct namecache_ts *)ncp)->
1659 					    nc_dotdottime;
1660 					if (ncp->nc_flag & NCF_NEGATIVE)
1661 						mtx_lock(&ncneg_hot.nl_lock);
1662 					n3->nc_flag |= NCF_DTS;
1663 					if (ncp->nc_flag & NCF_NEGATIVE)
1664 						mtx_unlock(&ncneg_hot.nl_lock);
1665 				}
1666 			}
1667 			goto out_unlock_free;
1668 		}
1669 	}
1670 
1671 	if (flag == NCF_ISDOTDOT) {
1672 		/*
1673 		 * See if we are trying to add .. entry, but some other lookup
1674 		 * has populated v_cache_dd pointer already.
1675 		 */
1676 		if (dvp->v_cache_dd != NULL)
1677 			goto out_unlock_free;
1678 		KASSERT(vp == NULL || vp->v_type == VDIR,
1679 		    ("wrong vnode type %p", vp));
1680 		dvp->v_cache_dd = ncp;
1681 	}
1682 
1683 	atomic_add_rel_long(&numcache, 1);
1684 	if (vp != NULL) {
1685 		if (vp->v_type == VDIR) {
1686 			if (flag != NCF_ISDOTDOT) {
1687 				/*
1688 				 * For this case, the cache entry maps both the
1689 				 * directory name in it and the name ".." for the
1690 				 * directory's parent.
1691 				 */
1692 				if ((ndd = vp->v_cache_dd) != NULL) {
1693 					if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
1694 						cache_zap_locked(ndd, false);
1695 					else
1696 						ndd = NULL;
1697 				}
1698 				vp->v_cache_dd = ncp;
1699 			}
1700 		} else {
1701 			vp->v_cache_dd = NULL;
1702 		}
1703 	}
1704 
1705 	if (flag != NCF_ISDOTDOT) {
1706 		if (LIST_EMPTY(&dvp->v_cache_src)) {
1707 			vhold(dvp);
1708 			atomic_add_rel_long(&numcachehv, 1);
1709 		}
1710 		LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
1711 	}
1712 
1713 	/*
1714 	 * Insert the new namecache entry into the appropriate chain
1715 	 * within the cache entries table.
1716 	 */
1717 	LIST_INSERT_HEAD(ncpp, ncp, nc_hash);
1718 
1719 	/*
1720 	 * If the entry is "negative", we place it into the
1721 	 * "negative" cache queue, otherwise, we place it into the
1722 	 * destination vnode's cache entries queue.
1723 	 */
1724 	if (vp != NULL) {
1725 		TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
1726 		SDT_PROBE3(vfs, namecache, enter, done, dvp, nc_get_name(ncp),
1727 		    vp);
1728 	} else {
1729 		if (cnp->cn_flags & ISWHITEOUT)
1730 			ncp->nc_flag |= NCF_WHITE;
1731 		cache_negative_insert(ncp, false);
1732 		SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
1733 		    nc_get_name(ncp));
1734 	}
1735 	cache_enter_unlock(&cel);
1736 	if (numneg * ncnegfactor > numcache)
1737 		cache_negative_zap_one();
1738 	cache_free(ndd);
1739 	return;
1740 out_unlock_free:
1741 	cache_enter_unlock(&cel);
1742 	cache_free(ncp);
1743 	return;
1744 }
1745 
1746 static u_int
1747 cache_roundup_2(u_int val)
1748 {
1749 	u_int res;
1750 
1751 	for (res = 1; res <= val; res <<= 1)
1752 		continue;
1753 
1754 	return (res);
1755 }
1756 
1757 /*
1758  * Name cache initialization, from vfs_init() when we are booting
1759  */
1760 static void
1761 nchinit(void *dummy __unused)
1762 {
1763 	u_int i;
1764 
1765 	cache_zone_small = uma_zcreate("S VFS Cache",
1766 	    sizeof(struct namecache) + CACHE_PATH_CUTOFF + 1,
1767 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
1768 	cache_zone_small_ts = uma_zcreate("STS VFS Cache",
1769 	    sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1,
1770 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
1771 	cache_zone_large = uma_zcreate("L VFS Cache",
1772 	    sizeof(struct namecache) + NAME_MAX + 1,
1773 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
1774 	cache_zone_large_ts = uma_zcreate("LTS VFS Cache",
1775 	    sizeof(struct namecache_ts) + NAME_MAX + 1,
1776 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
1777 
1778 	nchashtbl = hashinit(desiredvnodes * 2, M_VFSCACHE, &nchash);
1779 	ncbuckethash = cache_roundup_2(mp_ncpus * 64) - 1;
1780 	if (ncbuckethash > nchash)
1781 		ncbuckethash = nchash;
1782 	bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
1783 	    M_WAITOK | M_ZERO);
1784 	for (i = 0; i < numbucketlocks; i++)
1785 		rw_init_flags(&bucketlocks[i], "ncbuc", RW_DUPOK | RW_RECURSE);
1786 	ncvnodehash = cache_roundup_2(mp_ncpus * 64) - 1;
1787 	vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
1788 	    M_WAITOK | M_ZERO);
1789 	for (i = 0; i < numvnodelocks; i++)
1790 		mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
1791 	ncpurgeminvnodes = numbucketlocks;
1792 
1793 	ncneghash = 3;
1794 	neglists = malloc(sizeof(*neglists) * numneglists, M_VFSCACHE,
1795 	    M_WAITOK | M_ZERO);
1796 	for (i = 0; i < numneglists; i++) {
1797 		mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
1798 		TAILQ_INIT(&neglists[i].nl_list);
1799 	}
1800 	mtx_init(&ncneg_hot.nl_lock, "ncneglh", NULL, MTX_DEF);
1801 	TAILQ_INIT(&ncneg_hot.nl_list);
1802 
1803 	mtx_init(&ncneg_shrink_lock, "ncnegs", NULL, MTX_DEF);
1804 
1805 	numcalls = counter_u64_alloc(M_WAITOK);
1806 	dothits = counter_u64_alloc(M_WAITOK);
1807 	dotdothits = counter_u64_alloc(M_WAITOK);
1808 	numchecks = counter_u64_alloc(M_WAITOK);
1809 	nummiss = counter_u64_alloc(M_WAITOK);
1810 	nummisszap = counter_u64_alloc(M_WAITOK);
1811 	numposzaps = counter_u64_alloc(M_WAITOK);
1812 	numposhits = counter_u64_alloc(M_WAITOK);
1813 	numnegzaps = counter_u64_alloc(M_WAITOK);
1814 	numneghits = counter_u64_alloc(M_WAITOK);
1815 	numfullpathcalls = counter_u64_alloc(M_WAITOK);
1816 	numfullpathfail1 = counter_u64_alloc(M_WAITOK);
1817 	numfullpathfail2 = counter_u64_alloc(M_WAITOK);
1818 	numfullpathfail4 = counter_u64_alloc(M_WAITOK);
1819 	numfullpathfound = counter_u64_alloc(M_WAITOK);
1820 }
1821 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
1822 
1823 void
1824 cache_changesize(int newmaxvnodes)
1825 {
1826 	struct nchashhead *new_nchashtbl, *old_nchashtbl;
1827 	u_long new_nchash, old_nchash;
1828 	struct namecache *ncp;
1829 	uint32_t hash;
1830 	int i;
1831 
1832 	newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
1833 	if (newmaxvnodes < numbucketlocks)
1834 		newmaxvnodes = numbucketlocks;
1835 
1836 	new_nchashtbl = hashinit(newmaxvnodes, M_VFSCACHE, &new_nchash);
1837 	/* If same hash table size, nothing to do */
1838 	if (nchash == new_nchash) {
1839 		free(new_nchashtbl, M_VFSCACHE);
1840 		return;
1841 	}
1842 	/*
1843 	 * Move everything from the old hash table to the new table.
1844 	 * None of the namecache entries in the table can be removed
1845 	 * because to do so, they have to be removed from the hash table.
1846 	 */
1847 	cache_lock_all_vnodes();
1848 	cache_lock_all_buckets();
1849 	old_nchashtbl = nchashtbl;
1850 	old_nchash = nchash;
1851 	nchashtbl = new_nchashtbl;
1852 	nchash = new_nchash;
1853 	for (i = 0; i <= old_nchash; i++) {
1854 		while ((ncp = LIST_FIRST(&old_nchashtbl[i])) != NULL) {
1855 			hash = cache_get_hash(nc_get_name(ncp), ncp->nc_nlen,
1856 			    ncp->nc_dvp);
1857 			LIST_REMOVE(ncp, nc_hash);
1858 			LIST_INSERT_HEAD(NCHHASH(hash), ncp, nc_hash);
1859 		}
1860 	}
1861 	cache_unlock_all_buckets();
1862 	cache_unlock_all_vnodes();
1863 	free(old_nchashtbl, M_VFSCACHE);
1864 }
1865 
1866 /*
1867  * Invalidate all entries to a particular vnode.
1868  */
1869 void
1870 cache_purge(struct vnode *vp)
1871 {
1872 	TAILQ_HEAD(, namecache) ncps;
1873 	struct namecache *ncp, *nnp;
1874 	struct mtx *vlp, *vlp2;
1875 
1876 	CTR1(KTR_VFS, "cache_purge(%p)", vp);
1877 	SDT_PROBE1(vfs, namecache, purge, done, vp);
1878 	if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
1879 	    vp->v_cache_dd == NULL)
1880 		return;
1881 	TAILQ_INIT(&ncps);
1882 	vlp = VP2VNODELOCK(vp);
1883 	vlp2 = NULL;
1884 	mtx_lock(vlp);
1885 retry:
1886 	while (!LIST_EMPTY(&vp->v_cache_src)) {
1887 		ncp = LIST_FIRST(&vp->v_cache_src);
1888 		if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
1889 			goto retry;
1890 		TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
1891 	}
1892 	while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
1893 		ncp = TAILQ_FIRST(&vp->v_cache_dst);
1894 		if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
1895 			goto retry;
1896 		TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
1897 	}
1898 	ncp = vp->v_cache_dd;
1899 	if (ncp != NULL) {
1900 		KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
1901 		   ("lost dotdot link"));
1902 		if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
1903 			goto retry;
1904 		TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
1905 	}
1906 	KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
1907 	mtx_unlock(vlp);
1908 	if (vlp2 != NULL)
1909 		mtx_unlock(vlp2);
1910 	TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
1911 		cache_free(ncp);
1912 	}
1913 }
1914 
1915 /*
1916  * Invalidate all negative entries for a particular directory vnode.
1917  */
1918 void
1919 cache_purge_negative(struct vnode *vp)
1920 {
1921 	TAILQ_HEAD(, namecache) ncps;
1922 	struct namecache *ncp, *nnp;
1923 	struct mtx *vlp;
1924 
1925 	CTR1(KTR_VFS, "cache_purge_negative(%p)", vp);
1926 	SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
1927 	TAILQ_INIT(&ncps);
1928 	vlp = VP2VNODELOCK(vp);
1929 	mtx_lock(vlp);
1930 	LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
1931 		if (!(ncp->nc_flag & NCF_NEGATIVE))
1932 			continue;
1933 		cache_zap_negative_locked_vnode_kl(ncp, vp);
1934 		TAILQ_INSERT_TAIL(&ncps, ncp, nc_dst);
1935 	}
1936 	mtx_unlock(vlp);
1937 	TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
1938 		cache_free(ncp);
1939 	}
1940 }
1941 
1942 /*
1943  * Flush all entries referencing a particular filesystem.
1944  */
1945 void
1946 cache_purgevfs(struct mount *mp, bool force)
1947 {
1948 	TAILQ_HEAD(, namecache) ncps;
1949 	struct mtx *vlp1, *vlp2;
1950 	struct rwlock *blp;
1951 	struct nchashhead *bucket;
1952 	struct namecache *ncp, *nnp;
1953 	u_long i, j, n_nchash;
1954 	int error;
1955 
1956 	/* Scan hash tables for applicable entries */
1957 	SDT_PROBE1(vfs, namecache, purgevfs, done, mp);
1958 	if (!force && mp->mnt_nvnodelistsize <= ncpurgeminvnodes)
1959 		return;
1960 	TAILQ_INIT(&ncps);
1961 	n_nchash = nchash + 1;
1962 	vlp1 = vlp2 = NULL;
1963 	for (i = 0; i < numbucketlocks; i++) {
1964 		blp = (struct rwlock *)&bucketlocks[i];
1965 		rw_wlock(blp);
1966 		for (j = i; j < n_nchash; j += numbucketlocks) {
1967 retry:
1968 			bucket = &nchashtbl[j];
1969 			LIST_FOREACH_SAFE(ncp, bucket, nc_hash, nnp) {
1970 				cache_assert_bucket_locked(ncp, RA_WLOCKED);
1971 				if (ncp->nc_dvp->v_mount != mp)
1972 					continue;
1973 				error = cache_zap_wlocked_bucket_kl(ncp, blp,
1974 				    &vlp1, &vlp2);
1975 				if (error != 0)
1976 					goto retry;
1977 				TAILQ_INSERT_HEAD(&ncps, ncp, nc_dst);
1978 			}
1979 		}
1980 		rw_wunlock(blp);
1981 		if (vlp1 == NULL && vlp2 == NULL)
1982 			cache_maybe_yield();
1983 	}
1984 	if (vlp1 != NULL)
1985 		mtx_unlock(vlp1);
1986 	if (vlp2 != NULL)
1987 		mtx_unlock(vlp2);
1988 
1989 	TAILQ_FOREACH_SAFE(ncp, &ncps, nc_dst, nnp) {
1990 		cache_free(ncp);
1991 	}
1992 }
1993 
1994 /*
1995  * Perform canonical checks and cache lookup and pass on to filesystem
1996  * through the vop_cachedlookup only if needed.
1997  */
1998 
1999 int
2000 vfs_cache_lookup(struct vop_lookup_args *ap)
2001 {
2002 	struct vnode *dvp;
2003 	int error;
2004 	struct vnode **vpp = ap->a_vpp;
2005 	struct componentname *cnp = ap->a_cnp;
2006 	struct ucred *cred = cnp->cn_cred;
2007 	int flags = cnp->cn_flags;
2008 	struct thread *td = cnp->cn_thread;
2009 
2010 	*vpp = NULL;
2011 	dvp = ap->a_dvp;
2012 
2013 	if (dvp->v_type != VDIR)
2014 		return (ENOTDIR);
2015 
2016 	if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
2017 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
2018 		return (EROFS);
2019 
2020 	error = VOP_ACCESS(dvp, VEXEC, cred, td);
2021 	if (error)
2022 		return (error);
2023 
2024 	error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
2025 	if (error == 0)
2026 		return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
2027 	if (error == -1)
2028 		return (0);
2029 	return (error);
2030 }
2031 
2032 /*
2033  * XXX All of these sysctls would probably be more productive dead.
2034  */
2035 static int disablecwd;
2036 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0,
2037    "Disable the getcwd syscall");
2038 
2039 /* Implementation of the getcwd syscall. */
2040 int
2041 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
2042 {
2043 
2044 	return (kern___getcwd(td, uap->buf, UIO_USERSPACE, uap->buflen,
2045 	    MAXPATHLEN));
2046 }
2047 
2048 int
2049 kern___getcwd(struct thread *td, char *buf, enum uio_seg bufseg, u_int buflen,
2050     u_int path_max)
2051 {
2052 	char *bp, *tmpbuf;
2053 	struct filedesc *fdp;
2054 	struct vnode *cdir, *rdir;
2055 	int error;
2056 
2057 	if (__predict_false(disablecwd))
2058 		return (ENODEV);
2059 	if (__predict_false(buflen < 2))
2060 		return (EINVAL);
2061 	if (buflen > path_max)
2062 		buflen = path_max;
2063 
2064 	tmpbuf = malloc(buflen, M_TEMP, M_WAITOK);
2065 	fdp = td->td_proc->p_fd;
2066 	FILEDESC_SLOCK(fdp);
2067 	cdir = fdp->fd_cdir;
2068 	vrefact(cdir);
2069 	rdir = fdp->fd_rdir;
2070 	vrefact(rdir);
2071 	FILEDESC_SUNLOCK(fdp);
2072 	error = vn_fullpath1(td, cdir, rdir, tmpbuf, &bp, buflen);
2073 	vrele(rdir);
2074 	vrele(cdir);
2075 
2076 	if (!error) {
2077 		if (bufseg == UIO_SYSSPACE)
2078 			bcopy(bp, buf, strlen(bp) + 1);
2079 		else
2080 			error = copyout(bp, buf, strlen(bp) + 1);
2081 #ifdef KTRACE
2082 	if (KTRPOINT(curthread, KTR_NAMEI))
2083 		ktrnamei(bp);
2084 #endif
2085 	}
2086 	free(tmpbuf, M_TEMP);
2087 	return (error);
2088 }
2089 
2090 /*
2091  * Thus begins the fullpath magic.
2092  */
2093 
2094 static int disablefullpath;
2095 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW, &disablefullpath, 0,
2096     "Disable the vn_fullpath function");
2097 
2098 /*
2099  * Retrieve the full filesystem path that correspond to a vnode from the name
2100  * cache (if available)
2101  */
2102 int
2103 vn_fullpath(struct thread *td, struct vnode *vn, char **retbuf, char **freebuf)
2104 {
2105 	char *buf;
2106 	struct filedesc *fdp;
2107 	struct vnode *rdir;
2108 	int error;
2109 
2110 	if (__predict_false(disablefullpath))
2111 		return (ENODEV);
2112 	if (__predict_false(vn == NULL))
2113 		return (EINVAL);
2114 
2115 	buf = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
2116 	fdp = td->td_proc->p_fd;
2117 	FILEDESC_SLOCK(fdp);
2118 	rdir = fdp->fd_rdir;
2119 	VREF(rdir);
2120 	FILEDESC_SUNLOCK(fdp);
2121 	error = vn_fullpath1(td, vn, rdir, buf, retbuf, MAXPATHLEN);
2122 	vrele(rdir);
2123 
2124 	if (!error)
2125 		*freebuf = buf;
2126 	else
2127 		free(buf, M_TEMP);
2128 	return (error);
2129 }
2130 
2131 /*
2132  * This function is similar to vn_fullpath, but it attempts to lookup the
2133  * pathname relative to the global root mount point.  This is required for the
2134  * auditing sub-system, as audited pathnames must be absolute, relative to the
2135  * global root mount point.
2136  */
2137 int
2138 vn_fullpath_global(struct thread *td, struct vnode *vn,
2139     char **retbuf, char **freebuf)
2140 {
2141 	char *buf;
2142 	int error;
2143 
2144 	if (__predict_false(disablefullpath))
2145 		return (ENODEV);
2146 	if (__predict_false(vn == NULL))
2147 		return (EINVAL);
2148 	buf = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
2149 	error = vn_fullpath1(td, vn, rootvnode, buf, retbuf, MAXPATHLEN);
2150 	if (!error)
2151 		*freebuf = buf;
2152 	else
2153 		free(buf, M_TEMP);
2154 	return (error);
2155 }
2156 
2157 int
2158 vn_vptocnp(struct vnode **vp, struct ucred *cred, char *buf, u_int *buflen)
2159 {
2160 	struct vnode *dvp;
2161 	struct namecache *ncp;
2162 	struct mtx *vlp;
2163 	int error;
2164 
2165 	vlp = VP2VNODELOCK(*vp);
2166 	mtx_lock(vlp);
2167 	TAILQ_FOREACH(ncp, &((*vp)->v_cache_dst), nc_dst) {
2168 		if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2169 			break;
2170 	}
2171 	if (ncp != NULL) {
2172 		if (*buflen < ncp->nc_nlen) {
2173 			mtx_unlock(vlp);
2174 			vrele(*vp);
2175 			counter_u64_add(numfullpathfail4, 1);
2176 			error = ENOMEM;
2177 			SDT_PROBE3(vfs, namecache, fullpath, return, error,
2178 			    vp, NULL);
2179 			return (error);
2180 		}
2181 		*buflen -= ncp->nc_nlen;
2182 		memcpy(buf + *buflen, nc_get_name(ncp), ncp->nc_nlen);
2183 		SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
2184 		    nc_get_name(ncp), vp);
2185 		dvp = *vp;
2186 		*vp = ncp->nc_dvp;
2187 		vref(*vp);
2188 		mtx_unlock(vlp);
2189 		vrele(dvp);
2190 		return (0);
2191 	}
2192 	SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
2193 
2194 	mtx_unlock(vlp);
2195 	vn_lock(*vp, LK_SHARED | LK_RETRY);
2196 	error = VOP_VPTOCNP(*vp, &dvp, cred, buf, buflen);
2197 	vput(*vp);
2198 	if (error) {
2199 		counter_u64_add(numfullpathfail2, 1);
2200 		SDT_PROBE3(vfs, namecache, fullpath, return,  error, vp, NULL);
2201 		return (error);
2202 	}
2203 
2204 	*vp = dvp;
2205 	if (dvp->v_iflag & VI_DOOMED) {
2206 		/* forced unmount */
2207 		vrele(dvp);
2208 		error = ENOENT;
2209 		SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
2210 		return (error);
2211 	}
2212 	/*
2213 	 * *vp has its use count incremented still.
2214 	 */
2215 
2216 	return (0);
2217 }
2218 
2219 /*
2220  * The magic behind kern___getcwd() and vn_fullpath().
2221  */
2222 static int
2223 vn_fullpath1(struct thread *td, struct vnode *vp, struct vnode *rdir,
2224     char *buf, char **retbuf, u_int buflen)
2225 {
2226 	int error, slash_prefixed;
2227 #ifdef KDTRACE_HOOKS
2228 	struct vnode *startvp = vp;
2229 #endif
2230 	struct vnode *vp1;
2231 
2232 	buflen--;
2233 	buf[buflen] = '\0';
2234 	error = 0;
2235 	slash_prefixed = 0;
2236 
2237 	SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
2238 	counter_u64_add(numfullpathcalls, 1);
2239 	vref(vp);
2240 	if (vp->v_type != VDIR) {
2241 		error = vn_vptocnp(&vp, td->td_ucred, buf, &buflen);
2242 		if (error)
2243 			return (error);
2244 		if (buflen == 0) {
2245 			vrele(vp);
2246 			return (ENOMEM);
2247 		}
2248 		buf[--buflen] = '/';
2249 		slash_prefixed = 1;
2250 	}
2251 	while (vp != rdir && vp != rootvnode) {
2252 		/*
2253 		 * The vp vnode must be already fully constructed,
2254 		 * since it is either found in namecache or obtained
2255 		 * from VOP_VPTOCNP().  We may test for VV_ROOT safely
2256 		 * without obtaining the vnode lock.
2257 		 */
2258 		if ((vp->v_vflag & VV_ROOT) != 0) {
2259 			vn_lock(vp, LK_RETRY | LK_SHARED);
2260 
2261 			/*
2262 			 * With the vnode locked, check for races with
2263 			 * unmount, forced or not.  Note that we
2264 			 * already verified that vp is not equal to
2265 			 * the root vnode, which means that
2266 			 * mnt_vnodecovered can be NULL only for the
2267 			 * case of unmount.
2268 			 */
2269 			if ((vp->v_iflag & VI_DOOMED) != 0 ||
2270 			    (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
2271 			    vp1->v_mountedhere != vp->v_mount) {
2272 				vput(vp);
2273 				error = ENOENT;
2274 				SDT_PROBE3(vfs, namecache, fullpath, return,
2275 				    error, vp, NULL);
2276 				break;
2277 			}
2278 
2279 			vref(vp1);
2280 			vput(vp);
2281 			vp = vp1;
2282 			continue;
2283 		}
2284 		if (vp->v_type != VDIR) {
2285 			vrele(vp);
2286 			counter_u64_add(numfullpathfail1, 1);
2287 			error = ENOTDIR;
2288 			SDT_PROBE3(vfs, namecache, fullpath, return,
2289 			    error, vp, NULL);
2290 			break;
2291 		}
2292 		error = vn_vptocnp(&vp, td->td_ucred, buf, &buflen);
2293 		if (error)
2294 			break;
2295 		if (buflen == 0) {
2296 			vrele(vp);
2297 			error = ENOMEM;
2298 			SDT_PROBE3(vfs, namecache, fullpath, return, error,
2299 			    startvp, NULL);
2300 			break;
2301 		}
2302 		buf[--buflen] = '/';
2303 		slash_prefixed = 1;
2304 	}
2305 	if (error)
2306 		return (error);
2307 	if (!slash_prefixed) {
2308 		if (buflen == 0) {
2309 			vrele(vp);
2310 			counter_u64_add(numfullpathfail4, 1);
2311 			SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
2312 			    startvp, NULL);
2313 			return (ENOMEM);
2314 		}
2315 		buf[--buflen] = '/';
2316 	}
2317 	counter_u64_add(numfullpathfound, 1);
2318 	vrele(vp);
2319 
2320 	SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, buf + buflen);
2321 	*retbuf = buf + buflen;
2322 	return (0);
2323 }
2324 
2325 struct vnode *
2326 vn_dir_dd_ino(struct vnode *vp)
2327 {
2328 	struct namecache *ncp;
2329 	struct vnode *ddvp;
2330 	struct mtx *vlp;
2331 
2332 	ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
2333 	vlp = VP2VNODELOCK(vp);
2334 	mtx_lock(vlp);
2335 	TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
2336 		if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
2337 			continue;
2338 		ddvp = ncp->nc_dvp;
2339 		vhold(ddvp);
2340 		mtx_unlock(vlp);
2341 		if (vget(ddvp, LK_SHARED | LK_NOWAIT | LK_VNHELD, curthread))
2342 			return (NULL);
2343 		return (ddvp);
2344 	}
2345 	mtx_unlock(vlp);
2346 	return (NULL);
2347 }
2348 
2349 int
2350 vn_commname(struct vnode *vp, char *buf, u_int buflen)
2351 {
2352 	struct namecache *ncp;
2353 	struct mtx *vlp;
2354 	int l;
2355 
2356 	vlp = VP2VNODELOCK(vp);
2357 	mtx_lock(vlp);
2358 	TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
2359 		if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
2360 			break;
2361 	if (ncp == NULL) {
2362 		mtx_unlock(vlp);
2363 		return (ENOENT);
2364 	}
2365 	l = min(ncp->nc_nlen, buflen - 1);
2366 	memcpy(buf, nc_get_name(ncp), l);
2367 	mtx_unlock(vlp);
2368 	buf[l] = '\0';
2369 	return (0);
2370 }
2371 
2372 /* ABI compat shims for old kernel modules. */
2373 #undef cache_enter
2374 
2375 void	cache_enter(struct vnode *dvp, struct vnode *vp,
2376 	    struct componentname *cnp);
2377 
2378 void
2379 cache_enter(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2380 {
2381 
2382 	cache_enter_time(dvp, vp, cnp, NULL, NULL);
2383 }
2384 
2385 /*
2386  * This function updates path string to vnode's full global path
2387  * and checks the size of the new path string against the pathlen argument.
2388  *
2389  * Requires a locked, referenced vnode.
2390  * Vnode is re-locked on success or ENODEV, otherwise unlocked.
2391  *
2392  * If sysctl debug.disablefullpath is set, ENODEV is returned,
2393  * vnode is left locked and path remain untouched.
2394  *
2395  * If vp is a directory, the call to vn_fullpath_global() always succeeds
2396  * because it falls back to the ".." lookup if the namecache lookup fails.
2397  */
2398 int
2399 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
2400     u_int pathlen)
2401 {
2402 	struct nameidata nd;
2403 	struct vnode *vp1;
2404 	char *rpath, *fbuf;
2405 	int error;
2406 
2407 	ASSERT_VOP_ELOCKED(vp, __func__);
2408 
2409 	/* Return ENODEV if sysctl debug.disablefullpath==1 */
2410 	if (__predict_false(disablefullpath))
2411 		return (ENODEV);
2412 
2413 	/* Construct global filesystem path from vp. */
2414 	VOP_UNLOCK(vp, 0);
2415 	error = vn_fullpath_global(td, vp, &rpath, &fbuf);
2416 
2417 	if (error != 0) {
2418 		vrele(vp);
2419 		return (error);
2420 	}
2421 
2422 	if (strlen(rpath) >= pathlen) {
2423 		vrele(vp);
2424 		error = ENAMETOOLONG;
2425 		goto out;
2426 	}
2427 
2428 	/*
2429 	 * Re-lookup the vnode by path to detect a possible rename.
2430 	 * As a side effect, the vnode is relocked.
2431 	 * If vnode was renamed, return ENOENT.
2432 	 */
2433 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
2434 	    UIO_SYSSPACE, path, td);
2435 	error = namei(&nd);
2436 	if (error != 0) {
2437 		vrele(vp);
2438 		goto out;
2439 	}
2440 	NDFREE(&nd, NDF_ONLY_PNBUF);
2441 	vp1 = nd.ni_vp;
2442 	vrele(vp);
2443 	if (vp1 == vp)
2444 		strcpy(path, rpath);
2445 	else {
2446 		vput(vp1);
2447 		error = ENOENT;
2448 	}
2449 
2450 out:
2451 	free(fbuf, M_TEMP);
2452 	return (error);
2453 }
2454