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