xref: /dflybsd-src/sys/kern/vfs_cache.c (revision 6693db176654a0f25095ec64d0a74d58dcf0e47e)
1 /*
2  * Copyright (c) 2003,2004,2009 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 
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/kernel.h>
72 #include <sys/sysctl.h>
73 #include <sys/mount.h>
74 #include <sys/vnode.h>
75 #include <sys/malloc.h>
76 #include <sys/sysproto.h>
77 #include <sys/spinlock.h>
78 #include <sys/proc.h>
79 #include <sys/namei.h>
80 #include <sys/nlookup.h>
81 #include <sys/filedesc.h>
82 #include <sys/fnv_hash.h>
83 #include <sys/globaldata.h>
84 #include <sys/kern_syscall.h>
85 #include <sys/dirent.h>
86 #include <ddb/ddb.h>
87 
88 #include <sys/sysref2.h>
89 #include <sys/spinlock2.h>
90 #include <sys/mplock2.h>
91 
92 #define MAX_RECURSION_DEPTH	64
93 
94 /*
95  * Random lookups in the cache are accomplished with a hash table using
96  * a hash key of (nc_src_vp, name).  Each hash chain has its own spin lock.
97  *
98  * Negative entries may exist and correspond to resolved namecache
99  * structures where nc_vp is NULL.  In a negative entry, NCF_WHITEOUT
100  * will be set if the entry corresponds to a whited-out directory entry
101  * (verses simply not finding the entry at all).   ncneglist is locked
102  * with a global spinlock (ncspin).
103  *
104  * MPSAFE RULES:
105  *
106  * (1) A ncp must be referenced before it can be locked.
107  *
108  * (2) A ncp must be locked in order to modify it.
109  *
110  * (3) ncp locks are always ordered child -> parent.  That may seem
111  *     backwards but forward scans use the hash table and thus can hold
112  *     the parent unlocked when traversing downward.
113  *
114  *     This allows insert/rename/delete/dot-dot and other operations
115  *     to use ncp->nc_parent links.
116  *
117  *     This also prevents a locked up e.g. NFS node from creating a
118  *     chain reaction all the way back to the root vnode / namecache.
119  *
120  * (4) parent linkages require both the parent and child to be locked.
121  */
122 
123 /*
124  * Structures associated with name cacheing.
125  */
126 #define NCHHASH(hash)	(&nchashtbl[(hash) & nchash])
127 #define MINNEG		1024
128 
129 MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
130 
131 LIST_HEAD(nchash_list, namecache);
132 
133 struct nchash_head {
134        struct nchash_list list;
135        struct spinlock	spin;
136 };
137 
138 static struct nchash_head	*nchashtbl;
139 static struct namecache_list	ncneglist;
140 static struct spinlock		ncspin;
141 
142 /*
143  * ncvp_debug - debug cache_fromvp().  This is used by the NFS server
144  * to create the namecache infrastructure leading to a dangling vnode.
145  *
146  * 0	Only errors are reported
147  * 1	Successes are reported
148  * 2	Successes + the whole directory scan is reported
149  * 3	Force the directory scan code run as if the parent vnode did not
150  *	have a namecache record, even if it does have one.
151  */
152 static int	ncvp_debug;
153 SYSCTL_INT(_debug, OID_AUTO, ncvp_debug, CTLFLAG_RW, &ncvp_debug, 0, "");
154 
155 static u_long	nchash;			/* size of hash table */
156 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0, "");
157 
158 static int	ncnegfactor = 16;	/* ratio of negative entries */
159 SYSCTL_INT(_debug, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0, "");
160 
161 static int	nclockwarn;		/* warn on locked entries in ticks */
162 SYSCTL_INT(_debug, OID_AUTO, nclockwarn, CTLFLAG_RW, &nclockwarn, 0, "");
163 
164 static int	numneg;			/* number of cache entries allocated */
165 SYSCTL_INT(_debug, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0, "");
166 
167 static int	numdefered;		/* number of cache entries allocated */
168 SYSCTL_INT(_debug, OID_AUTO, numdefered, CTLFLAG_RD, &numdefered, 0, "");
169 
170 static int	numcache;		/* number of cache entries allocated */
171 SYSCTL_INT(_debug, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0, "");
172 
173 SYSCTL_INT(_debug, OID_AUTO, vnsize, CTLFLAG_RD, 0, sizeof(struct vnode), "");
174 SYSCTL_INT(_debug, OID_AUTO, ncsize, CTLFLAG_RD, 0, sizeof(struct namecache), "");
175 
176 int cache_mpsafe;
177 SYSCTL_INT(_vfs, OID_AUTO, cache_mpsafe, CTLFLAG_RW, &cache_mpsafe, 0, "");
178 
179 static int cache_resolve_mp(struct mount *mp);
180 static struct vnode *cache_dvpref(struct namecache *ncp);
181 static void _cache_lock(struct namecache *ncp);
182 static void _cache_setunresolved(struct namecache *ncp);
183 static void _cache_cleanneg(int count);
184 static void _cache_cleandefered(void);
185 
186 /*
187  * The new name cache statistics
188  */
189 SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0, "Name cache statistics");
190 #define STATNODE(mode, name, var) \
191 	SYSCTL_ULONG(_vfs_cache, OID_AUTO, name, mode, var, 0, "");
192 STATNODE(CTLFLAG_RD, numneg, &numneg);
193 STATNODE(CTLFLAG_RD, numcache, &numcache);
194 static u_long numcalls; STATNODE(CTLFLAG_RD, numcalls, &numcalls);
195 static u_long dothits; STATNODE(CTLFLAG_RD, dothits, &dothits);
196 static u_long dotdothits; STATNODE(CTLFLAG_RD, dotdothits, &dotdothits);
197 static u_long numchecks; STATNODE(CTLFLAG_RD, numchecks, &numchecks);
198 static u_long nummiss; STATNODE(CTLFLAG_RD, nummiss, &nummiss);
199 static u_long nummisszap; STATNODE(CTLFLAG_RD, nummisszap, &nummisszap);
200 static u_long numposzaps; STATNODE(CTLFLAG_RD, numposzaps, &numposzaps);
201 static u_long numposhits; STATNODE(CTLFLAG_RD, numposhits, &numposhits);
202 static u_long numnegzaps; STATNODE(CTLFLAG_RD, numnegzaps, &numnegzaps);
203 static u_long numneghits; STATNODE(CTLFLAG_RD, numneghits, &numneghits);
204 
205 struct nchstats nchstats[SMP_MAXCPU];
206 /*
207  * Export VFS cache effectiveness statistics to user-land.
208  *
209  * The statistics are left for aggregation to user-land so
210  * neat things can be achieved, like observing per-CPU cache
211  * distribution.
212  */
213 static int
214 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
215 {
216 	struct globaldata *gd;
217 	int i, error;
218 
219 	error = 0;
220 	for (i = 0; i < ncpus; ++i) {
221 		gd = globaldata_find(i);
222 		if ((error = SYSCTL_OUT(req, (void *)&(*gd->gd_nchstats),
223 			sizeof(struct nchstats))))
224 			break;
225 	}
226 
227 	return (error);
228 }
229 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE|CTLFLAG_RD,
230   0, 0, sysctl_nchstats, "S,nchstats", "VFS cache effectiveness statistics");
231 
232 static struct namecache *cache_zap(struct namecache *ncp, int nonblock);
233 
234 /*
235  * Namespace locking.  The caller must already hold a reference to the
236  * namecache structure in order to lock/unlock it.  This function prevents
237  * the namespace from being created or destroyed by accessors other then
238  * the lock holder.
239  *
240  * Note that holding a locked namecache structure prevents other threads
241  * from making namespace changes (e.g. deleting or creating), prevents
242  * vnode association state changes by other threads, and prevents the
243  * namecache entry from being resolved or unresolved by other threads.
244  *
245  * The lock owner has full authority to associate/disassociate vnodes
246  * and resolve/unresolve the locked ncp.
247  *
248  * The primary lock field is nc_exlocks.  nc_locktd is set after the
249  * fact (when locking) or cleared prior to unlocking.
250  *
251  * WARNING!  Holding a locked ncp will prevent a vnode from being destroyed
252  *	     or recycled, but it does NOT help you if the vnode had already
253  *	     initiated a recyclement.  If this is important, use cache_get()
254  *	     rather then cache_lock() (and deal with the differences in the
255  *	     way the refs counter is handled).  Or, alternatively, make an
256  *	     unconditional call to cache_validate() or cache_resolve()
257  *	     after cache_lock() returns.
258  *
259  * MPSAFE
260  */
261 static
262 void
263 _cache_lock(struct namecache *ncp)
264 {
265 	thread_t td;
266 	int didwarn;
267 	int error;
268 	u_int count;
269 
270 	KKASSERT(ncp->nc_refs != 0);
271 	didwarn = 0;
272 	td = curthread;
273 
274 	for (;;) {
275 		count = ncp->nc_exlocks;
276 
277 		if (count == 0) {
278 			if (atomic_cmpset_int(&ncp->nc_exlocks, 0, 1)) {
279 				/*
280 				 * The vp associated with a locked ncp must
281 				 * be held to prevent it from being recycled.
282 				 *
283 				 * WARNING!  If VRECLAIMED is set the vnode
284 				 * could already be in the middle of a recycle.
285 				 * Callers must use cache_vref() or
286 				 * cache_vget() on the locked ncp to
287 				 * validate the vp or set the cache entry
288 				 * to unresolved.
289 				 *
290 				 * NOTE! vhold() is allowed if we hold a
291 				 *	 lock on the ncp (which we do).
292 				 */
293 				ncp->nc_locktd = td;
294 				if (ncp->nc_vp)
295 					vhold(ncp->nc_vp);	/* MPSAFE */
296 				break;
297 			}
298 			/* cmpset failed */
299 			continue;
300 		}
301 		if (ncp->nc_locktd == td) {
302 			if (atomic_cmpset_int(&ncp->nc_exlocks, count,
303 					      count + 1)) {
304 				break;
305 			}
306 			/* cmpset failed */
307 			continue;
308 		}
309 		tsleep_interlock(ncp, 0);
310 		if (atomic_cmpset_int(&ncp->nc_exlocks, count,
311 				      count | NC_EXLOCK_REQ) == 0) {
312 			/* cmpset failed */
313 			continue;
314 		}
315 		error = tsleep(ncp, PINTERLOCKED, "clock", nclockwarn);
316 		if (error == EWOULDBLOCK) {
317 			if (didwarn == 0) {
318 				didwarn = ticks;
319 				kprintf("[diagnostic] cache_lock: blocked "
320 					"on %p",
321 					ncp);
322 				kprintf(" \"%*.*s\"\n",
323 					ncp->nc_nlen, ncp->nc_nlen,
324 					ncp->nc_name);
325 			}
326 		}
327 	}
328 	if (didwarn) {
329 		kprintf("[diagnostic] cache_lock: unblocked %*.*s after "
330 			"%d secs\n",
331 			ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name,
332 			(int)(ticks - didwarn) / hz);
333 	}
334 }
335 
336 /*
337  * NOTE: nc_refs may be zero if the ncp is interlocked by circumstance,
338  *	 such as the case where one of its children is locked.
339  *
340  * MPSAFE
341  */
342 static
343 int
344 _cache_lock_nonblock(struct namecache *ncp)
345 {
346 	thread_t td;
347 	u_int count;
348 
349 	td = curthread;
350 
351 	for (;;) {
352 		count = ncp->nc_exlocks;
353 
354 		if (count == 0) {
355 			if (atomic_cmpset_int(&ncp->nc_exlocks, 0, 1)) {
356 				/*
357 				 * The vp associated with a locked ncp must
358 				 * be held to prevent it from being recycled.
359 				 *
360 				 * WARNING!  If VRECLAIMED is set the vnode
361 				 * could already be in the middle of a recycle.
362 				 * Callers must use cache_vref() or
363 				 * cache_vget() on the locked ncp to
364 				 * validate the vp or set the cache entry
365 				 * to unresolved.
366 				 *
367 				 * NOTE! vhold() is allowed if we hold a
368 				 *	 lock on the ncp (which we do).
369 				 */
370 				ncp->nc_locktd = td;
371 				if (ncp->nc_vp)
372 					vhold(ncp->nc_vp);	/* MPSAFE */
373 				break;
374 			}
375 			/* cmpset failed */
376 			continue;
377 		}
378 		if (ncp->nc_locktd == td) {
379 			if (atomic_cmpset_int(&ncp->nc_exlocks, count,
380 					      count + 1)) {
381 				break;
382 			}
383 			/* cmpset failed */
384 			continue;
385 		}
386 		return(EWOULDBLOCK);
387 	}
388 	return(0);
389 }
390 
391 /*
392  * Helper function
393  *
394  * NOTE: nc_refs can be 0 (degenerate case during _cache_drop).
395  *
396  *	 nc_locktd must be NULLed out prior to nc_exlocks getting cleared.
397  *
398  * MPSAFE
399  */
400 static
401 void
402 _cache_unlock(struct namecache *ncp)
403 {
404 	thread_t td __debugvar = curthread;
405 	u_int count;
406 
407 	KKASSERT(ncp->nc_refs >= 0);
408 	KKASSERT(ncp->nc_exlocks > 0);
409 	KKASSERT(ncp->nc_locktd == td);
410 
411 	count = ncp->nc_exlocks;
412 	if ((count & ~NC_EXLOCK_REQ) == 1) {
413 		ncp->nc_locktd = NULL;
414 		if (ncp->nc_vp)
415 			vdrop(ncp->nc_vp);
416 	}
417 	for (;;) {
418 		if ((count & ~NC_EXLOCK_REQ) == 1) {
419 			if (atomic_cmpset_int(&ncp->nc_exlocks, count, 0)) {
420 				if (count & NC_EXLOCK_REQ)
421 					wakeup(ncp);
422 				break;
423 			}
424 		} else {
425 			if (atomic_cmpset_int(&ncp->nc_exlocks, count,
426 					      count - 1)) {
427 				break;
428 			}
429 		}
430 		count = ncp->nc_exlocks;
431 	}
432 }
433 
434 
435 /*
436  * cache_hold() and cache_drop() prevent the premature deletion of a
437  * namecache entry but do not prevent operations (such as zapping) on
438  * that namecache entry.
439  *
440  * This routine may only be called from outside this source module if
441  * nc_refs is already at least 1.
442  *
443  * This is a rare case where callers are allowed to hold a spinlock,
444  * so we can't ourselves.
445  *
446  * MPSAFE
447  */
448 static __inline
449 struct namecache *
450 _cache_hold(struct namecache *ncp)
451 {
452 	atomic_add_int(&ncp->nc_refs, 1);
453 	return(ncp);
454 }
455 
456 /*
457  * Drop a cache entry, taking care to deal with races.
458  *
459  * For potential 1->0 transitions we must hold the ncp lock to safely
460  * test its flags.  An unresolved entry with no children must be zapped
461  * to avoid leaks.
462  *
463  * The call to cache_zap() itself will handle all remaining races and
464  * will decrement the ncp's refs regardless.  If we are resolved or
465  * have children nc_refs can safely be dropped to 0 without having to
466  * zap the entry.
467  *
468  * NOTE: cache_zap() will re-check nc_refs and nc_list in a MPSAFE fashion.
469  *
470  * NOTE: cache_zap() may return a non-NULL referenced parent which must
471  *	 be dropped in a loop.
472  *
473  * MPSAFE
474  */
475 static __inline
476 void
477 _cache_drop(struct namecache *ncp)
478 {
479 	int refs;
480 
481 	while (ncp) {
482 		KKASSERT(ncp->nc_refs > 0);
483 		refs = ncp->nc_refs;
484 
485 		if (refs == 1) {
486 			if (_cache_lock_nonblock(ncp) == 0) {
487 				if ((ncp->nc_flag & NCF_UNRESOLVED) &&
488 				    TAILQ_EMPTY(&ncp->nc_list)) {
489 					ncp = cache_zap(ncp, 1);
490 					continue;
491 				}
492 				if (atomic_cmpset_int(&ncp->nc_refs, 1, 0)) {
493 					_cache_unlock(ncp);
494 					break;
495 				}
496 				_cache_unlock(ncp);
497 			}
498 		} else {
499 			if (atomic_cmpset_int(&ncp->nc_refs, refs, refs - 1))
500 				break;
501 		}
502 		cpu_pause();
503 	}
504 }
505 
506 /*
507  * Link a new namecache entry to its parent and to the hash table.  Be
508  * careful to avoid races if vhold() blocks in the future.
509  *
510  * Both ncp and par must be referenced and locked.
511  *
512  * NOTE: The hash table spinlock is likely held during this call, we
513  *	 can't do anything fancy.
514  *
515  * MPSAFE
516  */
517 static void
518 _cache_link_parent(struct namecache *ncp, struct namecache *par,
519 		   struct nchash_head *nchpp)
520 {
521 	KKASSERT(ncp->nc_parent == NULL);
522 	ncp->nc_parent = par;
523 	ncp->nc_head = nchpp;
524 	LIST_INSERT_HEAD(&nchpp->list, ncp, nc_hash);
525 
526 	if (TAILQ_EMPTY(&par->nc_list)) {
527 		TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
528 		/*
529 		 * Any vp associated with an ncp which has children must
530 		 * be held to prevent it from being recycled.
531 		 */
532 		if (par->nc_vp)
533 			vhold(par->nc_vp);
534 	} else {
535 		TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
536 	}
537 }
538 
539 /*
540  * Remove the parent and hash associations from a namecache structure.
541  * If this is the last child of the parent the cache_drop(par) will
542  * attempt to recursively zap the parent.
543  *
544  * ncp must be locked.  This routine will acquire a temporary lock on
545  * the parent as wlel as the appropriate hash chain.
546  *
547  * MPSAFE
548  */
549 static void
550 _cache_unlink_parent(struct namecache *ncp)
551 {
552 	struct namecache *par;
553 	struct vnode *dropvp;
554 
555 	if ((par = ncp->nc_parent) != NULL) {
556 		KKASSERT(ncp->nc_parent == par);
557 		_cache_hold(par);
558 		_cache_lock(par);
559 		spin_lock_wr(&ncp->nc_head->spin);
560 		LIST_REMOVE(ncp, nc_hash);
561 		TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
562 		dropvp = NULL;
563 		if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
564 			dropvp = par->nc_vp;
565 		spin_unlock_wr(&ncp->nc_head->spin);
566 		ncp->nc_parent = NULL;
567 		ncp->nc_head = NULL;
568 		_cache_unlock(par);
569 		_cache_drop(par);
570 
571 		/*
572 		 * We can only safely vdrop with no spinlocks held.
573 		 */
574 		if (dropvp)
575 			vdrop(dropvp);
576 	}
577 }
578 
579 /*
580  * Allocate a new namecache structure.  Most of the code does not require
581  * zero-termination of the string but it makes vop_compat_ncreate() easier.
582  *
583  * MPSAFE
584  */
585 static struct namecache *
586 cache_alloc(int nlen)
587 {
588 	struct namecache *ncp;
589 
590 	ncp = kmalloc(sizeof(*ncp), M_VFSCACHE, M_WAITOK|M_ZERO);
591 	if (nlen)
592 		ncp->nc_name = kmalloc(nlen + 1, M_VFSCACHE, M_WAITOK);
593 	ncp->nc_nlen = nlen;
594 	ncp->nc_flag = NCF_UNRESOLVED;
595 	ncp->nc_error = ENOTCONN;	/* needs to be resolved */
596 	ncp->nc_refs = 1;
597 
598 	TAILQ_INIT(&ncp->nc_list);
599 	_cache_lock(ncp);
600 	return(ncp);
601 }
602 
603 /*
604  * Can only be called for the case where the ncp has never been
605  * associated with anything (so no spinlocks are needed).
606  *
607  * MPSAFE
608  */
609 static void
610 _cache_free(struct namecache *ncp)
611 {
612 	KKASSERT(ncp->nc_refs == 1 && ncp->nc_exlocks == 1);
613 	if (ncp->nc_name)
614 		kfree(ncp->nc_name, M_VFSCACHE);
615 	kfree(ncp, M_VFSCACHE);
616 }
617 
618 /*
619  * MPSAFE
620  */
621 void
622 cache_zero(struct nchandle *nch)
623 {
624 	nch->ncp = NULL;
625 	nch->mount = NULL;
626 }
627 
628 /*
629  * Ref and deref a namecache structure.
630  *
631  * The caller must specify a stable ncp pointer, typically meaning the
632  * ncp is already referenced but this can also occur indirectly through
633  * e.g. holding a lock on a direct child.
634  *
635  * WARNING: Caller may hold an unrelated read spinlock, which means we can't
636  *	    use read spinlocks here.
637  *
638  * MPSAFE if nch is
639  */
640 struct nchandle *
641 cache_hold(struct nchandle *nch)
642 {
643 	_cache_hold(nch->ncp);
644 	atomic_add_int(&nch->mount->mnt_refs, 1);
645 	return(nch);
646 }
647 
648 /*
649  * Create a copy of a namecache handle for an already-referenced
650  * entry.
651  *
652  * MPSAFE if nch is
653  */
654 void
655 cache_copy(struct nchandle *nch, struct nchandle *target)
656 {
657 	*target = *nch;
658 	if (target->ncp)
659 		_cache_hold(target->ncp);
660 	atomic_add_int(&nch->mount->mnt_refs, 1);
661 }
662 
663 /*
664  * MPSAFE if nch is
665  */
666 void
667 cache_changemount(struct nchandle *nch, struct mount *mp)
668 {
669 	atomic_add_int(&nch->mount->mnt_refs, -1);
670 	nch->mount = mp;
671 	atomic_add_int(&nch->mount->mnt_refs, 1);
672 }
673 
674 /*
675  * MPSAFE
676  */
677 void
678 cache_drop(struct nchandle *nch)
679 {
680 	atomic_add_int(&nch->mount->mnt_refs, -1);
681 	_cache_drop(nch->ncp);
682 	nch->ncp = NULL;
683 	nch->mount = NULL;
684 }
685 
686 /*
687  * MPSAFE
688  */
689 void
690 cache_lock(struct nchandle *nch)
691 {
692 	_cache_lock(nch->ncp);
693 }
694 
695 /*
696  * Relock nch1 given an unlocked nch1 and a locked nch2.  The caller
697  * is responsible for checking both for validity on return as they
698  * may have become invalid.
699  *
700  * We have to deal with potential deadlocks here, just ping pong
701  * the lock until we get it (we will always block somewhere when
702  * looping so this is not cpu-intensive).
703  *
704  * which = 0	nch1 not locked, nch2 is locked
705  * which = 1	nch1 is locked, nch2 is not locked
706  */
707 void
708 cache_relock(struct nchandle *nch1, struct ucred *cred1,
709 	     struct nchandle *nch2, struct ucred *cred2)
710 {
711 	int which;
712 
713 	which = 0;
714 
715 	for (;;) {
716 		if (which == 0) {
717 			if (cache_lock_nonblock(nch1) == 0) {
718 				cache_resolve(nch1, cred1);
719 				break;
720 			}
721 			cache_unlock(nch2);
722 			cache_lock(nch1);
723 			cache_resolve(nch1, cred1);
724 			which = 1;
725 		} else {
726 			if (cache_lock_nonblock(nch2) == 0) {
727 				cache_resolve(nch2, cred2);
728 				break;
729 			}
730 			cache_unlock(nch1);
731 			cache_lock(nch2);
732 			cache_resolve(nch2, cred2);
733 			which = 0;
734 		}
735 	}
736 }
737 
738 /*
739  * MPSAFE
740  */
741 int
742 cache_lock_nonblock(struct nchandle *nch)
743 {
744 	return(_cache_lock_nonblock(nch->ncp));
745 }
746 
747 
748 /*
749  * MPSAFE
750  */
751 void
752 cache_unlock(struct nchandle *nch)
753 {
754 	_cache_unlock(nch->ncp);
755 }
756 
757 /*
758  * ref-and-lock, unlock-and-deref functions.
759  *
760  * This function is primarily used by nlookup.  Even though cache_lock
761  * holds the vnode, it is possible that the vnode may have already
762  * initiated a recyclement.
763  *
764  * We want cache_get() to return a definitively usable vnode or a
765  * definitively unresolved ncp.
766  *
767  * MPSAFE
768  */
769 static
770 struct namecache *
771 _cache_get(struct namecache *ncp)
772 {
773 	_cache_hold(ncp);
774 	_cache_lock(ncp);
775 	if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
776 		_cache_setunresolved(ncp);
777 	return(ncp);
778 }
779 
780 /*
781  * This is a special form of _cache_lock() which only succeeds if
782  * it can get a pristine, non-recursive lock.  The caller must have
783  * already ref'd the ncp.
784  *
785  * On success the ncp will be locked, on failure it will not.  The
786  * ref count does not change either way.
787  *
788  * We want _cache_lock_special() (on success) to return a definitively
789  * usable vnode or a definitively unresolved ncp.
790  *
791  * MPSAFE
792  */
793 static int
794 _cache_lock_special(struct namecache *ncp)
795 {
796 	if (_cache_lock_nonblock(ncp) == 0) {
797 		if ((ncp->nc_exlocks & ~NC_EXLOCK_REQ) == 1) {
798 			if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
799 				_cache_setunresolved(ncp);
800 			return(0);
801 		}
802 		_cache_unlock(ncp);
803 	}
804 	return(EWOULDBLOCK);
805 }
806 
807 
808 /*
809  * NOTE: The same nchandle can be passed for both arguments.
810  *
811  * MPSAFE
812  */
813 void
814 cache_get(struct nchandle *nch, struct nchandle *target)
815 {
816 	KKASSERT(nch->ncp->nc_refs > 0);
817 	target->mount = nch->mount;
818 	target->ncp = _cache_get(nch->ncp);
819 	atomic_add_int(&target->mount->mnt_refs, 1);
820 }
821 
822 /*
823  * MPSAFE
824  */
825 static __inline
826 void
827 _cache_put(struct namecache *ncp)
828 {
829 	_cache_unlock(ncp);
830 	_cache_drop(ncp);
831 }
832 
833 /*
834  * MPSAFE
835  */
836 void
837 cache_put(struct nchandle *nch)
838 {
839 	atomic_add_int(&nch->mount->mnt_refs, -1);
840 	_cache_put(nch->ncp);
841 	nch->ncp = NULL;
842 	nch->mount = NULL;
843 }
844 
845 /*
846  * Resolve an unresolved ncp by associating a vnode with it.  If the
847  * vnode is NULL, a negative cache entry is created.
848  *
849  * The ncp should be locked on entry and will remain locked on return.
850  *
851  * MPSAFE
852  */
853 static
854 void
855 _cache_setvp(struct mount *mp, struct namecache *ncp, struct vnode *vp)
856 {
857 	KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
858 
859 	if (vp != NULL) {
860 		/*
861 		 * Any vp associated with an ncp which has children must
862 		 * be held.  Any vp associated with a locked ncp must be held.
863 		 */
864 		if (!TAILQ_EMPTY(&ncp->nc_list))
865 			vhold(vp);
866 		spin_lock_wr(&vp->v_spinlock);
867 		ncp->nc_vp = vp;
868 		TAILQ_INSERT_HEAD(&vp->v_namecache, ncp, nc_vnode);
869 		spin_unlock_wr(&vp->v_spinlock);
870 		if (ncp->nc_exlocks)
871 			vhold(vp);
872 
873 		/*
874 		 * Set auxiliary flags
875 		 */
876 		switch(vp->v_type) {
877 		case VDIR:
878 			ncp->nc_flag |= NCF_ISDIR;
879 			break;
880 		case VLNK:
881 			ncp->nc_flag |= NCF_ISSYMLINK;
882 			/* XXX cache the contents of the symlink */
883 			break;
884 		default:
885 			break;
886 		}
887 		atomic_add_int(&numcache, 1);
888 		ncp->nc_error = 0;
889 	} else {
890 		/*
891 		 * When creating a negative cache hit we set the
892 		 * namecache_gen.  A later resolve will clean out the
893 		 * negative cache hit if the mount point's namecache_gen
894 		 * has changed.  Used by devfs, could also be used by
895 		 * other remote FSs.
896 		 */
897 		ncp->nc_vp = NULL;
898 		spin_lock_wr(&ncspin);
899 		TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
900 		++numneg;
901 		spin_unlock_wr(&ncspin);
902 		ncp->nc_error = ENOENT;
903 		if (mp)
904 			ncp->nc_namecache_gen = mp->mnt_namecache_gen;
905 	}
906 	ncp->nc_flag &= ~(NCF_UNRESOLVED | NCF_DEFEREDZAP);
907 }
908 
909 /*
910  * MPSAFE
911  */
912 void
913 cache_setvp(struct nchandle *nch, struct vnode *vp)
914 {
915 	_cache_setvp(nch->mount, nch->ncp, vp);
916 }
917 
918 /*
919  * MPSAFE
920  */
921 void
922 cache_settimeout(struct nchandle *nch, int nticks)
923 {
924 	struct namecache *ncp = nch->ncp;
925 
926 	if ((ncp->nc_timeout = ticks + nticks) == 0)
927 		ncp->nc_timeout = 1;
928 }
929 
930 /*
931  * Disassociate the vnode or negative-cache association and mark a
932  * namecache entry as unresolved again.  Note that the ncp is still
933  * left in the hash table and still linked to its parent.
934  *
935  * The ncp should be locked and refd on entry and will remain locked and refd
936  * on return.
937  *
938  * This routine is normally never called on a directory containing children.
939  * However, NFS often does just that in its rename() code as a cop-out to
940  * avoid complex namespace operations.  This disconnects a directory vnode
941  * from its namecache and can cause the OLDAPI and NEWAPI to get out of
942  * sync.
943  *
944  * MPSAFE
945  */
946 static
947 void
948 _cache_setunresolved(struct namecache *ncp)
949 {
950 	struct vnode *vp;
951 
952 	if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
953 		ncp->nc_flag |= NCF_UNRESOLVED;
954 		ncp->nc_timeout = 0;
955 		ncp->nc_error = ENOTCONN;
956 		if ((vp = ncp->nc_vp) != NULL) {
957 			atomic_add_int(&numcache, -1);
958 			spin_lock_wr(&vp->v_spinlock);
959 			ncp->nc_vp = NULL;
960 			TAILQ_REMOVE(&vp->v_namecache, ncp, nc_vnode);
961 			spin_unlock_wr(&vp->v_spinlock);
962 
963 			/*
964 			 * Any vp associated with an ncp with children is
965 			 * held by that ncp.  Any vp associated with a locked
966 			 * ncp is held by that ncp.  These conditions must be
967 			 * undone when the vp is cleared out from the ncp.
968 			 */
969 			if (!TAILQ_EMPTY(&ncp->nc_list))
970 				vdrop(vp);
971 			if (ncp->nc_exlocks)
972 				vdrop(vp);
973 		} else {
974 			spin_lock_wr(&ncspin);
975 			TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
976 			--numneg;
977 			spin_unlock_wr(&ncspin);
978 		}
979 		ncp->nc_flag &= ~(NCF_WHITEOUT|NCF_ISDIR|NCF_ISSYMLINK);
980 	}
981 }
982 
983 /*
984  * The cache_nresolve() code calls this function to automatically
985  * set a resolved cache element to unresolved if it has timed out
986  * or if it is a negative cache hit and the mount point namecache_gen
987  * has changed.
988  *
989  * MPSAFE
990  */
991 static __inline void
992 _cache_auto_unresolve(struct mount *mp, struct namecache *ncp)
993 {
994 	/*
995 	 * Already in an unresolved state, nothing to do.
996 	 */
997 	if (ncp->nc_flag & NCF_UNRESOLVED)
998 		return;
999 
1000 	/*
1001 	 * Try to zap entries that have timed out.  We have
1002 	 * to be careful here because locked leafs may depend
1003 	 * on the vnode remaining intact in a parent, so only
1004 	 * do this under very specific conditions.
1005 	 */
1006 	if (ncp->nc_timeout && (int)(ncp->nc_timeout - ticks) < 0 &&
1007 	    TAILQ_EMPTY(&ncp->nc_list)) {
1008 		_cache_setunresolved(ncp);
1009 		return;
1010 	}
1011 
1012 	/*
1013 	 * If a resolved negative cache hit is invalid due to
1014 	 * the mount's namecache generation being bumped, zap it.
1015 	 */
1016 	if (ncp->nc_vp == NULL &&
1017 	    ncp->nc_namecache_gen != mp->mnt_namecache_gen) {
1018 		_cache_setunresolved(ncp);
1019 		return;
1020 	}
1021 }
1022 
1023 /*
1024  * MPSAFE
1025  */
1026 void
1027 cache_setunresolved(struct nchandle *nch)
1028 {
1029 	_cache_setunresolved(nch->ncp);
1030 }
1031 
1032 /*
1033  * Determine if we can clear NCF_ISMOUNTPT by scanning the mountlist
1034  * looking for matches.  This flag tells the lookup code when it must
1035  * check for a mount linkage and also prevents the directories in question
1036  * from being deleted or renamed.
1037  *
1038  * MPSAFE
1039  */
1040 static
1041 int
1042 cache_clrmountpt_callback(struct mount *mp, void *data)
1043 {
1044 	struct nchandle *nch = data;
1045 
1046 	if (mp->mnt_ncmounton.ncp == nch->ncp)
1047 		return(1);
1048 	if (mp->mnt_ncmountpt.ncp == nch->ncp)
1049 		return(1);
1050 	return(0);
1051 }
1052 
1053 /*
1054  * MPSAFE
1055  */
1056 void
1057 cache_clrmountpt(struct nchandle *nch)
1058 {
1059 	int count;
1060 
1061 	count = mountlist_scan(cache_clrmountpt_callback, nch,
1062 			       MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1063 	if (count == 0)
1064 		nch->ncp->nc_flag &= ~NCF_ISMOUNTPT;
1065 }
1066 
1067 /*
1068  * Invalidate portions of the namecache topology given a starting entry.
1069  * The passed ncp is set to an unresolved state and:
1070  *
1071  * The passed ncp must be referencxed and locked.  The routine may unlock
1072  * and relock ncp several times, and will recheck the children and loop
1073  * to catch races.  When done the passed ncp will be returned with the
1074  * reference and lock intact.
1075  *
1076  * CINV_DESTROY		- Set a flag in the passed ncp entry indicating
1077  *			  that the physical underlying nodes have been
1078  *			  destroyed... as in deleted.  For example, when
1079  *			  a directory is removed.  This will cause record
1080  *			  lookups on the name to no longer be able to find
1081  *			  the record and tells the resolver to return failure
1082  *			  rather then trying to resolve through the parent.
1083  *
1084  *			  The topology itself, including ncp->nc_name,
1085  *			  remains intact.
1086  *
1087  *			  This only applies to the passed ncp, if CINV_CHILDREN
1088  *			  is specified the children are not flagged.
1089  *
1090  * CINV_CHILDREN	- Set all children (recursively) to an unresolved
1091  *			  state as well.
1092  *
1093  *			  Note that this will also have the side effect of
1094  *			  cleaning out any unreferenced nodes in the topology
1095  *			  from the leaves up as the recursion backs out.
1096  *
1097  * Note that the topology for any referenced nodes remains intact, but
1098  * the nodes will be marked as having been destroyed and will be set
1099  * to an unresolved state.
1100  *
1101  * It is possible for cache_inval() to race a cache_resolve(), meaning that
1102  * the namecache entry may not actually be invalidated on return if it was
1103  * revalidated while recursing down into its children.  This code guarentees
1104  * that the node(s) will go through an invalidation cycle, but does not
1105  * guarentee that they will remain in an invalidated state.
1106  *
1107  * Returns non-zero if a revalidation was detected during the invalidation
1108  * recursion, zero otherwise.  Note that since only the original ncp is
1109  * locked the revalidation ultimately can only indicate that the original ncp
1110  * *MIGHT* no have been reresolved.
1111  *
1112  * DEEP RECURSION HANDLING - If a recursive invalidation recurses deeply we
1113  * have to avoid blowing out the kernel stack.  We do this by saving the
1114  * deep namecache node and aborting the recursion, then re-recursing at that
1115  * node using a depth-first algorithm in order to allow multiple deep
1116  * recursions to chain through each other, then we restart the invalidation
1117  * from scratch.
1118  *
1119  * MPSAFE
1120  */
1121 
1122 struct cinvtrack {
1123 	struct namecache *resume_ncp;
1124 	int depth;
1125 };
1126 
1127 static int _cache_inval_internal(struct namecache *, int, struct cinvtrack *);
1128 
1129 static
1130 int
1131 _cache_inval(struct namecache *ncp, int flags)
1132 {
1133 	struct cinvtrack track;
1134 	struct namecache *ncp2;
1135 	int r;
1136 
1137 	track.depth = 0;
1138 	track.resume_ncp = NULL;
1139 
1140 	for (;;) {
1141 		r = _cache_inval_internal(ncp, flags, &track);
1142 		if (track.resume_ncp == NULL)
1143 			break;
1144 		kprintf("Warning: deep namecache recursion at %s\n",
1145 			ncp->nc_name);
1146 		_cache_unlock(ncp);
1147 		while ((ncp2 = track.resume_ncp) != NULL) {
1148 			track.resume_ncp = NULL;
1149 			_cache_lock(ncp2);
1150 			_cache_inval_internal(ncp2, flags & ~CINV_DESTROY,
1151 					     &track);
1152 			_cache_put(ncp2);
1153 		}
1154 		_cache_lock(ncp);
1155 	}
1156 	return(r);
1157 }
1158 
1159 int
1160 cache_inval(struct nchandle *nch, int flags)
1161 {
1162 	return(_cache_inval(nch->ncp, flags));
1163 }
1164 
1165 /*
1166  * Helper for _cache_inval().  The passed ncp is refd and locked and
1167  * remains that way on return, but may be unlocked/relocked multiple
1168  * times by the routine.
1169  */
1170 static int
1171 _cache_inval_internal(struct namecache *ncp, int flags, struct cinvtrack *track)
1172 {
1173 	struct namecache *kid;
1174 	struct namecache *nextkid;
1175 	int rcnt = 0;
1176 
1177 	KKASSERT(ncp->nc_exlocks);
1178 
1179 	_cache_setunresolved(ncp);
1180 	if (flags & CINV_DESTROY)
1181 		ncp->nc_flag |= NCF_DESTROYED;
1182 	if ((flags & CINV_CHILDREN) &&
1183 	    (kid = TAILQ_FIRST(&ncp->nc_list)) != NULL
1184 	) {
1185 		_cache_hold(kid);
1186 		if (++track->depth > MAX_RECURSION_DEPTH) {
1187 			track->resume_ncp = ncp;
1188 			_cache_hold(ncp);
1189 			++rcnt;
1190 		}
1191 		_cache_unlock(ncp);
1192 		while (kid) {
1193 			if (track->resume_ncp) {
1194 				_cache_drop(kid);
1195 				break;
1196 			}
1197 			if ((nextkid = TAILQ_NEXT(kid, nc_entry)) != NULL)
1198 				_cache_hold(nextkid);
1199 			if ((kid->nc_flag & NCF_UNRESOLVED) == 0 ||
1200 			    TAILQ_FIRST(&kid->nc_list)
1201 			) {
1202 				_cache_lock(kid);
1203 				rcnt += _cache_inval_internal(kid, flags & ~CINV_DESTROY, track);
1204 				_cache_unlock(kid);
1205 			}
1206 			_cache_drop(kid);
1207 			kid = nextkid;
1208 		}
1209 		--track->depth;
1210 		_cache_lock(ncp);
1211 	}
1212 
1213 	/*
1214 	 * Someone could have gotten in there while ncp was unlocked,
1215 	 * retry if so.
1216 	 */
1217 	if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
1218 		++rcnt;
1219 	return (rcnt);
1220 }
1221 
1222 /*
1223  * Invalidate a vnode's namecache associations.  To avoid races against
1224  * the resolver we do not invalidate a node which we previously invalidated
1225  * but which was then re-resolved while we were in the invalidation loop.
1226  *
1227  * Returns non-zero if any namecache entries remain after the invalidation
1228  * loop completed.
1229  *
1230  * NOTE: Unlike the namecache topology which guarentees that ncp's will not
1231  *	 be ripped out of the topology while held, the vnode's v_namecache
1232  *	 list has no such restriction.  NCP's can be ripped out of the list
1233  *	 at virtually any time if not locked, even if held.
1234  *
1235  *	 In addition, the v_namecache list itself must be locked via
1236  *	 the vnode's spinlock.
1237  *
1238  * MPSAFE
1239  */
1240 int
1241 cache_inval_vp(struct vnode *vp, int flags)
1242 {
1243 	struct namecache *ncp;
1244 	struct namecache *next;
1245 
1246 restart:
1247 	spin_lock_wr(&vp->v_spinlock);
1248 	ncp = TAILQ_FIRST(&vp->v_namecache);
1249 	if (ncp)
1250 		_cache_hold(ncp);
1251 	while (ncp) {
1252 		/* loop entered with ncp held and vp spin-locked */
1253 		if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1254 			_cache_hold(next);
1255 		spin_unlock_wr(&vp->v_spinlock);
1256 		_cache_lock(ncp);
1257 		if (ncp->nc_vp != vp) {
1258 			kprintf("Warning: cache_inval_vp: race-A detected on "
1259 				"%s\n", ncp->nc_name);
1260 			_cache_put(ncp);
1261 			if (next)
1262 				_cache_drop(next);
1263 			goto restart;
1264 		}
1265 		_cache_inval(ncp, flags);
1266 		_cache_put(ncp);		/* also releases reference */
1267 		ncp = next;
1268 		spin_lock_wr(&vp->v_spinlock);
1269 		if (ncp && ncp->nc_vp != vp) {
1270 			spin_unlock_wr(&vp->v_spinlock);
1271 			kprintf("Warning: cache_inval_vp: race-B detected on "
1272 				"%s\n", ncp->nc_name);
1273 			_cache_drop(ncp);
1274 			goto restart;
1275 		}
1276 	}
1277 	spin_unlock_wr(&vp->v_spinlock);
1278 	return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1279 }
1280 
1281 /*
1282  * This routine is used instead of the normal cache_inval_vp() when we
1283  * are trying to recycle otherwise good vnodes.
1284  *
1285  * Return 0 on success, non-zero if not all namecache records could be
1286  * disassociated from the vnode (for various reasons).
1287  *
1288  * MPSAFE
1289  */
1290 int
1291 cache_inval_vp_nonblock(struct vnode *vp)
1292 {
1293 	struct namecache *ncp;
1294 	struct namecache *next;
1295 
1296 	spin_lock_wr(&vp->v_spinlock);
1297 	ncp = TAILQ_FIRST(&vp->v_namecache);
1298 	if (ncp)
1299 		_cache_hold(ncp);
1300 	while (ncp) {
1301 		/* loop entered with ncp held */
1302 		if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1303 			_cache_hold(next);
1304 		spin_unlock_wr(&vp->v_spinlock);
1305 		if (_cache_lock_nonblock(ncp)) {
1306 			_cache_drop(ncp);
1307 			if (next)
1308 				_cache_drop(next);
1309 			goto done;
1310 		}
1311 		if (ncp->nc_vp != vp) {
1312 			kprintf("Warning: cache_inval_vp: race-A detected on "
1313 				"%s\n", ncp->nc_name);
1314 			_cache_put(ncp);
1315 			if (next)
1316 				_cache_drop(next);
1317 			goto done;
1318 		}
1319 		_cache_inval(ncp, 0);
1320 		_cache_put(ncp);		/* also releases reference */
1321 		ncp = next;
1322 		spin_lock_wr(&vp->v_spinlock);
1323 		if (ncp && ncp->nc_vp != vp) {
1324 			spin_unlock_wr(&vp->v_spinlock);
1325 			kprintf("Warning: cache_inval_vp: race-B detected on "
1326 				"%s\n", ncp->nc_name);
1327 			_cache_drop(ncp);
1328 			goto done;
1329 		}
1330 	}
1331 	spin_unlock_wr(&vp->v_spinlock);
1332 done:
1333 	return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1334 }
1335 
1336 /*
1337  * The source ncp has been renamed to the target ncp.  Both fncp and tncp
1338  * must be locked.  The target ncp is destroyed (as a normal rename-over
1339  * would destroy the target file or directory).
1340  *
1341  * Because there may be references to the source ncp we cannot copy its
1342  * contents to the target.  Instead the source ncp is relinked as the target
1343  * and the target ncp is removed from the namecache topology.
1344  *
1345  * MPSAFE
1346  */
1347 void
1348 cache_rename(struct nchandle *fnch, struct nchandle *tnch)
1349 {
1350 	struct namecache *fncp = fnch->ncp;
1351 	struct namecache *tncp = tnch->ncp;
1352 	struct namecache *tncp_par;
1353 	struct nchash_head *nchpp;
1354 	u_int32_t hash;
1355 	char *oname;
1356 
1357 	/*
1358 	 * Rename fncp (unlink)
1359 	 */
1360 	_cache_unlink_parent(fncp);
1361 	oname = fncp->nc_name;
1362 	fncp->nc_name = tncp->nc_name;
1363 	fncp->nc_nlen = tncp->nc_nlen;
1364 	tncp_par = tncp->nc_parent;
1365 	_cache_hold(tncp_par);
1366 	_cache_lock(tncp_par);
1367 
1368 	/*
1369 	 * Rename fncp (relink)
1370 	 */
1371 	hash = fnv_32_buf(fncp->nc_name, fncp->nc_nlen, FNV1_32_INIT);
1372 	hash = fnv_32_buf(&tncp_par, sizeof(tncp_par), hash);
1373 	nchpp = NCHHASH(hash);
1374 
1375 	spin_lock_wr(&nchpp->spin);
1376 	_cache_link_parent(fncp, tncp_par, nchpp);
1377 	spin_unlock_wr(&nchpp->spin);
1378 
1379 	_cache_put(tncp_par);
1380 
1381 	/*
1382 	 * Get rid of the overwritten tncp (unlink)
1383 	 */
1384 	_cache_setunresolved(tncp);
1385 	_cache_unlink_parent(tncp);
1386 	tncp->nc_name = NULL;
1387 	tncp->nc_nlen = 0;
1388 
1389 	if (oname)
1390 		kfree(oname, M_VFSCACHE);
1391 }
1392 
1393 /*
1394  * vget the vnode associated with the namecache entry.  Resolve the namecache
1395  * entry if necessary.  The passed ncp must be referenced and locked.
1396  *
1397  * lk_type may be LK_SHARED, LK_EXCLUSIVE.  A ref'd, possibly locked
1398  * (depending on the passed lk_type) will be returned in *vpp with an error
1399  * of 0, or NULL will be returned in *vpp with a non-0 error code.  The
1400  * most typical error is ENOENT, meaning that the ncp represents a negative
1401  * cache hit and there is no vnode to retrieve, but other errors can occur
1402  * too.
1403  *
1404  * The vget() can race a reclaim.  If this occurs we re-resolve the
1405  * namecache entry.
1406  *
1407  * There are numerous places in the kernel where vget() is called on a
1408  * vnode while one or more of its namecache entries is locked.  Releasing
1409  * a vnode never deadlocks against locked namecache entries (the vnode
1410  * will not get recycled while referenced ncp's exist).  This means we
1411  * can safely acquire the vnode.  In fact, we MUST NOT release the ncp
1412  * lock when acquiring the vp lock or we might cause a deadlock.
1413  *
1414  * MPSAFE
1415  */
1416 int
1417 cache_vget(struct nchandle *nch, struct ucred *cred,
1418 	   int lk_type, struct vnode **vpp)
1419 {
1420 	struct namecache *ncp;
1421 	struct vnode *vp;
1422 	int error;
1423 
1424 	ncp = nch->ncp;
1425 	KKASSERT(ncp->nc_locktd == curthread);
1426 again:
1427 	vp = NULL;
1428 	if (ncp->nc_flag & NCF_UNRESOLVED)
1429 		error = cache_resolve(nch, cred);
1430 	else
1431 		error = 0;
1432 
1433 	if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1434 		error = vget(vp, lk_type);
1435 		if (error) {
1436 			/*
1437 			 * VRECLAIM race
1438 			 */
1439 			if (error == ENOENT) {
1440 				kprintf("Warning: vnode reclaim race detected "
1441 					"in cache_vget on %p (%s)\n",
1442 					vp, ncp->nc_name);
1443 				_cache_setunresolved(ncp);
1444 				goto again;
1445 			}
1446 
1447 			/*
1448 			 * Not a reclaim race, some other error.
1449 			 */
1450 			KKASSERT(ncp->nc_vp == vp);
1451 			vp = NULL;
1452 		} else {
1453 			KKASSERT(ncp->nc_vp == vp);
1454 			KKASSERT((vp->v_flag & VRECLAIMED) == 0);
1455 		}
1456 	}
1457 	if (error == 0 && vp == NULL)
1458 		error = ENOENT;
1459 	*vpp = vp;
1460 	return(error);
1461 }
1462 
1463 int
1464 cache_vref(struct nchandle *nch, struct ucred *cred, struct vnode **vpp)
1465 {
1466 	struct namecache *ncp;
1467 	struct vnode *vp;
1468 	int error;
1469 
1470 	ncp = nch->ncp;
1471 	KKASSERT(ncp->nc_locktd == curthread);
1472 again:
1473 	vp = NULL;
1474 	if (ncp->nc_flag & NCF_UNRESOLVED)
1475 		error = cache_resolve(nch, cred);
1476 	else
1477 		error = 0;
1478 
1479 	if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1480 		error = vget(vp, LK_SHARED);
1481 		if (error) {
1482 			/*
1483 			 * VRECLAIM race
1484 			 */
1485 			if (error == ENOENT) {
1486 				kprintf("Warning: vnode reclaim race detected "
1487 					"in cache_vget on %p (%s)\n",
1488 					vp, ncp->nc_name);
1489 				_cache_setunresolved(ncp);
1490 				goto again;
1491 			}
1492 
1493 			/*
1494 			 * Not a reclaim race, some other error.
1495 			 */
1496 			KKASSERT(ncp->nc_vp == vp);
1497 			vp = NULL;
1498 		} else {
1499 			KKASSERT(ncp->nc_vp == vp);
1500 			KKASSERT((vp->v_flag & VRECLAIMED) == 0);
1501 			/* caller does not want a lock */
1502 			vn_unlock(vp);
1503 		}
1504 	}
1505 	if (error == 0 && vp == NULL)
1506 		error = ENOENT;
1507 	*vpp = vp;
1508 	return(error);
1509 }
1510 
1511 /*
1512  * Return a referenced vnode representing the parent directory of
1513  * ncp.
1514  *
1515  * Because the caller has locked the ncp it should not be possible for
1516  * the parent ncp to go away.  However, the parent can unresolve its
1517  * dvp at any time so we must be able to acquire a lock on the parent
1518  * to safely access nc_vp.
1519  *
1520  * We have to leave par unlocked when vget()ing dvp to avoid a deadlock,
1521  * so use vhold()/vdrop() while holding the lock to prevent dvp from
1522  * getting destroyed.
1523  *
1524  * MPSAFE - Note vhold() is allowed when dvp has 0 refs if we hold a
1525  *	    lock on the ncp in question..
1526  */
1527 static struct vnode *
1528 cache_dvpref(struct namecache *ncp)
1529 {
1530 	struct namecache *par;
1531 	struct vnode *dvp;
1532 
1533 	dvp = NULL;
1534 	if ((par = ncp->nc_parent) != NULL) {
1535 		_cache_hold(par);
1536 		_cache_lock(par);
1537 		if ((par->nc_flag & NCF_UNRESOLVED) == 0) {
1538 			if ((dvp = par->nc_vp) != NULL)
1539 				vhold(dvp);
1540 		}
1541 		_cache_unlock(par);
1542 		if (dvp) {
1543 			if (vget(dvp, LK_SHARED) == 0) {
1544 				vn_unlock(dvp);
1545 				vdrop(dvp);
1546 				/* return refd, unlocked dvp */
1547 			} else {
1548 				vdrop(dvp);
1549 				dvp = NULL;
1550 			}
1551 		}
1552 		_cache_drop(par);
1553 	}
1554 	return(dvp);
1555 }
1556 
1557 /*
1558  * Convert a directory vnode to a namecache record without any other
1559  * knowledge of the topology.  This ONLY works with directory vnodes and
1560  * is ONLY used by the NFS server.  dvp must be refd but unlocked, and the
1561  * returned ncp (if not NULL) will be held and unlocked.
1562  *
1563  * If 'makeit' is 0 and dvp has no existing namecache record, NULL is returned.
1564  * If 'makeit' is 1 we attempt to track-down and create the namecache topology
1565  * for dvp.  This will fail only if the directory has been deleted out from
1566  * under the caller.
1567  *
1568  * Callers must always check for a NULL return no matter the value of 'makeit'.
1569  *
1570  * To avoid underflowing the kernel stack each recursive call increments
1571  * the makeit variable.
1572  */
1573 
1574 static int cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1575 				  struct vnode *dvp, char *fakename);
1576 static int cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1577 				  struct vnode **saved_dvp);
1578 
1579 int
1580 cache_fromdvp(struct vnode *dvp, struct ucred *cred, int makeit,
1581 	      struct nchandle *nch)
1582 {
1583 	struct vnode *saved_dvp;
1584 	struct vnode *pvp;
1585 	char *fakename;
1586 	int error;
1587 
1588 	nch->ncp = NULL;
1589 	nch->mount = dvp->v_mount;
1590 	saved_dvp = NULL;
1591 	fakename = NULL;
1592 
1593 	/*
1594 	 * Loop until resolution, inside code will break out on error.
1595 	 */
1596 	while (makeit) {
1597 		/*
1598 		 * Break out if we successfully acquire a working ncp.
1599 		 */
1600 		spin_lock_wr(&dvp->v_spinlock);
1601 		nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
1602 		if (nch->ncp) {
1603 			cache_hold(nch);
1604 			spin_unlock_wr(&dvp->v_spinlock);
1605 			break;
1606 		}
1607 		spin_unlock_wr(&dvp->v_spinlock);
1608 
1609 		/*
1610 		 * If dvp is the root of its filesystem it should already
1611 		 * have a namecache pointer associated with it as a side
1612 		 * effect of the mount, but it may have been disassociated.
1613 		 */
1614 		if (dvp->v_flag & VROOT) {
1615 			nch->ncp = _cache_get(nch->mount->mnt_ncmountpt.ncp);
1616 			error = cache_resolve_mp(nch->mount);
1617 			_cache_put(nch->ncp);
1618 			if (ncvp_debug) {
1619 				kprintf("cache_fromdvp: resolve root of mount %p error %d",
1620 					dvp->v_mount, error);
1621 			}
1622 			if (error) {
1623 				if (ncvp_debug)
1624 					kprintf(" failed\n");
1625 				nch->ncp = NULL;
1626 				break;
1627 			}
1628 			if (ncvp_debug)
1629 				kprintf(" succeeded\n");
1630 			continue;
1631 		}
1632 
1633 		/*
1634 		 * If we are recursed too deeply resort to an O(n^2)
1635 		 * algorithm to resolve the namecache topology.  The
1636 		 * resolved pvp is left referenced in saved_dvp to
1637 		 * prevent the tree from being destroyed while we loop.
1638 		 */
1639 		if (makeit > 20) {
1640 			error = cache_fromdvp_try(dvp, cred, &saved_dvp);
1641 			if (error) {
1642 				kprintf("lookupdotdot(longpath) failed %d "
1643 				       "dvp %p\n", error, dvp);
1644 				nch->ncp = NULL;
1645 				break;
1646 			}
1647 			continue;
1648 		}
1649 
1650 		/*
1651 		 * Get the parent directory and resolve its ncp.
1652 		 */
1653 		if (fakename) {
1654 			kfree(fakename, M_TEMP);
1655 			fakename = NULL;
1656 		}
1657 		error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
1658 					  &fakename);
1659 		if (error) {
1660 			kprintf("lookupdotdot failed %d dvp %p\n", error, dvp);
1661 			break;
1662 		}
1663 		vn_unlock(pvp);
1664 
1665 		/*
1666 		 * Reuse makeit as a recursion depth counter.  On success
1667 		 * nch will be fully referenced.
1668 		 */
1669 		cache_fromdvp(pvp, cred, makeit + 1, nch);
1670 		vrele(pvp);
1671 		if (nch->ncp == NULL)
1672 			break;
1673 
1674 		/*
1675 		 * Do an inefficient scan of pvp (embodied by ncp) to look
1676 		 * for dvp.  This will create a namecache record for dvp on
1677 		 * success.  We loop up to recheck on success.
1678 		 *
1679 		 * ncp and dvp are both held but not locked.
1680 		 */
1681 		error = cache_inefficient_scan(nch, cred, dvp, fakename);
1682 		if (error) {
1683 			kprintf("cache_fromdvp: scan %p (%s) failed on dvp=%p\n",
1684 				pvp, nch->ncp->nc_name, dvp);
1685 			cache_drop(nch);
1686 			/* nch was NULLed out, reload mount */
1687 			nch->mount = dvp->v_mount;
1688 			break;
1689 		}
1690 		if (ncvp_debug) {
1691 			kprintf("cache_fromdvp: scan %p (%s) succeeded\n",
1692 				pvp, nch->ncp->nc_name);
1693 		}
1694 		cache_drop(nch);
1695 		/* nch was NULLed out, reload mount */
1696 		nch->mount = dvp->v_mount;
1697 	}
1698 
1699 	/*
1700 	 * If nch->ncp is non-NULL it will have been held already.
1701 	 */
1702 	if (fakename)
1703 		kfree(fakename, M_TEMP);
1704 	if (saved_dvp)
1705 		vrele(saved_dvp);
1706 	if (nch->ncp)
1707 		return (0);
1708 	return (EINVAL);
1709 }
1710 
1711 /*
1712  * Go up the chain of parent directories until we find something
1713  * we can resolve into the namecache.  This is very inefficient.
1714  */
1715 static
1716 int
1717 cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1718 		  struct vnode **saved_dvp)
1719 {
1720 	struct nchandle nch;
1721 	struct vnode *pvp;
1722 	int error;
1723 	static time_t last_fromdvp_report;
1724 	char *fakename;
1725 
1726 	/*
1727 	 * Loop getting the parent directory vnode until we get something we
1728 	 * can resolve in the namecache.
1729 	 */
1730 	vref(dvp);
1731 	nch.mount = dvp->v_mount;
1732 	nch.ncp = NULL;
1733 	fakename = NULL;
1734 
1735 	for (;;) {
1736 		if (fakename) {
1737 			kfree(fakename, M_TEMP);
1738 			fakename = NULL;
1739 		}
1740 		error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
1741 					  &fakename);
1742 		if (error) {
1743 			vrele(dvp);
1744 			break;
1745 		}
1746 		vn_unlock(pvp);
1747 		spin_lock_wr(&pvp->v_spinlock);
1748 		if ((nch.ncp = TAILQ_FIRST(&pvp->v_namecache)) != NULL) {
1749 			_cache_hold(nch.ncp);
1750 			spin_unlock_wr(&pvp->v_spinlock);
1751 			vrele(pvp);
1752 			break;
1753 		}
1754 		spin_unlock_wr(&pvp->v_spinlock);
1755 		if (pvp->v_flag & VROOT) {
1756 			nch.ncp = _cache_get(pvp->v_mount->mnt_ncmountpt.ncp);
1757 			error = cache_resolve_mp(nch.mount);
1758 			_cache_unlock(nch.ncp);
1759 			vrele(pvp);
1760 			if (error) {
1761 				_cache_drop(nch.ncp);
1762 				nch.ncp = NULL;
1763 				vrele(dvp);
1764 			}
1765 			break;
1766 		}
1767 		vrele(dvp);
1768 		dvp = pvp;
1769 	}
1770 	if (error == 0) {
1771 		if (last_fromdvp_report != time_second) {
1772 			last_fromdvp_report = time_second;
1773 			kprintf("Warning: extremely inefficient path "
1774 				"resolution on %s\n",
1775 				nch.ncp->nc_name);
1776 		}
1777 		error = cache_inefficient_scan(&nch, cred, dvp, fakename);
1778 
1779 		/*
1780 		 * Hopefully dvp now has a namecache record associated with
1781 		 * it.  Leave it referenced to prevent the kernel from
1782 		 * recycling the vnode.  Otherwise extremely long directory
1783 		 * paths could result in endless recycling.
1784 		 */
1785 		if (*saved_dvp)
1786 		    vrele(*saved_dvp);
1787 		*saved_dvp = dvp;
1788 		_cache_drop(nch.ncp);
1789 	}
1790 	if (fakename)
1791 		kfree(fakename, M_TEMP);
1792 	return (error);
1793 }
1794 
1795 /*
1796  * Do an inefficient scan of the directory represented by ncp looking for
1797  * the directory vnode dvp.  ncp must be held but not locked on entry and
1798  * will be held on return.  dvp must be refd but not locked on entry and
1799  * will remain refd on return.
1800  *
1801  * Why do this at all?  Well, due to its stateless nature the NFS server
1802  * converts file handles directly to vnodes without necessarily going through
1803  * the namecache ops that would otherwise create the namecache topology
1804  * leading to the vnode.  We could either (1) Change the namecache algorithms
1805  * to allow disconnect namecache records that are re-merged opportunistically,
1806  * or (2) Make the NFS server backtrack and scan to recover a connected
1807  * namecache topology in order to then be able to issue new API lookups.
1808  *
1809  * It turns out that (1) is a huge mess.  It takes a nice clean set of
1810  * namecache algorithms and introduces a lot of complication in every subsystem
1811  * that calls into the namecache to deal with the re-merge case, especially
1812  * since we are using the namecache to placehold negative lookups and the
1813  * vnode might not be immediately assigned. (2) is certainly far less
1814  * efficient then (1), but since we are only talking about directories here
1815  * (which are likely to remain cached), the case does not actually run all
1816  * that often and has the supreme advantage of not polluting the namecache
1817  * algorithms.
1818  *
1819  * If a fakename is supplied just construct a namecache entry using the
1820  * fake name.
1821  */
1822 static int
1823 cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1824 		       struct vnode *dvp, char *fakename)
1825 {
1826 	struct nlcomponent nlc;
1827 	struct nchandle rncp;
1828 	struct dirent *den;
1829 	struct vnode *pvp;
1830 	struct vattr vat;
1831 	struct iovec iov;
1832 	struct uio uio;
1833 	int blksize;
1834 	int eofflag;
1835 	int bytes;
1836 	char *rbuf;
1837 	int error;
1838 
1839 	vat.va_blocksize = 0;
1840 	if ((error = VOP_GETATTR(dvp, &vat)) != 0)
1841 		return (error);
1842 	cache_lock(nch);
1843 	error = cache_vref(nch, cred, &pvp);
1844 	cache_unlock(nch);
1845 	if (error)
1846 		return (error);
1847 	if (ncvp_debug) {
1848 		kprintf("inefficient_scan: directory iosize %ld "
1849 			"vattr fileid = %lld\n",
1850 			vat.va_blocksize,
1851 			(long long)vat.va_fileid);
1852 	}
1853 
1854 	/*
1855 	 * Use the supplied fakename if not NULL.  Fake names are typically
1856 	 * not in the actual filesystem hierarchy.  This is used by HAMMER
1857 	 * to glue @@timestamp recursions together.
1858 	 */
1859 	if (fakename) {
1860 		nlc.nlc_nameptr = fakename;
1861 		nlc.nlc_namelen = strlen(fakename);
1862 		rncp = cache_nlookup(nch, &nlc);
1863 		goto done;
1864 	}
1865 
1866 	if ((blksize = vat.va_blocksize) == 0)
1867 		blksize = DEV_BSIZE;
1868 	rbuf = kmalloc(blksize, M_TEMP, M_WAITOK);
1869 	rncp.ncp = NULL;
1870 
1871 	eofflag = 0;
1872 	uio.uio_offset = 0;
1873 again:
1874 	iov.iov_base = rbuf;
1875 	iov.iov_len = blksize;
1876 	uio.uio_iov = &iov;
1877 	uio.uio_iovcnt = 1;
1878 	uio.uio_resid = blksize;
1879 	uio.uio_segflg = UIO_SYSSPACE;
1880 	uio.uio_rw = UIO_READ;
1881 	uio.uio_td = curthread;
1882 
1883 	if (ncvp_debug >= 2)
1884 		kprintf("cache_inefficient_scan: readdir @ %08x\n", (int)uio.uio_offset);
1885 	error = VOP_READDIR(pvp, &uio, cred, &eofflag, NULL, NULL);
1886 	if (error == 0) {
1887 		den = (struct dirent *)rbuf;
1888 		bytes = blksize - uio.uio_resid;
1889 
1890 		while (bytes > 0) {
1891 			if (ncvp_debug >= 2) {
1892 				kprintf("cache_inefficient_scan: %*.*s\n",
1893 					den->d_namlen, den->d_namlen,
1894 					den->d_name);
1895 			}
1896 			if (den->d_type != DT_WHT &&
1897 			    den->d_ino == vat.va_fileid) {
1898 				if (ncvp_debug) {
1899 					kprintf("cache_inefficient_scan: "
1900 					       "MATCHED inode %lld path %s/%*.*s\n",
1901 					       (long long)vat.va_fileid,
1902 					       nch->ncp->nc_name,
1903 					       den->d_namlen, den->d_namlen,
1904 					       den->d_name);
1905 				}
1906 				nlc.nlc_nameptr = den->d_name;
1907 				nlc.nlc_namelen = den->d_namlen;
1908 				rncp = cache_nlookup(nch, &nlc);
1909 				KKASSERT(rncp.ncp != NULL);
1910 				break;
1911 			}
1912 			bytes -= _DIRENT_DIRSIZ(den);
1913 			den = _DIRENT_NEXT(den);
1914 		}
1915 		if (rncp.ncp == NULL && eofflag == 0 && uio.uio_resid != blksize)
1916 			goto again;
1917 	}
1918 	kfree(rbuf, M_TEMP);
1919 done:
1920 	vrele(pvp);
1921 	if (rncp.ncp) {
1922 		if (rncp.ncp->nc_flag & NCF_UNRESOLVED) {
1923 			_cache_setvp(rncp.mount, rncp.ncp, dvp);
1924 			if (ncvp_debug >= 2) {
1925 				kprintf("cache_inefficient_scan: setvp %s/%s = %p\n",
1926 					nch->ncp->nc_name, rncp.ncp->nc_name, dvp);
1927 			}
1928 		} else {
1929 			if (ncvp_debug >= 2) {
1930 				kprintf("cache_inefficient_scan: setvp %s/%s already set %p/%p\n",
1931 					nch->ncp->nc_name, rncp.ncp->nc_name, dvp,
1932 					rncp.ncp->nc_vp);
1933 			}
1934 		}
1935 		if (rncp.ncp->nc_vp == NULL)
1936 			error = rncp.ncp->nc_error;
1937 		/*
1938 		 * Release rncp after a successful nlookup.  rncp was fully
1939 		 * referenced.
1940 		 */
1941 		cache_put(&rncp);
1942 	} else {
1943 		kprintf("cache_inefficient_scan: dvp %p NOT FOUND in %s\n",
1944 			dvp, nch->ncp->nc_name);
1945 		error = ENOENT;
1946 	}
1947 	return (error);
1948 }
1949 
1950 /*
1951  * Zap a namecache entry.  The ncp is unconditionally set to an unresolved
1952  * state, which disassociates it from its vnode or ncneglist.
1953  *
1954  * Then, if there are no additional references to the ncp and no children,
1955  * the ncp is removed from the topology and destroyed.
1956  *
1957  * References and/or children may exist if the ncp is in the middle of the
1958  * topology, preventing the ncp from being destroyed.
1959  *
1960  * This function must be called with the ncp held and locked and will unlock
1961  * and drop it during zapping.
1962  *
1963  * If nonblock is non-zero and the parent ncp cannot be locked we give up.
1964  * This case can occur in the cache_drop() path.
1965  *
1966  * This function may returned a held (but NOT locked) parent node which the
1967  * caller must drop.  We do this so _cache_drop() can loop, to avoid
1968  * blowing out the kernel stack.
1969  *
1970  * WARNING!  For MPSAFE operation this routine must acquire up to three
1971  *	     spin locks to be able to safely test nc_refs.  Lock order is
1972  *	     very important.
1973  *
1974  *	     hash spinlock if on hash list
1975  *	     parent spinlock if child of parent
1976  *	     (the ncp is unresolved so there is no vnode association)
1977  */
1978 static struct namecache *
1979 cache_zap(struct namecache *ncp, int nonblock)
1980 {
1981 	struct namecache *par;
1982 	struct vnode *dropvp;
1983 	int refs;
1984 
1985 	/*
1986 	 * Disassociate the vnode or negative cache ref and set NCF_UNRESOLVED.
1987 	 */
1988 	_cache_setunresolved(ncp);
1989 
1990 	/*
1991 	 * Try to scrap the entry and possibly tail-recurse on its parent.
1992 	 * We only scrap unref'd (other then our ref) unresolved entries,
1993 	 * we do not scrap 'live' entries.
1994 	 *
1995 	 * Note that once the spinlocks are acquired if nc_refs == 1 no
1996 	 * other references are possible.  If it isn't, however, we have
1997 	 * to decrement but also be sure to avoid a 1->0 transition.
1998 	 */
1999 	KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
2000 	KKASSERT(ncp->nc_refs > 0);
2001 
2002 	/*
2003 	 * Acquire locks.  Note that the parent can't go away while we hold
2004 	 * a child locked.
2005 	 */
2006 	if ((par = ncp->nc_parent) != NULL) {
2007 		if (nonblock) {
2008 			for (;;) {
2009 				if (_cache_lock_nonblock(par) == 0)
2010 					break;
2011 				kprintf("Warning ncp %p cache_drop "
2012 					"deadlock avoided\n", ncp);
2013 				refs = ncp->nc_refs;
2014 				ncp->nc_flag |= NCF_DEFEREDZAP;
2015 				++numdefered;	/* MP race ok */
2016 				if (atomic_cmpset_int(&ncp->nc_refs,
2017 						      refs, refs - 1)) {
2018 					_cache_unlock(ncp);
2019 					return(NULL);
2020 				}
2021 				cpu_pause();
2022 			}
2023 			_cache_hold(par);
2024 		} else {
2025 			_cache_hold(par);
2026 			_cache_lock(par);
2027 		}
2028 		spin_lock_wr(&ncp->nc_head->spin);
2029 	}
2030 
2031 	/*
2032 	 * If someone other then us has a ref or we have children
2033 	 * we cannot zap the entry.  The 1->0 transition and any
2034 	 * further list operation is protected by the spinlocks
2035 	 * we have acquired but other transitions are not.
2036 	 */
2037 	for (;;) {
2038 		refs = ncp->nc_refs;
2039 		if (refs == 1 && TAILQ_EMPTY(&ncp->nc_list))
2040 			break;
2041 		if (atomic_cmpset_int(&ncp->nc_refs, refs, refs - 1)) {
2042 			if (par) {
2043 				spin_unlock_wr(&ncp->nc_head->spin);
2044 				_cache_put(par);
2045 			}
2046 			_cache_unlock(ncp);
2047 			return(NULL);
2048 		}
2049 		cpu_pause();
2050 	}
2051 
2052 	/*
2053 	 * We are the only ref and with the spinlocks held no further
2054 	 * refs can be acquired by others.
2055 	 *
2056 	 * Remove us from the hash list and parent list.  We have to
2057 	 * drop a ref on the parent's vp if the parent's list becomes
2058 	 * empty.
2059 	 */
2060 	dropvp = NULL;
2061 	if (par) {
2062 		struct nchash_head *nchpp = ncp->nc_head;
2063 
2064 		KKASSERT(nchpp != NULL);
2065 		LIST_REMOVE(ncp, nc_hash);
2066 		TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
2067 		if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
2068 			dropvp = par->nc_vp;
2069 		ncp->nc_head = NULL;
2070 		ncp->nc_parent = NULL;
2071 		spin_unlock_wr(&nchpp->spin);
2072 		_cache_unlock(par);
2073 	} else {
2074 		KKASSERT(ncp->nc_head == NULL);
2075 	}
2076 
2077 	/*
2078 	 * ncp should not have picked up any refs.  Physically
2079 	 * destroy the ncp.
2080 	 */
2081 	KKASSERT(ncp->nc_refs == 1);
2082 	/* _cache_unlock(ncp) not required */
2083 	ncp->nc_refs = -1;	/* safety */
2084 	if (ncp->nc_name)
2085 		kfree(ncp->nc_name, M_VFSCACHE);
2086 	kfree(ncp, M_VFSCACHE);
2087 
2088 	/*
2089 	 * Delayed drop (we had to release our spinlocks)
2090 	 *
2091 	 * The refed parent (if not  NULL) must be dropped.  The
2092 	 * caller is responsible for looping.
2093 	 */
2094 	if (dropvp)
2095 		vdrop(dropvp);
2096 	return(par);
2097 }
2098 
2099 /*
2100  * Clean up dangling negative cache and defered-drop entries in the
2101  * namecache.
2102  */
2103 static enum { CHI_LOW, CHI_HIGH } cache_hysteresis_state = CHI_LOW;
2104 
2105 void
2106 cache_hysteresis(void)
2107 {
2108 	/*
2109 	 * Don't cache too many negative hits.  We use hysteresis to reduce
2110 	 * the impact on the critical path.
2111 	 */
2112 	switch(cache_hysteresis_state) {
2113 	case CHI_LOW:
2114 		if (numneg > MINNEG && numneg * ncnegfactor > numcache) {
2115 			_cache_cleanneg(10);
2116 			cache_hysteresis_state = CHI_HIGH;
2117 		}
2118 		break;
2119 	case CHI_HIGH:
2120 		if (numneg > MINNEG * 9 / 10 &&
2121 		    numneg * ncnegfactor * 9 / 10 > numcache
2122 		) {
2123 			_cache_cleanneg(10);
2124 		} else {
2125 			cache_hysteresis_state = CHI_LOW;
2126 		}
2127 		break;
2128 	}
2129 
2130 	/*
2131 	 * Clean out dangling defered-zap ncps which could not
2132 	 * be cleanly dropped if too many build up.  Note
2133 	 * that numdefered is not an exact number as such ncps
2134 	 * can be reused and the counter is not handled in a MP
2135 	 * safe manner by design.
2136 	 */
2137 	if (numdefered * ncnegfactor > numcache) {
2138 		_cache_cleandefered();
2139 	}
2140 }
2141 
2142 /*
2143  * NEW NAMECACHE LOOKUP API
2144  *
2145  * Lookup an entry in the namecache.  The passed par_nch must be referenced
2146  * and unlocked.  A referenced and locked nchandle with a non-NULL nch.ncp
2147  * is ALWAYS returned, eve if the supplied component is illegal.
2148  *
2149  * The resulting namecache entry should be returned to the system with
2150  * cache_put() or cache_unlock() + cache_drop().
2151  *
2152  * namecache locks are recursive but care must be taken to avoid lock order
2153  * reversals (hence why the passed par_nch must be unlocked).  Locking
2154  * rules are to order for parent traversals, not for child traversals.
2155  *
2156  * Nobody else will be able to manipulate the associated namespace (e.g.
2157  * create, delete, rename, rename-target) until the caller unlocks the
2158  * entry.
2159  *
2160  * The returned entry will be in one of three states:  positive hit (non-null
2161  * vnode), negative hit (null vnode), or unresolved (NCF_UNRESOLVED is set).
2162  * Unresolved entries must be resolved through the filesystem to associate the
2163  * vnode and/or determine whether a positive or negative hit has occured.
2164  *
2165  * It is not necessary to lock a directory in order to lock namespace under
2166  * that directory.  In fact, it is explicitly not allowed to do that.  A
2167  * directory is typically only locked when being created, renamed, or
2168  * destroyed.
2169  *
2170  * The directory (par) may be unresolved, in which case any returned child
2171  * will likely also be marked unresolved.  Likely but not guarenteed.  Since
2172  * the filesystem lookup requires a resolved directory vnode the caller is
2173  * responsible for resolving the namecache chain top-down.  This API
2174  * specifically allows whole chains to be created in an unresolved state.
2175  */
2176 struct nchandle
2177 cache_nlookup(struct nchandle *par_nch, struct nlcomponent *nlc)
2178 {
2179 	struct nchandle nch;
2180 	struct namecache *ncp;
2181 	struct namecache *new_ncp;
2182 	struct nchash_head *nchpp;
2183 	struct mount *mp;
2184 	u_int32_t hash;
2185 	globaldata_t gd;
2186 	int par_locked;
2187 
2188 	numcalls++;
2189 	gd = mycpu;
2190 	mp = par_nch->mount;
2191 	par_locked = 0;
2192 
2193 	/*
2194 	 * This is a good time to call it, no ncp's are locked by
2195 	 * the caller or us.
2196 	 */
2197 	cache_hysteresis();
2198 
2199 	/*
2200 	 * Try to locate an existing entry
2201 	 */
2202 	hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
2203 	hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
2204 	new_ncp = NULL;
2205 	nchpp = NCHHASH(hash);
2206 restart:
2207 	spin_lock_wr(&nchpp->spin);
2208 	LIST_FOREACH(ncp, &nchpp->list, nc_hash) {
2209 		numchecks++;
2210 
2211 		/*
2212 		 * Break out if we find a matching entry.  Note that
2213 		 * UNRESOLVED entries may match, but DESTROYED entries
2214 		 * do not.
2215 		 */
2216 		if (ncp->nc_parent == par_nch->ncp &&
2217 		    ncp->nc_nlen == nlc->nlc_namelen &&
2218 		    bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
2219 		    (ncp->nc_flag & NCF_DESTROYED) == 0
2220 		) {
2221 			_cache_hold(ncp);
2222 			spin_unlock_wr(&nchpp->spin);
2223 			if (par_locked) {
2224 				_cache_unlock(par_nch->ncp);
2225 				par_locked = 0;
2226 			}
2227 			if (_cache_lock_special(ncp) == 0) {
2228 				_cache_auto_unresolve(mp, ncp);
2229 				if (new_ncp)
2230 					_cache_free(new_ncp);
2231 				goto found;
2232 			}
2233 			_cache_get(ncp);
2234 			_cache_put(ncp);
2235 			_cache_drop(ncp);
2236 			goto restart;
2237 		}
2238 	}
2239 
2240 	/*
2241 	 * We failed to locate an entry, create a new entry and add it to
2242 	 * the cache.  The parent ncp must also be locked so we
2243 	 * can link into it.
2244 	 *
2245 	 * We have to relookup after possibly blocking in kmalloc or
2246 	 * when locking par_nch.
2247 	 *
2248 	 * NOTE: nlc_namelen can be 0 and nlc_nameptr NULL as a special
2249 	 *	 mount case, in which case nc_name will be NULL.
2250 	 */
2251 	if (new_ncp == NULL) {
2252 		spin_unlock_wr(&nchpp->spin);
2253 		new_ncp = cache_alloc(nlc->nlc_namelen);
2254 		if (nlc->nlc_namelen) {
2255 			bcopy(nlc->nlc_nameptr, new_ncp->nc_name,
2256 			      nlc->nlc_namelen);
2257 			new_ncp->nc_name[nlc->nlc_namelen] = 0;
2258 		}
2259 		goto restart;
2260 	}
2261 	if (par_locked == 0) {
2262 		spin_unlock_wr(&nchpp->spin);
2263 		_cache_lock(par_nch->ncp);
2264 		par_locked = 1;
2265 		goto restart;
2266 	}
2267 
2268 	/*
2269 	 * WARNING!  We still hold the spinlock.  We have to set the hash
2270 	 *	     table entry attomically.
2271 	 */
2272 	ncp = new_ncp;
2273 	_cache_link_parent(ncp, par_nch->ncp, nchpp);
2274 	spin_unlock_wr(&nchpp->spin);
2275 	_cache_unlock(par_nch->ncp);
2276 	/* par_locked = 0 - not used */
2277 found:
2278 	/*
2279 	 * stats and namecache size management
2280 	 */
2281 	if (ncp->nc_flag & NCF_UNRESOLVED)
2282 		++gd->gd_nchstats->ncs_miss;
2283 	else if (ncp->nc_vp)
2284 		++gd->gd_nchstats->ncs_goodhits;
2285 	else
2286 		++gd->gd_nchstats->ncs_neghits;
2287 	nch.mount = mp;
2288 	nch.ncp = ncp;
2289 	atomic_add_int(&nch.mount->mnt_refs, 1);
2290 	return(nch);
2291 }
2292 
2293 /*
2294  * The namecache entry is marked as being used as a mount point.
2295  * Locate the mount if it is visible to the caller.
2296  */
2297 struct findmount_info {
2298 	struct mount *result;
2299 	struct mount *nch_mount;
2300 	struct namecache *nch_ncp;
2301 };
2302 
2303 static
2304 int
2305 cache_findmount_callback(struct mount *mp, void *data)
2306 {
2307 	struct findmount_info *info = data;
2308 
2309 	/*
2310 	 * Check the mount's mounted-on point against the passed nch.
2311 	 */
2312 	if (mp->mnt_ncmounton.mount == info->nch_mount &&
2313 	    mp->mnt_ncmounton.ncp == info->nch_ncp
2314 	) {
2315 	    info->result = mp;
2316 	    return(-1);
2317 	}
2318 	return(0);
2319 }
2320 
2321 struct mount *
2322 cache_findmount(struct nchandle *nch)
2323 {
2324 	struct findmount_info info;
2325 
2326 	info.result = NULL;
2327 	info.nch_mount = nch->mount;
2328 	info.nch_ncp = nch->ncp;
2329 	mountlist_scan(cache_findmount_callback, &info,
2330 			       MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
2331 	return(info.result);
2332 }
2333 
2334 /*
2335  * Resolve an unresolved namecache entry, generally by looking it up.
2336  * The passed ncp must be locked and refd.
2337  *
2338  * Theoretically since a vnode cannot be recycled while held, and since
2339  * the nc_parent chain holds its vnode as long as children exist, the
2340  * direct parent of the cache entry we are trying to resolve should
2341  * have a valid vnode.  If not then generate an error that we can
2342  * determine is related to a resolver bug.
2343  *
2344  * However, if a vnode was in the middle of a recyclement when the NCP
2345  * got locked, ncp->nc_vp might point to a vnode that is about to become
2346  * invalid.  cache_resolve() handles this case by unresolving the entry
2347  * and then re-resolving it.
2348  *
2349  * Note that successful resolution does not necessarily return an error
2350  * code of 0.  If the ncp resolves to a negative cache hit then ENOENT
2351  * will be returned.
2352  *
2353  * MPSAFE
2354  */
2355 int
2356 cache_resolve(struct nchandle *nch, struct ucred *cred)
2357 {
2358 	struct namecache *par_tmp;
2359 	struct namecache *par;
2360 	struct namecache *ncp;
2361 	struct nchandle nctmp;
2362 	struct mount *mp;
2363 	struct vnode *dvp;
2364 	int error;
2365 
2366 	ncp = nch->ncp;
2367 	mp = nch->mount;
2368 restart:
2369 	/*
2370 	 * If the ncp is already resolved we have nothing to do.  However,
2371 	 * we do want to guarentee that a usable vnode is returned when
2372 	 * a vnode is present, so make sure it hasn't been reclaimed.
2373 	 */
2374 	if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
2375 		if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
2376 			_cache_setunresolved(ncp);
2377 		if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
2378 			return (ncp->nc_error);
2379 	}
2380 
2381 	/*
2382 	 * Mount points need special handling because the parent does not
2383 	 * belong to the same filesystem as the ncp.
2384 	 */
2385 	if (ncp == mp->mnt_ncmountpt.ncp)
2386 		return (cache_resolve_mp(mp));
2387 
2388 	/*
2389 	 * We expect an unbroken chain of ncps to at least the mount point,
2390 	 * and even all the way to root (but this code doesn't have to go
2391 	 * past the mount point).
2392 	 */
2393 	if (ncp->nc_parent == NULL) {
2394 		kprintf("EXDEV case 1 %p %*.*s\n", ncp,
2395 			ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
2396 		ncp->nc_error = EXDEV;
2397 		return(ncp->nc_error);
2398 	}
2399 
2400 	/*
2401 	 * The vp's of the parent directories in the chain are held via vhold()
2402 	 * due to the existance of the child, and should not disappear.
2403 	 * However, there are cases where they can disappear:
2404 	 *
2405 	 *	- due to filesystem I/O errors.
2406 	 *	- due to NFS being stupid about tracking the namespace and
2407 	 *	  destroys the namespace for entire directories quite often.
2408 	 *	- due to forced unmounts.
2409 	 *	- due to an rmdir (parent will be marked DESTROYED)
2410 	 *
2411 	 * When this occurs we have to track the chain backwards and resolve
2412 	 * it, looping until the resolver catches up to the current node.  We
2413 	 * could recurse here but we might run ourselves out of kernel stack
2414 	 * so we do it in a more painful manner.  This situation really should
2415 	 * not occur all that often, or if it does not have to go back too
2416 	 * many nodes to resolve the ncp.
2417 	 */
2418 	while ((dvp = cache_dvpref(ncp)) == NULL) {
2419 		/*
2420 		 * This case can occur if a process is CD'd into a
2421 		 * directory which is then rmdir'd.  If the parent is marked
2422 		 * destroyed there is no point trying to resolve it.
2423 		 */
2424 		if (ncp->nc_parent->nc_flag & NCF_DESTROYED)
2425 			return(ENOENT);
2426 		par = ncp->nc_parent;
2427 		_cache_hold(par);
2428 		_cache_lock(par);
2429 		while ((par_tmp = par->nc_parent) != NULL &&
2430 		       par_tmp->nc_vp == NULL) {
2431 			_cache_hold(par_tmp);
2432 			_cache_lock(par_tmp);
2433 			_cache_put(par);
2434 			par = par_tmp;
2435 		}
2436 		if (par->nc_parent == NULL) {
2437 			kprintf("EXDEV case 2 %*.*s\n",
2438 				par->nc_nlen, par->nc_nlen, par->nc_name);
2439 			_cache_put(par);
2440 			return (EXDEV);
2441 		}
2442 		kprintf("[diagnostic] cache_resolve: had to recurse on %*.*s\n",
2443 			par->nc_nlen, par->nc_nlen, par->nc_name);
2444 		/*
2445 		 * The parent is not set in stone, ref and lock it to prevent
2446 		 * it from disappearing.  Also note that due to renames it
2447 		 * is possible for our ncp to move and for par to no longer
2448 		 * be one of its parents.  We resolve it anyway, the loop
2449 		 * will handle any moves.
2450 		 */
2451 		_cache_get(par);	/* additional hold/lock */
2452 		_cache_put(par);	/* from earlier hold/lock */
2453 		if (par == nch->mount->mnt_ncmountpt.ncp) {
2454 			cache_resolve_mp(nch->mount);
2455 		} else if ((dvp = cache_dvpref(par)) == NULL) {
2456 			kprintf("[diagnostic] cache_resolve: raced on %*.*s\n", par->nc_nlen, par->nc_nlen, par->nc_name);
2457 			_cache_put(par);
2458 			continue;
2459 		} else {
2460 			if (par->nc_flag & NCF_UNRESOLVED) {
2461 				nctmp.mount = mp;
2462 				nctmp.ncp = par;
2463 				par->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
2464 			}
2465 			vrele(dvp);
2466 		}
2467 		if ((error = par->nc_error) != 0) {
2468 			if (par->nc_error != EAGAIN) {
2469 				kprintf("EXDEV case 3 %*.*s error %d\n",
2470 				    par->nc_nlen, par->nc_nlen, par->nc_name,
2471 				    par->nc_error);
2472 				_cache_put(par);
2473 				return(error);
2474 			}
2475 			kprintf("[diagnostic] cache_resolve: EAGAIN par %p %*.*s\n",
2476 				par, par->nc_nlen, par->nc_nlen, par->nc_name);
2477 		}
2478 		_cache_put(par);
2479 		/* loop */
2480 	}
2481 
2482 	/*
2483 	 * Call VOP_NRESOLVE() to get the vp, then scan for any disconnected
2484 	 * ncp's and reattach them.  If this occurs the original ncp is marked
2485 	 * EAGAIN to force a relookup.
2486 	 *
2487 	 * NOTE: in order to call VOP_NRESOLVE(), the parent of the passed
2488 	 * ncp must already be resolved.
2489 	 */
2490 	if (dvp) {
2491 		nctmp.mount = mp;
2492 		nctmp.ncp = ncp;
2493 		ncp->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
2494 		vrele(dvp);
2495 	} else {
2496 		ncp->nc_error = EPERM;
2497 	}
2498 	if (ncp->nc_error == EAGAIN) {
2499 		kprintf("[diagnostic] cache_resolve: EAGAIN ncp %p %*.*s\n",
2500 			ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
2501 		goto restart;
2502 	}
2503 	return(ncp->nc_error);
2504 }
2505 
2506 /*
2507  * Resolve the ncp associated with a mount point.  Such ncp's almost always
2508  * remain resolved and this routine is rarely called.  NFS MPs tends to force
2509  * re-resolution more often due to its mac-truck-smash-the-namecache
2510  * method of tracking namespace changes.
2511  *
2512  * The semantics for this call is that the passed ncp must be locked on
2513  * entry and will be locked on return.  However, if we actually have to
2514  * resolve the mount point we temporarily unlock the entry in order to
2515  * avoid race-to-root deadlocks due to e.g. dead NFS mounts.  Because of
2516  * the unlock we have to recheck the flags after we relock.
2517  */
2518 static int
2519 cache_resolve_mp(struct mount *mp)
2520 {
2521 	struct namecache *ncp = mp->mnt_ncmountpt.ncp;
2522 	struct vnode *vp;
2523 	int error;
2524 
2525 	KKASSERT(mp != NULL);
2526 
2527 	/*
2528 	 * If the ncp is already resolved we have nothing to do.  However,
2529 	 * we do want to guarentee that a usable vnode is returned when
2530 	 * a vnode is present, so make sure it hasn't been reclaimed.
2531 	 */
2532 	if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
2533 		if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
2534 			_cache_setunresolved(ncp);
2535 	}
2536 
2537 	if (ncp->nc_flag & NCF_UNRESOLVED) {
2538 		_cache_unlock(ncp);
2539 		while (vfs_busy(mp, 0))
2540 			;
2541 		error = VFS_ROOT(mp, &vp);
2542 		_cache_lock(ncp);
2543 
2544 		/*
2545 		 * recheck the ncp state after relocking.
2546 		 */
2547 		if (ncp->nc_flag & NCF_UNRESOLVED) {
2548 			ncp->nc_error = error;
2549 			if (error == 0) {
2550 				_cache_setvp(mp, ncp, vp);
2551 				vput(vp);
2552 			} else {
2553 				kprintf("[diagnostic] cache_resolve_mp: failed"
2554 					" to resolve mount %p err=%d ncp=%p\n",
2555 					mp, error, ncp);
2556 				_cache_setvp(mp, ncp, NULL);
2557 			}
2558 		} else if (error == 0) {
2559 			vput(vp);
2560 		}
2561 		vfs_unbusy(mp);
2562 	}
2563 	return(ncp->nc_error);
2564 }
2565 
2566 /*
2567  * Clean out negative cache entries when too many have accumulated.
2568  *
2569  * MPSAFE
2570  */
2571 static void
2572 _cache_cleanneg(int count)
2573 {
2574 	struct namecache *ncp;
2575 
2576 	/*
2577 	 * Automode from the vnlru proc - clean out 10% of the negative cache
2578 	 * entries.
2579 	 */
2580 	if (count == 0)
2581 		count = numneg / 10 + 1;
2582 
2583 	/*
2584 	 * Attempt to clean out the specified number of negative cache
2585 	 * entries.
2586 	 */
2587 	while (count) {
2588 		spin_lock_wr(&ncspin);
2589 		ncp = TAILQ_FIRST(&ncneglist);
2590 		if (ncp == NULL) {
2591 			spin_unlock_wr(&ncspin);
2592 			break;
2593 		}
2594 		TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
2595 		TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
2596 		_cache_hold(ncp);
2597 		spin_unlock_wr(&ncspin);
2598 		if (_cache_lock_special(ncp) == 0) {
2599 			ncp = cache_zap(ncp, 0);
2600 			if (ncp)
2601 				_cache_drop(ncp);
2602 		} else {
2603 			_cache_drop(ncp);
2604 		}
2605 		--count;
2606 	}
2607 }
2608 
2609 /*
2610  * This is a kitchen sink function to clean out ncps which we
2611  * tried to zap from cache_drop() but failed because we were
2612  * unable to acquire the parent lock.
2613  *
2614  * Such entries can also be removed via cache_inval_vp(), such
2615  * as when unmounting.
2616  *
2617  * MPSAFE
2618  */
2619 static void
2620 _cache_cleandefered(void)
2621 {
2622 	struct nchash_head *nchpp;
2623 	struct namecache *ncp;
2624 	struct namecache dummy;
2625 	int i;
2626 
2627 	bzero(&dummy, sizeof(dummy));
2628 	dummy.nc_flag = NCF_DESTROYED;
2629 
2630 	for (i = 0; i <= nchash; ++i) {
2631 		nchpp = &nchashtbl[i];
2632 
2633 		spin_lock_wr(&nchpp->spin);
2634 		LIST_INSERT_HEAD(&nchpp->list, &dummy, nc_hash);
2635 		ncp = &dummy;
2636 		while ((ncp = LIST_NEXT(ncp, nc_hash)) != NULL) {
2637 			if ((ncp->nc_flag & NCF_DEFEREDZAP) == 0)
2638 				continue;
2639 			LIST_REMOVE(&dummy, nc_hash);
2640 			LIST_INSERT_AFTER(ncp, &dummy, nc_hash);
2641 			_cache_hold(ncp);
2642 			spin_unlock_wr(&nchpp->spin);
2643 			_cache_drop(ncp);
2644 			spin_lock_wr(&nchpp->spin);
2645 			ncp = &dummy;
2646 		}
2647 		LIST_REMOVE(&dummy, nc_hash);
2648 		spin_unlock_wr(&nchpp->spin);
2649 	}
2650 }
2651 
2652 /*
2653  * Name cache initialization, from vfsinit() when we are booting
2654  */
2655 void
2656 nchinit(void)
2657 {
2658 	int i;
2659 	globaldata_t gd;
2660 
2661 	/* initialise per-cpu namecache effectiveness statistics. */
2662 	for (i = 0; i < ncpus; ++i) {
2663 		gd = globaldata_find(i);
2664 		gd->gd_nchstats = &nchstats[i];
2665 	}
2666 	TAILQ_INIT(&ncneglist);
2667 	spin_init(&ncspin);
2668 	nchashtbl = hashinit_ext(desiredvnodes*2, sizeof(struct nchash_head),
2669 				 M_VFSCACHE, &nchash);
2670 	for (i = 0; i <= (int)nchash; ++i) {
2671 		LIST_INIT(&nchashtbl[i].list);
2672 		spin_init(&nchashtbl[i].spin);
2673 	}
2674 	nclockwarn = 5 * hz;
2675 }
2676 
2677 /*
2678  * Called from start_init() to bootstrap the root filesystem.  Returns
2679  * a referenced, unlocked namecache record.
2680  */
2681 void
2682 cache_allocroot(struct nchandle *nch, struct mount *mp, struct vnode *vp)
2683 {
2684 	nch->ncp = cache_alloc(0);
2685 	nch->mount = mp;
2686 	atomic_add_int(&mp->mnt_refs, 1);
2687 	if (vp)
2688 		_cache_setvp(nch->mount, nch->ncp, vp);
2689 }
2690 
2691 /*
2692  * vfs_cache_setroot()
2693  *
2694  *	Create an association between the root of our namecache and
2695  *	the root vnode.  This routine may be called several times during
2696  *	booting.
2697  *
2698  *	If the caller intends to save the returned namecache pointer somewhere
2699  *	it must cache_hold() it.
2700  */
2701 void
2702 vfs_cache_setroot(struct vnode *nvp, struct nchandle *nch)
2703 {
2704 	struct vnode *ovp;
2705 	struct nchandle onch;
2706 
2707 	ovp = rootvnode;
2708 	onch = rootnch;
2709 	rootvnode = nvp;
2710 	if (nch)
2711 		rootnch = *nch;
2712 	else
2713 		cache_zero(&rootnch);
2714 	if (ovp)
2715 		vrele(ovp);
2716 	if (onch.ncp)
2717 		cache_drop(&onch);
2718 }
2719 
2720 /*
2721  * XXX OLD API COMPAT FUNCTION.  This really messes up the new namecache
2722  * topology and is being removed as quickly as possible.  The new VOP_N*()
2723  * API calls are required to make specific adjustments using the supplied
2724  * ncp pointers rather then just bogusly purging random vnodes.
2725  *
2726  * Invalidate all namecache entries to a particular vnode as well as
2727  * any direct children of that vnode in the namecache.  This is a
2728  * 'catch all' purge used by filesystems that do not know any better.
2729  *
2730  * Note that the linkage between the vnode and its namecache entries will
2731  * be removed, but the namecache entries themselves might stay put due to
2732  * active references from elsewhere in the system or due to the existance of
2733  * the children.   The namecache topology is left intact even if we do not
2734  * know what the vnode association is.  Such entries will be marked
2735  * NCF_UNRESOLVED.
2736  */
2737 void
2738 cache_purge(struct vnode *vp)
2739 {
2740 	cache_inval_vp(vp, CINV_DESTROY | CINV_CHILDREN);
2741 }
2742 
2743 /*
2744  * Flush all entries referencing a particular filesystem.
2745  *
2746  * Since we need to check it anyway, we will flush all the invalid
2747  * entries at the same time.
2748  */
2749 #if 0
2750 
2751 void
2752 cache_purgevfs(struct mount *mp)
2753 {
2754 	struct nchash_head *nchpp;
2755 	struct namecache *ncp, *nnp;
2756 
2757 	/*
2758 	 * Scan hash tables for applicable entries.
2759 	 */
2760 	for (nchpp = &nchashtbl[nchash]; nchpp >= nchashtbl; nchpp--) {
2761 		spin_lock_wr(&nchpp->spin); XXX
2762 		ncp = LIST_FIRST(&nchpp->list);
2763 		if (ncp)
2764 			_cache_hold(ncp);
2765 		while (ncp) {
2766 			nnp = LIST_NEXT(ncp, nc_hash);
2767 			if (nnp)
2768 				_cache_hold(nnp);
2769 			if (ncp->nc_mount == mp) {
2770 				_cache_lock(ncp);
2771 				ncp = cache_zap(ncp, 0);
2772 				if (ncp)
2773 					_cache_drop(ncp);
2774 			} else {
2775 				_cache_drop(ncp);
2776 			}
2777 			ncp = nnp;
2778 		}
2779 		spin_unlock_wr(&nchpp->spin); XXX
2780 	}
2781 }
2782 
2783 #endif
2784 
2785 static int disablecwd;
2786 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0, "");
2787 
2788 static u_long numcwdcalls; STATNODE(CTLFLAG_RD, numcwdcalls, &numcwdcalls);
2789 static u_long numcwdfail1; STATNODE(CTLFLAG_RD, numcwdfail1, &numcwdfail1);
2790 static u_long numcwdfail2; STATNODE(CTLFLAG_RD, numcwdfail2, &numcwdfail2);
2791 static u_long numcwdfail3; STATNODE(CTLFLAG_RD, numcwdfail3, &numcwdfail3);
2792 static u_long numcwdfail4; STATNODE(CTLFLAG_RD, numcwdfail4, &numcwdfail4);
2793 static u_long numcwdfound; STATNODE(CTLFLAG_RD, numcwdfound, &numcwdfound);
2794 
2795 /*
2796  * MPALMOSTSAFE
2797  */
2798 int
2799 sys___getcwd(struct __getcwd_args *uap)
2800 {
2801 	int buflen;
2802 	int error;
2803 	char *buf;
2804 	char *bp;
2805 
2806 	if (disablecwd)
2807 		return (ENODEV);
2808 
2809 	buflen = uap->buflen;
2810 	if (buflen == 0)
2811 		return (EINVAL);
2812 	if (buflen > MAXPATHLEN)
2813 		buflen = MAXPATHLEN;
2814 
2815 	buf = kmalloc(buflen, M_TEMP, M_WAITOK);
2816 	get_mplock();
2817 	bp = kern_getcwd(buf, buflen, &error);
2818 	rel_mplock();
2819 	if (error == 0)
2820 		error = copyout(bp, uap->buf, strlen(bp) + 1);
2821 	kfree(buf, M_TEMP);
2822 	return (error);
2823 }
2824 
2825 char *
2826 kern_getcwd(char *buf, size_t buflen, int *error)
2827 {
2828 	struct proc *p = curproc;
2829 	char *bp;
2830 	int i, slash_prefixed;
2831 	struct filedesc *fdp;
2832 	struct nchandle nch;
2833 	struct namecache *ncp;
2834 
2835 	numcwdcalls++;
2836 	bp = buf;
2837 	bp += buflen - 1;
2838 	*bp = '\0';
2839 	fdp = p->p_fd;
2840 	slash_prefixed = 0;
2841 
2842 	nch = fdp->fd_ncdir;
2843 	ncp = nch.ncp;
2844 	if (ncp)
2845 		_cache_hold(ncp);
2846 
2847 	while (ncp && (ncp != fdp->fd_nrdir.ncp ||
2848 	       nch.mount != fdp->fd_nrdir.mount)
2849 	) {
2850 		/*
2851 		 * While traversing upwards if we encounter the root
2852 		 * of the current mount we have to skip to the mount point
2853 		 * in the underlying filesystem.
2854 		 */
2855 		if (ncp == nch.mount->mnt_ncmountpt.ncp) {
2856 			nch = nch.mount->mnt_ncmounton;
2857 			_cache_drop(ncp);
2858 			ncp = nch.ncp;
2859 			if (ncp)
2860 				_cache_hold(ncp);
2861 			continue;
2862 		}
2863 
2864 		/*
2865 		 * Prepend the path segment
2866 		 */
2867 		for (i = ncp->nc_nlen - 1; i >= 0; i--) {
2868 			if (bp == buf) {
2869 				numcwdfail4++;
2870 				*error = ERANGE;
2871 				bp = NULL;
2872 				goto done;
2873 			}
2874 			*--bp = ncp->nc_name[i];
2875 		}
2876 		if (bp == buf) {
2877 			numcwdfail4++;
2878 			*error = ERANGE;
2879 			bp = NULL;
2880 			goto done;
2881 		}
2882 		*--bp = '/';
2883 		slash_prefixed = 1;
2884 
2885 		/*
2886 		 * Go up a directory.  This isn't a mount point so we don't
2887 		 * have to check again.
2888 		 */
2889 		while ((nch.ncp = ncp->nc_parent) != NULL) {
2890 			_cache_lock(ncp);
2891 			if (nch.ncp != ncp->nc_parent) {
2892 				_cache_unlock(ncp);
2893 				continue;
2894 			}
2895 			_cache_hold(nch.ncp);
2896 			_cache_unlock(ncp);
2897 			break;
2898 		}
2899 		_cache_drop(ncp);
2900 		ncp = nch.ncp;
2901 	}
2902 	if (ncp == NULL) {
2903 		numcwdfail2++;
2904 		*error = ENOENT;
2905 		bp = NULL;
2906 		goto done;
2907 	}
2908 	if (!slash_prefixed) {
2909 		if (bp == buf) {
2910 			numcwdfail4++;
2911 			*error = ERANGE;
2912 			bp = NULL;
2913 			goto done;
2914 		}
2915 		*--bp = '/';
2916 	}
2917 	numcwdfound++;
2918 	*error = 0;
2919 done:
2920 	if (ncp)
2921 		_cache_drop(ncp);
2922 	return (bp);
2923 }
2924 
2925 /*
2926  * Thus begins the fullpath magic.
2927  *
2928  * The passed nchp is referenced but not locked.
2929  */
2930 #undef STATNODE
2931 #define STATNODE(name)							\
2932 	static u_int name;						\
2933 	SYSCTL_UINT(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, "")
2934 
2935 static int disablefullpath;
2936 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW,
2937     &disablefullpath, 0, "");
2938 
2939 STATNODE(numfullpathcalls);
2940 STATNODE(numfullpathfail1);
2941 STATNODE(numfullpathfail2);
2942 STATNODE(numfullpathfail3);
2943 STATNODE(numfullpathfail4);
2944 STATNODE(numfullpathfound);
2945 
2946 int
2947 cache_fullpath(struct proc *p, struct nchandle *nchp,
2948 	       char **retbuf, char **freebuf)
2949 {
2950 	struct nchandle fd_nrdir;
2951 	struct nchandle nch;
2952 	struct namecache *ncp;
2953 	struct mount *mp;
2954 	char *bp, *buf;
2955 	int slash_prefixed;
2956 	int error = 0;
2957 	int i;
2958 
2959 	atomic_add_int(&numfullpathcalls, -1);
2960 
2961 	*retbuf = NULL;
2962 	*freebuf = NULL;
2963 
2964 	buf = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
2965 	bp = buf + MAXPATHLEN - 1;
2966 	*bp = '\0';
2967 	if (p != NULL)
2968 		fd_nrdir = p->p_fd->fd_nrdir;
2969 	else
2970 		fd_nrdir = rootnch;
2971 	slash_prefixed = 0;
2972 	nch = *nchp;
2973 	ncp = nch.ncp;
2974 	if (ncp)
2975 		_cache_hold(ncp);
2976 	mp = nch.mount;
2977 
2978 	while (ncp && (ncp != fd_nrdir.ncp || mp != fd_nrdir.mount)) {
2979 		/*
2980 		 * While traversing upwards if we encounter the root
2981 		 * of the current mount we have to skip to the mount point.
2982 		 */
2983 		if (ncp == mp->mnt_ncmountpt.ncp) {
2984 			nch = mp->mnt_ncmounton;
2985 			_cache_drop(ncp);
2986 			ncp = nch.ncp;
2987 			if (ncp)
2988 				_cache_hold(ncp);
2989 			mp = nch.mount;
2990 			continue;
2991 		}
2992 
2993 		/*
2994 		 * Prepend the path segment
2995 		 */
2996 		for (i = ncp->nc_nlen - 1; i >= 0; i--) {
2997 			if (bp == buf) {
2998 				numfullpathfail4++;
2999 				kfree(buf, M_TEMP);
3000 				error = ENOMEM;
3001 				goto done;
3002 			}
3003 			*--bp = ncp->nc_name[i];
3004 		}
3005 		if (bp == buf) {
3006 			numfullpathfail4++;
3007 			kfree(buf, M_TEMP);
3008 			error = ENOMEM;
3009 			goto done;
3010 		}
3011 		*--bp = '/';
3012 		slash_prefixed = 1;
3013 
3014 		/*
3015 		 * Go up a directory.  This isn't a mount point so we don't
3016 		 * have to check again.
3017 		 *
3018 		 * We can only safely access nc_parent with ncp held locked.
3019 		 */
3020 		while ((nch.ncp = ncp->nc_parent) != NULL) {
3021 			_cache_lock(ncp);
3022 			if (nch.ncp != ncp->nc_parent) {
3023 				_cache_unlock(ncp);
3024 				continue;
3025 			}
3026 			_cache_hold(nch.ncp);
3027 			_cache_unlock(ncp);
3028 			break;
3029 		}
3030 		_cache_drop(ncp);
3031 		ncp = nch.ncp;
3032 	}
3033 	if (ncp == NULL) {
3034 		numfullpathfail2++;
3035 		kfree(buf, M_TEMP);
3036 		error = ENOENT;
3037 		goto done;
3038 	}
3039 
3040 	if (!slash_prefixed) {
3041 		if (bp == buf) {
3042 			numfullpathfail4++;
3043 			kfree(buf, M_TEMP);
3044 			error = ENOMEM;
3045 			goto done;
3046 		}
3047 		*--bp = '/';
3048 	}
3049 	numfullpathfound++;
3050 	*retbuf = bp;
3051 	*freebuf = buf;
3052 	error = 0;
3053 done:
3054 	if (ncp)
3055 		_cache_drop(ncp);
3056 	return(error);
3057 }
3058 
3059 int
3060 vn_fullpath(struct proc *p, struct vnode *vn, char **retbuf, char **freebuf)
3061 {
3062 	struct namecache *ncp;
3063 	struct nchandle nch;
3064 	int error;
3065 
3066 	atomic_add_int(&numfullpathcalls, 1);
3067 	if (disablefullpath)
3068 		return (ENODEV);
3069 
3070 	if (p == NULL)
3071 		return (EINVAL);
3072 
3073 	/* vn is NULL, client wants us to use p->p_textvp */
3074 	if (vn == NULL) {
3075 		if ((vn = p->p_textvp) == NULL)
3076 			return (EINVAL);
3077 	}
3078 	spin_lock_wr(&vn->v_spinlock);
3079 	TAILQ_FOREACH(ncp, &vn->v_namecache, nc_vnode) {
3080 		if (ncp->nc_nlen)
3081 			break;
3082 	}
3083 	if (ncp == NULL) {
3084 		spin_unlock_wr(&vn->v_spinlock);
3085 		return (EINVAL);
3086 	}
3087 	_cache_hold(ncp);
3088 	spin_unlock_wr(&vn->v_spinlock);
3089 
3090 	atomic_add_int(&numfullpathcalls, -1);
3091 	nch.ncp = ncp;;
3092 	nch.mount = vn->v_mount;
3093 	error = cache_fullpath(p, &nch, retbuf, freebuf);
3094 	_cache_drop(ncp);
3095 	return (error);
3096 }
3097