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