xref: /dflybsd-src/sys/kern/vfs_cache.c (revision 872a09d51adf63b4bdae6adb1d96a53f76e161e2)
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. Neither the name of the University nor the names of its contributors
49  *    may be used to endorse or promote products derived from this software
50  *    without specific prior written permission.
51  *
52  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62  * SUCH DAMAGE.
63  */
64 
65 #include <sys/param.h>
66 #include <sys/systm.h>
67 #include <sys/uio.h>
68 #include <sys/kernel.h>
69 #include <sys/sysctl.h>
70 #include <sys/mount.h>
71 #include <sys/vnode.h>
72 #include <sys/malloc.h>
73 #include <sys/sysproto.h>
74 #include <sys/spinlock.h>
75 #include <sys/proc.h>
76 #include <sys/namei.h>
77 #include <sys/nlookup.h>
78 #include <sys/filedesc.h>
79 #include <sys/fnv_hash.h>
80 #include <sys/globaldata.h>
81 #include <sys/kern_syscall.h>
82 #include <sys/dirent.h>
83 #include <ddb/ddb.h>
84 
85 #include <sys/spinlock2.h>
86 
87 #define MAX_RECURSION_DEPTH	64
88 
89 /*
90  * Random lookups in the cache are accomplished with a hash table using
91  * a hash key of (nc_src_vp, name).  Each hash chain has its own spin lock.
92  *
93  * Negative entries may exist and correspond to resolved namecache
94  * structures where nc_vp is NULL.  In a negative entry, NCF_WHITEOUT
95  * will be set if the entry corresponds to a whited-out directory entry
96  * (verses simply not finding the entry at all).   pcpu_ncache[n].neg_list
97  * is locked via pcpu_ncache[n].neg_spin;
98  *
99  * MPSAFE RULES:
100  *
101  * (1) A ncp must be referenced before it can be locked.
102  *
103  * (2) A ncp must be locked in order to modify it.
104  *
105  * (3) ncp locks are always ordered child -> parent.  That may seem
106  *     backwards but forward scans use the hash table and thus can hold
107  *     the parent unlocked when traversing downward.
108  *
109  *     This allows insert/rename/delete/dot-dot and other operations
110  *     to use ncp->nc_parent links.
111  *
112  *     This also prevents a locked up e.g. NFS node from creating a
113  *     chain reaction all the way back to the root vnode / namecache.
114  *
115  * (4) parent linkages require both the parent and child to be locked.
116  */
117 
118 /*
119  * Structures associated with name cacheing.
120  */
121 #define NCHHASH(hash)		(&nchashtbl[(hash) & nchash])
122 #define MINNEG			1024
123 #define MINPOS			1024
124 #define NCMOUNT_NUMCACHE	32768	/* power of 2 */
125 
126 MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
127 
128 TAILQ_HEAD(nchash_list, namecache);
129 
130 /*
131  * Don't cachealign, but at least pad to 32 bytes so entries
132  * don't cross a cache line.
133  */
134 struct nchash_head {
135        struct nchash_list list;	/* 16 bytes */
136        struct spinlock	spin;	/* 8 bytes */
137        long	pad01;		/* 8 bytes */
138 };
139 
140 struct ncmount_cache {
141 	struct spinlock	spin;
142 	struct namecache *ncp;
143 	struct mount *mp;
144 	int isneg;		/* if != 0 mp is originator and not target */
145 	int ticks;
146 } __cachealign;
147 
148 struct pcpu_ncache {
149 	struct spinlock		neg_spin;	/* for neg_list and neg_count */
150 	struct namecache_list	neg_list;
151 	long			neg_count;
152 	long			vfscache_negs;
153 	long			vfscache_count;
154 	long			vfscache_leafs;
155 	long			numdefered;
156 } __cachealign;
157 
158 __read_mostly static struct nchash_head	*nchashtbl;
159 __read_mostly static struct pcpu_ncache	*pcpu_ncache;
160 static struct ncmount_cache	ncmount_cache[NCMOUNT_NUMCACHE];
161 
162 /*
163  * ncvp_debug - debug cache_fromvp().  This is used by the NFS server
164  * to create the namecache infrastructure leading to a dangling vnode.
165  *
166  * 0	Only errors are reported
167  * 1	Successes are reported
168  * 2	Successes + the whole directory scan is reported
169  * 3	Force the directory scan code run as if the parent vnode did not
170  *	have a namecache record, even if it does have one.
171  */
172 __read_mostly static int	ncvp_debug;
173 SYSCTL_INT(_debug, OID_AUTO, ncvp_debug, CTLFLAG_RW, &ncvp_debug, 0,
174     "Namecache debug level (0-3)");
175 
176 __read_mostly static u_long nchash;		/* size of hash table */
177 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
178     "Size of namecache hash table");
179 
180 __read_mostly static int ncnegflush = 10;	/* burst for negative flush */
181 SYSCTL_INT(_debug, OID_AUTO, ncnegflush, CTLFLAG_RW, &ncnegflush, 0,
182     "Batch flush negative entries");
183 
184 __read_mostly static int ncposflush = 10;	/* burst for positive flush */
185 SYSCTL_INT(_debug, OID_AUTO, ncposflush, CTLFLAG_RW, &ncposflush, 0,
186     "Batch flush positive entries");
187 
188 __read_mostly static int ncnegfactor = 16;	/* ratio of negative entries */
189 SYSCTL_INT(_debug, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0,
190     "Ratio of namecache negative entries");
191 
192 __read_mostly static int nclockwarn;	/* warn on locked entries in ticks */
193 SYSCTL_INT(_debug, OID_AUTO, nclockwarn, CTLFLAG_RW, &nclockwarn, 0,
194     "Warn on locked namecache entries in ticks");
195 
196 __read_mostly static int ncposlimit;	/* number of cache entries allocated */
197 SYSCTL_INT(_debug, OID_AUTO, ncposlimit, CTLFLAG_RW, &ncposlimit, 0,
198     "Number of cache entries allocated");
199 
200 __read_mostly static int ncp_shared_lock_disable = 0;
201 SYSCTL_INT(_debug, OID_AUTO, ncp_shared_lock_disable, CTLFLAG_RW,
202 	   &ncp_shared_lock_disable, 0, "Disable shared namecache locks");
203 
204 SYSCTL_INT(_debug, OID_AUTO, vnsize, CTLFLAG_RD, 0, sizeof(struct vnode),
205     "sizeof(struct vnode)");
206 SYSCTL_INT(_debug, OID_AUTO, ncsize, CTLFLAG_RD, 0, sizeof(struct namecache),
207     "sizeof(struct namecache)");
208 
209 __read_mostly static int ncmount_cache_enable = 1;
210 SYSCTL_INT(_debug, OID_AUTO, ncmount_cache_enable, CTLFLAG_RW,
211 	   &ncmount_cache_enable, 0, "mount point cache");
212 
213 static __inline void _cache_drop(struct namecache *ncp);
214 static int cache_resolve_mp(struct mount *mp);
215 static struct vnode *cache_dvpref(struct namecache *ncp);
216 static void _cache_lock(struct namecache *ncp);
217 static void _cache_setunresolved(struct namecache *ncp);
218 static void _cache_cleanneg(long count);
219 static void _cache_cleanpos(long count);
220 static void _cache_cleandefered(void);
221 static void _cache_unlink(struct namecache *ncp);
222 #if 0
223 static void vfscache_rollup_all(void);
224 #endif
225 
226 /*
227  * The new name cache statistics (these are rolled up globals and not
228  * modified in the critical path, see struct pcpu_ncache).
229  */
230 SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0, "Name cache statistics");
231 static long vfscache_negs;
232 SYSCTL_LONG(_vfs_cache, OID_AUTO, numneg, CTLFLAG_RD, &vfscache_negs, 0,
233     "Number of negative namecache entries");
234 static long vfscache_count;
235 SYSCTL_LONG(_vfs_cache, OID_AUTO, numcache, CTLFLAG_RD, &vfscache_count, 0,
236     "Number of namecaches entries");
237 static long vfscache_leafs;
238 SYSCTL_LONG(_vfs_cache, OID_AUTO, numleafs, CTLFLAG_RD, &vfscache_leafs, 0,
239     "Number of namecaches entries");
240 static long	numdefered;
241 SYSCTL_LONG(_debug, OID_AUTO, numdefered, CTLFLAG_RD, &numdefered, 0,
242     "Number of cache entries allocated");
243 
244 
245 struct nchstats nchstats[SMP_MAXCPU];
246 /*
247  * Export VFS cache effectiveness statistics to user-land.
248  *
249  * The statistics are left for aggregation to user-land so
250  * neat things can be achieved, like observing per-CPU cache
251  * distribution.
252  */
253 static int
254 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
255 {
256 	struct globaldata *gd;
257 	int i, error;
258 
259 	error = 0;
260 	for (i = 0; i < ncpus; ++i) {
261 		gd = globaldata_find(i);
262 		if ((error = SYSCTL_OUT(req, (void *)&(*gd->gd_nchstats),
263 			sizeof(struct nchstats))))
264 			break;
265 	}
266 
267 	return (error);
268 }
269 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE|CTLFLAG_RD,
270   0, 0, sysctl_nchstats, "S,nchstats", "VFS cache effectiveness statistics");
271 
272 static struct namecache *cache_zap(struct namecache *ncp, int nonblock);
273 
274 /*
275  * Cache mount points and namecache records in order to avoid unnecessary
276  * atomic ops on mnt_refs and ncp->refs.  This improves concurrent SMP
277  * performance and is particularly important on multi-socket systems to
278  * reduce cache-line ping-ponging.
279  *
280  * Try to keep the pcpu structure within one cache line (~64 bytes).
281  */
282 #define MNTCACHE_COUNT      5
283 
284 struct mntcache {
285 	struct mount	*mntary[MNTCACHE_COUNT];
286 	struct namecache *ncp1;
287 	struct namecache *ncp2;
288 	struct nchandle  ncdir;
289 	int		iter;
290 	int		unused01;
291 } __cachealign;
292 
293 static struct mntcache	pcpu_mntcache[MAXCPU];
294 
295 static
296 void
297 _cache_mntref(struct mount *mp)
298 {
299 	struct mntcache *cache = &pcpu_mntcache[mycpu->gd_cpuid];
300 	int i;
301 
302 	for (i = 0; i < MNTCACHE_COUNT; ++i) {
303 		if (cache->mntary[i] != mp)
304 			continue;
305 		if (atomic_cmpset_ptr((void *)&cache->mntary[i], mp, NULL))
306 			return;
307 	}
308 	atomic_add_int(&mp->mnt_refs, 1);
309 }
310 
311 static
312 void
313 _cache_mntrel(struct mount *mp)
314 {
315 	struct mntcache *cache = &pcpu_mntcache[mycpu->gd_cpuid];
316 	int i;
317 
318 	for (i = 0; i < MNTCACHE_COUNT; ++i) {
319 		if (cache->mntary[i] == NULL) {
320 			mp = atomic_swap_ptr((void *)&cache->mntary[i], mp);
321 			if (mp == NULL)
322 				return;
323 		}
324 	}
325 	i = (int)((uint32_t)++cache->iter % (uint32_t)MNTCACHE_COUNT);
326 	mp = atomic_swap_ptr((void *)&cache->mntary[i], mp);
327 	if (mp)
328 		atomic_add_int(&mp->mnt_refs, -1);
329 }
330 
331 /*
332  * Clears all cached mount points on all cpus.  This routine should only
333  * be called when we are waiting for a mount to clear, e.g. so we can
334  * unmount.
335  */
336 void
337 cache_clearmntcache(void)
338 {
339 	int n;
340 
341 	for (n = 0; n < ncpus; ++n) {
342 		struct mntcache *cache = &pcpu_mntcache[n];
343 		struct namecache *ncp;
344 		struct mount *mp;
345 		int i;
346 
347 		for (i = 0; i < MNTCACHE_COUNT; ++i) {
348 			if (cache->mntary[i]) {
349 				mp = atomic_swap_ptr(
350 					(void *)&cache->mntary[i], NULL);
351 				if (mp)
352 					atomic_add_int(&mp->mnt_refs, -1);
353 			}
354 		}
355 		if (cache->ncp1) {
356 			ncp = atomic_swap_ptr((void *)&cache->ncp1, NULL);
357 			if (ncp)
358 				_cache_drop(ncp);
359 		}
360 		if (cache->ncp2) {
361 			ncp = atomic_swap_ptr((void *)&cache->ncp2, NULL);
362 			if (ncp)
363 				_cache_drop(ncp);
364 		}
365 		if (cache->ncdir.ncp) {
366 			ncp = atomic_swap_ptr((void *)&cache->ncdir.ncp, NULL);
367 			if (ncp)
368 				_cache_drop(ncp);
369 		}
370 		if (cache->ncdir.mount) {
371 			mp = atomic_swap_ptr((void *)&cache->ncdir.mount, NULL);
372 			if (mp)
373 				atomic_add_int(&mp->mnt_refs, -1);
374 		}
375 	}
376 }
377 
378 
379 /*
380  * Namespace locking.  The caller must already hold a reference to the
381  * namecache structure in order to lock/unlock it.  This function prevents
382  * the namespace from being created or destroyed by accessors other then
383  * the lock holder.
384  *
385  * Note that holding a locked namecache structure prevents other threads
386  * from making namespace changes (e.g. deleting or creating), prevents
387  * vnode association state changes by other threads, and prevents the
388  * namecache entry from being resolved or unresolved by other threads.
389  *
390  * An exclusive lock owner has full authority to associate/disassociate
391  * vnodes and resolve/unresolve the locked ncp.
392  *
393  * A shared lock owner only has authority to acquire the underlying vnode,
394  * if any.
395  *
396  * The primary lock field is nc_lockstatus.  nc_locktd is set after the
397  * fact (when locking) or cleared prior to unlocking.
398  *
399  * WARNING!  Holding a locked ncp will prevent a vnode from being destroyed
400  *	     or recycled, but it does NOT help you if the vnode had already
401  *	     initiated a recyclement.  If this is important, use cache_get()
402  *	     rather then cache_lock() (and deal with the differences in the
403  *	     way the refs counter is handled).  Or, alternatively, make an
404  *	     unconditional call to cache_validate() or cache_resolve()
405  *	     after cache_lock() returns.
406  */
407 static
408 void
409 _cache_lock(struct namecache *ncp)
410 {
411 	thread_t td;
412 	int didwarn;
413 	int begticks;
414 	int error;
415 	u_int count;
416 
417 	KKASSERT(ncp->nc_refs != 0);
418 	didwarn = 0;
419 	begticks = 0;
420 	td = curthread;
421 
422 	for (;;) {
423 		count = ncp->nc_lockstatus;
424 		cpu_ccfence();
425 
426 		if ((count & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 0) {
427 			if (atomic_cmpset_int(&ncp->nc_lockstatus,
428 					      count, count + 1)) {
429 				/*
430 				 * The vp associated with a locked ncp must
431 				 * be held to prevent it from being recycled.
432 				 *
433 				 * WARNING!  If VRECLAIMED is set the vnode
434 				 * could already be in the middle of a recycle.
435 				 * Callers must use cache_vref() or
436 				 * cache_vget() on the locked ncp to
437 				 * validate the vp or set the cache entry
438 				 * to unresolved.
439 				 *
440 				 * NOTE! vhold() is allowed if we hold a
441 				 *	 lock on the ncp (which we do).
442 				 */
443 				ncp->nc_locktd = td;
444 				if (ncp->nc_vp)
445 					vhold(ncp->nc_vp);
446 				break;
447 			}
448 			/* cmpset failed */
449 			continue;
450 		}
451 		if (ncp->nc_locktd == td) {
452 			KKASSERT((count & NC_SHLOCK_FLAG) == 0);
453 			if (atomic_cmpset_int(&ncp->nc_lockstatus,
454 					      count, count + 1)) {
455 				break;
456 			}
457 			/* cmpset failed */
458 			continue;
459 		}
460 		tsleep_interlock(&ncp->nc_locktd, 0);
461 		if (atomic_cmpset_int(&ncp->nc_lockstatus, count,
462 				      count | NC_EXLOCK_REQ) == 0) {
463 			/* cmpset failed */
464 			continue;
465 		}
466 		if (begticks == 0)
467 			begticks = ticks;
468 		error = tsleep(&ncp->nc_locktd, PINTERLOCKED,
469 			       "clock", nclockwarn);
470 		if (error == EWOULDBLOCK) {
471 			if (didwarn == 0) {
472 				didwarn = ticks;
473 				kprintf("[diagnostic] cache_lock: "
474 					"%s blocked on %p %08x",
475 					td->td_comm, ncp, count);
476 				kprintf(" \"%*.*s\"\n",
477 					ncp->nc_nlen, ncp->nc_nlen,
478 					ncp->nc_name);
479 			}
480 		}
481 		/* loop */
482 	}
483 	if (didwarn) {
484 		kprintf("[diagnostic] cache_lock: %s unblocked %*.*s after "
485 			"%d secs\n",
486 			td->td_comm,
487 			ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name,
488 			(int)(ticks + (hz / 2) - begticks) / hz);
489 	}
490 }
491 
492 /*
493  * The shared lock works similarly to the exclusive lock except
494  * nc_locktd is left NULL and we need an interlock (VHOLD) to
495  * prevent vhold() races, since the moment our cmpset_int succeeds
496  * another cpu can come in and get its own shared lock.
497  *
498  * A critical section is needed to prevent interruption during the
499  * VHOLD interlock.
500  */
501 static
502 void
503 _cache_lock_shared(struct namecache *ncp)
504 {
505 	int didwarn;
506 	int error;
507 	u_int count;
508 	u_int optreq = NC_EXLOCK_REQ;
509 
510 	KKASSERT(ncp->nc_refs != 0);
511 	didwarn = 0;
512 
513 	for (;;) {
514 		count = ncp->nc_lockstatus;
515 		cpu_ccfence();
516 
517 		if ((count & ~NC_SHLOCK_REQ) == 0) {
518 			crit_enter();
519 			if (atomic_cmpset_int(&ncp->nc_lockstatus,
520 				      count,
521 				      (count + 1) | NC_SHLOCK_FLAG |
522 						    NC_SHLOCK_VHOLD)) {
523 				/*
524 				 * The vp associated with a locked ncp must
525 				 * be held to prevent it from being recycled.
526 				 *
527 				 * WARNING!  If VRECLAIMED is set the vnode
528 				 * could already be in the middle of a recycle.
529 				 * Callers must use cache_vref() or
530 				 * cache_vget() on the locked ncp to
531 				 * validate the vp or set the cache entry
532 				 * to unresolved.
533 				 *
534 				 * NOTE! vhold() is allowed if we hold a
535 				 *	 lock on the ncp (which we do).
536 				 */
537 				if (ncp->nc_vp)
538 					vhold(ncp->nc_vp);
539 				atomic_clear_int(&ncp->nc_lockstatus,
540 						 NC_SHLOCK_VHOLD);
541 				crit_exit();
542 				break;
543 			}
544 			/* cmpset failed */
545 			crit_exit();
546 			continue;
547 		}
548 
549 		/*
550 		 * If already held shared we can just bump the count, but
551 		 * only allow this if nobody is trying to get the lock
552 		 * exclusively.  If we are blocking too long ignore excl
553 		 * requests (which can race/deadlock us).
554 		 *
555 		 * VHOLD is a bit of a hack.  Even though we successfully
556 		 * added another shared ref, the cpu that got the first
557 		 * shared ref might not yet have held the vnode.
558 		 */
559 		if ((count & (optreq|NC_SHLOCK_FLAG)) == NC_SHLOCK_FLAG) {
560 			KKASSERT((count & ~(NC_EXLOCK_REQ |
561 					    NC_SHLOCK_REQ |
562 					    NC_SHLOCK_FLAG)) > 0);
563 			if (atomic_cmpset_int(&ncp->nc_lockstatus,
564 					      count, count + 1)) {
565 				while (ncp->nc_lockstatus & NC_SHLOCK_VHOLD)
566 					cpu_pause();
567 				break;
568 			}
569 			continue;
570 		}
571 		tsleep_interlock(ncp, 0);
572 		if (atomic_cmpset_int(&ncp->nc_lockstatus, count,
573 				      count | NC_SHLOCK_REQ) == 0) {
574 			/* cmpset failed */
575 			continue;
576 		}
577 		error = tsleep(ncp, PINTERLOCKED, "clocksh", nclockwarn);
578 		if (error == EWOULDBLOCK) {
579 			optreq = 0;
580 			if (didwarn == 0) {
581 				didwarn = ticks - nclockwarn;
582 				kprintf("[diagnostic] cache_lock_shared: "
583 					"%s blocked on %p %08x "
584 					"\"%*.*s\"\n",
585 					curthread->td_comm, ncp, count,
586 					ncp->nc_nlen, ncp->nc_nlen,
587 					ncp->nc_name);
588 			}
589 		}
590 		/* loop */
591 	}
592 	if (didwarn) {
593 		kprintf("[diagnostic] cache_lock_shared: "
594 			"%s unblocked %*.*s after %d secs\n",
595 			curthread->td_comm,
596 			ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name,
597 			(int)(ticks - didwarn) / hz);
598 	}
599 }
600 
601 /*
602  * Lock ncp exclusively, return 0 on success.
603  *
604  * NOTE: nc_refs may be zero if the ncp is interlocked by circumstance,
605  *	 such as the case where one of its children is locked.
606  */
607 static
608 int
609 _cache_lock_nonblock(struct namecache *ncp)
610 {
611 	thread_t td;
612 	u_int count;
613 
614 	td = curthread;
615 
616 	for (;;) {
617 		count = ncp->nc_lockstatus;
618 
619 		if ((count & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 0) {
620 			if (atomic_cmpset_int(&ncp->nc_lockstatus,
621 					      count, count + 1)) {
622 				/*
623 				 * The vp associated with a locked ncp must
624 				 * be held to prevent it from being recycled.
625 				 *
626 				 * WARNING!  If VRECLAIMED is set the vnode
627 				 * could already be in the middle of a recycle.
628 				 * Callers must use cache_vref() or
629 				 * cache_vget() on the locked ncp to
630 				 * validate the vp or set the cache entry
631 				 * to unresolved.
632 				 *
633 				 * NOTE! vhold() is allowed if we hold a
634 				 *	 lock on the ncp (which we do).
635 				 */
636 				ncp->nc_locktd = td;
637 				if (ncp->nc_vp)
638 					vhold(ncp->nc_vp);
639 				break;
640 			}
641 			/* cmpset failed */
642 			continue;
643 		}
644 		if (ncp->nc_locktd == td) {
645 			if (atomic_cmpset_int(&ncp->nc_lockstatus,
646 					      count, count + 1)) {
647 				break;
648 			}
649 			/* cmpset failed */
650 			continue;
651 		}
652 		return(EWOULDBLOCK);
653 	}
654 	return(0);
655 }
656 
657 /*
658  * The shared lock works similarly to the exclusive lock except
659  * nc_locktd is left NULL and we need an interlock (VHOLD) to
660  * prevent vhold() races, since the moment our cmpset_int succeeds
661  * another cpu can come in and get its own shared lock.
662  *
663  * A critical section is needed to prevent interruption during the
664  * VHOLD interlock.
665  */
666 static
667 int
668 _cache_lock_shared_nonblock(struct namecache *ncp)
669 {
670 	u_int count;
671 
672 	for (;;) {
673 		count = ncp->nc_lockstatus;
674 
675 		if ((count & ~NC_SHLOCK_REQ) == 0) {
676 			crit_enter();
677 			if (atomic_cmpset_int(&ncp->nc_lockstatus,
678 				      count,
679 				      (count + 1) | NC_SHLOCK_FLAG |
680 						    NC_SHLOCK_VHOLD)) {
681 				/*
682 				 * The vp associated with a locked ncp must
683 				 * be held to prevent it from being recycled.
684 				 *
685 				 * WARNING!  If VRECLAIMED is set the vnode
686 				 * could already be in the middle of a recycle.
687 				 * Callers must use cache_vref() or
688 				 * cache_vget() on the locked ncp to
689 				 * validate the vp or set the cache entry
690 				 * to unresolved.
691 				 *
692 				 * NOTE! vhold() is allowed if we hold a
693 				 *	 lock on the ncp (which we do).
694 				 */
695 				if (ncp->nc_vp)
696 					vhold(ncp->nc_vp);
697 				atomic_clear_int(&ncp->nc_lockstatus,
698 						 NC_SHLOCK_VHOLD);
699 				crit_exit();
700 				break;
701 			}
702 			/* cmpset failed */
703 			crit_exit();
704 			continue;
705 		}
706 
707 		/*
708 		 * If already held shared we can just bump the count, but
709 		 * only allow this if nobody is trying to get the lock
710 		 * exclusively.
711 		 *
712 		 * VHOLD is a bit of a hack.  Even though we successfully
713 		 * added another shared ref, the cpu that got the first
714 		 * shared ref might not yet have held the vnode.
715 		 */
716 		if ((count & (NC_EXLOCK_REQ|NC_SHLOCK_FLAG)) ==
717 		    NC_SHLOCK_FLAG) {
718 			KKASSERT((count & ~(NC_EXLOCK_REQ |
719 					    NC_SHLOCK_REQ |
720 					    NC_SHLOCK_FLAG)) > 0);
721 			if (atomic_cmpset_int(&ncp->nc_lockstatus,
722 					      count, count + 1)) {
723 				while (ncp->nc_lockstatus & NC_SHLOCK_VHOLD)
724 					cpu_pause();
725 				break;
726 			}
727 			continue;
728 		}
729 		return(EWOULDBLOCK);
730 	}
731 	return(0);
732 }
733 
734 /*
735  * Helper function
736  *
737  * NOTE: nc_refs can be 0 (degenerate case during _cache_drop).
738  *
739  *	 nc_locktd must be NULLed out prior to nc_lockstatus getting cleared.
740  */
741 static
742 void
743 _cache_unlock(struct namecache *ncp)
744 {
745 	thread_t td __debugvar = curthread;
746 	u_int count;
747 	u_int ncount;
748 	struct vnode *dropvp;
749 
750 	KKASSERT(ncp->nc_refs >= 0);
751 	KKASSERT((ncp->nc_lockstatus & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) > 0);
752 	KKASSERT((ncp->nc_lockstatus & NC_SHLOCK_FLAG) || ncp->nc_locktd == td);
753 
754 	count = ncp->nc_lockstatus;
755 	cpu_ccfence();
756 
757 	/*
758 	 * Clear nc_locktd prior to the atomic op (excl lock only)
759 	 */
760 	if ((count & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 1)
761 		ncp->nc_locktd = NULL;
762 	dropvp = NULL;
763 
764 	for (;;) {
765 		if ((count &
766 		     ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ|NC_SHLOCK_FLAG)) == 1) {
767 			dropvp = ncp->nc_vp;
768 			if (count & NC_EXLOCK_REQ)
769 				ncount = count & NC_SHLOCK_REQ; /* cnt->0 */
770 			else
771 				ncount = 0;
772 
773 			if (atomic_cmpset_int(&ncp->nc_lockstatus,
774 					      count, ncount)) {
775 				if (count & NC_EXLOCK_REQ)
776 					wakeup(&ncp->nc_locktd);
777 				else if (count & NC_SHLOCK_REQ)
778 					wakeup(ncp);
779 				break;
780 			}
781 			dropvp = NULL;
782 		} else {
783 			KKASSERT((count & NC_SHLOCK_VHOLD) == 0);
784 			KKASSERT((count & ~(NC_EXLOCK_REQ |
785 					    NC_SHLOCK_REQ |
786 					    NC_SHLOCK_FLAG)) > 1);
787 			if (atomic_cmpset_int(&ncp->nc_lockstatus,
788 					      count, count - 1)) {
789 				break;
790 			}
791 		}
792 		count = ncp->nc_lockstatus;
793 		cpu_ccfence();
794 	}
795 
796 	/*
797 	 * Don't actually drop the vp until we successfully clean out
798 	 * the lock, otherwise we may race another shared lock.
799 	 */
800 	if (dropvp)
801 		vdrop(dropvp);
802 }
803 
804 static
805 int
806 _cache_lockstatus(struct namecache *ncp)
807 {
808 	if (ncp->nc_locktd == curthread)
809 		return(LK_EXCLUSIVE);
810 	if (ncp->nc_lockstatus & NC_SHLOCK_FLAG)
811 		return(LK_SHARED);
812 	return(-1);
813 }
814 
815 /*
816  * cache_hold() and cache_drop() prevent the premature deletion of a
817  * namecache entry but do not prevent operations (such as zapping) on
818  * that namecache entry.
819  *
820  * This routine may only be called from outside this source module if
821  * nc_refs is already at least 1.
822  *
823  * This is a rare case where callers are allowed to hold a spinlock,
824  * so we can't ourselves.
825  */
826 static __inline
827 struct namecache *
828 _cache_hold(struct namecache *ncp)
829 {
830 	atomic_add_int(&ncp->nc_refs, 1);
831 	return(ncp);
832 }
833 
834 /*
835  * Drop a cache entry, taking care to deal with races.
836  *
837  * For potential 1->0 transitions we must hold the ncp lock to safely
838  * test its flags.  An unresolved entry with no children must be zapped
839  * to avoid leaks.
840  *
841  * The call to cache_zap() itself will handle all remaining races and
842  * will decrement the ncp's refs regardless.  If we are resolved or
843  * have children nc_refs can safely be dropped to 0 without having to
844  * zap the entry.
845  *
846  * NOTE: cache_zap() will re-check nc_refs and nc_list in a MPSAFE fashion.
847  *
848  * NOTE: cache_zap() may return a non-NULL referenced parent which must
849  *	 be dropped in a loop.
850  */
851 static __inline
852 void
853 _cache_drop(struct namecache *ncp)
854 {
855 	int refs;
856 
857 	while (ncp) {
858 		KKASSERT(ncp->nc_refs > 0);
859 		refs = ncp->nc_refs;
860 
861 		if (refs == 1) {
862 			if (_cache_lock_nonblock(ncp) == 0) {
863 				ncp->nc_flag &= ~NCF_DEFEREDZAP;
864 				if ((ncp->nc_flag & NCF_UNRESOLVED) &&
865 				    TAILQ_EMPTY(&ncp->nc_list)) {
866 					ncp = cache_zap(ncp, 1);
867 					continue;
868 				}
869 				if (atomic_cmpset_int(&ncp->nc_refs, 1, 0)) {
870 					_cache_unlock(ncp);
871 					break;
872 				}
873 				_cache_unlock(ncp);
874 			}
875 		} else {
876 			if (atomic_cmpset_int(&ncp->nc_refs, refs, refs - 1))
877 				break;
878 		}
879 		cpu_pause();
880 	}
881 }
882 
883 /*
884  * Link a new namecache entry to its parent and to the hash table.  Be
885  * careful to avoid races if vhold() blocks in the future.
886  *
887  * Both ncp and par must be referenced and locked.
888  *
889  * NOTE: The hash table spinlock is held during this call, we can't do
890  *	 anything fancy.
891  */
892 static void
893 _cache_link_parent(struct namecache *ncp, struct namecache *par,
894 		   struct nchash_head *nchpp)
895 {
896 	struct pcpu_ncache *pn = &pcpu_ncache[mycpu->gd_cpuid];
897 
898 	KKASSERT(ncp->nc_parent == NULL);
899 	ncp->nc_parent = par;
900 	ncp->nc_head = nchpp;
901 
902 	/*
903 	 * Set inheritance flags.  Note that the parent flags may be
904 	 * stale due to getattr potentially not having been run yet
905 	 * (it gets run during nlookup()'s).
906 	 */
907 	ncp->nc_flag &= ~(NCF_SF_PNOCACHE | NCF_UF_PCACHE);
908 	if (par->nc_flag & (NCF_SF_NOCACHE | NCF_SF_PNOCACHE))
909 		ncp->nc_flag |= NCF_SF_PNOCACHE;
910 	if (par->nc_flag & (NCF_UF_CACHE | NCF_UF_PCACHE))
911 		ncp->nc_flag |= NCF_UF_PCACHE;
912 
913 	/*
914 	 * Add to hash table and parent, adjust accounting
915 	 */
916 	TAILQ_INSERT_HEAD(&nchpp->list, ncp, nc_hash);
917 	atomic_add_long(&pn->vfscache_count, 1);
918 	if (TAILQ_EMPTY(&ncp->nc_list))
919 		atomic_add_long(&pn->vfscache_leafs, 1);
920 
921 	if (TAILQ_EMPTY(&par->nc_list)) {
922 		TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
923 		atomic_add_long(&pn->vfscache_leafs, -1);
924 		/*
925 		 * Any vp associated with an ncp which has children must
926 		 * be held to prevent it from being recycled.
927 		 */
928 		if (par->nc_vp)
929 			vhold(par->nc_vp);
930 	} else {
931 		TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
932 	}
933 }
934 
935 /*
936  * Remove the parent and hash associations from a namecache structure.
937  * If this is the last child of the parent the cache_drop(par) will
938  * attempt to recursively zap the parent.
939  *
940  * ncp must be locked.  This routine will acquire a temporary lock on
941  * the parent as wlel as the appropriate hash chain.
942  */
943 static void
944 _cache_unlink_parent(struct namecache *ncp)
945 {
946 	struct pcpu_ncache *pn = &pcpu_ncache[mycpu->gd_cpuid];
947 	struct namecache *par;
948 	struct vnode *dropvp;
949 
950 	if ((par = ncp->nc_parent) != NULL) {
951 		KKASSERT(ncp->nc_parent == par);
952 		_cache_hold(par);
953 		_cache_lock(par);
954 		spin_lock(&ncp->nc_head->spin);
955 
956 		/*
957 		 * Remove from hash table and parent, adjust accounting
958 		 */
959 		TAILQ_REMOVE(&ncp->nc_head->list, ncp, nc_hash);
960 		TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
961 		atomic_add_long(&pn->vfscache_count, -1);
962 		if (TAILQ_EMPTY(&ncp->nc_list))
963 			atomic_add_long(&pn->vfscache_leafs, -1);
964 
965 		dropvp = NULL;
966 		if (TAILQ_EMPTY(&par->nc_list)) {
967 			atomic_add_long(&pn->vfscache_leafs, 1);
968 			if (par->nc_vp)
969 				dropvp = par->nc_vp;
970 		}
971 		spin_unlock(&ncp->nc_head->spin);
972 		ncp->nc_parent = NULL;
973 		ncp->nc_head = NULL;
974 		_cache_unlock(par);
975 		_cache_drop(par);
976 
977 		/*
978 		 * We can only safely vdrop with no spinlocks held.
979 		 */
980 		if (dropvp)
981 			vdrop(dropvp);
982 	}
983 }
984 
985 /*
986  * Allocate a new namecache structure.  Most of the code does not require
987  * zero-termination of the string but it makes vop_compat_ncreate() easier.
988  */
989 static struct namecache *
990 cache_alloc(int nlen)
991 {
992 	struct namecache *ncp;
993 
994 	ncp = kmalloc(sizeof(*ncp), M_VFSCACHE, M_WAITOK|M_ZERO);
995 	if (nlen)
996 		ncp->nc_name = kmalloc(nlen + 1, M_VFSCACHE, M_WAITOK);
997 	ncp->nc_nlen = nlen;
998 	ncp->nc_flag = NCF_UNRESOLVED;
999 	ncp->nc_error = ENOTCONN;	/* needs to be resolved */
1000 	ncp->nc_refs = 1;
1001 
1002 	TAILQ_INIT(&ncp->nc_list);
1003 	_cache_lock(ncp);
1004 	return(ncp);
1005 }
1006 
1007 /*
1008  * Can only be called for the case where the ncp has never been
1009  * associated with anything (so no spinlocks are needed).
1010  */
1011 static void
1012 _cache_free(struct namecache *ncp)
1013 {
1014 	KKASSERT(ncp->nc_refs == 1 && ncp->nc_lockstatus == 1);
1015 	if (ncp->nc_name)
1016 		kfree(ncp->nc_name, M_VFSCACHE);
1017 	kfree(ncp, M_VFSCACHE);
1018 }
1019 
1020 /*
1021  * [re]initialize a nchandle.
1022  */
1023 void
1024 cache_zero(struct nchandle *nch)
1025 {
1026 	nch->ncp = NULL;
1027 	nch->mount = NULL;
1028 }
1029 
1030 /*
1031  * Ref and deref a namecache structure.
1032  *
1033  * The caller must specify a stable ncp pointer, typically meaning the
1034  * ncp is already referenced but this can also occur indirectly through
1035  * e.g. holding a lock on a direct child.
1036  *
1037  * WARNING: Caller may hold an unrelated read spinlock, which means we can't
1038  *	    use read spinlocks here.
1039  */
1040 struct nchandle *
1041 cache_hold(struct nchandle *nch)
1042 {
1043 	_cache_hold(nch->ncp);
1044 	_cache_mntref(nch->mount);
1045 	return(nch);
1046 }
1047 
1048 /*
1049  * Create a copy of a namecache handle for an already-referenced
1050  * entry.
1051  */
1052 void
1053 cache_copy(struct nchandle *nch, struct nchandle *target)
1054 {
1055 	struct mntcache *cache = &pcpu_mntcache[mycpu->gd_cpuid];
1056 	struct namecache *ncp;
1057 
1058 	*target = *nch;
1059 	_cache_mntref(target->mount);
1060 	ncp = target->ncp;
1061 	if (ncp) {
1062 		if (ncp == cache->ncp1) {
1063 			if (atomic_cmpset_ptr((void *)&cache->ncp1, ncp, NULL))
1064 				return;
1065 		}
1066 		if (ncp == cache->ncp2) {
1067 			if (atomic_cmpset_ptr((void *)&cache->ncp2, ncp, NULL))
1068 				return;
1069 		}
1070 		_cache_hold(ncp);
1071 	}
1072 }
1073 
1074 /*
1075  * Caller wants to copy the current directory, copy it out from our
1076  * pcpu cache if possible (the entire critical path is just two localized
1077  * cmpset ops).  If the pcpu cache has a snapshot at all it will be a
1078  * valid one, so we don't have to lock p->p_fd even though we are loading
1079  * two fields.
1080  *
1081  * This has a limited effect since nlookup must still ref and shlock the
1082  * vnode to check perms.  We do avoid the per-proc spin-lock though, which
1083  * can aid threaded programs.
1084  */
1085 void
1086 cache_copy_ncdir(struct proc *p, struct nchandle *target)
1087 {
1088 	struct mntcache *cache = &pcpu_mntcache[mycpu->gd_cpuid];
1089 
1090 	*target = p->p_fd->fd_ncdir;
1091 	if (target->ncp == cache->ncdir.ncp &&
1092 	    target->mount == cache->ncdir.mount) {
1093 		if (atomic_cmpset_ptr((void *)&cache->ncdir.ncp,
1094 				      target->ncp, NULL)) {
1095 			if (atomic_cmpset_ptr((void *)&cache->ncdir.mount,
1096 					      target->mount, NULL)) {
1097 				/* CRITICAL PATH */
1098 				return;
1099 			}
1100 			_cache_drop(target->ncp);
1101 		}
1102 	}
1103 	spin_lock_shared(&p->p_fd->fd_spin);
1104 	cache_copy(&p->p_fd->fd_ncdir, target);
1105 	spin_unlock_shared(&p->p_fd->fd_spin);
1106 }
1107 
1108 void
1109 cache_changemount(struct nchandle *nch, struct mount *mp)
1110 {
1111 	_cache_mntref(mp);
1112 	_cache_mntrel(nch->mount);
1113 	nch->mount = mp;
1114 }
1115 
1116 void
1117 cache_drop(struct nchandle *nch)
1118 {
1119 	_cache_mntrel(nch->mount);
1120 	_cache_drop(nch->ncp);
1121 	nch->ncp = NULL;
1122 	nch->mount = NULL;
1123 }
1124 
1125 /*
1126  * Drop the nchandle, but try to cache the ref to avoid global atomic
1127  * ops.  This is typically done on the system root and jail root nchandles.
1128  */
1129 void
1130 cache_drop_and_cache(struct nchandle *nch)
1131 {
1132 	struct mntcache *cache = &pcpu_mntcache[mycpu->gd_cpuid];
1133 	struct namecache *ncp;
1134 
1135 	_cache_mntrel(nch->mount);
1136 	ncp = nch->ncp;
1137 	if (cache->ncp1 == NULL) {
1138 		ncp = atomic_swap_ptr((void *)&cache->ncp1, ncp);
1139 		if (ncp == NULL)
1140 			goto done;
1141 	}
1142 	if (cache->ncp2 == NULL) {
1143 		ncp = atomic_swap_ptr((void *)&cache->ncp2, ncp);
1144 		if (ncp == NULL)
1145 			goto done;
1146 	}
1147 	if (++cache->iter & 1)
1148 		ncp = atomic_swap_ptr((void *)&cache->ncp2, ncp);
1149 	else
1150 		ncp = atomic_swap_ptr((void *)&cache->ncp1, ncp);
1151 	if (ncp)
1152 		_cache_drop(ncp);
1153 done:
1154 	nch->ncp = NULL;
1155 	nch->mount = NULL;
1156 }
1157 
1158 /*
1159  * We are dropping what the caller believes is the current directory,
1160  * unconditionally store it in our pcpu cache.  Anything already in
1161  * the cache will be discarded.
1162  */
1163 void
1164 cache_drop_ncdir(struct nchandle *nch)
1165 {
1166 	struct mntcache *cache = &pcpu_mntcache[mycpu->gd_cpuid];
1167 
1168 	nch->ncp = atomic_swap_ptr((void *)&cache->ncdir.ncp, nch->ncp);
1169 	nch->mount = atomic_swap_ptr((void *)&cache->ncdir.mount, nch->mount);
1170 	if (nch->ncp)
1171 		_cache_drop(nch->ncp);
1172 	if (nch->mount)
1173 		_cache_mntrel(nch->mount);
1174 	nch->ncp = NULL;
1175 	nch->mount = NULL;
1176 }
1177 
1178 int
1179 cache_lockstatus(struct nchandle *nch)
1180 {
1181 	return(_cache_lockstatus(nch->ncp));
1182 }
1183 
1184 void
1185 cache_lock(struct nchandle *nch)
1186 {
1187 	_cache_lock(nch->ncp);
1188 }
1189 
1190 void
1191 cache_lock_maybe_shared(struct nchandle *nch, int excl)
1192 {
1193 	struct namecache *ncp = nch->ncp;
1194 
1195 	if (ncp_shared_lock_disable || excl ||
1196 	    (ncp->nc_flag & NCF_UNRESOLVED)) {
1197 		_cache_lock(ncp);
1198 	} else {
1199 		_cache_lock_shared(ncp);
1200 		if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1201 			if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED)) {
1202 				_cache_unlock(ncp);
1203 				_cache_lock(ncp);
1204 			}
1205 		} else {
1206 			_cache_unlock(ncp);
1207 			_cache_lock(ncp);
1208 		}
1209 	}
1210 }
1211 
1212 /*
1213  * Relock nch1 given an unlocked nch1 and a locked nch2.  The caller
1214  * is responsible for checking both for validity on return as they
1215  * may have become invalid.
1216  *
1217  * We have to deal with potential deadlocks here, just ping pong
1218  * the lock until we get it (we will always block somewhere when
1219  * looping so this is not cpu-intensive).
1220  *
1221  * which = 0	nch1 not locked, nch2 is locked
1222  * which = 1	nch1 is locked, nch2 is not locked
1223  */
1224 void
1225 cache_relock(struct nchandle *nch1, struct ucred *cred1,
1226 	     struct nchandle *nch2, struct ucred *cred2)
1227 {
1228 	int which;
1229 
1230 	which = 0;
1231 
1232 	for (;;) {
1233 		if (which == 0) {
1234 			if (cache_lock_nonblock(nch1) == 0) {
1235 				cache_resolve(nch1, cred1);
1236 				break;
1237 			}
1238 			cache_unlock(nch2);
1239 			cache_lock(nch1);
1240 			cache_resolve(nch1, cred1);
1241 			which = 1;
1242 		} else {
1243 			if (cache_lock_nonblock(nch2) == 0) {
1244 				cache_resolve(nch2, cred2);
1245 				break;
1246 			}
1247 			cache_unlock(nch1);
1248 			cache_lock(nch2);
1249 			cache_resolve(nch2, cred2);
1250 			which = 0;
1251 		}
1252 	}
1253 }
1254 
1255 int
1256 cache_lock_nonblock(struct nchandle *nch)
1257 {
1258 	return(_cache_lock_nonblock(nch->ncp));
1259 }
1260 
1261 void
1262 cache_unlock(struct nchandle *nch)
1263 {
1264 	_cache_unlock(nch->ncp);
1265 }
1266 
1267 /*
1268  * ref-and-lock, unlock-and-deref functions.
1269  *
1270  * This function is primarily used by nlookup.  Even though cache_lock
1271  * holds the vnode, it is possible that the vnode may have already
1272  * initiated a recyclement.
1273  *
1274  * We want cache_get() to return a definitively usable vnode or a
1275  * definitively unresolved ncp.
1276  */
1277 static
1278 struct namecache *
1279 _cache_get(struct namecache *ncp)
1280 {
1281 	_cache_hold(ncp);
1282 	_cache_lock(ncp);
1283 	if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
1284 		_cache_setunresolved(ncp);
1285 	return(ncp);
1286 }
1287 
1288 /*
1289  * Attempt to obtain a shared lock on the ncp.  A shared lock will only
1290  * be obtained if the ncp is resolved and the vnode (if not ENOENT) is
1291  * valid.  Otherwise an exclusive lock will be acquired instead.
1292  */
1293 static
1294 struct namecache *
1295 _cache_get_maybe_shared(struct namecache *ncp, int excl)
1296 {
1297 	if (ncp_shared_lock_disable || excl ||
1298 	    (ncp->nc_flag & NCF_UNRESOLVED)) {
1299 		return(_cache_get(ncp));
1300 	}
1301 	_cache_hold(ncp);
1302 	_cache_lock_shared(ncp);
1303 	if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1304 		if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED)) {
1305 			_cache_unlock(ncp);
1306 			ncp = _cache_get(ncp);
1307 			_cache_drop(ncp);
1308 		}
1309 	} else {
1310 		_cache_unlock(ncp);
1311 		ncp = _cache_get(ncp);
1312 		_cache_drop(ncp);
1313 	}
1314 	return(ncp);
1315 }
1316 
1317 /*
1318  * This is a special form of _cache_lock() which only succeeds if
1319  * it can get a pristine, non-recursive lock.  The caller must have
1320  * already ref'd the ncp.
1321  *
1322  * On success the ncp will be locked, on failure it will not.  The
1323  * ref count does not change either way.
1324  *
1325  * We want _cache_lock_special() (on success) to return a definitively
1326  * usable vnode or a definitively unresolved ncp.
1327  */
1328 static int
1329 _cache_lock_special(struct namecache *ncp)
1330 {
1331 	if (_cache_lock_nonblock(ncp) == 0) {
1332 		if ((ncp->nc_lockstatus &
1333 		     ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ)) == 1) {
1334 			if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
1335 				_cache_setunresolved(ncp);
1336 			return(0);
1337 		}
1338 		_cache_unlock(ncp);
1339 	}
1340 	return(EWOULDBLOCK);
1341 }
1342 
1343 /*
1344  * This function tries to get a shared lock but will back-off to an exclusive
1345  * lock if:
1346  *
1347  * (1) Some other thread is trying to obtain an exclusive lock
1348  *     (to prevent the exclusive requester from getting livelocked out
1349  *     by many shared locks).
1350  *
1351  * (2) The current thread already owns an exclusive lock (to avoid
1352  *     deadlocking).
1353  *
1354  * WARNING! On machines with lots of cores we really want to try hard to
1355  *	    get a shared lock or concurrent path lookups can chain-react
1356  *	    into a very high-latency exclusive lock.
1357  */
1358 static int
1359 _cache_lock_shared_special(struct namecache *ncp)
1360 {
1361 	/*
1362 	 * Only honor a successful shared lock (returning 0) if there is
1363 	 * no exclusive request pending and the vnode, if present, is not
1364 	 * in a reclaimed state.
1365 	 */
1366 	if (_cache_lock_shared_nonblock(ncp) == 0) {
1367 		if ((ncp->nc_lockstatus & NC_EXLOCK_REQ) == 0) {
1368 			if (ncp->nc_vp == NULL ||
1369 			    (ncp->nc_vp->v_flag & VRECLAIMED) == 0) {
1370 				return(0);
1371 			}
1372 		}
1373 		_cache_unlock(ncp);
1374 		return(EWOULDBLOCK);
1375 	}
1376 
1377 	/*
1378 	 * Non-blocking shared lock failed.  If we already own the exclusive
1379 	 * lock just acquire another exclusive lock (instead of deadlocking).
1380 	 * Otherwise acquire a shared lock.
1381 	 */
1382 	if (ncp->nc_locktd == curthread) {
1383 		_cache_lock(ncp);
1384 		return(0);
1385 	}
1386 	_cache_lock_shared(ncp);
1387 	return(0);
1388 }
1389 
1390 
1391 /*
1392  * NOTE: The same nchandle can be passed for both arguments.
1393  */
1394 void
1395 cache_get(struct nchandle *nch, struct nchandle *target)
1396 {
1397 	KKASSERT(nch->ncp->nc_refs > 0);
1398 	target->mount = nch->mount;
1399 	target->ncp = _cache_get(nch->ncp);
1400 	_cache_mntref(target->mount);
1401 }
1402 
1403 void
1404 cache_get_maybe_shared(struct nchandle *nch, struct nchandle *target, int excl)
1405 {
1406 	KKASSERT(nch->ncp->nc_refs > 0);
1407 	target->mount = nch->mount;
1408 	target->ncp = _cache_get_maybe_shared(nch->ncp, excl);
1409 	_cache_mntref(target->mount);
1410 }
1411 
1412 /*
1413  *
1414  */
1415 static __inline
1416 void
1417 _cache_put(struct namecache *ncp)
1418 {
1419 	_cache_unlock(ncp);
1420 	_cache_drop(ncp);
1421 }
1422 
1423 /*
1424  *
1425  */
1426 void
1427 cache_put(struct nchandle *nch)
1428 {
1429 	_cache_mntrel(nch->mount);
1430 	_cache_put(nch->ncp);
1431 	nch->ncp = NULL;
1432 	nch->mount = NULL;
1433 }
1434 
1435 /*
1436  * Resolve an unresolved ncp by associating a vnode with it.  If the
1437  * vnode is NULL, a negative cache entry is created.
1438  *
1439  * The ncp should be locked on entry and will remain locked on return.
1440  */
1441 static
1442 void
1443 _cache_setvp(struct mount *mp, struct namecache *ncp, struct vnode *vp)
1444 {
1445 	KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
1446 	KKASSERT(_cache_lockstatus(ncp) == LK_EXCLUSIVE);
1447 
1448 	if (vp != NULL) {
1449 		/*
1450 		 * Any vp associated with an ncp which has children must
1451 		 * be held.  Any vp associated with a locked ncp must be held.
1452 		 */
1453 		if (!TAILQ_EMPTY(&ncp->nc_list))
1454 			vhold(vp);
1455 		spin_lock(&vp->v_spin);
1456 		ncp->nc_vp = vp;
1457 		TAILQ_INSERT_HEAD(&vp->v_namecache, ncp, nc_vnode);
1458 		spin_unlock(&vp->v_spin);
1459 		if (ncp->nc_lockstatus & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ))
1460 			vhold(vp);
1461 
1462 		/*
1463 		 * Set auxiliary flags
1464 		 */
1465 		switch(vp->v_type) {
1466 		case VDIR:
1467 			ncp->nc_flag |= NCF_ISDIR;
1468 			break;
1469 		case VLNK:
1470 			ncp->nc_flag |= NCF_ISSYMLINK;
1471 			/* XXX cache the contents of the symlink */
1472 			break;
1473 		default:
1474 			break;
1475 		}
1476 		ncp->nc_error = 0;
1477 		/* XXX: this is a hack to work-around the lack of a real pfs vfs
1478 		 * implementation*/
1479 		if (mp != NULL)
1480 			if (strncmp(mp->mnt_stat.f_fstypename, "null", 5) == 0)
1481 				vp->v_pfsmp = mp;
1482 	} else {
1483 		/*
1484 		 * When creating a negative cache hit we set the
1485 		 * namecache_gen.  A later resolve will clean out the
1486 		 * negative cache hit if the mount point's namecache_gen
1487 		 * has changed.  Used by devfs, could also be used by
1488 		 * other remote FSs.
1489 		 */
1490 		struct pcpu_ncache *pn = &pcpu_ncache[mycpu->gd_cpuid];
1491 
1492 		ncp->nc_vp = NULL;
1493 		ncp->nc_negcpu = mycpu->gd_cpuid;
1494 		spin_lock(&pn->neg_spin);
1495 		TAILQ_INSERT_TAIL(&pn->neg_list, ncp, nc_vnode);
1496 		++pn->neg_count;
1497 		spin_unlock(&pn->neg_spin);
1498 		atomic_add_long(&pn->vfscache_negs, 1);
1499 
1500 		ncp->nc_error = ENOENT;
1501 		if (mp)
1502 			VFS_NCPGEN_SET(mp, ncp);
1503 	}
1504 	ncp->nc_flag &= ~(NCF_UNRESOLVED | NCF_DEFEREDZAP);
1505 }
1506 
1507 /*
1508  *
1509  */
1510 void
1511 cache_setvp(struct nchandle *nch, struct vnode *vp)
1512 {
1513 	_cache_setvp(nch->mount, nch->ncp, vp);
1514 }
1515 
1516 /*
1517  *
1518  */
1519 void
1520 cache_settimeout(struct nchandle *nch, int nticks)
1521 {
1522 	struct namecache *ncp = nch->ncp;
1523 
1524 	if ((ncp->nc_timeout = ticks + nticks) == 0)
1525 		ncp->nc_timeout = 1;
1526 }
1527 
1528 /*
1529  * Disassociate the vnode or negative-cache association and mark a
1530  * namecache entry as unresolved again.  Note that the ncp is still
1531  * left in the hash table and still linked to its parent.
1532  *
1533  * The ncp should be locked and refd on entry and will remain locked and refd
1534  * on return.
1535  *
1536  * This routine is normally never called on a directory containing children.
1537  * However, NFS often does just that in its rename() code as a cop-out to
1538  * avoid complex namespace operations.  This disconnects a directory vnode
1539  * from its namecache and can cause the OLDAPI and NEWAPI to get out of
1540  * sync.
1541  *
1542  */
1543 static
1544 void
1545 _cache_setunresolved(struct namecache *ncp)
1546 {
1547 	struct vnode *vp;
1548 
1549 	if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1550 		ncp->nc_flag |= NCF_UNRESOLVED;
1551 		ncp->nc_timeout = 0;
1552 		ncp->nc_error = ENOTCONN;
1553 		if ((vp = ncp->nc_vp) != NULL) {
1554 			spin_lock(&vp->v_spin);
1555 			ncp->nc_vp = NULL;
1556 			TAILQ_REMOVE(&vp->v_namecache, ncp, nc_vnode);
1557 			spin_unlock(&vp->v_spin);
1558 
1559 			/*
1560 			 * Any vp associated with an ncp with children is
1561 			 * held by that ncp.  Any vp associated with a locked
1562 			 * ncp is held by that ncp.  These conditions must be
1563 			 * undone when the vp is cleared out from the ncp.
1564 			 */
1565 			if (!TAILQ_EMPTY(&ncp->nc_list))
1566 				vdrop(vp);
1567 			if (ncp->nc_lockstatus & ~(NC_EXLOCK_REQ|NC_SHLOCK_REQ))
1568 				vdrop(vp);
1569 		} else {
1570 			struct pcpu_ncache *pn;
1571 
1572 			pn = &pcpu_ncache[ncp->nc_negcpu];
1573 
1574 			atomic_add_long(&pn->vfscache_negs, -1);
1575 			spin_lock(&pn->neg_spin);
1576 			TAILQ_REMOVE(&pn->neg_list, ncp, nc_vnode);
1577 			--pn->neg_count;
1578 			spin_unlock(&pn->neg_spin);
1579 		}
1580 		ncp->nc_flag &= ~(NCF_WHITEOUT|NCF_ISDIR|NCF_ISSYMLINK);
1581 	}
1582 }
1583 
1584 /*
1585  * The cache_nresolve() code calls this function to automatically
1586  * set a resolved cache element to unresolved if it has timed out
1587  * or if it is a negative cache hit and the mount point namecache_gen
1588  * has changed.
1589  */
1590 static __inline int
1591 _cache_auto_unresolve_test(struct mount *mp, struct namecache *ncp)
1592 {
1593 	/*
1594 	 * Try to zap entries that have timed out.  We have
1595 	 * to be careful here because locked leafs may depend
1596 	 * on the vnode remaining intact in a parent, so only
1597 	 * do this under very specific conditions.
1598 	 */
1599 	if (ncp->nc_timeout && (int)(ncp->nc_timeout - ticks) < 0 &&
1600 	    TAILQ_EMPTY(&ncp->nc_list)) {
1601 		return 1;
1602 	}
1603 
1604 	/*
1605 	 * If a resolved negative cache hit is invalid due to
1606 	 * the mount's namecache generation being bumped, zap it.
1607 	 */
1608 	if (ncp->nc_vp == NULL && VFS_NCPGEN_TEST(mp, ncp)) {
1609 		return 1;
1610 	}
1611 
1612 	/*
1613 	 * Otherwise we are good
1614 	 */
1615 	return 0;
1616 }
1617 
1618 static __inline void
1619 _cache_auto_unresolve(struct mount *mp, struct namecache *ncp)
1620 {
1621 	/*
1622 	 * Already in an unresolved state, nothing to do.
1623 	 */
1624 	if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1625 		if (_cache_auto_unresolve_test(mp, ncp))
1626 			_cache_setunresolved(ncp);
1627 	}
1628 }
1629 
1630 /*
1631  *
1632  */
1633 void
1634 cache_setunresolved(struct nchandle *nch)
1635 {
1636 	_cache_setunresolved(nch->ncp);
1637 }
1638 
1639 /*
1640  * Determine if we can clear NCF_ISMOUNTPT by scanning the mountlist
1641  * looking for matches.  This flag tells the lookup code when it must
1642  * check for a mount linkage and also prevents the directories in question
1643  * from being deleted or renamed.
1644  */
1645 static
1646 int
1647 cache_clrmountpt_callback(struct mount *mp, void *data)
1648 {
1649 	struct nchandle *nch = data;
1650 
1651 	if (mp->mnt_ncmounton.ncp == nch->ncp)
1652 		return(1);
1653 	if (mp->mnt_ncmountpt.ncp == nch->ncp)
1654 		return(1);
1655 	return(0);
1656 }
1657 
1658 /*
1659  * Clear NCF_ISMOUNTPT on nch->ncp if it is no longer associated
1660  * with a mount point.
1661  */
1662 void
1663 cache_clrmountpt(struct nchandle *nch)
1664 {
1665 	int count;
1666 
1667 	count = mountlist_scan(cache_clrmountpt_callback, nch,
1668 			       MNTSCAN_FORWARD | MNTSCAN_NOBUSY |
1669 			       MNTSCAN_NOUNLOCK);
1670 	if (count == 0)
1671 		nch->ncp->nc_flag &= ~NCF_ISMOUNTPT;
1672 }
1673 
1674 /*
1675  * Invalidate portions of the namecache topology given a starting entry.
1676  * The passed ncp is set to an unresolved state and:
1677  *
1678  * The passed ncp must be referencxed and locked.  The routine may unlock
1679  * and relock ncp several times, and will recheck the children and loop
1680  * to catch races.  When done the passed ncp will be returned with the
1681  * reference and lock intact.
1682  *
1683  * CINV_DESTROY		- Set a flag in the passed ncp entry indicating
1684  *			  that the physical underlying nodes have been
1685  *			  destroyed... as in deleted.  For example, when
1686  *			  a directory is removed.  This will cause record
1687  *			  lookups on the name to no longer be able to find
1688  *			  the record and tells the resolver to return failure
1689  *			  rather then trying to resolve through the parent.
1690  *
1691  *			  The topology itself, including ncp->nc_name,
1692  *			  remains intact.
1693  *
1694  *			  This only applies to the passed ncp, if CINV_CHILDREN
1695  *			  is specified the children are not flagged.
1696  *
1697  * CINV_CHILDREN	- Set all children (recursively) to an unresolved
1698  *			  state as well.
1699  *
1700  *			  Note that this will also have the side effect of
1701  *			  cleaning out any unreferenced nodes in the topology
1702  *			  from the leaves up as the recursion backs out.
1703  *
1704  * Note that the topology for any referenced nodes remains intact, but
1705  * the nodes will be marked as having been destroyed and will be set
1706  * to an unresolved state.
1707  *
1708  * It is possible for cache_inval() to race a cache_resolve(), meaning that
1709  * the namecache entry may not actually be invalidated on return if it was
1710  * revalidated while recursing down into its children.  This code guarentees
1711  * that the node(s) will go through an invalidation cycle, but does not
1712  * guarentee that they will remain in an invalidated state.
1713  *
1714  * Returns non-zero if a revalidation was detected during the invalidation
1715  * recursion, zero otherwise.  Note that since only the original ncp is
1716  * locked the revalidation ultimately can only indicate that the original ncp
1717  * *MIGHT* no have been reresolved.
1718  *
1719  * DEEP RECURSION HANDLING - If a recursive invalidation recurses deeply we
1720  * have to avoid blowing out the kernel stack.  We do this by saving the
1721  * deep namecache node and aborting the recursion, then re-recursing at that
1722  * node using a depth-first algorithm in order to allow multiple deep
1723  * recursions to chain through each other, then we restart the invalidation
1724  * from scratch.
1725  */
1726 
1727 struct cinvtrack {
1728 	struct namecache *resume_ncp;
1729 	int depth;
1730 };
1731 
1732 static int _cache_inval_internal(struct namecache *, int, struct cinvtrack *);
1733 
1734 static
1735 int
1736 _cache_inval(struct namecache *ncp, int flags)
1737 {
1738 	struct cinvtrack track;
1739 	struct namecache *ncp2;
1740 	int r;
1741 
1742 	track.depth = 0;
1743 	track.resume_ncp = NULL;
1744 
1745 	for (;;) {
1746 		r = _cache_inval_internal(ncp, flags, &track);
1747 		if (track.resume_ncp == NULL)
1748 			break;
1749 		_cache_unlock(ncp);
1750 		while ((ncp2 = track.resume_ncp) != NULL) {
1751 			track.resume_ncp = NULL;
1752 			_cache_lock(ncp2);
1753 			_cache_inval_internal(ncp2, flags & ~CINV_DESTROY,
1754 					     &track);
1755 			_cache_put(ncp2);
1756 		}
1757 		_cache_lock(ncp);
1758 	}
1759 	return(r);
1760 }
1761 
1762 int
1763 cache_inval(struct nchandle *nch, int flags)
1764 {
1765 	return(_cache_inval(nch->ncp, flags));
1766 }
1767 
1768 /*
1769  * Helper for _cache_inval().  The passed ncp is refd and locked and
1770  * remains that way on return, but may be unlocked/relocked multiple
1771  * times by the routine.
1772  */
1773 static int
1774 _cache_inval_internal(struct namecache *ncp, int flags, struct cinvtrack *track)
1775 {
1776 	struct namecache *nextkid;
1777 	int rcnt = 0;
1778 
1779 	KKASSERT(_cache_lockstatus(ncp) == LK_EXCLUSIVE);
1780 
1781 	_cache_setunresolved(ncp);
1782 	if (flags & CINV_DESTROY) {
1783 		ncp->nc_flag |= NCF_DESTROYED;
1784 		++ncp->nc_generation;
1785 	}
1786 	while ((flags & CINV_CHILDREN) &&
1787 	       (nextkid = TAILQ_FIRST(&ncp->nc_list)) != NULL
1788 	) {
1789 		struct namecache *kid;
1790 		int restart;
1791 
1792 		restart = 0;
1793 		_cache_hold(nextkid);
1794 		if (++track->depth > MAX_RECURSION_DEPTH) {
1795 			track->resume_ncp = ncp;
1796 			_cache_hold(ncp);
1797 			++rcnt;
1798 		}
1799 		while ((kid = nextkid) != NULL) {
1800 			/*
1801 			 * Parent (ncp) must be locked for the iteration.
1802 			 */
1803 			nextkid = NULL;
1804 			if (kid->nc_parent != ncp) {
1805 				_cache_drop(kid);
1806 				kprintf("cache_inval_internal restartA %s\n",
1807 					ncp->nc_name);
1808 				restart = 1;
1809 				break;
1810 			}
1811 			if ((nextkid = TAILQ_NEXT(kid, nc_entry)) != NULL)
1812 				_cache_hold(nextkid);
1813 
1814 			/*
1815 			 * Parent unlocked for this section to avoid
1816 			 * deadlocks.
1817 			 */
1818 			_cache_unlock(ncp);
1819 			if (track->resume_ncp) {
1820 				_cache_drop(kid);
1821 				_cache_lock(ncp);
1822 				break;
1823 			}
1824 			if ((kid->nc_flag & NCF_UNRESOLVED) == 0 ||
1825 			    TAILQ_FIRST(&kid->nc_list)
1826 			) {
1827 				_cache_lock(kid);
1828 				if (kid->nc_parent != ncp) {
1829 					kprintf("cache_inval_internal "
1830 						"restartB %s\n",
1831 						ncp->nc_name);
1832 					restart = 1;
1833 					_cache_unlock(kid);
1834 					_cache_drop(kid);
1835 					_cache_lock(ncp);
1836 					break;
1837 				}
1838 
1839 				rcnt += _cache_inval_internal(kid, flags & ~CINV_DESTROY, track);
1840 				_cache_unlock(kid);
1841 			}
1842 			_cache_drop(kid);
1843 			_cache_lock(ncp);
1844 		}
1845 		if (nextkid)
1846 			_cache_drop(nextkid);
1847 		--track->depth;
1848 		if (restart == 0)
1849 			break;
1850 	}
1851 
1852 	/*
1853 	 * Someone could have gotten in there while ncp was unlocked,
1854 	 * retry if so.
1855 	 */
1856 	if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
1857 		++rcnt;
1858 	return (rcnt);
1859 }
1860 
1861 /*
1862  * Invalidate a vnode's namecache associations.  To avoid races against
1863  * the resolver we do not invalidate a node which we previously invalidated
1864  * but which was then re-resolved while we were in the invalidation loop.
1865  *
1866  * Returns non-zero if any namecache entries remain after the invalidation
1867  * loop completed.
1868  *
1869  * NOTE: Unlike the namecache topology which guarentees that ncp's will not
1870  *	 be ripped out of the topology while held, the vnode's v_namecache
1871  *	 list has no such restriction.  NCP's can be ripped out of the list
1872  *	 at virtually any time if not locked, even if held.
1873  *
1874  *	 In addition, the v_namecache list itself must be locked via
1875  *	 the vnode's spinlock.
1876  */
1877 int
1878 cache_inval_vp(struct vnode *vp, int flags)
1879 {
1880 	struct namecache *ncp;
1881 	struct namecache *next;
1882 
1883 restart:
1884 	spin_lock(&vp->v_spin);
1885 	ncp = TAILQ_FIRST(&vp->v_namecache);
1886 	if (ncp)
1887 		_cache_hold(ncp);
1888 	while (ncp) {
1889 		/* loop entered with ncp held and vp spin-locked */
1890 		if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1891 			_cache_hold(next);
1892 		spin_unlock(&vp->v_spin);
1893 		_cache_lock(ncp);
1894 		if (ncp->nc_vp != vp) {
1895 			kprintf("Warning: cache_inval_vp: race-A detected on "
1896 				"%s\n", ncp->nc_name);
1897 			_cache_put(ncp);
1898 			if (next)
1899 				_cache_drop(next);
1900 			goto restart;
1901 		}
1902 		_cache_inval(ncp, flags);
1903 		_cache_put(ncp);		/* also releases reference */
1904 		ncp = next;
1905 		spin_lock(&vp->v_spin);
1906 		if (ncp && ncp->nc_vp != vp) {
1907 			spin_unlock(&vp->v_spin);
1908 			kprintf("Warning: cache_inval_vp: race-B detected on "
1909 				"%s\n", ncp->nc_name);
1910 			_cache_drop(ncp);
1911 			goto restart;
1912 		}
1913 	}
1914 	spin_unlock(&vp->v_spin);
1915 	return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1916 }
1917 
1918 /*
1919  * This routine is used instead of the normal cache_inval_vp() when we
1920  * are trying to recycle otherwise good vnodes.
1921  *
1922  * Return 0 on success, non-zero if not all namecache records could be
1923  * disassociated from the vnode (for various reasons).
1924  */
1925 int
1926 cache_inval_vp_nonblock(struct vnode *vp)
1927 {
1928 	struct namecache *ncp;
1929 	struct namecache *next;
1930 
1931 	spin_lock(&vp->v_spin);
1932 	ncp = TAILQ_FIRST(&vp->v_namecache);
1933 	if (ncp)
1934 		_cache_hold(ncp);
1935 	while (ncp) {
1936 		/* loop entered with ncp held */
1937 		if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1938 			_cache_hold(next);
1939 		spin_unlock(&vp->v_spin);
1940 		if (_cache_lock_nonblock(ncp)) {
1941 			_cache_drop(ncp);
1942 			if (next)
1943 				_cache_drop(next);
1944 			goto done;
1945 		}
1946 		if (ncp->nc_vp != vp) {
1947 			kprintf("Warning: cache_inval_vp: race-A detected on "
1948 				"%s\n", ncp->nc_name);
1949 			_cache_put(ncp);
1950 			if (next)
1951 				_cache_drop(next);
1952 			goto done;
1953 		}
1954 		_cache_inval(ncp, 0);
1955 		_cache_put(ncp);		/* also releases reference */
1956 		ncp = next;
1957 		spin_lock(&vp->v_spin);
1958 		if (ncp && ncp->nc_vp != vp) {
1959 			spin_unlock(&vp->v_spin);
1960 			kprintf("Warning: cache_inval_vp: race-B detected on "
1961 				"%s\n", ncp->nc_name);
1962 			_cache_drop(ncp);
1963 			goto done;
1964 		}
1965 	}
1966 	spin_unlock(&vp->v_spin);
1967 done:
1968 	return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1969 }
1970 
1971 /*
1972  * Clears the universal directory search 'ok' flag.  This flag allows
1973  * nlookup() to bypass normal vnode checks.  This flag is a cached flag
1974  * so clearing it simply forces revalidation.
1975  */
1976 void
1977 cache_inval_wxok(struct vnode *vp)
1978 {
1979 	struct namecache *ncp;
1980 
1981 	spin_lock(&vp->v_spin);
1982 	TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1983 		if (ncp->nc_flag & (NCF_WXOK | NCF_NOTX))
1984 			atomic_clear_short(&ncp->nc_flag, NCF_WXOK | NCF_NOTX);
1985 	}
1986 	spin_unlock(&vp->v_spin);
1987 }
1988 
1989 /*
1990  * The source ncp has been renamed to the target ncp.  Both fncp and tncp
1991  * must be locked.  The target ncp is destroyed (as a normal rename-over
1992  * would destroy the target file or directory).
1993  *
1994  * Because there may be references to the source ncp we cannot copy its
1995  * contents to the target.  Instead the source ncp is relinked as the target
1996  * and the target ncp is removed from the namecache topology.
1997  */
1998 void
1999 cache_rename(struct nchandle *fnch, struct nchandle *tnch)
2000 {
2001 	struct namecache *fncp = fnch->ncp;
2002 	struct namecache *tncp = tnch->ncp;
2003 	struct namecache *tncp_par;
2004 	struct nchash_head *nchpp;
2005 	u_int32_t hash;
2006 	char *oname;
2007 	char *nname;
2008 
2009 	++fncp->nc_generation;
2010 	++tncp->nc_generation;
2011 	if (tncp->nc_nlen) {
2012 		nname = kmalloc(tncp->nc_nlen + 1, M_VFSCACHE, M_WAITOK);
2013 		bcopy(tncp->nc_name, nname, tncp->nc_nlen);
2014 		nname[tncp->nc_nlen] = 0;
2015 	} else {
2016 		nname = NULL;
2017 	}
2018 
2019 	/*
2020 	 * Rename fncp (unlink)
2021 	 */
2022 	_cache_unlink_parent(fncp);
2023 	oname = fncp->nc_name;
2024 	fncp->nc_name = nname;
2025 	fncp->nc_nlen = tncp->nc_nlen;
2026 	if (oname)
2027 		kfree(oname, M_VFSCACHE);
2028 
2029 	tncp_par = tncp->nc_parent;
2030 	_cache_hold(tncp_par);
2031 	_cache_lock(tncp_par);
2032 
2033 	/*
2034 	 * Rename fncp (relink)
2035 	 */
2036 	hash = fnv_32_buf(fncp->nc_name, fncp->nc_nlen, FNV1_32_INIT);
2037 	hash = fnv_32_buf(&tncp_par, sizeof(tncp_par), hash);
2038 	nchpp = NCHHASH(hash);
2039 
2040 	spin_lock(&nchpp->spin);
2041 	_cache_link_parent(fncp, tncp_par, nchpp);
2042 	spin_unlock(&nchpp->spin);
2043 
2044 	_cache_put(tncp_par);
2045 
2046 	/*
2047 	 * Get rid of the overwritten tncp (unlink)
2048 	 */
2049 	_cache_unlink(tncp);
2050 }
2051 
2052 /*
2053  * Perform actions consistent with unlinking a file.  The passed-in ncp
2054  * must be locked.
2055  *
2056  * The ncp is marked DESTROYED so it no longer shows up in searches,
2057  * and will be physically deleted when the vnode goes away.
2058  *
2059  * If the related vnode has no refs then we cycle it through vget()/vput()
2060  * to (possibly if we don't have a ref race) trigger a deactivation,
2061  * allowing the VFS to trivially detect and recycle the deleted vnode
2062  * via VOP_INACTIVE().
2063  *
2064  * NOTE: _cache_rename() will automatically call _cache_unlink() on the
2065  *	 target ncp.
2066  */
2067 void
2068 cache_unlink(struct nchandle *nch)
2069 {
2070 	_cache_unlink(nch->ncp);
2071 }
2072 
2073 static void
2074 _cache_unlink(struct namecache *ncp)
2075 {
2076 	struct vnode *vp;
2077 
2078 	/*
2079 	 * Causes lookups to fail and allows another ncp with the same
2080 	 * name to be created under ncp->nc_parent.
2081 	 */
2082 	ncp->nc_flag |= NCF_DESTROYED;
2083 	++ncp->nc_generation;
2084 
2085 	/*
2086 	 * Attempt to trigger a deactivation.  Set VREF_FINALIZE to
2087 	 * force action on the 1->0 transition.
2088 	 */
2089 	if ((ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
2090 	    (vp = ncp->nc_vp) != NULL) {
2091 		atomic_set_int(&vp->v_refcnt, VREF_FINALIZE);
2092 		if (VREFCNT(vp) <= 0) {
2093 			if (vget(vp, LK_SHARED) == 0)
2094 				vput(vp);
2095 		}
2096 	}
2097 }
2098 
2099 /*
2100  * Return non-zero if the nch might be associated with an open and/or mmap()'d
2101  * file.  The easy solution is to just return non-zero if the vnode has refs.
2102  * Used to interlock hammer2 reclaims (VREF_FINALIZE should already be set to
2103  * force the reclaim).
2104  */
2105 int
2106 cache_isopen(struct nchandle *nch)
2107 {
2108 	struct vnode *vp;
2109 	struct namecache *ncp = nch->ncp;
2110 
2111 	if ((ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
2112 	    (vp = ncp->nc_vp) != NULL &&
2113 	    VREFCNT(vp)) {
2114 		return 1;
2115 	}
2116 	return 0;
2117 }
2118 
2119 
2120 /*
2121  * vget the vnode associated with the namecache entry.  Resolve the namecache
2122  * entry if necessary.  The passed ncp must be referenced and locked.  If
2123  * the ncp is resolved it might be locked shared.
2124  *
2125  * lk_type may be LK_SHARED, LK_EXCLUSIVE.  A ref'd, possibly locked
2126  * (depending on the passed lk_type) will be returned in *vpp with an error
2127  * of 0, or NULL will be returned in *vpp with a non-0 error code.  The
2128  * most typical error is ENOENT, meaning that the ncp represents a negative
2129  * cache hit and there is no vnode to retrieve, but other errors can occur
2130  * too.
2131  *
2132  * The vget() can race a reclaim.  If this occurs we re-resolve the
2133  * namecache entry.
2134  *
2135  * There are numerous places in the kernel where vget() is called on a
2136  * vnode while one or more of its namecache entries is locked.  Releasing
2137  * a vnode never deadlocks against locked namecache entries (the vnode
2138  * will not get recycled while referenced ncp's exist).  This means we
2139  * can safely acquire the vnode.  In fact, we MUST NOT release the ncp
2140  * lock when acquiring the vp lock or we might cause a deadlock.
2141  *
2142  * NOTE: The passed-in ncp must be locked exclusively if it is initially
2143  *	 unresolved.  If a reclaim race occurs the passed-in ncp will be
2144  *	 relocked exclusively before being re-resolved.
2145  */
2146 int
2147 cache_vget(struct nchandle *nch, struct ucred *cred,
2148 	   int lk_type, struct vnode **vpp)
2149 {
2150 	struct namecache *ncp;
2151 	struct vnode *vp;
2152 	int error;
2153 
2154 	ncp = nch->ncp;
2155 again:
2156 	vp = NULL;
2157 	if (ncp->nc_flag & NCF_UNRESOLVED)
2158 		error = cache_resolve(nch, cred);
2159 	else
2160 		error = 0;
2161 
2162 	if (error == 0 && (vp = ncp->nc_vp) != NULL) {
2163 		error = vget(vp, lk_type);
2164 		if (error) {
2165 			/*
2166 			 * VRECLAIM race
2167 			 *
2168 			 * The ncp may have been locked shared, we must relock
2169 			 * it exclusively before we can set it to unresolved.
2170 			 */
2171 			if (error == ENOENT) {
2172 				kprintf("Warning: vnode reclaim race detected "
2173 					"in cache_vget on %p (%s)\n",
2174 					vp, ncp->nc_name);
2175 				_cache_unlock(ncp);
2176 				_cache_lock(ncp);
2177 				_cache_setunresolved(ncp);
2178 				goto again;
2179 			}
2180 
2181 			/*
2182 			 * Not a reclaim race, some other error.
2183 			 */
2184 			KKASSERT(ncp->nc_vp == vp);
2185 			vp = NULL;
2186 		} else {
2187 			KKASSERT(ncp->nc_vp == vp);
2188 			KKASSERT((vp->v_flag & VRECLAIMED) == 0);
2189 		}
2190 	}
2191 	if (error == 0 && vp == NULL)
2192 		error = ENOENT;
2193 	*vpp = vp;
2194 	return(error);
2195 }
2196 
2197 /*
2198  * Similar to cache_vget() but only acquires a ref on the vnode.
2199  *
2200  * NOTE: The passed-in ncp must be locked exclusively if it is initially
2201  *	 unresolved.  If a reclaim race occurs the passed-in ncp will be
2202  *	 relocked exclusively before being re-resolved.
2203  */
2204 int
2205 cache_vref(struct nchandle *nch, struct ucred *cred, struct vnode **vpp)
2206 {
2207 	struct namecache *ncp;
2208 	struct vnode *vp;
2209 	int error;
2210 
2211 	ncp = nch->ncp;
2212 again:
2213 	vp = NULL;
2214 	if (ncp->nc_flag & NCF_UNRESOLVED)
2215 		error = cache_resolve(nch, cred);
2216 	else
2217 		error = 0;
2218 
2219 	if (error == 0 && (vp = ncp->nc_vp) != NULL) {
2220 		error = vget(vp, LK_SHARED);
2221 		if (error) {
2222 			/*
2223 			 * VRECLAIM race
2224 			 */
2225 			if (error == ENOENT) {
2226 				kprintf("Warning: vnode reclaim race detected "
2227 					"in cache_vget on %p (%s)\n",
2228 					vp, ncp->nc_name);
2229 				_cache_unlock(ncp);
2230 				_cache_lock(ncp);
2231 				_cache_setunresolved(ncp);
2232 				goto again;
2233 			}
2234 
2235 			/*
2236 			 * Not a reclaim race, some other error.
2237 			 */
2238 			KKASSERT(ncp->nc_vp == vp);
2239 			vp = NULL;
2240 		} else {
2241 			KKASSERT(ncp->nc_vp == vp);
2242 			KKASSERT((vp->v_flag & VRECLAIMED) == 0);
2243 			/* caller does not want a lock */
2244 			vn_unlock(vp);
2245 		}
2246 	}
2247 	if (error == 0 && vp == NULL)
2248 		error = ENOENT;
2249 	*vpp = vp;
2250 	return(error);
2251 }
2252 
2253 /*
2254  * Return a referenced vnode representing the parent directory of
2255  * ncp.
2256  *
2257  * Because the caller has locked the ncp it should not be possible for
2258  * the parent ncp to go away.  However, the parent can unresolve its
2259  * dvp at any time so we must be able to acquire a lock on the parent
2260  * to safely access nc_vp.
2261  *
2262  * We have to leave par unlocked when vget()ing dvp to avoid a deadlock,
2263  * so use vhold()/vdrop() while holding the lock to prevent dvp from
2264  * getting destroyed.
2265  *
2266  * NOTE: vhold() is allowed when dvp has 0 refs if we hold a
2267  *	 lock on the ncp in question..
2268  */
2269 static struct vnode *
2270 cache_dvpref(struct namecache *ncp)
2271 {
2272 	struct namecache *par;
2273 	struct vnode *dvp;
2274 
2275 	dvp = NULL;
2276 	if ((par = ncp->nc_parent) != NULL) {
2277 		_cache_hold(par);
2278 		_cache_lock(par);
2279 		if ((par->nc_flag & NCF_UNRESOLVED) == 0) {
2280 			if ((dvp = par->nc_vp) != NULL)
2281 				vhold(dvp);
2282 		}
2283 		_cache_unlock(par);
2284 		if (dvp) {
2285 			if (vget(dvp, LK_SHARED) == 0) {
2286 				vn_unlock(dvp);
2287 				vdrop(dvp);
2288 				/* return refd, unlocked dvp */
2289 			} else {
2290 				vdrop(dvp);
2291 				dvp = NULL;
2292 			}
2293 		}
2294 		_cache_drop(par);
2295 	}
2296 	return(dvp);
2297 }
2298 
2299 /*
2300  * Convert a directory vnode to a namecache record without any other
2301  * knowledge of the topology.  This ONLY works with directory vnodes and
2302  * is ONLY used by the NFS server.  dvp must be refd but unlocked, and the
2303  * returned ncp (if not NULL) will be held and unlocked.
2304  *
2305  * If 'makeit' is 0 and dvp has no existing namecache record, NULL is returned.
2306  * If 'makeit' is 1 we attempt to track-down and create the namecache topology
2307  * for dvp.  This will fail only if the directory has been deleted out from
2308  * under the caller.
2309  *
2310  * Callers must always check for a NULL return no matter the value of 'makeit'.
2311  *
2312  * To avoid underflowing the kernel stack each recursive call increments
2313  * the makeit variable.
2314  */
2315 
2316 static int cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
2317 				  struct vnode *dvp, char *fakename);
2318 static int cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
2319 				  struct vnode **saved_dvp);
2320 
2321 int
2322 cache_fromdvp(struct vnode *dvp, struct ucred *cred, int makeit,
2323 	      struct nchandle *nch)
2324 {
2325 	struct vnode *saved_dvp;
2326 	struct vnode *pvp;
2327 	char *fakename;
2328 	int error;
2329 
2330 	nch->ncp = NULL;
2331 	nch->mount = dvp->v_mount;
2332 	saved_dvp = NULL;
2333 	fakename = NULL;
2334 
2335 	/*
2336 	 * Handle the makeit == 0 degenerate case
2337 	 */
2338 	if (makeit == 0) {
2339 		spin_lock_shared(&dvp->v_spin);
2340 		nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
2341 		if (nch->ncp)
2342 			cache_hold(nch);
2343 		spin_unlock_shared(&dvp->v_spin);
2344 	}
2345 
2346 	/*
2347 	 * Loop until resolution, inside code will break out on error.
2348 	 */
2349 	while (makeit) {
2350 		/*
2351 		 * Break out if we successfully acquire a working ncp.
2352 		 */
2353 		spin_lock_shared(&dvp->v_spin);
2354 		nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
2355 		if (nch->ncp) {
2356 			cache_hold(nch);
2357 			spin_unlock_shared(&dvp->v_spin);
2358 			break;
2359 		}
2360 		spin_unlock_shared(&dvp->v_spin);
2361 
2362 		/*
2363 		 * If dvp is the root of its filesystem it should already
2364 		 * have a namecache pointer associated with it as a side
2365 		 * effect of the mount, but it may have been disassociated.
2366 		 */
2367 		if (dvp->v_flag & VROOT) {
2368 			nch->ncp = _cache_get(nch->mount->mnt_ncmountpt.ncp);
2369 			error = cache_resolve_mp(nch->mount);
2370 			_cache_put(nch->ncp);
2371 			if (ncvp_debug) {
2372 				kprintf("cache_fromdvp: resolve root of mount %p error %d",
2373 					dvp->v_mount, error);
2374 			}
2375 			if (error) {
2376 				if (ncvp_debug)
2377 					kprintf(" failed\n");
2378 				nch->ncp = NULL;
2379 				break;
2380 			}
2381 			if (ncvp_debug)
2382 				kprintf(" succeeded\n");
2383 			continue;
2384 		}
2385 
2386 		/*
2387 		 * If we are recursed too deeply resort to an O(n^2)
2388 		 * algorithm to resolve the namecache topology.  The
2389 		 * resolved pvp is left referenced in saved_dvp to
2390 		 * prevent the tree from being destroyed while we loop.
2391 		 */
2392 		if (makeit > 20) {
2393 			error = cache_fromdvp_try(dvp, cred, &saved_dvp);
2394 			if (error) {
2395 				kprintf("lookupdotdot(longpath) failed %d "
2396 				       "dvp %p\n", error, dvp);
2397 				nch->ncp = NULL;
2398 				break;
2399 			}
2400 			continue;
2401 		}
2402 
2403 		/*
2404 		 * Get the parent directory and resolve its ncp.
2405 		 */
2406 		if (fakename) {
2407 			kfree(fakename, M_TEMP);
2408 			fakename = NULL;
2409 		}
2410 		error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
2411 					  &fakename);
2412 		if (error) {
2413 			kprintf("lookupdotdot failed %d dvp %p\n", error, dvp);
2414 			break;
2415 		}
2416 		vn_unlock(pvp);
2417 
2418 		/*
2419 		 * Reuse makeit as a recursion depth counter.  On success
2420 		 * nch will be fully referenced.
2421 		 */
2422 		cache_fromdvp(pvp, cred, makeit + 1, nch);
2423 		vrele(pvp);
2424 		if (nch->ncp == NULL)
2425 			break;
2426 
2427 		/*
2428 		 * Do an inefficient scan of pvp (embodied by ncp) to look
2429 		 * for dvp.  This will create a namecache record for dvp on
2430 		 * success.  We loop up to recheck on success.
2431 		 *
2432 		 * ncp and dvp are both held but not locked.
2433 		 */
2434 		error = cache_inefficient_scan(nch, cred, dvp, fakename);
2435 		if (error) {
2436 			kprintf("cache_fromdvp: scan %p (%s) failed on dvp=%p\n",
2437 				pvp, nch->ncp->nc_name, dvp);
2438 			cache_drop(nch);
2439 			/* nch was NULLed out, reload mount */
2440 			nch->mount = dvp->v_mount;
2441 			break;
2442 		}
2443 		if (ncvp_debug) {
2444 			kprintf("cache_fromdvp: scan %p (%s) succeeded\n",
2445 				pvp, nch->ncp->nc_name);
2446 		}
2447 		cache_drop(nch);
2448 		/* nch was NULLed out, reload mount */
2449 		nch->mount = dvp->v_mount;
2450 	}
2451 
2452 	/*
2453 	 * If nch->ncp is non-NULL it will have been held already.
2454 	 */
2455 	if (fakename)
2456 		kfree(fakename, M_TEMP);
2457 	if (saved_dvp)
2458 		vrele(saved_dvp);
2459 	if (nch->ncp)
2460 		return (0);
2461 	return (EINVAL);
2462 }
2463 
2464 /*
2465  * Go up the chain of parent directories until we find something
2466  * we can resolve into the namecache.  This is very inefficient.
2467  */
2468 static
2469 int
2470 cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
2471 		  struct vnode **saved_dvp)
2472 {
2473 	struct nchandle nch;
2474 	struct vnode *pvp;
2475 	int error;
2476 	static time_t last_fromdvp_report;
2477 	char *fakename;
2478 
2479 	/*
2480 	 * Loop getting the parent directory vnode until we get something we
2481 	 * can resolve in the namecache.
2482 	 */
2483 	vref(dvp);
2484 	nch.mount = dvp->v_mount;
2485 	nch.ncp = NULL;
2486 	fakename = NULL;
2487 
2488 	for (;;) {
2489 		if (fakename) {
2490 			kfree(fakename, M_TEMP);
2491 			fakename = NULL;
2492 		}
2493 		error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
2494 					  &fakename);
2495 		if (error) {
2496 			vrele(dvp);
2497 			break;
2498 		}
2499 		vn_unlock(pvp);
2500 		spin_lock_shared(&pvp->v_spin);
2501 		if ((nch.ncp = TAILQ_FIRST(&pvp->v_namecache)) != NULL) {
2502 			_cache_hold(nch.ncp);
2503 			spin_unlock_shared(&pvp->v_spin);
2504 			vrele(pvp);
2505 			break;
2506 		}
2507 		spin_unlock_shared(&pvp->v_spin);
2508 		if (pvp->v_flag & VROOT) {
2509 			nch.ncp = _cache_get(pvp->v_mount->mnt_ncmountpt.ncp);
2510 			error = cache_resolve_mp(nch.mount);
2511 			_cache_unlock(nch.ncp);
2512 			vrele(pvp);
2513 			if (error) {
2514 				_cache_drop(nch.ncp);
2515 				nch.ncp = NULL;
2516 				vrele(dvp);
2517 			}
2518 			break;
2519 		}
2520 		vrele(dvp);
2521 		dvp = pvp;
2522 	}
2523 	if (error == 0) {
2524 		if (last_fromdvp_report != time_uptime) {
2525 			last_fromdvp_report = time_uptime;
2526 			kprintf("Warning: extremely inefficient path "
2527 				"resolution on %s\n",
2528 				nch.ncp->nc_name);
2529 		}
2530 		error = cache_inefficient_scan(&nch, cred, dvp, fakename);
2531 
2532 		/*
2533 		 * Hopefully dvp now has a namecache record associated with
2534 		 * it.  Leave it referenced to prevent the kernel from
2535 		 * recycling the vnode.  Otherwise extremely long directory
2536 		 * paths could result in endless recycling.
2537 		 */
2538 		if (*saved_dvp)
2539 		    vrele(*saved_dvp);
2540 		*saved_dvp = dvp;
2541 		_cache_drop(nch.ncp);
2542 	}
2543 	if (fakename)
2544 		kfree(fakename, M_TEMP);
2545 	return (error);
2546 }
2547 
2548 /*
2549  * Do an inefficient scan of the directory represented by ncp looking for
2550  * the directory vnode dvp.  ncp must be held but not locked on entry and
2551  * will be held on return.  dvp must be refd but not locked on entry and
2552  * will remain refd on return.
2553  *
2554  * Why do this at all?  Well, due to its stateless nature the NFS server
2555  * converts file handles directly to vnodes without necessarily going through
2556  * the namecache ops that would otherwise create the namecache topology
2557  * leading to the vnode.  We could either (1) Change the namecache algorithms
2558  * to allow disconnect namecache records that are re-merged opportunistically,
2559  * or (2) Make the NFS server backtrack and scan to recover a connected
2560  * namecache topology in order to then be able to issue new API lookups.
2561  *
2562  * It turns out that (1) is a huge mess.  It takes a nice clean set of
2563  * namecache algorithms and introduces a lot of complication in every subsystem
2564  * that calls into the namecache to deal with the re-merge case, especially
2565  * since we are using the namecache to placehold negative lookups and the
2566  * vnode might not be immediately assigned. (2) is certainly far less
2567  * efficient then (1), but since we are only talking about directories here
2568  * (which are likely to remain cached), the case does not actually run all
2569  * that often and has the supreme advantage of not polluting the namecache
2570  * algorithms.
2571  *
2572  * If a fakename is supplied just construct a namecache entry using the
2573  * fake name.
2574  */
2575 static int
2576 cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
2577 		       struct vnode *dvp, char *fakename)
2578 {
2579 	struct nlcomponent nlc;
2580 	struct nchandle rncp;
2581 	struct dirent *den;
2582 	struct vnode *pvp;
2583 	struct vattr vat;
2584 	struct iovec iov;
2585 	struct uio uio;
2586 	int blksize;
2587 	int eofflag;
2588 	int bytes;
2589 	char *rbuf;
2590 	int error;
2591 
2592 	vat.va_blocksize = 0;
2593 	if ((error = VOP_GETATTR(dvp, &vat)) != 0)
2594 		return (error);
2595 	cache_lock(nch);
2596 	error = cache_vref(nch, cred, &pvp);
2597 	cache_unlock(nch);
2598 	if (error)
2599 		return (error);
2600 	if (ncvp_debug) {
2601 		kprintf("inefficient_scan of (%p,%s): directory iosize %ld "
2602 			"vattr fileid = %lld\n",
2603 			nch->ncp, nch->ncp->nc_name,
2604 			vat.va_blocksize,
2605 			(long long)vat.va_fileid);
2606 	}
2607 
2608 	/*
2609 	 * Use the supplied fakename if not NULL.  Fake names are typically
2610 	 * not in the actual filesystem hierarchy.  This is used by HAMMER
2611 	 * to glue @@timestamp recursions together.
2612 	 */
2613 	if (fakename) {
2614 		nlc.nlc_nameptr = fakename;
2615 		nlc.nlc_namelen = strlen(fakename);
2616 		rncp = cache_nlookup(nch, &nlc);
2617 		goto done;
2618 	}
2619 
2620 	if ((blksize = vat.va_blocksize) == 0)
2621 		blksize = DEV_BSIZE;
2622 	rbuf = kmalloc(blksize, M_TEMP, M_WAITOK);
2623 	rncp.ncp = NULL;
2624 
2625 	eofflag = 0;
2626 	uio.uio_offset = 0;
2627 again:
2628 	iov.iov_base = rbuf;
2629 	iov.iov_len = blksize;
2630 	uio.uio_iov = &iov;
2631 	uio.uio_iovcnt = 1;
2632 	uio.uio_resid = blksize;
2633 	uio.uio_segflg = UIO_SYSSPACE;
2634 	uio.uio_rw = UIO_READ;
2635 	uio.uio_td = curthread;
2636 
2637 	if (ncvp_debug >= 2)
2638 		kprintf("cache_inefficient_scan: readdir @ %08x\n", (int)uio.uio_offset);
2639 	error = VOP_READDIR(pvp, &uio, cred, &eofflag, NULL, NULL);
2640 	if (error == 0) {
2641 		den = (struct dirent *)rbuf;
2642 		bytes = blksize - uio.uio_resid;
2643 
2644 		while (bytes > 0) {
2645 			if (ncvp_debug >= 2) {
2646 				kprintf("cache_inefficient_scan: %*.*s\n",
2647 					den->d_namlen, den->d_namlen,
2648 					den->d_name);
2649 			}
2650 			if (den->d_type != DT_WHT &&
2651 			    den->d_ino == vat.va_fileid) {
2652 				if (ncvp_debug) {
2653 					kprintf("cache_inefficient_scan: "
2654 					       "MATCHED inode %lld path %s/%*.*s\n",
2655 					       (long long)vat.va_fileid,
2656 					       nch->ncp->nc_name,
2657 					       den->d_namlen, den->d_namlen,
2658 					       den->d_name);
2659 				}
2660 				nlc.nlc_nameptr = den->d_name;
2661 				nlc.nlc_namelen = den->d_namlen;
2662 				rncp = cache_nlookup(nch, &nlc);
2663 				KKASSERT(rncp.ncp != NULL);
2664 				break;
2665 			}
2666 			bytes -= _DIRENT_DIRSIZ(den);
2667 			den = _DIRENT_NEXT(den);
2668 		}
2669 		if (rncp.ncp == NULL && eofflag == 0 && uio.uio_resid != blksize)
2670 			goto again;
2671 	}
2672 	kfree(rbuf, M_TEMP);
2673 done:
2674 	vrele(pvp);
2675 	if (rncp.ncp) {
2676 		if (rncp.ncp->nc_flag & NCF_UNRESOLVED) {
2677 			_cache_setvp(rncp.mount, rncp.ncp, dvp);
2678 			if (ncvp_debug >= 2) {
2679 				kprintf("cache_inefficient_scan: setvp %s/%s = %p\n",
2680 					nch->ncp->nc_name, rncp.ncp->nc_name, dvp);
2681 			}
2682 		} else {
2683 			if (ncvp_debug >= 2) {
2684 				kprintf("cache_inefficient_scan: setvp %s/%s already set %p/%p\n",
2685 					nch->ncp->nc_name, rncp.ncp->nc_name, dvp,
2686 					rncp.ncp->nc_vp);
2687 			}
2688 		}
2689 		if (rncp.ncp->nc_vp == NULL)
2690 			error = rncp.ncp->nc_error;
2691 		/*
2692 		 * Release rncp after a successful nlookup.  rncp was fully
2693 		 * referenced.
2694 		 */
2695 		cache_put(&rncp);
2696 	} else {
2697 		kprintf("cache_inefficient_scan: dvp %p NOT FOUND in %s\n",
2698 			dvp, nch->ncp->nc_name);
2699 		error = ENOENT;
2700 	}
2701 	return (error);
2702 }
2703 
2704 /*
2705  * Zap a namecache entry.  The ncp is unconditionally set to an unresolved
2706  * state, which disassociates it from its vnode or pcpu_ncache[n].neg_list.
2707  *
2708  * Then, if there are no additional references to the ncp and no children,
2709  * the ncp is removed from the topology and destroyed.
2710  *
2711  * References and/or children may exist if the ncp is in the middle of the
2712  * topology, preventing the ncp from being destroyed.
2713  *
2714  * This function must be called with the ncp held and locked and will unlock
2715  * and drop it during zapping.
2716  *
2717  * If nonblock is non-zero and the parent ncp cannot be locked we give up.
2718  * This case can occur in the cache_drop() path.
2719  *
2720  * This function may returned a held (but NOT locked) parent node which the
2721  * caller must drop.  We do this so _cache_drop() can loop, to avoid
2722  * blowing out the kernel stack.
2723  *
2724  * WARNING!  For MPSAFE operation this routine must acquire up to three
2725  *	     spin locks to be able to safely test nc_refs.  Lock order is
2726  *	     very important.
2727  *
2728  *	     hash spinlock if on hash list
2729  *	     parent spinlock if child of parent
2730  *	     (the ncp is unresolved so there is no vnode association)
2731  */
2732 static struct namecache *
2733 cache_zap(struct namecache *ncp, int nonblock)
2734 {
2735 	struct namecache *par;
2736 	struct vnode *dropvp;
2737 	struct nchash_head *nchpp;
2738 	int refs;
2739 
2740 	/*
2741 	 * Disassociate the vnode or negative cache ref and set NCF_UNRESOLVED.
2742 	 */
2743 	_cache_setunresolved(ncp);
2744 
2745 	/*
2746 	 * Try to scrap the entry and possibly tail-recurse on its parent.
2747 	 * We only scrap unref'd (other then our ref) unresolved entries,
2748 	 * we do not scrap 'live' entries.
2749 	 *
2750 	 * Note that once the spinlocks are acquired if nc_refs == 1 no
2751 	 * other references are possible.  If it isn't, however, we have
2752 	 * to decrement but also be sure to avoid a 1->0 transition.
2753 	 */
2754 	KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
2755 	KKASSERT(ncp->nc_refs > 0);
2756 
2757 	/*
2758 	 * Acquire locks.  Note that the parent can't go away while we hold
2759 	 * a child locked.
2760 	 */
2761 	nchpp = NULL;
2762 	if ((par = ncp->nc_parent) != NULL) {
2763 		if (nonblock) {
2764 			for (;;) {
2765 				if (_cache_lock_nonblock(par) == 0)
2766 					break;
2767 				refs = ncp->nc_refs;
2768 				ncp->nc_flag |= NCF_DEFEREDZAP;
2769 				atomic_add_long(
2770 				    &pcpu_ncache[mycpu->gd_cpuid].numdefered,
2771 				    1);
2772 				if (atomic_cmpset_int(&ncp->nc_refs,
2773 						      refs, refs - 1)) {
2774 					_cache_unlock(ncp);
2775 					return(NULL);
2776 				}
2777 				cpu_pause();
2778 			}
2779 			_cache_hold(par);
2780 		} else {
2781 			_cache_hold(par);
2782 			_cache_lock(par);
2783 		}
2784 		nchpp = ncp->nc_head;
2785 		spin_lock(&nchpp->spin);
2786 	}
2787 
2788 	/*
2789 	 * At this point if we find refs == 1 it should not be possible for
2790 	 * anyone else to have access to the ncp.  We are holding the only
2791 	 * possible access point left (nchpp) spin-locked.
2792 	 *
2793 	 * If someone other then us has a ref or we have children
2794 	 * we cannot zap the entry.  The 1->0 transition and any
2795 	 * further list operation is protected by the spinlocks
2796 	 * we have acquired but other transitions are not.
2797 	 */
2798 	for (;;) {
2799 		refs = ncp->nc_refs;
2800 		cpu_ccfence();
2801 		if (refs == 1 && TAILQ_EMPTY(&ncp->nc_list))
2802 			break;
2803 		if (atomic_cmpset_int(&ncp->nc_refs, refs, refs - 1)) {
2804 			if (par) {
2805 				spin_unlock(&nchpp->spin);
2806 				_cache_put(par);
2807 			}
2808 			_cache_unlock(ncp);
2809 			return(NULL);
2810 		}
2811 		cpu_pause();
2812 	}
2813 
2814 	/*
2815 	 * We are the only ref and with the spinlocks held no further
2816 	 * refs can be acquired by others.
2817 	 *
2818 	 * Remove us from the hash list and parent list.  We have to
2819 	 * drop a ref on the parent's vp if the parent's list becomes
2820 	 * empty.
2821 	 */
2822 	dropvp = NULL;
2823 	if (par) {
2824 		struct pcpu_ncache *pn = &pcpu_ncache[mycpu->gd_cpuid];
2825 
2826 		KKASSERT(nchpp == ncp->nc_head);
2827 		TAILQ_REMOVE(&ncp->nc_head->list, ncp, nc_hash);
2828 		TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
2829 		atomic_add_long(&pn->vfscache_count, -1);
2830 		if (TAILQ_EMPTY(&ncp->nc_list))
2831 			atomic_add_long(&pn->vfscache_leafs, -1);
2832 
2833 		if (TAILQ_EMPTY(&par->nc_list)) {
2834 			atomic_add_long(&pn->vfscache_leafs, 1);
2835 			if (par->nc_vp)
2836 				dropvp = par->nc_vp;
2837 		}
2838 		ncp->nc_head = NULL;
2839 		ncp->nc_parent = NULL;
2840 		spin_unlock(&nchpp->spin);
2841 		_cache_unlock(par);
2842 	} else {
2843 		KKASSERT(ncp->nc_head == NULL);
2844 	}
2845 
2846 	/*
2847 	 * ncp should not have picked up any refs.  Physically
2848 	 * destroy the ncp.
2849 	 */
2850 	if (ncp->nc_refs != 1) {
2851 		int save_refs = ncp->nc_refs;
2852 		cpu_ccfence();
2853 		panic("cache_zap: %p bad refs %d (%d)\n",
2854 			ncp, save_refs, atomic_fetchadd_int(&ncp->nc_refs, 0));
2855 	}
2856 	KKASSERT(ncp->nc_refs == 1);
2857 	/* _cache_unlock(ncp) not required */
2858 	ncp->nc_refs = -1;	/* safety */
2859 	if (ncp->nc_name)
2860 		kfree(ncp->nc_name, M_VFSCACHE);
2861 	kfree(ncp, M_VFSCACHE);
2862 
2863 	/*
2864 	 * Delayed drop (we had to release our spinlocks)
2865 	 *
2866 	 * The refed parent (if not  NULL) must be dropped.  The
2867 	 * caller is responsible for looping.
2868 	 */
2869 	if (dropvp)
2870 		vdrop(dropvp);
2871 	return(par);
2872 }
2873 
2874 /*
2875  * Clean up dangling negative cache and defered-drop entries in the
2876  * namecache.
2877  *
2878  * This routine is called in the critical path and also called from
2879  * vnlru().  When called from vnlru we use a lower limit to try to
2880  * deal with the negative cache before the critical path has to start
2881  * dealing with it.
2882  */
2883 typedef enum { CHI_LOW, CHI_HIGH } cache_hs_t;
2884 
2885 static cache_hs_t neg_cache_hysteresis_state[2] = { CHI_LOW, CHI_LOW };
2886 static cache_hs_t pos_cache_hysteresis_state[2] = { CHI_LOW, CHI_LOW };
2887 
2888 void
2889 cache_hysteresis(int critpath)
2890 {
2891 	long poslimit;
2892 	long neglimit = maxvnodes / ncnegfactor;
2893 	long xnumcache = vfscache_leafs;
2894 
2895 	if (critpath == 0)
2896 		neglimit = neglimit * 8 / 10;
2897 
2898 	/*
2899 	 * Don't cache too many negative hits.  We use hysteresis to reduce
2900 	 * the impact on the critical path.
2901 	 */
2902 	switch(neg_cache_hysteresis_state[critpath]) {
2903 	case CHI_LOW:
2904 		if (vfscache_negs > MINNEG && vfscache_negs > neglimit) {
2905 			if (critpath)
2906 				_cache_cleanneg(ncnegflush);
2907 			else
2908 				_cache_cleanneg(ncnegflush +
2909 						vfscache_negs - neglimit);
2910 			neg_cache_hysteresis_state[critpath] = CHI_HIGH;
2911 		}
2912 		break;
2913 	case CHI_HIGH:
2914 		if (vfscache_negs > MINNEG * 9 / 10 &&
2915 		    vfscache_negs * 9 / 10 > neglimit
2916 		) {
2917 			if (critpath)
2918 				_cache_cleanneg(ncnegflush);
2919 			else
2920 				_cache_cleanneg(ncnegflush +
2921 						vfscache_negs * 9 / 10 -
2922 						neglimit);
2923 		} else {
2924 			neg_cache_hysteresis_state[critpath] = CHI_LOW;
2925 		}
2926 		break;
2927 	}
2928 
2929 	/*
2930 	 * Don't cache too many positive hits.  We use hysteresis to reduce
2931 	 * the impact on the critical path.
2932 	 *
2933 	 * Excessive positive hits can accumulate due to large numbers of
2934 	 * hardlinks (the vnode cache will not prevent hl ncps from growing
2935 	 * into infinity).
2936 	 */
2937 	if ((poslimit = ncposlimit) == 0)
2938 		poslimit = maxvnodes * 2;
2939 	if (critpath == 0)
2940 		poslimit = poslimit * 8 / 10;
2941 
2942 	switch(pos_cache_hysteresis_state[critpath]) {
2943 	case CHI_LOW:
2944 		if (xnumcache > poslimit && xnumcache > MINPOS) {
2945 			if (critpath)
2946 				_cache_cleanpos(ncposflush);
2947 			else
2948 				_cache_cleanpos(ncposflush +
2949 						xnumcache - poslimit);
2950 			pos_cache_hysteresis_state[critpath] = CHI_HIGH;
2951 		}
2952 		break;
2953 	case CHI_HIGH:
2954 		if (xnumcache > poslimit * 5 / 6 && xnumcache > MINPOS) {
2955 			if (critpath)
2956 				_cache_cleanpos(ncposflush);
2957 			else
2958 				_cache_cleanpos(ncposflush +
2959 						xnumcache - poslimit * 5 / 6);
2960 		} else {
2961 			pos_cache_hysteresis_state[critpath] = CHI_LOW;
2962 		}
2963 		break;
2964 	}
2965 
2966 	/*
2967 	 * Clean out dangling defered-zap ncps which could not be cleanly
2968 	 * dropped if too many build up.  Note that numdefered is
2969 	 * heuristical.  Make sure we are real-time for the current cpu,
2970 	 * plus the global rollup.
2971 	 */
2972 	if (pcpu_ncache[mycpu->gd_cpuid].numdefered + numdefered > neglimit) {
2973 		_cache_cleandefered();
2974 	}
2975 }
2976 
2977 /*
2978  * NEW NAMECACHE LOOKUP API
2979  *
2980  * Lookup an entry in the namecache.  The passed par_nch must be referenced
2981  * and unlocked.  A referenced and locked nchandle with a non-NULL nch.ncp
2982  * is ALWAYS returned, eve if the supplied component is illegal.
2983  *
2984  * The resulting namecache entry should be returned to the system with
2985  * cache_put() or cache_unlock() + cache_drop().
2986  *
2987  * namecache locks are recursive but care must be taken to avoid lock order
2988  * reversals (hence why the passed par_nch must be unlocked).  Locking
2989  * rules are to order for parent traversals, not for child traversals.
2990  *
2991  * Nobody else will be able to manipulate the associated namespace (e.g.
2992  * create, delete, rename, rename-target) until the caller unlocks the
2993  * entry.
2994  *
2995  * The returned entry will be in one of three states:  positive hit (non-null
2996  * vnode), negative hit (null vnode), or unresolved (NCF_UNRESOLVED is set).
2997  * Unresolved entries must be resolved through the filesystem to associate the
2998  * vnode and/or determine whether a positive or negative hit has occured.
2999  *
3000  * It is not necessary to lock a directory in order to lock namespace under
3001  * that directory.  In fact, it is explicitly not allowed to do that.  A
3002  * directory is typically only locked when being created, renamed, or
3003  * destroyed.
3004  *
3005  * The directory (par) may be unresolved, in which case any returned child
3006  * will likely also be marked unresolved.  Likely but not guarenteed.  Since
3007  * the filesystem lookup requires a resolved directory vnode the caller is
3008  * responsible for resolving the namecache chain top-down.  This API
3009  * specifically allows whole chains to be created in an unresolved state.
3010  */
3011 struct nchandle
3012 cache_nlookup(struct nchandle *par_nch, struct nlcomponent *nlc)
3013 {
3014 	struct nchandle nch;
3015 	struct namecache *ncp;
3016 	struct namecache *new_ncp;
3017 	struct namecache *rep_ncp;	/* reuse a destroyed ncp */
3018 	struct nchash_head *nchpp;
3019 	struct mount *mp;
3020 	u_int32_t hash;
3021 	globaldata_t gd;
3022 	int par_locked;
3023 
3024 	gd = mycpu;
3025 	mp = par_nch->mount;
3026 	par_locked = 0;
3027 
3028 	/*
3029 	 * This is a good time to call it, no ncp's are locked by
3030 	 * the caller or us.
3031 	 */
3032 	cache_hysteresis(1);
3033 
3034 	/*
3035 	 * Try to locate an existing entry
3036 	 */
3037 	hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
3038 	hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
3039 	new_ncp = NULL;
3040 	nchpp = NCHHASH(hash);
3041 restart:
3042 	rep_ncp = NULL;
3043 	if (new_ncp)
3044 		spin_lock(&nchpp->spin);
3045 	else
3046 		spin_lock_shared(&nchpp->spin);
3047 
3048 	TAILQ_FOREACH(ncp, &nchpp->list, nc_hash) {
3049 		/*
3050 		 * Break out if we find a matching entry.  Note that
3051 		 * UNRESOLVED entries may match, but DESTROYED entries
3052 		 * do not.
3053 		 *
3054 		 * We may be able to reuse DESTROYED entries that we come
3055 		 * across, even if the name does not match, as long as
3056 		 * nc_nlen is correct.
3057 		 */
3058 		if (ncp->nc_parent == par_nch->ncp &&
3059 		    ncp->nc_nlen == nlc->nlc_namelen) {
3060 			if (ncp->nc_flag & NCF_DESTROYED) {
3061 				if (ncp->nc_refs == 0 && rep_ncp == NULL)
3062 					rep_ncp = ncp;
3063 				continue;
3064 			}
3065 			if (bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen))
3066 				continue;
3067 			_cache_hold(ncp);
3068 			if (new_ncp)
3069 				spin_unlock(&nchpp->spin);
3070 			else
3071 				spin_unlock_shared(&nchpp->spin);
3072 			if (par_locked) {
3073 				_cache_unlock(par_nch->ncp);
3074 				par_locked = 0;
3075 			}
3076 			if (_cache_lock_special(ncp) == 0) {
3077 				/*
3078 				 * Successfully locked but we must re-test
3079 				 * conditions that might have changed since
3080 				 * we did not have the lock before.
3081 				 */
3082 				if (ncp->nc_parent != par_nch->ncp ||
3083 				    ncp->nc_nlen != nlc->nlc_namelen ||
3084 				    bcmp(ncp->nc_name, nlc->nlc_nameptr,
3085 					 ncp->nc_nlen) ||
3086 				    (ncp->nc_flag & NCF_DESTROYED)) {
3087 					_cache_put(ncp);
3088 					goto restart;
3089 				}
3090 				_cache_auto_unresolve(mp, ncp);
3091 				if (new_ncp)
3092 					_cache_free(new_ncp);
3093 				goto found;
3094 			}
3095 			_cache_get(ncp);	/* cycle the lock to block */
3096 			_cache_put(ncp);
3097 			_cache_drop(ncp);
3098 			goto restart;
3099 		}
3100 	}
3101 
3102 	/*
3103 	 * We failed to locate the entry, try to resurrect a destroyed
3104 	 * entry that we did find that is already correctly linked into
3105 	 * nchpp and the parent.  We must re-test conditions after
3106 	 * successfully locking rep_ncp.
3107 	 *
3108 	 * This case can occur under heavy loads due to not being able
3109 	 * to safely lock the parent in cache_zap().  Nominally a repeated
3110 	 * create/unlink load, but only the namelen needs to match.
3111 	 */
3112 	if (rep_ncp && new_ncp == NULL) {
3113 		if (_cache_lock_nonblock(rep_ncp) == 0) {
3114 			_cache_hold(rep_ncp);
3115 			if (rep_ncp->nc_parent == par_nch->ncp &&
3116 			    rep_ncp->nc_nlen == nlc->nlc_namelen &&
3117 			    (rep_ncp->nc_flag & NCF_DESTROYED)) {
3118 				/*
3119 				 * Update nc_name as reuse as new.
3120 				 */
3121 				ncp = rep_ncp;
3122 				bcopy(nlc->nlc_nameptr, ncp->nc_name,
3123 				      nlc->nlc_namelen);
3124 				spin_unlock_shared(&nchpp->spin);
3125 				_cache_setunresolved(ncp);
3126 				ncp->nc_flag = NCF_UNRESOLVED;
3127 				ncp->nc_error = ENOTCONN;
3128 				goto found;
3129 			}
3130 			_cache_put(rep_ncp);
3131 		}
3132 	}
3133 
3134 	/*
3135 	 * Otherwise create a new entry and add it to the cache.  The parent
3136 	 * ncp must also be locked so we can link into it.
3137 	 *
3138 	 * We have to relookup after possibly blocking in kmalloc or
3139 	 * when locking par_nch.
3140 	 *
3141 	 * NOTE: nlc_namelen can be 0 and nlc_nameptr NULL as a special
3142 	 *	 mount case, in which case nc_name will be NULL.
3143 	 */
3144 	if (new_ncp == NULL) {
3145 		spin_unlock_shared(&nchpp->spin);
3146 		new_ncp = cache_alloc(nlc->nlc_namelen);
3147 		if (nlc->nlc_namelen) {
3148 			bcopy(nlc->nlc_nameptr, new_ncp->nc_name,
3149 			      nlc->nlc_namelen);
3150 			new_ncp->nc_name[nlc->nlc_namelen] = 0;
3151 		}
3152 		goto restart;
3153 	}
3154 
3155 	/*
3156 	 * NOTE! The spinlock is held exclusively here because new_ncp
3157 	 *	 is non-NULL.
3158 	 */
3159 	if (par_locked == 0) {
3160 		spin_unlock(&nchpp->spin);
3161 		_cache_lock(par_nch->ncp);
3162 		par_locked = 1;
3163 		goto restart;
3164 	}
3165 
3166 	/*
3167 	 * WARNING!  We still hold the spinlock.  We have to set the hash
3168 	 *	     table entry atomically.
3169 	 */
3170 	ncp = new_ncp;
3171 	_cache_link_parent(ncp, par_nch->ncp, nchpp);
3172 	spin_unlock(&nchpp->spin);
3173 	_cache_unlock(par_nch->ncp);
3174 	/* par_locked = 0 - not used */
3175 found:
3176 	/*
3177 	 * stats and namecache size management
3178 	 */
3179 	if (ncp->nc_flag & NCF_UNRESOLVED)
3180 		++gd->gd_nchstats->ncs_miss;
3181 	else if (ncp->nc_vp)
3182 		++gd->gd_nchstats->ncs_goodhits;
3183 	else
3184 		++gd->gd_nchstats->ncs_neghits;
3185 	nch.mount = mp;
3186 	nch.ncp = ncp;
3187 	_cache_mntref(nch.mount);
3188 
3189 	return(nch);
3190 }
3191 
3192 /*
3193  * Attempt to lookup a namecache entry and return with a shared namecache
3194  * lock.
3195  */
3196 int
3197 cache_nlookup_maybe_shared(struct nchandle *par_nch, struct nlcomponent *nlc,
3198 			   int excl, struct nchandle *res_nch)
3199 {
3200 	struct namecache *ncp;
3201 	struct nchash_head *nchpp;
3202 	struct mount *mp;
3203 	u_int32_t hash;
3204 	globaldata_t gd;
3205 
3206 	/*
3207 	 * If exclusive requested or shared namecache locks are disabled,
3208 	 * return failure.
3209 	 */
3210 	if (ncp_shared_lock_disable || excl)
3211 		return(EWOULDBLOCK);
3212 
3213 	gd = mycpu;
3214 	mp = par_nch->mount;
3215 
3216 	/*
3217 	 * This is a good time to call it, no ncp's are locked by
3218 	 * the caller or us.
3219 	 */
3220 	cache_hysteresis(1);
3221 
3222 	/*
3223 	 * Try to locate an existing entry
3224 	 */
3225 	hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
3226 	hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
3227 	nchpp = NCHHASH(hash);
3228 
3229 	spin_lock_shared(&nchpp->spin);
3230 
3231 	TAILQ_FOREACH(ncp, &nchpp->list, nc_hash) {
3232 		/*
3233 		 * Break out if we find a matching entry.  Note that
3234 		 * UNRESOLVED entries may match, but DESTROYED entries
3235 		 * do not.
3236 		 */
3237 		if (ncp->nc_parent == par_nch->ncp &&
3238 		    ncp->nc_nlen == nlc->nlc_namelen &&
3239 		    bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
3240 		    (ncp->nc_flag & NCF_DESTROYED) == 0
3241 		) {
3242 			_cache_hold(ncp);
3243 			spin_unlock_shared(&nchpp->spin);
3244 			if (_cache_lock_shared_special(ncp) == 0) {
3245 				if (ncp->nc_parent == par_nch->ncp &&
3246 				    ncp->nc_nlen == nlc->nlc_namelen &&
3247 				    bcmp(ncp->nc_name, nlc->nlc_nameptr,
3248 					 ncp->nc_nlen) == 0 &&
3249 				    (ncp->nc_flag & NCF_DESTROYED) == 0 &&
3250 				    (ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
3251 				    _cache_auto_unresolve_test(mp, ncp) == 0) {
3252 					goto found;
3253 				}
3254 				_cache_unlock(ncp);
3255 			}
3256 			_cache_drop(ncp);
3257 			spin_lock_shared(&nchpp->spin);
3258 			break;
3259 		}
3260 	}
3261 
3262 	/*
3263 	 * Failure
3264 	 */
3265 	spin_unlock_shared(&nchpp->spin);
3266 	return(EWOULDBLOCK);
3267 
3268 	/*
3269 	 * Success
3270 	 *
3271 	 * Note that nc_error might be non-zero (e.g ENOENT).
3272 	 */
3273 found:
3274 	res_nch->mount = mp;
3275 	res_nch->ncp = ncp;
3276 	++gd->gd_nchstats->ncs_goodhits;
3277 	_cache_mntref(res_nch->mount);
3278 
3279 	KKASSERT(ncp->nc_error != EWOULDBLOCK);
3280 	return(ncp->nc_error);
3281 }
3282 
3283 /*
3284  * This is a non-blocking verison of cache_nlookup() used by
3285  * nfs_readdirplusrpc_uio().  It can fail for any reason and
3286  * will return nch.ncp == NULL in that case.
3287  */
3288 struct nchandle
3289 cache_nlookup_nonblock(struct nchandle *par_nch, struct nlcomponent *nlc)
3290 {
3291 	struct nchandle nch;
3292 	struct namecache *ncp;
3293 	struct namecache *new_ncp;
3294 	struct nchash_head *nchpp;
3295 	struct mount *mp;
3296 	u_int32_t hash;
3297 	globaldata_t gd;
3298 	int par_locked;
3299 
3300 	gd = mycpu;
3301 	mp = par_nch->mount;
3302 	par_locked = 0;
3303 
3304 	/*
3305 	 * Try to locate an existing entry
3306 	 */
3307 	hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
3308 	hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
3309 	new_ncp = NULL;
3310 	nchpp = NCHHASH(hash);
3311 restart:
3312 	spin_lock(&nchpp->spin);
3313 	TAILQ_FOREACH(ncp, &nchpp->list, nc_hash) {
3314 		/*
3315 		 * Break out if we find a matching entry.  Note that
3316 		 * UNRESOLVED entries may match, but DESTROYED entries
3317 		 * do not.
3318 		 */
3319 		if (ncp->nc_parent == par_nch->ncp &&
3320 		    ncp->nc_nlen == nlc->nlc_namelen &&
3321 		    bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
3322 		    (ncp->nc_flag & NCF_DESTROYED) == 0
3323 		) {
3324 			_cache_hold(ncp);
3325 			spin_unlock(&nchpp->spin);
3326 			if (par_locked) {
3327 				_cache_unlock(par_nch->ncp);
3328 				par_locked = 0;
3329 			}
3330 			if (_cache_lock_special(ncp) == 0) {
3331 				if (ncp->nc_parent != par_nch->ncp ||
3332 				    ncp->nc_nlen != nlc->nlc_namelen ||
3333 				    bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) ||
3334 				    (ncp->nc_flag & NCF_DESTROYED)) {
3335 					kprintf("cache_lookup_nonblock: "
3336 						"ncp-race %p %*.*s\n",
3337 						ncp,
3338 						nlc->nlc_namelen,
3339 						nlc->nlc_namelen,
3340 						nlc->nlc_nameptr);
3341 					_cache_unlock(ncp);
3342 					_cache_drop(ncp);
3343 					goto failed;
3344 				}
3345 				_cache_auto_unresolve(mp, ncp);
3346 				if (new_ncp) {
3347 					_cache_free(new_ncp);
3348 					new_ncp = NULL;
3349 				}
3350 				goto found;
3351 			}
3352 			_cache_drop(ncp);
3353 			goto failed;
3354 		}
3355 	}
3356 
3357 	/*
3358 	 * We failed to locate an entry, create a new entry and add it to
3359 	 * the cache.  The parent ncp must also be locked so we
3360 	 * can link into it.
3361 	 *
3362 	 * We have to relookup after possibly blocking in kmalloc or
3363 	 * when locking par_nch.
3364 	 *
3365 	 * NOTE: nlc_namelen can be 0 and nlc_nameptr NULL as a special
3366 	 *	 mount case, in which case nc_name will be NULL.
3367 	 */
3368 	if (new_ncp == NULL) {
3369 		spin_unlock(&nchpp->spin);
3370 		new_ncp = cache_alloc(nlc->nlc_namelen);
3371 		if (nlc->nlc_namelen) {
3372 			bcopy(nlc->nlc_nameptr, new_ncp->nc_name,
3373 			      nlc->nlc_namelen);
3374 			new_ncp->nc_name[nlc->nlc_namelen] = 0;
3375 		}
3376 		goto restart;
3377 	}
3378 	if (par_locked == 0) {
3379 		spin_unlock(&nchpp->spin);
3380 		if (_cache_lock_nonblock(par_nch->ncp) == 0) {
3381 			par_locked = 1;
3382 			goto restart;
3383 		}
3384 		goto failed;
3385 	}
3386 
3387 	/*
3388 	 * WARNING!  We still hold the spinlock.  We have to set the hash
3389 	 *	     table entry atomically.
3390 	 */
3391 	ncp = new_ncp;
3392 	_cache_link_parent(ncp, par_nch->ncp, nchpp);
3393 	spin_unlock(&nchpp->spin);
3394 	_cache_unlock(par_nch->ncp);
3395 	/* par_locked = 0 - not used */
3396 found:
3397 	/*
3398 	 * stats and namecache size management
3399 	 */
3400 	if (ncp->nc_flag & NCF_UNRESOLVED)
3401 		++gd->gd_nchstats->ncs_miss;
3402 	else if (ncp->nc_vp)
3403 		++gd->gd_nchstats->ncs_goodhits;
3404 	else
3405 		++gd->gd_nchstats->ncs_neghits;
3406 	nch.mount = mp;
3407 	nch.ncp = ncp;
3408 	_cache_mntref(nch.mount);
3409 
3410 	return(nch);
3411 failed:
3412 	if (new_ncp) {
3413 		_cache_free(new_ncp);
3414 		new_ncp = NULL;
3415 	}
3416 	nch.mount = NULL;
3417 	nch.ncp = NULL;
3418 	return(nch);
3419 }
3420 
3421 /*
3422  * The namecache entry is marked as being used as a mount point.
3423  * Locate the mount if it is visible to the caller.  The DragonFly
3424  * mount system allows arbitrary loops in the topology and disentangles
3425  * those loops by matching against (mp, ncp) rather than just (ncp).
3426  * This means any given ncp can dive any number of mounts, depending
3427  * on the relative mount (e.g. nullfs) the caller is at in the topology.
3428  *
3429  * We use a very simple frontend cache to reduce SMP conflicts,
3430  * which we have to do because the mountlist scan needs an exclusive
3431  * lock around its ripout info list.  Not to mention that there might
3432  * be a lot of mounts.
3433  *
3434  * The hash table is 4-way set-associative and will either return the
3435  * matching slot or the best slot to reuse.
3436  */
3437 struct findmount_info {
3438 	struct mount *result;
3439 	struct mount *nch_mount;
3440 	struct namecache *nch_ncp;
3441 };
3442 
3443 static
3444 struct ncmount_cache *
3445 ncmount_cache_lookup4(struct mount *mp, struct namecache *ncp)
3446 {
3447 	uintptr_t hash;
3448 
3449 	hash = ((uintptr_t)mp / sizeof(*mp)) *
3450 		((uintptr_t)ncp / sizeof(*ncp));
3451 	hash ^= (uintptr_t)ncp >> 12;
3452 	hash ^= (uintptr_t)mp >> 12;
3453 	hash = hash & ((NCMOUNT_NUMCACHE - 1) & ~3);
3454 
3455 	return (&ncmount_cache[hash]);
3456 }
3457 
3458 static
3459 struct ncmount_cache *
3460 ncmount_cache_lookup(struct mount *mp, struct namecache *ncp)
3461 {
3462 	struct ncmount_cache *ncc;
3463 	struct ncmount_cache *best;
3464 	uintptr_t hash;
3465 	int delta;
3466 	int best_delta;
3467 	int i;
3468 
3469 	hash = ((uintptr_t)mp / sizeof(*mp)) *
3470 		((uintptr_t)ncp / sizeof(*ncp));
3471 	hash ^= (uintptr_t)ncp >> 12;
3472 	hash ^= (uintptr_t)mp >> 12;
3473 	hash = hash & ((NCMOUNT_NUMCACHE - 1) & ~3);
3474 
3475 	ncc = &ncmount_cache[hash];
3476 
3477 	/*
3478 	 * NOTE: When checking for a ticks overflow implement a slop of
3479 	 *	 2 ticks just to be safe, because ticks is accessed
3480 	 *	 non-atomically one CPU can increment it while another
3481 	 *	 is still using the old value.
3482 	 */
3483 	if (ncc->mp == mp && ncc->ncp == ncp)	/* 0 */
3484 		return ncc;
3485 	delta = (int)(ticks - ncc->ticks);	/* beware GCC opts */
3486 	if (delta < -2)				/* overflow reset */
3487 		ncc->ticks = ticks;
3488 	best = ncc;
3489 	best_delta = delta;
3490 
3491 	for (i = 1; i < 4; ++i) {		/* 1, 2, 3 */
3492 		++ncc;
3493 		if (ncc->mp == mp && ncc->ncp == ncp)
3494 			return ncc;
3495 		delta = (int)(ticks - ncc->ticks);
3496 		if (delta < -2)
3497 			ncc->ticks = ticks;
3498 		if (delta > best_delta) {
3499 			best_delta = delta;
3500 			best = ncc;
3501 		}
3502 	}
3503 	return best;
3504 }
3505 
3506 static
3507 int
3508 cache_findmount_callback(struct mount *mp, void *data)
3509 {
3510 	struct findmount_info *info = data;
3511 
3512 	/*
3513 	 * Check the mount's mounted-on point against the passed nch.
3514 	 */
3515 	if (mp->mnt_ncmounton.mount == info->nch_mount &&
3516 	    mp->mnt_ncmounton.ncp == info->nch_ncp
3517 	) {
3518 	    info->result = mp;
3519 	    _cache_mntref(mp);
3520 	    return(-1);
3521 	}
3522 	return(0);
3523 }
3524 
3525 /*
3526  * Find the recursive mountpoint (mp, ncp) -> mtpt
3527  */
3528 struct mount *
3529 cache_findmount(struct nchandle *nch)
3530 {
3531 	struct findmount_info info;
3532 	struct ncmount_cache *ncc;
3533 	struct mount *mp;
3534 
3535 	/*
3536 	 * Fast
3537 	 */
3538 	if (ncmount_cache_enable == 0) {
3539 		ncc = NULL;
3540 		goto skip;
3541 	}
3542 	ncc = ncmount_cache_lookup(nch->mount, nch->ncp);
3543 	if (ncc->ncp == nch->ncp) {
3544 		spin_lock_shared(&ncc->spin);
3545 		if (ncc->isneg == 0 &&
3546 		    ncc->ncp == nch->ncp && (mp = ncc->mp) != NULL) {
3547 			if (mp->mnt_ncmounton.mount == nch->mount &&
3548 			    mp->mnt_ncmounton.ncp == nch->ncp) {
3549 				/*
3550 				 * Cache hit (positive) (avoid dirtying
3551 				 * the cache line if possible)
3552 				 */
3553 				if (ncc->ticks != (int)ticks)
3554 					ncc->ticks = (int)ticks;
3555 				_cache_mntref(mp);
3556 				spin_unlock_shared(&ncc->spin);
3557 				return(mp);
3558 			}
3559 			/* else cache miss */
3560 		}
3561 		if (ncc->isneg &&
3562 		    ncc->ncp == nch->ncp && ncc->mp == nch->mount) {
3563 			/*
3564 			 * Cache hit (negative) (avoid dirtying
3565 			 * the cache line if possible)
3566 			 */
3567 			if (ncc->ticks != (int)ticks)
3568 				ncc->ticks = (int)ticks;
3569 			spin_unlock_shared(&ncc->spin);
3570 			return(NULL);
3571 		}
3572 		spin_unlock_shared(&ncc->spin);
3573 	}
3574 skip:
3575 
3576 	/*
3577 	 * Slow
3578 	 */
3579 	info.result = NULL;
3580 	info.nch_mount = nch->mount;
3581 	info.nch_ncp = nch->ncp;
3582 	mountlist_scan(cache_findmount_callback, &info,
3583 		       MNTSCAN_FORWARD | MNTSCAN_NOBUSY | MNTSCAN_NOUNLOCK);
3584 
3585 	/*
3586 	 * Cache the result.
3587 	 *
3588 	 * Negative lookups: We cache the originating {ncp,mp}. (mp) is
3589 	 *		     only used for pointer comparisons and is not
3590 	 *		     referenced (otherwise there would be dangling
3591 	 *		     refs).
3592 	 *
3593 	 * Positive lookups: We cache the originating {ncp} and the target
3594 	 *		     (mp).  (mp) is referenced.
3595 	 *
3596 	 * Indeterminant:    If the match is undergoing an unmount we do
3597 	 *		     not cache it to avoid racing cache_unmounting(),
3598 	 *		     but still return the match.
3599 	 */
3600 	if (ncc) {
3601 		spin_lock(&ncc->spin);
3602 		if (info.result == NULL) {
3603 			if (ncc->isneg == 0 && ncc->mp)
3604 				_cache_mntrel(ncc->mp);
3605 			ncc->ncp = nch->ncp;
3606 			ncc->mp = nch->mount;
3607 			ncc->isneg = 1;
3608 			ncc->ticks = (int)ticks;
3609 			spin_unlock(&ncc->spin);
3610 		} else if ((info.result->mnt_kern_flag & MNTK_UNMOUNT) == 0) {
3611 			if (ncc->isneg == 0 && ncc->mp)
3612 				_cache_mntrel(ncc->mp);
3613 			_cache_mntref(info.result);
3614 			ncc->ncp = nch->ncp;
3615 			ncc->mp = info.result;
3616 			ncc->isneg = 0;
3617 			ncc->ticks = (int)ticks;
3618 			spin_unlock(&ncc->spin);
3619 		} else {
3620 			spin_unlock(&ncc->spin);
3621 		}
3622 	}
3623 	return(info.result);
3624 }
3625 
3626 void
3627 cache_dropmount(struct mount *mp)
3628 {
3629 	_cache_mntrel(mp);
3630 }
3631 
3632 void
3633 cache_ismounting(struct mount *mp)
3634 {
3635 	struct nchandle *nch = &mp->mnt_ncmounton;
3636 	struct ncmount_cache *ncc;
3637 	int i;
3638 
3639 	ncc = ncmount_cache_lookup4(nch->mount, nch->ncp);
3640 	for (i = 0; i < 4; ++i) {
3641 		if (ncc->isneg &&
3642 		    ncc->ncp == nch->ncp && ncc->mp == nch->mount) {
3643 			spin_lock(&ncc->spin);
3644 			if (ncc->isneg &&
3645 			    ncc->ncp == nch->ncp && ncc->mp == nch->mount) {
3646 				ncc->ncp = NULL;
3647 				ncc->mp = NULL;
3648 				ncc->ticks = (int)ticks - hz * 120;
3649 			}
3650 			spin_unlock(&ncc->spin);
3651 		}
3652 		++ncc;
3653 	}
3654 }
3655 
3656 void
3657 cache_unmounting(struct mount *mp)
3658 {
3659 	struct nchandle *nch = &mp->mnt_ncmounton;
3660 	struct ncmount_cache *ncc;
3661 	int i;
3662 
3663 	ncc = ncmount_cache_lookup4(nch->mount, nch->ncp);
3664 	for (i = 0; i < 4; ++i) {
3665 		if (ncc->isneg == 0 &&
3666 		    ncc->ncp == nch->ncp && ncc->mp == mp) {
3667 			spin_lock(&ncc->spin);
3668 			if (ncc->isneg == 0 &&
3669 			    ncc->ncp == nch->ncp && ncc->mp == mp) {
3670 				_cache_mntrel(mp);
3671 				ncc->ncp = NULL;
3672 				ncc->mp = NULL;
3673 				ncc->ticks = (int)ticks - hz * 120;
3674 			}
3675 			spin_unlock(&ncc->spin);
3676 		}
3677 		++ncc;
3678 	}
3679 }
3680 
3681 /*
3682  * Resolve an unresolved namecache entry, generally by looking it up.
3683  * The passed ncp must be locked and refd.
3684  *
3685  * Theoretically since a vnode cannot be recycled while held, and since
3686  * the nc_parent chain holds its vnode as long as children exist, the
3687  * direct parent of the cache entry we are trying to resolve should
3688  * have a valid vnode.  If not then generate an error that we can
3689  * determine is related to a resolver bug.
3690  *
3691  * However, if a vnode was in the middle of a recyclement when the NCP
3692  * got locked, ncp->nc_vp might point to a vnode that is about to become
3693  * invalid.  cache_resolve() handles this case by unresolving the entry
3694  * and then re-resolving it.
3695  *
3696  * Note that successful resolution does not necessarily return an error
3697  * code of 0.  If the ncp resolves to a negative cache hit then ENOENT
3698  * will be returned.
3699  */
3700 int
3701 cache_resolve(struct nchandle *nch, struct ucred *cred)
3702 {
3703 	struct namecache *par_tmp;
3704 	struct namecache *par;
3705 	struct namecache *ncp;
3706 	struct nchandle nctmp;
3707 	struct mount *mp;
3708 	struct vnode *dvp;
3709 	int error;
3710 
3711 	ncp = nch->ncp;
3712 	mp = nch->mount;
3713 	KKASSERT(_cache_lockstatus(ncp) == LK_EXCLUSIVE);
3714 restart:
3715 	/*
3716 	 * If the ncp is already resolved we have nothing to do.  However,
3717 	 * we do want to guarentee that a usable vnode is returned when
3718 	 * a vnode is present, so make sure it hasn't been reclaimed.
3719 	 */
3720 	if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
3721 		if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
3722 			_cache_setunresolved(ncp);
3723 		if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
3724 			return (ncp->nc_error);
3725 	}
3726 
3727 	/*
3728 	 * If the ncp was destroyed it will never resolve again.  This
3729 	 * can basically only happen when someone is chdir'd into an
3730 	 * empty directory which is then rmdir'd.  We want to catch this
3731 	 * here and not dive the VFS because the VFS might actually
3732 	 * have a way to re-resolve the disconnected ncp, which will
3733 	 * result in inconsistencies in the cdir/nch for proc->p_fd.
3734 	 */
3735 	if (ncp->nc_flag & NCF_DESTROYED)
3736 		return(EINVAL);
3737 
3738 	/*
3739 	 * Mount points need special handling because the parent does not
3740 	 * belong to the same filesystem as the ncp.
3741 	 */
3742 	if (ncp == mp->mnt_ncmountpt.ncp)
3743 		return (cache_resolve_mp(mp));
3744 
3745 	/*
3746 	 * We expect an unbroken chain of ncps to at least the mount point,
3747 	 * and even all the way to root (but this code doesn't have to go
3748 	 * past the mount point).
3749 	 */
3750 	if (ncp->nc_parent == NULL) {
3751 		kprintf("EXDEV case 1 %p %*.*s\n", ncp,
3752 			ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
3753 		ncp->nc_error = EXDEV;
3754 		return(ncp->nc_error);
3755 	}
3756 
3757 	/*
3758 	 * The vp's of the parent directories in the chain are held via vhold()
3759 	 * due to the existance of the child, and should not disappear.
3760 	 * However, there are cases where they can disappear:
3761 	 *
3762 	 *	- due to filesystem I/O errors.
3763 	 *	- due to NFS being stupid about tracking the namespace and
3764 	 *	  destroys the namespace for entire directories quite often.
3765 	 *	- due to forced unmounts.
3766 	 *	- due to an rmdir (parent will be marked DESTROYED)
3767 	 *
3768 	 * When this occurs we have to track the chain backwards and resolve
3769 	 * it, looping until the resolver catches up to the current node.  We
3770 	 * could recurse here but we might run ourselves out of kernel stack
3771 	 * so we do it in a more painful manner.  This situation really should
3772 	 * not occur all that often, or if it does not have to go back too
3773 	 * many nodes to resolve the ncp.
3774 	 */
3775 	while ((dvp = cache_dvpref(ncp)) == NULL) {
3776 		/*
3777 		 * This case can occur if a process is CD'd into a
3778 		 * directory which is then rmdir'd.  If the parent is marked
3779 		 * destroyed there is no point trying to resolve it.
3780 		 */
3781 		if (ncp->nc_parent->nc_flag & NCF_DESTROYED)
3782 			return(ENOENT);
3783 		par = ncp->nc_parent;
3784 		_cache_hold(par);
3785 		_cache_lock(par);
3786 		while ((par_tmp = par->nc_parent) != NULL &&
3787 		       par_tmp->nc_vp == NULL) {
3788 			_cache_hold(par_tmp);
3789 			_cache_lock(par_tmp);
3790 			_cache_put(par);
3791 			par = par_tmp;
3792 		}
3793 		if (par->nc_parent == NULL) {
3794 			kprintf("EXDEV case 2 %*.*s\n",
3795 				par->nc_nlen, par->nc_nlen, par->nc_name);
3796 			_cache_put(par);
3797 			return (EXDEV);
3798 		}
3799 		/*
3800 		 * The parent is not set in stone, ref and lock it to prevent
3801 		 * it from disappearing.  Also note that due to renames it
3802 		 * is possible for our ncp to move and for par to no longer
3803 		 * be one of its parents.  We resolve it anyway, the loop
3804 		 * will handle any moves.
3805 		 */
3806 		_cache_get(par);	/* additional hold/lock */
3807 		_cache_put(par);	/* from earlier hold/lock */
3808 		if (par == nch->mount->mnt_ncmountpt.ncp) {
3809 			cache_resolve_mp(nch->mount);
3810 		} else if ((dvp = cache_dvpref(par)) == NULL) {
3811 			kprintf("[diagnostic] cache_resolve: raced on %*.*s\n", par->nc_nlen, par->nc_nlen, par->nc_name);
3812 			_cache_put(par);
3813 			continue;
3814 		} else {
3815 			if (par->nc_flag & NCF_UNRESOLVED) {
3816 				nctmp.mount = mp;
3817 				nctmp.ncp = par;
3818 				par->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
3819 			}
3820 			vrele(dvp);
3821 		}
3822 		if ((error = par->nc_error) != 0) {
3823 			if (par->nc_error != EAGAIN) {
3824 				kprintf("EXDEV case 3 %*.*s error %d\n",
3825 				    par->nc_nlen, par->nc_nlen, par->nc_name,
3826 				    par->nc_error);
3827 				_cache_put(par);
3828 				return(error);
3829 			}
3830 			kprintf("[diagnostic] cache_resolve: EAGAIN par %p %*.*s\n",
3831 				par, par->nc_nlen, par->nc_nlen, par->nc_name);
3832 		}
3833 		_cache_put(par);
3834 		/* loop */
3835 	}
3836 
3837 	/*
3838 	 * Call VOP_NRESOLVE() to get the vp, then scan for any disconnected
3839 	 * ncp's and reattach them.  If this occurs the original ncp is marked
3840 	 * EAGAIN to force a relookup.
3841 	 *
3842 	 * NOTE: in order to call VOP_NRESOLVE(), the parent of the passed
3843 	 * ncp must already be resolved.
3844 	 */
3845 	if (dvp) {
3846 		nctmp.mount = mp;
3847 		nctmp.ncp = ncp;
3848 		ncp->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
3849 		vrele(dvp);
3850 	} else {
3851 		ncp->nc_error = EPERM;
3852 	}
3853 	if (ncp->nc_error == EAGAIN) {
3854 		kprintf("[diagnostic] cache_resolve: EAGAIN ncp %p %*.*s\n",
3855 			ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
3856 		goto restart;
3857 	}
3858 	return(ncp->nc_error);
3859 }
3860 
3861 /*
3862  * Resolve the ncp associated with a mount point.  Such ncp's almost always
3863  * remain resolved and this routine is rarely called.  NFS MPs tends to force
3864  * re-resolution more often due to its mac-truck-smash-the-namecache
3865  * method of tracking namespace changes.
3866  *
3867  * The semantics for this call is that the passed ncp must be locked on
3868  * entry and will be locked on return.  However, if we actually have to
3869  * resolve the mount point we temporarily unlock the entry in order to
3870  * avoid race-to-root deadlocks due to e.g. dead NFS mounts.  Because of
3871  * the unlock we have to recheck the flags after we relock.
3872  */
3873 static int
3874 cache_resolve_mp(struct mount *mp)
3875 {
3876 	struct namecache *ncp = mp->mnt_ncmountpt.ncp;
3877 	struct vnode *vp;
3878 	int error;
3879 
3880 	KKASSERT(mp != NULL);
3881 
3882 	/*
3883 	 * If the ncp is already resolved we have nothing to do.  However,
3884 	 * we do want to guarentee that a usable vnode is returned when
3885 	 * a vnode is present, so make sure it hasn't been reclaimed.
3886 	 */
3887 	if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
3888 		if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
3889 			_cache_setunresolved(ncp);
3890 	}
3891 
3892 	if (ncp->nc_flag & NCF_UNRESOLVED) {
3893 		_cache_unlock(ncp);
3894 		while (vfs_busy(mp, 0))
3895 			;
3896 		error = VFS_ROOT(mp, &vp);
3897 		_cache_lock(ncp);
3898 
3899 		/*
3900 		 * recheck the ncp state after relocking.
3901 		 */
3902 		if (ncp->nc_flag & NCF_UNRESOLVED) {
3903 			ncp->nc_error = error;
3904 			if (error == 0) {
3905 				_cache_setvp(mp, ncp, vp);
3906 				vput(vp);
3907 			} else {
3908 				kprintf("[diagnostic] cache_resolve_mp: failed"
3909 					" to resolve mount %p err=%d ncp=%p\n",
3910 					mp, error, ncp);
3911 				_cache_setvp(mp, ncp, NULL);
3912 			}
3913 		} else if (error == 0) {
3914 			vput(vp);
3915 		}
3916 		vfs_unbusy(mp);
3917 	}
3918 	return(ncp->nc_error);
3919 }
3920 
3921 /*
3922  * Clean out negative cache entries when too many have accumulated.
3923  */
3924 static void
3925 _cache_cleanneg(long count)
3926 {
3927 	struct pcpu_ncache *pn;
3928 	struct namecache *ncp;
3929 	static uint32_t neg_rover;
3930 	uint32_t n;
3931 	long vnegs;
3932 
3933 	n = neg_rover++;	/* SMP heuristical, race ok */
3934 	cpu_ccfence();
3935 	n = n % (uint32_t)ncpus;
3936 
3937 	/*
3938 	 * Normalize vfscache_negs and count.  count is sometimes based
3939 	 * on vfscache_negs.  vfscache_negs is heuristical and can sometimes
3940 	 * have crazy values.
3941 	 */
3942 	vnegs = vfscache_negs;
3943 	cpu_ccfence();
3944 	if (vnegs <= MINNEG)
3945 		vnegs = MINNEG;
3946 	if (count < 1)
3947 		count = 1;
3948 
3949 	pn = &pcpu_ncache[n];
3950 	spin_lock(&pn->neg_spin);
3951 	count = pn->neg_count * count / vnegs + 1;
3952 	spin_unlock(&pn->neg_spin);
3953 
3954 	/*
3955 	 * Attempt to clean out the specified number of negative cache
3956 	 * entries.
3957 	 */
3958 	while (count > 0) {
3959 		spin_lock(&pn->neg_spin);
3960 		ncp = TAILQ_FIRST(&pn->neg_list);
3961 		if (ncp == NULL) {
3962 			spin_unlock(&pn->neg_spin);
3963 			break;
3964 		}
3965 		TAILQ_REMOVE(&pn->neg_list, ncp, nc_vnode);
3966 		TAILQ_INSERT_TAIL(&pn->neg_list, ncp, nc_vnode);
3967 		_cache_hold(ncp);
3968 		spin_unlock(&pn->neg_spin);
3969 
3970 		/*
3971 		 * This can race, so we must re-check that the ncp
3972 		 * is on the ncneg.list after successfully locking it.
3973 		 */
3974 		if (_cache_lock_special(ncp) == 0) {
3975 			if (ncp->nc_vp == NULL &&
3976 			    (ncp->nc_flag & NCF_UNRESOLVED) == 0) {
3977 				ncp = cache_zap(ncp, 1);
3978 				if (ncp)
3979 					_cache_drop(ncp);
3980 			} else {
3981 				_cache_unlock(ncp);
3982 				_cache_drop(ncp);
3983 			}
3984 		} else {
3985 			_cache_drop(ncp);
3986 		}
3987 		--count;
3988 	}
3989 }
3990 
3991 /*
3992  * Clean out positive cache entries when too many have accumulated.
3993  */
3994 static void
3995 _cache_cleanpos(long count)
3996 {
3997 	static volatile int rover;
3998 	struct nchash_head *nchpp;
3999 	struct namecache *ncp;
4000 	int rover_copy;
4001 
4002 	/*
4003 	 * Attempt to clean out the specified number of negative cache
4004 	 * entries.
4005 	 */
4006 	while (count > 0) {
4007 		rover_copy = ++rover;	/* MPSAFEENOUGH */
4008 		cpu_ccfence();
4009 		nchpp = NCHHASH(rover_copy);
4010 
4011 		if (TAILQ_FIRST(&nchpp->list) == NULL) {
4012 			--count;
4013 			continue;
4014 		}
4015 
4016 		/*
4017 		 * Cycle ncp on list, ignore and do not move DUMMY
4018 		 * ncps.  These are temporary list iterators.
4019 		 *
4020 		 * We must cycle the ncp to the end of the list to
4021 		 * ensure that all ncp's have an equal chance of
4022 		 * being removed.
4023 		 */
4024 		spin_lock(&nchpp->spin);
4025 		ncp = TAILQ_FIRST(&nchpp->list);
4026 		while (ncp && (ncp->nc_flag & NCF_DUMMY))
4027 			ncp = TAILQ_NEXT(ncp, nc_hash);
4028 		if (ncp) {
4029 			TAILQ_REMOVE(&nchpp->list, ncp, nc_hash);
4030 			TAILQ_INSERT_TAIL(&nchpp->list, ncp, nc_hash);
4031 			_cache_hold(ncp);
4032 		}
4033 		spin_unlock(&nchpp->spin);
4034 
4035 		if (ncp) {
4036 			if (_cache_lock_special(ncp) == 0) {
4037 				ncp = cache_zap(ncp, 1);
4038 				if (ncp)
4039 					_cache_drop(ncp);
4040 			} else {
4041 				_cache_drop(ncp);
4042 			}
4043 		}
4044 		--count;
4045 	}
4046 }
4047 
4048 /*
4049  * This is a kitchen sink function to clean out ncps which we
4050  * tried to zap from cache_drop() but failed because we were
4051  * unable to acquire the parent lock.
4052  *
4053  * Such entries can also be removed via cache_inval_vp(), such
4054  * as when unmounting.
4055  */
4056 static void
4057 _cache_cleandefered(void)
4058 {
4059 	struct nchash_head *nchpp;
4060 	struct namecache *ncp;
4061 	struct namecache dummy;
4062 	int i;
4063 
4064 	/*
4065 	 * Create a list iterator.  DUMMY indicates that this is a list
4066 	 * iterator, DESTROYED prevents matches by lookup functions.
4067 	 */
4068 	numdefered = 0;
4069 	pcpu_ncache[mycpu->gd_cpuid].numdefered = 0;
4070 	bzero(&dummy, sizeof(dummy));
4071 	dummy.nc_flag = NCF_DESTROYED | NCF_DUMMY;
4072 	dummy.nc_refs = 1;
4073 
4074 	for (i = 0; i <= nchash; ++i) {
4075 		nchpp = &nchashtbl[i];
4076 
4077 		spin_lock(&nchpp->spin);
4078 		TAILQ_INSERT_HEAD(&nchpp->list, &dummy, nc_hash);
4079 		ncp = &dummy;
4080 		while ((ncp = TAILQ_NEXT(ncp, nc_hash)) != NULL) {
4081 			if ((ncp->nc_flag & NCF_DEFEREDZAP) == 0)
4082 				continue;
4083 			TAILQ_REMOVE(&nchpp->list, &dummy, nc_hash);
4084 			TAILQ_INSERT_AFTER(&nchpp->list, ncp, &dummy, nc_hash);
4085 			_cache_hold(ncp);
4086 			spin_unlock(&nchpp->spin);
4087 			if (_cache_lock_nonblock(ncp) == 0) {
4088 				ncp->nc_flag &= ~NCF_DEFEREDZAP;
4089 				_cache_unlock(ncp);
4090 			}
4091 			_cache_drop(ncp);
4092 			spin_lock(&nchpp->spin);
4093 			ncp = &dummy;
4094 		}
4095 		TAILQ_REMOVE(&nchpp->list, &dummy, nc_hash);
4096 		spin_unlock(&nchpp->spin);
4097 	}
4098 }
4099 
4100 /*
4101  * Name cache initialization, from vfsinit() when we are booting
4102  */
4103 void
4104 nchinit(void)
4105 {
4106 	struct pcpu_ncache *pn;
4107 	globaldata_t gd;
4108 	int i;
4109 
4110 	/*
4111 	 * Per-cpu accounting and negative hit list
4112 	 */
4113 	pcpu_ncache = kmalloc(sizeof(*pcpu_ncache) * ncpus,
4114 			      M_VFSCACHE, M_WAITOK|M_ZERO);
4115 	for (i = 0; i < ncpus; ++i) {
4116 		pn = &pcpu_ncache[i];
4117 		TAILQ_INIT(&pn->neg_list);
4118 		spin_init(&pn->neg_spin, "ncneg");
4119 	}
4120 
4121 	/*
4122 	 * Initialise per-cpu namecache effectiveness statistics.
4123 	 */
4124 	for (i = 0; i < ncpus; ++i) {
4125 		gd = globaldata_find(i);
4126 		gd->gd_nchstats = &nchstats[i];
4127 	}
4128 
4129 	/*
4130 	 * Create a generous namecache hash table
4131 	 */
4132 	nchashtbl = hashinit_ext(vfs_inodehashsize(),
4133 				 sizeof(struct nchash_head),
4134 				 M_VFSCACHE, &nchash);
4135 	for (i = 0; i <= (int)nchash; ++i) {
4136 		TAILQ_INIT(&nchashtbl[i].list);
4137 		spin_init(&nchashtbl[i].spin, "nchinit_hash");
4138 	}
4139 	for (i = 0; i < NCMOUNT_NUMCACHE; ++i)
4140 		spin_init(&ncmount_cache[i].spin, "nchinit_cache");
4141 	nclockwarn = 5 * hz;
4142 }
4143 
4144 /*
4145  * Called from start_init() to bootstrap the root filesystem.  Returns
4146  * a referenced, unlocked namecache record.
4147  */
4148 void
4149 cache_allocroot(struct nchandle *nch, struct mount *mp, struct vnode *vp)
4150 {
4151 	nch->ncp = cache_alloc(0);
4152 	nch->mount = mp;
4153 	_cache_mntref(mp);
4154 	if (vp)
4155 		_cache_setvp(nch->mount, nch->ncp, vp);
4156 }
4157 
4158 /*
4159  * vfs_cache_setroot()
4160  *
4161  *	Create an association between the root of our namecache and
4162  *	the root vnode.  This routine may be called several times during
4163  *	booting.
4164  *
4165  *	If the caller intends to save the returned namecache pointer somewhere
4166  *	it must cache_hold() it.
4167  */
4168 void
4169 vfs_cache_setroot(struct vnode *nvp, struct nchandle *nch)
4170 {
4171 	struct vnode *ovp;
4172 	struct nchandle onch;
4173 
4174 	ovp = rootvnode;
4175 	onch = rootnch;
4176 	rootvnode = nvp;
4177 	if (nch)
4178 		rootnch = *nch;
4179 	else
4180 		cache_zero(&rootnch);
4181 	if (ovp)
4182 		vrele(ovp);
4183 	if (onch.ncp)
4184 		cache_drop(&onch);
4185 }
4186 
4187 /*
4188  * XXX OLD API COMPAT FUNCTION.  This really messes up the new namecache
4189  * topology and is being removed as quickly as possible.  The new VOP_N*()
4190  * API calls are required to make specific adjustments using the supplied
4191  * ncp pointers rather then just bogusly purging random vnodes.
4192  *
4193  * Invalidate all namecache entries to a particular vnode as well as
4194  * any direct children of that vnode in the namecache.  This is a
4195  * 'catch all' purge used by filesystems that do not know any better.
4196  *
4197  * Note that the linkage between the vnode and its namecache entries will
4198  * be removed, but the namecache entries themselves might stay put due to
4199  * active references from elsewhere in the system or due to the existance of
4200  * the children.   The namecache topology is left intact even if we do not
4201  * know what the vnode association is.  Such entries will be marked
4202  * NCF_UNRESOLVED.
4203  */
4204 void
4205 cache_purge(struct vnode *vp)
4206 {
4207 	cache_inval_vp(vp, CINV_DESTROY | CINV_CHILDREN);
4208 }
4209 
4210 static int disablecwd;
4211 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0,
4212     "Disable getcwd");
4213 
4214 static u_long numcwdcalls;
4215 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdcalls, CTLFLAG_RD, &numcwdcalls, 0,
4216     "Number of current directory resolution calls");
4217 static u_long numcwdfailnf;
4218 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfailnf, CTLFLAG_RD, &numcwdfailnf, 0,
4219     "Number of current directory failures due to lack of file");
4220 static u_long numcwdfailsz;
4221 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfailsz, CTLFLAG_RD, &numcwdfailsz, 0,
4222     "Number of current directory failures due to large result");
4223 static u_long numcwdfound;
4224 SYSCTL_ULONG(_vfs_cache, OID_AUTO, numcwdfound, CTLFLAG_RD, &numcwdfound, 0,
4225     "Number of current directory resolution successes");
4226 
4227 /*
4228  * MPALMOSTSAFE
4229  */
4230 int
4231 sys___getcwd(struct __getcwd_args *uap)
4232 {
4233 	u_int buflen;
4234 	int error;
4235 	char *buf;
4236 	char *bp;
4237 
4238 	if (disablecwd)
4239 		return (ENODEV);
4240 
4241 	buflen = uap->buflen;
4242 	if (buflen == 0)
4243 		return (EINVAL);
4244 	if (buflen > MAXPATHLEN)
4245 		buflen = MAXPATHLEN;
4246 
4247 	buf = kmalloc(buflen, M_TEMP, M_WAITOK);
4248 	bp = kern_getcwd(buf, buflen, &error);
4249 	if (error == 0)
4250 		error = copyout(bp, uap->buf, strlen(bp) + 1);
4251 	kfree(buf, M_TEMP);
4252 	return (error);
4253 }
4254 
4255 char *
4256 kern_getcwd(char *buf, size_t buflen, int *error)
4257 {
4258 	struct proc *p = curproc;
4259 	char *bp;
4260 	int i, slash_prefixed;
4261 	struct filedesc *fdp;
4262 	struct nchandle nch;
4263 	struct namecache *ncp;
4264 
4265 	numcwdcalls++;
4266 	bp = buf;
4267 	bp += buflen - 1;
4268 	*bp = '\0';
4269 	fdp = p->p_fd;
4270 	slash_prefixed = 0;
4271 
4272 	nch = fdp->fd_ncdir;
4273 	ncp = nch.ncp;
4274 	if (ncp)
4275 		_cache_hold(ncp);
4276 
4277 	while (ncp && (ncp != fdp->fd_nrdir.ncp ||
4278 	       nch.mount != fdp->fd_nrdir.mount)
4279 	) {
4280 		/*
4281 		 * While traversing upwards if we encounter the root
4282 		 * of the current mount we have to skip to the mount point
4283 		 * in the underlying filesystem.
4284 		 */
4285 		if (ncp == nch.mount->mnt_ncmountpt.ncp) {
4286 			nch = nch.mount->mnt_ncmounton;
4287 			_cache_drop(ncp);
4288 			ncp = nch.ncp;
4289 			if (ncp)
4290 				_cache_hold(ncp);
4291 			continue;
4292 		}
4293 
4294 		/*
4295 		 * Prepend the path segment
4296 		 */
4297 		for (i = ncp->nc_nlen - 1; i >= 0; i--) {
4298 			if (bp == buf) {
4299 				numcwdfailsz++;
4300 				*error = ERANGE;
4301 				bp = NULL;
4302 				goto done;
4303 			}
4304 			*--bp = ncp->nc_name[i];
4305 		}
4306 		if (bp == buf) {
4307 			numcwdfailsz++;
4308 			*error = ERANGE;
4309 			bp = NULL;
4310 			goto done;
4311 		}
4312 		*--bp = '/';
4313 		slash_prefixed = 1;
4314 
4315 		/*
4316 		 * Go up a directory.  This isn't a mount point so we don't
4317 		 * have to check again.
4318 		 */
4319 		while ((nch.ncp = ncp->nc_parent) != NULL) {
4320 			if (ncp_shared_lock_disable)
4321 				_cache_lock(ncp);
4322 			else
4323 				_cache_lock_shared(ncp);
4324 			if (nch.ncp != ncp->nc_parent) {
4325 				_cache_unlock(ncp);
4326 				continue;
4327 			}
4328 			_cache_hold(nch.ncp);
4329 			_cache_unlock(ncp);
4330 			break;
4331 		}
4332 		_cache_drop(ncp);
4333 		ncp = nch.ncp;
4334 	}
4335 	if (ncp == NULL) {
4336 		numcwdfailnf++;
4337 		*error = ENOENT;
4338 		bp = NULL;
4339 		goto done;
4340 	}
4341 	if (!slash_prefixed) {
4342 		if (bp == buf) {
4343 			numcwdfailsz++;
4344 			*error = ERANGE;
4345 			bp = NULL;
4346 			goto done;
4347 		}
4348 		*--bp = '/';
4349 	}
4350 	numcwdfound++;
4351 	*error = 0;
4352 done:
4353 	if (ncp)
4354 		_cache_drop(ncp);
4355 	return (bp);
4356 }
4357 
4358 /*
4359  * Thus begins the fullpath magic.
4360  *
4361  * The passed nchp is referenced but not locked.
4362  */
4363 static int disablefullpath;
4364 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW,
4365     &disablefullpath, 0,
4366     "Disable fullpath lookups");
4367 
4368 int
4369 cache_fullpath(struct proc *p, struct nchandle *nchp, struct nchandle *nchbase,
4370 	       char **retbuf, char **freebuf, int guess)
4371 {
4372 	struct nchandle fd_nrdir;
4373 	struct nchandle nch;
4374 	struct namecache *ncp;
4375 	struct mount *mp, *new_mp;
4376 	char *bp, *buf;
4377 	int slash_prefixed;
4378 	int error = 0;
4379 	int i;
4380 
4381 	*retbuf = NULL;
4382 	*freebuf = NULL;
4383 
4384 	buf = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
4385 	bp = buf + MAXPATHLEN - 1;
4386 	*bp = '\0';
4387 	if (nchbase)
4388 		fd_nrdir = *nchbase;
4389 	else if (p != NULL)
4390 		fd_nrdir = p->p_fd->fd_nrdir;
4391 	else
4392 		fd_nrdir = rootnch;
4393 	slash_prefixed = 0;
4394 	nch = *nchp;
4395 	ncp = nch.ncp;
4396 	if (ncp)
4397 		_cache_hold(ncp);
4398 	mp = nch.mount;
4399 
4400 	while (ncp && (ncp != fd_nrdir.ncp || mp != fd_nrdir.mount)) {
4401 		new_mp = NULL;
4402 
4403 		/*
4404 		 * If we are asked to guess the upwards path, we do so whenever
4405 		 * we encounter an ncp marked as a mountpoint. We try to find
4406 		 * the actual mountpoint by finding the mountpoint with this
4407 		 * ncp.
4408 		 */
4409 		if (guess && (ncp->nc_flag & NCF_ISMOUNTPT)) {
4410 			new_mp = mount_get_by_nc(ncp);
4411 		}
4412 		/*
4413 		 * While traversing upwards if we encounter the root
4414 		 * of the current mount we have to skip to the mount point.
4415 		 */
4416 		if (ncp == mp->mnt_ncmountpt.ncp) {
4417 			new_mp = mp;
4418 		}
4419 		if (new_mp) {
4420 			nch = new_mp->mnt_ncmounton;
4421 			_cache_drop(ncp);
4422 			ncp = nch.ncp;
4423 			if (ncp)
4424 				_cache_hold(ncp);
4425 			mp = nch.mount;
4426 			continue;
4427 		}
4428 
4429 		/*
4430 		 * Prepend the path segment
4431 		 */
4432 		for (i = ncp->nc_nlen - 1; i >= 0; i--) {
4433 			if (bp == buf) {
4434 				kfree(buf, M_TEMP);
4435 				error = ENOMEM;
4436 				goto done;
4437 			}
4438 			*--bp = ncp->nc_name[i];
4439 		}
4440 		if (bp == buf) {
4441 			kfree(buf, M_TEMP);
4442 			error = ENOMEM;
4443 			goto done;
4444 		}
4445 		*--bp = '/';
4446 		slash_prefixed = 1;
4447 
4448 		/*
4449 		 * Go up a directory.  This isn't a mount point so we don't
4450 		 * have to check again.
4451 		 *
4452 		 * We can only safely access nc_parent with ncp held locked.
4453 		 */
4454 		while ((nch.ncp = ncp->nc_parent) != NULL) {
4455 			_cache_lock(ncp);
4456 			if (nch.ncp != ncp->nc_parent) {
4457 				_cache_unlock(ncp);
4458 				continue;
4459 			}
4460 			_cache_hold(nch.ncp);
4461 			_cache_unlock(ncp);
4462 			break;
4463 		}
4464 		_cache_drop(ncp);
4465 		ncp = nch.ncp;
4466 	}
4467 	if (ncp == NULL) {
4468 		kfree(buf, M_TEMP);
4469 		error = ENOENT;
4470 		goto done;
4471 	}
4472 
4473 	if (!slash_prefixed) {
4474 		if (bp == buf) {
4475 			kfree(buf, M_TEMP);
4476 			error = ENOMEM;
4477 			goto done;
4478 		}
4479 		*--bp = '/';
4480 	}
4481 	*retbuf = bp;
4482 	*freebuf = buf;
4483 	error = 0;
4484 done:
4485 	if (ncp)
4486 		_cache_drop(ncp);
4487 	return(error);
4488 }
4489 
4490 int
4491 vn_fullpath(struct proc *p, struct vnode *vn, char **retbuf,
4492 	    char **freebuf, int guess)
4493 {
4494 	struct namecache *ncp;
4495 	struct nchandle nch;
4496 	int error;
4497 
4498 	*freebuf = NULL;
4499 	if (disablefullpath)
4500 		return (ENODEV);
4501 
4502 	if (p == NULL)
4503 		return (EINVAL);
4504 
4505 	/* vn is NULL, client wants us to use p->p_textvp */
4506 	if (vn == NULL) {
4507 		if ((vn = p->p_textvp) == NULL)
4508 			return (EINVAL);
4509 	}
4510 	spin_lock_shared(&vn->v_spin);
4511 	TAILQ_FOREACH(ncp, &vn->v_namecache, nc_vnode) {
4512 		if (ncp->nc_nlen)
4513 			break;
4514 	}
4515 	if (ncp == NULL) {
4516 		spin_unlock_shared(&vn->v_spin);
4517 		return (EINVAL);
4518 	}
4519 	_cache_hold(ncp);
4520 	spin_unlock_shared(&vn->v_spin);
4521 
4522 	nch.ncp = ncp;
4523 	nch.mount = vn->v_mount;
4524 	error = cache_fullpath(p, &nch, NULL, retbuf, freebuf, guess);
4525 	_cache_drop(ncp);
4526 	return (error);
4527 }
4528 
4529 void
4530 vfscache_rollup_cpu(struct globaldata *gd)
4531 {
4532 	struct pcpu_ncache *pn;
4533 	long count;
4534 
4535 	if (pcpu_ncache == NULL)
4536 		return;
4537 	pn = &pcpu_ncache[gd->gd_cpuid];
4538 
4539 	if (pn->vfscache_count) {
4540 		count = atomic_swap_long(&pn->vfscache_count, 0);
4541 		atomic_add_long(&vfscache_count, count);
4542 	}
4543 	if (pn->vfscache_leafs) {
4544 		count = atomic_swap_long(&pn->vfscache_leafs, 0);
4545 		atomic_add_long(&vfscache_leafs, count);
4546 	}
4547 	if (pn->vfscache_negs) {
4548 		count = atomic_swap_long(&pn->vfscache_negs, 0);
4549 		atomic_add_long(&vfscache_negs, count);
4550 	}
4551 	if (pn->numdefered) {
4552 		count = atomic_swap_long(&pn->numdefered, 0);
4553 		atomic_add_long(&numdefered, count);
4554 	}
4555 }
4556 
4557 #if 0
4558 static void
4559 vfscache_rollup_all(void)
4560 {
4561 	int n;
4562 
4563 	for (n = 0; n < ncpus; ++n)
4564 		vfscache_rollup_cpu(globaldata_find(n));
4565 }
4566 #endif
4567