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