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