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