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