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