HAMMER 26/many: More NFS support work, rename fixes
[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.87 2008/02/06 00:27:27 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         return(_cache_get_nonblock(nch->ncp));
565 }
566
567 static __inline
568 void
569 _cache_put(struct namecache *ncp)
570 {
571         _cache_unlock(ncp);
572         _cache_drop(ncp);
573 }
574
575 void
576 cache_put(struct nchandle *nch)
577 {
578         --nch->mount->mnt_refs;
579         _cache_put(nch->ncp);
580         nch->ncp = NULL;
581         nch->mount = NULL;
582 }
583
584 /*
585  * Resolve an unresolved ncp by associating a vnode with it.  If the
586  * vnode is NULL, a negative cache entry is created.
587  *
588  * The ncp should be locked on entry and will remain locked on return.
589  */
590 static
591 void
592 _cache_setvp(struct namecache *ncp, struct vnode *vp)
593 {
594         KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
595         ncp->nc_vp = vp;
596         if (vp != NULL) {
597                 /*
598                  * Any vp associated with an ncp which has children must
599                  * be held.  Any vp associated with a locked ncp must be held.
600                  */
601                 if (!TAILQ_EMPTY(&ncp->nc_list))
602                         vhold(vp);
603                 TAILQ_INSERT_HEAD(&vp->v_namecache, ncp, nc_vnode);
604                 if (ncp->nc_exlocks)
605                         vhold(vp);
606
607                 /*
608                  * Set auxiliary flags
609                  */
610                 switch(vp->v_type) {
611                 case VDIR:
612                         ncp->nc_flag |= NCF_ISDIR;
613                         break;
614                 case VLNK:
615                         ncp->nc_flag |= NCF_ISSYMLINK;
616                         /* XXX cache the contents of the symlink */
617                         break;
618                 default:
619                         break;
620                 }
621                 ++numcache;
622                 ncp->nc_error = 0;
623         } else {
624                 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
625                 ++numneg;
626                 ncp->nc_error = ENOENT;
627         }
628         ncp->nc_flag &= ~NCF_UNRESOLVED;
629 }
630
631 void
632 cache_setvp(struct nchandle *nch, struct vnode *vp)
633 {
634         _cache_setvp(nch->ncp, vp);
635 }
636
637 void
638 cache_settimeout(struct nchandle *nch, int nticks)
639 {
640         struct namecache *ncp = nch->ncp;
641
642         if ((ncp->nc_timeout = ticks + nticks) == 0)
643                 ncp->nc_timeout = 1;
644 }
645
646 /*
647  * Disassociate the vnode or negative-cache association and mark a
648  * namecache entry as unresolved again.  Note that the ncp is still
649  * left in the hash table and still linked to its parent.
650  *
651  * The ncp should be locked and refd on entry and will remain locked and refd
652  * on return.
653  *
654  * This routine is normally never called on a directory containing children.
655  * However, NFS often does just that in its rename() code as a cop-out to
656  * avoid complex namespace operations.  This disconnects a directory vnode
657  * from its namecache and can cause the OLDAPI and NEWAPI to get out of
658  * sync.
659  *
660  * NOTE: NCF_FSMID must be cleared so a refurbishment of the ncp, such as
661  * in a create, properly propogates flag up the chain.
662  */
663 static
664 void
665 _cache_setunresolved(struct namecache *ncp)
666 {
667         struct vnode *vp;
668
669         if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
670                 ncp->nc_flag |= NCF_UNRESOLVED;
671                 ncp->nc_timeout = 0;
672                 ncp->nc_error = ENOTCONN;
673                 ++numunres;
674                 if ((vp = ncp->nc_vp) != NULL) {
675                         --numcache;
676                         ncp->nc_vp = NULL;
677                         TAILQ_REMOVE(&vp->v_namecache, ncp, nc_vnode);
678
679                         /*
680                          * Any vp associated with an ncp with children is
681                          * held by that ncp.  Any vp associated with a locked
682                          * ncp is held by that ncp.  These conditions must be
683                          * undone when the vp is cleared out from the ncp.
684                          */
685                         if (ncp->nc_flag & NCF_FSMID)
686                                 vupdatefsmid(vp);
687                         if (!TAILQ_EMPTY(&ncp->nc_list))
688                                 vdrop(vp);
689                         if (ncp->nc_exlocks)
690                                 vdrop(vp);
691                 } else {
692                         TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
693                         --numneg;
694                 }
695                 ncp->nc_flag &= ~(NCF_WHITEOUT|NCF_ISDIR|NCF_ISSYMLINK|
696                                   NCF_FSMID);
697         }
698 }
699
700 void
701 cache_setunresolved(struct nchandle *nch)
702 {
703         _cache_setunresolved(nch->ncp);
704 }
705
706 /*
707  * Determine if we can clear NCF_ISMOUNTPT by scanning the mountlist
708  * looking for matches.  This flag tells the lookup code when it must
709  * check for a mount linkage and also prevents the directories in question
710  * from being deleted or renamed.
711  */
712 static
713 int
714 cache_clrmountpt_callback(struct mount *mp, void *data)
715 {
716         struct nchandle *nch = data;
717
718         if (mp->mnt_ncmounton.ncp == nch->ncp)
719                 return(1);
720         if (mp->mnt_ncmountpt.ncp == nch->ncp)
721                 return(1);
722         return(0);
723 }
724
725 void
726 cache_clrmountpt(struct nchandle *nch)
727 {
728         int count;
729
730         count = mountlist_scan(cache_clrmountpt_callback, nch,
731                                MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
732         if (count == 0)
733                 nch->ncp->nc_flag &= ~NCF_ISMOUNTPT;
734 }
735
736 /*
737  * Invalidate portions of the namecache topology given a starting entry.
738  * The passed ncp is set to an unresolved state and:
739  *
740  * The passed ncp must be locked.
741  *
742  * CINV_DESTROY         - Set a flag in the passed ncp entry indicating
743  *                        that the physical underlying nodes have been 
744  *                        destroyed... as in deleted.  For example, when
745  *                        a directory is removed.  This will cause record
746  *                        lookups on the name to no longer be able to find
747  *                        the record and tells the resolver to return failure
748  *                        rather then trying to resolve through the parent.
749  *
750  *                        The topology itself, including ncp->nc_name,
751  *                        remains intact.
752  *
753  *                        This only applies to the passed ncp, if CINV_CHILDREN
754  *                        is specified the children are not flagged.
755  *
756  * CINV_CHILDREN        - Set all children (recursively) to an unresolved
757  *                        state as well.
758  *
759  *                        Note that this will also have the side effect of
760  *                        cleaning out any unreferenced nodes in the topology
761  *                        from the leaves up as the recursion backs out.
762  *
763  * Note that the topology for any referenced nodes remains intact.
764  *
765  * It is possible for cache_inval() to race a cache_resolve(), meaning that
766  * the namecache entry may not actually be invalidated on return if it was
767  * revalidated while recursing down into its children.  This code guarentees
768  * that the node(s) will go through an invalidation cycle, but does not 
769  * guarentee that they will remain in an invalidated state. 
770  *
771  * Returns non-zero if a revalidation was detected during the invalidation
772  * recursion, zero otherwise.  Note that since only the original ncp is
773  * locked the revalidation ultimately can only indicate that the original ncp
774  * *MIGHT* no have been reresolved.
775  *
776  * DEEP RECURSION HANDLING - If a recursive invalidation recurses deeply we
777  * have to avoid blowing out the kernel stack.  We do this by saving the
778  * deep namecache node and aborting the recursion, then re-recursing at that
779  * node using a depth-first algorithm in order to allow multiple deep
780  * recursions to chain through each other, then we restart the invalidation
781  * from scratch.
782  */
783
784 struct cinvtrack {
785         struct namecache *resume_ncp;
786         int depth;
787 };
788
789 static int _cache_inval_internal(struct namecache *, int, struct cinvtrack *);
790
791 static
792 int
793 _cache_inval(struct namecache *ncp, int flags)
794 {
795         struct cinvtrack track;
796         struct namecache *ncp2;
797         int r;
798
799         track.depth = 0;
800         track.resume_ncp = NULL;
801
802         for (;;) {
803                 r = _cache_inval_internal(ncp, flags, &track);
804                 if (track.resume_ncp == NULL)
805                         break;
806                 kprintf("Warning: deep namecache recursion at %s\n",
807                         ncp->nc_name);
808                 _cache_unlock(ncp);
809                 while ((ncp2 = track.resume_ncp) != NULL) {
810                         track.resume_ncp = NULL;
811                         _cache_lock(ncp2);
812                         _cache_inval_internal(ncp2, flags & ~CINV_DESTROY,
813                                              &track);
814                         _cache_put(ncp2);
815                 }
816                 _cache_lock(ncp);
817         }
818         return(r);
819 }
820
821 int
822 cache_inval(struct nchandle *nch, int flags)
823 {
824         return(_cache_inval(nch->ncp, flags));
825 }
826
827 static int
828 _cache_inval_internal(struct namecache *ncp, int flags, struct cinvtrack *track)
829 {
830         struct namecache *kid;
831         struct namecache *nextkid;
832         int rcnt = 0;
833
834         KKASSERT(ncp->nc_exlocks);
835
836         _cache_setunresolved(ncp);
837         if (flags & CINV_DESTROY)
838                 ncp->nc_flag |= NCF_DESTROYED;
839
840         if ((flags & CINV_CHILDREN) && 
841             (kid = TAILQ_FIRST(&ncp->nc_list)) != NULL
842         ) {
843                 if (++track->depth > MAX_RECURSION_DEPTH) {
844                         track->resume_ncp = ncp;
845                         _cache_hold(ncp);
846                         ++rcnt;
847                 }
848                 _cache_hold(kid);
849                 _cache_unlock(ncp);
850                 while (kid) {
851                         if (track->resume_ncp) {
852                                 _cache_drop(kid);
853                                 break;
854                         }
855                         if ((nextkid = TAILQ_NEXT(kid, nc_entry)) != NULL)
856                                 _cache_hold(nextkid);
857                         if ((kid->nc_flag & NCF_UNRESOLVED) == 0 ||
858                             TAILQ_FIRST(&kid->nc_list)
859                         ) {
860                                 _cache_lock(kid);
861                                 rcnt += _cache_inval_internal(kid, flags & ~CINV_DESTROY, track);
862                                 _cache_unlock(kid);
863                         }
864                         _cache_drop(kid);
865                         kid = nextkid;
866                 }
867                 --track->depth;
868                 _cache_lock(ncp);
869         }
870
871         /*
872          * Someone could have gotten in there while ncp was unlocked,
873          * retry if so.
874          */
875         if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
876                 ++rcnt;
877         return (rcnt);
878 }
879
880 /*
881  * Invalidate a vnode's namecache associations.  To avoid races against
882  * the resolver we do not invalidate a node which we previously invalidated
883  * but which was then re-resolved while we were in the invalidation loop.
884  *
885  * Returns non-zero if any namecache entries remain after the invalidation
886  * loop completed.
887  *
888  * NOTE: unlike the namecache topology which guarentees that ncp's will not
889  * be ripped out of the topology while held, the vnode's v_namecache list
890  * has no such restriction.  NCP's can be ripped out of the list at virtually
891  * any time if not locked, even if held.
892  */
893 int
894 cache_inval_vp(struct vnode *vp, int flags)
895 {
896         struct namecache *ncp;
897         struct namecache *next;
898
899 restart:
900         ncp = TAILQ_FIRST(&vp->v_namecache);
901         if (ncp)
902                 _cache_hold(ncp);
903         while (ncp) {
904                 /* loop entered with ncp held */
905                 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
906                         _cache_hold(next);
907                 _cache_lock(ncp);
908                 if (ncp->nc_vp != vp) {
909                         kprintf("Warning: cache_inval_vp: race-A detected on "
910                                 "%s\n", ncp->nc_name);
911                         _cache_put(ncp);
912                         if (next)
913                                 _cache_drop(next);
914                         goto restart;
915                 }
916                 _cache_inval(ncp, flags);
917                 _cache_put(ncp);                /* also releases reference */
918                 ncp = next;
919                 if (ncp && ncp->nc_vp != vp) {
920                         kprintf("Warning: cache_inval_vp: race-B detected on "
921                                 "%s\n", ncp->nc_name);
922                         _cache_drop(ncp);
923                         goto restart;
924                 }
925         }
926         return(TAILQ_FIRST(&vp->v_namecache) != NULL);
927 }
928
929 /*
930  * This routine is used instead of the normal cache_inval_vp() when we
931  * are trying to recycle otherwise good vnodes.
932  *
933  * Return 0 on success, non-zero if not all namecache records could be
934  * disassociated from the vnode (for various reasons).
935  */
936 int
937 cache_inval_vp_nonblock(struct vnode *vp)
938 {
939         struct namecache *ncp;
940         struct namecache *next;
941
942         ncp = TAILQ_FIRST(&vp->v_namecache);
943         if (ncp)
944                 _cache_hold(ncp);
945         while (ncp) {
946                 /* loop entered with ncp held */
947                 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
948                         _cache_hold(next);
949                 if (_cache_lock_nonblock(ncp)) {
950                         _cache_drop(ncp);
951                         if (next)
952                                 _cache_drop(next);
953                         break;
954                 }
955                 if (ncp->nc_vp != vp) {
956                         kprintf("Warning: cache_inval_vp: race-A detected on "
957                                 "%s\n", ncp->nc_name);
958                         _cache_put(ncp);
959                         if (next)
960                                 _cache_drop(next);
961                         break;
962                 }
963                 _cache_inval(ncp, 0);
964                 _cache_put(ncp);                /* also releases reference */
965                 ncp = next;
966                 if (ncp && ncp->nc_vp != vp) {
967                         kprintf("Warning: cache_inval_vp: race-B detected on "
968                                 "%s\n", ncp->nc_name);
969                         _cache_drop(ncp);
970                         break;
971                 }
972         }
973         return(TAILQ_FIRST(&vp->v_namecache) != NULL);
974 }
975
976 /*
977  * The source ncp has been renamed to the target ncp.  Both fncp and tncp
978  * must be locked.  The target ncp is destroyed (as a normal rename-over
979  * would destroy the target file or directory).
980  *
981  * Because there may be references to the source ncp we cannot copy its
982  * contents to the target.  Instead the source ncp is relinked as the target
983  * and the target ncp is removed from the namecache topology.
984  */
985 void
986 cache_rename(struct nchandle *fnch, struct nchandle *tnch)
987 {
988         struct namecache *fncp = fnch->ncp;
989         struct namecache *tncp = tnch->ncp;
990         char *oname;
991
992         _cache_setunresolved(tncp);
993         cache_unlink_parent(fncp);
994         cache_link_parent(fncp, tncp->nc_parent);
995         cache_unlink_parent(tncp);
996         oname = fncp->nc_name;
997         fncp->nc_name = tncp->nc_name;
998         fncp->nc_nlen = tncp->nc_nlen;
999         tncp->nc_name = NULL;
1000         tncp->nc_nlen = 0;
1001         if (fncp->nc_flag & NCF_HASHED)
1002                 _cache_rehash(fncp);
1003         if (tncp->nc_flag & NCF_HASHED)
1004                 _cache_rehash(tncp);
1005         if (oname)
1006                 kfree(oname, M_VFSCACHE);
1007 }
1008
1009 /*
1010  * vget the vnode associated with the namecache entry.  Resolve the namecache
1011  * entry if necessary and deal with namecache/vp races.  The passed ncp must
1012  * be referenced and may be locked.  The ncp's ref/locking state is not 
1013  * effected by this call.
1014  *
1015  * lk_type may be LK_SHARED, LK_EXCLUSIVE.  A ref'd, possibly locked
1016  * (depending on the passed lk_type) will be returned in *vpp with an error
1017  * of 0, or NULL will be returned in *vpp with a non-0 error code.  The
1018  * most typical error is ENOENT, meaning that the ncp represents a negative
1019  * cache hit and there is no vnode to retrieve, but other errors can occur
1020  * too.
1021  *
1022  * The main race we have to deal with are namecache zaps.  The ncp itself
1023  * will not disappear since it is referenced, and it turns out that the
1024  * validity of the vp pointer can be checked simply by rechecking the
1025  * contents of ncp->nc_vp.
1026  */
1027 int
1028 cache_vget(struct nchandle *nch, struct ucred *cred,
1029            int lk_type, struct vnode **vpp)
1030 {
1031         struct namecache *ncp;
1032         struct vnode *vp;
1033         int error;
1034
1035         ncp = nch->ncp;
1036 again:
1037         vp = NULL;
1038         if (ncp->nc_flag & NCF_UNRESOLVED) {
1039                 _cache_lock(ncp);
1040                 error = cache_resolve(nch, cred);
1041                 _cache_unlock(ncp);
1042         } else {
1043                 error = 0;
1044         }
1045         if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1046                 /*
1047                  * Accessing the vnode from the namecache is a bit 
1048                  * dangerous.  Because there are no refs on the vnode, it
1049                  * could be in the middle of a reclaim.
1050                  */
1051                 if (vp->v_flag & VRECLAIMED) {
1052                         kprintf("Warning: vnode reclaim race detected in cache_vget on %p (%s)\n", vp, ncp->nc_name);
1053                         _cache_lock(ncp);
1054                         _cache_setunresolved(ncp);
1055                         _cache_unlock(ncp);
1056                         goto again;
1057                 }
1058                 error = vget(vp, lk_type);
1059                 if (error) {
1060                         if (vp != ncp->nc_vp)
1061                                 goto again;
1062                         vp = NULL;
1063                 } else if (vp != ncp->nc_vp) {
1064                         vput(vp);
1065                         goto again;
1066                 } else if (vp->v_flag & VRECLAIMED) {
1067                         panic("vget succeeded on a VRECLAIMED node! vp %p", vp);
1068                 }
1069         }
1070         if (error == 0 && vp == NULL)
1071                 error = ENOENT;
1072         *vpp = vp;
1073         return(error);
1074 }
1075
1076 int
1077 cache_vref(struct nchandle *nch, struct ucred *cred, struct vnode **vpp)
1078 {
1079         struct namecache *ncp;
1080         struct vnode *vp;
1081         int error;
1082
1083         ncp = nch->ncp;
1084
1085 again:
1086         vp = NULL;
1087         if (ncp->nc_flag & NCF_UNRESOLVED) {
1088                 _cache_lock(ncp);
1089                 error = cache_resolve(nch, cred);
1090                 _cache_unlock(ncp);
1091         } else {
1092                 error = 0;
1093         }
1094         if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1095                 /*
1096                  * Since we did not obtain any locks, a cache zap 
1097                  * race can occur here if the vnode is in the middle
1098                  * of being reclaimed and has not yet been able to
1099                  * clean out its cache node.  If that case occurs,
1100                  * we must lock and unresolve the cache, then loop
1101                  * to retry.
1102                  */
1103                 if ((error = vget(vp, LK_SHARED)) != 0) {
1104                         if (error == ENOENT) {
1105                                 kprintf("Warning: vnode reclaim race detected on cache_vref %p (%s)\n", vp, ncp->nc_name);
1106                                 _cache_lock(ncp);
1107                                 _cache_setunresolved(ncp);
1108                                 _cache_unlock(ncp);
1109                                 goto again;
1110                         }
1111                         /* fatal error */
1112                 } else {
1113                         /* caller does not want a lock */
1114                         vn_unlock(vp);
1115                 }
1116         }
1117         if (error == 0 && vp == NULL)
1118                 error = ENOENT;
1119         *vpp = vp;
1120         return(error);
1121 }
1122
1123 /*
1124  * Recursively set the FSMID update flag for namecache nodes leading
1125  * to root.  This will cause the next getattr or reclaim to increment the
1126  * fsmid and mark the inode for lazy updating.
1127  *
1128  * Stop recursing when we hit a node whos NCF_FSMID flag is already set.
1129  * This makes FSMIDs work in an Einsteinian fashion - where the observation
1130  * effects the result.  In this case a program monitoring a higher level
1131  * node will have detected some prior change and started its scan (clearing
1132  * NCF_FSMID in higher level nodes), but since it has not yet observed the
1133  * node where we find NCF_FSMID still set, we can safely make the related
1134  * modification without interfering with the theorized program.
1135  *
1136  * This also means that FSMIDs cannot represent time-domain quantities
1137  * in a hierarchical sense.  But the main reason for doing it this way
1138  * is to reduce the amount of recursion that occurs in the critical path
1139  * when e.g. a program is writing to a file that sits deep in a directory
1140  * hierarchy.
1141  */
1142 void
1143 cache_update_fsmid(struct nchandle *nch)
1144 {
1145         struct namecache *ncp;
1146         struct namecache *scan;
1147         struct vnode *vp;
1148
1149         ncp = nch->ncp;
1150
1151         /*
1152          * Warning: even if we get a non-NULL vp it could still be in the
1153          * middle of a recyclement.  Don't do anything fancy, just set
1154          * NCF_FSMID.
1155          */
1156         if ((vp = ncp->nc_vp) != NULL) {
1157                 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1158                         for (scan = ncp; scan; scan = scan->nc_parent) {
1159                                 if (scan->nc_flag & NCF_FSMID)
1160                                         break;
1161                                 scan->nc_flag |= NCF_FSMID;
1162                         }
1163                 }
1164         } else {
1165                 while (ncp && (ncp->nc_flag & NCF_FSMID) == 0) {
1166                         ncp->nc_flag |= NCF_FSMID;
1167                         ncp = ncp->nc_parent;
1168                 }
1169         }
1170 }
1171
1172 void
1173 cache_update_fsmid_vp(struct vnode *vp)
1174 {
1175         struct namecache *ncp;
1176         struct namecache *scan;
1177
1178         TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1179                 for (scan = ncp; scan; scan = scan->nc_parent) {
1180                         if (scan->nc_flag & NCF_FSMID)
1181                                 break;
1182                         scan->nc_flag |= NCF_FSMID;
1183                 }
1184         }
1185 }
1186
1187 /*
1188  * If getattr is called on a vnode (e.g. a stat call), the filesystem
1189  * may call this routine to determine if the namecache has the hierarchical
1190  * change flag set, requiring the fsmid to be updated.
1191  *
1192  * Since 0 indicates no support, make sure the filesystem fsmid is at least
1193  * 1.
1194  */
1195 int
1196 cache_check_fsmid_vp(struct vnode *vp, int64_t *fsmid)
1197 {
1198         struct namecache *ncp;
1199         int changed = 0;
1200
1201         TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1202                 if (ncp->nc_flag & NCF_FSMID) {
1203                         ncp->nc_flag &= ~NCF_FSMID;
1204                         changed = 1;
1205                 }
1206         }
1207         if (*fsmid == 0)
1208                 ++*fsmid;
1209         if (changed)
1210                 ++*fsmid;
1211         return(changed);
1212 }
1213
1214 /*
1215  * Obtain the FSMID for a vnode for filesystems which do not support
1216  * a built-in FSMID.
1217  */
1218 int64_t
1219 cache_sync_fsmid_vp(struct vnode *vp)
1220 {
1221         struct namecache *ncp;
1222
1223         if ((ncp = TAILQ_FIRST(&vp->v_namecache)) != NULL) {
1224                 if (ncp->nc_flag & NCF_FSMID) {
1225                         ncp->nc_flag &= ~NCF_FSMID;
1226                         ++ncp->nc_fsmid;
1227                 }
1228                 return(ncp->nc_fsmid);
1229         }
1230         return(VNOVAL);
1231 }
1232
1233 /*
1234  * Convert a directory vnode to a namecache record without any other 
1235  * knowledge of the topology.  This ONLY works with directory vnodes and
1236  * is ONLY used by the NFS server.  dvp must be refd but unlocked, and the
1237  * returned ncp (if not NULL) will be held and unlocked.
1238  *
1239  * If 'makeit' is 0 and dvp has no existing namecache record, NULL is returned.
1240  * If 'makeit' is 1 we attempt to track-down and create the namecache topology
1241  * for dvp.  This will fail only if the directory has been deleted out from
1242  * under the caller.  
1243  *
1244  * Callers must always check for a NULL return no matter the value of 'makeit'.
1245  *
1246  * To avoid underflowing the kernel stack each recursive call increments
1247  * the makeit variable.
1248  */
1249
1250 static int cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1251                                   struct vnode *dvp, char *fakename);
1252 static int cache_fromdvp_try(struct vnode *dvp, struct ucred *cred, 
1253                                   struct vnode **saved_dvp);
1254
1255 int
1256 cache_fromdvp(struct vnode *dvp, struct ucred *cred, int makeit,
1257               struct nchandle *nch)
1258 {
1259         struct vnode *saved_dvp;
1260         struct vnode *pvp;
1261         char *fakename;
1262         int error;
1263
1264         nch->ncp = NULL;
1265         nch->mount = dvp->v_mount;
1266         saved_dvp = NULL;
1267         fakename = NULL;
1268
1269         /*
1270          * Temporary debugging code to force the directory scanning code
1271          * to be exercised.
1272          */
1273         if (ncvp_debug >= 3 && makeit && TAILQ_FIRST(&dvp->v_namecache)) {
1274                 nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
1275                 kprintf("cache_fromdvp: forcing %s\n", nch->ncp->nc_name);
1276                 goto force;
1277         }
1278
1279         /*
1280          * Loop until resolution, inside code will break out on error.
1281          */
1282         while ((nch->ncp = TAILQ_FIRST(&dvp->v_namecache)) == NULL && makeit) {
1283 force:
1284                 /*
1285                  * If dvp is the root of its filesystem it should already
1286                  * have a namecache pointer associated with it as a side 
1287                  * effect of the mount, but it may have been disassociated.
1288                  */
1289                 if (dvp->v_flag & VROOT) {
1290                         nch->ncp = _cache_get(nch->mount->mnt_ncmountpt.ncp);
1291                         error = cache_resolve_mp(nch->mount);
1292                         _cache_put(nch->ncp);
1293                         if (ncvp_debug) {
1294                                 kprintf("cache_fromdvp: resolve root of mount %p error %d", 
1295                                         dvp->v_mount, error);
1296                         }
1297                         if (error) {
1298                                 if (ncvp_debug)
1299                                         kprintf(" failed\n");
1300                                 nch->ncp = NULL;
1301                                 break;
1302                         }
1303                         if (ncvp_debug)
1304                                 kprintf(" succeeded\n");
1305                         continue;
1306                 }
1307
1308                 /*
1309                  * If we are recursed too deeply resort to an O(n^2)
1310                  * algorithm to resolve the namecache topology.  The
1311                  * resolved pvp is left referenced in saved_dvp to
1312                  * prevent the tree from being destroyed while we loop.
1313                  */
1314                 if (makeit > 20) {
1315                         error = cache_fromdvp_try(dvp, cred, &saved_dvp);
1316                         if (error) {
1317                                 kprintf("lookupdotdot(longpath) failed %d "
1318                                        "dvp %p\n", error, dvp);
1319                                 break;
1320                         }
1321                         continue;
1322                 }
1323
1324                 /*
1325                  * Get the parent directory and resolve its ncp.
1326                  */
1327                 if (fakename) {
1328                         kfree(fakename, M_TEMP);
1329                         fakename = NULL;
1330                 }
1331                 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
1332                                           &fakename);
1333                 if (error) {
1334                         kprintf("lookupdotdot failed %d dvp %p\n", error, dvp);
1335                         break;
1336                 }
1337                 vn_unlock(pvp);
1338
1339                 /*
1340                  * Reuse makeit as a recursion depth counter.
1341                  */
1342                 cache_fromdvp(pvp, cred, makeit + 1, nch);
1343                 vrele(pvp);
1344                 if (nch->ncp == NULL)
1345                         break;
1346
1347                 /*
1348                  * Do an inefficient scan of pvp (embodied by ncp) to look
1349                  * for dvp.  This will create a namecache record for dvp on
1350                  * success.  We loop up to recheck on success.
1351                  *
1352                  * ncp and dvp are both held but not locked.
1353                  */
1354                 error = cache_inefficient_scan(nch, cred, dvp, fakename);
1355                 _cache_drop(nch->ncp);
1356                 if (error) {
1357                         kprintf("cache_fromdvp: scan %p (%s) failed on dvp=%p\n",
1358                                 pvp, nch->ncp->nc_name, dvp);
1359                         nch->ncp = NULL;
1360                         break;
1361                 }
1362                 if (ncvp_debug) {
1363                         kprintf("cache_fromdvp: scan %p (%s) succeeded\n",
1364                                 pvp, nch->ncp->nc_name);
1365                 }
1366         }
1367
1368         if (fakename)
1369                 kfree(fakename, M_TEMP);
1370
1371         /*
1372          * hold it for real so the mount gets a ref
1373          */
1374         if (nch->ncp)
1375                 cache_hold(nch);
1376         if (saved_dvp)
1377                 vrele(saved_dvp);
1378         if (nch->ncp)
1379                 return (0);
1380         return (EINVAL);
1381 }
1382
1383 /*
1384  * Go up the chain of parent directories until we find something
1385  * we can resolve into the namecache.  This is very inefficient.
1386  */
1387 static
1388 int
1389 cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1390                   struct vnode **saved_dvp)
1391 {
1392         struct nchandle nch;
1393         struct vnode *pvp;
1394         int error;
1395         static time_t last_fromdvp_report;
1396         char *fakename;
1397
1398         /*
1399          * Loop getting the parent directory vnode until we get something we
1400          * can resolve in the namecache.
1401          */
1402         vref(dvp);
1403         nch.mount = dvp->v_mount;
1404         fakename = NULL;
1405
1406         for (;;) {
1407                 if (fakename) {
1408                         kfree(fakename, M_TEMP);
1409                         fakename = NULL;
1410                 }
1411                 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
1412                                           &fakename);
1413                 if (error) {
1414                         vrele(dvp);
1415                         break;
1416                 }
1417                 vn_unlock(pvp);
1418                 if ((nch.ncp = TAILQ_FIRST(&pvp->v_namecache)) != NULL) {
1419                         _cache_hold(nch.ncp);
1420                         vrele(pvp);
1421                         break;
1422                 }
1423                 if (pvp->v_flag & VROOT) {
1424                         nch.ncp = _cache_get(pvp->v_mount->mnt_ncmountpt.ncp);
1425                         error = cache_resolve_mp(nch.mount);
1426                         _cache_unlock(nch.ncp);
1427                         vrele(pvp);
1428                         if (error) {
1429                                 _cache_drop(nch.ncp);
1430                                 vrele(dvp);
1431                         }
1432                         break;
1433                 }
1434                 vrele(dvp);
1435                 dvp = pvp;
1436         }
1437         if (error == 0) {
1438                 if (last_fromdvp_report != time_second) {
1439                         last_fromdvp_report = time_second;
1440                         kprintf("Warning: extremely inefficient path "
1441                                 "resolution on %s\n",
1442                                 nch.ncp->nc_name);
1443                 }
1444                 error = cache_inefficient_scan(&nch, cred, dvp, fakename);
1445
1446                 /*
1447                  * Hopefully dvp now has a namecache record associated with
1448                  * it.  Leave it referenced to prevent the kernel from
1449                  * recycling the vnode.  Otherwise extremely long directory
1450                  * paths could result in endless recycling.
1451                  */
1452                 if (*saved_dvp)
1453                     vrele(*saved_dvp);
1454                 *saved_dvp = dvp;
1455         }
1456         if (fakename)
1457                 kfree(fakename, M_TEMP);
1458         return (error);
1459 }
1460
1461
1462 /*
1463  * Do an inefficient scan of the directory represented by ncp looking for
1464  * the directory vnode dvp.  ncp must be held but not locked on entry and
1465  * will be held on return.  dvp must be refd but not locked on entry and
1466  * will remain refd on return.
1467  *
1468  * Why do this at all?  Well, due to its stateless nature the NFS server
1469  * converts file handles directly to vnodes without necessarily going through
1470  * the namecache ops that would otherwise create the namecache topology
1471  * leading to the vnode.  We could either (1) Change the namecache algorithms
1472  * to allow disconnect namecache records that are re-merged opportunistically,
1473  * or (2) Make the NFS server backtrack and scan to recover a connected
1474  * namecache topology in order to then be able to issue new API lookups.
1475  *
1476  * It turns out that (1) is a huge mess.  It takes a nice clean set of 
1477  * namecache algorithms and introduces a lot of complication in every subsystem
1478  * that calls into the namecache to deal with the re-merge case, especially
1479  * since we are using the namecache to placehold negative lookups and the
1480  * vnode might not be immediately assigned. (2) is certainly far less
1481  * efficient then (1), but since we are only talking about directories here
1482  * (which are likely to remain cached), the case does not actually run all
1483  * that often and has the supreme advantage of not polluting the namecache
1484  * algorithms.
1485  *
1486  * If a fakename is supplied just construct a namecache entry using the
1487  * fake name.
1488  */
1489 static int
1490 cache_inefficient_scan(struct nchandle *nch, struct ucred *cred, 
1491                        struct vnode *dvp, char *fakename)
1492 {
1493         struct nlcomponent nlc;
1494         struct nchandle rncp;
1495         struct dirent *den;
1496         struct vnode *pvp;
1497         struct vattr vat;
1498         struct iovec iov;
1499         struct uio uio;
1500         int blksize;
1501         int eofflag;
1502         int bytes;
1503         char *rbuf;
1504         int error;
1505
1506         vat.va_blocksize = 0;
1507         if ((error = VOP_GETATTR(dvp, &vat)) != 0)
1508                 return (error);
1509         if ((error = cache_vref(nch, cred, &pvp)) != 0)
1510                 return (error);
1511         if (ncvp_debug)
1512                 kprintf("inefficient_scan: directory iosize %ld vattr fileid = %lld\n", vat.va_blocksize, vat.va_fileid);
1513
1514         /*
1515          * Use the supplied fakename if not NULL.  Fake names are typically
1516          * not in the actual filesystem hierarchy.  This is used by HAMMER
1517          * to glue @@timestamp recursions together.
1518          */
1519         if (fakename) {
1520                 nlc.nlc_nameptr = fakename;
1521                 nlc.nlc_namelen = strlen(fakename);
1522                 rncp = cache_nlookup(nch, &nlc);
1523                 goto done;
1524         }
1525
1526         if ((blksize = vat.va_blocksize) == 0)
1527                 blksize = DEV_BSIZE;
1528         rbuf = kmalloc(blksize, M_TEMP, M_WAITOK);
1529         rncp.ncp = NULL;
1530
1531         eofflag = 0;
1532         uio.uio_offset = 0;
1533 again:
1534         iov.iov_base = rbuf;
1535         iov.iov_len = blksize;
1536         uio.uio_iov = &iov;
1537         uio.uio_iovcnt = 1;
1538         uio.uio_resid = blksize;
1539         uio.uio_segflg = UIO_SYSSPACE;
1540         uio.uio_rw = UIO_READ;
1541         uio.uio_td = curthread;
1542
1543         if (ncvp_debug >= 2)
1544                 kprintf("cache_inefficient_scan: readdir @ %08x\n", (int)uio.uio_offset);
1545         error = VOP_READDIR(pvp, &uio, cred, &eofflag, NULL, NULL);
1546         if (error == 0) {
1547                 den = (struct dirent *)rbuf;
1548                 bytes = blksize - uio.uio_resid;
1549
1550                 while (bytes > 0) {
1551                         if (ncvp_debug >= 2) {
1552                                 kprintf("cache_inefficient_scan: %*.*s\n",
1553                                         den->d_namlen, den->d_namlen, 
1554                                         den->d_name);
1555                         }
1556                         if (den->d_type != DT_WHT &&
1557                             den->d_ino == vat.va_fileid) {
1558                                 if (ncvp_debug) {
1559                                         kprintf("cache_inefficient_scan: "
1560                                                "MATCHED inode %lld path %s/%*.*s\n",
1561                                                vat.va_fileid, nch->ncp->nc_name,
1562                                                den->d_namlen, den->d_namlen,
1563                                                den->d_name);
1564                                 }
1565                                 nlc.nlc_nameptr = den->d_name;
1566                                 nlc.nlc_namelen = den->d_namlen;
1567                                 rncp = cache_nlookup(nch, &nlc);
1568                                 KKASSERT(rncp.ncp != NULL);
1569                                 break;
1570                         }
1571                         bytes -= _DIRENT_DIRSIZ(den);
1572                         den = _DIRENT_NEXT(den);
1573                 }
1574                 if (rncp.ncp == NULL && eofflag == 0 && uio.uio_resid != blksize)
1575                         goto again;
1576         }
1577         kfree(rbuf, M_TEMP);
1578 done:
1579         vrele(pvp);
1580         if (rncp.ncp) {
1581                 if (rncp.ncp->nc_flag & NCF_UNRESOLVED) {
1582                         _cache_setvp(rncp.ncp, dvp);
1583                         if (ncvp_debug >= 2) {
1584                                 kprintf("cache_inefficient_scan: setvp %s/%s = %p\n",
1585                                         nch->ncp->nc_name, rncp.ncp->nc_name, dvp);
1586                         }
1587                 } else {
1588                         if (ncvp_debug >= 2) {
1589                                 kprintf("cache_inefficient_scan: setvp %s/%s already set %p/%p\n", 
1590                                         nch->ncp->nc_name, rncp.ncp->nc_name, dvp,
1591                                         rncp.ncp->nc_vp);
1592                         }
1593                 }
1594                 if (rncp.ncp->nc_vp == NULL)
1595                         error = rncp.ncp->nc_error;
1596                 _cache_put(rncp.ncp);
1597         } else {
1598                 kprintf("cache_inefficient_scan: dvp %p NOT FOUND in %s\n",
1599                         dvp, nch->ncp->nc_name);
1600                 error = ENOENT;
1601         }
1602         return (error);
1603 }
1604
1605 /*
1606  * Zap a namecache entry.  The ncp is unconditionally set to an unresolved
1607  * state, which disassociates it from its vnode or ncneglist.
1608  *
1609  * Then, if there are no additional references to the ncp and no children,
1610  * the ncp is removed from the topology and destroyed.  This function will
1611  * also run through the nc_parent chain and destroy parent ncps if possible.
1612  * As a side benefit, it turns out the only conditions that allow running
1613  * up the chain are also the conditions to ensure no deadlock will occur.
1614  *
1615  * References and/or children may exist if the ncp is in the middle of the
1616  * topology, preventing the ncp from being destroyed.
1617  *
1618  * This function must be called with the ncp held and locked and will unlock
1619  * and drop it during zapping.
1620  */
1621 static void
1622 cache_zap(struct namecache *ncp)
1623 {
1624         struct namecache *par;
1625
1626         /*
1627          * Disassociate the vnode or negative cache ref and set NCF_UNRESOLVED.
1628          */
1629         _cache_setunresolved(ncp);
1630
1631         /*
1632          * Try to scrap the entry and possibly tail-recurse on its parent.
1633          * We only scrap unref'd (other then our ref) unresolved entries,
1634          * we do not scrap 'live' entries.
1635          */
1636         while (ncp->nc_flag & NCF_UNRESOLVED) {
1637                 /*
1638                  * Someone other then us has a ref, stop.
1639                  */
1640                 if (ncp->nc_refs > 1)
1641                         goto done;
1642
1643                 /*
1644                  * We have children, stop.
1645                  */
1646                 if (!TAILQ_EMPTY(&ncp->nc_list))
1647                         goto done;
1648
1649                 /*
1650                  * Remove ncp from the topology: hash table and parent linkage.
1651                  */
1652                 if (ncp->nc_flag & NCF_HASHED) {
1653                         ncp->nc_flag &= ~NCF_HASHED;
1654                         LIST_REMOVE(ncp, nc_hash);
1655                 }
1656                 if ((par = ncp->nc_parent) != NULL) {
1657                         par = _cache_hold(par);
1658                         TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
1659                         ncp->nc_parent = NULL;
1660                         if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
1661                                 vdrop(par->nc_vp);
1662                 }
1663
1664                 /*
1665                  * ncp should not have picked up any refs.  Physically
1666                  * destroy the ncp.
1667                  */
1668                 KKASSERT(ncp->nc_refs == 1);
1669                 --numunres;
1670                 /* _cache_unlock(ncp) not required */
1671                 ncp->nc_refs = -1;      /* safety */
1672                 if (ncp->nc_name)
1673                         kfree(ncp->nc_name, M_VFSCACHE);
1674                 kfree(ncp, M_VFSCACHE);
1675
1676                 /*
1677                  * Loop on the parent (it may be NULL).  Only bother looping
1678                  * if the parent has a single ref (ours), which also means
1679                  * we can lock it trivially.
1680                  */
1681                 ncp = par;
1682                 if (ncp == NULL)
1683                         return;
1684                 if (ncp->nc_refs != 1) {
1685                         _cache_drop(ncp);
1686                         return;
1687                 }
1688                 KKASSERT(par->nc_exlocks == 0);
1689                 _cache_lock(ncp);
1690         }
1691 done:
1692         _cache_unlock(ncp);
1693         atomic_subtract_int(&ncp->nc_refs, 1);
1694 }
1695
1696 static enum { CHI_LOW, CHI_HIGH } cache_hysteresis_state = CHI_LOW;
1697
1698 static __inline
1699 void
1700 cache_hysteresis(void)
1701 {
1702         /*
1703          * Don't cache too many negative hits.  We use hysteresis to reduce
1704          * the impact on the critical path.
1705          */
1706         switch(cache_hysteresis_state) {
1707         case CHI_LOW:
1708                 if (numneg > MINNEG && numneg * ncnegfactor > numcache) {
1709                         cache_cleanneg(10);
1710                         cache_hysteresis_state = CHI_HIGH;
1711                 }
1712                 break;
1713         case CHI_HIGH:
1714                 if (numneg > MINNEG * 9 / 10 && 
1715                     numneg * ncnegfactor * 9 / 10 > numcache
1716                 ) {
1717                         cache_cleanneg(10);
1718                 } else {
1719                         cache_hysteresis_state = CHI_LOW;
1720                 }
1721                 break;
1722         }
1723 }
1724
1725 /*
1726  * NEW NAMECACHE LOOKUP API
1727  *
1728  * Lookup an entry in the cache.  A locked, referenced, non-NULL 
1729  * entry is *always* returned, even if the supplied component is illegal.
1730  * The resulting namecache entry should be returned to the system with
1731  * cache_put() or _cache_unlock() + cache_drop().
1732  *
1733  * namecache locks are recursive but care must be taken to avoid lock order
1734  * reversals.
1735  *
1736  * Nobody else will be able to manipulate the associated namespace (e.g.
1737  * create, delete, rename, rename-target) until the caller unlocks the
1738  * entry.
1739  *
1740  * The returned entry will be in one of three states:  positive hit (non-null
1741  * vnode), negative hit (null vnode), or unresolved (NCF_UNRESOLVED is set).
1742  * Unresolved entries must be resolved through the filesystem to associate the
1743  * vnode and/or determine whether a positive or negative hit has occured.
1744  *
1745  * It is not necessary to lock a directory in order to lock namespace under
1746  * that directory.  In fact, it is explicitly not allowed to do that.  A
1747  * directory is typically only locked when being created, renamed, or
1748  * destroyed.
1749  *
1750  * The directory (par) may be unresolved, in which case any returned child
1751  * will likely also be marked unresolved.  Likely but not guarenteed.  Since
1752  * the filesystem lookup requires a resolved directory vnode the caller is
1753  * responsible for resolving the namecache chain top-down.  This API 
1754  * specifically allows whole chains to be created in an unresolved state.
1755  */
1756 struct nchandle
1757 cache_nlookup(struct nchandle *par_nch, struct nlcomponent *nlc)
1758 {
1759         struct nchandle nch;
1760         struct namecache *ncp;
1761         struct namecache *new_ncp;
1762         struct nchashhead *nchpp;
1763         u_int32_t hash;
1764         globaldata_t gd;
1765
1766         numcalls++;
1767         gd = mycpu;
1768
1769         /*
1770          * Try to locate an existing entry
1771          */
1772         hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
1773         hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
1774         new_ncp = NULL;
1775 restart:
1776         LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1777                 numchecks++;
1778
1779                 /*
1780                  * Try to zap entries that have timed out.  We have
1781                  * to be careful here because locked leafs may depend
1782                  * on the vnode remaining intact in a parent, so only
1783                  * do this under very specific conditions.
1784                  */
1785                 if (ncp->nc_timeout && 
1786                     (int)(ncp->nc_timeout - ticks) < 0 &&
1787                     (ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
1788                     ncp->nc_exlocks == 0 &&
1789                     TAILQ_EMPTY(&ncp->nc_list)
1790                 ) {
1791                         cache_zap(_cache_get(ncp));
1792                         goto restart;
1793                 }
1794
1795                 /*
1796                  * Break out if we find a matching entry.  Note that
1797                  * UNRESOLVED entries may match, but DESTROYED entries
1798                  * do not.
1799                  */
1800                 if (ncp->nc_parent == par_nch->ncp &&
1801                     ncp->nc_nlen == nlc->nlc_namelen &&
1802                     bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
1803                     (ncp->nc_flag & NCF_DESTROYED) == 0
1804                 ) {
1805                         if (_cache_get_nonblock(ncp) == 0) {
1806                                 if (new_ncp)
1807                                         _cache_free(new_ncp);
1808                                 goto found;
1809                         }
1810                         _cache_get(ncp);
1811                         _cache_put(ncp);
1812                         goto restart;
1813                 }
1814         }
1815
1816         /*
1817          * We failed to locate an entry, create a new entry and add it to
1818          * the cache.  We have to relookup after possibly blocking in
1819          * malloc.
1820          */
1821         if (new_ncp == NULL) {
1822                 new_ncp = cache_alloc(nlc->nlc_namelen);
1823                 goto restart;
1824         }
1825
1826         ncp = new_ncp;
1827
1828         /*
1829          * Initialize as a new UNRESOLVED entry, lock (non-blocking),
1830          * and link to the parent.  The mount point is usually inherited
1831          * from the parent unless this is a special case such as a mount
1832          * point where nlc_namelen is 0.   If nlc_namelen is 0 nc_name will
1833          * be NULL.
1834          */
1835         if (nlc->nlc_namelen) {
1836                 bcopy(nlc->nlc_nameptr, ncp->nc_name, nlc->nlc_namelen);
1837                 ncp->nc_name[nlc->nlc_namelen] = 0;
1838         }
1839         nchpp = NCHHASH(hash);
1840         LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
1841         ncp->nc_flag |= NCF_HASHED;
1842         cache_link_parent(ncp, par_nch->ncp);
1843 found:
1844         /*
1845          * stats and namecache size management
1846          */
1847         if (ncp->nc_flag & NCF_UNRESOLVED)
1848                 ++gd->gd_nchstats->ncs_miss;
1849         else if (ncp->nc_vp)
1850                 ++gd->gd_nchstats->ncs_goodhits;
1851         else
1852                 ++gd->gd_nchstats->ncs_neghits;
1853         cache_hysteresis();
1854         nch.mount = par_nch->mount;
1855         nch.ncp = ncp;
1856         ++nch.mount->mnt_refs;
1857         return(nch);
1858 }
1859
1860 /*
1861  * The namecache entry is marked as being used as a mount point. 
1862  * Locate the mount if it is visible to the caller.
1863  */
1864 struct findmount_info {
1865         struct mount *result;
1866         struct mount *nch_mount;
1867         struct namecache *nch_ncp;
1868 };
1869
1870 static
1871 int
1872 cache_findmount_callback(struct mount *mp, void *data)
1873 {
1874         struct findmount_info *info = data;
1875
1876         /*
1877          * Check the mount's mounted-on point against the passed nch.
1878          */
1879         if (mp->mnt_ncmounton.mount == info->nch_mount &&
1880             mp->mnt_ncmounton.ncp == info->nch_ncp
1881         ) {
1882             info->result = mp;
1883             return(-1);
1884         }
1885         return(0);
1886 }
1887
1888 struct mount *
1889 cache_findmount(struct nchandle *nch)
1890 {
1891         struct findmount_info info;
1892
1893         info.result = NULL;
1894         info.nch_mount = nch->mount;
1895         info.nch_ncp = nch->ncp;
1896         mountlist_scan(cache_findmount_callback, &info,
1897                                MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1898         return(info.result);
1899 }
1900
1901 /*
1902  * Resolve an unresolved namecache entry, generally by looking it up.
1903  * The passed ncp must be locked and refd. 
1904  *
1905  * Theoretically since a vnode cannot be recycled while held, and since
1906  * the nc_parent chain holds its vnode as long as children exist, the
1907  * direct parent of the cache entry we are trying to resolve should
1908  * have a valid vnode.  If not then generate an error that we can 
1909  * determine is related to a resolver bug.
1910  *
1911  * However, if a vnode was in the middle of a recyclement when the NCP
1912  * got locked, ncp->nc_vp might point to a vnode that is about to become
1913  * invalid.  cache_resolve() handles this case by unresolving the entry
1914  * and then re-resolving it.
1915  *
1916  * Note that successful resolution does not necessarily return an error
1917  * code of 0.  If the ncp resolves to a negative cache hit then ENOENT
1918  * will be returned.
1919  */
1920 int
1921 cache_resolve(struct nchandle *nch, struct ucred *cred)
1922 {
1923         struct namecache *par;
1924         struct namecache *ncp;
1925         struct nchandle nctmp;
1926         struct mount *mp;
1927         struct vnode *dvp;
1928         int error;
1929
1930         ncp = nch->ncp;
1931         mp = nch->mount;
1932 restart:
1933         /*
1934          * If the ncp is already resolved we have nothing to do.  However,
1935          * we do want to guarentee that a usable vnode is returned when
1936          * a vnode is present, so make sure it hasn't been reclaimed.
1937          */
1938         if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
1939                 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
1940                         _cache_setunresolved(ncp);
1941                 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
1942                         return (ncp->nc_error);
1943         }
1944
1945         /*
1946          * Mount points need special handling because the parent does not
1947          * belong to the same filesystem as the ncp.
1948          */
1949         if (ncp == mp->mnt_ncmountpt.ncp)
1950                 return (cache_resolve_mp(mp));
1951
1952         /*
1953          * We expect an unbroken chain of ncps to at least the mount point,
1954          * and even all the way to root (but this code doesn't have to go
1955          * past the mount point).
1956          */
1957         if (ncp->nc_parent == NULL) {
1958                 kprintf("EXDEV case 1 %p %*.*s\n", ncp,
1959                         ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
1960                 ncp->nc_error = EXDEV;
1961                 return(ncp->nc_error);
1962         }
1963
1964         /*
1965          * The vp's of the parent directories in the chain are held via vhold()
1966          * due to the existance of the child, and should not disappear. 
1967          * However, there are cases where they can disappear:
1968          *
1969          *      - due to filesystem I/O errors.
1970          *      - due to NFS being stupid about tracking the namespace and
1971          *        destroys the namespace for entire directories quite often.
1972          *      - due to forced unmounts.
1973          *      - due to an rmdir (parent will be marked DESTROYED)
1974          *
1975          * When this occurs we have to track the chain backwards and resolve
1976          * it, looping until the resolver catches up to the current node.  We
1977          * could recurse here but we might run ourselves out of kernel stack
1978          * so we do it in a more painful manner.  This situation really should
1979          * not occur all that often, or if it does not have to go back too
1980          * many nodes to resolve the ncp.
1981          */
1982         while (ncp->nc_parent->nc_vp == NULL) {
1983                 /*
1984                  * This case can occur if a process is CD'd into a
1985                  * directory which is then rmdir'd.  If the parent is marked
1986                  * destroyed there is no point trying to resolve it.
1987                  */
1988                 if (ncp->nc_parent->nc_flag & NCF_DESTROYED)
1989                         return(ENOENT);
1990
1991                 par = ncp->nc_parent;
1992                 while (par->nc_parent && par->nc_parent->nc_vp == NULL)
1993                         par = par->nc_parent;
1994                 if (par->nc_parent == NULL) {
1995                         kprintf("EXDEV case 2 %*.*s\n",
1996                                 par->nc_nlen, par->nc_nlen, par->nc_name);
1997                         return (EXDEV);
1998                 }
1999                 kprintf("[diagnostic] cache_resolve: had to recurse on %*.*s\n",
2000                         par->nc_nlen, par->nc_nlen, par->nc_name);
2001                 /*
2002                  * The parent is not set in stone, ref and lock it to prevent
2003                  * it from disappearing.  Also note that due to renames it
2004                  * is possible for our ncp to move and for par to no longer
2005                  * be one of its parents.  We resolve it anyway, the loop 
2006                  * will handle any moves.
2007                  */
2008                 _cache_get(par);
2009                 if (par == nch->mount->mnt_ncmountpt.ncp) {
2010                         cache_resolve_mp(nch->mount);
2011                 } else if ((dvp = par->nc_parent->nc_vp) == NULL) {
2012                         kprintf("[diagnostic] cache_resolve: raced on %*.*s\n", par->nc_nlen, par->nc_nlen, par->nc_name);
2013                         _cache_put(par);
2014                         continue;
2015                 } else if (par->nc_flag & NCF_UNRESOLVED) {
2016                         /* vhold(dvp); - DVP can't go away */
2017                         nctmp.mount = mp;
2018                         nctmp.ncp = par;
2019                         par->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
2020                         /* vdrop(dvp); */
2021                 }
2022                 if ((error = par->nc_error) != 0) {
2023                         if (par->nc_error != EAGAIN) {
2024                                 kprintf("EXDEV case 3 %*.*s error %d\n",
2025                                     par->nc_nlen, par->nc_nlen, par->nc_name,
2026                                     par->nc_error);
2027                                 _cache_put(par);
2028                                 return(error);
2029                         }
2030                         kprintf("[diagnostic] cache_resolve: EAGAIN par %p %*.*s\n",
2031                                 par, par->nc_nlen, par->nc_nlen, par->nc_name);
2032                 }
2033                 _cache_put(par);
2034                 /* loop */
2035         }
2036
2037         /*
2038          * Call VOP_NRESOLVE() to get the vp, then scan for any disconnected
2039          * ncp's and reattach them.  If this occurs the original ncp is marked
2040          * EAGAIN to force a relookup.
2041          *
2042          * NOTE: in order to call VOP_NRESOLVE(), the parent of the passed
2043          * ncp must already be resolved.
2044          */
2045         dvp = ncp->nc_parent->nc_vp;
2046         /* vhold(dvp); - dvp can't go away */
2047         nctmp.mount = mp;
2048         nctmp.ncp = ncp;
2049         ncp->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
2050         /* vdrop(dvp); */
2051         if (ncp->nc_error == EAGAIN) {
2052                 kprintf("[diagnostic] cache_resolve: EAGAIN ncp %p %*.*s\n",
2053                         ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
2054                 goto restart;
2055         }
2056         return(ncp->nc_error);
2057 }
2058
2059 /*
2060  * Resolve the ncp associated with a mount point.  Such ncp's almost always
2061  * remain resolved and this routine is rarely called.  NFS MPs tends to force
2062  * re-resolution more often due to its mac-truck-smash-the-namecache
2063  * method of tracking namespace changes.
2064  *
2065  * The semantics for this call is that the passed ncp must be locked on
2066  * entry and will be locked on return.  However, if we actually have to
2067  * resolve the mount point we temporarily unlock the entry in order to
2068  * avoid race-to-root deadlocks due to e.g. dead NFS mounts.  Because of
2069  * the unlock we have to recheck the flags after we relock.
2070  */
2071 static int
2072 cache_resolve_mp(struct mount *mp)
2073 {
2074         struct namecache *ncp = mp->mnt_ncmountpt.ncp;
2075         struct vnode *vp;
2076         int error;
2077
2078         KKASSERT(mp != NULL);
2079
2080         /*
2081          * If the ncp is already resolved we have nothing to do.  However,
2082          * we do want to guarentee that a usable vnode is returned when
2083          * a vnode is present, so make sure it hasn't been reclaimed.
2084          */
2085         if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
2086                 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
2087                         _cache_setunresolved(ncp);
2088         }
2089
2090         if (ncp->nc_flag & NCF_UNRESOLVED) {
2091                 _cache_unlock(ncp);
2092                 while (vfs_busy(mp, 0))
2093                         ;
2094                 error = VFS_ROOT(mp, &vp);
2095                 _cache_lock(ncp);
2096
2097                 /*
2098                  * recheck the ncp state after relocking.
2099                  */
2100                 if (ncp->nc_flag & NCF_UNRESOLVED) {
2101                         ncp->nc_error = error;
2102                         if (error == 0) {
2103                                 _cache_setvp(ncp, vp);
2104                                 vput(vp);
2105                         } else {
2106                                 kprintf("[diagnostic] cache_resolve_mp: failed to resolve mount %p\n", mp);
2107                                 _cache_setvp(ncp, NULL);
2108                         }
2109                 } else if (error == 0) {
2110                         vput(vp);
2111                 }
2112                 vfs_unbusy(mp);
2113         }
2114         return(ncp->nc_error);
2115 }
2116
2117 void
2118 cache_cleanneg(int count)
2119 {
2120         struct namecache *ncp;
2121
2122         /*
2123          * Automode from the vnlru proc - clean out 10% of the negative cache
2124          * entries.
2125          */
2126         if (count == 0)
2127                 count = numneg / 10 + 1;
2128
2129         /*
2130          * Attempt to clean out the specified number of negative cache
2131          * entries.
2132          */
2133         while (count) {
2134                 ncp = TAILQ_FIRST(&ncneglist);
2135                 if (ncp == NULL) {
2136                         KKASSERT(numneg == 0);
2137                         break;
2138                 }
2139                 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
2140                 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
2141                 if (_cache_get_nonblock(ncp) == 0)
2142                         cache_zap(ncp);
2143                 --count;
2144         }
2145 }
2146
2147 /*
2148  * Rehash a ncp.  Rehashing is typically required if the name changes (should
2149  * not generally occur) or the parent link changes.  This function will
2150  * unhash the ncp if the ncp is no longer hashable.
2151  */
2152 static void
2153 _cache_rehash(struct namecache *ncp)
2154 {
2155         struct nchashhead *nchpp;
2156         u_int32_t hash;
2157
2158         if (ncp->nc_flag & NCF_HASHED) {
2159                 ncp->nc_flag &= ~NCF_HASHED;
2160                 LIST_REMOVE(ncp, nc_hash);
2161         }
2162         if (ncp->nc_nlen && ncp->nc_parent) {
2163                 hash = fnv_32_buf(ncp->nc_name, ncp->nc_nlen, FNV1_32_INIT);
2164                 hash = fnv_32_buf(&ncp->nc_parent, 
2165                                         sizeof(ncp->nc_parent), hash);
2166                 nchpp = NCHHASH(hash);
2167                 LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
2168                 ncp->nc_flag |= NCF_HASHED;
2169         }
2170 }
2171
2172 /*
2173  * Name cache initialization, from vfsinit() when we are booting
2174  */
2175 void
2176 nchinit(void)
2177 {
2178         int i;
2179         globaldata_t gd;
2180
2181         /* initialise per-cpu namecache effectiveness statistics. */
2182         for (i = 0; i < ncpus; ++i) {
2183                 gd = globaldata_find(i);
2184                 gd->gd_nchstats = &nchstats[i];
2185         }
2186         TAILQ_INIT(&ncneglist);
2187         nchashtbl = hashinit(desiredvnodes*2, M_VFSCACHE, &nchash);
2188         nclockwarn = 1 * hz;
2189 }
2190
2191 /*
2192  * Called from start_init() to bootstrap the root filesystem.  Returns
2193  * a referenced, unlocked namecache record.
2194  */
2195 void
2196 cache_allocroot(struct nchandle *nch, struct mount *mp, struct vnode *vp)
2197 {
2198         nch->ncp = cache_alloc(0);
2199         nch->mount = mp;
2200         ++mp->mnt_refs;
2201         if (vp)
2202                 _cache_setvp(nch->ncp, vp);
2203 }
2204
2205 /*
2206  * vfs_cache_setroot()
2207  *
2208  *      Create an association between the root of our namecache and
2209  *      the root vnode.  This routine may be called several times during
2210  *      booting.
2211  *
2212  *      If the caller intends to save the returned namecache pointer somewhere
2213  *      it must cache_hold() it.
2214  */
2215 void
2216 vfs_cache_setroot(struct vnode *nvp, struct nchandle *nch)
2217 {
2218         struct vnode *ovp;
2219         struct nchandle onch;
2220
2221         ovp = rootvnode;
2222         onch = rootnch;
2223         rootvnode = nvp;
2224         if (nch)
2225                 rootnch = *nch;
2226         else
2227                 cache_zero(&rootnch);
2228         if (ovp)
2229                 vrele(ovp);
2230         if (onch.ncp)
2231                 cache_drop(&onch);
2232 }
2233
2234 /*
2235  * XXX OLD API COMPAT FUNCTION.  This really messes up the new namecache
2236  * topology and is being removed as quickly as possible.  The new VOP_N*()
2237  * API calls are required to make specific adjustments using the supplied
2238  * ncp pointers rather then just bogusly purging random vnodes.
2239  *
2240  * Invalidate all namecache entries to a particular vnode as well as 
2241  * any direct children of that vnode in the namecache.  This is a 
2242  * 'catch all' purge used by filesystems that do not know any better.
2243  *
2244  * Note that the linkage between the vnode and its namecache entries will
2245  * be removed, but the namecache entries themselves might stay put due to
2246  * active references from elsewhere in the system or due to the existance of
2247  * the children.   The namecache topology is left intact even if we do not
2248  * know what the vnode association is.  Such entries will be marked
2249  * NCF_UNRESOLVED.
2250  */
2251 void
2252 cache_purge(struct vnode *vp)
2253 {
2254         cache_inval_vp(vp, CINV_DESTROY | CINV_CHILDREN);
2255 }
2256
2257 /*
2258  * Flush all entries referencing a particular filesystem.
2259  *
2260  * Since we need to check it anyway, we will flush all the invalid
2261  * entries at the same time.
2262  */
2263 #if 0
2264
2265 void
2266 cache_purgevfs(struct mount *mp)
2267 {
2268         struct nchashhead *nchpp;
2269         struct namecache *ncp, *nnp;
2270
2271         /*
2272          * Scan hash tables for applicable entries.
2273          */
2274         for (nchpp = &nchashtbl[nchash]; nchpp >= nchashtbl; nchpp--) {
2275                 ncp = LIST_FIRST(nchpp);
2276                 if (ncp)
2277                         _cache_hold(ncp);
2278                 while (ncp) {
2279                         nnp = LIST_NEXT(ncp, nc_hash);
2280                         if (nnp)
2281                                 _cache_hold(nnp);
2282                         if (ncp->nc_mount == mp) {
2283                                 _cache_lock(ncp);
2284                                 cache_zap(ncp);
2285                         } else {
2286                                 _cache_drop(ncp);
2287                         }
2288                         ncp = nnp;
2289                 }
2290         }
2291 }
2292
2293 #endif
2294
2295 /*
2296  * Create a new (theoretically) unique fsmid
2297  */
2298 int64_t
2299 cache_getnewfsmid(void)
2300 {
2301         static int fsmid_roller;
2302         int64_t fsmid;
2303
2304         ++fsmid_roller;
2305         fsmid = ((int64_t)time_second << 32) |
2306                         (fsmid_roller & 0x7FFFFFFF);
2307         return (fsmid);
2308 }
2309
2310
2311 static int disablecwd;
2312 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0, "");
2313
2314 static u_long numcwdcalls; STATNODE(CTLFLAG_RD, numcwdcalls, &numcwdcalls);
2315 static u_long numcwdfail1; STATNODE(CTLFLAG_RD, numcwdfail1, &numcwdfail1);
2316 static u_long numcwdfail2; STATNODE(CTLFLAG_RD, numcwdfail2, &numcwdfail2);
2317 static u_long numcwdfail3; STATNODE(CTLFLAG_RD, numcwdfail3, &numcwdfail3);
2318 static u_long numcwdfail4; STATNODE(CTLFLAG_RD, numcwdfail4, &numcwdfail4);
2319 static u_long numcwdfound; STATNODE(CTLFLAG_RD, numcwdfound, &numcwdfound);
2320
2321 int
2322 sys___getcwd(struct __getcwd_args *uap)
2323 {
2324         int buflen;
2325         int error;
2326         char *buf;
2327         char *bp;
2328
2329         if (disablecwd)
2330                 return (ENODEV);
2331
2332         buflen = uap->buflen;
2333         if (buflen < 2)
2334                 return (EINVAL);
2335         if (buflen > MAXPATHLEN)
2336                 buflen = MAXPATHLEN;
2337
2338         buf = kmalloc(buflen, M_TEMP, M_WAITOK);
2339         bp = kern_getcwd(buf, buflen, &error);
2340         if (error == 0)
2341                 error = copyout(bp, uap->buf, strlen(bp) + 1);
2342         kfree(buf, M_TEMP);
2343         return (error);
2344 }
2345
2346 char *
2347 kern_getcwd(char *buf, size_t buflen, int *error)
2348 {
2349         struct proc *p = curproc;
2350         char *bp;
2351         int i, slash_prefixed;
2352         struct filedesc *fdp;
2353         struct nchandle nch;
2354
2355         numcwdcalls++;
2356         bp = buf;
2357         bp += buflen - 1;
2358         *bp = '\0';
2359         fdp = p->p_fd;
2360         slash_prefixed = 0;
2361
2362         nch = fdp->fd_ncdir;
2363         while (nch.ncp && (nch.ncp != fdp->fd_nrdir.ncp || 
2364                nch.mount != fdp->fd_nrdir.mount)
2365         ) {
2366                 /*
2367                  * While traversing upwards if we encounter the root
2368                  * of the current mount we have to skip to the mount point
2369                  * in the underlying filesystem.
2370                  */
2371                 if (nch.ncp == nch.mount->mnt_ncmountpt.ncp) {
2372                         nch = nch.mount->mnt_ncmounton;
2373                         continue;
2374                 }
2375
2376                 /*
2377                  * Prepend the path segment
2378                  */
2379                 for (i = nch.ncp->nc_nlen - 1; i >= 0; i--) {
2380                         if (bp == buf) {
2381                                 numcwdfail4++;
2382                                 *error = ENOMEM;
2383                                 return(NULL);
2384                         }
2385                         *--bp = nch.ncp->nc_name[i];
2386                 }
2387                 if (bp == buf) {
2388                         numcwdfail4++;
2389                         *error = ENOMEM;
2390                         return(NULL);
2391                 }
2392                 *--bp = '/';
2393                 slash_prefixed = 1;
2394
2395                 /*
2396                  * Go up a directory.  This isn't a mount point so we don't
2397                  * have to check again.
2398                  */
2399                 nch.ncp = nch.ncp->nc_parent;
2400         }
2401         if (nch.ncp == NULL) {
2402                 numcwdfail2++;
2403                 *error = ENOENT;
2404                 return(NULL);
2405         }
2406         if (!slash_prefixed) {
2407                 if (bp == buf) {
2408                         numcwdfail4++;
2409                         *error = ENOMEM;
2410                         return(NULL);
2411                 }
2412                 *--bp = '/';
2413         }
2414         numcwdfound++;
2415         *error = 0;
2416         return (bp);
2417 }
2418
2419 /*
2420  * Thus begins the fullpath magic.
2421  */
2422
2423 #undef STATNODE
2424 #define STATNODE(name)                                                  \
2425         static u_int name;                                              \
2426         SYSCTL_UINT(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, "")
2427
2428 static int disablefullpath;
2429 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW,
2430     &disablefullpath, 0, "");
2431
2432 STATNODE(numfullpathcalls);
2433 STATNODE(numfullpathfail1);
2434 STATNODE(numfullpathfail2);
2435 STATNODE(numfullpathfail3);
2436 STATNODE(numfullpathfail4);
2437 STATNODE(numfullpathfound);
2438
2439 int
2440 cache_fullpath(struct proc *p, struct nchandle *nchp, char **retbuf, char **freebuf)
2441 {
2442         char *bp, *buf;
2443         int i, slash_prefixed;
2444         struct nchandle fd_nrdir;
2445         struct nchandle nch;
2446
2447         numfullpathcalls--;
2448
2449         *retbuf = NULL; 
2450         *freebuf = NULL;
2451
2452         buf = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
2453         bp = buf + MAXPATHLEN - 1;
2454         *bp = '\0';
2455         if (p != NULL)
2456                 fd_nrdir = p->p_fd->fd_nrdir;
2457         else
2458                 fd_nrdir = rootnch;
2459         slash_prefixed = 0;
2460         nch = *nchp;
2461
2462         while (nch.ncp && 
2463                (nch.ncp != fd_nrdir.ncp || nch.mount != fd_nrdir.mount)
2464         ) {
2465                 /*
2466                  * While traversing upwards if we encounter the root
2467                  * of the current mount we have to skip to the mount point.
2468                  */
2469                 if (nch.ncp == nch.mount->mnt_ncmountpt.ncp) {
2470                         nch = nch.mount->mnt_ncmounton;
2471                         continue;
2472                 }
2473
2474                 /*
2475                  * Prepend the path segment
2476                  */
2477                 for (i = nch.ncp->nc_nlen - 1; i >= 0; i--) {
2478                         if (bp == buf) {
2479                                 numfullpathfail4++;
2480                                 kfree(buf, M_TEMP);
2481                                 return(ENOMEM);
2482                         }
2483                         *--bp = nch.ncp->nc_name[i];
2484                 }
2485                 if (bp == buf) {
2486                         numfullpathfail4++;
2487                         kfree(buf, M_TEMP);
2488                         return(ENOMEM);
2489                 }
2490                 *--bp = '/';
2491                 slash_prefixed = 1;
2492
2493                 /*
2494                  * Go up a directory.  This isn't a mount point so we don't
2495                  * have to check again.
2496                  */
2497                 nch.ncp = nch.ncp->nc_parent;
2498         }
2499         if (nch.ncp == NULL) {
2500                 numfullpathfail2++;
2501                 kfree(buf, M_TEMP);
2502                 return(ENOENT);
2503         }
2504
2505         if (!slash_prefixed) {
2506                 if (bp == buf) {
2507                         numfullpathfail4++;
2508                         kfree(buf, M_TEMP);
2509                         return(ENOMEM);
2510                 }
2511                 *--bp = '/';
2512         }
2513         numfullpathfound++;
2514         *retbuf = bp; 
2515         *freebuf = buf;
2516
2517         return(0);
2518 }
2519
2520 int
2521 vn_fullpath(struct proc *p, struct vnode *vn, char **retbuf, char **freebuf) 
2522 {
2523         struct namecache *ncp;
2524         struct nchandle nch;
2525
2526         numfullpathcalls++;
2527         if (disablefullpath)
2528                 return (ENODEV);
2529
2530         if (p == NULL)
2531                 return (EINVAL);
2532
2533         /* vn is NULL, client wants us to use p->p_textvp */
2534         if (vn == NULL) {
2535                 if ((vn = p->p_textvp) == NULL)
2536                         return (EINVAL);
2537         }
2538         TAILQ_FOREACH(ncp, &vn->v_namecache, nc_vnode) {
2539                 if (ncp->nc_nlen)
2540                         break;
2541         }
2542         if (ncp == NULL)
2543                 return (EINVAL);
2544
2545         numfullpathcalls--;
2546         nch.ncp = ncp;;
2547         nch.mount = vn->v_mount;
2548         return(cache_fullpath(p, &nch, retbuf, freebuf));
2549 }