VFS messaging/interfacing work stage 9/99: VFS 'NEW' API WORK.
[dragonfly.git] / sys / kern / vfs_cache.c
1 /*
2  * Copyright (c) 2003,2004 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  * 
34  * Copyright (c) 1989, 1993, 1995
35  *      The Regents of the University of California.  All rights reserved.
36  *
37  * This code is derived from software contributed to Berkeley by
38  * Poul-Henning Kamp of the FreeBSD Project.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. All advertising materials mentioning features or use of this software
49  *    must display the following acknowledgement:
50  *      This product includes software developed by the University of
51  *      California, Berkeley and its contributors.
52  * 4. Neither the name of the University nor the names of its contributors
53  *    may be used to endorse or promote products derived from this software
54  *    without specific prior written permission.
55  *
56  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
57  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
58  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
59  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
60  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
61  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
62  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
64  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
65  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66  * SUCH DAMAGE.
67  *
68  *      @(#)vfs_cache.c 8.5 (Berkeley) 3/22/95
69  * $FreeBSD: src/sys/kern/vfs_cache.c,v 1.42.2.6 2001/10/05 20:07:03 dillon Exp $
70  * $DragonFly: src/sys/kern/vfs_cache.c,v 1.42 2004/11/12 00:09:24 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 u_long   numneg;         /* number of cache entries allocated */
136 SYSCTL_ULONG(_debug, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0, "");
137
138 static u_long   numcache;               /* number of cache entries allocated */
139 SYSCTL_ULONG(_debug, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0, "");
140
141 static u_long   numunres;               /* number of unresolved entries */
142 SYSCTL_ULONG(_debug, OID_AUTO, numunres, CTLFLAG_RD, &numunres, 0, "");
143
144 SYSCTL_INT(_debug, OID_AUTO, vnsize, CTLFLAG_RD, 0, sizeof(struct vnode), "");
145 SYSCTL_INT(_debug, OID_AUTO, ncsize, CTLFLAG_RD, 0, sizeof(struct namecache), "");
146
147 static int cache_resolve_mp(struct namecache *ncp);
148 static void cache_rehash(struct namecache *ncp);
149
150 /*
151  * The new name cache statistics
152  */
153 SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0, "Name cache statistics");
154 #define STATNODE(mode, name, var) \
155         SYSCTL_ULONG(_vfs_cache, OID_AUTO, name, mode, var, 0, "");
156 STATNODE(CTLFLAG_RD, numneg, &numneg);
157 STATNODE(CTLFLAG_RD, numcache, &numcache);
158 static u_long numcalls; STATNODE(CTLFLAG_RD, numcalls, &numcalls);
159 static u_long dothits; STATNODE(CTLFLAG_RD, dothits, &dothits);
160 static u_long dotdothits; STATNODE(CTLFLAG_RD, dotdothits, &dotdothits);
161 static u_long numchecks; STATNODE(CTLFLAG_RD, numchecks, &numchecks);
162 static u_long nummiss; STATNODE(CTLFLAG_RD, nummiss, &nummiss);
163 static u_long nummisszap; STATNODE(CTLFLAG_RD, nummisszap, &nummisszap);
164 static u_long numposzaps; STATNODE(CTLFLAG_RD, numposzaps, &numposzaps);
165 static u_long numposhits; STATNODE(CTLFLAG_RD, numposhits, &numposhits);
166 static u_long numnegzaps; STATNODE(CTLFLAG_RD, numnegzaps, &numnegzaps);
167 static u_long numneghits; STATNODE(CTLFLAG_RD, numneghits, &numneghits);
168
169 struct nchstats nchstats[SMP_MAXCPU];
170 /*
171  * Export VFS cache effectiveness statistics to user-land.
172  *
173  * The statistics are left for aggregation to user-land so
174  * neat things can be achieved, like observing per-CPU cache
175  * distribution.
176  */
177 static int
178 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
179 {
180         struct globaldata *gd;
181         int i, error;
182
183         error = 0;
184         for (i = 0; i < ncpus; ++i) {
185                 gd = globaldata_find(i);
186                 if ((error = SYSCTL_OUT(req, (void *)&(*gd->gd_nchstats),
187                         sizeof(struct nchstats))))
188                         break;
189         }
190
191         return (error);
192 }
193 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE|CTLFLAG_RD,
194   0, 0, sysctl_nchstats, "S,nchstats", "VFS cache effectiveness statistics");
195
196 static void cache_zap(struct namecache *ncp);
197
198 /*
199  * cache_hold() and cache_drop() prevent the premature deletion of a
200  * namecache entry but do not prevent operations (such as zapping) on
201  * that namecache entry.
202  */
203 static __inline
204 struct namecache *
205 _cache_hold(struct namecache *ncp)
206 {
207         ++ncp->nc_refs;
208         return(ncp);
209 }
210
211 /*
212  * When dropping an entry, if only one ref remains and the entry has not
213  * been resolved, zap it.  Since the one reference is being dropped the
214  * entry had better not be locked.
215  */
216 static __inline
217 void
218 _cache_drop(struct namecache *ncp)
219 {
220         KKASSERT(ncp->nc_refs > 0);
221         if (ncp->nc_refs == 1 && 
222             (ncp->nc_flag & NCF_UNRESOLVED) && 
223             TAILQ_EMPTY(&ncp->nc_list)
224         ) {
225                 KKASSERT(ncp->nc_exlocks == 0);
226                 cache_lock(ncp);
227                 cache_zap(ncp);
228         } else {
229                 --ncp->nc_refs;
230         }
231 }
232
233 /*
234  * Link a new namecache entry to its parent.  Be careful to avoid races
235  * if vhold() blocks in the future.
236  *
237  * If we are creating a child under an oldapi parent we must mark the
238  * child as being an oldapi entry as well.
239  */
240 static void
241 cache_link_parent(struct namecache *ncp, struct namecache *par)
242 {
243         KKASSERT(ncp->nc_parent == NULL);
244         ncp->nc_parent = par;
245         if (TAILQ_EMPTY(&par->nc_list)) {
246                 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
247                 /*
248                  * Any vp associated with an ncp which has children must
249                  * be held to prevent it from being recycled.
250                  */
251                 if (par->nc_vp)
252                         vhold(par->nc_vp);
253         } else {
254                 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
255         }
256 }
257
258 /*
259  * Remove the parent association from a namecache structure.  If this is
260  * the last child of the parent the cache_drop(par) will attempt to
261  * recursively zap the parent.
262  */
263 static void
264 cache_unlink_parent(struct namecache *ncp)
265 {
266         struct namecache *par;
267
268         if ((par = ncp->nc_parent) != NULL) {
269                 ncp->nc_parent = NULL;
270                 par = cache_hold(par);
271                 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
272                 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
273                         vdrop(par->nc_vp);
274                 cache_drop(par);
275         }
276 }
277
278 /*
279  * Allocate a new namecache structure.  Most of the code does not require
280  * zero-termination of the string but it makes vop_compat_ncreate() easier.
281  */
282 static struct namecache *
283 cache_alloc(int nlen)
284 {
285         struct namecache *ncp;
286
287         ncp = malloc(sizeof(*ncp), M_VFSCACHE, M_WAITOK|M_ZERO);
288         if (nlen)
289                 ncp->nc_name = malloc(nlen + 1, M_VFSCACHE, M_WAITOK);
290         ncp->nc_nlen = nlen;
291         ncp->nc_flag = NCF_UNRESOLVED;
292         ncp->nc_error = ENOTCONN;       /* needs to be resolved */
293         ncp->nc_refs = 1;
294         TAILQ_INIT(&ncp->nc_list);
295         cache_lock(ncp);
296         return(ncp);
297 }
298
299 static void
300 cache_free(struct namecache *ncp)
301 {
302         KKASSERT(ncp->nc_refs == 1 && ncp->nc_exlocks == 1);
303         if (ncp->nc_name)
304                 free(ncp->nc_name, M_VFSCACHE);
305         free(ncp, M_VFSCACHE);
306 }
307
308 /*
309  * Ref and deref a namecache structure.
310  */
311 struct namecache *
312 cache_hold(struct namecache *ncp)
313 {
314         return(_cache_hold(ncp));
315 }
316
317 void
318 cache_drop(struct namecache *ncp)
319 {
320         _cache_drop(ncp);
321 }
322
323 /*
324  * Namespace locking.  The caller must already hold a reference to the
325  * namecache structure in order to lock/unlock it.  This function prevents
326  * the namespace from being created or destroyed by accessors other then
327  * the lock holder.
328  *
329  * Note that holding a locked namecache structure prevents other threads
330  * from making namespace changes (e.g. deleting or creating), prevents
331  * vnode association state changes by other threads, and prevents the
332  * namecache entry from being resolved or unresolved by other threads.
333  *
334  * The lock owner has full authority to associate/disassociate vnodes
335  * and resolve/unresolve the locked ncp.
336  *
337  * In particular, if a vnode is associated with a locked cache entry
338  * that vnode will *NOT* be recycled.  We accomplish this by vhold()ing the
339  * vnode.  XXX we should find a more efficient way to prevent the vnode
340  * from being recycled, but remember that any given vnode may have multiple
341  * namecache associations (think hardlinks).
342  */
343 void
344 cache_lock(struct namecache *ncp)
345 {
346         thread_t td;
347         int didwarn;
348
349         KKASSERT(ncp->nc_refs != 0);
350         didwarn = 0;
351         td = curthread;
352
353         for (;;) {
354                 if (ncp->nc_exlocks == 0) {
355                         ncp->nc_exlocks = 1;
356                         ncp->nc_locktd = td;
357                         /* 
358                          * The vp associated with a locked ncp must be held
359                          * to prevent it from being recycled (which would
360                          * cause the ncp to become unresolved).
361                          *
362                          * XXX loop on race for later MPSAFE work.
363                          */
364                         if (ncp->nc_vp)
365                                 vhold(ncp->nc_vp);
366                         break;
367                 }
368                 if (ncp->nc_locktd == td) {
369                         ++ncp->nc_exlocks;
370                         break;
371                 }
372                 ncp->nc_flag |= NCF_LOCKREQ;
373                 if (tsleep(ncp, 0, "clock", hz) == EWOULDBLOCK) {
374                         if (didwarn)
375                                 continue;
376                         didwarn = 1;
377                         printf("[diagnostic] cache_lock: blocked on %p", ncp);
378                         if ((ncp->nc_flag & NCF_MOUNTPT) && ncp->nc_mount)
379                             printf(" [MOUNTPT %s]\n", ncp->nc_mount->mnt_stat.f_mntonname);
380                         else
381                             printf(" \"%*.*s\"\n",
382                                 ncp->nc_nlen, ncp->nc_nlen,
383                                 ncp->nc_name);
384                 }
385         }
386
387         if (didwarn == 1) {
388                 printf("[diagnostic] cache_lock: unblocked %*.*s\n",
389                         ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
390         }
391 }
392
393 int
394 cache_lock_nonblock(struct namecache *ncp)
395 {
396         thread_t td;
397
398         KKASSERT(ncp->nc_refs != 0);
399         td = curthread;
400         if (ncp->nc_exlocks == 0) {
401                 ncp->nc_exlocks = 1;
402                 ncp->nc_locktd = td;
403                 /* 
404                  * The vp associated with a locked ncp must be held
405                  * to prevent it from being recycled (which would
406                  * cause the ncp to become unresolved).
407                  *
408                  * XXX loop on race for later MPSAFE work.
409                  */
410                 if (ncp->nc_vp)
411                         vhold(ncp->nc_vp);
412                 return(0);
413         } else {
414                 return(EWOULDBLOCK);
415         }
416 }
417
418 void
419 cache_unlock(struct namecache *ncp)
420 {
421         thread_t td = curthread;
422
423         KKASSERT(ncp->nc_refs > 0);
424         KKASSERT(ncp->nc_exlocks > 0);
425         KKASSERT(ncp->nc_locktd == td);
426         if (--ncp->nc_exlocks == 0) {
427                 if (ncp->nc_vp)
428                         vdrop(ncp->nc_vp);
429                 ncp->nc_locktd = NULL;
430                 if (ncp->nc_flag & NCF_LOCKREQ) {
431                         ncp->nc_flag &= ~NCF_LOCKREQ;
432                         wakeup_one(ncp);
433                 }
434         }
435 }
436
437 /*
438  * ref-and-lock, unlock-and-deref functions.
439  */
440 struct namecache *
441 cache_get(struct namecache *ncp)
442 {
443         _cache_hold(ncp);
444         cache_lock(ncp);
445         return(ncp);
446 }
447
448 int
449 cache_get_nonblock(struct namecache *ncp)
450 {
451         /* XXX MP */
452         if (ncp->nc_exlocks == 0 || ncp->nc_locktd == curthread) {
453                 _cache_hold(ncp);
454                 cache_lock(ncp);
455                 return(0);
456         }
457         return(EWOULDBLOCK);
458 }
459
460 void
461 cache_put(struct namecache *ncp)
462 {
463         cache_unlock(ncp);
464         _cache_drop(ncp);
465 }
466
467 /*
468  * Resolve an unresolved ncp by associating a vnode with it.  If the
469  * vnode is NULL, a negative cache entry is created.
470  *
471  * The ncp should be locked on entry and will remain locked on return.
472  */
473 void
474 cache_setvp(struct namecache *ncp, struct vnode *vp)
475 {
476         KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
477         ncp->nc_vp = vp;
478         if (vp != NULL) {
479                 /*
480                  * Any vp associated with an ncp which has children must
481                  * be held.  Any vp associated with a locked ncp must be held.
482                  */
483                 if (!TAILQ_EMPTY(&ncp->nc_list))
484                         vhold(vp);
485                 TAILQ_INSERT_HEAD(&vp->v_namecache, ncp, nc_vnode);
486                 if (ncp->nc_exlocks)
487                         vhold(vp);
488
489                 /*
490                  * Set auxillary flags
491                  */
492                 switch(vp->v_type) {
493                 case VDIR:
494                         ncp->nc_flag |= NCF_ISDIR;
495                         break;
496                 case VLNK:
497                         ncp->nc_flag |= NCF_ISSYMLINK;
498                         /* XXX cache the contents of the symlink */
499                         break;
500                 default:
501                         break;
502                 }
503                 ++numcache;
504                 ncp->nc_error = 0;
505         } else {
506                 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
507                 ++numneg;
508                 ncp->nc_error = ENOENT;
509         }
510         ncp->nc_flag &= ~NCF_UNRESOLVED;
511 }
512
513 void
514 cache_settimeout(struct namecache *ncp, int nticks)
515 {
516         if ((ncp->nc_timeout = ticks + nticks) == 0)
517                 ncp->nc_timeout = 1;
518 }
519
520 /*
521  * Disassociate the vnode or negative-cache association and mark a
522  * namecache entry as unresolved again.  Note that the ncp is still
523  * left in the hash table and still linked to its parent.
524  *
525  * The ncp should be locked and refd on entry and will remain locked and refd
526  * on return.
527  *
528  * This routine is normally never called on a directory containing children.
529  * However, NFS often does just that in its rename() code as a cop-out to
530  * avoid complex namespace operations.  This disconnects a directory vnode
531  * from its namecache and can cause the OLDAPI and NEWAPI to get out of
532  * sync.
533  */
534 void
535 cache_setunresolved(struct namecache *ncp)
536 {
537         struct vnode *vp;
538
539         if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
540                 ncp->nc_flag |= NCF_UNRESOLVED;
541                 ncp->nc_flag &= ~(NCF_WHITEOUT|NCF_ISDIR|NCF_ISSYMLINK);
542                 ncp->nc_timeout = 0;
543                 ncp->nc_error = ENOTCONN;
544                 ++numunres;
545                 if ((vp = ncp->nc_vp) != NULL) {
546                         --numcache;
547                         ncp->nc_vp = NULL;
548                         TAILQ_REMOVE(&vp->v_namecache, ncp, nc_vnode);
549
550                         /*
551                          * Any vp associated with an ncp with children is
552                          * held by that ncp.  Any vp associated with a locked
553                          * ncp is held by that ncp.  These conditions must be
554                          * undone when the vp is cleared out from the ncp.
555                          */
556                         if (!TAILQ_EMPTY(&ncp->nc_list))
557                                 vdrop(vp);
558                         if (ncp->nc_exlocks)
559                                 vdrop(vp);
560                 } else {
561                         TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
562                         --numneg;
563                 }
564         }
565 }
566
567 /*
568  * Invalidate portions of a namecache entry.  The passed ncp should be
569  * referenced and locked but we might not adhere to that rule during the
570  * old api -> new api transition period.
571  *
572  * CINV_PARENT          - disconnect the ncp from its parent
573  * CINV_SELF            - same as cache_setunresolved(ncp)
574  * CINV_CHILDREN        - disconnect children of the ncp from the ncp
575  */
576 void
577 cache_inval(struct namecache *ncp, int flags)
578 {
579         struct namecache *kid;
580         struct namecache *nextkid;
581
582         if (flags & CINV_SELF)
583                 cache_setunresolved(ncp);
584         if (flags & CINV_PARENT)
585                 cache_unlink_parent(ncp);
586
587         /*
588          * Children are invalidated when the parent is destroyed.  This
589          * basically disconnects the children from the parent.  Anyone
590          * CD'd into a child will no longer be able to ".." back up.
591          *
592          * Any unresolved or negative cache-hit children with a ref count
593          * of 0 must be immediately and recursively destroyed or this
594          * disconnection may leave them dangling forever.  XXX this recursion
595          * could run the kernel out of stack, the children should be placed
596          * on a to-destroy list instead.
597          */
598         if (flags & CINV_CHILDREN) {
599                 if ((kid = TAILQ_FIRST(&ncp->nc_list)) != NULL)
600                         cache_hold(kid);
601                 while (kid) {
602                         if ((nextkid = TAILQ_NEXT(kid, nc_entry)) != NULL)
603                                 cache_hold(nextkid);
604                         if (kid->nc_refs == 0 &&
605                             ((kid->nc_flag & NCF_UNRESOLVED) || 
606                              kid->nc_vp == NULL)
607                         ) {
608                                 cache_inval(kid, CINV_PARENT);
609                         }
610                         cache_unlink_parent(kid);
611                         cache_drop(kid);
612                         kid = nextkid;
613                 }
614         }
615 }
616
617 void
618 cache_inval_vp(struct vnode *vp, int flags)
619 {
620         struct namecache *ncp;
621
622         if (flags & CINV_SELF) {
623                 while ((ncp = TAILQ_FIRST(&vp->v_namecache)) != NULL) {
624                         cache_hold(ncp);
625                         KKASSERT((ncp->nc_flag & NCF_UNRESOLVED) == 0);
626                         cache_inval(ncp, flags);
627                         cache_drop(ncp);
628                 }
629         } else {
630                 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
631                         cache_hold(ncp);
632                         cache_inval(ncp, flags);
633                         cache_drop(ncp);
634                 }
635         }
636 }
637
638 /*
639  * The source ncp has been renamed to the target ncp.  Both fncp and tncp
640  * must be locked.  Both will be set to unresolved, any children of tncp
641  * will be disconnected (the prior contents of the target is assumed to be
642  * destroyed by the rename operation, e.g. renaming over an empty directory),
643  * and all children of fncp will be moved to tncp.
644  *
645  * After we return the caller has the option of calling cache_setvp() if
646  * the vnode of the new target ncp is known.
647  *
648  * Any process CD'd into any of the children will no longer be able to ".."
649  * back out.  An rm -rf can cause this situation to occur.
650  */
651 void
652 cache_rename(struct namecache *fncp, struct namecache *tncp)
653 {
654         struct namecache *scan;
655
656         cache_setunresolved(fncp);
657         cache_setunresolved(tncp);
658         cache_inval(tncp, CINV_CHILDREN);
659         while ((scan = TAILQ_FIRST(&fncp->nc_list)) != NULL) {
660                 cache_hold(scan);
661                 cache_unlink_parent(scan);
662                 cache_link_parent(scan, tncp);
663                 if (scan->nc_flag & NCF_HASHED)
664                         cache_rehash(scan);
665                 cache_drop(scan);
666         }
667 }
668
669 /*
670  * vget the vnode associated with the namecache entry.  Resolve the namecache
671  * entry if necessary and deal with namecache/vp races.  The passed ncp must
672  * be referenced and may be locked.  The ncp's ref/locking state is not 
673  * effected by this call.
674  *
675  * lk_type may be LK_SHARED, LK_EXCLUSIVE.  A ref'd, possibly locked
676  * (depending on the passed lk_type) will be returned in *vpp with an error
677  * of 0, or NULL will be returned in *vpp with a non-0 error code.  The
678  * most typical error is ENOENT, meaning that the ncp represents a negative
679  * cache hit and there is no vnode to retrieve, but other errors can occur
680  * too.
681  *
682  * The main race we have to deal with are namecache zaps.  The ncp itself
683  * will not disappear since it is referenced, and it turns out that the
684  * validity of the vp pointer can be checked simply by rechecking the
685  * contents of ncp->nc_vp.
686  */
687 int
688 cache_vget(struct namecache *ncp, struct ucred *cred,
689            int lk_type, struct vnode **vpp)
690 {
691         struct vnode *vp;
692         int error;
693
694 again:
695         vp = NULL;
696         if (ncp->nc_flag & NCF_UNRESOLVED) {
697                 cache_lock(ncp);
698                 error = cache_resolve(ncp, cred);
699                 cache_unlock(ncp);
700         } else {
701                 error = 0;
702         }
703         if (error == 0 && (vp = ncp->nc_vp) != NULL) {
704                 error = vget(vp, lk_type, curthread);
705                 if (error) {
706                         if (vp != ncp->nc_vp)   /* handle cache_zap race */
707                                 goto again;
708                         vp = NULL;
709                 } else if (vp != ncp->nc_vp) {  /* handle cache_zap race */
710                         vput(vp);
711                         goto again;
712                 }
713         }
714         if (error == 0 && vp == NULL)
715                 error = ENOENT;
716         *vpp = vp;
717         return(error);
718 }
719
720 int
721 cache_vref(struct namecache *ncp, struct ucred *cred, struct vnode **vpp)
722 {
723         struct vnode *vp;
724         int error;
725
726 again:
727         vp = NULL;
728         if (ncp->nc_flag & NCF_UNRESOLVED) {
729                 cache_lock(ncp);
730                 error = cache_resolve(ncp, cred);
731                 cache_unlock(ncp);
732         } else {
733                 error = 0;
734         }
735         if (error == 0 && (vp = ncp->nc_vp) != NULL) {
736                 vref(vp);
737                 if (vp != ncp->nc_vp) {         /* handle cache_zap race */
738                         vrele(vp);
739                         goto again;
740                 }
741         }
742         if (error == 0 && vp == NULL)
743                 error = ENOENT;
744         *vpp = vp;
745         return(error);
746 }
747
748 /*
749  * Convert a directory vnode to a namecache record without any other 
750  * knowledge of the topology.  This ONLY works with directory vnodes and
751  * is ONLY used by the NFS server.  dvp must be refd but unlocked, and the
752  * returned ncp (if not NULL) will be held and unlocked.
753  *
754  * If 'makeit' is 0 and dvp has no existing namecache record, NULL is returned.
755  * If 'makeit' is 1 we attempt to track-down and create the namecache topology
756  * for dvp.  This will fail only if the directory has been deleted out from
757  * under the caller.  
758  *
759  * Callers must always check for a NULL return no matter the value of 'makeit'.
760  */
761
762 static int cache_inefficient_scan(struct namecache *ncp, struct ucred *cred,
763                                   struct vnode *dvp);
764
765 struct namecache *
766 cache_fromdvp(struct vnode *dvp, struct ucred *cred, int makeit)
767 {
768         struct namecache *ncp;
769         struct vnode *pvp;
770         int error;
771
772         /*
773          * Temporary debugging code to force the directory scanning code
774          * to be exercised.
775          */
776         ncp = NULL;
777         if (ncvp_debug >= 3 && makeit && TAILQ_FIRST(&dvp->v_namecache)) {
778                 ncp = TAILQ_FIRST(&dvp->v_namecache);
779                 printf("cache_fromdvp: forcing %s\n", ncp->nc_name);
780                 goto force;
781         }
782
783         /*
784          * Loop until resolution, inside code will break out on error.
785          */
786         while ((ncp = TAILQ_FIRST(&dvp->v_namecache)) == NULL && makeit) {
787 force:
788                 /*
789                  * If dvp is the root of its filesystem it should already
790                  * have a namecache pointer associated with it as a side 
791                  * effect of the mount, but it may have been disassociated.
792                  */
793                 if (dvp->v_flag & VROOT) {
794                         ncp = cache_get(dvp->v_mount->mnt_ncp);
795                         error = cache_resolve_mp(ncp);
796                         cache_put(ncp);
797                         if (ncvp_debug) {
798                                 printf("cache_fromdvp: resolve root of mount %p error %d", 
799                                         dvp->v_mount, error);
800                         }
801                         if (error) {
802                                 if (ncvp_debug)
803                                         printf(" failed\n");
804                                 ncp = NULL;
805                                 break;
806                         }
807                         if (ncvp_debug)
808                                 printf(" succeeded\n");
809                         continue;
810                 }
811
812                 /*
813                  * Get the parent directory and resolve its ncp.
814                  */
815                 error = vop_nlookupdotdot(dvp->v_ops, dvp, &pvp, cred);
816                 if (error) {
817                         printf("lookupdotdot failed %d %p\n", error, pvp);
818                         break;
819                 }
820                 VOP_UNLOCK(pvp, 0, curthread);
821
822                 /*
823                  * XXX this recursion could run the kernel out of stack,
824                  * change to a less efficient algorithm if we get too deep
825                  * (use 'makeit' for a depth counter?)
826                  */
827                 ncp = cache_fromdvp(pvp, cred, makeit);
828                 vrele(pvp);
829                 if (ncp == NULL)
830                         break;
831
832                 /*
833                  * Do an inefficient scan of pvp (embodied by ncp) to look
834                  * for dvp.  This will create a namecache record for dvp on
835                  * success.  We loop up to recheck on success.
836                  *
837                  * ncp and dvp are both held but not locked.
838                  */
839                 error = cache_inefficient_scan(ncp, cred, dvp);
840                 cache_drop(ncp);
841                 if (error) {
842                         printf("cache_fromdvp: scan %p (%s) failed on dvp=%p\n",
843                                 pvp, ncp->nc_name, dvp);
844                         ncp = NULL;
845                         break;
846                 }
847                 if (ncvp_debug) {
848                         printf("cache_fromdvp: scan %p (%s) succeeded\n",
849                                 pvp, ncp->nc_name);
850                 }
851         }
852         if (ncp)
853                 cache_hold(ncp);
854         return (ncp);
855 }
856
857 /*
858  * Do an inefficient scan of the directory represented by ncp looking for
859  * the directory vnode dvp.  ncp must be held but not locked on entry and
860  * will be held on return.  dvp must be refd but not locked on entry and
861  * will remain refd on return.
862  *
863  * Why do this at all?  Well, due to its stateless nature the NFS server
864  * converts file handles directly to vnodes without necessarily going through
865  * the namecache ops that would otherwise create the namecache topology
866  * leading to the vnode.  We could either (1) Change the namecache algorithms
867  * to allow disconnect namecache records that are re-merged opportunistically,
868  * or (2) Make the NFS server backtrack and scan to recover a connected
869  * namecache topology in order to then be able to issue new API lookups.
870  *
871  * It turns out that (1) is a huge mess.  It takes a nice clean set of 
872  * namecache algorithms and introduces a lot of complication in every subsystem
873  * that calls into the namecache to deal with the re-merge case, especially
874  * since we are using the namecache to placehold negative lookups and the
875  * vnode might not be immediately assigned. (2) is certainly far less
876  * efficient then (1), but since we are only talking about directories here
877  * (which are likely to remain cached), the case does not actually run all
878  * that often and has the supreme advantage of not polluting the namecache
879  * algorithms.
880  */
881 static int
882 cache_inefficient_scan(struct namecache *ncp, struct ucred *cred, 
883                        struct vnode *dvp)
884 {
885         struct nlcomponent nlc;
886         struct namecache *rncp;
887         struct dirent *den;
888         struct vnode *pvp;
889         struct vattr vat;
890         struct iovec iov;
891         struct uio uio;
892         u_long *cookies;
893         off_t baseoff;
894         int ncookies;
895         int blksize;
896         int eofflag;
897         char *rbuf;
898         int error;
899         int xoff;
900         int i;
901
902         vat.va_blocksize = 0;
903         if ((error = VOP_GETATTR(dvp, &vat, curthread)) != 0)
904                 return (error);
905         if ((error = cache_vget(ncp, cred, LK_SHARED, &pvp)) != 0)
906                 return (error);
907         if (ncvp_debug)
908                 printf("inefficient_scan: directory iosize %ld vattr fileid = %ld\n", vat.va_blocksize, (long)vat.va_fileid);
909         if ((blksize = vat.va_blocksize) == 0)
910                 blksize = DEV_BSIZE;
911         rbuf = malloc(blksize, M_TEMP, M_WAITOK);
912         rncp = NULL;
913
914         eofflag = 0;
915         uio.uio_offset = 0;
916         cookies = NULL;
917 again:
918         baseoff = uio.uio_offset;
919         iov.iov_base = rbuf;
920         iov.iov_len = blksize;
921         uio.uio_iov = &iov;
922         uio.uio_iovcnt = 1;
923         uio.uio_resid = blksize;
924         uio.uio_segflg = UIO_SYSSPACE;
925         uio.uio_rw = UIO_READ;
926         uio.uio_td = curthread;
927
928         if (cookies) {
929                 free(cookies, M_TEMP);
930                 cookies = NULL;
931         }
932         if (ncvp_debug >= 2)
933                 printf("cache_inefficient_scan: readdir @ %08x\n", (int)baseoff);
934         error = VOP_READDIR(pvp, &uio, cred, &eofflag, &ncookies, &cookies);
935         if (error == 0 && cookies == NULL)
936                 error = EPERM;
937         if (error == 0) {
938                 for (i = 0; i < ncookies; ++i) {
939                         xoff = (int)(cookies[i] - (u_long)baseoff);
940                         /*
941                          * UFS plays a little trick to skip the first entry
942                          * in a directory ("."), by assigning the cookie to
943                          * dpoff + dp->d_reclen in the loop.  This causes
944                          * the last cookie to be assigned to the data-end of
945                          * the directory.  XXX
946                          */
947                         if (xoff == blksize)
948                                 break;
949                         KKASSERT(xoff >= 0 && xoff <= blksize);
950                         den = (struct dirent *)(rbuf + xoff);
951                         if (ncvp_debug >= 2)
952                                 printf("cache_inefficient_scan: %*.*s\n",
953                                         den->d_namlen, den->d_namlen, den->d_name);
954                         if (den->d_type != DT_WHT &&
955                             den->d_fileno == vat.va_fileid) {
956                                 if (ncvp_debug)
957                                         printf("cache_inefficient_scan: MATCHED inode %ld path %s/%*.*s\n", vat.va_fileid, ncp->nc_name, den->d_namlen, den->d_namlen, den->d_name);
958                                 nlc.nlc_nameptr = den->d_name;
959                                 nlc.nlc_namelen = den->d_namlen;
960                                 VOP_UNLOCK(pvp, 0, curthread);
961                                 rncp = cache_nlookup(ncp, &nlc);
962                                 KKASSERT(rncp != NULL);
963                                 break;
964                         }
965                 }
966                 if (rncp == NULL && eofflag == 0 && uio.uio_resid != blksize)
967                         goto again;
968         }
969         if (cookies) {
970                 free(cookies, M_TEMP);
971                 cookies = NULL;
972         }
973         if (rncp) {
974                 vrele(pvp);
975                 if (rncp->nc_flag & NCF_UNRESOLVED) {
976                         cache_setvp(rncp, dvp);
977                         if (ncvp_debug >= 2) {
978                                 printf("cache_inefficient_scan: setvp %s/%s = %p\n",
979                                         ncp->nc_name, rncp->nc_name, dvp);
980                         }
981                 } else {
982                         if (ncvp_debug >= 2) {
983                                 printf("cache_inefficient_scan: setvp %s/%s already set %p/%p\n", 
984                                         ncp->nc_name, rncp->nc_name, dvp,
985                                         rncp->nc_vp);
986                         }
987                 }
988                 if (rncp->nc_vp == NULL)
989                         error = rncp->nc_error;
990                 cache_put(rncp);
991         } else {
992                 printf("cache_inefficient_scan: dvp %p NOT FOUND in %s\n",
993                         dvp, ncp->nc_name);
994                 vput(pvp);
995                 error = ENOENT;
996         }
997         free(rbuf, M_TEMP);
998         return (error);
999 }
1000
1001 /*
1002  * Zap a namecache entry.  The ncp is unconditionally set to an unresolved
1003  * state, which disassociates it from its vnode or ncneglist.
1004  *
1005  * Then, if there are no additional references to the ncp and no children,
1006  * the ncp is removed from the topology and destroyed.  This function will
1007  * also run through the nc_parent chain and destroy parent ncps if possible.
1008  * As a side benefit, it turns out the only conditions that allow running
1009  * up the chain are also the conditions to ensure no deadlock will occur.
1010  *
1011  * References and/or children may exist if the ncp is in the middle of the
1012  * topology, preventing the ncp from being destroyed.
1013  *
1014  * This function must be called with the ncp held and locked and will unlock
1015  * and drop it during zapping.
1016  */
1017 static void
1018 cache_zap(struct namecache *ncp)
1019 {
1020         struct namecache *par;
1021
1022         /*
1023          * Disassociate the vnode or negative cache ref and set NCF_UNRESOLVED.
1024          */
1025         cache_setunresolved(ncp);
1026
1027         /*
1028          * Try to scrap the entry and possibly tail-recurse on its parent.
1029          * We only scrap unref'd (other then our ref) unresolved entries,
1030          * we do not scrap 'live' entries.
1031          */
1032         while (ncp->nc_flag & NCF_UNRESOLVED) {
1033                 /*
1034                  * Someone other then us has a ref, stop.
1035                  */
1036                 if (ncp->nc_refs > 1)
1037                         goto done;
1038
1039                 /*
1040                  * We have children, stop.
1041                  */
1042                 if (!TAILQ_EMPTY(&ncp->nc_list))
1043                         goto done;
1044
1045                 /*
1046                  * Remove ncp from the topology: hash table and parent linkage.
1047                  */
1048                 if (ncp->nc_flag & NCF_HASHED) {
1049                         ncp->nc_flag &= ~NCF_HASHED;
1050                         LIST_REMOVE(ncp, nc_hash);
1051                 }
1052                 if ((par = ncp->nc_parent) != NULL) {
1053                         par = cache_hold(par);
1054                         TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
1055                         ncp->nc_parent = NULL;
1056                         if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
1057                                 vdrop(par->nc_vp);
1058                 }
1059
1060                 /*
1061                  * ncp should not have picked up any refs.  Physically
1062                  * destroy the ncp.
1063                  */
1064                 KKASSERT(ncp->nc_refs == 1);
1065                 --numunres;
1066                 /* cache_unlock(ncp) not required */
1067                 ncp->nc_refs = -1;      /* safety */
1068                 if (ncp->nc_name)
1069                         free(ncp->nc_name, M_VFSCACHE);
1070                 free(ncp, M_VFSCACHE);
1071
1072                 /*
1073                  * Loop on the parent (it may be NULL).  Only bother looping
1074                  * if the parent has a single ref (ours), which also means
1075                  * we can lock it trivially.
1076                  */
1077                 ncp = par;
1078                 if (ncp == NULL)
1079                         return;
1080                 if (ncp->nc_refs != 1) {
1081                         cache_drop(ncp);
1082                         return;
1083                 }
1084                 KKASSERT(par->nc_exlocks == 0);
1085                 cache_lock(ncp);
1086         }
1087 done:
1088         cache_unlock(ncp);
1089         --ncp->nc_refs;
1090 }
1091
1092 static enum { CHI_LOW, CHI_HIGH } cache_hysteresis_state = CHI_LOW;
1093
1094 static __inline
1095 void
1096 cache_hysteresis(void)
1097 {
1098         /*
1099          * Don't cache too many negative hits.  We use hysteresis to reduce
1100          * the impact on the critical path.
1101          */
1102         switch(cache_hysteresis_state) {
1103         case CHI_LOW:
1104                 if (numneg > MINNEG && numneg * ncnegfactor > numcache) {
1105                         cache_cleanneg(10);
1106                         cache_hysteresis_state = CHI_HIGH;
1107                 }
1108                 break;
1109         case CHI_HIGH:
1110                 if (numneg > MINNEG * 9 / 10 && 
1111                     numneg * ncnegfactor * 9 / 10 > numcache
1112                 ) {
1113                         cache_cleanneg(10);
1114                 } else {
1115                         cache_hysteresis_state = CHI_LOW;
1116                 }
1117                 break;
1118         }
1119 }
1120
1121 /*
1122  * NEW NAMECACHE LOOKUP API
1123  *
1124  * Lookup an entry in the cache.  A locked, referenced, non-NULL 
1125  * entry is *always* returned, even if the supplied component is illegal.
1126  * The resulting namecache entry should be returned to the system with
1127  * cache_put() or cache_unlock() + cache_drop().
1128  *
1129  * namecache locks are recursive but care must be taken to avoid lock order
1130  * reversals.
1131  *
1132  * Nobody else will be able to manipulate the associated namespace (e.g.
1133  * create, delete, rename, rename-target) until the caller unlocks the
1134  * entry.
1135  *
1136  * The returned entry will be in one of three states:  positive hit (non-null
1137  * vnode), negative hit (null vnode), or unresolved (NCF_UNRESOLVED is set).
1138  * Unresolved entries must be resolved through the filesystem to associate the
1139  * vnode and/or determine whether a positive or negative hit has occured.
1140  *
1141  * It is not necessary to lock a directory in order to lock namespace under
1142  * that directory.  In fact, it is explicitly not allowed to do that.  A
1143  * directory is typically only locked when being created, renamed, or
1144  * destroyed.
1145  *
1146  * The directory (par) may be unresolved, in which case any returned child
1147  * will likely also be marked unresolved.  Likely but not guarenteed.  Since
1148  * the filesystem lookup requires a resolved directory vnode the caller is
1149  * responsible for resolving the namecache chain top-down.  This API 
1150  * specifically allows whole chains to be created in an unresolved state.
1151  */
1152 struct namecache *
1153 cache_nlookup(struct namecache *par, struct nlcomponent *nlc)
1154 {
1155         struct namecache *ncp;
1156         struct namecache *new_ncp;
1157         struct nchashhead *nchpp;
1158         u_int32_t hash;
1159         globaldata_t gd;
1160
1161         numcalls++;
1162         gd = mycpu;
1163
1164         /*
1165          * Try to locate an existing entry
1166          */
1167         hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
1168         hash = fnv_32_buf(&par, sizeof(par), hash);
1169         new_ncp = NULL;
1170 restart:
1171         LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1172                 numchecks++;
1173
1174                 /*
1175                  * Zap entries that have timed out.
1176                  */
1177                 if (ncp->nc_timeout && 
1178                     (int)(ncp->nc_timeout - ticks) < 0 &&
1179                     (ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
1180                     ncp->nc_exlocks == 0
1181                 ) {
1182                         cache_zap(cache_get(ncp));
1183                         goto restart;
1184                 }
1185
1186                 /*
1187                  * Break out if we find a matching entry.  Note that
1188                  * UNRESOLVED entries may match.
1189                  */
1190                 if (ncp->nc_parent == par &&
1191                     ncp->nc_nlen == nlc->nlc_namelen &&
1192                     bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0
1193                 ) {
1194                         if (cache_get_nonblock(ncp) == 0) {
1195                                 if (new_ncp)
1196                                         cache_free(new_ncp);
1197                                 goto found;
1198                         }
1199                         cache_get(ncp);
1200                         cache_put(ncp);
1201                         goto restart;
1202                 }
1203         }
1204
1205         /*
1206          * We failed to locate an entry, create a new entry and add it to
1207          * the cache.  We have to relookup after possibly blocking in
1208          * malloc.
1209          */
1210         if (new_ncp == NULL) {
1211                 new_ncp = cache_alloc(nlc->nlc_namelen);
1212                 goto restart;
1213         }
1214
1215         ncp = new_ncp;
1216
1217         /*
1218          * Initialize as a new UNRESOLVED entry, lock (non-blocking),
1219          * and link to the parent.  The mount point is usually inherited
1220          * from the parent unless this is a special case such as a mount
1221          * point where nlc_namelen is 0.  The caller is responsible for
1222          * setting nc_mount in that case.  If nlc_namelen is 0 nc_name will
1223          * be NULL.
1224          */
1225         if (nlc->nlc_namelen) {
1226                 bcopy(nlc->nlc_nameptr, ncp->nc_name, nlc->nlc_namelen);
1227                 ncp->nc_name[nlc->nlc_namelen] = 0;
1228                 ncp->nc_mount = par->nc_mount;
1229         }
1230         nchpp = NCHHASH(hash);
1231         LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
1232         ncp->nc_flag |= NCF_HASHED;
1233         cache_link_parent(ncp, par);
1234 found:
1235         /*
1236          * stats and namecache size management
1237          */
1238         if (ncp->nc_flag & NCF_UNRESOLVED)
1239                 ++gd->gd_nchstats->ncs_miss;
1240         else if (ncp->nc_vp)
1241                 ++gd->gd_nchstats->ncs_goodhits;
1242         else
1243                 ++gd->gd_nchstats->ncs_neghits;
1244         cache_hysteresis();
1245         return(ncp);
1246 }
1247
1248 /*
1249  * Resolve an unresolved namecache entry, generally by looking it up.
1250  * The passed ncp must be locked and refd. 
1251  *
1252  * Theoretically since a vnode cannot be recycled while held, and since
1253  * the nc_parent chain holds its vnode as long as children exist, the
1254  * direct parent of the cache entry we are trying to resolve should
1255  * have a valid vnode.  If not then generate an error that we can 
1256  * determine is related to a resolver bug.
1257  *
1258  * Note that successful resolution does not necessarily return an error
1259  * code of 0.  If the ncp resolves to a negative cache hit then ENOENT
1260  * will be returned.
1261  */
1262 int
1263 cache_resolve(struct namecache *ncp, struct ucred *cred)
1264 {
1265         struct namecache *par;
1266         int error;
1267
1268 restart:
1269         /*
1270          * If the ncp is already resolved we have nothing to do.
1271          */
1272         if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
1273                 return (ncp->nc_error);
1274
1275         /*
1276          * Mount points need special handling because the parent does not
1277          * belong to the same filesystem as the ncp.
1278          */
1279         if (ncp->nc_flag & NCF_MOUNTPT)
1280                 return (cache_resolve_mp(ncp));
1281
1282         /*
1283          * We expect an unbroken chain of ncps to at least the mount point,
1284          * and even all the way to root (but this code doesn't have to go
1285          * past the mount point).
1286          */
1287         if (ncp->nc_parent == NULL) {
1288                 printf("EXDEV case 1 %p %*.*s\n", ncp,
1289                         ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
1290                 ncp->nc_error = EXDEV;
1291                 return(ncp->nc_error);
1292         }
1293
1294         /*
1295          * The vp's of the parent directories in the chain are held via vhold()
1296          * due to the existance of the child, and should not disappear. 
1297          * However, there are cases where they can disappear:
1298          *
1299          *      - due to filesystem I/O errors.
1300          *      - due to NFS being stupid about tracking the namespace and
1301          *        destroys the namespace for entire directories quite often.
1302          *      - due to forced unmounts.
1303          *
1304          * When this occurs we have to track the chain backwards and resolve
1305          * it, looping until the resolver catches up to the current node.  We
1306          * could recurse here but we might run ourselves out of kernel stack
1307          * so we do it in a more painful manner.  This situation really should
1308          * not occur all that often, or if it does not have to go back too
1309          * many nodes to resolve the ncp.
1310          */
1311         while (ncp->nc_parent->nc_vp == NULL) {
1312                 par = ncp->nc_parent;
1313                 while (par->nc_parent && par->nc_parent->nc_vp == NULL)
1314                         par = par->nc_parent;
1315                 if (par->nc_parent == NULL) {
1316                         printf("EXDEV case 2 %*.*s\n",
1317                                 par->nc_nlen, par->nc_nlen, par->nc_name);
1318                         return (EXDEV);
1319                 }
1320                 printf("[diagnostic] cache_resolve: had to recurse on %*.*s\n",
1321                         par->nc_nlen, par->nc_nlen, par->nc_name);
1322                 /*
1323                  * The parent is not set in stone, ref and lock it to prevent
1324                  * it from disappearing.  Also note that due to renames it
1325                  * is possible for our ncp to move and for par to no longer
1326                  * be one of its parents.  We resolve it anyway, the loop 
1327                  * will handle any moves.
1328                  */
1329                 cache_get(par);
1330                 if (par->nc_flag & NCF_MOUNTPT) {
1331                         cache_resolve_mp(par);
1332                 } else if (par->nc_parent->nc_vp == NULL) {
1333                         printf("[diagnostic] cache_resolve: raced on %*.*s\n", par->nc_nlen, par->nc_nlen, par->nc_name);
1334                         cache_put(par);
1335                         continue;
1336                 } else if (par->nc_flag & NCF_UNRESOLVED) {
1337                         par->nc_error = VOP_NRESOLVE(par, cred);
1338                 }
1339                 if ((error = par->nc_error) != 0) {
1340                         if (par->nc_error != EAGAIN) {
1341                                 printf("EXDEV case 3 %*.*s error %d\n",
1342                                     par->nc_nlen, par->nc_nlen, par->nc_name,
1343                                     par->nc_error);
1344                                 cache_put(par);
1345                                 return(error);
1346                         }
1347                         printf("[diagnostic] cache_resolve: EAGAIN par %p %*.*s\n",
1348                                 par, par->nc_nlen, par->nc_nlen, par->nc_name);
1349                 }
1350                 cache_put(par);
1351                 /* loop */
1352         }
1353
1354         /*
1355          * Call VOP_NRESOLVE() to get the vp, then scan for any disconnected
1356          * ncp's and reattach them.  If this occurs the original ncp is marked
1357          * EAGAIN to force a relookup.
1358          *
1359          * NOTE: in order to call VOP_NRESOLVE(), the parent of the passed
1360          * ncp must already be resolved.
1361          */
1362         KKASSERT((ncp->nc_flag & NCF_MOUNTPT) == 0);
1363         ncp->nc_error = VOP_NRESOLVE(ncp, cred);
1364         /*vop_nresolve(ncp->nc_parent->nc_vp->v_ops, ncp, cred);*/
1365         if (ncp->nc_error == EAGAIN) {
1366                 printf("[diagnostic] cache_resolve: EAGAIN ncp %p %*.*s\n",
1367                         ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
1368                 goto restart;
1369         }
1370         return(ncp->nc_error);
1371 }
1372
1373 /*
1374  * Resolve the ncp associated with a mount point.  Such ncp's almost always
1375  * remain resolved and this routine is rarely called.  NFS MPs tends to force
1376  * re-resolution more often due to its mac-truck-smash-the-namecache
1377  * method of tracking namespace changes.
1378  *
1379  * The passed ncp must be locked.
1380  */
1381 static int
1382 cache_resolve_mp(struct namecache *ncp)
1383 {
1384         struct vnode *vp;
1385         struct mount *mp = ncp->nc_mount;
1386
1387         KKASSERT(mp != NULL);
1388         if (ncp->nc_flag & NCF_UNRESOLVED) {
1389                 while (vfs_busy(mp, 0, NULL, curthread))
1390                         ;
1391                 ncp->nc_error = VFS_ROOT(mp, &vp);
1392                 if (ncp->nc_error == 0) {
1393                         cache_setvp(ncp, vp);
1394                         vput(vp);
1395                 } else {
1396                         printf("[diagnostic] cache_resolve_mp: failed to resolve mount %p\n", mp);
1397                         cache_setvp(ncp, NULL);
1398                 }
1399                 vfs_unbusy(mp, curthread);
1400         }
1401         return(ncp->nc_error);
1402 }
1403
1404 void
1405 cache_cleanneg(int count)
1406 {
1407         struct namecache *ncp;
1408
1409         /*
1410          * Automode from the vnlru proc - clean out 10% of the negative cache
1411          * entries.
1412          */
1413         if (count == 0)
1414                 count = numneg / 10 + 1;
1415
1416         /*
1417          * Attempt to clean out the specified number of negative cache
1418          * entries.
1419          */
1420         while (count) {
1421                 ncp = TAILQ_FIRST(&ncneglist);
1422                 if (ncp == NULL) {
1423                         KKASSERT(numneg == 0);
1424                         break;
1425                 }
1426                 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
1427                 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
1428                 if (cache_get_nonblock(ncp) == 0)
1429                         cache_zap(ncp);
1430                 --count;
1431         }
1432 }
1433
1434 /*
1435  * Rehash a ncp.  Rehashing is typically required if the name changes (should
1436  * not generally occur) or the parent link changes.  This function will
1437  * unhash the ncp if the ncp is no longer hashable.
1438  */
1439 static void
1440 cache_rehash(struct namecache *ncp)
1441 {
1442         struct nchashhead *nchpp;
1443         u_int32_t hash;
1444
1445         if (ncp->nc_flag & NCF_HASHED) {
1446                 ncp->nc_flag &= ~NCF_HASHED;
1447                 LIST_REMOVE(ncp, nc_hash);
1448         }
1449         if (ncp->nc_nlen && ncp->nc_parent) {
1450                 hash = fnv_32_buf(ncp->nc_name, ncp->nc_nlen, FNV1_32_INIT);
1451                 hash = fnv_32_buf(&ncp->nc_parent, 
1452                                         sizeof(ncp->nc_parent), hash);
1453                 nchpp = NCHHASH(hash);
1454                 LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
1455                 ncp->nc_flag |= NCF_HASHED;
1456         }
1457 }
1458
1459 /*
1460  * Name cache initialization, from vfsinit() when we are booting
1461  */
1462 void
1463 nchinit(void)
1464 {
1465         int i;
1466         globaldata_t gd;
1467
1468         /* initialise per-cpu namecache effectiveness statistics. */
1469         for (i = 0; i < ncpus; ++i) {
1470                 gd = globaldata_find(i);
1471                 gd->gd_nchstats = &nchstats[i];
1472         }
1473         
1474         TAILQ_INIT(&ncneglist);
1475         nchashtbl = hashinit(desiredvnodes*2, M_VFSCACHE, &nchash);
1476 }
1477
1478 /*
1479  * Called from start_init() to bootstrap the root filesystem.  Returns
1480  * a referenced, unlocked namecache record.
1481  */
1482 struct namecache *
1483 cache_allocroot(struct mount *mp, struct vnode *vp)
1484 {
1485         struct namecache *ncp = cache_alloc(0);
1486
1487         ncp->nc_flag |= NCF_MOUNTPT | NCF_ROOT;
1488         ncp->nc_mount = mp;
1489         cache_setvp(ncp, vp);
1490         return(ncp);
1491 }
1492
1493 /*
1494  * vfs_cache_setroot()
1495  *
1496  *      Create an association between the root of our namecache and
1497  *      the root vnode.  This routine may be called several times during
1498  *      booting.
1499  *
1500  *      If the caller intends to save the returned namecache pointer somewhere
1501  *      it must cache_hold() it.
1502  */
1503 void
1504 vfs_cache_setroot(struct vnode *nvp, struct namecache *ncp)
1505 {
1506         struct vnode *ovp;
1507         struct namecache *oncp;
1508
1509         ovp = rootvnode;
1510         oncp = rootncp;
1511         rootvnode = nvp;
1512         rootncp = ncp;
1513
1514         if (ovp)
1515                 vrele(ovp);
1516         if (oncp)
1517                 cache_drop(oncp);
1518 }
1519
1520 /*
1521  * XXX OLD API COMPAT FUNCTION.  This really messes up the new namecache
1522  * topology and is being removed as quickly as possible.  The new VOP_N*()
1523  * API calls are required to make specific adjustments using the supplied
1524  * ncp pointers rather then just bogusly purging random vnodes.
1525  *
1526  * Invalidate all namecache entries to a particular vnode as well as 
1527  * any direct children of that vnode in the namecache.  This is a 
1528  * 'catch all' purge used by filesystems that do not know any better.
1529  *
1530  * A new vnode v_id is generated.  Note that no vnode will ever have a
1531  * v_id of 0.
1532  *
1533  * Note that the linkage between the vnode and its namecache entries will
1534  * be removed, but the namecache entries themselves might stay put due to
1535  * active references from elsewhere in the system or due to the existance of
1536  * the children.   The namecache topology is left intact even if we do not
1537  * know what the vnode association is.  Such entries will be marked
1538  * NCF_UNRESOLVED.
1539  *
1540  * XXX: Only time and the size of v_id prevents this from failing:
1541  * XXX: In theory we should hunt down all (struct vnode*, v_id)
1542  * XXX: soft references and nuke them, at least on the global
1543  * XXX: v_id wraparound.  The period of resistance can be extended
1544  * XXX: by incrementing each vnodes v_id individually instead of
1545  * XXX: using the global v_id.
1546  */
1547 void
1548 cache_purge(struct vnode *vp)
1549 {
1550         static u_long nextid;
1551
1552         cache_inval_vp(vp, CINV_PARENT | CINV_SELF | CINV_CHILDREN);
1553
1554         /*
1555          * Calculate a new unique id for ".." handling
1556          */
1557         do {
1558                 nextid++;
1559         } while (nextid == vp->v_id || nextid == 0);
1560         vp->v_id = nextid;
1561 }
1562
1563 /*
1564  * Flush all entries referencing a particular filesystem.
1565  *
1566  * Since we need to check it anyway, we will flush all the invalid
1567  * entries at the same time.
1568  */
1569 void
1570 cache_purgevfs(struct mount *mp)
1571 {
1572         struct nchashhead *nchpp;
1573         struct namecache *ncp, *nnp;
1574
1575         /*
1576          * Scan hash tables for applicable entries.
1577          */
1578         for (nchpp = &nchashtbl[nchash]; nchpp >= nchashtbl; nchpp--) {
1579                 ncp = LIST_FIRST(nchpp);
1580                 if (ncp)
1581                         cache_hold(ncp);
1582                 while (ncp) {
1583                         nnp = LIST_NEXT(ncp, nc_hash);
1584                         if (nnp)
1585                                 cache_hold(nnp);
1586                         if (ncp->nc_mount == mp) {
1587                                 cache_lock(ncp);
1588                                 cache_zap(ncp);
1589                         } else {
1590                                 cache_drop(ncp);
1591                         }
1592                         ncp = nnp;
1593                 }
1594         }
1595 }
1596
1597 static int disablecwd;
1598 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0, "");
1599
1600 static u_long numcwdcalls; STATNODE(CTLFLAG_RD, numcwdcalls, &numcwdcalls);
1601 static u_long numcwdfail1; STATNODE(CTLFLAG_RD, numcwdfail1, &numcwdfail1);
1602 static u_long numcwdfail2; STATNODE(CTLFLAG_RD, numcwdfail2, &numcwdfail2);
1603 static u_long numcwdfail3; STATNODE(CTLFLAG_RD, numcwdfail3, &numcwdfail3);
1604 static u_long numcwdfail4; STATNODE(CTLFLAG_RD, numcwdfail4, &numcwdfail4);
1605 static u_long numcwdfound; STATNODE(CTLFLAG_RD, numcwdfound, &numcwdfound);
1606
1607 int
1608 __getcwd(struct __getcwd_args *uap)
1609 {
1610         int buflen;
1611         int error;
1612         char *buf;
1613         char *bp;
1614
1615         if (disablecwd)
1616                 return (ENODEV);
1617
1618         buflen = uap->buflen;
1619         if (buflen < 2)
1620                 return (EINVAL);
1621         if (buflen > MAXPATHLEN)
1622                 buflen = MAXPATHLEN;
1623
1624         buf = malloc(buflen, M_TEMP, M_WAITOK);
1625         bp = kern_getcwd(buf, buflen, &error);
1626         if (error == 0)
1627                 error = copyout(bp, uap->buf, strlen(bp) + 1);
1628         free(buf, M_TEMP);
1629         return (error);
1630 }
1631
1632 char *
1633 kern_getcwd(char *buf, size_t buflen, int *error)
1634 {
1635         struct proc *p = curproc;
1636         char *bp;
1637         int i, slash_prefixed;
1638         struct filedesc *fdp;
1639         struct namecache *ncp;
1640
1641         numcwdcalls++;
1642         bp = buf;
1643         bp += buflen - 1;
1644         *bp = '\0';
1645         fdp = p->p_fd;
1646         slash_prefixed = 0;
1647
1648         ncp = fdp->fd_ncdir;
1649         while (ncp && ncp != fdp->fd_nrdir && (ncp->nc_flag & NCF_ROOT) == 0) {
1650                 if (ncp->nc_flag & NCF_MOUNTPT) {
1651                         if (ncp->nc_mount == NULL) {
1652                                 *error = EBADF;         /* forced unmount? */
1653                                 return(NULL);
1654                         }
1655                         ncp = ncp->nc_parent;
1656                         continue;
1657                 }
1658                 for (i = ncp->nc_nlen - 1; i >= 0; i--) {
1659                         if (bp == buf) {
1660                                 numcwdfail4++;
1661                                 *error = ENOMEM;
1662                                 return(NULL);
1663                         }
1664                         *--bp = ncp->nc_name[i];
1665                 }
1666                 if (bp == buf) {
1667                         numcwdfail4++;
1668                         *error = ENOMEM;
1669                         return(NULL);
1670                 }
1671                 *--bp = '/';
1672                 slash_prefixed = 1;
1673                 ncp = ncp->nc_parent;
1674         }
1675         if (ncp == NULL) {
1676                 numcwdfail2++;
1677                 *error = ENOENT;
1678                 return(NULL);
1679         }
1680         if (!slash_prefixed) {
1681                 if (bp == buf) {
1682                         numcwdfail4++;
1683                         *error = ENOMEM;
1684                         return(NULL);
1685                 }
1686                 *--bp = '/';
1687         }
1688         numcwdfound++;
1689         *error = 0;
1690         return (bp);
1691 }
1692
1693 /*
1694  * Thus begins the fullpath magic.
1695  */
1696
1697 #undef STATNODE
1698 #define STATNODE(name)                                                  \
1699         static u_int name;                                              \
1700         SYSCTL_UINT(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, "")
1701
1702 static int disablefullpath;
1703 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW,
1704     &disablefullpath, 0, "");
1705
1706 STATNODE(numfullpathcalls);
1707 STATNODE(numfullpathfail1);
1708 STATNODE(numfullpathfail2);
1709 STATNODE(numfullpathfail3);
1710 STATNODE(numfullpathfail4);
1711 STATNODE(numfullpathfound);
1712
1713 int
1714 vn_fullpath(struct proc *p, struct vnode *vn, char **retbuf, char **freebuf) 
1715 {
1716         char *bp, *buf;
1717         int i, slash_prefixed;
1718         struct filedesc *fdp;
1719         struct namecache *ncp;
1720
1721         numfullpathcalls++;
1722         if (disablefullpath)
1723                 return (ENODEV);
1724
1725         if (p == NULL)
1726                 return (EINVAL);
1727
1728         /* vn is NULL, client wants us to use p->p_textvp */
1729         if (vn == NULL) {
1730                 if ((vn = p->p_textvp) == NULL)
1731                         return (EINVAL);
1732         }
1733         TAILQ_FOREACH(ncp, &vn->v_namecache, nc_vnode) {
1734                 if (ncp->nc_nlen)
1735                         break;
1736         }
1737         if (ncp == NULL)
1738                 return (EINVAL);
1739
1740         buf = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1741         bp = buf + MAXPATHLEN - 1;
1742         *bp = '\0';
1743         fdp = p->p_fd;
1744         slash_prefixed = 0;
1745         while (ncp && ncp != fdp->fd_nrdir && (ncp->nc_flag & NCF_ROOT) == 0) {
1746                 if (ncp->nc_flag & NCF_MOUNTPT) {
1747                         if (ncp->nc_mount == NULL) {
1748                                 free(buf, M_TEMP);
1749                                 return(EBADF);
1750                         }
1751                         ncp = ncp->nc_parent;
1752                         continue;
1753                 }
1754                 for (i = ncp->nc_nlen - 1; i >= 0; i--) {
1755                         if (bp == buf) {
1756                                 numfullpathfail4++;
1757                                 free(buf, M_TEMP);
1758                                 return (ENOMEM);
1759                         }
1760                         *--bp = ncp->nc_name[i];
1761                 }
1762                 if (bp == buf) {
1763                         numfullpathfail4++;
1764                         free(buf, M_TEMP);
1765                         return (ENOMEM);
1766                 }
1767                 *--bp = '/';
1768                 slash_prefixed = 1;
1769                 ncp = ncp->nc_parent;
1770         }
1771         if (ncp == NULL) {
1772                 numfullpathfail2++;
1773                 free(buf, M_TEMP);
1774                 return (ENOENT);
1775         }
1776         if (!slash_prefixed) {
1777                 if (bp == buf) {
1778                         numfullpathfail4++;
1779                         free(buf, M_TEMP);
1780                         return (ENOMEM);
1781                 }
1782                 *--bp = '/';
1783         }
1784         numfullpathfound++;
1785         *retbuf = bp; 
1786         *freebuf = buf;
1787         return (0);
1788 }
1789