Fix a race between the namecache and the vnode recycler. A vnode cannot be
[dragonfly.git] / sys / kern / vfs_cache.c
1 /*
2  * Copyright (c) 2003,2004 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  * 
34  * Copyright (c) 1989, 1993, 1995
35  *      The Regents of the University of California.  All rights reserved.
36  *
37  * This code is derived from software contributed to Berkeley by
38  * Poul-Henning Kamp of the FreeBSD Project.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. All advertising materials mentioning features or use of this software
49  *    must display the following acknowledgement:
50  *      This product includes software developed by the University of
51  *      California, Berkeley and its contributors.
52  * 4. Neither the name of the University nor the names of its contributors
53  *    may be used to endorse or promote products derived from this software
54  *    without specific prior written permission.
55  *
56  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
57  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
58  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
59  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
60  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
61  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
62  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
64  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
65  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66  * SUCH DAMAGE.
67  *
68  *      @(#)vfs_cache.c 8.5 (Berkeley) 3/22/95
69  * $FreeBSD: src/sys/kern/vfs_cache.c,v 1.42.2.6 2001/10/05 20:07:03 dillon Exp $
70  * $DragonFly: src/sys/kern/vfs_cache.c,v 1.89 2008/05/08 01:41:05 dillon Exp $
71  */
72
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/kernel.h>
76 #include <sys/sysctl.h>
77 #include <sys/mount.h>
78 #include <sys/vnode.h>
79 #include <sys/malloc.h>
80 #include <sys/sysproto.h>
81 #include <sys/proc.h>
82 #include <sys/namei.h>
83 #include <sys/nlookup.h>
84 #include <sys/filedesc.h>
85 #include <sys/fnv_hash.h>
86 #include <sys/globaldata.h>
87 #include <sys/kern_syscall.h>
88 #include <sys/dirent.h>
89 #include <ddb/ddb.h>
90
91 #include <sys/sysref2.h>
92
93 #define MAX_RECURSION_DEPTH     64
94
95 /*
96  * Random lookups in the cache are accomplished with a hash table using
97  * a hash key of (nc_src_vp, name).
98  *
99  * Negative entries may exist and correspond to structures where nc_vp
100  * is NULL.  In a negative entry, NCF_WHITEOUT will be set if the entry
101  * corresponds to a whited-out directory entry (verses simply not finding the
102  * entry at all).
103  *
104  * Upon reaching the last segment of a path, if the reference is for DELETE,
105  * or NOCACHE is set (rewrite), and the name is located in the cache, it
106  * will be dropped.
107  */
108
109 /*
110  * Structures associated with name cacheing.
111  */
112 #define NCHHASH(hash)   (&nchashtbl[(hash) & nchash])
113 #define MINNEG          1024
114
115 MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
116
117 static LIST_HEAD(nchashhead, namecache) *nchashtbl;     /* Hash Table */
118 static struct namecache_list    ncneglist;              /* instead of vnode */
119
120 /*
121  * ncvp_debug - debug cache_fromvp().  This is used by the NFS server
122  * to create the namecache infrastructure leading to a dangling vnode.
123  *
124  * 0    Only errors are reported
125  * 1    Successes are reported
126  * 2    Successes + the whole directory scan is reported
127  * 3    Force the directory scan code run as if the parent vnode did not
128  *      have a namecache record, even if it does have one.
129  */
130 static int      ncvp_debug;
131 SYSCTL_INT(_debug, OID_AUTO, ncvp_debug, CTLFLAG_RW, &ncvp_debug, 0, "");
132
133 static u_long   nchash;                 /* size of hash table */
134 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0, "");
135
136 static u_long   ncnegfactor = 16;       /* ratio of negative entries */
137 SYSCTL_ULONG(_debug, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0, "");
138
139 static int      nclockwarn;             /* warn on locked entries in ticks */
140 SYSCTL_INT(_debug, OID_AUTO, nclockwarn, CTLFLAG_RW, &nclockwarn, 0, "");
141
142 static u_long   numneg;         /* number of cache entries allocated */
143 SYSCTL_ULONG(_debug, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0, "");
144
145 static u_long   numcache;               /* number of cache entries allocated */
146 SYSCTL_ULONG(_debug, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0, "");
147
148 static u_long   numunres;               /* number of unresolved entries */
149 SYSCTL_ULONG(_debug, OID_AUTO, numunres, CTLFLAG_RD, &numunres, 0, "");
150
151 SYSCTL_INT(_debug, OID_AUTO, vnsize, CTLFLAG_RD, 0, sizeof(struct vnode), "");
152 SYSCTL_INT(_debug, OID_AUTO, ncsize, CTLFLAG_RD, 0, sizeof(struct namecache), "");
153
154 static int cache_resolve_mp(struct mount *mp);
155 static void _cache_rehash(struct namecache *ncp);
156 static void _cache_lock(struct namecache *ncp);
157 static void _cache_setunresolved(struct namecache *ncp);
158
159 /*
160  * The new name cache statistics
161  */
162 SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0, "Name cache statistics");
163 #define STATNODE(mode, name, var) \
164         SYSCTL_ULONG(_vfs_cache, OID_AUTO, name, mode, var, 0, "");
165 STATNODE(CTLFLAG_RD, numneg, &numneg);
166 STATNODE(CTLFLAG_RD, numcache, &numcache);
167 static u_long numcalls; STATNODE(CTLFLAG_RD, numcalls, &numcalls);
168 static u_long dothits; STATNODE(CTLFLAG_RD, dothits, &dothits);
169 static u_long dotdothits; STATNODE(CTLFLAG_RD, dotdothits, &dotdothits);
170 static u_long numchecks; STATNODE(CTLFLAG_RD, numchecks, &numchecks);
171 static u_long nummiss; STATNODE(CTLFLAG_RD, nummiss, &nummiss);
172 static u_long nummisszap; STATNODE(CTLFLAG_RD, nummisszap, &nummisszap);
173 static u_long numposzaps; STATNODE(CTLFLAG_RD, numposzaps, &numposzaps);
174 static u_long numposhits; STATNODE(CTLFLAG_RD, numposhits, &numposhits);
175 static u_long numnegzaps; STATNODE(CTLFLAG_RD, numnegzaps, &numnegzaps);
176 static u_long numneghits; STATNODE(CTLFLAG_RD, numneghits, &numneghits);
177
178 struct nchstats nchstats[SMP_MAXCPU];
179 /*
180  * Export VFS cache effectiveness statistics to user-land.
181  *
182  * The statistics are left for aggregation to user-land so
183  * neat things can be achieved, like observing per-CPU cache
184  * distribution.
185  */
186 static int
187 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
188 {
189         struct globaldata *gd;
190         int i, error;
191
192         error = 0;
193         for (i = 0; i < ncpus; ++i) {
194                 gd = globaldata_find(i);
195                 if ((error = SYSCTL_OUT(req, (void *)&(*gd->gd_nchstats),
196                         sizeof(struct nchstats))))
197                         break;
198         }
199
200         return (error);
201 }
202 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE|CTLFLAG_RD,
203   0, 0, sysctl_nchstats, "S,nchstats", "VFS cache effectiveness statistics");
204
205 static void cache_zap(struct namecache *ncp);
206
207 /*
208  * cache_hold() and cache_drop() prevent the premature deletion of a
209  * namecache entry but do not prevent operations (such as zapping) on
210  * that namecache entry.
211  *
212  * This routine may only be called from outside this source module if
213  * nc_refs is already at least 1.
214  *
215  * This is a rare case where callers are allowed to hold a spinlock,
216  * so we can't ourselves.
217  */
218 static __inline
219 struct namecache *
220 _cache_hold(struct namecache *ncp)
221 {
222         atomic_add_int(&ncp->nc_refs, 1);
223         return(ncp);
224 }
225
226 /*
227  * When dropping an entry, if only one ref remains and the entry has not
228  * been resolved, zap it.  Since the one reference is being dropped the
229  * entry had better not be locked.
230  */
231 static __inline
232 void
233 _cache_drop(struct namecache *ncp)
234 {
235         KKASSERT(ncp->nc_refs > 0);
236         if (ncp->nc_refs == 1 && 
237             (ncp->nc_flag & NCF_UNRESOLVED) && 
238             TAILQ_EMPTY(&ncp->nc_list)
239         ) {
240                 KKASSERT(ncp->nc_exlocks == 0);
241                 _cache_lock(ncp);
242                 cache_zap(ncp);
243         } else {
244                 atomic_subtract_int(&ncp->nc_refs, 1);
245         }
246 }
247
248 /*
249  * Link a new namecache entry to its parent.  Be careful to avoid races
250  * if vhold() blocks in the future.
251  */
252 static void
253 cache_link_parent(struct namecache *ncp, struct namecache *par)
254 {
255         KKASSERT(ncp->nc_parent == NULL);
256         ncp->nc_parent = par;
257         if (TAILQ_EMPTY(&par->nc_list)) {
258                 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
259                 /*
260                  * Any vp associated with an ncp which has children must
261                  * be held to prevent it from being recycled.
262                  */
263                 if (par->nc_vp)
264                         vhold(par->nc_vp);
265         } else {
266                 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
267         }
268 }
269
270 /*
271  * Remove the parent association from a namecache structure.  If this is
272  * the last child of the parent the cache_drop(par) will attempt to
273  * recursively zap the parent.
274  */
275 static void
276 cache_unlink_parent(struct namecache *ncp)
277 {
278         struct namecache *par;
279
280         if ((par = ncp->nc_parent) != NULL) {
281                 ncp->nc_parent = NULL;
282                 par = _cache_hold(par);
283                 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
284                 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
285                         vdrop(par->nc_vp);
286                 _cache_drop(par);
287         }
288 }
289
290 /*
291  * Allocate a new namecache structure.  Most of the code does not require
292  * zero-termination of the string but it makes vop_compat_ncreate() easier.
293  */
294 static struct namecache *
295 cache_alloc(int nlen)
296 {
297         struct namecache *ncp;
298
299         ncp = kmalloc(sizeof(*ncp), M_VFSCACHE, M_WAITOK|M_ZERO);
300         if (nlen)
301                 ncp->nc_name = kmalloc(nlen + 1, M_VFSCACHE, M_WAITOK);
302         ncp->nc_nlen = nlen;
303         ncp->nc_flag = NCF_UNRESOLVED;
304         ncp->nc_error = ENOTCONN;       /* needs to be resolved */
305         ncp->nc_refs = 1;
306
307         /*
308          * Construct a fake FSMID based on the time of day and a 32 bit
309          * roller for uniqueness.  This is used to generate a useful
310          * FSMID for filesystems which do not support it.
311          */
312         ncp->nc_fsmid = cache_getnewfsmid();
313         TAILQ_INIT(&ncp->nc_list);
314         _cache_lock(ncp);
315         return(ncp);
316 }
317
318 static void
319 _cache_free(struct namecache *ncp)
320 {
321         KKASSERT(ncp->nc_refs == 1 && ncp->nc_exlocks == 1);
322         if (ncp->nc_name)
323                 kfree(ncp->nc_name, M_VFSCACHE);
324         kfree(ncp, M_VFSCACHE);
325 }
326
327 void
328 cache_zero(struct nchandle *nch)
329 {
330         nch->ncp = NULL;
331         nch->mount = NULL;
332 }
333
334 /*
335  * Ref and deref a namecache structure.
336  *
337  * Warning: caller may hold an unrelated read spinlock, which means we can't
338  * use read spinlocks here.
339  */
340 struct nchandle *
341 cache_hold(struct nchandle *nch)
342 {
343         _cache_hold(nch->ncp);
344         ++nch->mount->mnt_refs;
345         return(nch);
346 }
347
348 void
349 cache_copy(struct nchandle *nch, struct nchandle *target)
350 {
351         *target = *nch;
352         _cache_hold(target->ncp);
353         ++nch->mount->mnt_refs;
354 }
355
356 void
357 cache_changemount(struct nchandle *nch, struct mount *mp)
358 {
359         --nch->mount->mnt_refs;
360         nch->mount = mp;
361         ++nch->mount->mnt_refs;
362 }
363
364 void
365 cache_drop(struct nchandle *nch)
366 {
367         --nch->mount->mnt_refs;
368         _cache_drop(nch->ncp);
369         nch->ncp = NULL;
370         nch->mount = NULL;
371 }
372
373 /*
374  * Namespace locking.  The caller must already hold a reference to the
375  * namecache structure in order to lock/unlock it.  This function prevents
376  * the namespace from being created or destroyed by accessors other then
377  * the lock holder.
378  *
379  * Note that holding a locked namecache structure prevents other threads
380  * from making namespace changes (e.g. deleting or creating), prevents
381  * vnode association state changes by other threads, and prevents the
382  * namecache entry from being resolved or unresolved by other threads.
383  *
384  * The lock owner has full authority to associate/disassociate vnodes
385  * and resolve/unresolve the locked ncp.
386  *
387  * WARNING!  Holding a locked ncp will prevent a vnode from being destroyed
388  * or recycled, but it does NOT help you if the vnode had already initiated
389  * a recyclement.  If this is important, use cache_get() rather then 
390  * cache_lock() (and deal with the differences in the way the refs counter
391  * is handled).  Or, alternatively, make an unconditional call to 
392  * cache_validate() or cache_resolve() after cache_lock() returns.
393  */
394 static
395 void
396 _cache_lock(struct namecache *ncp)
397 {
398         thread_t td;
399         int didwarn;
400
401         KKASSERT(ncp->nc_refs != 0);
402         didwarn = 0;
403         td = curthread;
404
405         for (;;) {
406                 if (ncp->nc_exlocks == 0) {
407                         ncp->nc_exlocks = 1;
408                         ncp->nc_locktd = td;
409                         /* 
410                          * The vp associated with a locked ncp must be held
411                          * to prevent it from being recycled (which would
412                          * cause the ncp to become unresolved).
413                          *
414                          * WARNING!  If VRECLAIMED is set the vnode could
415                          * already be in the middle of a recycle.  Callers
416                          * should not assume that nc_vp is usable when
417                          * not NULL.  cache_vref() or cache_vget() must be
418                          * called.
419                          *
420                          * XXX loop on race for later MPSAFE work.
421                          */
422                         if (ncp->nc_vp)
423                                 vhold(ncp->nc_vp);
424                         break;
425                 }
426                 if (ncp->nc_locktd == td) {
427                         ++ncp->nc_exlocks;
428                         break;
429                 }
430                 ncp->nc_flag |= NCF_LOCKREQ;
431                 if (tsleep(ncp, 0, "clock", nclockwarn) == EWOULDBLOCK) {
432                         if (didwarn)
433                                 continue;
434                         didwarn = 1;
435                         kprintf("[diagnostic] cache_lock: blocked on %p", ncp);
436                         kprintf(" \"%*.*s\"\n",
437                                 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
438                 }
439         }
440
441         if (didwarn == 1) {
442                 kprintf("[diagnostic] cache_lock: unblocked %*.*s\n",
443                         ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
444         }
445 }
446
447 void
448 cache_lock(struct nchandle *nch)
449 {
450         _cache_lock(nch->ncp);
451 }
452
453 static
454 int
455 _cache_lock_nonblock(struct namecache *ncp)
456 {
457         thread_t td;
458
459         KKASSERT(ncp->nc_refs != 0);
460         td = curthread;
461         if (ncp->nc_exlocks == 0) {
462                 ncp->nc_exlocks = 1;
463                 ncp->nc_locktd = td;
464                 /* 
465                  * The vp associated with a locked ncp must be held
466                  * to prevent it from being recycled (which would
467                  * cause the ncp to become unresolved).
468                  *
469                  * WARNING!  If VRECLAIMED is set the vnode could
470                  * already be in the middle of a recycle.  Callers
471                  * should not assume that nc_vp is usable when
472                  * not NULL.  cache_vref() or cache_vget() must be
473                  * called.
474                  *
475                  * XXX loop on race for later MPSAFE work.
476                  */
477                 if (ncp->nc_vp)
478                         vhold(ncp->nc_vp);
479                 return(0);
480         } else {
481                 return(EWOULDBLOCK);
482         }
483 }
484
485 int
486 cache_lock_nonblock(struct nchandle *nch)
487 {
488         return(_cache_lock_nonblock(nch->ncp));
489 }
490
491 static
492 void
493 _cache_unlock(struct namecache *ncp)
494 {
495         thread_t td = curthread;
496
497         KKASSERT(ncp->nc_refs > 0);
498         KKASSERT(ncp->nc_exlocks > 0);
499         KKASSERT(ncp->nc_locktd == td);
500         if (--ncp->nc_exlocks == 0) {
501                 if (ncp->nc_vp)
502                         vdrop(ncp->nc_vp);
503                 ncp->nc_locktd = NULL;
504                 if (ncp->nc_flag & NCF_LOCKREQ) {
505                         ncp->nc_flag &= ~NCF_LOCKREQ;
506                         wakeup(ncp);
507                 }
508         }
509 }
510
511 void
512 cache_unlock(struct nchandle *nch)
513 {
514         _cache_unlock(nch->ncp);
515 }
516
517 /*
518  * ref-and-lock, unlock-and-deref functions.
519  *
520  * This function is primarily used by nlookup.  Even though cache_lock
521  * holds the vnode, it is possible that the vnode may have already
522  * initiated a recyclement.  We want cache_get() to return a definitively
523  * usable vnode or a definitively unresolved ncp.
524  */
525 static
526 struct namecache *
527 _cache_get(struct namecache *ncp)
528 {
529         _cache_hold(ncp);
530         _cache_lock(ncp);
531         if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
532                 _cache_setunresolved(ncp);
533         return(ncp);
534 }
535
536 /*
537  * note: the same nchandle can be passed for both arguments.
538  */
539 void
540 cache_get(struct nchandle *nch, struct nchandle *target)
541 {
542         target->mount = nch->mount;
543         target->ncp = _cache_get(nch->ncp);
544         ++target->mount->mnt_refs;
545 }
546
547 static int
548 _cache_get_nonblock(struct namecache *ncp)
549 {
550         /* XXX MP */
551         if (ncp->nc_exlocks == 0 || ncp->nc_locktd == curthread) {
552                 _cache_hold(ncp);
553                 _cache_lock(ncp);
554                 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
555                         _cache_setunresolved(ncp);
556                 return(0);
557         }
558         return(EWOULDBLOCK);
559 }
560
561 int
562 cache_get_nonblock(struct nchandle *nch)
563 {
564         int error;
565
566         if ((error = _cache_get_nonblock(nch->ncp)) == 0)
567                 ++nch->mount->mnt_refs;
568         return (error);
569 }
570
571 static __inline
572 void
573 _cache_put(struct namecache *ncp)
574 {
575         _cache_unlock(ncp);
576         _cache_drop(ncp);
577 }
578
579 void
580 cache_put(struct nchandle *nch)
581 {
582         --nch->mount->mnt_refs;
583         _cache_put(nch->ncp);
584         nch->ncp = NULL;
585         nch->mount = NULL;
586 }
587
588 /*
589  * Resolve an unresolved ncp by associating a vnode with it.  If the
590  * vnode is NULL, a negative cache entry is created.
591  *
592  * The ncp should be locked on entry and will remain locked on return.
593  */
594 static
595 void
596 _cache_setvp(struct namecache *ncp, struct vnode *vp)
597 {
598         KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
599         ncp->nc_vp = vp;
600         if (vp != NULL) {
601                 /*
602                  * Any vp associated with an ncp which has children must
603                  * be held.  Any vp associated with a locked ncp must be held.
604                  */
605                 if (!TAILQ_EMPTY(&ncp->nc_list))
606                         vhold(vp);
607                 TAILQ_INSERT_HEAD(&vp->v_namecache, ncp, nc_vnode);
608                 if (ncp->nc_exlocks)
609                         vhold(vp);
610
611                 /*
612                  * Set auxiliary flags
613                  */
614                 switch(vp->v_type) {
615                 case VDIR:
616                         ncp->nc_flag |= NCF_ISDIR;
617                         break;
618                 case VLNK:
619                         ncp->nc_flag |= NCF_ISSYMLINK;
620                         /* XXX cache the contents of the symlink */
621                         break;
622                 default:
623                         break;
624                 }
625                 ++numcache;
626                 ncp->nc_error = 0;
627         } else {
628                 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
629                 ++numneg;
630                 ncp->nc_error = ENOENT;
631         }
632         ncp->nc_flag &= ~NCF_UNRESOLVED;
633 }
634
635 void
636 cache_setvp(struct nchandle *nch, struct vnode *vp)
637 {
638         _cache_setvp(nch->ncp, vp);
639 }
640
641 void
642 cache_settimeout(struct nchandle *nch, int nticks)
643 {
644         struct namecache *ncp = nch->ncp;
645
646         if ((ncp->nc_timeout = ticks + nticks) == 0)
647                 ncp->nc_timeout = 1;
648 }
649
650 /*
651  * Disassociate the vnode or negative-cache association and mark a
652  * namecache entry as unresolved again.  Note that the ncp is still
653  * left in the hash table and still linked to its parent.
654  *
655  * The ncp should be locked and refd on entry and will remain locked and refd
656  * on return.
657  *
658  * This routine is normally never called on a directory containing children.
659  * However, NFS often does just that in its rename() code as a cop-out to
660  * avoid complex namespace operations.  This disconnects a directory vnode
661  * from its namecache and can cause the OLDAPI and NEWAPI to get out of
662  * sync.
663  *
664  * NOTE: NCF_FSMID must be cleared so a refurbishment of the ncp, such as
665  * in a create, properly propogates flag up the chain.
666  */
667 static
668 void
669 _cache_setunresolved(struct namecache *ncp)
670 {
671         struct vnode *vp;
672
673         if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
674                 ncp->nc_flag |= NCF_UNRESOLVED;
675                 ncp->nc_timeout = 0;
676                 ncp->nc_error = ENOTCONN;
677                 ++numunres;
678                 if ((vp = ncp->nc_vp) != NULL) {
679                         --numcache;
680                         ncp->nc_vp = NULL;
681                         TAILQ_REMOVE(&vp->v_namecache, ncp, nc_vnode);
682
683                         /*
684                          * Any vp associated with an ncp with children is
685                          * held by that ncp.  Any vp associated with a locked
686                          * ncp is held by that ncp.  These conditions must be
687                          * undone when the vp is cleared out from the ncp.
688                          */
689                         if (ncp->nc_flag & NCF_FSMID)
690                                 vupdatefsmid(vp);
691                         if (!TAILQ_EMPTY(&ncp->nc_list))
692                                 vdrop(vp);
693                         if (ncp->nc_exlocks)
694                                 vdrop(vp);
695                 } else {
696                         TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
697                         --numneg;
698                 }
699                 ncp->nc_flag &= ~(NCF_WHITEOUT|NCF_ISDIR|NCF_ISSYMLINK|
700                                   NCF_FSMID);
701         }
702 }
703
704 void
705 cache_setunresolved(struct nchandle *nch)
706 {
707         _cache_setunresolved(nch->ncp);
708 }
709
710 /*
711  * Determine if we can clear NCF_ISMOUNTPT by scanning the mountlist
712  * looking for matches.  This flag tells the lookup code when it must
713  * check for a mount linkage and also prevents the directories in question
714  * from being deleted or renamed.
715  */
716 static
717 int
718 cache_clrmountpt_callback(struct mount *mp, void *data)
719 {
720         struct nchandle *nch = data;
721
722         if (mp->mnt_ncmounton.ncp == nch->ncp)
723                 return(1);
724         if (mp->mnt_ncmountpt.ncp == nch->ncp)
725                 return(1);
726         return(0);
727 }
728
729 void
730 cache_clrmountpt(struct nchandle *nch)
731 {
732         int count;
733
734         count = mountlist_scan(cache_clrmountpt_callback, nch,
735                                MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
736         if (count == 0)
737                 nch->ncp->nc_flag &= ~NCF_ISMOUNTPT;
738 }
739
740 /*
741  * Invalidate portions of the namecache topology given a starting entry.
742  * The passed ncp is set to an unresolved state and:
743  *
744  * The passed ncp must be locked.
745  *
746  * CINV_DESTROY         - Set a flag in the passed ncp entry indicating
747  *                        that the physical underlying nodes have been 
748  *                        destroyed... as in deleted.  For example, when
749  *                        a directory is removed.  This will cause record
750  *                        lookups on the name to no longer be able to find
751  *                        the record and tells the resolver to return failure
752  *                        rather then trying to resolve through the parent.
753  *
754  *                        The topology itself, including ncp->nc_name,
755  *                        remains intact.
756  *
757  *                        This only applies to the passed ncp, if CINV_CHILDREN
758  *                        is specified the children are not flagged.
759  *
760  * CINV_CHILDREN        - Set all children (recursively) to an unresolved
761  *                        state as well.
762  *
763  *                        Note that this will also have the side effect of
764  *                        cleaning out any unreferenced nodes in the topology
765  *                        from the leaves up as the recursion backs out.
766  *
767  * Note that the topology for any referenced nodes remains intact.
768  *
769  * It is possible for cache_inval() to race a cache_resolve(), meaning that
770  * the namecache entry may not actually be invalidated on return if it was
771  * revalidated while recursing down into its children.  This code guarentees
772  * that the node(s) will go through an invalidation cycle, but does not 
773  * guarentee that they will remain in an invalidated state. 
774  *
775  * Returns non-zero if a revalidation was detected during the invalidation
776  * recursion, zero otherwise.  Note that since only the original ncp is
777  * locked the revalidation ultimately can only indicate that the original ncp
778  * *MIGHT* no have been reresolved.
779  *
780  * DEEP RECURSION HANDLING - If a recursive invalidation recurses deeply we
781  * have to avoid blowing out the kernel stack.  We do this by saving the
782  * deep namecache node and aborting the recursion, then re-recursing at that
783  * node using a depth-first algorithm in order to allow multiple deep
784  * recursions to chain through each other, then we restart the invalidation
785  * from scratch.
786  */
787
788 struct cinvtrack {
789         struct namecache *resume_ncp;
790         int depth;
791 };
792
793 static int _cache_inval_internal(struct namecache *, int, struct cinvtrack *);
794
795 static
796 int
797 _cache_inval(struct namecache *ncp, int flags)
798 {
799         struct cinvtrack track;
800         struct namecache *ncp2;
801         int r;
802
803         track.depth = 0;
804         track.resume_ncp = NULL;
805
806         for (;;) {
807                 r = _cache_inval_internal(ncp, flags, &track);
808                 if (track.resume_ncp == NULL)
809                         break;
810                 kprintf("Warning: deep namecache recursion at %s\n",
811                         ncp->nc_name);
812                 _cache_unlock(ncp);
813                 while ((ncp2 = track.resume_ncp) != NULL) {
814                         track.resume_ncp = NULL;
815                         _cache_lock(ncp2);
816                         _cache_inval_internal(ncp2, flags & ~CINV_DESTROY,
817                                              &track);
818                         _cache_put(ncp2);
819                 }
820                 _cache_lock(ncp);
821         }
822         return(r);
823 }
824
825 int
826 cache_inval(struct nchandle *nch, int flags)
827 {
828         return(_cache_inval(nch->ncp, flags));
829 }
830
831 static int
832 _cache_inval_internal(struct namecache *ncp, int flags, struct cinvtrack *track)
833 {
834         struct namecache *kid;
835         struct namecache *nextkid;
836         int rcnt = 0;
837
838         KKASSERT(ncp->nc_exlocks);
839
840         _cache_setunresolved(ncp);
841         if (flags & CINV_DESTROY)
842                 ncp->nc_flag |= NCF_DESTROYED;
843
844         if ((flags & CINV_CHILDREN) && 
845             (kid = TAILQ_FIRST(&ncp->nc_list)) != NULL
846         ) {
847                 if (++track->depth > MAX_RECURSION_DEPTH) {
848                         track->resume_ncp = ncp;
849                         _cache_hold(ncp);
850                         ++rcnt;
851                 }
852                 _cache_hold(kid);
853                 _cache_unlock(ncp);
854                 while (kid) {
855                         if (track->resume_ncp) {
856                                 _cache_drop(kid);
857                                 break;
858                         }
859                         if ((nextkid = TAILQ_NEXT(kid, nc_entry)) != NULL)
860                                 _cache_hold(nextkid);
861                         if ((kid->nc_flag & NCF_UNRESOLVED) == 0 ||
862                             TAILQ_FIRST(&kid->nc_list)
863                         ) {
864                                 _cache_lock(kid);
865                                 rcnt += _cache_inval_internal(kid, flags & ~CINV_DESTROY, track);
866                                 _cache_unlock(kid);
867                         }
868                         _cache_drop(kid);
869                         kid = nextkid;
870                 }
871                 --track->depth;
872                 _cache_lock(ncp);
873         }
874
875         /*
876          * Someone could have gotten in there while ncp was unlocked,
877          * retry if so.
878          */
879         if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
880                 ++rcnt;
881         return (rcnt);
882 }
883
884 /*
885  * Invalidate a vnode's namecache associations.  To avoid races against
886  * the resolver we do not invalidate a node which we previously invalidated
887  * but which was then re-resolved while we were in the invalidation loop.
888  *
889  * Returns non-zero if any namecache entries remain after the invalidation
890  * loop completed.
891  *
892  * NOTE: unlike the namecache topology which guarentees that ncp's will not
893  * be ripped out of the topology while held, the vnode's v_namecache list
894  * has no such restriction.  NCP's can be ripped out of the list at virtually
895  * any time if not locked, even if held.
896  */
897 int
898 cache_inval_vp(struct vnode *vp, int flags)
899 {
900         struct namecache *ncp;
901         struct namecache *next;
902
903 restart:
904         ncp = TAILQ_FIRST(&vp->v_namecache);
905         if (ncp)
906                 _cache_hold(ncp);
907         while (ncp) {
908                 /* loop entered with ncp held */
909                 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
910                         _cache_hold(next);
911                 _cache_lock(ncp);
912                 if (ncp->nc_vp != vp) {
913                         kprintf("Warning: cache_inval_vp: race-A detected on "
914                                 "%s\n", ncp->nc_name);
915                         _cache_put(ncp);
916                         if (next)
917                                 _cache_drop(next);
918                         goto restart;
919                 }
920                 _cache_inval(ncp, flags);
921                 _cache_put(ncp);                /* also releases reference */
922                 ncp = next;
923                 if (ncp && ncp->nc_vp != vp) {
924                         kprintf("Warning: cache_inval_vp: race-B detected on "
925                                 "%s\n", ncp->nc_name);
926                         _cache_drop(ncp);
927                         goto restart;
928                 }
929         }
930         return(TAILQ_FIRST(&vp->v_namecache) != NULL);
931 }
932
933 /*
934  * This routine is used instead of the normal cache_inval_vp() when we
935  * are trying to recycle otherwise good vnodes.
936  *
937  * Return 0 on success, non-zero if not all namecache records could be
938  * disassociated from the vnode (for various reasons).
939  */
940 int
941 cache_inval_vp_nonblock(struct vnode *vp)
942 {
943         struct namecache *ncp;
944         struct namecache *next;
945
946         ncp = TAILQ_FIRST(&vp->v_namecache);
947         if (ncp)
948                 _cache_hold(ncp);
949         while (ncp) {
950                 /* loop entered with ncp held */
951                 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
952                         _cache_hold(next);
953                 if (_cache_lock_nonblock(ncp)) {
954                         _cache_drop(ncp);
955                         if (next)
956                                 _cache_drop(next);
957                         break;
958                 }
959                 if (ncp->nc_vp != vp) {
960                         kprintf("Warning: cache_inval_vp: race-A detected on "
961                                 "%s\n", ncp->nc_name);
962                         _cache_put(ncp);
963                         if (next)
964                                 _cache_drop(next);
965                         break;
966                 }
967                 _cache_inval(ncp, 0);
968                 _cache_put(ncp);                /* also releases reference */
969                 ncp = next;
970                 if (ncp && ncp->nc_vp != vp) {
971                         kprintf("Warning: cache_inval_vp: race-B detected on "
972                                 "%s\n", ncp->nc_name);
973                         _cache_drop(ncp);
974                         break;
975                 }
976         }
977         return(TAILQ_FIRST(&vp->v_namecache) != NULL);
978 }
979
980 /*
981  * The source ncp has been renamed to the target ncp.  Both fncp and tncp
982  * must be locked.  The target ncp is destroyed (as a normal rename-over
983  * would destroy the target file or directory).
984  *
985  * Because there may be references to the source ncp we cannot copy its
986  * contents to the target.  Instead the source ncp is relinked as the target
987  * and the target ncp is removed from the namecache topology.
988  */
989 void
990 cache_rename(struct nchandle *fnch, struct nchandle *tnch)
991 {
992         struct namecache *fncp = fnch->ncp;
993         struct namecache *tncp = tnch->ncp;
994         char *oname;
995
996         _cache_setunresolved(tncp);
997         cache_unlink_parent(fncp);
998         cache_link_parent(fncp, tncp->nc_parent);
999         cache_unlink_parent(tncp);
1000         oname = fncp->nc_name;
1001         fncp->nc_name = tncp->nc_name;
1002         fncp->nc_nlen = tncp->nc_nlen;
1003         tncp->nc_name = NULL;
1004         tncp->nc_nlen = 0;
1005         if (fncp->nc_flag & NCF_HASHED)
1006                 _cache_rehash(fncp);
1007         if (tncp->nc_flag & NCF_HASHED)
1008                 _cache_rehash(tncp);
1009         if (oname)
1010                 kfree(oname, M_VFSCACHE);
1011 }
1012
1013 /*
1014  * vget the vnode associated with the namecache entry.  Resolve the namecache
1015  * entry if necessary and deal with namecache/vp races.  The passed ncp must
1016  * be referenced and may be locked.  The ncp's ref/locking state is not 
1017  * effected by this call.
1018  *
1019  * lk_type may be LK_SHARED, LK_EXCLUSIVE.  A ref'd, possibly locked
1020  * (depending on the passed lk_type) will be returned in *vpp with an error
1021  * of 0, or NULL will be returned in *vpp with a non-0 error code.  The
1022  * most typical error is ENOENT, meaning that the ncp represents a negative
1023  * cache hit and there is no vnode to retrieve, but other errors can occur
1024  * too.
1025  *
1026  * The main race we have to deal with are namecache zaps.  The ncp itself
1027  * will not disappear since it is referenced, and it turns out that the
1028  * validity of the vp pointer can be checked simply by rechecking the
1029  * contents of ncp->nc_vp.
1030  */
1031 int
1032 cache_vget(struct nchandle *nch, struct ucred *cred,
1033            int lk_type, struct vnode **vpp)
1034 {
1035         struct namecache *ncp;
1036         struct vnode *vp;
1037         int error;
1038
1039         ncp = nch->ncp;
1040 again:
1041         vp = NULL;
1042         if (ncp->nc_flag & NCF_UNRESOLVED) {
1043                 _cache_lock(ncp);
1044                 error = cache_resolve(nch, cred);
1045                 _cache_unlock(ncp);
1046         } else {
1047                 error = 0;
1048         }
1049         if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1050                 /*
1051                  * Accessing the vnode from the namecache is a bit 
1052                  * dangerous.  Because there are no refs on the vnode, it
1053                  * could be in the middle of a reclaim.
1054                  */
1055                 if (vp->v_flag & VRECLAIMED) {
1056                         kprintf("Warning: vnode reclaim race detected in cache_vget on %p (%s)\n", vp, ncp->nc_name);
1057                         _cache_lock(ncp);
1058                         _cache_setunresolved(ncp);
1059                         _cache_unlock(ncp);
1060                         goto again;
1061                 }
1062                 error = vget(vp, lk_type);
1063                 if (error) {
1064                         if (vp != ncp->nc_vp)
1065                                 goto again;
1066                         vp = NULL;
1067                 } else if (vp != ncp->nc_vp) {
1068                         vput(vp);
1069                         goto again;
1070                 } else if (vp->v_flag & VRECLAIMED) {
1071                         panic("vget succeeded on a VRECLAIMED node! vp %p", vp);
1072                 }
1073         }
1074         if (error == 0 && vp == NULL)
1075                 error = ENOENT;
1076         *vpp = vp;
1077         return(error);
1078 }
1079
1080 int
1081 cache_vref(struct nchandle *nch, struct ucred *cred, struct vnode **vpp)
1082 {
1083         struct namecache *ncp;
1084         struct vnode *vp;
1085         int error;
1086
1087         ncp = nch->ncp;
1088
1089 again:
1090         vp = NULL;
1091         if (ncp->nc_flag & NCF_UNRESOLVED) {
1092                 _cache_lock(ncp);
1093                 error = cache_resolve(nch, cred);
1094                 _cache_unlock(ncp);
1095         } else {
1096                 error = 0;
1097         }
1098         if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1099                 /*
1100                  * Since we did not obtain any locks, a cache zap 
1101                  * race can occur here if the vnode is in the middle
1102                  * of being reclaimed and has not yet been able to
1103                  * clean out its cache node.  If that case occurs,
1104                  * we must lock and unresolve the cache, then loop
1105                  * to retry.
1106                  */
1107                 if ((error = vget(vp, LK_SHARED)) != 0) {
1108                         if (error == ENOENT) {
1109                                 kprintf("Warning: vnode reclaim race detected on cache_vref %p (%s)\n", vp, ncp->nc_name);
1110                                 _cache_lock(ncp);
1111                                 _cache_setunresolved(ncp);
1112                                 _cache_unlock(ncp);
1113                                 goto again;
1114                         }
1115                         /* fatal error */
1116                 } else {
1117                         /* caller does not want a lock */
1118                         vn_unlock(vp);
1119                 }
1120         }
1121         if (error == 0 && vp == NULL)
1122                 error = ENOENT;
1123         *vpp = vp;
1124         return(error);
1125 }
1126
1127 /*
1128  * Return a referenced vnode representing the parent directory of
1129  * ncp.  Because the caller has locked the ncp it should not be possible for
1130  * the parent to go away.
1131  */
1132 struct vnode *
1133 cache_dvpref(struct namecache *ncp)
1134 {
1135         struct vnode *dvp;
1136 #if 0
1137         int error;
1138 #endif
1139
1140         if (ncp->nc_parent == NULL)
1141                 return(NULL);
1142         if ((dvp = ncp->nc_parent->nc_vp) == NULL)
1143                 return(NULL);
1144         KKASSERT((dvp->v_flag & VRECLAIMED) == 0);
1145         vhold(dvp);
1146         return(dvp);
1147 #if 0
1148         if (vget(dvp, LK_SHARED) == 0) {
1149                 vn_unlock(dvp);
1150                 return(dvp);
1151         } else {
1152                 panic("cache_dvpref: vget(%p) failed", dvp);
1153                 return(NULL);   /* NOT REACHED */
1154         }
1155 #endif
1156 }
1157
1158 void
1159 cache_dvprel(struct vnode *dvp)
1160 {
1161         vdrop(dvp);
1162 #if 0
1163         vrele(dvp);
1164 #endif
1165 }
1166
1167 /*
1168  * Recursively set the FSMID update flag for namecache nodes leading
1169  * to root.  This will cause the next getattr or reclaim to increment the
1170  * fsmid and mark the inode for lazy updating.
1171  *
1172  * Stop recursing when we hit a node whos NCF_FSMID flag is already set.
1173  * This makes FSMIDs work in an Einsteinian fashion - where the observation
1174  * effects the result.  In this case a program monitoring a higher level
1175  * node will have detected some prior change and started its scan (clearing
1176  * NCF_FSMID in higher level nodes), but since it has not yet observed the
1177  * node where we find NCF_FSMID still set, we can safely make the related
1178  * modification without interfering with the theorized program.
1179  *
1180  * This also means that FSMIDs cannot represent time-domain quantities
1181  * in a hierarchical sense.  But the main reason for doing it this way
1182  * is to reduce the amount of recursion that occurs in the critical path
1183  * when e.g. a program is writing to a file that sits deep in a directory
1184  * hierarchy.
1185  */
1186 void
1187 cache_update_fsmid(struct nchandle *nch)
1188 {
1189         struct namecache *ncp;
1190         struct namecache *scan;
1191         struct vnode *vp;
1192
1193         ncp = nch->ncp;
1194
1195         /*
1196          * Warning: even if we get a non-NULL vp it could still be in the
1197          * middle of a recyclement.  Don't do anything fancy, just set
1198          * NCF_FSMID.
1199          */
1200         if ((vp = ncp->nc_vp) != NULL) {
1201                 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1202                         for (scan = ncp; scan; scan = scan->nc_parent) {
1203                                 if (scan->nc_flag & NCF_FSMID)
1204                                         break;
1205                                 scan->nc_flag |= NCF_FSMID;
1206                         }
1207                 }
1208         } else {
1209                 while (ncp && (ncp->nc_flag & NCF_FSMID) == 0) {
1210                         ncp->nc_flag |= NCF_FSMID;
1211                         ncp = ncp->nc_parent;
1212                 }
1213         }
1214 }
1215
1216 void
1217 cache_update_fsmid_vp(struct vnode *vp)
1218 {
1219         struct namecache *ncp;
1220         struct namecache *scan;
1221
1222         TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1223                 for (scan = ncp; scan; scan = scan->nc_parent) {
1224                         if (scan->nc_flag & NCF_FSMID)
1225                                 break;
1226                         scan->nc_flag |= NCF_FSMID;
1227                 }
1228         }
1229 }
1230
1231 /*
1232  * If getattr is called on a vnode (e.g. a stat call), the filesystem
1233  * may call this routine to determine if the namecache has the hierarchical
1234  * change flag set, requiring the fsmid to be updated.
1235  *
1236  * Since 0 indicates no support, make sure the filesystem fsmid is at least
1237  * 1.
1238  */
1239 int
1240 cache_check_fsmid_vp(struct vnode *vp, int64_t *fsmid)
1241 {
1242         struct namecache *ncp;
1243         int changed = 0;
1244
1245         TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1246                 if (ncp->nc_flag & NCF_FSMID) {
1247                         ncp->nc_flag &= ~NCF_FSMID;
1248                         changed = 1;
1249                 }
1250         }
1251         if (*fsmid == 0)
1252                 ++*fsmid;
1253         if (changed)
1254                 ++*fsmid;
1255         return(changed);
1256 }
1257
1258 /*
1259  * Obtain the FSMID for a vnode for filesystems which do not support
1260  * a built-in FSMID.
1261  */
1262 int64_t
1263 cache_sync_fsmid_vp(struct vnode *vp)
1264 {
1265         struct namecache *ncp;
1266
1267         if ((ncp = TAILQ_FIRST(&vp->v_namecache)) != NULL) {
1268                 if (ncp->nc_flag & NCF_FSMID) {
1269                         ncp->nc_flag &= ~NCF_FSMID;
1270                         ++ncp->nc_fsmid;
1271                 }
1272                 return(ncp->nc_fsmid);
1273         }
1274         return(VNOVAL);
1275 }
1276
1277 /*
1278  * Convert a directory vnode to a namecache record without any other 
1279  * knowledge of the topology.  This ONLY works with directory vnodes and
1280  * is ONLY used by the NFS server.  dvp must be refd but unlocked, and the
1281  * returned ncp (if not NULL) will be held and unlocked.
1282  *
1283  * If 'makeit' is 0 and dvp has no existing namecache record, NULL is returned.
1284  * If 'makeit' is 1 we attempt to track-down and create the namecache topology
1285  * for dvp.  This will fail only if the directory has been deleted out from
1286  * under the caller.  
1287  *
1288  * Callers must always check for a NULL return no matter the value of 'makeit'.
1289  *
1290  * To avoid underflowing the kernel stack each recursive call increments
1291  * the makeit variable.
1292  */
1293
1294 static int cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1295                                   struct vnode *dvp, char *fakename);
1296 static int cache_fromdvp_try(struct vnode *dvp, struct ucred *cred, 
1297                                   struct vnode **saved_dvp);
1298
1299 int
1300 cache_fromdvp(struct vnode *dvp, struct ucred *cred, int makeit,
1301               struct nchandle *nch)
1302 {
1303         struct vnode *saved_dvp;
1304         struct vnode *pvp;
1305         char *fakename;
1306         int error;
1307
1308         nch->ncp = NULL;
1309         nch->mount = dvp->v_mount;
1310         saved_dvp = NULL;
1311         fakename = NULL;
1312
1313         /*
1314          * Temporary debugging code to force the directory scanning code
1315          * to be exercised.
1316          */
1317         if (ncvp_debug >= 3 && makeit && TAILQ_FIRST(&dvp->v_namecache)) {
1318                 nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
1319                 kprintf("cache_fromdvp: forcing %s\n", nch->ncp->nc_name);
1320                 goto force;
1321         }
1322
1323         /*
1324          * Loop until resolution, inside code will break out on error.
1325          */
1326         while ((nch->ncp = TAILQ_FIRST(&dvp->v_namecache)) == NULL && makeit) {
1327 force:
1328                 /*
1329                  * If dvp is the root of its filesystem it should already
1330                  * have a namecache pointer associated with it as a side 
1331                  * effect of the mount, but it may have been disassociated.
1332                  */
1333                 if (dvp->v_flag & VROOT) {
1334                         nch->ncp = _cache_get(nch->mount->mnt_ncmountpt.ncp);
1335                         error = cache_resolve_mp(nch->mount);
1336                         _cache_put(nch->ncp);
1337                         if (ncvp_debug) {
1338                                 kprintf("cache_fromdvp: resolve root of mount %p error %d", 
1339                                         dvp->v_mount, error);
1340                         }
1341                         if (error) {
1342                                 if (ncvp_debug)
1343                                         kprintf(" failed\n");
1344                                 nch->ncp = NULL;
1345                                 break;
1346                         }
1347                         if (ncvp_debug)
1348                                 kprintf(" succeeded\n");
1349                         continue;
1350                 }
1351
1352                 /*
1353                  * If we are recursed too deeply resort to an O(n^2)
1354                  * algorithm to resolve the namecache topology.  The
1355                  * resolved pvp is left referenced in saved_dvp to
1356                  * prevent the tree from being destroyed while we loop.
1357                  */
1358                 if (makeit > 20) {
1359                         error = cache_fromdvp_try(dvp, cred, &saved_dvp);
1360                         if (error) {
1361                                 kprintf("lookupdotdot(longpath) failed %d "
1362                                        "dvp %p\n", error, dvp);
1363                                 nch->ncp = NULL;
1364                                 break;
1365                         }
1366                         continue;
1367                 }
1368
1369                 /*
1370                  * Get the parent directory and resolve its ncp.
1371                  */
1372                 if (fakename) {
1373                         kfree(fakename, M_TEMP);
1374                         fakename = NULL;
1375                 }
1376                 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
1377                                           &fakename);
1378                 if (error) {
1379                         kprintf("lookupdotdot failed %d dvp %p\n", error, dvp);
1380                         break;
1381                 }
1382                 vn_unlock(pvp);
1383
1384                 /*
1385                  * Reuse makeit as a recursion depth counter.  On success
1386                  * nch will be fully referenced.
1387                  */
1388                 cache_fromdvp(pvp, cred, makeit + 1, nch);
1389                 vrele(pvp);
1390                 if (nch->ncp == NULL)
1391                         break;
1392
1393                 /*
1394                  * Do an inefficient scan of pvp (embodied by ncp) to look
1395                  * for dvp.  This will create a namecache record for dvp on
1396                  * success.  We loop up to recheck on success.
1397                  *
1398                  * ncp and dvp are both held but not locked.
1399                  */
1400                 error = cache_inefficient_scan(nch, cred, dvp, fakename);
1401                 if (error) {
1402                         kprintf("cache_fromdvp: scan %p (%s) failed on dvp=%p\n",
1403                                 pvp, nch->ncp->nc_name, dvp);
1404                         cache_drop(nch);
1405                         /* nch was NULLed out, reload mount */
1406                         nch->mount = dvp->v_mount;
1407                         break;
1408                 }
1409                 if (ncvp_debug) {
1410                         kprintf("cache_fromdvp: scan %p (%s) succeeded\n",
1411                                 pvp, nch->ncp->nc_name);
1412                 }
1413                 cache_drop(nch);
1414                 /* nch was NULLed out, reload mount */
1415                 nch->mount = dvp->v_mount;
1416         }
1417
1418         if (fakename)
1419                 kfree(fakename, M_TEMP);
1420
1421         /*
1422          * hold it for real so the mount gets a ref
1423          */
1424         if (nch->ncp)
1425                 cache_hold(nch);
1426         if (saved_dvp)
1427                 vrele(saved_dvp);
1428         if (nch->ncp)
1429                 return (0);
1430         return (EINVAL);
1431 }
1432
1433 /*
1434  * Go up the chain of parent directories until we find something
1435  * we can resolve into the namecache.  This is very inefficient.
1436  */
1437 static
1438 int
1439 cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1440                   struct vnode **saved_dvp)
1441 {
1442         struct nchandle nch;
1443         struct vnode *pvp;
1444         int error;
1445         static time_t last_fromdvp_report;
1446         char *fakename;
1447
1448         /*
1449          * Loop getting the parent directory vnode until we get something we
1450          * can resolve in the namecache.
1451          */
1452         vref(dvp);
1453         nch.mount = dvp->v_mount;
1454         nch.ncp = NULL;
1455         fakename = NULL;
1456
1457         for (;;) {
1458                 if (fakename) {
1459                         kfree(fakename, M_TEMP);
1460                         fakename = NULL;
1461                 }
1462                 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
1463                                           &fakename);
1464                 if (error) {
1465                         vrele(dvp);
1466                         break;
1467                 }
1468                 vn_unlock(pvp);
1469                 if ((nch.ncp = TAILQ_FIRST(&pvp->v_namecache)) != NULL) {
1470                         _cache_hold(nch.ncp);
1471                         vrele(pvp);
1472                         break;
1473                 }
1474                 if (pvp->v_flag & VROOT) {
1475                         nch.ncp = _cache_get(pvp->v_mount->mnt_ncmountpt.ncp);
1476                         error = cache_resolve_mp(nch.mount);
1477                         _cache_unlock(nch.ncp);
1478                         vrele(pvp);
1479                         if (error) {
1480                                 _cache_drop(nch.ncp);
1481                                 nch.ncp = NULL;
1482                                 vrele(dvp);
1483                         }
1484                         break;
1485                 }
1486                 vrele(dvp);
1487                 dvp = pvp;
1488         }
1489         if (error == 0) {
1490                 if (last_fromdvp_report != time_second) {
1491                         last_fromdvp_report = time_second;
1492                         kprintf("Warning: extremely inefficient path "
1493                                 "resolution on %s\n",
1494                                 nch.ncp->nc_name);
1495                 }
1496                 error = cache_inefficient_scan(&nch, cred, dvp, fakename);
1497
1498                 /*
1499                  * Hopefully dvp now has a namecache record associated with
1500                  * it.  Leave it referenced to prevent the kernel from
1501                  * recycling the vnode.  Otherwise extremely long directory
1502                  * paths could result in endless recycling.
1503                  */
1504                 if (*saved_dvp)
1505                     vrele(*saved_dvp);
1506                 *saved_dvp = dvp;
1507                 _cache_drop(nch.ncp);
1508         }
1509         if (fakename)
1510                 kfree(fakename, M_TEMP);
1511         return (error);
1512 }
1513
1514 /*
1515  * Do an inefficient scan of the directory represented by ncp looking for
1516  * the directory vnode dvp.  ncp must be held but not locked on entry and
1517  * will be held on return.  dvp must be refd but not locked on entry and
1518  * will remain refd on return.
1519  *
1520  * Why do this at all?  Well, due to its stateless nature the NFS server
1521  * converts file handles directly to vnodes without necessarily going through
1522  * the namecache ops that would otherwise create the namecache topology
1523  * leading to the vnode.  We could either (1) Change the namecache algorithms
1524  * to allow disconnect namecache records that are re-merged opportunistically,
1525  * or (2) Make the NFS server backtrack and scan to recover a connected
1526  * namecache topology in order to then be able to issue new API lookups.
1527  *
1528  * It turns out that (1) is a huge mess.  It takes a nice clean set of 
1529  * namecache algorithms and introduces a lot of complication in every subsystem
1530  * that calls into the namecache to deal with the re-merge case, especially
1531  * since we are using the namecache to placehold negative lookups and the
1532  * vnode might not be immediately assigned. (2) is certainly far less
1533  * efficient then (1), but since we are only talking about directories here
1534  * (which are likely to remain cached), the case does not actually run all
1535  * that often and has the supreme advantage of not polluting the namecache
1536  * algorithms.
1537  *
1538  * If a fakename is supplied just construct a namecache entry using the
1539  * fake name.
1540  */
1541 static int
1542 cache_inefficient_scan(struct nchandle *nch, struct ucred *cred, 
1543                        struct vnode *dvp, char *fakename)
1544 {
1545         struct nlcomponent nlc;
1546         struct nchandle rncp;
1547         struct dirent *den;
1548         struct vnode *pvp;
1549         struct vattr vat;
1550         struct iovec iov;
1551         struct uio uio;
1552         int blksize;
1553         int eofflag;
1554         int bytes;
1555         char *rbuf;
1556         int error;
1557
1558         vat.va_blocksize = 0;
1559         if ((error = VOP_GETATTR(dvp, &vat)) != 0)
1560                 return (error);
1561         if ((error = cache_vref(nch, cred, &pvp)) != 0)
1562                 return (error);
1563         if (ncvp_debug)
1564                 kprintf("inefficient_scan: directory iosize %ld vattr fileid = %lld\n", vat.va_blocksize, vat.va_fileid);
1565
1566         /*
1567          * Use the supplied fakename if not NULL.  Fake names are typically
1568          * not in the actual filesystem hierarchy.  This is used by HAMMER
1569          * to glue @@timestamp recursions together.
1570          */
1571         if (fakename) {
1572                 nlc.nlc_nameptr = fakename;
1573                 nlc.nlc_namelen = strlen(fakename);
1574                 rncp = cache_nlookup(nch, &nlc);
1575                 goto done;
1576         }
1577
1578         if ((blksize = vat.va_blocksize) == 0)
1579                 blksize = DEV_BSIZE;
1580         rbuf = kmalloc(blksize, M_TEMP, M_WAITOK);
1581         rncp.ncp = NULL;
1582
1583         eofflag = 0;
1584         uio.uio_offset = 0;
1585 again:
1586         iov.iov_base = rbuf;
1587         iov.iov_len = blksize;
1588         uio.uio_iov = &iov;
1589         uio.uio_iovcnt = 1;
1590         uio.uio_resid = blksize;
1591         uio.uio_segflg = UIO_SYSSPACE;
1592         uio.uio_rw = UIO_READ;
1593         uio.uio_td = curthread;
1594
1595         if (ncvp_debug >= 2)
1596                 kprintf("cache_inefficient_scan: readdir @ %08x\n", (int)uio.uio_offset);
1597         error = VOP_READDIR(pvp, &uio, cred, &eofflag, NULL, NULL);
1598         if (error == 0) {
1599                 den = (struct dirent *)rbuf;
1600                 bytes = blksize - uio.uio_resid;
1601
1602                 while (bytes > 0) {
1603                         if (ncvp_debug >= 2) {
1604                                 kprintf("cache_inefficient_scan: %*.*s\n",
1605                                         den->d_namlen, den->d_namlen, 
1606                                         den->d_name);
1607                         }
1608                         if (den->d_type != DT_WHT &&
1609                             den->d_ino == vat.va_fileid) {
1610                                 if (ncvp_debug) {
1611                                         kprintf("cache_inefficient_scan: "
1612                                                "MATCHED inode %lld path %s/%*.*s\n",
1613                                                vat.va_fileid, nch->ncp->nc_name,
1614                                                den->d_namlen, den->d_namlen,
1615                                                den->d_name);
1616                                 }
1617                                 nlc.nlc_nameptr = den->d_name;
1618                                 nlc.nlc_namelen = den->d_namlen;
1619                                 rncp = cache_nlookup(nch, &nlc);
1620                                 KKASSERT(rncp.ncp != NULL);
1621                                 break;
1622                         }
1623                         bytes -= _DIRENT_DIRSIZ(den);
1624                         den = _DIRENT_NEXT(den);
1625                 }
1626                 if (rncp.ncp == NULL && eofflag == 0 && uio.uio_resid != blksize)
1627                         goto again;
1628         }
1629         kfree(rbuf, M_TEMP);
1630 done:
1631         vrele(pvp);
1632         if (rncp.ncp) {
1633                 if (rncp.ncp->nc_flag & NCF_UNRESOLVED) {
1634                         _cache_setvp(rncp.ncp, dvp);
1635                         if (ncvp_debug >= 2) {
1636                                 kprintf("cache_inefficient_scan: setvp %s/%s = %p\n",
1637                                         nch->ncp->nc_name, rncp.ncp->nc_name, dvp);
1638                         }
1639                 } else {
1640                         if (ncvp_debug >= 2) {
1641                                 kprintf("cache_inefficient_scan: setvp %s/%s already set %p/%p\n", 
1642                                         nch->ncp->nc_name, rncp.ncp->nc_name, dvp,
1643                                         rncp.ncp->nc_vp);
1644                         }
1645                 }
1646                 if (rncp.ncp->nc_vp == NULL)
1647                         error = rncp.ncp->nc_error;
1648                 /* 
1649                  * Release rncp after a successful nlookup.  rncp was fully
1650                  * referenced.
1651                  */
1652                 cache_put(&rncp);
1653         } else {
1654                 kprintf("cache_inefficient_scan: dvp %p NOT FOUND in %s\n",
1655                         dvp, nch->ncp->nc_name);
1656                 error = ENOENT;
1657         }
1658         return (error);
1659 }
1660
1661 /*
1662  * Zap a namecache entry.  The ncp is unconditionally set to an unresolved
1663  * state, which disassociates it from its vnode or ncneglist.
1664  *
1665  * Then, if there are no additional references to the ncp and no children,
1666  * the ncp is removed from the topology and destroyed.  This function will
1667  * also run through the nc_parent chain and destroy parent ncps if possible.
1668  * As a side benefit, it turns out the only conditions that allow running
1669  * up the chain are also the conditions to ensure no deadlock will occur.
1670  *
1671  * References and/or children may exist if the ncp is in the middle of the
1672  * topology, preventing the ncp from being destroyed.
1673  *
1674  * This function must be called with the ncp held and locked and will unlock
1675  * and drop it during zapping.
1676  */
1677 static void
1678 cache_zap(struct namecache *ncp)
1679 {
1680         struct namecache *par;
1681
1682         /*
1683          * Disassociate the vnode or negative cache ref and set NCF_UNRESOLVED.
1684          */
1685         _cache_setunresolved(ncp);
1686
1687         /*
1688          * Try to scrap the entry and possibly tail-recurse on its parent.
1689          * We only scrap unref'd (other then our ref) unresolved entries,
1690          * we do not scrap 'live' entries.
1691          */
1692         while (ncp->nc_flag & NCF_UNRESOLVED) {
1693                 /*
1694                  * Someone other then us has a ref, stop.
1695                  */
1696                 if (ncp->nc_refs > 1)
1697                         goto done;
1698
1699                 /*
1700                  * We have children, stop.
1701                  */
1702                 if (!TAILQ_EMPTY(&ncp->nc_list))
1703                         goto done;
1704
1705                 /*
1706                  * Remove ncp from the topology: hash table and parent linkage.
1707                  */
1708                 if (ncp->nc_flag & NCF_HASHED) {
1709                         ncp->nc_flag &= ~NCF_HASHED;
1710                         LIST_REMOVE(ncp, nc_hash);
1711                 }
1712                 if ((par = ncp->nc_parent) != NULL) {
1713                         par = _cache_hold(par);
1714                         TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
1715                         ncp->nc_parent = NULL;
1716                         if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
1717                                 vdrop(par->nc_vp);
1718                 }
1719
1720                 /*
1721                  * ncp should not have picked up any refs.  Physically
1722                  * destroy the ncp.
1723                  */
1724                 KKASSERT(ncp->nc_refs == 1);
1725                 --numunres;
1726                 /* _cache_unlock(ncp) not required */
1727                 ncp->nc_refs = -1;      /* safety */
1728                 if (ncp->nc_name)
1729                         kfree(ncp->nc_name, M_VFSCACHE);
1730                 kfree(ncp, M_VFSCACHE);
1731
1732                 /*
1733                  * Loop on the parent (it may be NULL).  Only bother looping
1734                  * if the parent has a single ref (ours), which also means
1735                  * we can lock it trivially.
1736                  */
1737                 ncp = par;
1738                 if (ncp == NULL)
1739                         return;
1740                 if (ncp->nc_refs != 1) {
1741                         _cache_drop(ncp);
1742                         return;
1743                 }
1744                 KKASSERT(par->nc_exlocks == 0);
1745                 _cache_lock(ncp);
1746         }
1747 done:
1748         _cache_unlock(ncp);
1749         atomic_subtract_int(&ncp->nc_refs, 1);
1750 }
1751
1752 static enum { CHI_LOW, CHI_HIGH } cache_hysteresis_state = CHI_LOW;
1753
1754 static __inline
1755 void
1756 cache_hysteresis(void)
1757 {
1758         /*
1759          * Don't cache too many negative hits.  We use hysteresis to reduce
1760          * the impact on the critical path.
1761          */
1762         switch(cache_hysteresis_state) {
1763         case CHI_LOW:
1764                 if (numneg > MINNEG && numneg * ncnegfactor > numcache) {
1765                         cache_cleanneg(10);
1766                         cache_hysteresis_state = CHI_HIGH;
1767                 }
1768                 break;
1769         case CHI_HIGH:
1770                 if (numneg > MINNEG * 9 / 10 && 
1771                     numneg * ncnegfactor * 9 / 10 > numcache
1772                 ) {
1773                         cache_cleanneg(10);
1774                 } else {
1775                         cache_hysteresis_state = CHI_LOW;
1776                 }
1777                 break;
1778         }
1779 }
1780
1781 /*
1782  * NEW NAMECACHE LOOKUP API
1783  *
1784  * Lookup an entry in the cache.  A locked, referenced, non-NULL 
1785  * entry is *always* returned, even if the supplied component is illegal.
1786  * The resulting namecache entry should be returned to the system with
1787  * cache_put() or _cache_unlock() + cache_drop().
1788  *
1789  * namecache locks are recursive but care must be taken to avoid lock order
1790  * reversals.
1791  *
1792  * Nobody else will be able to manipulate the associated namespace (e.g.
1793  * create, delete, rename, rename-target) until the caller unlocks the
1794  * entry.
1795  *
1796  * The returned entry will be in one of three states:  positive hit (non-null
1797  * vnode), negative hit (null vnode), or unresolved (NCF_UNRESOLVED is set).
1798  * Unresolved entries must be resolved through the filesystem to associate the
1799  * vnode and/or determine whether a positive or negative hit has occured.
1800  *
1801  * It is not necessary to lock a directory in order to lock namespace under
1802  * that directory.  In fact, it is explicitly not allowed to do that.  A
1803  * directory is typically only locked when being created, renamed, or
1804  * destroyed.
1805  *
1806  * The directory (par) may be unresolved, in which case any returned child
1807  * will likely also be marked unresolved.  Likely but not guarenteed.  Since
1808  * the filesystem lookup requires a resolved directory vnode the caller is
1809  * responsible for resolving the namecache chain top-down.  This API 
1810  * specifically allows whole chains to be created in an unresolved state.
1811  */
1812 struct nchandle
1813 cache_nlookup(struct nchandle *par_nch, struct nlcomponent *nlc)
1814 {
1815         struct nchandle nch;
1816         struct namecache *ncp;
1817         struct namecache *new_ncp;
1818         struct nchashhead *nchpp;
1819         u_int32_t hash;
1820         globaldata_t gd;
1821
1822         numcalls++;
1823         gd = mycpu;
1824
1825         /*
1826          * Try to locate an existing entry
1827          */
1828         hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
1829         hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
1830         new_ncp = NULL;
1831 restart:
1832         LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1833                 numchecks++;
1834
1835                 /*
1836                  * Try to zap entries that have timed out.  We have
1837                  * to be careful here because locked leafs may depend
1838                  * on the vnode remaining intact in a parent, so only
1839                  * do this under very specific conditions.
1840                  */
1841                 if (ncp->nc_timeout && 
1842                     (int)(ncp->nc_timeout - ticks) < 0 &&
1843                     (ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
1844                     ncp->nc_exlocks == 0 &&
1845                     TAILQ_EMPTY(&ncp->nc_list)
1846                 ) {
1847                         cache_zap(_cache_get(ncp));
1848                         goto restart;
1849                 }
1850
1851                 /*
1852                  * Break out if we find a matching entry.  Note that
1853                  * UNRESOLVED entries may match, but DESTROYED entries
1854                  * do not.
1855                  */
1856                 if (ncp->nc_parent == par_nch->ncp &&
1857                     ncp->nc_nlen == nlc->nlc_namelen &&
1858                     bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
1859                     (ncp->nc_flag & NCF_DESTROYED) == 0
1860                 ) {
1861                         if (_cache_get_nonblock(ncp) == 0) {
1862                                 if (new_ncp)
1863                                         _cache_free(new_ncp);
1864                                 goto found;
1865                         }
1866                         _cache_get(ncp);
1867                         _cache_put(ncp);
1868                         goto restart;
1869                 }
1870         }
1871
1872         /*
1873          * We failed to locate an entry, create a new entry and add it to
1874          * the cache.  We have to relookup after possibly blocking in
1875          * malloc.
1876          */
1877         if (new_ncp == NULL) {
1878                 new_ncp = cache_alloc(nlc->nlc_namelen);
1879                 goto restart;
1880         }
1881
1882         ncp = new_ncp;
1883
1884         /*
1885          * Initialize as a new UNRESOLVED entry, lock (non-blocking),
1886          * and link to the parent.  The mount point is usually inherited
1887          * from the parent unless this is a special case such as a mount
1888          * point where nlc_namelen is 0.   If nlc_namelen is 0 nc_name will
1889          * be NULL.
1890          */
1891         if (nlc->nlc_namelen) {
1892                 bcopy(nlc->nlc_nameptr, ncp->nc_name, nlc->nlc_namelen);
1893                 ncp->nc_name[nlc->nlc_namelen] = 0;
1894         }
1895         nchpp = NCHHASH(hash);
1896         LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
1897         ncp->nc_flag |= NCF_HASHED;
1898         cache_link_parent(ncp, par_nch->ncp);
1899 found:
1900         /*
1901          * stats and namecache size management
1902          */
1903         if (ncp->nc_flag & NCF_UNRESOLVED)
1904                 ++gd->gd_nchstats->ncs_miss;
1905         else if (ncp->nc_vp)
1906                 ++gd->gd_nchstats->ncs_goodhits;
1907         else
1908                 ++gd->gd_nchstats->ncs_neghits;
1909         cache_hysteresis();
1910         nch.mount = par_nch->mount;
1911         nch.ncp = ncp;
1912         ++nch.mount->mnt_refs;
1913         return(nch);
1914 }
1915
1916 /*
1917  * The namecache entry is marked as being used as a mount point. 
1918  * Locate the mount if it is visible to the caller.
1919  */
1920 struct findmount_info {
1921         struct mount *result;
1922         struct mount *nch_mount;
1923         struct namecache *nch_ncp;
1924 };
1925
1926 static
1927 int
1928 cache_findmount_callback(struct mount *mp, void *data)
1929 {
1930         struct findmount_info *info = data;
1931
1932         /*
1933          * Check the mount's mounted-on point against the passed nch.
1934          */
1935         if (mp->mnt_ncmounton.mount == info->nch_mount &&
1936             mp->mnt_ncmounton.ncp == info->nch_ncp
1937         ) {
1938             info->result = mp;
1939             return(-1);
1940         }
1941         return(0);
1942 }
1943
1944 struct mount *
1945 cache_findmount(struct nchandle *nch)
1946 {
1947         struct findmount_info info;
1948
1949         info.result = NULL;
1950         info.nch_mount = nch->mount;
1951         info.nch_ncp = nch->ncp;
1952         mountlist_scan(cache_findmount_callback, &info,
1953                                MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1954         return(info.result);
1955 }
1956
1957 /*
1958  * Resolve an unresolved namecache entry, generally by looking it up.
1959  * The passed ncp must be locked and refd. 
1960  *
1961  * Theoretically since a vnode cannot be recycled while held, and since
1962  * the nc_parent chain holds its vnode as long as children exist, the
1963  * direct parent of the cache entry we are trying to resolve should
1964  * have a valid vnode.  If not then generate an error that we can 
1965  * determine is related to a resolver bug.
1966  *
1967  * However, if a vnode was in the middle of a recyclement when the NCP
1968  * got locked, ncp->nc_vp might point to a vnode that is about to become
1969  * invalid.  cache_resolve() handles this case by unresolving the entry
1970  * and then re-resolving it.
1971  *
1972  * Note that successful resolution does not necessarily return an error
1973  * code of 0.  If the ncp resolves to a negative cache hit then ENOENT
1974  * will be returned.
1975  */
1976 int
1977 cache_resolve(struct nchandle *nch, struct ucred *cred)
1978 {
1979         struct namecache *par;
1980         struct namecache *ncp;
1981         struct nchandle nctmp;
1982         struct mount *mp;
1983         struct vnode *dvp;
1984         int error;
1985
1986         ncp = nch->ncp;
1987         mp = nch->mount;
1988 restart:
1989         /*
1990          * If the ncp is already resolved we have nothing to do.  However,
1991          * we do want to guarentee that a usable vnode is returned when
1992          * a vnode is present, so make sure it hasn't been reclaimed.
1993          */
1994         if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1995                 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
1996                         _cache_setunresolved(ncp);
1997                 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
1998                         return (ncp->nc_error);
1999         }
2000
2001         /*
2002          * Mount points need special handling because the parent does not
2003          * belong to the same filesystem as the ncp.
2004          */
2005         if (ncp == mp->mnt_ncmountpt.ncp)
2006                 return (cache_resolve_mp(mp));
2007
2008         /*
2009          * We expect an unbroken chain of ncps to at least the mount point,
2010          * and even all the way to root (but this code doesn't have to go
2011          * past the mount point).
2012          */
2013         if (ncp->nc_parent == NULL) {
2014                 kprintf("EXDEV case 1 %p %*.*s\n", ncp,
2015                         ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
2016                 ncp->nc_error = EXDEV;
2017                 return(ncp->nc_error);
2018         }
2019
2020         /*
2021          * The vp's of the parent directories in the chain are held via vhold()
2022          * due to the existance of the child, and should not disappear. 
2023          * However, there are cases where they can disappear:
2024          *
2025          *      - due to filesystem I/O errors.
2026          *      - due to NFS being stupid about tracking the namespace and
2027          *        destroys the namespace for entire directories quite often.
2028          *      - due to forced unmounts.
2029          *      - due to an rmdir (parent will be marked DESTROYED)
2030          *
2031          * When this occurs we have to track the chain backwards and resolve
2032          * it, looping until the resolver catches up to the current node.  We
2033          * could recurse here but we might run ourselves out of kernel stack
2034          * so we do it in a more painful manner.  This situation really should
2035          * not occur all that often, or if it does not have to go back too
2036          * many nodes to resolve the ncp.
2037          */
2038         while (ncp->nc_parent->nc_vp == NULL) {
2039                 /*
2040                  * This case can occur if a process is CD'd into a
2041                  * directory which is then rmdir'd.  If the parent is marked
2042                  * destroyed there is no point trying to resolve it.
2043                  */
2044                 if (ncp->nc_parent->nc_flag & NCF_DESTROYED)
2045                         return(ENOENT);
2046
2047                 par = ncp->nc_parent;
2048                 while (par->nc_parent && par->nc_parent->nc_vp == NULL)
2049                         par = par->nc_parent;
2050                 if (par->nc_parent == NULL) {
2051                         kprintf("EXDEV case 2 %*.*s\n",
2052                                 par->nc_nlen, par->nc_nlen, par->nc_name);
2053                         return (EXDEV);
2054                 }
2055                 kprintf("[diagnostic] cache_resolve: had to recurse on %*.*s\n",
2056                         par->nc_nlen, par->nc_nlen, par->nc_name);
2057                 /*
2058                  * The parent is not set in stone, ref and lock it to prevent
2059                  * it from disappearing.  Also note that due to renames it
2060                  * is possible for our ncp to move and for par to no longer
2061                  * be one of its parents.  We resolve it anyway, the loop 
2062                  * will handle any moves.
2063                  */
2064                 _cache_get(par);
2065                 if (par == nch->mount->mnt_ncmountpt.ncp) {
2066                         cache_resolve_mp(nch->mount);
2067                 } else if ((dvp = cache_dvpref(par)) == NULL) {
2068                         kprintf("[diagnostic] cache_resolve: raced on %*.*s\n", par->nc_nlen, par->nc_nlen, par->nc_name);
2069                         _cache_put(par);
2070                         continue;
2071                 } else {
2072                         if (par->nc_flag & NCF_UNRESOLVED) {
2073                                 nctmp.mount = mp;
2074                                 nctmp.ncp = par;
2075                                 par->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
2076                         }
2077                         cache_dvprel(dvp);
2078                 }
2079                 if ((error = par->nc_error) != 0) {
2080                         if (par->nc_error != EAGAIN) {
2081                                 kprintf("EXDEV case 3 %*.*s error %d\n",
2082                                     par->nc_nlen, par->nc_nlen, par->nc_name,
2083                                     par->nc_error);
2084                                 _cache_put(par);
2085                                 return(error);
2086                         }
2087                         kprintf("[diagnostic] cache_resolve: EAGAIN par %p %*.*s\n",
2088                                 par, par->nc_nlen, par->nc_nlen, par->nc_name);
2089                 }
2090                 _cache_put(par);
2091                 /* loop */
2092         }
2093
2094         /*
2095          * Call VOP_NRESOLVE() to get the vp, then scan for any disconnected
2096          * ncp's and reattach them.  If this occurs the original ncp is marked
2097          * EAGAIN to force a relookup.
2098          *
2099          * NOTE: in order to call VOP_NRESOLVE(), the parent of the passed
2100          * ncp must already be resolved.
2101          */
2102         if ((dvp = cache_dvpref(ncp)) != NULL) {
2103                 nctmp.mount = mp;
2104                 nctmp.ncp = ncp;
2105                 ncp->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
2106                 cache_dvprel(dvp);
2107         } else {
2108                 ncp->nc_error = EPERM;
2109         }
2110         if (ncp->nc_error == EAGAIN) {
2111                 kprintf("[diagnostic] cache_resolve: EAGAIN ncp %p %*.*s\n",
2112                         ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
2113                 goto restart;
2114         }
2115         return(ncp->nc_error);
2116 }
2117
2118 /*
2119  * Resolve the ncp associated with a mount point.  Such ncp's almost always
2120  * remain resolved and this routine is rarely called.  NFS MPs tends to force
2121  * re-resolution more often due to its mac-truck-smash-the-namecache
2122  * method of tracking namespace changes.
2123  *
2124  * The semantics for this call is that the passed ncp must be locked on
2125  * entry and will be locked on return.  However, if we actually have to
2126  * resolve the mount point we temporarily unlock the entry in order to
2127  * avoid race-to-root deadlocks due to e.g. dead NFS mounts.  Because of
2128  * the unlock we have to recheck the flags after we relock.
2129  */
2130 static int
2131 cache_resolve_mp(struct mount *mp)
2132 {
2133         struct namecache *ncp = mp->mnt_ncmountpt.ncp;
2134         struct vnode *vp;
2135         int error;
2136
2137         KKASSERT(mp != NULL);
2138
2139         /*
2140          * If the ncp is already resolved we have nothing to do.  However,
2141          * we do want to guarentee that a usable vnode is returned when
2142          * a vnode is present, so make sure it hasn't been reclaimed.
2143          */
2144         if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
2145                 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
2146                         _cache_setunresolved(ncp);
2147         }
2148
2149         if (ncp->nc_flag & NCF_UNRESOLVED) {
2150                 _cache_unlock(ncp);
2151                 while (vfs_busy(mp, 0))
2152                         ;
2153                 error = VFS_ROOT(mp, &vp);
2154                 _cache_lock(ncp);
2155
2156                 /*
2157                  * recheck the ncp state after relocking.
2158                  */
2159                 if (ncp->nc_flag & NCF_UNRESOLVED) {
2160                         ncp->nc_error = error;
2161                         if (error == 0) {
2162                                 _cache_setvp(ncp, vp);
2163                                 vput(vp);
2164                         } else {
2165                                 kprintf("[diagnostic] cache_resolve_mp: failed to resolve mount %p\n", mp);
2166                                 _cache_setvp(ncp, NULL);
2167                         }
2168                 } else if (error == 0) {
2169                         vput(vp);
2170                 }
2171                 vfs_unbusy(mp);
2172         }
2173         return(ncp->nc_error);
2174 }
2175
2176 void
2177 cache_cleanneg(int count)
2178 {
2179         struct namecache *ncp;
2180
2181         /*
2182          * Automode from the vnlru proc - clean out 10% of the negative cache
2183          * entries.
2184          */
2185         if (count == 0)
2186                 count = numneg / 10 + 1;
2187
2188         /*
2189          * Attempt to clean out the specified number of negative cache
2190          * entries.
2191          */
2192         while (count) {
2193                 ncp = TAILQ_FIRST(&ncneglist);
2194                 if (ncp == NULL) {
2195                         KKASSERT(numneg == 0);
2196                         break;
2197                 }
2198                 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
2199                 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
2200                 if (_cache_get_nonblock(ncp) == 0)
2201                         cache_zap(ncp);
2202                 --count;
2203         }
2204 }
2205
2206 /*
2207  * Rehash a ncp.  Rehashing is typically required if the name changes (should
2208  * not generally occur) or the parent link changes.  This function will
2209  * unhash the ncp if the ncp is no longer hashable.
2210  */
2211 static void
2212 _cache_rehash(struct namecache *ncp)
2213 {
2214         struct nchashhead *nchpp;
2215         u_int32_t hash;
2216
2217         if (ncp->nc_flag & NCF_HASHED) {
2218                 ncp->nc_flag &= ~NCF_HASHED;
2219                 LIST_REMOVE(ncp, nc_hash);
2220         }
2221         if (ncp->nc_nlen && ncp->nc_parent) {
2222                 hash = fnv_32_buf(ncp->nc_name, ncp->nc_nlen, FNV1_32_INIT);
2223                 hash = fnv_32_buf(&ncp->nc_parent, 
2224                                         sizeof(ncp->nc_parent), hash);
2225                 nchpp = NCHHASH(hash);
2226                 LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
2227                 ncp->nc_flag |= NCF_HASHED;
2228         }
2229 }
2230
2231 /*
2232  * Name cache initialization, from vfsinit() when we are booting
2233  */
2234 void
2235 nchinit(void)
2236 {
2237         int i;
2238         globaldata_t gd;
2239
2240         /* initialise per-cpu namecache effectiveness statistics. */
2241         for (i = 0; i < ncpus; ++i) {
2242                 gd = globaldata_find(i);
2243                 gd->gd_nchstats = &nchstats[i];
2244         }
2245         TAILQ_INIT(&ncneglist);
2246         nchashtbl = hashinit(desiredvnodes*2, M_VFSCACHE, &nchash);
2247         nclockwarn = 1 * hz;
2248 }
2249
2250 /*
2251  * Called from start_init() to bootstrap the root filesystem.  Returns
2252  * a referenced, unlocked namecache record.
2253  */
2254 void
2255 cache_allocroot(struct nchandle *nch, struct mount *mp, struct vnode *vp)
2256 {
2257         nch->ncp = cache_alloc(0);
2258         nch->mount = mp;
2259         ++mp->mnt_refs;
2260         if (vp)
2261                 _cache_setvp(nch->ncp, vp);
2262 }
2263
2264 /*
2265  * vfs_cache_setroot()
2266  *
2267  *      Create an association between the root of our namecache and
2268  *      the root vnode.  This routine may be called several times during
2269  *      booting.
2270  *
2271  *      If the caller intends to save the returned namecache pointer somewhere
2272  *      it must cache_hold() it.
2273  */
2274 void
2275 vfs_cache_setroot(struct vnode *nvp, struct nchandle *nch)
2276 {
2277         struct vnode *ovp;
2278         struct nchandle onch;
2279
2280         ovp = rootvnode;
2281         onch = rootnch;
2282         rootvnode = nvp;
2283         if (nch)
2284                 rootnch = *nch;
2285         else
2286                 cache_zero(&rootnch);
2287         if (ovp)
2288                 vrele(ovp);
2289         if (onch.ncp)
2290                 cache_drop(&onch);
2291 }
2292
2293 /*
2294  * XXX OLD API COMPAT FUNCTION.  This really messes up the new namecache
2295  * topology and is being removed as quickly as possible.  The new VOP_N*()
2296  * API calls are required to make specific adjustments using the supplied
2297  * ncp pointers rather then just bogusly purging random vnodes.
2298  *
2299  * Invalidate all namecache entries to a particular vnode as well as 
2300  * any direct children of that vnode in the namecache.  This is a 
2301  * 'catch all' purge used by filesystems that do not know any better.
2302  *
2303  * Note that the linkage between the vnode and its namecache entries will
2304  * be removed, but the namecache entries themselves might stay put due to
2305  * active references from elsewhere in the system or due to the existance of
2306  * the children.   The namecache topology is left intact even if we do not
2307  * know what the vnode association is.  Such entries will be marked
2308  * NCF_UNRESOLVED.
2309  */
2310 void
2311 cache_purge(struct vnode *vp)
2312 {
2313         cache_inval_vp(vp, CINV_DESTROY | CINV_CHILDREN);
2314 }
2315
2316 /*
2317  * Flush all entries referencing a particular filesystem.
2318  *
2319  * Since we need to check it anyway, we will flush all the invalid
2320  * entries at the same time.
2321  */
2322 #if 0
2323
2324 void
2325 cache_purgevfs(struct mount *mp)
2326 {
2327         struct nchashhead *nchpp;
2328         struct namecache *ncp, *nnp;
2329
2330         /*
2331          * Scan hash tables for applicable entries.
2332          */
2333         for (nchpp = &nchashtbl[nchash]; nchpp >= nchashtbl; nchpp--) {
2334                 ncp = LIST_FIRST(nchpp);
2335                 if (ncp)
2336                         _cache_hold(ncp);
2337                 while (ncp) {
2338                         nnp = LIST_NEXT(ncp, nc_hash);
2339                         if (nnp)
2340                                 _cache_hold(nnp);
2341                         if (ncp->nc_mount == mp) {
2342                                 _cache_lock(ncp);
2343                                 cache_zap(ncp);
2344                         } else {
2345                                 _cache_drop(ncp);
2346                         }
2347                         ncp = nnp;
2348                 }
2349         }
2350 }
2351
2352 #endif
2353
2354 /*
2355  * Create a new (theoretically) unique fsmid
2356  */
2357 int64_t
2358 cache_getnewfsmid(void)
2359 {
2360         static int fsmid_roller;
2361         int64_t fsmid;
2362
2363         ++fsmid_roller;
2364         fsmid = ((int64_t)time_second << 32) |
2365                         (fsmid_roller & 0x7FFFFFFF);
2366         return (fsmid);
2367 }
2368
2369
2370 static int disablecwd;
2371 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0, "");
2372
2373 static u_long numcwdcalls; STATNODE(CTLFLAG_RD, numcwdcalls, &numcwdcalls);
2374 static u_long numcwdfail1; STATNODE(CTLFLAG_RD, numcwdfail1, &numcwdfail1);
2375 static u_long numcwdfail2; STATNODE(CTLFLAG_RD, numcwdfail2, &numcwdfail2);
2376 static u_long numcwdfail3; STATNODE(CTLFLAG_RD, numcwdfail3, &numcwdfail3);
2377 static u_long numcwdfail4; STATNODE(CTLFLAG_RD, numcwdfail4, &numcwdfail4);
2378 static u_long numcwdfound; STATNODE(CTLFLAG_RD, numcwdfound, &numcwdfound);
2379
2380 int
2381 sys___getcwd(struct __getcwd_args *uap)
2382 {
2383         int buflen;
2384         int error;
2385         char *buf;
2386         char *bp;
2387
2388         if (disablecwd)
2389                 return (ENODEV);
2390
2391         buflen = uap->buflen;
2392         if (buflen < 2)
2393                 return (EINVAL);
2394         if (buflen > MAXPATHLEN)
2395                 buflen = MAXPATHLEN;
2396
2397         buf = kmalloc(buflen, M_TEMP, M_WAITOK);
2398         bp = kern_getcwd(buf, buflen, &error);
2399         if (error == 0)
2400                 error = copyout(bp, uap->buf, strlen(bp) + 1);
2401         kfree(buf, M_TEMP);
2402         return (error);
2403 }
2404
2405 char *
2406 kern_getcwd(char *buf, size_t buflen, int *error)
2407 {
2408         struct proc *p = curproc;
2409         char *bp;
2410         int i, slash_prefixed;
2411         struct filedesc *fdp;
2412         struct nchandle nch;
2413
2414         numcwdcalls++;
2415         bp = buf;
2416         bp += buflen - 1;
2417         *bp = '\0';
2418         fdp = p->p_fd;
2419         slash_prefixed = 0;
2420
2421         nch = fdp->fd_ncdir;
2422         while (nch.ncp && (nch.ncp != fdp->fd_nrdir.ncp || 
2423                nch.mount != fdp->fd_nrdir.mount)
2424         ) {
2425                 /*
2426                  * While traversing upwards if we encounter the root
2427                  * of the current mount we have to skip to the mount point
2428                  * in the underlying filesystem.
2429                  */
2430                 if (nch.ncp == nch.mount->mnt_ncmountpt.ncp) {
2431                         nch = nch.mount->mnt_ncmounton;
2432                         continue;
2433                 }
2434
2435                 /*
2436                  * Prepend the path segment
2437                  */
2438                 for (i = nch.ncp->nc_nlen - 1; i >= 0; i--) {
2439                         if (bp == buf) {
2440                                 numcwdfail4++;
2441                                 *error = ENOMEM;
2442                                 return(NULL);
2443                         }
2444                         *--bp = nch.ncp->nc_name[i];
2445                 }
2446                 if (bp == buf) {
2447                         numcwdfail4++;
2448                         *error = ENOMEM;
2449                         return(NULL);
2450                 }
2451                 *--bp = '/';
2452                 slash_prefixed = 1;
2453
2454                 /*
2455                  * Go up a directory.  This isn't a mount point so we don't
2456                  * have to check again.
2457                  */
2458                 nch.ncp = nch.ncp->nc_parent;
2459         }
2460         if (nch.ncp == NULL) {
2461                 numcwdfail2++;
2462                 *error = ENOENT;
2463                 return(NULL);
2464         }
2465         if (!slash_prefixed) {
2466                 if (bp == buf) {
2467                         numcwdfail4++;
2468                         *error = ENOMEM;
2469                         return(NULL);
2470                 }
2471                 *--bp = '/';
2472         }
2473         numcwdfound++;
2474         *error = 0;
2475         return (bp);
2476 }
2477
2478 /*
2479  * Thus begins the fullpath magic.
2480  */
2481
2482 #undef STATNODE
2483 #define STATNODE(name)                                                  \
2484         static u_int name;                                              \
2485         SYSCTL_UINT(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, "")
2486
2487 static int disablefullpath;
2488 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW,
2489     &disablefullpath, 0, "");
2490
2491 STATNODE(numfullpathcalls);
2492 STATNODE(numfullpathfail1);
2493 STATNODE(numfullpathfail2);
2494 STATNODE(numfullpathfail3);
2495 STATNODE(numfullpathfail4);
2496 STATNODE(numfullpathfound);
2497
2498 int
2499 cache_fullpath(struct proc *p, struct nchandle *nchp, char **retbuf, char **freebuf)
2500 {
2501         char *bp, *buf;
2502         int i, slash_prefixed;
2503         struct nchandle fd_nrdir;
2504         struct nchandle nch;
2505
2506         numfullpathcalls--;
2507
2508         *retbuf = NULL; 
2509         *freebuf = NULL;
2510
2511         buf = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
2512         bp = buf + MAXPATHLEN - 1;
2513         *bp = '\0';
2514         if (p != NULL)
2515                 fd_nrdir = p->p_fd->fd_nrdir;
2516         else
2517                 fd_nrdir = rootnch;
2518         slash_prefixed = 0;
2519         nch = *nchp;
2520
2521         while (nch.ncp && 
2522                (nch.ncp != fd_nrdir.ncp || nch.mount != fd_nrdir.mount)
2523         ) {
2524                 /*
2525                  * While traversing upwards if we encounter the root
2526                  * of the current mount we have to skip to the mount point.
2527                  */
2528                 if (nch.ncp == nch.mount->mnt_ncmountpt.ncp) {
2529                         nch = nch.mount->mnt_ncmounton;
2530                         continue;
2531                 }
2532
2533                 /*
2534                  * Prepend the path segment
2535                  */
2536                 for (i = nch.ncp->nc_nlen - 1; i >= 0; i--) {
2537                         if (bp == buf) {
2538                                 numfullpathfail4++;
2539                                 kfree(buf, M_TEMP);
2540                                 return(ENOMEM);
2541                         }
2542                         *--bp = nch.ncp->nc_name[i];
2543                 }
2544                 if (bp == buf) {
2545                         numfullpathfail4++;
2546                         kfree(buf, M_TEMP);
2547                         return(ENOMEM);
2548                 }
2549                 *--bp = '/';
2550                 slash_prefixed = 1;
2551
2552                 /*
2553                  * Go up a directory.  This isn't a mount point so we don't
2554                  * have to check again.
2555                  */
2556                 nch.ncp = nch.ncp->nc_parent;
2557         }
2558         if (nch.ncp == NULL) {
2559                 numfullpathfail2++;
2560                 kfree(buf, M_TEMP);
2561                 return(ENOENT);
2562         }
2563
2564         if (!slash_prefixed) {
2565                 if (bp == buf) {
2566                         numfullpathfail4++;
2567                         kfree(buf, M_TEMP);
2568                         return(ENOMEM);
2569                 }
2570                 *--bp = '/';
2571         }
2572         numfullpathfound++;
2573         *retbuf = bp; 
2574         *freebuf = buf;
2575
2576         return(0);
2577 }
2578
2579 int
2580 vn_fullpath(struct proc *p, struct vnode *vn, char **retbuf, char **freebuf) 
2581 {
2582         struct namecache *ncp;
2583         struct nchandle nch;
2584
2585         numfullpathcalls++;
2586         if (disablefullpath)
2587                 return (ENODEV);
2588
2589         if (p == NULL)
2590                 return (EINVAL);
2591
2592         /* vn is NULL, client wants us to use p->p_textvp */
2593         if (vn == NULL) {
2594                 if ((vn = p->p_textvp) == NULL)
2595                         return (EINVAL);
2596         }
2597         TAILQ_FOREACH(ncp, &vn->v_namecache, nc_vnode) {
2598                 if (ncp->nc_nlen)
2599                         break;
2600         }
2601         if (ncp == NULL)
2602                 return (EINVAL);
2603
2604         numfullpathcalls--;
2605         nch.ncp = ncp;;
2606         nch.mount = vn->v_mount;
2607         return(cache_fullpath(p, &nch, retbuf, freebuf));
2608 }