xref: /freebsd/sys/kern/vfs_cache.c (revision 52267f7411adcc76ede961420e08c0e42f42d415)
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 <sys/param.h>
39 #include <sys/filedesc.h>
40 #include <sys/fnv_hash.h>
41 #include <sys/kernel.h>
42 #include <sys/lock.h>
43 #include <sys/malloc.h>
44 #include <sys/mount.h>
45 #include <sys/mutex.h>
46 #include <sys/namei.h>
47 #include <sys/proc.h>
48 #include <sys/syscallsubr.h>
49 #include <sys/sysctl.h>
50 #include <sys/sysproto.h>
51 #include <sys/systm.h>
52 #include <sys/vnode.h>
53 
54 #include <vm/uma.h>
55 
56 /*
57  * This structure describes the elements in the cache of recent
58  * names looked up by namei.
59  */
60 
61 struct	namecache {
62 	LIST_ENTRY(namecache) nc_hash;	/* hash chain */
63 	LIST_ENTRY(namecache) nc_src;	/* source vnode list */
64 	TAILQ_ENTRY(namecache) nc_dst;	/* destination vnode list */
65 	struct	vnode *nc_dvp;		/* vnode of parent of name */
66 	struct	vnode *nc_vp;		/* vnode the name refers to */
67 	u_char	nc_flag;		/* flag bits */
68 	u_char	nc_nlen;		/* length of name */
69 	char	nc_name[0];		/* segment name */
70 };
71 
72 /*
73  * Name caching works as follows:
74  *
75  * Names found by directory scans are retained in a cache
76  * for future reference.  It is managed LRU, so frequently
77  * used names will hang around.  Cache is indexed by hash value
78  * obtained from (vp, name) where vp refers to the directory
79  * containing name.
80  *
81  * If it is a "negative" entry, (i.e. for a name that is known NOT to
82  * exist) the vnode pointer will be NULL.
83  *
84  * Upon reaching the last segment of a path, if the reference
85  * is for DELETE, or NOCACHE is set (rewrite), and the
86  * name is located in the cache, it will be dropped.
87  */
88 
89 /*
90  * Structures associated with name cacheing.
91  */
92 #define NCHHASH(hash) \
93 	(&nchashtbl[(hash) & nchash])
94 static LIST_HEAD(nchashhead, namecache) *nchashtbl;	/* Hash Table */
95 static TAILQ_HEAD(, namecache) ncneg;	/* Hash Table */
96 static u_long	nchash;			/* size of hash table */
97 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0, "");
98 static u_long	ncnegfactor = 16;	/* ratio of negative entries */
99 SYSCTL_ULONG(_debug, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0, "");
100 static u_long	numneg;			/* number of cache entries allocated */
101 SYSCTL_ULONG(_debug, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0, "");
102 static u_long	numcache;		/* number of cache entries allocated */
103 SYSCTL_ULONG(_debug, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0, "");
104 static u_long	numcachehv;		/* number of cache entries with vnodes held */
105 SYSCTL_ULONG(_debug, OID_AUTO, numcachehv, CTLFLAG_RD, &numcachehv, 0, "");
106 #if 0
107 static u_long	numcachepl;		/* number of cache purge for leaf entries */
108 SYSCTL_ULONG(_debug, OID_AUTO, numcachepl, CTLFLAG_RD, &numcachepl, 0, "");
109 #endif
110 struct	nchstats nchstats;		/* cache effectiveness statistics */
111 
112 static struct mtx cache_lock;
113 MTX_SYSINIT(vfscache, &cache_lock, "Name Cache", MTX_DEF);
114 
115 #define	CACHE_LOCK()	mtx_lock(&cache_lock)
116 #define	CACHE_UNLOCK()	mtx_unlock(&cache_lock)
117 
118 /*
119  * UMA zones for the VFS cache.
120  *
121  * The small cache is used for entries with short names, which are the
122  * most common.  The large cache is used for entries which are too big to
123  * fit in the small cache.
124  */
125 static uma_zone_t cache_zone_small;
126 static uma_zone_t cache_zone_large;
127 
128 #define	CACHE_PATH_CUTOFF	32
129 #define	CACHE_ZONE_SMALL	(sizeof(struct namecache) + CACHE_PATH_CUTOFF)
130 #define	CACHE_ZONE_LARGE	(sizeof(struct namecache) + NAME_MAX)
131 
132 #define cache_alloc(len)	uma_zalloc(((len) <= CACHE_PATH_CUTOFF) ? \
133 	cache_zone_small : cache_zone_large, M_WAITOK)
134 #define cache_free(ncp)		do { \
135 	if (ncp != NULL) \
136 		uma_zfree(((ncp)->nc_nlen <= CACHE_PATH_CUTOFF) ? \
137 		    cache_zone_small : cache_zone_large, (ncp)); \
138 } while (0)
139 
140 static int	doingcache = 1;		/* 1 => enable the cache */
141 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0, "");
142 
143 /* Export size information to userland */
144 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, 0,
145 	sizeof(struct namecache), "");
146 
147 /*
148  * The new name cache statistics
149  */
150 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0, "Name cache statistics");
151 #define STATNODE(mode, name, var) \
152 	SYSCTL_ULONG(_vfs_cache, OID_AUTO, name, mode, var, 0, "");
153 STATNODE(CTLFLAG_RD, numneg, &numneg);
154 STATNODE(CTLFLAG_RD, numcache, &numcache);
155 static u_long numcalls; STATNODE(CTLFLAG_RD, numcalls, &numcalls);
156 static u_long dothits; STATNODE(CTLFLAG_RD, dothits, &dothits);
157 static u_long dotdothits; STATNODE(CTLFLAG_RD, dotdothits, &dotdothits);
158 static u_long numchecks; STATNODE(CTLFLAG_RD, numchecks, &numchecks);
159 static u_long nummiss; STATNODE(CTLFLAG_RD, nummiss, &nummiss);
160 static u_long nummisszap; STATNODE(CTLFLAG_RD, nummisszap, &nummisszap);
161 static u_long numposzaps; STATNODE(CTLFLAG_RD, numposzaps, &numposzaps);
162 static u_long numposhits; STATNODE(CTLFLAG_RD, numposhits, &numposhits);
163 static u_long numnegzaps; STATNODE(CTLFLAG_RD, numnegzaps, &numnegzaps);
164 static u_long numneghits; STATNODE(CTLFLAG_RD, numneghits, &numneghits);
165 
166 SYSCTL_OPAQUE(_vfs_cache, OID_AUTO, nchstats, CTLFLAG_RD, &nchstats,
167 	sizeof(nchstats), "LU", "VFS cache effectiveness statistics");
168 
169 
170 
171 static void cache_zap(struct namecache *ncp);
172 static int vn_fullpath1(struct thread *td, struct vnode *vp, struct vnode *rdir,
173     char *buf, char **retbuf, u_int buflen);
174 
175 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
176 
177 /*
178  * Flags in namecache.nc_flag
179  */
180 #define NCF_WHITE	1
181 
182 /*
183  * Grab an atomic snapshot of the name cache hash chain lengths
184  */
185 SYSCTL_NODE(_debug, OID_AUTO, hashstat, CTLFLAG_RW, NULL, "hash table stats");
186 
187 static int
188 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
189 {
190 	int error;
191 	struct nchashhead *ncpp;
192 	struct namecache *ncp;
193 	int n_nchash;
194 	int count;
195 
196 	n_nchash = nchash + 1;	/* nchash is max index, not count */
197 	if (!req->oldptr)
198 		return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
199 
200 	/* Scan hash tables for applicable entries */
201 	for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
202 		CACHE_LOCK();
203 		count = 0;
204 		LIST_FOREACH(ncp, ncpp, nc_hash) {
205 			count++;
206 		}
207 		CACHE_UNLOCK();
208 		error = SYSCTL_OUT(req, &count, sizeof(count));
209 		if (error)
210 			return (error);
211 	}
212 	return (0);
213 }
214 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD,
215 	0, 0, sysctl_debug_hashstat_rawnchash, "S,int", "nchash chain lengths");
216 
217 static int
218 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
219 {
220 	int error;
221 	struct nchashhead *ncpp;
222 	struct namecache *ncp;
223 	int n_nchash;
224 	int count, maxlength, used, pct;
225 
226 	if (!req->oldptr)
227 		return SYSCTL_OUT(req, 0, 4 * sizeof(int));
228 
229 	n_nchash = nchash + 1;	/* nchash is max index, not count */
230 	used = 0;
231 	maxlength = 0;
232 
233 	/* Scan hash tables for applicable entries */
234 	for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
235 		count = 0;
236 		CACHE_LOCK();
237 		LIST_FOREACH(ncp, ncpp, nc_hash) {
238 			count++;
239 		}
240 		CACHE_UNLOCK();
241 		if (count)
242 			used++;
243 		if (maxlength < count)
244 			maxlength = count;
245 	}
246 	n_nchash = nchash + 1;
247 	pct = (used * 100 * 100) / n_nchash;
248 	error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
249 	if (error)
250 		return (error);
251 	error = SYSCTL_OUT(req, &used, sizeof(used));
252 	if (error)
253 		return (error);
254 	error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
255 	if (error)
256 		return (error);
257 	error = SYSCTL_OUT(req, &pct, sizeof(pct));
258 	if (error)
259 		return (error);
260 	return (0);
261 }
262 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD,
263 	0, 0, sysctl_debug_hashstat_nchash, "I", "nchash chain lengths");
264 
265 /*
266  * cache_zap():
267  *
268  *   Removes a namecache entry from cache, whether it contains an actual
269  *   pointer to a vnode or if it is just a negative cache entry.
270  */
271 static void
272 cache_zap(ncp)
273 	struct namecache *ncp;
274 {
275 	struct vnode *vp;
276 
277 	mtx_assert(&cache_lock, MA_OWNED);
278 	CTR2(KTR_VFS, "cache_zap(%p) vp %p", ncp, ncp->nc_vp);
279 	vp = NULL;
280 	LIST_REMOVE(ncp, nc_hash);
281 	LIST_REMOVE(ncp, nc_src);
282 	if (LIST_EMPTY(&ncp->nc_dvp->v_cache_src)) {
283 		vp = ncp->nc_dvp;
284 		numcachehv--;
285 	}
286 	if (ncp->nc_vp) {
287 		TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst, ncp, nc_dst);
288 		ncp->nc_vp->v_dd = NULL;
289 	} else {
290 		TAILQ_REMOVE(&ncneg, ncp, nc_dst);
291 		numneg--;
292 	}
293 	numcache--;
294 	cache_free(ncp);
295 	if (vp)
296 		vdrop(vp);
297 }
298 
299 /*
300  * Lookup an entry in the cache
301  *
302  * Lookup is called with dvp pointing to the directory to search,
303  * cnp pointing to the name of the entry being sought. If the lookup
304  * succeeds, the vnode is returned in *vpp, and a status of -1 is
305  * returned. If the lookup determines that the name does not exist
306  * (negative cacheing), a status of ENOENT is returned. If the lookup
307  * fails, a status of zero is returned.  If the directory vnode is
308  * recycled out from under us due to a forced unmount, a status of
309  * EBADF is returned.
310  *
311  * vpp is locked and ref'd on return.  If we're looking up DOTDOT, dvp is
312  * unlocked.  If we're looking up . an extra ref is taken, but the lock is
313  * not recursively acquired.
314  */
315 
316 int
317 cache_lookup(dvp, vpp, cnp)
318 	struct vnode *dvp;
319 	struct vnode **vpp;
320 	struct componentname *cnp;
321 {
322 	struct namecache *ncp;
323 	u_int32_t hash;
324 	int error, ltype;
325 
326 	if (!doingcache) {
327 		cnp->cn_flags &= ~MAKEENTRY;
328 		return (0);
329 	}
330 retry:
331 	CACHE_LOCK();
332 	numcalls++;
333 
334 	if (cnp->cn_nameptr[0] == '.') {
335 		if (cnp->cn_namelen == 1) {
336 			*vpp = dvp;
337 			CTR2(KTR_VFS, "cache_lookup(%p, %s) found via .",
338 			    dvp, cnp->cn_nameptr);
339 			dothits++;
340 			goto success;
341 		}
342 		if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
343 			dotdothits++;
344 			if (dvp->v_dd == NULL ||
345 			    (cnp->cn_flags & MAKEENTRY) == 0) {
346 				CACHE_UNLOCK();
347 				return (0);
348 			}
349 			*vpp = dvp->v_dd;
350 			CTR3(KTR_VFS, "cache_lookup(%p, %s) found %p via ..",
351 			    dvp, cnp->cn_nameptr, *vpp);
352 			goto success;
353 		}
354 	}
355 
356 	hash = fnv_32_buf(cnp->cn_nameptr, cnp->cn_namelen, FNV1_32_INIT);
357 	hash = fnv_32_buf(&dvp, sizeof(dvp), hash);
358 	LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
359 		numchecks++;
360 		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
361 		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
362 			break;
363 	}
364 
365 	/* We failed to find an entry */
366 	if (ncp == 0) {
367 		if ((cnp->cn_flags & MAKEENTRY) == 0) {
368 			nummisszap++;
369 		} else {
370 			nummiss++;
371 		}
372 		nchstats.ncs_miss++;
373 		CACHE_UNLOCK();
374 		return (0);
375 	}
376 
377 	/* We don't want to have an entry, so dump it */
378 	if ((cnp->cn_flags & MAKEENTRY) == 0) {
379 		numposzaps++;
380 		nchstats.ncs_badhits++;
381 		cache_zap(ncp);
382 		CACHE_UNLOCK();
383 		return (0);
384 	}
385 
386 	/* We found a "positive" match, return the vnode */
387 	if (ncp->nc_vp) {
388 		numposhits++;
389 		nchstats.ncs_goodhits++;
390 		*vpp = ncp->nc_vp;
391 		CTR4(KTR_VFS, "cache_lookup(%p, %s) found %p via ncp %p",
392 		    dvp, cnp->cn_nameptr, *vpp, ncp);
393 		goto success;
394 	}
395 
396 	/* We found a negative match, and want to create it, so purge */
397 	if (cnp->cn_nameiop == CREATE) {
398 		numnegzaps++;
399 		nchstats.ncs_badhits++;
400 		cache_zap(ncp);
401 		CACHE_UNLOCK();
402 		return (0);
403 	}
404 
405 	numneghits++;
406 	/*
407 	 * We found a "negative" match, so we shift it to the end of
408 	 * the "negative" cache entries queue to satisfy LRU.  Also,
409 	 * check to see if the entry is a whiteout; indicate this to
410 	 * the componentname, if so.
411 	 */
412 	TAILQ_REMOVE(&ncneg, ncp, nc_dst);
413 	TAILQ_INSERT_TAIL(&ncneg, ncp, nc_dst);
414 	nchstats.ncs_neghits++;
415 	if (ncp->nc_flag & NCF_WHITE)
416 		cnp->cn_flags |= ISWHITEOUT;
417 	CACHE_UNLOCK();
418 	return (ENOENT);
419 
420 success:
421 	/*
422 	 * On success we return a locked and ref'd vnode as per the lookup
423 	 * protocol.
424 	 */
425 	if (dvp == *vpp) {   /* lookup on "." */
426 		VREF(*vpp);
427 		CACHE_UNLOCK();
428 		/*
429 		 * When we lookup "." we still can be asked to lock it
430 		 * differently...
431 		 */
432 		ltype = cnp->cn_lkflags & LK_TYPE_MASK;
433 		if (ltype != VOP_ISLOCKED(*vpp)) {
434 			if (ltype == LK_EXCLUSIVE) {
435 				vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
436 				if ((*vpp)->v_iflag & VI_DOOMED) {
437 					/* forced unmount */
438 					vrele(*vpp);
439 					*vpp = NULL;
440 					return (EBADF);
441 				}
442 			} else
443 				vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
444 		}
445 		return (-1);
446 	}
447 	ltype = 0;	/* silence gcc warning */
448 	if (cnp->cn_flags & ISDOTDOT) {
449 		ltype = VOP_ISLOCKED(dvp);
450 		VOP_UNLOCK(dvp, 0);
451 	}
452 	VI_LOCK(*vpp);
453 	CACHE_UNLOCK();
454 	error = vget(*vpp, cnp->cn_lkflags | LK_INTERLOCK, cnp->cn_thread);
455 	if (cnp->cn_flags & ISDOTDOT)
456 		vn_lock(dvp, ltype | LK_RETRY);
457 	if (error) {
458 		*vpp = NULL;
459 		goto retry;
460 	}
461 	if ((cnp->cn_flags & ISLASTCN) &&
462 	    (cnp->cn_lkflags & LK_TYPE_MASK) == LK_EXCLUSIVE) {
463 		ASSERT_VOP_ELOCKED(*vpp, "cache_lookup");
464 	}
465 	return (-1);
466 }
467 
468 /*
469  * Add an entry to the cache.
470  */
471 void
472 cache_enter(dvp, vp, cnp)
473 	struct vnode *dvp;
474 	struct vnode *vp;
475 	struct componentname *cnp;
476 {
477 	struct namecache *ncp, *n2;
478 	struct nchashhead *ncpp;
479 	u_int32_t hash;
480 	int hold;
481 	int zap;
482 	int len;
483 
484 	CTR3(KTR_VFS, "cache_enter(%p, %p, %s)", dvp, vp, cnp->cn_nameptr);
485 	VNASSERT(vp == NULL || (vp->v_iflag & VI_DOOMED) == 0, vp,
486 	    ("cahe_enter: Adding a doomed vnode"));
487 
488 	if (!doingcache)
489 		return;
490 
491 	if (cnp->cn_nameptr[0] == '.') {
492 		if (cnp->cn_namelen == 1) {
493 			return;
494 		}
495 		/*
496 		 * For dotdot lookups only cache the v_dd pointer if the
497 		 * directory has a link back to its parent via v_cache_dst.
498 		 * Without this an unlinked directory would keep a soft
499 		 * reference to its parent which could not be NULLd at
500 		 * cache_purge() time.
501 		 */
502 		if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
503 			CACHE_LOCK();
504 			if (!TAILQ_EMPTY(&dvp->v_cache_dst))
505 				dvp->v_dd = vp;
506 			CACHE_UNLOCK();
507 			return;
508 		}
509 	}
510 
511 	hold = 0;
512 	zap = 0;
513 
514 	/*
515 	 * Calculate the hash key and setup as much of the new
516 	 * namecache entry as possible before acquiring the lock.
517 	 */
518 	ncp = cache_alloc(cnp->cn_namelen);
519 	ncp->nc_vp = vp;
520 	ncp->nc_dvp = dvp;
521 	len = ncp->nc_nlen = cnp->cn_namelen;
522 	hash = fnv_32_buf(cnp->cn_nameptr, len, FNV1_32_INIT);
523 	bcopy(cnp->cn_nameptr, ncp->nc_name, len);
524 	hash = fnv_32_buf(&dvp, sizeof(dvp), hash);
525 	CACHE_LOCK();
526 
527 	/*
528 	 * See if this vnode is already in the cache with this name.
529 	 * This can happen with concurrent lookups of the same path
530 	 * name.
531 	 */
532 	if (vp) {
533 		TAILQ_FOREACH(n2, &vp->v_cache_dst, nc_dst) {
534 			if (n2->nc_dvp == dvp &&
535 			    n2->nc_nlen == cnp->cn_namelen &&
536 			    !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
537 				CACHE_UNLOCK();
538 				cache_free(ncp);
539 				return;
540 			}
541 		}
542 	} else {
543 		TAILQ_FOREACH(n2, &ncneg, nc_dst) {
544 			if (n2->nc_nlen == cnp->cn_namelen &&
545 			    !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
546 				CACHE_UNLOCK();
547 				cache_free(ncp);
548 				return;
549 			}
550 		}
551 	}
552 
553 	numcache++;
554 	if (!vp) {
555 		numneg++;
556 		ncp->nc_flag = cnp->cn_flags & ISWHITEOUT ? NCF_WHITE : 0;
557 	} else if (vp->v_type == VDIR) {
558 		vp->v_dd = dvp;
559 	} else {
560 		vp->v_dd = NULL;
561 	}
562 
563 	/*
564 	 * Insert the new namecache entry into the appropriate chain
565 	 * within the cache entries table.
566 	 */
567 	ncpp = NCHHASH(hash);
568 	LIST_INSERT_HEAD(ncpp, ncp, nc_hash);
569 	if (LIST_EMPTY(&dvp->v_cache_src)) {
570 		hold = 1;
571 		numcachehv++;
572 	}
573 	LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
574 	/*
575 	 * If the entry is "negative", we place it into the
576 	 * "negative" cache queue, otherwise, we place it into the
577 	 * destination vnode's cache entries queue.
578 	 */
579 	if (vp) {
580 		TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
581 	} else {
582 		TAILQ_INSERT_TAIL(&ncneg, ncp, nc_dst);
583 	}
584 	if (numneg * ncnegfactor > numcache) {
585 		ncp = TAILQ_FIRST(&ncneg);
586 		zap = 1;
587 	}
588 	if (hold)
589 		vhold(dvp);
590 	if (zap)
591 		cache_zap(ncp);
592 	CACHE_UNLOCK();
593 }
594 
595 /*
596  * Name cache initialization, from vfs_init() when we are booting
597  */
598 static void
599 nchinit(void *dummy __unused)
600 {
601 
602 	TAILQ_INIT(&ncneg);
603 
604 	cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL, NULL,
605 	    NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
606 	cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE, NULL,
607 	    NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
608 
609 	nchashtbl = hashinit(desiredvnodes * 2, M_VFSCACHE, &nchash);
610 }
611 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
612 
613 
614 /*
615  * Invalidate all entries to a particular vnode.
616  */
617 void
618 cache_purge(vp)
619 	struct vnode *vp;
620 {
621 
622 	CTR1(KTR_VFS, "cache_purge(%p)", vp);
623 	CACHE_LOCK();
624 	while (!LIST_EMPTY(&vp->v_cache_src))
625 		cache_zap(LIST_FIRST(&vp->v_cache_src));
626 	while (!TAILQ_EMPTY(&vp->v_cache_dst))
627 		cache_zap(TAILQ_FIRST(&vp->v_cache_dst));
628 	vp->v_dd = NULL;
629 	CACHE_UNLOCK();
630 }
631 
632 /*
633  * Flush all entries referencing a particular filesystem.
634  */
635 void
636 cache_purgevfs(mp)
637 	struct mount *mp;
638 {
639 	struct nchashhead *ncpp;
640 	struct namecache *ncp, *nnp;
641 
642 	/* Scan hash tables for applicable entries */
643 	CACHE_LOCK();
644 	for (ncpp = &nchashtbl[nchash]; ncpp >= nchashtbl; ncpp--) {
645 		LIST_FOREACH_SAFE(ncp, ncpp, nc_hash, nnp) {
646 			if (ncp->nc_dvp->v_mount == mp)
647 				cache_zap(ncp);
648 		}
649 	}
650 	CACHE_UNLOCK();
651 }
652 
653 /*
654  * Perform canonical checks and cache lookup and pass on to filesystem
655  * through the vop_cachedlookup only if needed.
656  */
657 
658 int
659 vfs_cache_lookup(ap)
660 	struct vop_lookup_args /* {
661 		struct vnode *a_dvp;
662 		struct vnode **a_vpp;
663 		struct componentname *a_cnp;
664 	} */ *ap;
665 {
666 	struct vnode *dvp;
667 	int error;
668 	struct vnode **vpp = ap->a_vpp;
669 	struct componentname *cnp = ap->a_cnp;
670 	struct ucred *cred = cnp->cn_cred;
671 	int flags = cnp->cn_flags;
672 	struct thread *td = cnp->cn_thread;
673 
674 	*vpp = NULL;
675 	dvp = ap->a_dvp;
676 
677 	if (dvp->v_type != VDIR)
678 		return (ENOTDIR);
679 
680 	if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
681 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
682 		return (EROFS);
683 
684 	error = VOP_ACCESS(dvp, VEXEC, cred, td);
685 	if (error)
686 		return (error);
687 
688 	error = cache_lookup(dvp, vpp, cnp);
689 	if (error == 0)
690 		return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
691 	if (error == -1)
692 		return (0);
693 	return (error);
694 }
695 
696 
697 #ifndef _SYS_SYSPROTO_H_
698 struct  __getcwd_args {
699 	u_char	*buf;
700 	u_int	buflen;
701 };
702 #endif
703 
704 /*
705  * XXX All of these sysctls would probably be more productive dead.
706  */
707 static int disablecwd;
708 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0,
709    "Disable the getcwd syscall");
710 
711 /* Implementation of the getcwd syscall. */
712 int
713 __getcwd(td, uap)
714 	struct thread *td;
715 	struct __getcwd_args *uap;
716 {
717 
718 	return (kern___getcwd(td, uap->buf, UIO_USERSPACE, uap->buflen));
719 }
720 
721 int
722 kern___getcwd(struct thread *td, u_char *buf, enum uio_seg bufseg, u_int buflen)
723 {
724 	char *bp, *tmpbuf;
725 	struct filedesc *fdp;
726 	struct vnode *cdir, *rdir;
727 	int error, vfslocked;
728 
729 	if (disablecwd)
730 		return (ENODEV);
731 	if (buflen < 2)
732 		return (EINVAL);
733 	if (buflen > MAXPATHLEN)
734 		buflen = MAXPATHLEN;
735 
736 	tmpbuf = malloc(buflen, M_TEMP, M_WAITOK);
737 	fdp = td->td_proc->p_fd;
738 	FILEDESC_SLOCK(fdp);
739 	cdir = fdp->fd_cdir;
740 	VREF(cdir);
741 	rdir = fdp->fd_rdir;
742 	VREF(rdir);
743 	FILEDESC_SUNLOCK(fdp);
744 	error = vn_fullpath1(td, cdir, rdir, tmpbuf, &bp, buflen);
745 	vfslocked = VFS_LOCK_GIANT(rdir->v_mount);
746 	vrele(rdir);
747 	VFS_UNLOCK_GIANT(vfslocked);
748 	vfslocked = VFS_LOCK_GIANT(cdir->v_mount);
749 	vrele(cdir);
750 	VFS_UNLOCK_GIANT(vfslocked);
751 
752 	if (!error) {
753 		if (bufseg == UIO_SYSSPACE)
754 			bcopy(bp, buf, strlen(bp) + 1);
755 		else
756 			error = copyout(bp, buf, strlen(bp) + 1);
757 	}
758 	free(tmpbuf, M_TEMP);
759 	return (error);
760 }
761 
762 /*
763  * Thus begins the fullpath magic.
764  */
765 
766 #undef STATNODE
767 #define STATNODE(name)							\
768 	static u_int name;						\
769 	SYSCTL_UINT(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, "")
770 
771 static int disablefullpath;
772 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW, &disablefullpath, 0,
773 	"Disable the vn_fullpath function");
774 
775 /* These count for kern___getcwd(), too. */
776 STATNODE(numfullpathcalls);
777 STATNODE(numfullpathfail1);
778 STATNODE(numfullpathfail2);
779 STATNODE(numfullpathfail4);
780 STATNODE(numfullpathfound);
781 
782 /*
783  * Retrieve the full filesystem path that correspond to a vnode from the name
784  * cache (if available)
785  */
786 int
787 vn_fullpath(struct thread *td, struct vnode *vn, char **retbuf, char **freebuf)
788 {
789 	char *buf;
790 	struct filedesc *fdp;
791 	struct vnode *rdir;
792 	int error, vfslocked;
793 
794 	if (disablefullpath)
795 		return (ENODEV);
796 	if (vn == NULL)
797 		return (EINVAL);
798 
799 	buf = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
800 	fdp = td->td_proc->p_fd;
801 	FILEDESC_SLOCK(fdp);
802 	rdir = fdp->fd_rdir;
803 	VREF(rdir);
804 	FILEDESC_SUNLOCK(fdp);
805 	error = vn_fullpath1(td, vn, rdir, buf, retbuf, MAXPATHLEN);
806 	vfslocked = VFS_LOCK_GIANT(rdir->v_mount);
807 	vrele(rdir);
808 	VFS_UNLOCK_GIANT(vfslocked);
809 
810 	if (!error)
811 		*freebuf = buf;
812 	else
813 		free(buf, M_TEMP);
814 	return (error);
815 }
816 
817 /*
818  * This function is similar to vn_fullpath, but it attempts to lookup the
819  * pathname relative to the global root mount point.  This is required for the
820  * auditing sub-system, as audited pathnames must be absolute, relative to the
821  * global root mount point.
822  */
823 int
824 vn_fullpath_global(struct thread *td, struct vnode *vn,
825     char **retbuf, char **freebuf)
826 {
827 	char *buf;
828 	int error;
829 
830 	if (disablefullpath)
831 		return (ENODEV);
832 	if (vn == NULL)
833 		return (EINVAL);
834 	buf = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
835 	error = vn_fullpath1(td, vn, rootvnode, buf, retbuf, MAXPATHLEN);
836 	if (!error)
837 		*freebuf = buf;
838 	else
839 		free(buf, M_TEMP);
840 	return (error);
841 }
842 
843 /*
844  * The magic behind kern___getcwd() and vn_fullpath().
845  */
846 static int
847 vn_fullpath1(struct thread *td, struct vnode *vp, struct vnode *rdir,
848     char *buf, char **retbuf, u_int buflen)
849 {
850 	char *bp;
851 	int error, i, slash_prefixed;
852 	struct namecache *ncp;
853 
854 	bp = buf + buflen - 1;
855 	*bp = '\0';
856 	error = 0;
857 	slash_prefixed = 0;
858 
859 	CACHE_LOCK();
860 	numfullpathcalls++;
861 	if (vp->v_type != VDIR) {
862 		ncp = TAILQ_FIRST(&vp->v_cache_dst);
863 		if (!ncp) {
864 			numfullpathfail2++;
865 			CACHE_UNLOCK();
866 			return (ENOENT);
867 		}
868 		for (i = ncp->nc_nlen - 1; i >= 0 && bp > buf; i--)
869 			*--bp = ncp->nc_name[i];
870 		if (bp == buf) {
871 			numfullpathfail4++;
872 			CACHE_UNLOCK();
873 			return (ENOMEM);
874 		}
875 		*--bp = '/';
876 		slash_prefixed = 1;
877 		vp = ncp->nc_dvp;
878 	}
879 	while (vp != rdir && vp != rootvnode) {
880 		if (vp->v_vflag & VV_ROOT) {
881 			if (vp->v_iflag & VI_DOOMED) {	/* forced unmount */
882 				error = EBADF;
883 				break;
884 			}
885 			vp = vp->v_mount->mnt_vnodecovered;
886 			continue;
887 		}
888 		if (vp->v_dd == NULL) {
889 			numfullpathfail1++;
890 			error = ENOTDIR;
891 			break;
892 		}
893 		ncp = TAILQ_FIRST(&vp->v_cache_dst);
894 		if (!ncp) {
895 			numfullpathfail2++;
896 			error = ENOENT;
897 			break;
898 		}
899 		MPASS(ncp->nc_dvp == vp->v_dd);
900 		for (i = ncp->nc_nlen - 1; i >= 0 && bp != buf; i--)
901 			*--bp = ncp->nc_name[i];
902 		if (bp == buf) {
903 			numfullpathfail4++;
904 			error = ENOMEM;
905 			break;
906 		}
907 		*--bp = '/';
908 		slash_prefixed = 1;
909 		vp = ncp->nc_dvp;
910 	}
911 	if (error) {
912 		CACHE_UNLOCK();
913 		return (error);
914 	}
915 	if (!slash_prefixed) {
916 		if (bp == buf) {
917 			numfullpathfail4++;
918 			CACHE_UNLOCK();
919 			return (ENOMEM);
920 		} else {
921 			*--bp = '/';
922 		}
923 	}
924 	numfullpathfound++;
925 	CACHE_UNLOCK();
926 
927 	*retbuf = bp;
928 	return (0);
929 }
930 
931 int
932 vn_commname(struct vnode *vp, char *buf, u_int buflen)
933 {
934 	struct namecache *ncp;
935 	int l;
936 
937 	CACHE_LOCK();
938 	ncp = TAILQ_FIRST(&vp->v_cache_dst);
939 	if (!ncp) {
940 		CACHE_UNLOCK();
941 		return (ENOENT);
942 	}
943 	l = min(ncp->nc_nlen, buflen - 1);
944 	memcpy(buf, ncp->nc_name, l);
945 	CACHE_UNLOCK();
946 	buf[l] = '\0';
947 	return (0);
948 }
949