xref: /dragonfly/sys/kern/vfs_cache.c (revision c2cd059b)
1 /*
2  * Copyright (c) 2003,2004 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
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
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * Copyright (c) 1989, 1993, 1995
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * This code is derived from software contributed to Berkeley by
38  * Poul-Henning Kamp of the FreeBSD Project.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. All advertising materials mentioning features or use of this software
49  *    must display the following acknowledgement:
50  *	This product includes software developed by the University of
51  *	California, Berkeley and its contributors.
52  * 4. Neither the name of the University nor the names of its contributors
53  *    may be used to endorse or promote products derived from this software
54  *    without specific prior written permission.
55  *
56  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
57  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
58  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
59  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
60  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
61  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
62  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
64  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
65  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66  * SUCH DAMAGE.
67  *
68  *	@(#)vfs_cache.c	8.5 (Berkeley) 3/22/95
69  * $FreeBSD: src/sys/kern/vfs_cache.c,v 1.42.2.6 2001/10/05 20:07:03 dillon Exp $
70  * $DragonFly: src/sys/kern/vfs_cache.c,v 1.61 2006/03/21 18:14:43 dillon Exp $
71  */
72 
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/kernel.h>
76 #include <sys/sysctl.h>
77 #include <sys/mount.h>
78 #include <sys/vnode.h>
79 #include <sys/malloc.h>
80 #include <sys/sysproto.h>
81 #include <sys/proc.h>
82 #include <sys/namei.h>
83 #include <sys/nlookup.h>
84 #include <sys/filedesc.h>
85 #include <sys/fnv_hash.h>
86 #include <sys/globaldata.h>
87 #include <sys/kern_syscall.h>
88 #include <sys/dirent.h>
89 #include <ddb/ddb.h>
90 
91 /*
92  * Random lookups in the cache are accomplished with a hash table using
93  * a hash key of (nc_src_vp, name).
94  *
95  * Negative entries may exist and correspond to structures where nc_vp
96  * is NULL.  In a negative entry, NCF_WHITEOUT will be set if the entry
97  * corresponds to a whited-out directory entry (verses simply not finding the
98  * entry at all).
99  *
100  * Upon reaching the last segment of a path, if the reference is for DELETE,
101  * or NOCACHE is set (rewrite), and the name is located in the cache, it
102  * will be dropped.
103  */
104 
105 /*
106  * Structures associated with name cacheing.
107  */
108 #define NCHHASH(hash)	(&nchashtbl[(hash) & nchash])
109 #define MINNEG		1024
110 
111 MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
112 
113 static LIST_HEAD(nchashhead, namecache) *nchashtbl;	/* Hash Table */
114 static struct namecache_list	ncneglist;		/* instead of vnode */
115 
116 /*
117  * ncvp_debug - debug cache_fromvp().  This is used by the NFS server
118  * to create the namecache infrastructure leading to a dangling vnode.
119  *
120  * 0	Only errors are reported
121  * 1	Successes are reported
122  * 2	Successes + the whole directory scan is reported
123  * 3	Force the directory scan code run as if the parent vnode did not
124  *	have a namecache record, even if it does have one.
125  */
126 static int	ncvp_debug;
127 SYSCTL_INT(_debug, OID_AUTO, ncvp_debug, CTLFLAG_RW, &ncvp_debug, 0, "");
128 
129 static u_long	nchash;			/* size of hash table */
130 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0, "");
131 
132 static u_long	ncnegfactor = 16;	/* ratio of negative entries */
133 SYSCTL_ULONG(_debug, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0, "");
134 
135 static int	nclockwarn;		/* warn on locked entries in ticks */
136 SYSCTL_INT(_debug, OID_AUTO, nclockwarn, CTLFLAG_RW, &nclockwarn, 0, "");
137 
138 static u_long	numneg;		/* number of cache entries allocated */
139 SYSCTL_ULONG(_debug, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0, "");
140 
141 static u_long	numcache;		/* number of cache entries allocated */
142 SYSCTL_ULONG(_debug, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0, "");
143 
144 static u_long	numunres;		/* number of unresolved entries */
145 SYSCTL_ULONG(_debug, OID_AUTO, numunres, CTLFLAG_RD, &numunres, 0, "");
146 
147 SYSCTL_INT(_debug, OID_AUTO, vnsize, CTLFLAG_RD, 0, sizeof(struct vnode), "");
148 SYSCTL_INT(_debug, OID_AUTO, ncsize, CTLFLAG_RD, 0, sizeof(struct namecache), "");
149 
150 static int cache_resolve_mp(struct namecache *ncp);
151 static void cache_rehash(struct namecache *ncp);
152 
153 /*
154  * The new name cache statistics
155  */
156 SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0, "Name cache statistics");
157 #define STATNODE(mode, name, var) \
158 	SYSCTL_ULONG(_vfs_cache, OID_AUTO, name, mode, var, 0, "");
159 STATNODE(CTLFLAG_RD, numneg, &numneg);
160 STATNODE(CTLFLAG_RD, numcache, &numcache);
161 static u_long numcalls; STATNODE(CTLFLAG_RD, numcalls, &numcalls);
162 static u_long dothits; STATNODE(CTLFLAG_RD, dothits, &dothits);
163 static u_long dotdothits; STATNODE(CTLFLAG_RD, dotdothits, &dotdothits);
164 static u_long numchecks; STATNODE(CTLFLAG_RD, numchecks, &numchecks);
165 static u_long nummiss; STATNODE(CTLFLAG_RD, nummiss, &nummiss);
166 static u_long nummisszap; STATNODE(CTLFLAG_RD, nummisszap, &nummisszap);
167 static u_long numposzaps; STATNODE(CTLFLAG_RD, numposzaps, &numposzaps);
168 static u_long numposhits; STATNODE(CTLFLAG_RD, numposhits, &numposhits);
169 static u_long numnegzaps; STATNODE(CTLFLAG_RD, numnegzaps, &numnegzaps);
170 static u_long numneghits; STATNODE(CTLFLAG_RD, numneghits, &numneghits);
171 
172 struct nchstats nchstats[SMP_MAXCPU];
173 /*
174  * Export VFS cache effectiveness statistics to user-land.
175  *
176  * The statistics are left for aggregation to user-land so
177  * neat things can be achieved, like observing per-CPU cache
178  * distribution.
179  */
180 static int
181 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
182 {
183 	struct globaldata *gd;
184 	int i, error;
185 
186 	error = 0;
187 	for (i = 0; i < ncpus; ++i) {
188 		gd = globaldata_find(i);
189 		if ((error = SYSCTL_OUT(req, (void *)&(*gd->gd_nchstats),
190 			sizeof(struct nchstats))))
191 			break;
192 	}
193 
194 	return (error);
195 }
196 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE|CTLFLAG_RD,
197   0, 0, sysctl_nchstats, "S,nchstats", "VFS cache effectiveness statistics");
198 
199 static void cache_zap(struct namecache *ncp);
200 
201 /*
202  * cache_hold() and cache_drop() prevent the premature deletion of a
203  * namecache entry but do not prevent operations (such as zapping) on
204  * that namecache entry.
205  */
206 static __inline
207 struct namecache *
208 _cache_hold(struct namecache *ncp)
209 {
210 	++ncp->nc_refs;
211 	return(ncp);
212 }
213 
214 /*
215  * When dropping an entry, if only one ref remains and the entry has not
216  * been resolved, zap it.  Since the one reference is being dropped the
217  * entry had better not be locked.
218  */
219 static __inline
220 void
221 _cache_drop(struct namecache *ncp)
222 {
223 	KKASSERT(ncp->nc_refs > 0);
224 	if (ncp->nc_refs == 1 &&
225 	    (ncp->nc_flag & NCF_UNRESOLVED) &&
226 	    TAILQ_EMPTY(&ncp->nc_list)
227 	) {
228 		KKASSERT(ncp->nc_exlocks == 0);
229 		cache_lock(ncp);
230 		cache_zap(ncp);
231 	} else {
232 		--ncp->nc_refs;
233 	}
234 }
235 
236 /*
237  * Link a new namecache entry to its parent.  Be careful to avoid races
238  * if vhold() blocks in the future.
239  *
240  * If we are creating a child under an oldapi parent we must mark the
241  * child as being an oldapi entry as well.
242  */
243 static void
244 cache_link_parent(struct namecache *ncp, struct namecache *par)
245 {
246 	KKASSERT(ncp->nc_parent == NULL);
247 	ncp->nc_parent = par;
248 	if (TAILQ_EMPTY(&par->nc_list)) {
249 		TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
250 		/*
251 		 * Any vp associated with an ncp which has children must
252 		 * be held to prevent it from being recycled.
253 		 */
254 		if (par->nc_vp)
255 			vhold(par->nc_vp);
256 	} else {
257 		TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
258 	}
259 }
260 
261 /*
262  * Remove the parent association from a namecache structure.  If this is
263  * the last child of the parent the cache_drop(par) will attempt to
264  * recursively zap the parent.
265  */
266 static void
267 cache_unlink_parent(struct namecache *ncp)
268 {
269 	struct namecache *par;
270 
271 	if ((par = ncp->nc_parent) != NULL) {
272 		ncp->nc_parent = NULL;
273 		par = cache_hold(par);
274 		TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
275 		if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
276 			vdrop(par->nc_vp);
277 		cache_drop(par);
278 	}
279 }
280 
281 /*
282  * Allocate a new namecache structure.  Most of the code does not require
283  * zero-termination of the string but it makes vop_compat_ncreate() easier.
284  */
285 static struct namecache *
286 cache_alloc(int nlen)
287 {
288 	struct namecache *ncp;
289 
290 	ncp = malloc(sizeof(*ncp), M_VFSCACHE, M_WAITOK|M_ZERO);
291 	if (nlen)
292 		ncp->nc_name = malloc(nlen + 1, M_VFSCACHE, M_WAITOK);
293 	ncp->nc_nlen = nlen;
294 	ncp->nc_flag = NCF_UNRESOLVED;
295 	ncp->nc_error = ENOTCONN;	/* needs to be resolved */
296 	ncp->nc_refs = 1;
297 	ncp->nc_fsmid = 1;
298 	TAILQ_INIT(&ncp->nc_list);
299 	cache_lock(ncp);
300 	return(ncp);
301 }
302 
303 static void
304 cache_free(struct namecache *ncp)
305 {
306 	KKASSERT(ncp->nc_refs == 1 && ncp->nc_exlocks == 1);
307 	if (ncp->nc_name)
308 		free(ncp->nc_name, M_VFSCACHE);
309 	free(ncp, M_VFSCACHE);
310 }
311 
312 /*
313  * Ref and deref a namecache structure.
314  */
315 struct namecache *
316 cache_hold(struct namecache *ncp)
317 {
318 	return(_cache_hold(ncp));
319 }
320 
321 void
322 cache_drop(struct namecache *ncp)
323 {
324 	_cache_drop(ncp);
325 }
326 
327 /*
328  * Namespace locking.  The caller must already hold a reference to the
329  * namecache structure in order to lock/unlock it.  This function prevents
330  * the namespace from being created or destroyed by accessors other then
331  * the lock holder.
332  *
333  * Note that holding a locked namecache structure prevents other threads
334  * from making namespace changes (e.g. deleting or creating), prevents
335  * vnode association state changes by other threads, and prevents the
336  * namecache entry from being resolved or unresolved by other threads.
337  *
338  * The lock owner has full authority to associate/disassociate vnodes
339  * and resolve/unresolve the locked ncp.
340  *
341  * In particular, if a vnode is associated with a locked cache entry
342  * that vnode will *NOT* be recycled.  We accomplish this by vhold()ing the
343  * vnode.  XXX we should find a more efficient way to prevent the vnode
344  * from being recycled, but remember that any given vnode may have multiple
345  * namecache associations (think hardlinks).
346  */
347 void
348 cache_lock(struct namecache *ncp)
349 {
350 	thread_t td;
351 	int didwarn;
352 
353 	KKASSERT(ncp->nc_refs != 0);
354 	didwarn = 0;
355 	td = curthread;
356 
357 	for (;;) {
358 		if (ncp->nc_exlocks == 0) {
359 			ncp->nc_exlocks = 1;
360 			ncp->nc_locktd = td;
361 			/*
362 			 * The vp associated with a locked ncp must be held
363 			 * to prevent it from being recycled (which would
364 			 * cause the ncp to become unresolved).
365 			 *
366 			 * XXX loop on race for later MPSAFE work.
367 			 */
368 			if (ncp->nc_vp)
369 				vhold(ncp->nc_vp);
370 			break;
371 		}
372 		if (ncp->nc_locktd == td) {
373 			++ncp->nc_exlocks;
374 			break;
375 		}
376 		ncp->nc_flag |= NCF_LOCKREQ;
377 		if (tsleep(ncp, 0, "clock", nclockwarn) == EWOULDBLOCK) {
378 			if (didwarn)
379 				continue;
380 			didwarn = 1;
381 			printf("[diagnostic] cache_lock: blocked on %p", ncp);
382 			if ((ncp->nc_flag & NCF_MOUNTPT) && ncp->nc_mount)
383 			    printf(" [MOUNTFROM %s]\n", ncp->nc_mount->mnt_stat.f_mntfromname);
384 			else
385 			    printf(" \"%*.*s\"\n",
386 				ncp->nc_nlen, ncp->nc_nlen,
387 				ncp->nc_name);
388 		}
389 	}
390 
391 	if (didwarn == 1) {
392 		printf("[diagnostic] cache_lock: unblocked %*.*s\n",
393 			ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
394 	}
395 }
396 
397 int
398 cache_lock_nonblock(struct namecache *ncp)
399 {
400 	thread_t td;
401 
402 	KKASSERT(ncp->nc_refs != 0);
403 	td = curthread;
404 	if (ncp->nc_exlocks == 0) {
405 		ncp->nc_exlocks = 1;
406 		ncp->nc_locktd = td;
407 		/*
408 		 * The vp associated with a locked ncp must be held
409 		 * to prevent it from being recycled (which would
410 		 * cause the ncp to become unresolved).
411 		 *
412 		 * XXX loop on race for later MPSAFE work.
413 		 */
414 		if (ncp->nc_vp)
415 			vhold(ncp->nc_vp);
416 		return(0);
417 	} else {
418 		return(EWOULDBLOCK);
419 	}
420 }
421 
422 void
423 cache_unlock(struct namecache *ncp)
424 {
425 	thread_t td = curthread;
426 
427 	KKASSERT(ncp->nc_refs > 0);
428 	KKASSERT(ncp->nc_exlocks > 0);
429 	KKASSERT(ncp->nc_locktd == td);
430 	if (--ncp->nc_exlocks == 0) {
431 		if (ncp->nc_vp)
432 			vdrop(ncp->nc_vp);
433 		ncp->nc_locktd = NULL;
434 		if (ncp->nc_flag & NCF_LOCKREQ) {
435 			ncp->nc_flag &= ~NCF_LOCKREQ;
436 			wakeup(ncp);
437 		}
438 	}
439 }
440 
441 /*
442  * ref-and-lock, unlock-and-deref functions.
443  */
444 struct namecache *
445 cache_get(struct namecache *ncp)
446 {
447 	_cache_hold(ncp);
448 	cache_lock(ncp);
449 	return(ncp);
450 }
451 
452 int
453 cache_get_nonblock(struct namecache *ncp)
454 {
455 	/* XXX MP */
456 	if (ncp->nc_exlocks == 0 || ncp->nc_locktd == curthread) {
457 		_cache_hold(ncp);
458 		cache_lock(ncp);
459 		return(0);
460 	}
461 	return(EWOULDBLOCK);
462 }
463 
464 void
465 cache_put(struct namecache *ncp)
466 {
467 	cache_unlock(ncp);
468 	_cache_drop(ncp);
469 }
470 
471 /*
472  * Resolve an unresolved ncp by associating a vnode with it.  If the
473  * vnode is NULL, a negative cache entry is created.
474  *
475  * The ncp should be locked on entry and will remain locked on return.
476  */
477 void
478 cache_setvp(struct namecache *ncp, struct vnode *vp)
479 {
480 	KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
481 	ncp->nc_vp = vp;
482 	if (vp != NULL) {
483 		/*
484 		 * Any vp associated with an ncp which has children must
485 		 * be held.  Any vp associated with a locked ncp must be held.
486 		 */
487 		if (!TAILQ_EMPTY(&ncp->nc_list))
488 			vhold(vp);
489 		TAILQ_INSERT_HEAD(&vp->v_namecache, ncp, nc_vnode);
490 		if (ncp->nc_exlocks)
491 			vhold(vp);
492 
493 		/*
494 		 * Set auxillary flags
495 		 */
496 		switch(vp->v_type) {
497 		case VDIR:
498 			ncp->nc_flag |= NCF_ISDIR;
499 			break;
500 		case VLNK:
501 			ncp->nc_flag |= NCF_ISSYMLINK;
502 			/* XXX cache the contents of the symlink */
503 			break;
504 		default:
505 			break;
506 		}
507 		++numcache;
508 		ncp->nc_error = 0;
509 	} else {
510 		TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
511 		++numneg;
512 		ncp->nc_error = ENOENT;
513 	}
514 	ncp->nc_flag &= ~NCF_UNRESOLVED;
515 }
516 
517 void
518 cache_settimeout(struct namecache *ncp, int nticks)
519 {
520 	if ((ncp->nc_timeout = ticks + nticks) == 0)
521 		ncp->nc_timeout = 1;
522 }
523 
524 /*
525  * Disassociate the vnode or negative-cache association and mark a
526  * namecache entry as unresolved again.  Note that the ncp is still
527  * left in the hash table and still linked to its parent.
528  *
529  * The ncp should be locked and refd on entry and will remain locked and refd
530  * on return.
531  *
532  * This routine is normally never called on a directory containing children.
533  * However, NFS often does just that in its rename() code as a cop-out to
534  * avoid complex namespace operations.  This disconnects a directory vnode
535  * from its namecache and can cause the OLDAPI and NEWAPI to get out of
536  * sync.
537  *
538  * NOTE: NCF_FSMID must be cleared so a refurbishment of the ncp, such as
539  * in a create, properly propogates flag up the chain.
540  */
541 void
542 cache_setunresolved(struct namecache *ncp)
543 {
544 	struct vnode *vp;
545 
546 	if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
547 		ncp->nc_flag |= NCF_UNRESOLVED;
548 		ncp->nc_flag &= ~(NCF_WHITEOUT|NCF_ISDIR|NCF_ISSYMLINK|
549 				  NCF_FSMID);
550 		ncp->nc_timeout = 0;
551 		ncp->nc_error = ENOTCONN;
552 		++numunres;
553 		if ((vp = ncp->nc_vp) != NULL) {
554 			--numcache;
555 			ncp->nc_vp = NULL;
556 			TAILQ_REMOVE(&vp->v_namecache, ncp, nc_vnode);
557 
558 			/*
559 			 * Any vp associated with an ncp with children is
560 			 * held by that ncp.  Any vp associated with a locked
561 			 * ncp is held by that ncp.  These conditions must be
562 			 * undone when the vp is cleared out from the ncp.
563 			 */
564 			if (!TAILQ_EMPTY(&ncp->nc_list))
565 				vdrop(vp);
566 			if (ncp->nc_exlocks)
567 				vdrop(vp);
568 		} else {
569 			TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
570 			--numneg;
571 		}
572 	}
573 }
574 
575 /*
576  * Invalidate portions of the namecache topology given a starting entry.
577  * The passed ncp is set to an unresolved state and:
578  *
579  * The passed ncp must be locked.
580  *
581  * CINV_DESTROY		- Set a flag in the passed ncp entry indicating
582  *			  that the physical underlying nodes have been
583  *			  destroyed... as in deleted.  For example, when
584  *			  a directory is removed.  This will cause record
585  *			  lookups on the name to no longer be able to find
586  *			  the record and tells the resolver to return failure
587  *			  rather then trying to resolve through the parent.
588  *
589  *			  The topology itself, including ncp->nc_name,
590  *			  remains intact.
591  *
592  *			  This only applies to the passed ncp, if CINV_CHILDREN
593  *			  is specified the children are not flagged.
594  *
595  * CINV_CHILDREN	- Set all children (recursively) to an unresolved
596  *			  state as well.
597  *
598  *			  Note that this will also have the side effect of
599  *			  cleaning out any unreferenced nodes in the topology
600  *			  from the leaves up as the recursion backs out.
601  *
602  * Note that the topology for any referenced nodes remains intact.
603  *
604  * It is possible for cache_inval() to race a cache_resolve(), meaning that
605  * the namecache entry may not actually be invalidated on return if it was
606  * revalidated while recursing down into its children.  This code guarentees
607  * that the node(s) will go through an invalidation cycle, but does not
608  * guarentee that they will remain in an invalidated state.
609  *
610  * Returns non-zero if a revalidation was detected during the invalidation
611  * recursion, zero otherwise.  Note that since only the original ncp is
612  * locked the revalidation ultimately can only indicate that the original ncp
613  * *MIGHT* no have been reresolved.
614  */
615 int
616 cache_inval(struct namecache *ncp, int flags)
617 {
618 	struct namecache *kid;
619 	struct namecache *nextkid;
620 	int rcnt = 0;
621 
622 	KKASSERT(ncp->nc_exlocks);
623 
624 	cache_setunresolved(ncp);
625 	if (flags & CINV_DESTROY)
626 		ncp->nc_flag |= NCF_DESTROYED;
627 
628 	if ((flags & CINV_CHILDREN) &&
629 	    (kid = TAILQ_FIRST(&ncp->nc_list)) != NULL
630 	) {
631 		cache_hold(kid);
632 		cache_unlock(ncp);
633 		while (kid) {
634 			if ((nextkid = TAILQ_NEXT(kid, nc_entry)) != NULL)
635 				cache_hold(nextkid);
636 			if ((kid->nc_flag & NCF_UNRESOLVED) == 0 ||
637 			    TAILQ_FIRST(&kid->nc_list)
638 			) {
639 				cache_lock(kid);
640 				rcnt += cache_inval(kid, flags & ~CINV_DESTROY);
641 				cache_unlock(kid);
642 			}
643 			cache_drop(kid);
644 			kid = nextkid;
645 		}
646 		cache_lock(ncp);
647 	}
648 
649 	/*
650 	 * Someone could have gotten in there while ncp was unlocked,
651 	 * retry if so.
652 	 */
653 	if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
654 		++rcnt;
655 	return (rcnt);
656 }
657 
658 /*
659  * Invalidate a vnode's namecache associations.  To avoid races against
660  * the resolver we do not invalidate a node which we previously invalidated
661  * but which was then re-resolved while we were in the invalidation loop.
662  *
663  * Returns non-zero if any namecache entries remain after the invalidation
664  * loop completed.
665  *
666  * NOTE: unlike the namecache topology which guarentees that ncp's will not
667  * be ripped out of the topology while held, the vnode's v_namecache list
668  * has no such restriction.  NCP's can be ripped out of the list at virtually
669  * any time if not locked, even if held.
670  */
671 int
672 cache_inval_vp(struct vnode *vp, int flags, int *retflags)
673 {
674 	struct namecache *ncp;
675 	struct namecache *next;
676 
677 restart:
678 	ncp = TAILQ_FIRST(&vp->v_namecache);
679 	if (ncp)
680 		cache_hold(ncp);
681 	while (ncp) {
682 		/* loop entered with ncp held */
683 		if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
684 			cache_hold(next);
685 		cache_lock(ncp);
686 		if (ncp->nc_vp != vp) {
687 			printf("Warning: cache_inval_vp: race-A detected on "
688 				"%s\n", ncp->nc_name);
689 			cache_put(ncp);
690 			if (next)
691 				cache_drop(next);
692 			goto restart;
693 		}
694 		*retflags |= ncp->nc_flag & NCF_FSMID;
695 		cache_inval(ncp, flags);
696 		cache_put(ncp);		/* also releases reference */
697 		ncp = next;
698 		if (ncp && ncp->nc_vp != vp) {
699 			printf("Warning: cache_inval_vp: race-B detected on "
700 				"%s\n", ncp->nc_name);
701 			cache_drop(ncp);
702 			goto restart;
703 		}
704 	}
705 	return(TAILQ_FIRST(&vp->v_namecache) != NULL);
706 }
707 
708 /*
709  * The source ncp has been renamed to the target ncp.  Both fncp and tncp
710  * must be locked.  Both will be set to unresolved, any children of tncp
711  * will be disconnected (the prior contents of the target is assumed to be
712  * destroyed by the rename operation, e.g. renaming over an empty directory),
713  * and all children of fncp will be moved to tncp.
714  *
715  * XXX the disconnection could pose a problem, check code paths to make
716  * sure any code that blocks can handle the parent being changed out from
717  * under it.  Maybe we should lock the children (watch out for deadlocks) ?
718  *
719  * After we return the caller has the option of calling cache_setvp() if
720  * the vnode of the new target ncp is known.
721  *
722  * Any process CD'd into any of the children will no longer be able to ".."
723  * back out.  An rm -rf can cause this situation to occur.
724  */
725 void
726 cache_rename(struct namecache *fncp, struct namecache *tncp)
727 {
728 	struct namecache *scan;
729 	int didwarn = 0;
730 
731 	cache_setunresolved(fncp);
732 	cache_setunresolved(tncp);
733 	while (cache_inval(tncp, CINV_CHILDREN) != 0) {
734 		if (didwarn++ % 10 == 0) {
735 			printf("Warning: cache_rename: race during "
736 				"rename %s->%s\n",
737 				fncp->nc_name, tncp->nc_name);
738 		}
739 		tsleep(tncp, 0, "mvrace", hz / 10);
740 		cache_setunresolved(tncp);
741 	}
742 	while ((scan = TAILQ_FIRST(&fncp->nc_list)) != NULL) {
743 		cache_hold(scan);
744 		cache_unlink_parent(scan);
745 		cache_link_parent(scan, tncp);
746 		if (scan->nc_flag & NCF_HASHED)
747 			cache_rehash(scan);
748 		cache_drop(scan);
749 	}
750 }
751 
752 /*
753  * vget the vnode associated with the namecache entry.  Resolve the namecache
754  * entry if necessary and deal with namecache/vp races.  The passed ncp must
755  * be referenced and may be locked.  The ncp's ref/locking state is not
756  * effected by this call.
757  *
758  * lk_type may be LK_SHARED, LK_EXCLUSIVE.  A ref'd, possibly locked
759  * (depending on the passed lk_type) will be returned in *vpp with an error
760  * of 0, or NULL will be returned in *vpp with a non-0 error code.  The
761  * most typical error is ENOENT, meaning that the ncp represents a negative
762  * cache hit and there is no vnode to retrieve, but other errors can occur
763  * too.
764  *
765  * The main race we have to deal with are namecache zaps.  The ncp itself
766  * will not disappear since it is referenced, and it turns out that the
767  * validity of the vp pointer can be checked simply by rechecking the
768  * contents of ncp->nc_vp.
769  */
770 int
771 cache_vget(struct namecache *ncp, struct ucred *cred,
772 	   int lk_type, struct vnode **vpp)
773 {
774 	struct vnode *vp;
775 	int error;
776 
777 again:
778 	vp = NULL;
779 	if (ncp->nc_flag & NCF_UNRESOLVED) {
780 		cache_lock(ncp);
781 		error = cache_resolve(ncp, cred);
782 		cache_unlock(ncp);
783 	} else {
784 		error = 0;
785 	}
786 	if (error == 0 && (vp = ncp->nc_vp) != NULL) {
787 		error = vget(vp, lk_type, curthread);
788 		if (error) {
789 			if (vp != ncp->nc_vp)	/* handle cache_zap race */
790 				goto again;
791 			vp = NULL;
792 		} else if (vp != ncp->nc_vp) {	/* handle cache_zap race */
793 			vput(vp);
794 			goto again;
795 		}
796 	}
797 	if (error == 0 && vp == NULL)
798 		error = ENOENT;
799 	*vpp = vp;
800 	return(error);
801 }
802 
803 int
804 cache_vref(struct namecache *ncp, struct ucred *cred, struct vnode **vpp)
805 {
806 	struct vnode *vp;
807 	int error;
808 
809 again:
810 	vp = NULL;
811 	if (ncp->nc_flag & NCF_UNRESOLVED) {
812 		cache_lock(ncp);
813 		error = cache_resolve(ncp, cred);
814 		cache_unlock(ncp);
815 	} else {
816 		error = 0;
817 	}
818 	if (error == 0 && (vp = ncp->nc_vp) != NULL) {
819 		vref(vp);
820 		if (vp != ncp->nc_vp) {		/* handle cache_zap race */
821 			vrele(vp);
822 			goto again;
823 		}
824 	}
825 	if (error == 0 && vp == NULL)
826 		error = ENOENT;
827 	*vpp = vp;
828 	return(error);
829 }
830 
831 /*
832  * Recursively set the FSMID update flag for namecache nodes leading
833  * to root.  This will cause the next getattr or reclaim to increment the
834  * fsmid and mark the inode for lazy updating.
835  *
836  * Stop recursing when we hit a node whos NCF_FSMID flag is already set.
837  * This makes FSMIDs work in an Einsteinian fashion - where the observation
838  * effects the result.  In this case a program monitoring a higher level
839  * node will have detected some prior change and started its scan (clearing
840  * NCF_FSMID in higher level nodes), but since it has not yet observed the
841  * node where we find NCF_FSMID still set, we can safely make the related
842  * modification without interfering with the theorized program.
843  *
844  * This also means that FSMIDs cannot represent time-domain quantities
845  * in a hierarchical sense.  But the main reason for doing it this way
846  * is to reduce the amount of recursion that occurs in the critical path
847  * when e.g. a program is writing to a file that sits deep in a directory
848  * hierarchy.
849  */
850 void
851 cache_update_fsmid(struct namecache *ncp)
852 {
853 	struct vnode *vp;
854 	struct namecache *scan;
855 
856 	if ((vp = ncp->nc_vp) != NULL) {
857 		TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
858 			for (scan = ncp; scan; scan = scan->nc_parent) {
859 				if (scan->nc_flag & NCF_FSMID)
860 					break;
861 				scan->nc_flag |= NCF_FSMID;
862 			}
863 		}
864 	} else {
865 		while (ncp && (ncp->nc_flag & NCF_FSMID) == 0) {
866 			ncp->nc_flag |= NCF_FSMID;
867 			ncp = ncp->nc_parent;
868 		}
869 	}
870 }
871 
872 void
873 cache_update_fsmid_vp(struct vnode *vp)
874 {
875 	struct namecache *ncp;
876 	struct namecache *scan;
877 
878 	TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
879 		for (scan = ncp; scan; scan = scan->nc_parent) {
880 			if (scan->nc_flag & NCF_FSMID)
881 				break;
882 			scan->nc_flag |= NCF_FSMID;
883 		}
884 	}
885 }
886 
887 /*
888  * If getattr is called on a vnode (e.g. a stat call), the filesystem
889  * may call this routine to determine if the namecache has the hierarchical
890  * change flag set, requiring the fsmid to be updated.
891  *
892  * Since 0 indicates no support, make sure the filesystem fsmid is at least
893  * 1.
894  */
895 int
896 cache_check_fsmid_vp(struct vnode *vp, int64_t *fsmid)
897 {
898 	struct namecache *ncp;
899 	int changed = 0;
900 
901 	TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
902 		if (ncp->nc_flag & NCF_FSMID) {
903 			ncp->nc_flag &= ~NCF_FSMID;
904 			changed = 1;
905 		}
906 	}
907 	if (*fsmid == 0)
908 		++*fsmid;
909 	if (changed)
910 		++*fsmid;
911 	return(changed);
912 }
913 
914 /*
915  * Convert a directory vnode to a namecache record without any other
916  * knowledge of the topology.  This ONLY works with directory vnodes and
917  * is ONLY used by the NFS server.  dvp must be refd but unlocked, and the
918  * returned ncp (if not NULL) will be held and unlocked.
919  *
920  * If 'makeit' is 0 and dvp has no existing namecache record, NULL is returned.
921  * If 'makeit' is 1 we attempt to track-down and create the namecache topology
922  * for dvp.  This will fail only if the directory has been deleted out from
923  * under the caller.
924  *
925  * Callers must always check for a NULL return no matter the value of 'makeit'.
926  *
927  * To avoid underflowing the kernel stack each recursive call increments
928  * the makeit variable.
929  */
930 
931 static int cache_inefficient_scan(struct namecache *ncp, struct ucred *cred,
932 				  struct vnode *dvp);
933 static int cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
934 				  struct vnode **saved_dvp);
935 
936 struct namecache *
937 cache_fromdvp(struct vnode *dvp, struct ucred *cred, int makeit)
938 {
939 	struct namecache *ncp;
940 	struct vnode *saved_dvp;
941 	struct vnode *pvp;
942 	int error;
943 
944 	ncp = NULL;
945 	saved_dvp = NULL;
946 
947 	/*
948 	 * Temporary debugging code to force the directory scanning code
949 	 * to be exercised.
950 	 */
951 	if (ncvp_debug >= 3 && makeit && TAILQ_FIRST(&dvp->v_namecache)) {
952 		ncp = TAILQ_FIRST(&dvp->v_namecache);
953 		printf("cache_fromdvp: forcing %s\n", ncp->nc_name);
954 		goto force;
955 	}
956 
957 	/*
958 	 * Loop until resolution, inside code will break out on error.
959 	 */
960 	while ((ncp = TAILQ_FIRST(&dvp->v_namecache)) == NULL && makeit) {
961 force:
962 		/*
963 		 * If dvp is the root of its filesystem it should already
964 		 * have a namecache pointer associated with it as a side
965 		 * effect of the mount, but it may have been disassociated.
966 		 */
967 		if (dvp->v_flag & VROOT) {
968 			ncp = cache_get(dvp->v_mount->mnt_ncp);
969 			error = cache_resolve_mp(ncp);
970 			cache_put(ncp);
971 			if (ncvp_debug) {
972 				printf("cache_fromdvp: resolve root of mount %p error %d",
973 					dvp->v_mount, error);
974 			}
975 			if (error) {
976 				if (ncvp_debug)
977 					printf(" failed\n");
978 				ncp = NULL;
979 				break;
980 			}
981 			if (ncvp_debug)
982 				printf(" succeeded\n");
983 			continue;
984 		}
985 
986 		/*
987 		 * If we are recursed too deeply resort to an O(n^2)
988 		 * algorithm to resolve the namecache topology.  The
989 		 * resolved pvp is left referenced in saved_dvp to
990 		 * prevent the tree from being destroyed while we loop.
991 		 */
992 		if (makeit > 20) {
993 			error = cache_fromdvp_try(dvp, cred, &saved_dvp);
994 			if (error) {
995 				printf("lookupdotdot(longpath) failed %d "
996 				       "dvp %p\n", error, dvp);
997 				break;
998 			}
999 			continue;
1000 		}
1001 
1002 		/*
1003 		 * Get the parent directory and resolve its ncp.
1004 		 */
1005 		error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred);
1006 		if (error) {
1007 			printf("lookupdotdot failed %d dvp %p\n", error, dvp);
1008 			break;
1009 		}
1010 		VOP_UNLOCK(pvp, 0, curthread);
1011 
1012 		/*
1013 		 * Reuse makeit as a recursion depth counter.
1014 		 */
1015 		ncp = cache_fromdvp(pvp, cred, makeit + 1);
1016 		vrele(pvp);
1017 		if (ncp == NULL)
1018 			break;
1019 
1020 		/*
1021 		 * Do an inefficient scan of pvp (embodied by ncp) to look
1022 		 * for dvp.  This will create a namecache record for dvp on
1023 		 * success.  We loop up to recheck on success.
1024 		 *
1025 		 * ncp and dvp are both held but not locked.
1026 		 */
1027 		error = cache_inefficient_scan(ncp, cred, dvp);
1028 		cache_drop(ncp);
1029 		if (error) {
1030 			printf("cache_fromdvp: scan %p (%s) failed on dvp=%p\n",
1031 				pvp, ncp->nc_name, dvp);
1032 			ncp = NULL;
1033 			break;
1034 		}
1035 		if (ncvp_debug) {
1036 			printf("cache_fromdvp: scan %p (%s) succeeded\n",
1037 				pvp, ncp->nc_name);
1038 		}
1039 	}
1040 	if (ncp)
1041 		cache_hold(ncp);
1042 	if (saved_dvp)
1043 		vrele(saved_dvp);
1044 	return (ncp);
1045 }
1046 
1047 /*
1048  * Go up the chain of parent directories until we find something
1049  * we can resolve into the namecache.  This is very inefficient.
1050  */
1051 static
1052 int
1053 cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1054 		  struct vnode **saved_dvp)
1055 {
1056 	struct namecache *ncp;
1057 	struct vnode *pvp;
1058 	int error;
1059 	static time_t last_fromdvp_report;
1060 
1061 	/*
1062 	 * Loop getting the parent directory vnode until we get something we
1063 	 * can resolve in the namecache.
1064 	 */
1065 	vref(dvp);
1066 	for (;;) {
1067 		error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred);
1068 		if (error) {
1069 			vrele(dvp);
1070 			return (error);
1071 		}
1072 		VOP_UNLOCK(pvp, 0, curthread);
1073 		if ((ncp = TAILQ_FIRST(&pvp->v_namecache)) != NULL) {
1074 			cache_hold(ncp);
1075 			vrele(pvp);
1076 			break;
1077 		}
1078 		if (pvp->v_flag & VROOT) {
1079 			ncp = cache_get(pvp->v_mount->mnt_ncp);
1080 			error = cache_resolve_mp(ncp);
1081 			cache_unlock(ncp);
1082 			vrele(pvp);
1083 			if (error) {
1084 				cache_drop(ncp);
1085 				vrele(dvp);
1086 				return (error);
1087 			}
1088 			break;
1089 		}
1090 		vrele(dvp);
1091 		dvp = pvp;
1092 	}
1093 	if (last_fromdvp_report != time_second) {
1094 		last_fromdvp_report = time_second;
1095 		printf("Warning: extremely inefficient path resolution on %s\n",
1096 			ncp->nc_name);
1097 	}
1098 	error = cache_inefficient_scan(ncp, cred, dvp);
1099 
1100 	/*
1101 	 * Hopefully dvp now has a namecache record associated with it.
1102 	 * Leave it referenced to prevent the kernel from recycling the
1103 	 * vnode.  Otherwise extremely long directory paths could result
1104 	 * in endless recycling.
1105 	 */
1106 	if (*saved_dvp)
1107 	    vrele(*saved_dvp);
1108 	*saved_dvp = dvp;
1109 	return (error);
1110 }
1111 
1112 
1113 /*
1114  * Do an inefficient scan of the directory represented by ncp looking for
1115  * the directory vnode dvp.  ncp must be held but not locked on entry and
1116  * will be held on return.  dvp must be refd but not locked on entry and
1117  * will remain refd on return.
1118  *
1119  * Why do this at all?  Well, due to its stateless nature the NFS server
1120  * converts file handles directly to vnodes without necessarily going through
1121  * the namecache ops that would otherwise create the namecache topology
1122  * leading to the vnode.  We could either (1) Change the namecache algorithms
1123  * to allow disconnect namecache records that are re-merged opportunistically,
1124  * or (2) Make the NFS server backtrack and scan to recover a connected
1125  * namecache topology in order to then be able to issue new API lookups.
1126  *
1127  * It turns out that (1) is a huge mess.  It takes a nice clean set of
1128  * namecache algorithms and introduces a lot of complication in every subsystem
1129  * that calls into the namecache to deal with the re-merge case, especially
1130  * since we are using the namecache to placehold negative lookups and the
1131  * vnode might not be immediately assigned. (2) is certainly far less
1132  * efficient then (1), but since we are only talking about directories here
1133  * (which are likely to remain cached), the case does not actually run all
1134  * that often and has the supreme advantage of not polluting the namecache
1135  * algorithms.
1136  */
1137 static int
1138 cache_inefficient_scan(struct namecache *ncp, struct ucred *cred,
1139 		       struct vnode *dvp)
1140 {
1141 	struct nlcomponent nlc;
1142 	struct namecache *rncp;
1143 	struct dirent *den;
1144 	struct vnode *pvp;
1145 	struct vattr vat;
1146 	struct iovec iov;
1147 	struct uio uio;
1148 	int blksize;
1149 	int eofflag;
1150 	int bytes;
1151 	char *rbuf;
1152 	int error;
1153 
1154 	vat.va_blocksize = 0;
1155 	if ((error = VOP_GETATTR(dvp, &vat, curthread)) != 0)
1156 		return (error);
1157 	if ((error = cache_vget(ncp, cred, LK_SHARED, &pvp)) != 0)
1158 		return (error);
1159 	if (ncvp_debug)
1160 		printf("inefficient_scan: directory iosize %ld vattr fileid = %ld\n", vat.va_blocksize, (long)vat.va_fileid);
1161 	if ((blksize = vat.va_blocksize) == 0)
1162 		blksize = DEV_BSIZE;
1163 	rbuf = malloc(blksize, M_TEMP, M_WAITOK);
1164 	rncp = NULL;
1165 
1166 	eofflag = 0;
1167 	uio.uio_offset = 0;
1168 again:
1169 	iov.iov_base = rbuf;
1170 	iov.iov_len = blksize;
1171 	uio.uio_iov = &iov;
1172 	uio.uio_iovcnt = 1;
1173 	uio.uio_resid = blksize;
1174 	uio.uio_segflg = UIO_SYSSPACE;
1175 	uio.uio_rw = UIO_READ;
1176 	uio.uio_td = curthread;
1177 
1178 	if (ncvp_debug >= 2)
1179 		printf("cache_inefficient_scan: readdir @ %08x\n", (int)uio.uio_offset);
1180 	error = VOP_READDIR(pvp, &uio, cred, &eofflag, NULL, NULL);
1181 	if (error == 0) {
1182 		den = (struct dirent *)rbuf;
1183 		bytes = blksize - uio.uio_resid;
1184 
1185 		while (bytes > 0) {
1186 			if (ncvp_debug >= 2) {
1187 				printf("cache_inefficient_scan: %*.*s\n",
1188 					den->d_namlen, den->d_namlen,
1189 					den->d_name);
1190 			}
1191 			if (den->d_type != DT_WHT &&
1192 			    den->d_ino == vat.va_fileid) {
1193 				if (ncvp_debug) {
1194 					printf("cache_inefficient_scan: "
1195 					       "MATCHED inode %ld path %s/%*.*s\n",
1196 					       vat.va_fileid, ncp->nc_name,
1197 					       den->d_namlen, den->d_namlen,
1198 					       den->d_name);
1199 				}
1200 				nlc.nlc_nameptr = den->d_name;
1201 				nlc.nlc_namelen = den->d_namlen;
1202 				VOP_UNLOCK(pvp, 0, curthread);
1203 				rncp = cache_nlookup(ncp, &nlc);
1204 				KKASSERT(rncp != NULL);
1205 				break;
1206 			}
1207 			bytes -= _DIRENT_DIRSIZ(den);
1208 			den = _DIRENT_NEXT(den);
1209 		}
1210 		if (rncp == NULL && eofflag == 0 && uio.uio_resid != blksize)
1211 			goto again;
1212 	}
1213 	if (rncp) {
1214 		vrele(pvp);
1215 		if (rncp->nc_flag & NCF_UNRESOLVED) {
1216 			cache_setvp(rncp, dvp);
1217 			if (ncvp_debug >= 2) {
1218 				printf("cache_inefficient_scan: setvp %s/%s = %p\n",
1219 					ncp->nc_name, rncp->nc_name, dvp);
1220 			}
1221 		} else {
1222 			if (ncvp_debug >= 2) {
1223 				printf("cache_inefficient_scan: setvp %s/%s already set %p/%p\n",
1224 					ncp->nc_name, rncp->nc_name, dvp,
1225 					rncp->nc_vp);
1226 			}
1227 		}
1228 		if (rncp->nc_vp == NULL)
1229 			error = rncp->nc_error;
1230 		cache_put(rncp);
1231 	} else {
1232 		printf("cache_inefficient_scan: dvp %p NOT FOUND in %s\n",
1233 			dvp, ncp->nc_name);
1234 		vput(pvp);
1235 		error = ENOENT;
1236 	}
1237 	free(rbuf, M_TEMP);
1238 	return (error);
1239 }
1240 
1241 /*
1242  * Zap a namecache entry.  The ncp is unconditionally set to an unresolved
1243  * state, which disassociates it from its vnode or ncneglist.
1244  *
1245  * Then, if there are no additional references to the ncp and no children,
1246  * the ncp is removed from the topology and destroyed.  This function will
1247  * also run through the nc_parent chain and destroy parent ncps if possible.
1248  * As a side benefit, it turns out the only conditions that allow running
1249  * up the chain are also the conditions to ensure no deadlock will occur.
1250  *
1251  * References and/or children may exist if the ncp is in the middle of the
1252  * topology, preventing the ncp from being destroyed.
1253  *
1254  * This function must be called with the ncp held and locked and will unlock
1255  * and drop it during zapping.
1256  */
1257 static void
1258 cache_zap(struct namecache *ncp)
1259 {
1260 	struct namecache *par;
1261 
1262 	/*
1263 	 * Disassociate the vnode or negative cache ref and set NCF_UNRESOLVED.
1264 	 */
1265 	cache_setunresolved(ncp);
1266 
1267 	/*
1268 	 * Try to scrap the entry and possibly tail-recurse on its parent.
1269 	 * We only scrap unref'd (other then our ref) unresolved entries,
1270 	 * we do not scrap 'live' entries.
1271 	 */
1272 	while (ncp->nc_flag & NCF_UNRESOLVED) {
1273 		/*
1274 		 * Someone other then us has a ref, stop.
1275 		 */
1276 		if (ncp->nc_refs > 1)
1277 			goto done;
1278 
1279 		/*
1280 		 * We have children, stop.
1281 		 */
1282 		if (!TAILQ_EMPTY(&ncp->nc_list))
1283 			goto done;
1284 
1285 		/*
1286 		 * Remove ncp from the topology: hash table and parent linkage.
1287 		 */
1288 		if (ncp->nc_flag & NCF_HASHED) {
1289 			ncp->nc_flag &= ~NCF_HASHED;
1290 			LIST_REMOVE(ncp, nc_hash);
1291 		}
1292 		if ((par = ncp->nc_parent) != NULL) {
1293 			par = cache_hold(par);
1294 			TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
1295 			ncp->nc_parent = NULL;
1296 			if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
1297 				vdrop(par->nc_vp);
1298 		}
1299 
1300 		/*
1301 		 * ncp should not have picked up any refs.  Physically
1302 		 * destroy the ncp.
1303 		 */
1304 		KKASSERT(ncp->nc_refs == 1);
1305 		--numunres;
1306 		/* cache_unlock(ncp) not required */
1307 		ncp->nc_refs = -1;	/* safety */
1308 		if (ncp->nc_name)
1309 			free(ncp->nc_name, M_VFSCACHE);
1310 		free(ncp, M_VFSCACHE);
1311 
1312 		/*
1313 		 * Loop on the parent (it may be NULL).  Only bother looping
1314 		 * if the parent has a single ref (ours), which also means
1315 		 * we can lock it trivially.
1316 		 */
1317 		ncp = par;
1318 		if (ncp == NULL)
1319 			return;
1320 		if (ncp->nc_refs != 1) {
1321 			cache_drop(ncp);
1322 			return;
1323 		}
1324 		KKASSERT(par->nc_exlocks == 0);
1325 		cache_lock(ncp);
1326 	}
1327 done:
1328 	cache_unlock(ncp);
1329 	--ncp->nc_refs;
1330 }
1331 
1332 static enum { CHI_LOW, CHI_HIGH } cache_hysteresis_state = CHI_LOW;
1333 
1334 static __inline
1335 void
1336 cache_hysteresis(void)
1337 {
1338 	/*
1339 	 * Don't cache too many negative hits.  We use hysteresis to reduce
1340 	 * the impact on the critical path.
1341 	 */
1342 	switch(cache_hysteresis_state) {
1343 	case CHI_LOW:
1344 		if (numneg > MINNEG && numneg * ncnegfactor > numcache) {
1345 			cache_cleanneg(10);
1346 			cache_hysteresis_state = CHI_HIGH;
1347 		}
1348 		break;
1349 	case CHI_HIGH:
1350 		if (numneg > MINNEG * 9 / 10 &&
1351 		    numneg * ncnegfactor * 9 / 10 > numcache
1352 		) {
1353 			cache_cleanneg(10);
1354 		} else {
1355 			cache_hysteresis_state = CHI_LOW;
1356 		}
1357 		break;
1358 	}
1359 }
1360 
1361 /*
1362  * NEW NAMECACHE LOOKUP API
1363  *
1364  * Lookup an entry in the cache.  A locked, referenced, non-NULL
1365  * entry is *always* returned, even if the supplied component is illegal.
1366  * The resulting namecache entry should be returned to the system with
1367  * cache_put() or cache_unlock() + cache_drop().
1368  *
1369  * namecache locks are recursive but care must be taken to avoid lock order
1370  * reversals.
1371  *
1372  * Nobody else will be able to manipulate the associated namespace (e.g.
1373  * create, delete, rename, rename-target) until the caller unlocks the
1374  * entry.
1375  *
1376  * The returned entry will be in one of three states:  positive hit (non-null
1377  * vnode), negative hit (null vnode), or unresolved (NCF_UNRESOLVED is set).
1378  * Unresolved entries must be resolved through the filesystem to associate the
1379  * vnode and/or determine whether a positive or negative hit has occured.
1380  *
1381  * It is not necessary to lock a directory in order to lock namespace under
1382  * that directory.  In fact, it is explicitly not allowed to do that.  A
1383  * directory is typically only locked when being created, renamed, or
1384  * destroyed.
1385  *
1386  * The directory (par) may be unresolved, in which case any returned child
1387  * will likely also be marked unresolved.  Likely but not guarenteed.  Since
1388  * the filesystem lookup requires a resolved directory vnode the caller is
1389  * responsible for resolving the namecache chain top-down.  This API
1390  * specifically allows whole chains to be created in an unresolved state.
1391  */
1392 struct namecache *
1393 cache_nlookup(struct namecache *par, struct nlcomponent *nlc)
1394 {
1395 	struct namecache *ncp;
1396 	struct namecache *new_ncp;
1397 	struct nchashhead *nchpp;
1398 	u_int32_t hash;
1399 	globaldata_t gd;
1400 
1401 	numcalls++;
1402 	gd = mycpu;
1403 
1404 	/*
1405 	 * Try to locate an existing entry
1406 	 */
1407 	hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
1408 	hash = fnv_32_buf(&par, sizeof(par), hash);
1409 	new_ncp = NULL;
1410 restart:
1411 	LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1412 		numchecks++;
1413 
1414 		/*
1415 		 * Zap entries that have timed out.
1416 		 */
1417 		if (ncp->nc_timeout &&
1418 		    (int)(ncp->nc_timeout - ticks) < 0 &&
1419 		    (ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
1420 		    ncp->nc_exlocks == 0
1421 		) {
1422 			cache_zap(cache_get(ncp));
1423 			goto restart;
1424 		}
1425 
1426 		/*
1427 		 * Break out if we find a matching entry.  Note that
1428 		 * UNRESOLVED entries may match, but DESTROYED entries
1429 		 * do not.
1430 		 */
1431 		if (ncp->nc_parent == par &&
1432 		    ncp->nc_nlen == nlc->nlc_namelen &&
1433 		    bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
1434 		    (ncp->nc_flag & NCF_DESTROYED) == 0
1435 		) {
1436 			if (cache_get_nonblock(ncp) == 0) {
1437 				if (new_ncp)
1438 					cache_free(new_ncp);
1439 				goto found;
1440 			}
1441 			cache_get(ncp);
1442 			cache_put(ncp);
1443 			goto restart;
1444 		}
1445 	}
1446 
1447 	/*
1448 	 * We failed to locate an entry, create a new entry and add it to
1449 	 * the cache.  We have to relookup after possibly blocking in
1450 	 * malloc.
1451 	 */
1452 	if (new_ncp == NULL) {
1453 		new_ncp = cache_alloc(nlc->nlc_namelen);
1454 		goto restart;
1455 	}
1456 
1457 	ncp = new_ncp;
1458 
1459 	/*
1460 	 * Initialize as a new UNRESOLVED entry, lock (non-blocking),
1461 	 * and link to the parent.  The mount point is usually inherited
1462 	 * from the parent unless this is a special case such as a mount
1463 	 * point where nlc_namelen is 0.  The caller is responsible for
1464 	 * setting nc_mount in that case.  If nlc_namelen is 0 nc_name will
1465 	 * be NULL.
1466 	 */
1467 	if (nlc->nlc_namelen) {
1468 		bcopy(nlc->nlc_nameptr, ncp->nc_name, nlc->nlc_namelen);
1469 		ncp->nc_name[nlc->nlc_namelen] = 0;
1470 		ncp->nc_mount = par->nc_mount;
1471 	}
1472 	nchpp = NCHHASH(hash);
1473 	LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
1474 	ncp->nc_flag |= NCF_HASHED;
1475 	cache_link_parent(ncp, par);
1476 found:
1477 	/*
1478 	 * stats and namecache size management
1479 	 */
1480 	if (ncp->nc_flag & NCF_UNRESOLVED)
1481 		++gd->gd_nchstats->ncs_miss;
1482 	else if (ncp->nc_vp)
1483 		++gd->gd_nchstats->ncs_goodhits;
1484 	else
1485 		++gd->gd_nchstats->ncs_neghits;
1486 	cache_hysteresis();
1487 	return(ncp);
1488 }
1489 
1490 /*
1491  * Resolve an unresolved namecache entry, generally by looking it up.
1492  * The passed ncp must be locked and refd.
1493  *
1494  * Theoretically since a vnode cannot be recycled while held, and since
1495  * the nc_parent chain holds its vnode as long as children exist, the
1496  * direct parent of the cache entry we are trying to resolve should
1497  * have a valid vnode.  If not then generate an error that we can
1498  * determine is related to a resolver bug.
1499  *
1500  * Note that successful resolution does not necessarily return an error
1501  * code of 0.  If the ncp resolves to a negative cache hit then ENOENT
1502  * will be returned.
1503  */
1504 int
1505 cache_resolve(struct namecache *ncp, struct ucred *cred)
1506 {
1507 	struct namecache *par;
1508 	int error;
1509 
1510 restart:
1511 	/*
1512 	 * If the ncp is already resolved we have nothing to do.
1513 	 */
1514 	if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
1515 		return (ncp->nc_error);
1516 
1517 	/*
1518 	 * Mount points need special handling because the parent does not
1519 	 * belong to the same filesystem as the ncp.
1520 	 */
1521 	if (ncp->nc_flag & NCF_MOUNTPT)
1522 		return (cache_resolve_mp(ncp));
1523 
1524 	/*
1525 	 * We expect an unbroken chain of ncps to at least the mount point,
1526 	 * and even all the way to root (but this code doesn't have to go
1527 	 * past the mount point).
1528 	 */
1529 	if (ncp->nc_parent == NULL) {
1530 		printf("EXDEV case 1 %p %*.*s\n", ncp,
1531 			ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
1532 		ncp->nc_error = EXDEV;
1533 		return(ncp->nc_error);
1534 	}
1535 
1536 	/*
1537 	 * The vp's of the parent directories in the chain are held via vhold()
1538 	 * due to the existance of the child, and should not disappear.
1539 	 * However, there are cases where they can disappear:
1540 	 *
1541 	 *	- due to filesystem I/O errors.
1542 	 *	- due to NFS being stupid about tracking the namespace and
1543 	 *	  destroys the namespace for entire directories quite often.
1544 	 *	- due to forced unmounts.
1545 	 *	- due to an rmdir (parent will be marked DESTROYED)
1546 	 *
1547 	 * When this occurs we have to track the chain backwards and resolve
1548 	 * it, looping until the resolver catches up to the current node.  We
1549 	 * could recurse here but we might run ourselves out of kernel stack
1550 	 * so we do it in a more painful manner.  This situation really should
1551 	 * not occur all that often, or if it does not have to go back too
1552 	 * many nodes to resolve the ncp.
1553 	 */
1554 	while (ncp->nc_parent->nc_vp == NULL) {
1555 		/*
1556 		 * This case can occur if a process is CD'd into a
1557 		 * directory which is then rmdir'd.  If the parent is marked
1558 		 * destroyed there is no point trying to resolve it.
1559 		 */
1560 		if (ncp->nc_parent->nc_flag & NCF_DESTROYED)
1561 			return(ENOENT);
1562 
1563 		par = ncp->nc_parent;
1564 		while (par->nc_parent && par->nc_parent->nc_vp == NULL)
1565 			par = par->nc_parent;
1566 		if (par->nc_parent == NULL) {
1567 			printf("EXDEV case 2 %*.*s\n",
1568 				par->nc_nlen, par->nc_nlen, par->nc_name);
1569 			return (EXDEV);
1570 		}
1571 		printf("[diagnostic] cache_resolve: had to recurse on %*.*s\n",
1572 			par->nc_nlen, par->nc_nlen, par->nc_name);
1573 		/*
1574 		 * The parent is not set in stone, ref and lock it to prevent
1575 		 * it from disappearing.  Also note that due to renames it
1576 		 * is possible for our ncp to move and for par to no longer
1577 		 * be one of its parents.  We resolve it anyway, the loop
1578 		 * will handle any moves.
1579 		 */
1580 		cache_get(par);
1581 		if (par->nc_flag & NCF_MOUNTPT) {
1582 			cache_resolve_mp(par);
1583 		} else if (par->nc_parent->nc_vp == NULL) {
1584 			printf("[diagnostic] cache_resolve: raced on %*.*s\n", par->nc_nlen, par->nc_nlen, par->nc_name);
1585 			cache_put(par);
1586 			continue;
1587 		} else if (par->nc_flag & NCF_UNRESOLVED) {
1588 			par->nc_error = VOP_NRESOLVE(par, cred);
1589 		}
1590 		if ((error = par->nc_error) != 0) {
1591 			if (par->nc_error != EAGAIN) {
1592 				printf("EXDEV case 3 %*.*s error %d\n",
1593 				    par->nc_nlen, par->nc_nlen, par->nc_name,
1594 				    par->nc_error);
1595 				cache_put(par);
1596 				return(error);
1597 			}
1598 			printf("[diagnostic] cache_resolve: EAGAIN par %p %*.*s\n",
1599 				par, par->nc_nlen, par->nc_nlen, par->nc_name);
1600 		}
1601 		cache_put(par);
1602 		/* loop */
1603 	}
1604 
1605 	/*
1606 	 * Call VOP_NRESOLVE() to get the vp, then scan for any disconnected
1607 	 * ncp's and reattach them.  If this occurs the original ncp is marked
1608 	 * EAGAIN to force a relookup.
1609 	 *
1610 	 * NOTE: in order to call VOP_NRESOLVE(), the parent of the passed
1611 	 * ncp must already be resolved.
1612 	 */
1613 	KKASSERT((ncp->nc_flag & NCF_MOUNTPT) == 0);
1614 	ncp->nc_error = VOP_NRESOLVE(ncp, cred);
1615 	/*vop_nresolve(*ncp->nc_parent->nc_vp->v_ops, ncp, cred);*/
1616 	if (ncp->nc_error == EAGAIN) {
1617 		printf("[diagnostic] cache_resolve: EAGAIN ncp %p %*.*s\n",
1618 			ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
1619 		goto restart;
1620 	}
1621 	return(ncp->nc_error);
1622 }
1623 
1624 /*
1625  * Resolve the ncp associated with a mount point.  Such ncp's almost always
1626  * remain resolved and this routine is rarely called.  NFS MPs tends to force
1627  * re-resolution more often due to its mac-truck-smash-the-namecache
1628  * method of tracking namespace changes.
1629  *
1630  * The semantics for this call is that the passed ncp must be locked on
1631  * entry and will be locked on return.  However, if we actually have to
1632  * resolve the mount point we temporarily unlock the entry in order to
1633  * avoid race-to-root deadlocks due to e.g. dead NFS mounts.  Because of
1634  * the unlock we have to recheck the flags after we relock.
1635  */
1636 static int
1637 cache_resolve_mp(struct namecache *ncp)
1638 {
1639 	struct vnode *vp;
1640 	struct mount *mp = ncp->nc_mount;
1641 	int error;
1642 
1643 	KKASSERT(mp != NULL);
1644 	if (ncp->nc_flag & NCF_UNRESOLVED) {
1645 		cache_unlock(ncp);
1646 		while (vfs_busy(mp, 0, curthread))
1647 			;
1648 		error = VFS_ROOT(mp, &vp);
1649 		cache_lock(ncp);
1650 
1651 		/*
1652 		 * recheck the ncp state after relocking.
1653 		 */
1654 		if (ncp->nc_flag & NCF_UNRESOLVED) {
1655 			ncp->nc_error = error;
1656 			if (error == 0) {
1657 				cache_setvp(ncp, vp);
1658 				vput(vp);
1659 			} else {
1660 				printf("[diagnostic] cache_resolve_mp: failed to resolve mount %p\n", mp);
1661 				cache_setvp(ncp, NULL);
1662 			}
1663 		} else if (error == 0) {
1664 			vput(vp);
1665 		}
1666 		vfs_unbusy(mp, curthread);
1667 	}
1668 	return(ncp->nc_error);
1669 }
1670 
1671 void
1672 cache_cleanneg(int count)
1673 {
1674 	struct namecache *ncp;
1675 
1676 	/*
1677 	 * Automode from the vnlru proc - clean out 10% of the negative cache
1678 	 * entries.
1679 	 */
1680 	if (count == 0)
1681 		count = numneg / 10 + 1;
1682 
1683 	/*
1684 	 * Attempt to clean out the specified number of negative cache
1685 	 * entries.
1686 	 */
1687 	while (count) {
1688 		ncp = TAILQ_FIRST(&ncneglist);
1689 		if (ncp == NULL) {
1690 			KKASSERT(numneg == 0);
1691 			break;
1692 		}
1693 		TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
1694 		TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
1695 		if (cache_get_nonblock(ncp) == 0)
1696 			cache_zap(ncp);
1697 		--count;
1698 	}
1699 }
1700 
1701 /*
1702  * Rehash a ncp.  Rehashing is typically required if the name changes (should
1703  * not generally occur) or the parent link changes.  This function will
1704  * unhash the ncp if the ncp is no longer hashable.
1705  */
1706 static void
1707 cache_rehash(struct namecache *ncp)
1708 {
1709 	struct nchashhead *nchpp;
1710 	u_int32_t hash;
1711 
1712 	if (ncp->nc_flag & NCF_HASHED) {
1713 		ncp->nc_flag &= ~NCF_HASHED;
1714 		LIST_REMOVE(ncp, nc_hash);
1715 	}
1716 	if (ncp->nc_nlen && ncp->nc_parent) {
1717 		hash = fnv_32_buf(ncp->nc_name, ncp->nc_nlen, FNV1_32_INIT);
1718 		hash = fnv_32_buf(&ncp->nc_parent,
1719 					sizeof(ncp->nc_parent), hash);
1720 		nchpp = NCHHASH(hash);
1721 		LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
1722 		ncp->nc_flag |= NCF_HASHED;
1723 	}
1724 }
1725 
1726 /*
1727  * Name cache initialization, from vfsinit() when we are booting
1728  */
1729 void
1730 nchinit(void)
1731 {
1732 	int i;
1733 	globaldata_t gd;
1734 
1735 	/* initialise per-cpu namecache effectiveness statistics. */
1736 	for (i = 0; i < ncpus; ++i) {
1737 		gd = globaldata_find(i);
1738 		gd->gd_nchstats = &nchstats[i];
1739 	}
1740 	TAILQ_INIT(&ncneglist);
1741 	nchashtbl = hashinit(desiredvnodes*2, M_VFSCACHE, &nchash);
1742 	nclockwarn = 1 * hz;
1743 }
1744 
1745 /*
1746  * Called from start_init() to bootstrap the root filesystem.  Returns
1747  * a referenced, unlocked namecache record.
1748  */
1749 struct namecache *
1750 cache_allocroot(struct mount *mp, struct vnode *vp)
1751 {
1752 	struct namecache *ncp = cache_alloc(0);
1753 
1754 	ncp->nc_flag |= NCF_MOUNTPT | NCF_ROOT;
1755 	ncp->nc_mount = mp;
1756 	cache_setvp(ncp, vp);
1757 	return(ncp);
1758 }
1759 
1760 /*
1761  * vfs_cache_setroot()
1762  *
1763  *	Create an association between the root of our namecache and
1764  *	the root vnode.  This routine may be called several times during
1765  *	booting.
1766  *
1767  *	If the caller intends to save the returned namecache pointer somewhere
1768  *	it must cache_hold() it.
1769  */
1770 void
1771 vfs_cache_setroot(struct vnode *nvp, struct namecache *ncp)
1772 {
1773 	struct vnode *ovp;
1774 	struct namecache *oncp;
1775 
1776 	ovp = rootvnode;
1777 	oncp = rootncp;
1778 	rootvnode = nvp;
1779 	rootncp = ncp;
1780 
1781 	if (ovp)
1782 		vrele(ovp);
1783 	if (oncp)
1784 		cache_drop(oncp);
1785 }
1786 
1787 /*
1788  * XXX OLD API COMPAT FUNCTION.  This really messes up the new namecache
1789  * topology and is being removed as quickly as possible.  The new VOP_N*()
1790  * API calls are required to make specific adjustments using the supplied
1791  * ncp pointers rather then just bogusly purging random vnodes.
1792  *
1793  * Invalidate all namecache entries to a particular vnode as well as
1794  * any direct children of that vnode in the namecache.  This is a
1795  * 'catch all' purge used by filesystems that do not know any better.
1796  *
1797  * A new vnode v_id is generated.  Note that no vnode will ever have a
1798  * v_id of 0.
1799  *
1800  * Note that the linkage between the vnode and its namecache entries will
1801  * be removed, but the namecache entries themselves might stay put due to
1802  * active references from elsewhere in the system or due to the existance of
1803  * the children.   The namecache topology is left intact even if we do not
1804  * know what the vnode association is.  Such entries will be marked
1805  * NCF_UNRESOLVED.
1806  *
1807  * XXX: Only time and the size of v_id prevents this from failing:
1808  * XXX: In theory we should hunt down all (struct vnode*, v_id)
1809  * XXX: soft references and nuke them, at least on the global
1810  * XXX: v_id wraparound.  The period of resistance can be extended
1811  * XXX: by incrementing each vnodes v_id individually instead of
1812  * XXX: using the global v_id.
1813  *
1814  * Does not support NCP_FSMID accumulation on invalidation (retflags is
1815  * not used).
1816  */
1817 void
1818 cache_purge(struct vnode *vp)
1819 {
1820 	static u_long nextid;
1821 	int retflags = 0;
1822 
1823 	cache_inval_vp(vp, CINV_DESTROY | CINV_CHILDREN, &retflags);
1824 
1825 	/*
1826 	 * Calculate a new unique id for ".." handling
1827 	 */
1828 	do {
1829 		nextid++;
1830 	} while (nextid == vp->v_id || nextid == 0);
1831 	vp->v_id = nextid;
1832 }
1833 
1834 /*
1835  * Flush all entries referencing a particular filesystem.
1836  *
1837  * Since we need to check it anyway, we will flush all the invalid
1838  * entries at the same time.
1839  */
1840 void
1841 cache_purgevfs(struct mount *mp)
1842 {
1843 	struct nchashhead *nchpp;
1844 	struct namecache *ncp, *nnp;
1845 
1846 	/*
1847 	 * Scan hash tables for applicable entries.
1848 	 */
1849 	for (nchpp = &nchashtbl[nchash]; nchpp >= nchashtbl; nchpp--) {
1850 		ncp = LIST_FIRST(nchpp);
1851 		if (ncp)
1852 			cache_hold(ncp);
1853 		while (ncp) {
1854 			nnp = LIST_NEXT(ncp, nc_hash);
1855 			if (nnp)
1856 				cache_hold(nnp);
1857 			if (ncp->nc_mount == mp) {
1858 				cache_lock(ncp);
1859 				cache_zap(ncp);
1860 			} else {
1861 				cache_drop(ncp);
1862 			}
1863 			ncp = nnp;
1864 		}
1865 	}
1866 }
1867 
1868 static int disablecwd;
1869 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0, "");
1870 
1871 static u_long numcwdcalls; STATNODE(CTLFLAG_RD, numcwdcalls, &numcwdcalls);
1872 static u_long numcwdfail1; STATNODE(CTLFLAG_RD, numcwdfail1, &numcwdfail1);
1873 static u_long numcwdfail2; STATNODE(CTLFLAG_RD, numcwdfail2, &numcwdfail2);
1874 static u_long numcwdfail3; STATNODE(CTLFLAG_RD, numcwdfail3, &numcwdfail3);
1875 static u_long numcwdfail4; STATNODE(CTLFLAG_RD, numcwdfail4, &numcwdfail4);
1876 static u_long numcwdfound; STATNODE(CTLFLAG_RD, numcwdfound, &numcwdfound);
1877 
1878 int
1879 __getcwd(struct __getcwd_args *uap)
1880 {
1881 	int buflen;
1882 	int error;
1883 	char *buf;
1884 	char *bp;
1885 
1886 	if (disablecwd)
1887 		return (ENODEV);
1888 
1889 	buflen = uap->buflen;
1890 	if (buflen < 2)
1891 		return (EINVAL);
1892 	if (buflen > MAXPATHLEN)
1893 		buflen = MAXPATHLEN;
1894 
1895 	buf = malloc(buflen, M_TEMP, M_WAITOK);
1896 	bp = kern_getcwd(buf, buflen, &error);
1897 	if (error == 0)
1898 		error = copyout(bp, uap->buf, strlen(bp) + 1);
1899 	free(buf, M_TEMP);
1900 	return (error);
1901 }
1902 
1903 char *
1904 kern_getcwd(char *buf, size_t buflen, int *error)
1905 {
1906 	struct proc *p = curproc;
1907 	char *bp;
1908 	int i, slash_prefixed;
1909 	struct filedesc *fdp;
1910 	struct namecache *ncp;
1911 
1912 	numcwdcalls++;
1913 	bp = buf;
1914 	bp += buflen - 1;
1915 	*bp = '\0';
1916 	fdp = p->p_fd;
1917 	slash_prefixed = 0;
1918 
1919 	ncp = fdp->fd_ncdir;
1920 	while (ncp && ncp != fdp->fd_nrdir && (ncp->nc_flag & NCF_ROOT) == 0) {
1921 		if (ncp->nc_flag & NCF_MOUNTPT) {
1922 			if (ncp->nc_mount == NULL) {
1923 				*error = EBADF;		/* forced unmount? */
1924 				return(NULL);
1925 			}
1926 			ncp = ncp->nc_parent;
1927 			continue;
1928 		}
1929 		for (i = ncp->nc_nlen - 1; i >= 0; i--) {
1930 			if (bp == buf) {
1931 				numcwdfail4++;
1932 				*error = ENOMEM;
1933 				return(NULL);
1934 			}
1935 			*--bp = ncp->nc_name[i];
1936 		}
1937 		if (bp == buf) {
1938 			numcwdfail4++;
1939 			*error = ENOMEM;
1940 			return(NULL);
1941 		}
1942 		*--bp = '/';
1943 		slash_prefixed = 1;
1944 		ncp = ncp->nc_parent;
1945 	}
1946 	if (ncp == NULL) {
1947 		numcwdfail2++;
1948 		*error = ENOENT;
1949 		return(NULL);
1950 	}
1951 	if (!slash_prefixed) {
1952 		if (bp == buf) {
1953 			numcwdfail4++;
1954 			*error = ENOMEM;
1955 			return(NULL);
1956 		}
1957 		*--bp = '/';
1958 	}
1959 	numcwdfound++;
1960 	*error = 0;
1961 	return (bp);
1962 }
1963 
1964 /*
1965  * Thus begins the fullpath magic.
1966  */
1967 
1968 #undef STATNODE
1969 #define STATNODE(name)							\
1970 	static u_int name;						\
1971 	SYSCTL_UINT(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, "")
1972 
1973 static int disablefullpath;
1974 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW,
1975     &disablefullpath, 0, "");
1976 
1977 STATNODE(numfullpathcalls);
1978 STATNODE(numfullpathfail1);
1979 STATNODE(numfullpathfail2);
1980 STATNODE(numfullpathfail3);
1981 STATNODE(numfullpathfail4);
1982 STATNODE(numfullpathfound);
1983 
1984 int
1985 cache_fullpath(struct proc *p, struct namecache *ncp, char **retbuf, char **freebuf)
1986 {
1987 	char *bp, *buf;
1988 	int i, slash_prefixed;
1989 	struct namecache *fd_nrdir;
1990 
1991 	numfullpathcalls--;
1992 
1993 	buf = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1994 	bp = buf + MAXPATHLEN - 1;
1995 	*bp = '\0';
1996 	if (p != NULL)
1997 		fd_nrdir = p->p_fd->fd_nrdir;
1998 	else
1999 		fd_nrdir = NULL;
2000 	slash_prefixed = 0;
2001 	while (ncp && ncp != fd_nrdir && (ncp->nc_flag & NCF_ROOT) == 0) {
2002 		if (ncp->nc_flag & NCF_MOUNTPT) {
2003 			if (ncp->nc_mount == NULL) {
2004 				free(buf, M_TEMP);
2005 				return(EBADF);
2006 			}
2007 			ncp = ncp->nc_parent;
2008 			continue;
2009 		}
2010 		for (i = ncp->nc_nlen - 1; i >= 0; i--) {
2011 			if (bp == buf) {
2012 				numfullpathfail4++;
2013 				free(buf, M_TEMP);
2014 				return(ENOMEM);
2015 			}
2016 			*--bp = ncp->nc_name[i];
2017 		}
2018 		if (bp == buf) {
2019 			numfullpathfail4++;
2020 			free(buf, M_TEMP);
2021 			return(ENOMEM);
2022 		}
2023 		*--bp = '/';
2024 		slash_prefixed = 1;
2025 		ncp = ncp->nc_parent;
2026 	}
2027 	if (ncp == NULL) {
2028 		numfullpathfail2++;
2029 		free(buf, M_TEMP);
2030 		return(ENOENT);
2031 	}
2032 	if (p != NULL && (ncp->nc_flag & NCF_ROOT) && ncp != fd_nrdir) {
2033 		bp = buf + MAXPATHLEN - 1;
2034 		*bp = '\0';
2035 		slash_prefixed = 0;
2036 	}
2037 	if (!slash_prefixed) {
2038 		if (bp == buf) {
2039 			numfullpathfail4++;
2040 			free(buf, M_TEMP);
2041 			return(ENOMEM);
2042 		}
2043 		*--bp = '/';
2044 	}
2045 	numfullpathfound++;
2046 	*retbuf = bp;
2047 	*freebuf = buf;
2048 
2049 	return(0);
2050 }
2051 
2052 int
2053 vn_fullpath(struct proc *p, struct vnode *vn, char **retbuf, char **freebuf)
2054 {
2055 	struct namecache *ncp;
2056 
2057 	numfullpathcalls++;
2058 	if (disablefullpath)
2059 		return (ENODEV);
2060 
2061 	if (p == NULL)
2062 		return (EINVAL);
2063 
2064 	/* vn is NULL, client wants us to use p->p_textvp */
2065 	if (vn == NULL) {
2066 		if ((vn = p->p_textvp) == NULL)
2067 			return (EINVAL);
2068 	}
2069 	TAILQ_FOREACH(ncp, &vn->v_namecache, nc_vnode) {
2070 		if (ncp->nc_nlen)
2071 			break;
2072 	}
2073 	if (ncp == NULL)
2074 		return (EINVAL);
2075 
2076 	numfullpathcalls--;
2077 	return(cache_fullpath(p, ncp, retbuf, freebuf));
2078 }
2079