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