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