]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_cache.c
cache: use counter(9) API to maintain statistics
[FreeBSD/FreeBSD.git] / sys / kern / vfs_cache.c
1 /*-
2  * Copyright (c) 1989, 1993, 1995
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Poul-Henning Kamp of the FreeBSD Project.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      @(#)vfs_cache.c 8.5 (Berkeley) 3/22/95
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include "opt_ktrace.h"
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/counter.h>
43 #include <sys/filedesc.h>
44 #include <sys/fnv_hash.h>
45 #include <sys/kernel.h>
46 #include <sys/lock.h>
47 #include <sys/malloc.h>
48 #include <sys/fcntl.h>
49 #include <sys/mount.h>
50 #include <sys/namei.h>
51 #include <sys/proc.h>
52 #include <sys/rwlock.h>
53 #include <sys/sdt.h>
54 #include <sys/syscallsubr.h>
55 #include <sys/sysctl.h>
56 #include <sys/sysproto.h>
57 #include <sys/vnode.h>
58 #ifdef KTRACE
59 #include <sys/ktrace.h>
60 #endif
61
62 #include <vm/uma.h>
63
64 SDT_PROVIDER_DECLARE(vfs);
65 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
66     "struct vnode *");
67 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
68     "char *");
69 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
70 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
71     "char *", "struct vnode *");
72 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
73 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
74     "struct vnode *", "char *");
75 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
76     "struct vnode *");
77 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
78     "struct vnode *", "char *");
79 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
80     "char *");
81 SDT_PROBE_DEFINE1(vfs, namecache, purge, done, "struct vnode *");
82 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
83 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
84 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
85     "struct vnode *");
86 SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
87     "char *");
88
89 /*
90  * This structure describes the elements in the cache of recent
91  * names looked up by namei.
92  */
93
94 struct  namecache {
95         LIST_ENTRY(namecache) nc_hash;  /* hash chain */
96         LIST_ENTRY(namecache) nc_src;   /* source vnode list */
97         TAILQ_ENTRY(namecache) nc_dst;  /* destination vnode list */
98         struct  vnode *nc_dvp;          /* vnode of parent of name */
99         struct  vnode *nc_vp;           /* vnode the name refers to */
100         u_char  nc_flag;                /* flag bits */
101         u_char  nc_nlen;                /* length of name */
102         char    nc_name[0];             /* segment name + nul */
103 };
104
105 /*
106  * struct namecache_ts repeats struct namecache layout up to the
107  * nc_nlen member.
108  * struct namecache_ts is used in place of struct namecache when time(s) need
109  * to be stored.  The nc_dotdottime field is used when a cache entry is mapping
110  * both a non-dotdot directory name plus dotdot for the directory's
111  * parent.
112  */
113 struct  namecache_ts {
114         LIST_ENTRY(namecache) nc_hash;  /* hash chain */
115         LIST_ENTRY(namecache) nc_src;   /* source vnode list */
116         TAILQ_ENTRY(namecache) nc_dst;  /* destination vnode list */
117         struct  vnode *nc_dvp;          /* vnode of parent of name */
118         struct  vnode *nc_vp;           /* vnode the name refers to */
119         u_char  nc_flag;                /* flag bits */
120         u_char  nc_nlen;                /* length of name */
121         struct  timespec nc_time;       /* timespec provided by fs */
122         struct  timespec nc_dotdottime; /* dotdot timespec provided by fs */
123         int     nc_ticks;               /* ticks value when entry was added */
124         char    nc_name[0];             /* segment name + nul */
125 };
126
127 /*
128  * Flags in namecache.nc_flag
129  */
130 #define NCF_WHITE       0x01
131 #define NCF_ISDOTDOT    0x02
132 #define NCF_TS          0x04
133 #define NCF_DTS         0x08
134
135 /*
136  * Name caching works as follows:
137  *
138  * Names found by directory scans are retained in a cache
139  * for future reference.  It is managed LRU, so frequently
140  * used names will hang around.  Cache is indexed by hash value
141  * obtained from (vp, name) where vp refers to the directory
142  * containing name.
143  *
144  * If it is a "negative" entry, (i.e. for a name that is known NOT to
145  * exist) the vnode pointer will be NULL.
146  *
147  * Upon reaching the last segment of a path, if the reference
148  * is for DELETE, or NOCACHE is set (rewrite), and the
149  * name is located in the cache, it will be dropped.
150  */
151
152 /*
153  * Structures associated with name cacheing.
154  */
155 #define NCHHASH(hash) \
156         (&nchashtbl[(hash) & nchash])
157 static LIST_HEAD(nchashhead, namecache) *nchashtbl;     /* Hash Table */
158 static TAILQ_HEAD(, namecache) ncneg;   /* Hash Table */
159 static u_long   nchash;                 /* size of hash table */
160 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
161     "Size of namecache hash table");
162 static u_long   ncnegfactor = 16;       /* ratio of negative entries */
163 SYSCTL_ULONG(_vfs, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0,
164     "Ratio of negative namecache entries");
165 static u_long   numneg;                 /* number of negative entries allocated */
166 SYSCTL_ULONG(_debug, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0,
167     "Number of negative entries in namecache");
168 static u_long   numcache;               /* number of cache entries allocated */
169 SYSCTL_ULONG(_debug, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0,
170     "Number of namecache entries");
171 static u_long   numcachehv;             /* number of cache entries with vnodes held */
172 SYSCTL_ULONG(_debug, OID_AUTO, numcachehv, CTLFLAG_RD, &numcachehv, 0,
173     "Number of namecache entries with vnodes held");
174 static u_int    ncsizefactor = 2;
175 SYSCTL_UINT(_vfs, OID_AUTO, ncsizefactor, CTLFLAG_RW, &ncsizefactor, 0,
176     "Size factor for namecache");
177
178 struct nchstats nchstats;               /* cache effectiveness statistics */
179
180 static struct rwlock cache_lock;
181 RW_SYSINIT(vfscache, &cache_lock, "Name Cache");
182
183 #define CACHE_UPGRADE_LOCK()    rw_try_upgrade(&cache_lock)
184 #define CACHE_RLOCK()           rw_rlock(&cache_lock)
185 #define CACHE_RUNLOCK()         rw_runlock(&cache_lock)
186 #define CACHE_WLOCK()           rw_wlock(&cache_lock)
187 #define CACHE_WUNLOCK()         rw_wunlock(&cache_lock)
188
189 /*
190  * UMA zones for the VFS cache.
191  *
192  * The small cache is used for entries with short names, which are the
193  * most common.  The large cache is used for entries which are too big to
194  * fit in the small cache.
195  */
196 static uma_zone_t cache_zone_small;
197 static uma_zone_t cache_zone_small_ts;
198 static uma_zone_t cache_zone_large;
199 static uma_zone_t cache_zone_large_ts;
200
201 #define CACHE_PATH_CUTOFF       35
202
203 static struct namecache *
204 cache_alloc(int len, int ts)
205 {
206
207         if (len > CACHE_PATH_CUTOFF) {
208                 if (ts)
209                         return (uma_zalloc(cache_zone_large_ts, M_WAITOK));
210                 else
211                         return (uma_zalloc(cache_zone_large, M_WAITOK));
212         }
213         if (ts)
214                 return (uma_zalloc(cache_zone_small_ts, M_WAITOK));
215         else
216                 return (uma_zalloc(cache_zone_small, M_WAITOK));
217 }
218
219 static void
220 cache_free(struct namecache *ncp)
221 {
222         int ts;
223
224         if (ncp == NULL)
225                 return;
226         ts = ncp->nc_flag & NCF_TS;
227         if (ncp->nc_nlen <= CACHE_PATH_CUTOFF) {
228                 if (ts)
229                         uma_zfree(cache_zone_small_ts, ncp);
230                 else
231                         uma_zfree(cache_zone_small, ncp);
232         } else if (ts)
233                 uma_zfree(cache_zone_large_ts, ncp);
234         else
235                 uma_zfree(cache_zone_large, ncp);
236 }
237
238 static char *
239 nc_get_name(struct namecache *ncp)
240 {
241         struct namecache_ts *ncp_ts;
242
243         if ((ncp->nc_flag & NCF_TS) == 0)
244                 return (ncp->nc_name);
245         ncp_ts = (struct namecache_ts *)ncp;
246         return (ncp_ts->nc_name);
247 }
248
249 static void
250 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
251 {
252
253         KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
254             (tsp == NULL && ticksp == NULL),
255             ("No NCF_TS"));
256
257         if (tsp != NULL)
258                 *tsp = ((struct namecache_ts *)ncp)->nc_time;
259         if (ticksp != NULL)
260                 *ticksp = ((struct namecache_ts *)ncp)->nc_ticks;
261 }
262
263 static int      doingcache = 1;         /* 1 => enable the cache */
264 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
265     "VFS namecache enabled");
266
267 /* Export size information to userland */
268 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
269     sizeof(struct namecache), "sizeof(struct namecache)");
270
271 /*
272  * The new name cache statistics
273  */
274 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0,
275     "Name cache statistics");
276 #define STATNODE_ULONG(name, descr)     \
277         SYSCTL_ULONG(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, descr);
278 #define STATNODE_COUNTER(name, descr)   \
279         static counter_u64_t name;      \
280         SYSCTL_COUNTER_U64(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, descr);
281 STATNODE_ULONG(numneg, "Number of negative cache entries");
282 STATNODE_ULONG(numcache, "Number of cache entries");
283 STATNODE_COUNTER(numcalls, "Number of cache lookups");
284 STATNODE_COUNTER(dothits, "Number of '.' hits");
285 STATNODE_COUNTER(dotdothits, "Number of '..' hits");
286 STATNODE_COUNTER(numchecks, "Number of checks in lookup");
287 STATNODE_COUNTER(nummiss, "Number of cache misses");
288 STATNODE_COUNTER(nummisszap, "Number of cache misses we do not want to cache");
289 STATNODE_COUNTER(numposzaps,
290     "Number of cache hits (positive) we do not want to cache");
291 STATNODE_COUNTER(numposhits, "Number of cache hits (positive)");
292 STATNODE_COUNTER(numnegzaps,
293     "Number of cache hits (negative) we do not want to cache");
294 STATNODE_COUNTER(numneghits, "Number of cache hits (negative)");
295 /* These count for kern___getcwd(), too. */
296 STATNODE_COUNTER(numfullpathcalls, "Number of fullpath search calls");
297 STATNODE_COUNTER(numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
298 STATNODE_COUNTER(numfullpathfail2,
299     "Number of fullpath search errors (VOP_VPTOCNP failures)");
300 STATNODE_COUNTER(numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
301 STATNODE_COUNTER(numfullpathfound, "Number of successful fullpath calls");
302 static long numupgrades; STATNODE_ULONG(numupgrades,
303     "Number of updates of the cache after lookup (write lock + retry)");
304
305 static void cache_zap(struct namecache *ncp);
306 static int vn_vptocnp_locked(struct vnode **vp, struct ucred *cred, char *buf,
307     u_int *buflen);
308 static int vn_fullpath1(struct thread *td, struct vnode *vp, struct vnode *rdir,
309     char *buf, char **retbuf, u_int buflen);
310
311 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
312
313 static int
314 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
315 {
316         struct nchstats snap;
317
318         if (req->oldptr == NULL)
319                 return (SYSCTL_OUT(req, 0, sizeof(snap)));
320
321         snap = nchstats;
322         snap.ncs_goodhits = counter_u64_fetch(numposhits);
323         snap.ncs_neghits = counter_u64_fetch(numneghits);
324         snap.ncs_badhits = counter_u64_fetch(numposzaps) +
325             counter_u64_fetch(numnegzaps);
326         snap.ncs_miss = counter_u64_fetch(nummisszap) +
327             counter_u64_fetch(nummiss);
328
329         return (SYSCTL_OUT(req, &snap, sizeof(snap)));
330 }
331 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
332     CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
333     "VFS cache effectiveness statistics");
334
335 #ifdef DIAGNOSTIC
336 /*
337  * Grab an atomic snapshot of the name cache hash chain lengths
338  */
339 static SYSCTL_NODE(_debug, OID_AUTO, hashstat, CTLFLAG_RW, NULL,
340     "hash table stats");
341
342 static int
343 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
344 {
345         struct nchashhead *ncpp;
346         struct namecache *ncp;
347         int i, error, n_nchash, *cntbuf;
348
349 retry:
350         n_nchash = nchash + 1;  /* nchash is max index, not count */
351         if (req->oldptr == NULL)
352                 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
353         cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
354         CACHE_RLOCK();
355         if (n_nchash != nchash + 1) {
356                 CACHE_RUNLOCK();
357                 free(cntbuf, M_TEMP);
358                 goto retry;
359         }
360         /* Scan hash tables counting entries */
361         for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
362                 LIST_FOREACH(ncp, ncpp, nc_hash)
363                         cntbuf[i]++;
364         CACHE_RUNLOCK();
365         for (error = 0, i = 0; i < n_nchash; i++)
366                 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
367                         break;
368         free(cntbuf, M_TEMP);
369         return (error);
370 }
371 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
372     CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
373     "nchash chain lengths");
374
375 static int
376 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
377 {
378         int error;
379         struct nchashhead *ncpp;
380         struct namecache *ncp;
381         int n_nchash;
382         int count, maxlength, used, pct;
383
384         if (!req->oldptr)
385                 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
386
387         CACHE_RLOCK();
388         n_nchash = nchash + 1;  /* nchash is max index, not count */
389         used = 0;
390         maxlength = 0;
391
392         /* Scan hash tables for applicable entries */
393         for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
394                 count = 0;
395                 LIST_FOREACH(ncp, ncpp, nc_hash) {
396                         count++;
397                 }
398                 if (count)
399                         used++;
400                 if (maxlength < count)
401                         maxlength = count;
402         }
403         n_nchash = nchash + 1;
404         CACHE_RUNLOCK();
405         pct = (used * 100) / (n_nchash / 100);
406         error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
407         if (error)
408                 return (error);
409         error = SYSCTL_OUT(req, &used, sizeof(used));
410         if (error)
411                 return (error);
412         error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
413         if (error)
414                 return (error);
415         error = SYSCTL_OUT(req, &pct, sizeof(pct));
416         if (error)
417                 return (error);
418         return (0);
419 }
420 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
421     CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
422     "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
423 #endif
424
425 /*
426  * cache_zap():
427  *
428  *   Removes a namecache entry from cache, whether it contains an actual
429  *   pointer to a vnode or if it is just a negative cache entry.
430  */
431 static void
432 cache_zap(struct namecache *ncp)
433 {
434         struct vnode *vp;
435
436         rw_assert(&cache_lock, RA_WLOCKED);
437         CTR2(KTR_VFS, "cache_zap(%p) vp %p", ncp, ncp->nc_vp);
438         if (ncp->nc_vp != NULL) {
439                 SDT_PROBE3(vfs, namecache, zap, done, ncp->nc_dvp,
440                     nc_get_name(ncp), ncp->nc_vp);
441         } else {
442                 SDT_PROBE2(vfs, namecache, zap_negative, done, ncp->nc_dvp,
443                     nc_get_name(ncp));
444         }
445         vp = NULL;
446         LIST_REMOVE(ncp, nc_hash);
447         if (ncp->nc_flag & NCF_ISDOTDOT) {
448                 if (ncp == ncp->nc_dvp->v_cache_dd)
449                         ncp->nc_dvp->v_cache_dd = NULL;
450         } else {
451                 LIST_REMOVE(ncp, nc_src);
452                 if (LIST_EMPTY(&ncp->nc_dvp->v_cache_src)) {
453                         vp = ncp->nc_dvp;
454                         numcachehv--;
455                 }
456         }
457         if (ncp->nc_vp) {
458                 TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst, ncp, nc_dst);
459                 if (ncp == ncp->nc_vp->v_cache_dd)
460                         ncp->nc_vp->v_cache_dd = NULL;
461         } else {
462                 TAILQ_REMOVE(&ncneg, ncp, nc_dst);
463                 numneg--;
464         }
465         numcache--;
466         cache_free(ncp);
467         if (vp != NULL)
468                 vdrop(vp);
469 }
470
471 /*
472  * Lookup an entry in the cache
473  *
474  * Lookup is called with dvp pointing to the directory to search,
475  * cnp pointing to the name of the entry being sought. If the lookup
476  * succeeds, the vnode is returned in *vpp, and a status of -1 is
477  * returned. If the lookup determines that the name does not exist
478  * (negative cacheing), a status of ENOENT is returned. If the lookup
479  * fails, a status of zero is returned.  If the directory vnode is
480  * recycled out from under us due to a forced unmount, a status of
481  * ENOENT is returned.
482  *
483  * vpp is locked and ref'd on return.  If we're looking up DOTDOT, dvp is
484  * unlocked.  If we're looking up . an extra ref is taken, but the lock is
485  * not recursively acquired.
486  */
487
488 int
489 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
490     struct timespec *tsp, int *ticksp)
491 {
492         struct namecache *ncp;
493         uint32_t hash;
494         int error, ltype, wlocked;
495
496         if (!doingcache) {
497                 cnp->cn_flags &= ~MAKEENTRY;
498                 return (0);
499         }
500 retry:
501         CACHE_RLOCK();
502         wlocked = 0;
503         counter_u64_add(numcalls, 1);
504         error = 0;
505
506 retry_wlocked:
507         if (cnp->cn_nameptr[0] == '.') {
508                 if (cnp->cn_namelen == 1) {
509                         *vpp = dvp;
510                         CTR2(KTR_VFS, "cache_lookup(%p, %s) found via .",
511                             dvp, cnp->cn_nameptr);
512                         counter_u64_add(dothits, 1);
513                         SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
514                         if (tsp != NULL)
515                                 timespecclear(tsp);
516                         if (ticksp != NULL)
517                                 *ticksp = ticks;
518                         goto success;
519                 }
520                 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
521                         counter_u64_add(dotdothits, 1);
522                         if (dvp->v_cache_dd == NULL) {
523                                 SDT_PROBE3(vfs, namecache, lookup, miss, dvp,
524                                     "..", NULL);
525                                 goto unlock;
526                         }
527                         if ((cnp->cn_flags & MAKEENTRY) == 0) {
528                                 if (!wlocked && !CACHE_UPGRADE_LOCK())
529                                         goto wlock;
530                                 if (dvp->v_cache_dd->nc_flag & NCF_ISDOTDOT)
531                                         cache_zap(dvp->v_cache_dd);
532                                 dvp->v_cache_dd = NULL;
533                                 CACHE_WUNLOCK();
534                                 return (0);
535                         }
536                         ncp = dvp->v_cache_dd;
537                         if (ncp->nc_flag & NCF_ISDOTDOT)
538                                 *vpp = ncp->nc_vp;
539                         else
540                                 *vpp = ncp->nc_dvp;
541                         /* Return failure if negative entry was found. */
542                         if (*vpp == NULL)
543                                 goto negative_success;
544                         CTR3(KTR_VFS, "cache_lookup(%p, %s) found %p via ..",
545                             dvp, cnp->cn_nameptr, *vpp);
546                         SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..",
547                             *vpp);
548                         cache_out_ts(ncp, tsp, ticksp);
549                         if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
550                             NCF_DTS && tsp != NULL)
551                                 *tsp = ((struct namecache_ts *)ncp)->
552                                     nc_dotdottime;
553                         goto success;
554                 }
555         }
556
557         hash = fnv_32_buf(cnp->cn_nameptr, cnp->cn_namelen, FNV1_32_INIT);
558         hash = fnv_32_buf(&dvp, sizeof(dvp), hash);
559         LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
560                 counter_u64_add(numchecks, 1);
561                 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
562                     !bcmp(nc_get_name(ncp), cnp->cn_nameptr, ncp->nc_nlen))
563                         break;
564         }
565
566         /* We failed to find an entry */
567         if (ncp == NULL) {
568                 SDT_PROBE3(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr,
569                     NULL);
570                 if ((cnp->cn_flags & MAKEENTRY) == 0) {
571                         counter_u64_add(nummisszap, 1);
572                 } else {
573                         counter_u64_add(nummiss, 1);
574                 }
575                 goto unlock;
576         }
577
578         /* We don't want to have an entry, so dump it */
579         if ((cnp->cn_flags & MAKEENTRY) == 0) {
580                 counter_u64_add(numposzaps, 1);
581                 if (!wlocked && !CACHE_UPGRADE_LOCK())
582                         goto wlock;
583                 cache_zap(ncp);
584                 CACHE_WUNLOCK();
585                 return (0);
586         }
587
588         /* We found a "positive" match, return the vnode */
589         if (ncp->nc_vp) {
590                 counter_u64_add(numposhits, 1);
591                 *vpp = ncp->nc_vp;
592                 CTR4(KTR_VFS, "cache_lookup(%p, %s) found %p via ncp %p",
593                     dvp, cnp->cn_nameptr, *vpp, ncp);
594                 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, nc_get_name(ncp),
595                     *vpp);
596                 cache_out_ts(ncp, tsp, ticksp);
597                 goto success;
598         }
599
600 negative_success:
601         /* We found a negative match, and want to create it, so purge */
602         if (cnp->cn_nameiop == CREATE) {
603                 counter_u64_add(numnegzaps, 1);
604                 if (!wlocked && !CACHE_UPGRADE_LOCK())
605                         goto wlock;
606                 cache_zap(ncp);
607                 CACHE_WUNLOCK();
608                 return (0);
609         }
610
611         if (!wlocked && !CACHE_UPGRADE_LOCK())
612                 goto wlock;
613         counter_u64_add(numneghits, 1);
614         /*
615          * We found a "negative" match, so we shift it to the end of
616          * the "negative" cache entries queue to satisfy LRU.  Also,
617          * check to see if the entry is a whiteout; indicate this to
618          * the componentname, if so.
619          */
620         TAILQ_REMOVE(&ncneg, ncp, nc_dst);
621         TAILQ_INSERT_TAIL(&ncneg, ncp, nc_dst);
622         if (ncp->nc_flag & NCF_WHITE)
623                 cnp->cn_flags |= ISWHITEOUT;
624         SDT_PROBE2(vfs, namecache, lookup, hit__negative, dvp,
625             nc_get_name(ncp));
626         cache_out_ts(ncp, tsp, ticksp);
627         CACHE_WUNLOCK();
628         return (ENOENT);
629
630 wlock:
631         /*
632          * We need to update the cache after our lookup, so upgrade to
633          * a write lock and retry the operation.
634          */
635         CACHE_RUNLOCK();
636         CACHE_WLOCK();
637         numupgrades++;
638         wlocked = 1;
639         goto retry_wlocked;
640
641 success:
642         /*
643          * On success we return a locked and ref'd vnode as per the lookup
644          * protocol.
645          */
646         if (dvp == *vpp) {   /* lookup on "." */
647                 VREF(*vpp);
648                 if (wlocked)
649                         CACHE_WUNLOCK();
650                 else
651                         CACHE_RUNLOCK();
652                 /*
653                  * When we lookup "." we still can be asked to lock it
654                  * differently...
655                  */
656                 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
657                 if (ltype != VOP_ISLOCKED(*vpp)) {
658                         if (ltype == LK_EXCLUSIVE) {
659                                 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
660                                 if ((*vpp)->v_iflag & VI_DOOMED) {
661                                         /* forced unmount */
662                                         vrele(*vpp);
663                                         *vpp = NULL;
664                                         return (ENOENT);
665                                 }
666                         } else
667                                 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
668                 }
669                 return (-1);
670         }
671         ltype = 0;      /* silence gcc warning */
672         if (cnp->cn_flags & ISDOTDOT) {
673                 ltype = VOP_ISLOCKED(dvp);
674                 VOP_UNLOCK(dvp, 0);
675         }
676         vhold(*vpp);
677         if (wlocked)
678                 CACHE_WUNLOCK();
679         else
680                 CACHE_RUNLOCK();
681         error = vget(*vpp, cnp->cn_lkflags | LK_VNHELD, cnp->cn_thread);
682         if (cnp->cn_flags & ISDOTDOT) {
683                 vn_lock(dvp, ltype | LK_RETRY);
684                 if (dvp->v_iflag & VI_DOOMED) {
685                         if (error == 0)
686                                 vput(*vpp);
687                         *vpp = NULL;
688                         return (ENOENT);
689                 }
690         }
691         if (error) {
692                 *vpp = NULL;
693                 goto retry;
694         }
695         if ((cnp->cn_flags & ISLASTCN) &&
696             (cnp->cn_lkflags & LK_TYPE_MASK) == LK_EXCLUSIVE) {
697                 ASSERT_VOP_ELOCKED(*vpp, "cache_lookup");
698         }
699         return (-1);
700
701 unlock:
702         if (wlocked)
703                 CACHE_WUNLOCK();
704         else
705                 CACHE_RUNLOCK();
706         return (0);
707 }
708
709 /*
710  * Add an entry to the cache.
711  */
712 void
713 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
714     struct timespec *tsp, struct timespec *dtsp)
715 {
716         struct namecache *ncp, *n2;
717         struct namecache_ts *n3;
718         struct nchashhead *ncpp;
719         uint32_t hash;
720         int flag;
721         int hold;
722         int zap;
723         int len;
724
725         CTR3(KTR_VFS, "cache_enter(%p, %p, %s)", dvp, vp, cnp->cn_nameptr);
726         VNASSERT(vp == NULL || (vp->v_iflag & VI_DOOMED) == 0, vp,
727             ("cache_enter: Adding a doomed vnode"));
728         VNASSERT(dvp == NULL || (dvp->v_iflag & VI_DOOMED) == 0, dvp,
729             ("cache_enter: Doomed vnode used as src"));
730
731         if (!doingcache)
732                 return;
733
734         /*
735          * Avoid blowout in namecache entries.
736          */
737         if (numcache >= desiredvnodes * ncsizefactor)
738                 return;
739
740         flag = 0;
741         if (cnp->cn_nameptr[0] == '.') {
742                 if (cnp->cn_namelen == 1)
743                         return;
744                 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
745                         CACHE_WLOCK();
746                         /*
747                          * If dotdot entry already exists, just retarget it
748                          * to new parent vnode, otherwise continue with new
749                          * namecache entry allocation.
750                          */
751                         if ((ncp = dvp->v_cache_dd) != NULL &&
752                             ncp->nc_flag & NCF_ISDOTDOT) {
753                                 KASSERT(ncp->nc_dvp == dvp,
754                                     ("wrong isdotdot parent"));
755                                 if (ncp->nc_vp != NULL) {
756                                         TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst,
757                                             ncp, nc_dst);
758                                 } else {
759                                         TAILQ_REMOVE(&ncneg, ncp, nc_dst);
760                                         numneg--;
761                                 }
762                                 if (vp != NULL) {
763                                         TAILQ_INSERT_HEAD(&vp->v_cache_dst,
764                                             ncp, nc_dst);
765                                 } else {
766                                         TAILQ_INSERT_TAIL(&ncneg, ncp, nc_dst);
767                                         numneg++;
768                                 }
769                                 ncp->nc_vp = vp;
770                                 CACHE_WUNLOCK();
771                                 return;
772                         }
773                         dvp->v_cache_dd = NULL;
774                         SDT_PROBE3(vfs, namecache, enter, done, dvp, "..", vp);
775                         CACHE_WUNLOCK();
776                         flag = NCF_ISDOTDOT;
777                 }
778         }
779
780         hold = 0;
781         zap = 0;
782
783         /*
784          * Calculate the hash key and setup as much of the new
785          * namecache entry as possible before acquiring the lock.
786          */
787         ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
788         ncp->nc_vp = vp;
789         ncp->nc_dvp = dvp;
790         ncp->nc_flag = flag;
791         if (tsp != NULL) {
792                 n3 = (struct namecache_ts *)ncp;
793                 n3->nc_time = *tsp;
794                 n3->nc_ticks = ticks;
795                 n3->nc_flag |= NCF_TS;
796                 if (dtsp != NULL) {
797                         n3->nc_dotdottime = *dtsp;
798                         n3->nc_flag |= NCF_DTS;
799                 }
800         }
801         len = ncp->nc_nlen = cnp->cn_namelen;
802         hash = fnv_32_buf(cnp->cn_nameptr, len, FNV1_32_INIT);
803         strlcpy(nc_get_name(ncp), cnp->cn_nameptr, len + 1);
804         hash = fnv_32_buf(&dvp, sizeof(dvp), hash);
805         CACHE_WLOCK();
806
807         /*
808          * See if this vnode or negative entry is already in the cache
809          * with this name.  This can happen with concurrent lookups of
810          * the same path name.
811          */
812         ncpp = NCHHASH(hash);
813         LIST_FOREACH(n2, ncpp, nc_hash) {
814                 if (n2->nc_dvp == dvp &&
815                     n2->nc_nlen == cnp->cn_namelen &&
816                     !bcmp(nc_get_name(n2), cnp->cn_nameptr, n2->nc_nlen)) {
817                         if (tsp != NULL) {
818                                 KASSERT((n2->nc_flag & NCF_TS) != 0,
819                                     ("no NCF_TS"));
820                                 n3 = (struct namecache_ts *)n2;
821                                 n3->nc_time =
822                                     ((struct namecache_ts *)ncp)->nc_time;
823                                 n3->nc_ticks =
824                                     ((struct namecache_ts *)ncp)->nc_ticks;
825                                 if (dtsp != NULL) {
826                                         n3->nc_dotdottime =
827                                             ((struct namecache_ts *)ncp)->
828                                             nc_dotdottime;
829                                         n3->nc_flag |= NCF_DTS;
830                                 }
831                         }
832                         CACHE_WUNLOCK();
833                         cache_free(ncp);
834                         return;
835                 }
836         }
837
838         if (flag == NCF_ISDOTDOT) {
839                 /*
840                  * See if we are trying to add .. entry, but some other lookup
841                  * has populated v_cache_dd pointer already.
842                  */
843                 if (dvp->v_cache_dd != NULL) {
844                         CACHE_WUNLOCK();
845                         cache_free(ncp);
846                         return;
847                 }
848                 KASSERT(vp == NULL || vp->v_type == VDIR,
849                     ("wrong vnode type %p", vp));
850                 dvp->v_cache_dd = ncp;
851         }
852
853         numcache++;
854         if (vp == NULL) {
855                 numneg++;
856                 if (cnp->cn_flags & ISWHITEOUT)
857                         ncp->nc_flag |= NCF_WHITE;
858         } else if (vp->v_type == VDIR) {
859                 if (flag != NCF_ISDOTDOT) {
860                         /*
861                          * For this case, the cache entry maps both the
862                          * directory name in it and the name ".." for the
863                          * directory's parent.
864                          */
865                         if ((n2 = vp->v_cache_dd) != NULL &&
866                             (n2->nc_flag & NCF_ISDOTDOT) != 0)
867                                 cache_zap(n2);
868                         vp->v_cache_dd = ncp;
869                 }
870         } else {
871                 vp->v_cache_dd = NULL;
872         }
873
874         /*
875          * Insert the new namecache entry into the appropriate chain
876          * within the cache entries table.
877          */
878         LIST_INSERT_HEAD(ncpp, ncp, nc_hash);
879         if (flag != NCF_ISDOTDOT) {
880                 if (LIST_EMPTY(&dvp->v_cache_src)) {
881                         hold = 1;
882                         numcachehv++;
883                 }
884                 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
885         }
886
887         /*
888          * If the entry is "negative", we place it into the
889          * "negative" cache queue, otherwise, we place it into the
890          * destination vnode's cache entries queue.
891          */
892         if (vp != NULL) {
893                 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
894                 SDT_PROBE3(vfs, namecache, enter, done, dvp, nc_get_name(ncp),
895                     vp);
896         } else {
897                 TAILQ_INSERT_TAIL(&ncneg, ncp, nc_dst);
898                 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
899                     nc_get_name(ncp));
900         }
901         if (numneg * ncnegfactor > numcache) {
902                 ncp = TAILQ_FIRST(&ncneg);
903                 KASSERT(ncp->nc_vp == NULL, ("ncp %p vp %p on ncneg",
904                     ncp, ncp->nc_vp));
905                 zap = 1;
906         }
907         if (hold)
908                 vhold(dvp);
909         if (zap)
910                 cache_zap(ncp);
911         CACHE_WUNLOCK();
912 }
913
914 /*
915  * Name cache initialization, from vfs_init() when we are booting
916  */
917 static void
918 nchinit(void *dummy __unused)
919 {
920
921         TAILQ_INIT(&ncneg);
922
923         cache_zone_small = uma_zcreate("S VFS Cache",
924             sizeof(struct namecache) + CACHE_PATH_CUTOFF + 1,
925             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
926         cache_zone_small_ts = uma_zcreate("STS VFS Cache",
927             sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1,
928             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
929         cache_zone_large = uma_zcreate("L VFS Cache",
930             sizeof(struct namecache) + NAME_MAX + 1,
931             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
932         cache_zone_large_ts = uma_zcreate("LTS VFS Cache",
933             sizeof(struct namecache_ts) + NAME_MAX + 1,
934             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
935
936         nchashtbl = hashinit(desiredvnodes * 2, M_VFSCACHE, &nchash);
937
938         numcalls = counter_u64_alloc(M_WAITOK);
939         dothits = counter_u64_alloc(M_WAITOK);
940         dotdothits = counter_u64_alloc(M_WAITOK);
941         numchecks = counter_u64_alloc(M_WAITOK);
942         nummiss = counter_u64_alloc(M_WAITOK);
943         nummisszap = counter_u64_alloc(M_WAITOK);
944         numposzaps = counter_u64_alloc(M_WAITOK);
945         numposhits = counter_u64_alloc(M_WAITOK);
946         numnegzaps = counter_u64_alloc(M_WAITOK);
947         numneghits = counter_u64_alloc(M_WAITOK);
948         numfullpathcalls = counter_u64_alloc(M_WAITOK);
949         numfullpathfail1 = counter_u64_alloc(M_WAITOK);
950         numfullpathfail2 = counter_u64_alloc(M_WAITOK);
951         numfullpathfail4 = counter_u64_alloc(M_WAITOK);
952         numfullpathfound = counter_u64_alloc(M_WAITOK);
953 }
954 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
955
956 void
957 cache_changesize(int newmaxvnodes)
958 {
959         struct nchashhead *new_nchashtbl, *old_nchashtbl;
960         u_long new_nchash, old_nchash;
961         struct namecache *ncp;
962         uint32_t hash;
963         int i;
964
965         new_nchashtbl = hashinit(newmaxvnodes * 2, M_VFSCACHE, &new_nchash);
966         /* If same hash table size, nothing to do */
967         if (nchash == new_nchash) {
968                 free(new_nchashtbl, M_VFSCACHE);
969                 return;
970         }
971         /*
972          * Move everything from the old hash table to the new table.
973          * None of the namecache entries in the table can be removed
974          * because to do so, they have to be removed from the hash table.
975          */
976         CACHE_WLOCK();
977         old_nchashtbl = nchashtbl;
978         old_nchash = nchash;
979         nchashtbl = new_nchashtbl;
980         nchash = new_nchash;
981         for (i = 0; i <= old_nchash; i++) {
982                 while ((ncp = LIST_FIRST(&old_nchashtbl[i])) != NULL) {
983                         hash = fnv_32_buf(nc_get_name(ncp), ncp->nc_nlen,
984                             FNV1_32_INIT);
985                         hash = fnv_32_buf(&ncp->nc_dvp, sizeof(ncp->nc_dvp),
986                             hash);
987                         LIST_REMOVE(ncp, nc_hash);
988                         LIST_INSERT_HEAD(NCHHASH(hash), ncp, nc_hash);
989                 }
990         }
991         CACHE_WUNLOCK();
992         free(old_nchashtbl, M_VFSCACHE);
993 }
994
995 /*
996  * Invalidate all entries to a particular vnode.
997  */
998 void
999 cache_purge(struct vnode *vp)
1000 {
1001
1002         CTR1(KTR_VFS, "cache_purge(%p)", vp);
1003         SDT_PROBE1(vfs, namecache, purge, done, vp);
1004         CACHE_WLOCK();
1005         while (!LIST_EMPTY(&vp->v_cache_src))
1006                 cache_zap(LIST_FIRST(&vp->v_cache_src));
1007         while (!TAILQ_EMPTY(&vp->v_cache_dst))
1008                 cache_zap(TAILQ_FIRST(&vp->v_cache_dst));
1009         if (vp->v_cache_dd != NULL) {
1010                 KASSERT(vp->v_cache_dd->nc_flag & NCF_ISDOTDOT,
1011                    ("lost dotdot link"));
1012                 cache_zap(vp->v_cache_dd);
1013         }
1014         KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
1015         CACHE_WUNLOCK();
1016 }
1017
1018 /*
1019  * Invalidate all negative entries for a particular directory vnode.
1020  */
1021 void
1022 cache_purge_negative(struct vnode *vp)
1023 {
1024         struct namecache *cp, *ncp;
1025
1026         CTR1(KTR_VFS, "cache_purge_negative(%p)", vp);
1027         SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
1028         CACHE_WLOCK();
1029         LIST_FOREACH_SAFE(cp, &vp->v_cache_src, nc_src, ncp) {
1030                 if (cp->nc_vp == NULL)
1031                         cache_zap(cp);
1032         }
1033         CACHE_WUNLOCK();
1034 }
1035
1036 /*
1037  * Flush all entries referencing a particular filesystem.
1038  */
1039 void
1040 cache_purgevfs(struct mount *mp)
1041 {
1042         struct nchashhead *ncpp;
1043         struct namecache *ncp, *nnp;
1044
1045         /* Scan hash tables for applicable entries */
1046         SDT_PROBE1(vfs, namecache, purgevfs, done, mp);
1047         CACHE_WLOCK();
1048         for (ncpp = &nchashtbl[nchash]; ncpp >= nchashtbl; ncpp--) {
1049                 LIST_FOREACH_SAFE(ncp, ncpp, nc_hash, nnp) {
1050                         if (ncp->nc_dvp->v_mount == mp)
1051                                 cache_zap(ncp);
1052                 }
1053         }
1054         CACHE_WUNLOCK();
1055 }
1056
1057 /*
1058  * Perform canonical checks and cache lookup and pass on to filesystem
1059  * through the vop_cachedlookup only if needed.
1060  */
1061
1062 int
1063 vfs_cache_lookup(struct vop_lookup_args *ap)
1064 {
1065         struct vnode *dvp;
1066         int error;
1067         struct vnode **vpp = ap->a_vpp;
1068         struct componentname *cnp = ap->a_cnp;
1069         struct ucred *cred = cnp->cn_cred;
1070         int flags = cnp->cn_flags;
1071         struct thread *td = cnp->cn_thread;
1072
1073         *vpp = NULL;
1074         dvp = ap->a_dvp;
1075
1076         if (dvp->v_type != VDIR)
1077                 return (ENOTDIR);
1078
1079         if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
1080             (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
1081                 return (EROFS);
1082
1083         error = VOP_ACCESS(dvp, VEXEC, cred, td);
1084         if (error)
1085                 return (error);
1086
1087         error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
1088         if (error == 0)
1089                 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
1090         if (error == -1)
1091                 return (0);
1092         return (error);
1093 }
1094
1095 /*
1096  * XXX All of these sysctls would probably be more productive dead.
1097  */
1098 static int disablecwd;
1099 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0,
1100    "Disable the getcwd syscall");
1101
1102 /* Implementation of the getcwd syscall. */
1103 int
1104 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
1105 {
1106
1107         return (kern___getcwd(td, uap->buf, UIO_USERSPACE, uap->buflen,
1108             MAXPATHLEN));
1109 }
1110
1111 int
1112 kern___getcwd(struct thread *td, char *buf, enum uio_seg bufseg, u_int buflen,
1113     u_int path_max)
1114 {
1115         char *bp, *tmpbuf;
1116         struct filedesc *fdp;
1117         struct vnode *cdir, *rdir;
1118         int error;
1119
1120         if (disablecwd)
1121                 return (ENODEV);
1122         if (buflen < 2)
1123                 return (EINVAL);
1124         if (buflen > path_max)
1125                 buflen = path_max;
1126
1127         tmpbuf = malloc(buflen, M_TEMP, M_WAITOK);
1128         fdp = td->td_proc->p_fd;
1129         FILEDESC_SLOCK(fdp);
1130         cdir = fdp->fd_cdir;
1131         VREF(cdir);
1132         rdir = fdp->fd_rdir;
1133         VREF(rdir);
1134         FILEDESC_SUNLOCK(fdp);
1135         error = vn_fullpath1(td, cdir, rdir, tmpbuf, &bp, buflen);
1136         vrele(rdir);
1137         vrele(cdir);
1138
1139         if (!error) {
1140                 if (bufseg == UIO_SYSSPACE)
1141                         bcopy(bp, buf, strlen(bp) + 1);
1142                 else
1143                         error = copyout(bp, buf, strlen(bp) + 1);
1144 #ifdef KTRACE
1145         if (KTRPOINT(curthread, KTR_NAMEI))
1146                 ktrnamei(bp);
1147 #endif
1148         }
1149         free(tmpbuf, M_TEMP);
1150         return (error);
1151 }
1152
1153 /*
1154  * Thus begins the fullpath magic.
1155  */
1156
1157 static int disablefullpath;
1158 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW, &disablefullpath, 0,
1159     "Disable the vn_fullpath function");
1160
1161 /*
1162  * Retrieve the full filesystem path that correspond to a vnode from the name
1163  * cache (if available)
1164  */
1165 int
1166 vn_fullpath(struct thread *td, struct vnode *vn, char **retbuf, char **freebuf)
1167 {
1168         char *buf;
1169         struct filedesc *fdp;
1170         struct vnode *rdir;
1171         int error;
1172
1173         if (disablefullpath)
1174                 return (ENODEV);
1175         if (vn == NULL)
1176                 return (EINVAL);
1177
1178         buf = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1179         fdp = td->td_proc->p_fd;
1180         FILEDESC_SLOCK(fdp);
1181         rdir = fdp->fd_rdir;
1182         VREF(rdir);
1183         FILEDESC_SUNLOCK(fdp);
1184         error = vn_fullpath1(td, vn, rdir, buf, retbuf, MAXPATHLEN);
1185         vrele(rdir);
1186
1187         if (!error)
1188                 *freebuf = buf;
1189         else
1190                 free(buf, M_TEMP);
1191         return (error);
1192 }
1193
1194 /*
1195  * This function is similar to vn_fullpath, but it attempts to lookup the
1196  * pathname relative to the global root mount point.  This is required for the
1197  * auditing sub-system, as audited pathnames must be absolute, relative to the
1198  * global root mount point.
1199  */
1200 int
1201 vn_fullpath_global(struct thread *td, struct vnode *vn,
1202     char **retbuf, char **freebuf)
1203 {
1204         char *buf;
1205         int error;
1206
1207         if (disablefullpath)
1208                 return (ENODEV);
1209         if (vn == NULL)
1210                 return (EINVAL);
1211         buf = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1212         error = vn_fullpath1(td, vn, rootvnode, buf, retbuf, MAXPATHLEN);
1213         if (!error)
1214                 *freebuf = buf;
1215         else
1216                 free(buf, M_TEMP);
1217         return (error);
1218 }
1219
1220 int
1221 vn_vptocnp(struct vnode **vp, struct ucred *cred, char *buf, u_int *buflen)
1222 {
1223         int error;
1224
1225         CACHE_RLOCK();
1226         error = vn_vptocnp_locked(vp, cred, buf, buflen);
1227         if (error == 0)
1228                 CACHE_RUNLOCK();
1229         return (error);
1230 }
1231
1232 static int
1233 vn_vptocnp_locked(struct vnode **vp, struct ucred *cred, char *buf,
1234     u_int *buflen)
1235 {
1236         struct vnode *dvp;
1237         struct namecache *ncp;
1238         int error;
1239
1240         TAILQ_FOREACH(ncp, &((*vp)->v_cache_dst), nc_dst) {
1241                 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
1242                         break;
1243         }
1244         if (ncp != NULL) {
1245                 if (*buflen < ncp->nc_nlen) {
1246                         CACHE_RUNLOCK();
1247                         vrele(*vp);
1248                         counter_u64_add(numfullpathfail4, 1);
1249                         error = ENOMEM;
1250                         SDT_PROBE3(vfs, namecache, fullpath, return, error,
1251                             vp, NULL);
1252                         return (error);
1253                 }
1254                 *buflen -= ncp->nc_nlen;
1255                 memcpy(buf + *buflen, nc_get_name(ncp), ncp->nc_nlen);
1256                 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
1257                     nc_get_name(ncp), vp);
1258                 dvp = *vp;
1259                 *vp = ncp->nc_dvp;
1260                 vref(*vp);
1261                 CACHE_RUNLOCK();
1262                 vrele(dvp);
1263                 CACHE_RLOCK();
1264                 return (0);
1265         }
1266         SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
1267
1268         CACHE_RUNLOCK();
1269         vn_lock(*vp, LK_SHARED | LK_RETRY);
1270         error = VOP_VPTOCNP(*vp, &dvp, cred, buf, buflen);
1271         vput(*vp);
1272         if (error) {
1273                 counter_u64_add(numfullpathfail2, 1);
1274                 SDT_PROBE3(vfs, namecache, fullpath, return,  error, vp, NULL);
1275                 return (error);
1276         }
1277
1278         *vp = dvp;
1279         CACHE_RLOCK();
1280         if (dvp->v_iflag & VI_DOOMED) {
1281                 /* forced unmount */
1282                 CACHE_RUNLOCK();
1283                 vrele(dvp);
1284                 error = ENOENT;
1285                 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
1286                 return (error);
1287         }
1288         /*
1289          * *vp has its use count incremented still.
1290          */
1291
1292         return (0);
1293 }
1294
1295 /*
1296  * The magic behind kern___getcwd() and vn_fullpath().
1297  */
1298 static int
1299 vn_fullpath1(struct thread *td, struct vnode *vp, struct vnode *rdir,
1300     char *buf, char **retbuf, u_int buflen)
1301 {
1302         int error, slash_prefixed;
1303 #ifdef KDTRACE_HOOKS
1304         struct vnode *startvp = vp;
1305 #endif
1306         struct vnode *vp1;
1307
1308         buflen--;
1309         buf[buflen] = '\0';
1310         error = 0;
1311         slash_prefixed = 0;
1312
1313         SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
1314         counter_u64_add(numfullpathcalls, 1);
1315         vref(vp);
1316         CACHE_RLOCK();
1317         if (vp->v_type != VDIR) {
1318                 error = vn_vptocnp_locked(&vp, td->td_ucred, buf, &buflen);
1319                 if (error)
1320                         return (error);
1321                 if (buflen == 0) {
1322                         CACHE_RUNLOCK();
1323                         vrele(vp);
1324                         return (ENOMEM);
1325                 }
1326                 buf[--buflen] = '/';
1327                 slash_prefixed = 1;
1328         }
1329         while (vp != rdir && vp != rootvnode) {
1330                 if (vp->v_vflag & VV_ROOT) {
1331                         if (vp->v_iflag & VI_DOOMED) {  /* forced unmount */
1332                                 CACHE_RUNLOCK();
1333                                 vrele(vp);
1334                                 error = ENOENT;
1335                                 SDT_PROBE3(vfs, namecache, fullpath, return,
1336                                     error, vp, NULL);
1337                                 break;
1338                         }
1339                         vp1 = vp->v_mount->mnt_vnodecovered;
1340                         vref(vp1);
1341                         CACHE_RUNLOCK();
1342                         vrele(vp);
1343                         vp = vp1;
1344                         CACHE_RLOCK();
1345                         continue;
1346                 }
1347                 if (vp->v_type != VDIR) {
1348                         CACHE_RUNLOCK();
1349                         vrele(vp);
1350                         counter_u64_add(numfullpathfail1, 1);
1351                         error = ENOTDIR;
1352                         SDT_PROBE3(vfs, namecache, fullpath, return,
1353                             error, vp, NULL);
1354                         break;
1355                 }
1356                 error = vn_vptocnp_locked(&vp, td->td_ucred, buf, &buflen);
1357                 if (error)
1358                         break;
1359                 if (buflen == 0) {
1360                         CACHE_RUNLOCK();
1361                         vrele(vp);
1362                         error = ENOMEM;
1363                         SDT_PROBE3(vfs, namecache, fullpath, return, error,
1364                             startvp, NULL);
1365                         break;
1366                 }
1367                 buf[--buflen] = '/';
1368                 slash_prefixed = 1;
1369         }
1370         if (error)
1371                 return (error);
1372         if (!slash_prefixed) {
1373                 if (buflen == 0) {
1374                         CACHE_RUNLOCK();
1375                         vrele(vp);
1376                         counter_u64_add(numfullpathfail4, 1);
1377                         SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
1378                             startvp, NULL);
1379                         return (ENOMEM);
1380                 }
1381                 buf[--buflen] = '/';
1382         }
1383         counter_u64_add(numfullpathfound, 1);
1384         CACHE_RUNLOCK();
1385         vrele(vp);
1386
1387         SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, buf + buflen);
1388         *retbuf = buf + buflen;
1389         return (0);
1390 }
1391
1392 struct vnode *
1393 vn_dir_dd_ino(struct vnode *vp)
1394 {
1395         struct namecache *ncp;
1396         struct vnode *ddvp;
1397
1398         ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
1399         CACHE_RLOCK();
1400         TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
1401                 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
1402                         continue;
1403                 ddvp = ncp->nc_dvp;
1404                 vhold(ddvp);
1405                 CACHE_RUNLOCK();
1406                 if (vget(ddvp, LK_SHARED | LK_NOWAIT | LK_VNHELD, curthread))
1407                         return (NULL);
1408                 return (ddvp);
1409         }
1410         CACHE_RUNLOCK();
1411         return (NULL);
1412 }
1413
1414 int
1415 vn_commname(struct vnode *vp, char *buf, u_int buflen)
1416 {
1417         struct namecache *ncp;
1418         int l;
1419
1420         CACHE_RLOCK();
1421         TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
1422                 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
1423                         break;
1424         if (ncp == NULL) {
1425                 CACHE_RUNLOCK();
1426                 return (ENOENT);
1427         }
1428         l = min(ncp->nc_nlen, buflen - 1);
1429         memcpy(buf, nc_get_name(ncp), l);
1430         CACHE_RUNLOCK();
1431         buf[l] = '\0';
1432         return (0);
1433 }
1434
1435 /* ABI compat shims for old kernel modules. */
1436 #undef cache_enter
1437
1438 void    cache_enter(struct vnode *dvp, struct vnode *vp,
1439             struct componentname *cnp);
1440
1441 void
1442 cache_enter(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
1443 {
1444
1445         cache_enter_time(dvp, vp, cnp, NULL, NULL);
1446 }
1447
1448 /*
1449  * This function updates path string to vnode's full global path
1450  * and checks the size of the new path string against the pathlen argument.
1451  *
1452  * Requires a locked, referenced vnode.
1453  * Vnode is re-locked on success or ENODEV, otherwise unlocked.
1454  *
1455  * If sysctl debug.disablefullpath is set, ENODEV is returned,
1456  * vnode is left locked and path remain untouched.
1457  *
1458  * If vp is a directory, the call to vn_fullpath_global() always succeeds
1459  * because it falls back to the ".." lookup if the namecache lookup fails.
1460  */
1461 int
1462 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
1463     u_int pathlen)
1464 {
1465         struct nameidata nd;
1466         struct vnode *vp1;
1467         char *rpath, *fbuf;
1468         int error;
1469
1470         ASSERT_VOP_ELOCKED(vp, __func__);
1471
1472         /* Return ENODEV if sysctl debug.disablefullpath==1 */
1473         if (disablefullpath)
1474                 return (ENODEV);
1475
1476         /* Construct global filesystem path from vp. */
1477         VOP_UNLOCK(vp, 0);
1478         error = vn_fullpath_global(td, vp, &rpath, &fbuf);
1479
1480         if (error != 0) {
1481                 vrele(vp);
1482                 return (error);
1483         }
1484
1485         if (strlen(rpath) >= pathlen) {
1486                 vrele(vp);
1487                 error = ENAMETOOLONG;
1488                 goto out;
1489         }
1490
1491         /*
1492          * Re-lookup the vnode by path to detect a possible rename.
1493          * As a side effect, the vnode is relocked.
1494          * If vnode was renamed, return ENOENT.
1495          */
1496         NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
1497             UIO_SYSSPACE, path, td);
1498         error = namei(&nd);
1499         if (error != 0) {
1500                 vrele(vp);
1501                 goto out;
1502         }
1503         NDFREE(&nd, NDF_ONLY_PNBUF);
1504         vp1 = nd.ni_vp;
1505         vrele(vp);
1506         if (vp1 == vp)
1507                 strcpy(path, rpath);
1508         else {
1509                 vput(vp1);
1510                 error = ENOENT;
1511         }
1512
1513 out:
1514         free(fbuf, M_TEMP);
1515         return (error);
1516 }