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