Merge from vendor branch LIBARCHIVE:
[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.41 2004/10/28 18:56:52 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 <ddb/ddb.h>
89
90 /*
91  * Random lookups in the cache are accomplished with a hash table using
92  * a hash key of (nc_src_vp, name).
93  *
94  * Negative entries may exist and correspond to structures where nc_vp
95  * is NULL.  In a negative entry, NCF_WHITEOUT will be set if the entry
96  * corresponds to a whited-out directory entry (verses simply not finding the
97  * entry at all).
98  *
99  * Upon reaching the last segment of a path, if the reference is for DELETE,
100  * or NOCACHE is set (rewrite), and the name is located in the cache, it
101  * will be dropped.
102  */
103
104 /*
105  * Structures associated with name cacheing.
106  */
107 #define NCHHASH(hash)   (&nchashtbl[(hash) & nchash])
108 #define MINNEG          1024
109
110 MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
111
112 static LIST_HEAD(nchashhead, namecache) *nchashtbl;     /* Hash Table */
113 static struct namecache_list    ncneglist;              /* instead of vnode */
114
115 static u_long   nchash;                 /* size of hash table */
116 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0, "");
117
118 static u_long   ncnegfactor = 16;       /* ratio of negative entries */
119 SYSCTL_ULONG(_debug, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0, "");
120
121 static u_long   numneg;         /* number of cache entries allocated */
122 SYSCTL_ULONG(_debug, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0, "");
123
124 static u_long   numcache;               /* number of cache entries allocated */
125 SYSCTL_ULONG(_debug, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0, "");
126
127 static u_long   numunres;               /* number of unresolved entries */
128 SYSCTL_ULONG(_debug, OID_AUTO, numunres, CTLFLAG_RD, &numunres, 0, "");
129
130 SYSCTL_INT(_debug, OID_AUTO, vnsize, CTLFLAG_RD, 0, sizeof(struct vnode), "");
131 SYSCTL_INT(_debug, OID_AUTO, ncsize, CTLFLAG_RD, 0, sizeof(struct namecache), "");
132
133 static int cache_resolve_mp(struct namecache *ncp);
134 static void cache_rehash(struct namecache *ncp);
135
136 /*
137  * The new name cache statistics
138  */
139 SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0, "Name cache statistics");
140 #define STATNODE(mode, name, var) \
141         SYSCTL_ULONG(_vfs_cache, OID_AUTO, name, mode, var, 0, "");
142 STATNODE(CTLFLAG_RD, numneg, &numneg);
143 STATNODE(CTLFLAG_RD, numcache, &numcache);
144 static u_long numcalls; STATNODE(CTLFLAG_RD, numcalls, &numcalls);
145 static u_long dothits; STATNODE(CTLFLAG_RD, dothits, &dothits);
146 static u_long dotdothits; STATNODE(CTLFLAG_RD, dotdothits, &dotdothits);
147 static u_long numchecks; STATNODE(CTLFLAG_RD, numchecks, &numchecks);
148 static u_long nummiss; STATNODE(CTLFLAG_RD, nummiss, &nummiss);
149 static u_long nummisszap; STATNODE(CTLFLAG_RD, nummisszap, &nummisszap);
150 static u_long numposzaps; STATNODE(CTLFLAG_RD, numposzaps, &numposzaps);
151 static u_long numposhits; STATNODE(CTLFLAG_RD, numposhits, &numposhits);
152 static u_long numnegzaps; STATNODE(CTLFLAG_RD, numnegzaps, &numnegzaps);
153 static u_long numneghits; STATNODE(CTLFLAG_RD, numneghits, &numneghits);
154
155 struct nchstats nchstats[SMP_MAXCPU];
156 /*
157  * Export VFS cache effectiveness statistics to user-land.
158  *
159  * The statistics are left for aggregation to user-land so
160  * neat things can be achieved, like observing per-CPU cache
161  * distribution.
162  */
163 static int
164 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
165 {
166         struct globaldata *gd;
167         int i, error;
168
169         error = 0;
170         for (i = 0; i < ncpus; ++i) {
171                 gd = globaldata_find(i);
172                 if ((error = SYSCTL_OUT(req, (void *)&(*gd->gd_nchstats),
173                         sizeof(struct nchstats))))
174                         break;
175         }
176
177         return (error);
178 }
179 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE|CTLFLAG_RD,
180   0, 0, sysctl_nchstats, "S,nchstats", "VFS cache effectiveness statistics");
181
182 static void cache_zap(struct namecache *ncp);
183
184 /*
185  * cache_hold() and cache_drop() prevent the premature deletion of a
186  * namecache entry but do not prevent operations (such as zapping) on
187  * that namecache entry.
188  */
189 static __inline
190 struct namecache *
191 _cache_hold(struct namecache *ncp)
192 {
193         ++ncp->nc_refs;
194         return(ncp);
195 }
196
197 /*
198  * When dropping an entry, if only one ref remains and the entry has not
199  * been resolved, zap it.  Since the one reference is being dropped the
200  * entry had better not be locked.
201  */
202 static __inline
203 void
204 _cache_drop(struct namecache *ncp)
205 {
206         KKASSERT(ncp->nc_refs > 0);
207         if (ncp->nc_refs == 1 && 
208             (ncp->nc_flag & NCF_UNRESOLVED) && 
209             TAILQ_EMPTY(&ncp->nc_list)
210         ) {
211                 KKASSERT(ncp->nc_exlocks == 0);
212                 cache_lock(ncp);
213                 cache_zap(ncp);
214         } else {
215                 --ncp->nc_refs;
216         }
217 }
218
219 /*
220  * Link a new namecache entry to its parent.  Be careful to avoid races
221  * if vhold() blocks in the future.
222  *
223  * If we are creating a child under an oldapi parent we must mark the
224  * child as being an oldapi entry as well.
225  */
226 static void
227 cache_link_parent(struct namecache *ncp, struct namecache *par)
228 {
229         KKASSERT(ncp->nc_parent == NULL);
230         ncp->nc_parent = par;
231         if (TAILQ_EMPTY(&par->nc_list)) {
232                 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
233                 /*
234                  * Any vp associated with an ncp which has children must
235                  * be held to prevent it from being recycled.
236                  */
237                 if (par->nc_vp)
238                         vhold(par->nc_vp);
239         } else {
240                 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
241         }
242 }
243
244 /*
245  * Remove the parent association from a namecache structure.  If this is
246  * the last child of the parent the cache_drop(par) will attempt to
247  * recursively zap the parent.
248  */
249 static void
250 cache_unlink_parent(struct namecache *ncp)
251 {
252         struct namecache *par;
253
254         if ((par = ncp->nc_parent) != NULL) {
255                 ncp->nc_parent = NULL;
256                 par = cache_hold(par);
257                 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
258                 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
259                         vdrop(par->nc_vp);
260                 cache_drop(par);
261         }
262 }
263
264 /*
265  * Allocate a new namecache structure.
266  */
267 static struct namecache *
268 cache_alloc(int nlen)
269 {
270         struct namecache *ncp;
271
272         ncp = malloc(sizeof(*ncp), M_VFSCACHE, M_WAITOK|M_ZERO);
273         if (nlen)
274                 ncp->nc_name = malloc(nlen, M_VFSCACHE, M_WAITOK);
275         ncp->nc_nlen = nlen;
276         ncp->nc_flag = NCF_UNRESOLVED;
277         ncp->nc_error = ENOTCONN;       /* needs to be resolved */
278         ncp->nc_refs = 1;
279         TAILQ_INIT(&ncp->nc_list);
280         cache_lock(ncp);
281         return(ncp);
282 }
283
284 static void
285 cache_free(struct namecache *ncp)
286 {
287         KKASSERT(ncp->nc_refs == 1 && ncp->nc_exlocks == 1);
288         if (ncp->nc_name)
289                 free(ncp->nc_name, M_VFSCACHE);
290         free(ncp, M_VFSCACHE);
291 }
292
293 /*
294  * Ref and deref a namecache structure.
295  */
296 struct namecache *
297 cache_hold(struct namecache *ncp)
298 {
299         return(_cache_hold(ncp));
300 }
301
302 void
303 cache_drop(struct namecache *ncp)
304 {
305         _cache_drop(ncp);
306 }
307
308 /*
309  * Namespace locking.  The caller must already hold a reference to the
310  * namecache structure in order to lock/unlock it.  This function prevents
311  * the namespace from being created or destroyed by accessors other then
312  * the lock holder.
313  *
314  * Note that holding a locked namecache structure prevents other threads
315  * from making namespace changes (e.g. deleting or creating), prevents
316  * vnode association state changes by other threads, and prevents the
317  * namecache entry from being resolved or unresolved by other threads.
318  *
319  * The lock owner has full authority to associate/disassociate vnodes
320  * and resolve/unresolve the locked ncp.
321  *
322  * In particular, if a vnode is associated with a locked cache entry
323  * that vnode will *NOT* be recycled.  We accomplish this by vhold()ing the
324  * vnode.  XXX we should find a more efficient way to prevent the vnode
325  * from being recycled, but remember that any given vnode may have multiple
326  * namecache associations (think hardlinks).
327  */
328 void
329 cache_lock(struct namecache *ncp)
330 {
331         thread_t td;
332         int didwarn;
333
334         KKASSERT(ncp->nc_refs != 0);
335         didwarn = 0;
336         td = curthread;
337
338         for (;;) {
339                 if (ncp->nc_exlocks == 0) {
340                         ncp->nc_exlocks = 1;
341                         ncp->nc_locktd = td;
342                         /* 
343                          * The vp associated with a locked ncp must be held
344                          * to prevent it from being recycled (which would
345                          * cause the ncp to become unresolved).
346                          *
347                          * XXX loop on race for later MPSAFE work.
348                          */
349                         if (ncp->nc_vp)
350                                 vhold(ncp->nc_vp);
351                         break;
352                 }
353                 if (ncp->nc_locktd == td) {
354                         ++ncp->nc_exlocks;
355                         break;
356                 }
357                 ncp->nc_flag |= NCF_LOCKREQ;
358                 if (tsleep(ncp, 0, "clock", hz) == EWOULDBLOCK) {
359                         if (didwarn)
360                                 continue;
361                         didwarn = 1;
362                         printf("[diagnostic] cache_lock: blocked on %p", ncp);
363                         if ((ncp->nc_flag & NCF_MOUNTPT) && ncp->nc_mount)
364                             printf(" [MOUNTPT %s]\n", ncp->nc_mount->mnt_stat.f_mntonname);
365                         else
366                             printf(" \"%*.*s\"\n",
367                                 ncp->nc_nlen, ncp->nc_nlen,
368                                 ncp->nc_name);
369                 }
370         }
371
372         if (didwarn == 1) {
373                 printf("[diagnostic] cache_lock: unblocked %*.*s\n",
374                         ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
375         }
376 }
377
378 void
379 cache_unlock(struct namecache *ncp)
380 {
381         thread_t td = curthread;
382
383         KKASSERT(ncp->nc_refs > 0);
384         KKASSERT(ncp->nc_exlocks > 0);
385         KKASSERT(ncp->nc_locktd == td);
386         if (--ncp->nc_exlocks == 0) {
387                 if (ncp->nc_vp)
388                         vdrop(ncp->nc_vp);
389                 ncp->nc_locktd = NULL;
390                 if (ncp->nc_flag & NCF_LOCKREQ) {
391                         ncp->nc_flag &= ~NCF_LOCKREQ;
392                         wakeup_one(ncp);
393                 }
394         }
395 }
396
397 /*
398  * ref-and-lock, unlock-and-deref functions.
399  */
400 struct namecache *
401 cache_get(struct namecache *ncp)
402 {
403         _cache_hold(ncp);
404         cache_lock(ncp);
405         return(ncp);
406 }
407
408 int
409 cache_get_nonblock(struct namecache *ncp)
410 {
411         /* XXX MP */
412         if (ncp->nc_exlocks == 0 || ncp->nc_locktd == curthread) {
413                 _cache_hold(ncp);
414                 cache_lock(ncp);
415                 return(0);
416         }
417         return(EWOULDBLOCK);
418 }
419
420 void
421 cache_put(struct namecache *ncp)
422 {
423         cache_unlock(ncp);
424         _cache_drop(ncp);
425 }
426
427 /*
428  * Resolve an unresolved ncp by associating a vnode with it.  If the
429  * vnode is NULL, a negative cache entry is created.
430  *
431  * The ncp should be locked on entry and will remain locked on return.
432  */
433 void
434 cache_setvp(struct namecache *ncp, struct vnode *vp)
435 {
436         KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
437         ncp->nc_vp = vp;
438         if (vp != NULL) {
439                 /*
440                  * Any vp associated with an ncp which has children must
441                  * be held.  Any vp associated with a locked ncp must be held.
442                  */
443                 if (!TAILQ_EMPTY(&ncp->nc_list))
444                         vhold(vp);
445                 TAILQ_INSERT_HEAD(&vp->v_namecache, ncp, nc_vnode);
446                 if (ncp->nc_exlocks)
447                         vhold(vp);
448
449                 /*
450                  * Set auxillary flags
451                  */
452                 switch(vp->v_type) {
453                 case VDIR:
454                         ncp->nc_flag |= NCF_ISDIR;
455                         break;
456                 case VLNK:
457                         ncp->nc_flag |= NCF_ISSYMLINK;
458                         /* XXX cache the contents of the symlink */
459                         break;
460                 default:
461                         break;
462                 }
463                 ++numcache;
464                 ncp->nc_error = 0;
465         } else {
466                 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
467                 ++numneg;
468                 ncp->nc_error = ENOENT;
469         }
470         ncp->nc_flag &= ~NCF_UNRESOLVED;
471 }
472
473 /*
474  * Disassociate the vnode or negative-cache association and mark a
475  * namecache entry as unresolved again.  Note that the ncp is still
476  * left in the hash table and still linked to its parent.
477  *
478  * The ncp should be locked and refd on entry and will remain locked and refd
479  * on return.
480  *
481  * This routine is normally never called on a directory containing children.
482  * However, NFS often does just that in its rename() code as a cop-out to
483  * avoid complex namespace operations.  This disconnects a directory vnode
484  * from its namecache and can cause the OLDAPI and NEWAPI to get out of
485  * sync.
486  */
487 void
488 cache_setunresolved(struct namecache *ncp)
489 {
490         struct vnode *vp;
491
492         if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
493                 ncp->nc_flag |= NCF_UNRESOLVED;
494                 ncp->nc_flag &= ~(NCF_WHITEOUT|NCF_ISDIR|NCF_ISSYMLINK);
495                 ncp->nc_error = ENOTCONN;
496                 ++numunres;
497                 if ((vp = ncp->nc_vp) != NULL) {
498                         --numcache;
499                         ncp->nc_vp = NULL;      /* safety */
500                         TAILQ_REMOVE(&vp->v_namecache, ncp, nc_vnode);
501
502                         /*
503                          * Any vp associated with an ncp with children is
504                          * held by that ncp.  Any vp associated with a locked
505                          * ncp is held by that ncp.  These conditions must be
506                          * undone when the vp is cleared out from the ncp.
507                          */
508                         if (!TAILQ_EMPTY(&ncp->nc_list))
509                                 vdrop(vp);
510                         if (ncp->nc_exlocks)
511                                 vdrop(vp);
512                 } else {
513                         TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
514                         --numneg;
515                 }
516
517 #if 0
518                 if (TAILQ_FIRST(&ncp->nc_list)) {
519                         db_print_backtrace();
520                         printf("[diagnostic] cache_setunresolved() called on directory with children: %p %*.*s\n", ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
521                 }
522 #endif
523         }
524 }
525
526 /*
527  * Invalidate portions of a namecache entry.  The passed ncp should be
528  * referenced and locked but we might not adhere to that rule during the
529  * old api -> new api transition period.
530  *
531  * CINV_PARENT          - disconnect the ncp from its parent
532  * CINV_SELF            - same as cache_setunresolved(ncp)
533  * CINV_CHILDREN        - disconnect children of the ncp from the ncp
534  */
535 void
536 cache_inval(struct namecache *ncp, int flags)
537 {
538         struct namecache *kid;
539         struct namecache *nextkid;
540
541         if (flags & CINV_SELF)
542                 cache_setunresolved(ncp);
543         if (flags & CINV_PARENT) {
544                 ncp->nc_flag |= NCF_REVALPARENT;
545                 cache_unlink_parent(ncp);
546         }
547
548         /*
549          * TEMPORARY XX old-api / rename handling.  Any unresolved or
550          * negative cache-hit children with a ref count of 0 must be
551          * recursively destroyed or this disconnection from our parent,
552          * or the childrens disconnection from us, may leave them dangling
553          * forever.
554          *
555          * In the new API it won't be possible to unlink in the middle of
556          * the topology and we will have a cache_rename() to physically
557          * move a subtree from one place to another.
558          */
559         if (flags & (CINV_PARENT|CINV_CHILDREN)) {
560                 if ((kid = TAILQ_FIRST(&ncp->nc_list)) != NULL)
561                         cache_hold(kid);
562                 while (kid) {
563                         if ((nextkid = TAILQ_NEXT(kid, nc_entry)) != NULL)
564                                 cache_hold(nextkid);
565                         if (kid->nc_refs == 0 &&
566                             ((kid->nc_flag & NCF_UNRESOLVED) || 
567                              kid->nc_vp == NULL)
568                         ) {
569                                 cache_inval(kid, CINV_PARENT);
570                         }
571                         cache_drop(kid);
572                         kid = nextkid;
573                 }
574         }
575
576         /*
577          * TEMPORARY XXX old-api / rename handling.
578          */
579         if (flags & CINV_CHILDREN) {
580                 while ((kid = TAILQ_FIRST(&ncp->nc_list)) != NULL) {
581                         kid->nc_flag |= NCF_REVALPARENT;
582                         cache_hold(kid);
583                         cache_unlink_parent(kid);
584                         cache_drop(kid);
585                 }
586         }
587 }
588
589 void
590 cache_inval_vp(struct vnode *vp, int flags)
591 {
592         struct namecache *ncp;
593
594         if (flags & CINV_SELF) {
595                 while ((ncp = TAILQ_FIRST(&vp->v_namecache)) != NULL) {
596                         cache_hold(ncp);
597                         KKASSERT((ncp->nc_flag & NCF_UNRESOLVED) == 0);
598                         cache_inval(ncp, flags);
599                         cache_drop(ncp);
600                 }
601         } else {
602                 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
603                         cache_hold(ncp);
604                         cache_inval(ncp, flags);
605                         cache_drop(ncp);
606                 }
607         }
608 }
609
610 /*
611  * vget the vnode associated with the namecache entry.  Resolve the namecache
612  * entry if necessary and deal with namecache/vp races.  The passed ncp must
613  * be referenced and may be locked.  The ncp's ref/locking state is not 
614  * effected by this call.
615  *
616  * lk_type may be LK_SHARED, LK_EXCLUSIVE.  A ref'd, possibly locked
617  * (depending on the passed lk_type) will be returned in *vpp with an error
618  * of 0, or NULL will be returned in *vpp with a non-0 error code.  The
619  * most typical error is ENOENT, meaning that the ncp represents a negative
620  * cache hit and there is no vnode to retrieve, but other errors can occur
621  * too.
622  *
623  * The main race we have to deal with are namecache zaps.  The ncp itself
624  * will not disappear since it is referenced, and it turns out that the
625  * validity of the vp pointer can be checked simply by rechecking the
626  * contents of ncp->nc_vp.
627  */
628 int
629 cache_vget(struct namecache *ncp, struct ucred *cred,
630            int lk_type, struct vnode **vpp)
631 {
632         struct vnode *vp;
633         int error;
634
635 again:
636         vp = NULL;
637         if (ncp->nc_flag & NCF_UNRESOLVED) {
638                 cache_lock(ncp);
639                 error = cache_resolve(ncp, cred);
640                 cache_unlock(ncp);
641         } else {
642                 error = 0;
643         }
644         if (error == 0 && (vp = ncp->nc_vp) != NULL) {
645                 error = vget(vp, lk_type, curthread);
646                 if (error) {
647                         if (vp != ncp->nc_vp)   /* handle cache_zap race */
648                                 goto again;
649                         vp = NULL;
650                 } else if (vp != ncp->nc_vp) {  /* handle cache_zap race */
651                         vput(vp);
652                         goto again;
653                 }
654         }
655         if (error == 0 && vp == NULL)
656                 error = ENOENT;
657         *vpp = vp;
658         return(error);
659 }
660
661 int
662 cache_vref(struct namecache *ncp, struct ucred *cred, struct vnode **vpp)
663 {
664         struct vnode *vp;
665         int error;
666
667 again:
668         vp = NULL;
669         if (ncp->nc_flag & NCF_UNRESOLVED) {
670                 cache_lock(ncp);
671                 error = cache_resolve(ncp, cred);
672                 cache_unlock(ncp);
673         } else {
674                 error = 0;
675         }
676         if (error == 0 && (vp = ncp->nc_vp) != NULL) {
677                 vref(vp);
678                 if (vp != ncp->nc_vp) {         /* handle cache_zap race */
679                         vrele(vp);
680                         goto again;
681                 }
682         }
683         if (error == 0 && vp == NULL)
684                 error = ENOENT;
685         *vpp = vp;
686         return(error);
687 }
688
689 /*
690  * Zap a namecache entry.  The ncp is unconditionally set to an unresolved
691  * state, which disassociates it from its vnode or ncneglist.
692  *
693  * Then, if there are no additional references to the ncp and no children,
694  * the ncp is removed from the topology and destroyed.  This function will
695  * also run through the nc_parent chain and destroy parent ncps if possible.
696  * As a side benefit, it turns out the only conditions that allow running
697  * up the chain are also the conditions to ensure no deadlock will occur.
698  *
699  * References and/or children may exist if the ncp is in the middle of the
700  * topology, preventing the ncp from being destroyed.
701  *
702  * This function must be called with the ncp held and locked and will unlock
703  * and drop it during zapping.
704  */
705 static void
706 cache_zap(struct namecache *ncp)
707 {
708         struct namecache *par;
709
710         /*
711          * Disassociate the vnode or negative cache ref and set NCF_UNRESOLVED.
712          */
713         cache_setunresolved(ncp);
714
715         /*
716          * Try to scrap the entry and possibly tail-recurse on its parent.
717          * We only scrap unref'd (other then our ref) unresolved entries,
718          * we do not scrap 'live' entries.
719          */
720         while (ncp->nc_flag & NCF_UNRESOLVED) {
721                 /*
722                  * Someone other then us has a ref, stop.
723                  */
724                 if (ncp->nc_refs > 1)
725                         goto done;
726
727                 /*
728                  * We have children, stop.
729                  */
730                 if (!TAILQ_EMPTY(&ncp->nc_list))
731                         goto done;
732
733                 /*
734                  * Remove ncp from the topology: hash table and parent linkage.
735                  */
736                 if (ncp->nc_flag & NCF_HASHED) {
737                         ncp->nc_flag &= ~NCF_HASHED;
738                         LIST_REMOVE(ncp, nc_hash);
739                 }
740                 if ((par = ncp->nc_parent) != NULL) {
741                         par = cache_hold(par);
742                         TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
743                         ncp->nc_parent = NULL;
744                         if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
745                                 vdrop(par->nc_vp);
746                 }
747
748                 /*
749                  * ncp should not have picked up any refs.  Physically
750                  * destroy the ncp.
751                  */
752                 KKASSERT(ncp->nc_refs == 1);
753                 --numunres;
754                 /* cache_unlock(ncp) not required */
755                 ncp->nc_refs = -1;      /* safety */
756                 if (ncp->nc_name)
757                         free(ncp->nc_name, M_VFSCACHE);
758                 free(ncp, M_VFSCACHE);
759
760                 /*
761                  * Loop on the parent (it may be NULL).  Only bother looping
762                  * if the parent has a single ref (ours), which also means
763                  * we can lock it trivially.
764                  */
765                 ncp = par;
766                 if (ncp == NULL)
767                         return;
768                 if (ncp->nc_refs != 1) {
769                         cache_drop(ncp);
770                         return;
771                 }
772                 KKASSERT(par->nc_exlocks == 0);
773                 cache_lock(ncp);
774         }
775 done:
776         cache_unlock(ncp);
777         --ncp->nc_refs;
778 }
779
780 static enum { CHI_LOW, CHI_HIGH } cache_hysteresis_state = CHI_LOW;
781
782 static __inline
783 void
784 cache_hysteresis(void)
785 {
786         /*
787          * Don't cache too many negative hits.  We use hysteresis to reduce
788          * the impact on the critical path.
789          */
790         switch(cache_hysteresis_state) {
791         case CHI_LOW:
792                 if (numneg > MINNEG && numneg * ncnegfactor > numcache) {
793                         cache_cleanneg(10);
794                         cache_hysteresis_state = CHI_HIGH;
795                 }
796                 break;
797         case CHI_HIGH:
798                 if (numneg > MINNEG * 9 / 10 && 
799                     numneg * ncnegfactor * 9 / 10 > numcache
800                 ) {
801                         cache_cleanneg(10);
802                 } else {
803                         cache_hysteresis_state = CHI_LOW;
804                 }
805                 break;
806         }
807 }
808
809 /*
810  * NEW NAMECACHE LOOKUP API
811  *
812  * Lookup an entry in the cache.  A locked, referenced, non-NULL 
813  * entry is *always* returned, even if the supplied component is illegal.
814  * The returned namecache entry should be returned to the system with
815  * cache_put() or cache_unlock() + cache_drop().
816  *
817  * namecache locks are recursive but care must be taken to avoid lock order
818  * reversals.
819  *
820  * Nobody else will be able to manipulate the associated namespace (e.g.
821  * create, delete, rename, rename-target) until the caller unlocks the
822  * entry.
823  *
824  * The returned entry will be in one of three states:  positive hit (non-null
825  * vnode), negative hit (null vnode), or unresolved (NCF_UNRESOLVED is set).
826  * Unresolved entries must be resolved through the filesystem to associate the
827  * vnode and/or determine whether a positive or negative hit has occured.
828  *
829  * It is not necessary to lock a directory in order to lock namespace under
830  * that directory.  In fact, it is explicitly not allowed to do that.  A
831  * directory is typically only locked when being created, renamed, or
832  * destroyed.
833  *
834  * The directory (par) may be unresolved, in which case any returned child
835  * will likely also be marked unresolved.  Likely but not guarenteed.  Since
836  * the filesystem VOP_NEWLOOKUP() requires a resolved directory vnode the
837  * caller is responsible for resolving the namecache chain top-down.  This API 
838  * specifically allows whole chains to be created in an unresolved state.
839  */
840 struct namecache *
841 cache_nlookup(struct namecache *par, struct nlcomponent *nlc)
842 {
843         struct namecache *ncp;
844         struct namecache *new_ncp;
845         struct nchashhead *nchpp;
846         u_int32_t hash;
847         globaldata_t gd;
848
849         numcalls++;
850         gd = mycpu;
851
852         /*
853          * Try to locate an existing entry
854          */
855         hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
856         hash = fnv_32_buf(&par, sizeof(par), hash);
857         new_ncp = NULL;
858 restart:
859         LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
860                 numchecks++;
861
862                 /*
863                  * Zap entries that have timed out.
864                  */
865                 if (ncp->nc_timeout && 
866                     (int)(ncp->nc_timeout - ticks) < 0 &&
867                     (ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
868                     ncp->nc_exlocks == 0
869                 ) {
870                         cache_zap(cache_get(ncp));
871                         goto restart;
872                 }
873
874                 /*
875                  * Break out if we find a matching entry.  Note that
876                  * UNRESOLVED entries may match.
877                  */
878                 if (ncp->nc_parent == par &&
879                     ncp->nc_nlen == nlc->nlc_namelen &&
880                     bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0
881                 ) {
882                         if (cache_get_nonblock(ncp) == 0) {
883                                 if (new_ncp)
884                                         cache_free(new_ncp);
885                                 goto found;
886                         }
887                         cache_get(ncp);
888                         cache_put(ncp);
889                         goto restart;
890                 }
891         }
892
893         /*
894          * We failed to locate an entry, create a new entry and add it to
895          * the cache.  We have to relookup after possibly blocking in
896          * malloc.
897          */
898         if (new_ncp == NULL) {
899                 new_ncp = cache_alloc(nlc->nlc_namelen);
900                 goto restart;
901         }
902
903         ncp = new_ncp;
904
905         /*
906          * Initialize as a new UNRESOLVED entry, lock (non-blocking),
907          * and link to the parent.  Only special mount points will have
908          * a namelen of 0.  Those will have their nc_mount assigned through
909          * other means.
910          */
911         if (nlc->nlc_namelen) {
912                 bcopy(nlc->nlc_nameptr, ncp->nc_name, nlc->nlc_namelen);
913                 ncp->nc_mount = par->nc_mount;
914         }
915         nchpp = NCHHASH(hash);
916         LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
917         ncp->nc_flag |= NCF_HASHED;
918         cache_link_parent(ncp, par);
919 found:
920         cache_hysteresis();
921         return(ncp);
922 }
923
924 /*
925  * Resolve an unresolved namecache entry, generally by looking it up.
926  * The passed ncp must be locked and refd. 
927  *
928  * Theoretically since a vnode cannot be recycled while held, and since
929  * the nc_parent chain holds its vnode as long as children exist, the
930  * direct parent of the cache entry we are trying to resolve should
931  * have a valid vnode.  If not then generate an error that we can 
932  * determine is related to a resolver bug.
933  */
934 int
935 cache_resolve(struct namecache *ncp, struct ucred *cred)
936 {
937         struct namecache *par;
938         struct namecache *scan;
939         int error;
940
941 restart:
942         /*
943          * If the ncp is already resolved we have nothing to do.
944          */
945         if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
946                 return (ncp->nc_error);
947
948         /*
949          * Mount points need special handling because the parent does not
950          * belong to the same filesystem as the ncp.
951          */
952         if (ncp->nc_flag & NCF_MOUNTPT)
953                 return (cache_resolve_mp(ncp));
954
955         /*
956          * We expect an unbroken chain of ncps to at least the mount point,
957          * and even all the way to root (but this code doesn't have to go
958          * past the mount point).
959          */
960         if (ncp->nc_parent == NULL) {
961                 printf("EXDEV case 1 %p %*.*s\n", ncp,
962                         ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
963                 ncp->nc_error = EXDEV;
964                 return(ncp->nc_error);
965         }
966
967         /*
968          * The vp's of the parent directories in the chain are held via vhold()
969          * due to the existance of the child, and should not disappear. 
970          * However, there are cases where they can disappear:
971          *
972          *      - due to filesystem I/O errors.
973          *      - due to NFS being stupid about tracking the namespace and
974          *        destroys the namespace for entire directories quite often.
975          *      - due to forced unmounts.
976          *
977          * When this occurs we have to track the chain backwards and resolve
978          * it, looping until the resolver catches up to the current node.  We
979          * could recurse here but we might run ourselves out of kernel stack
980          * so we do it in a more painful manner.  This situation really should
981          * not occur all that often, or if it does not have to go back too
982          * many nodes to resolve the ncp.
983          */
984         while (ncp->nc_parent->nc_vp == NULL) {
985                 par = ncp->nc_parent;
986                 while (par->nc_parent && par->nc_parent->nc_vp == NULL)
987                         par = par->nc_parent;
988                 if (par->nc_parent == NULL) {
989                         printf("EXDEV case 2 %*.*s\n",
990                                 par->nc_nlen, par->nc_nlen, par->nc_name);
991                         return (EXDEV);
992                 }
993                 printf("[diagnostic] cache_resolve: had to recurse on %*.*s\n",
994                         par->nc_nlen, par->nc_nlen, par->nc_name);
995                 /*
996                  * The parent is not set in stone, ref and lock it to prevent
997                  * it from disappearing.  Also note that due to renames it
998                  * is possible for our ncp to move and for par to no longer
999                  * be one of its parents.  We resolve it anyway, the loop 
1000                  * will handle any moves.
1001                  */
1002                 cache_get(par);
1003                 if (par->nc_flag & NCF_MOUNTPT) {
1004                         cache_resolve_mp(par);
1005                 } else if (par->nc_parent->nc_vp == NULL) {
1006                         printf("[diagnostic] cache_resolve: raced on %*.*s\n", par->nc_nlen, par->nc_nlen, par->nc_name);
1007                         cache_put(par);
1008                         continue;
1009                 } else {
1010                         par->nc_error = 
1011                             vop_resolve(par->nc_parent->nc_vp->v_ops, par, cred);
1012                 }
1013                 if ((error = par->nc_error) != 0) {
1014                         if (par->nc_error != EAGAIN) {
1015                                 printf("EXDEV case 3 %*.*s error %d\n",
1016                                     par->nc_nlen, par->nc_nlen, par->nc_name,
1017                                     par->nc_error);
1018                                 cache_put(par);
1019                                 return(error);
1020                         }
1021                         printf("[diagnostic] cache_resolve: EAGAIN par %p %*.*s\n",
1022                                 par, par->nc_nlen, par->nc_nlen, par->nc_name);
1023                 }
1024                 cache_put(par);
1025                 /* loop */
1026         }
1027
1028         /*
1029          * Call vop_resolve() to get the vp, then scan for any disconnected
1030          * ncp's and reattach them.  If this occurs the original ncp is marked
1031          * EAGAIN to force a relookup.
1032          */
1033         KKASSERT((ncp->nc_flag & NCF_MOUNTPT) == 0);
1034         ncp->nc_error = vop_resolve(ncp->nc_parent->nc_vp->v_ops, ncp, cred);
1035         if (ncp->nc_error == EAGAIN) {
1036                 printf("[diagnostic] cache_resolve: EAGAIN ncp %p %*.*s\n",
1037                         ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
1038                 goto restart;
1039         }
1040         if (ncp->nc_error == 0) {
1041                 TAILQ_FOREACH(scan, &ncp->nc_vp->v_namecache, nc_vnode) {
1042                         if (scan != ncp && (scan->nc_flag & NCF_REVALPARENT)) {
1043                                 cache_hold(scan);
1044                                 cache_link_parent(scan, ncp->nc_parent);
1045                                 cache_unlink_parent(ncp);
1046                                 scan->nc_flag &= ~NCF_REVALPARENT;
1047                                 ncp->nc_error = EAGAIN;
1048                                 if (scan->nc_flag & NCF_HASHED)
1049                                         cache_rehash(scan);
1050                                 printf("[diagnostic] cache_resolve: relinked %*.*s\n", scan->nc_nlen, scan->nc_nlen, scan->nc_name);
1051                                 cache_drop(scan);
1052                                 break;
1053                         }
1054                 }
1055         }
1056         return(ncp->nc_error);
1057 }
1058
1059 /*
1060  * Resolve the ncp associated with a mount point.  Such ncp's almost always
1061  * remain resolved and this routine is rarely called.  NFS MPs tends to force
1062  * re-resolution more often due to its mac-truck-smash-the-namecache
1063  * method of tracking namespace changes.
1064  *
1065  * The passed ncp must be locked.
1066  */
1067 static int
1068 cache_resolve_mp(struct namecache *ncp)
1069 {
1070         struct vnode *vp;
1071         struct mount *mp = ncp->nc_mount;
1072
1073         KKASSERT(mp != NULL);
1074         if (ncp->nc_flag & NCF_UNRESOLVED) {
1075                 while (vfs_busy(mp, 0, NULL, curthread))
1076                         ;
1077                 ncp->nc_error = VFS_ROOT(mp, &vp);
1078                 if (ncp->nc_error == 0) {
1079                         cache_setvp(ncp, vp);
1080                         vput(vp);
1081                 } else {
1082                         printf("[diagnostic] cache_resolve_mp: failed to resolve mount %p\n", mp);
1083                         cache_setvp(ncp, NULL);
1084                 }
1085                 vfs_unbusy(mp, curthread);
1086         }
1087         return(ncp->nc_error);
1088 }
1089
1090 /*
1091  * Lookup an entry in the cache.
1092  *
1093  * XXX OLD API ROUTINE!  WHEN ALL VFSs HAVE BEEN CLEANED UP THIS PROCEDURE
1094  * WILL BE REMOVED.  NOTE: even though this is an old api function it had
1095  * to be modified to vref() the returned vnode (whereas in 4.x an unreferenced
1096  * vnode was returned).  This is necessary because our namecache structure
1097  * manipulation can cause the vnode to be recycled if it isn't refd.
1098  *
1099  * Lookup is called with dvp pointing to the directory to search,
1100  * cnp pointing to the name of the entry being sought. 
1101  *
1102  * If the lookup succeeds, a REFd but unlocked vnode is returned in *vpp,
1103  * and a status of -1 is returned.
1104  *
1105  * If the lookup determines that the name does not exist (negative cacheing),
1106  * a status of ENOENT is returned. 
1107  *
1108  * If the lookup fails, a status of zero is returned.
1109  *
1110  * Matching UNRESOLVED entries are resolved.
1111  *
1112  * HACKS: we create dummy nodes for parents
1113  */
1114 int
1115 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
1116 {
1117         struct namecache *ncp;
1118         struct namecache *par;
1119         struct namecache *bpar;
1120         u_int32_t hash;
1121         globaldata_t gd = mycpu;
1122
1123         numcalls++;
1124         *vpp = NULL;
1125
1126         /*
1127          * Obtain the namecache entry associated with dvp.  If there is no
1128          * entry then assume a miss.
1129          */
1130         if ((par = TAILQ_FIRST(&dvp->v_namecache)) == NULL) {
1131                 if ((cnp->cn_flags & CNP_MAKEENTRY) == 0) {
1132                         nummisszap++;
1133                 } else {
1134                         nummiss++;
1135                 }
1136                 gd->gd_nchstats->ncs_miss++;
1137                 return (0);
1138         }
1139
1140         /*
1141          * Deal with "." and "..".   Note that if the namecache is disjoint,
1142          * we won't find a vnode for ".." and we return a miss.
1143          */
1144         if (cnp->cn_nameptr[0] == '.') {
1145                 if (cnp->cn_namelen == 1) {
1146                         *vpp = dvp;
1147                         vref(*vpp);
1148                         dothits++;
1149                         numposhits++;   /* include in total statistics */
1150                         return (-1);
1151                 }
1152                 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
1153                         if ((cnp->cn_flags & CNP_MAKEENTRY) == 0) {
1154                                 dotdothits++;
1155                                 numposhits++;
1156                                 return (0);
1157                         }
1158                         if (par->nc_parent == NULL ||
1159                             par->nc_parent->nc_vp == NULL) {
1160                                 nummiss++;
1161                                 gd->gd_nchstats->ncs_miss++;
1162                                 return (0);
1163                         }
1164                         *vpp = par->nc_parent->nc_vp;
1165                         vref(*vpp);
1166                         dotdothits++;
1167                         numposhits++;   /* include in total statistics */
1168                         return (-1);
1169                 }
1170         }
1171
1172         /*
1173          * Try to locate an existing entry
1174          */
1175         cache_hold(par);
1176         hash = fnv_32_buf(cnp->cn_nameptr, cnp->cn_namelen, FNV1_32_INIT);
1177         bpar = par;
1178         hash = fnv_32_buf(&bpar, sizeof(bpar), hash);
1179 restart:
1180         LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1181                 numchecks++;
1182
1183                 /*
1184                  * Zap entries that have timed out.  Don't do anything if
1185                  * the entry is in an unresolved state or is held locked.
1186                  */
1187                 if (ncp->nc_timeout && 
1188                     (int)(ncp->nc_timeout - ticks) < 0 &&
1189                     (ncp->nc_flag & NCF_UNRESOLVED) == 0 &&
1190                     ncp->nc_exlocks == 0
1191                 ) {
1192                         cache_zap(cache_get(ncp));
1193                         goto restart;
1194                 }
1195
1196                 /*
1197                  * Break out if we find a matching entry.
1198                  */
1199                 if (ncp->nc_parent == par &&
1200                     ncp->nc_nlen == cnp->cn_namelen &&
1201                     bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen) == 0
1202                 ) {
1203                         if (cache_get_nonblock(ncp) == 0)
1204                                 break;
1205                         cache_get(ncp);
1206                         cache_put(ncp);
1207                         goto restart;
1208                 }
1209         }
1210         cache_drop(par);
1211
1212         /*
1213          * We found an entry but it is unresolved, act the same as if we
1214          * failed to locate the entry.  cache_enter() will do the right
1215          * thing.
1216          */
1217         if (ncp && (ncp->nc_flag & NCF_UNRESOLVED)) {
1218                 cache_put(ncp);
1219                 ncp = NULL;
1220         }
1221
1222         /*
1223          * If we failed to locate an entry, return 0 (indicates failure).
1224          */
1225         if (ncp == NULL) {
1226                 if ((cnp->cn_flags & CNP_MAKEENTRY) == 0) {
1227                         nummisszap++;
1228                 } else {
1229                         nummiss++;
1230                 }
1231                 gd->gd_nchstats->ncs_miss++;
1232                 return (0);
1233         }
1234
1235         /*
1236          * If we found an entry, but we don't want to have one, we just
1237          * return.  The old API tried to zap the entry in the vfs_lookup()
1238          * phase but this is too early to know whether the operation
1239          * will have succeeded or not.  The new API zaps it after the
1240          * operation has succeeded, not here.
1241          *
1242          * At the same time, the old api's rename() function uses the
1243          * old api lookup to clear out any negative cache hit on the
1244          * target name.  We still have to do that.
1245          */
1246         if ((cnp->cn_flags & CNP_MAKEENTRY) == 0) {
1247                 if (cnp->cn_nameiop == NAMEI_RENAME && ncp->nc_vp == NULL)
1248                         cache_zap(ncp);
1249                 else
1250                         cache_put(ncp);
1251                 return (0);
1252         }
1253
1254         /*
1255          * If the vnode is not NULL then return the positive match.
1256          */
1257         if (ncp->nc_vp) {
1258                 numposhits++;
1259                 gd->gd_nchstats->ncs_goodhits++;
1260                 *vpp = ncp->nc_vp;
1261                 vref(*vpp);
1262                 cache_put(ncp);
1263                 return (-1);
1264         }
1265
1266         /*
1267          * If the vnode is NULL we found a negative match.  If we want to
1268          * create it, purge the negative match and return failure (as if
1269          * we hadn't found a match in the first place).
1270          */
1271         if (cnp->cn_nameiop == NAMEI_CREATE) {
1272                 numnegzaps++;
1273                 gd->gd_nchstats->ncs_badhits++;
1274                 cache_zap(ncp);
1275                 return (0);
1276         }
1277
1278         numneghits++;
1279
1280         /*
1281          * We found a "negative" match, ENOENT notifies client of this match.
1282          * The nc_flag field records whether this is a whiteout.  Since there
1283          * is no vnode we can use the vnode tailq link field with ncneglist.
1284          */
1285         TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
1286         TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
1287         gd->gd_nchstats->ncs_neghits++;
1288         if (ncp->nc_flag & NCF_WHITEOUT)
1289                 cnp->cn_flags |= CNP_ISWHITEOUT;
1290         cache_put(ncp);
1291         return (ENOENT);
1292 }
1293
1294 /*
1295  * Add an entry to the cache.  (OLD API)
1296  *
1297  * XXX OLD API ROUTINE!  WHEN ALL VFSs HAVE BEEN CLEANED UP THIS PROCEDURE
1298  * WILL BE REMOVED.
1299  *
1300  * Generally speaking this is 'optional'.  It's ok to do nothing at all.
1301  * The only reason I don't just return is to try to set nc_timeout if
1302  * requested.
1303  */
1304 void
1305 cache_enter(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
1306 {
1307         struct namecache *par;
1308         struct namecache *ncp;
1309         struct namecache *new_ncp;
1310         struct namecache *bpar;
1311         struct nchashhead *nchpp;
1312         u_int32_t hash;
1313
1314         /*
1315          * If the directory has no namecache entry we bail.  This will result
1316          * in a lot of misses but frankly we don't have much of a choice if
1317          * we want to be compatible with the new api's storage scheme.
1318          */
1319         if ((ncp = TAILQ_FIRST(&dvp->v_namecache)) == NULL)
1320                 return;
1321         cache_hold(ncp);
1322
1323         /*
1324          * This may be a bit confusing.  "." and ".." are 'virtual' entries.
1325          * We do not actually create a namecache entry representing either.
1326          * However, the ".." case is used to linkup a potentially disjoint
1327          * directory with its parent, to disconnect a directory from its
1328          * parent, or to change an existing linkage that may no longer be
1329          * correct (as might occur when a subdirectory is renamed).
1330          */
1331
1332         if (cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.') {
1333                 cache_drop(ncp);
1334                 return;
1335         }
1336         if (cnp->cn_namelen == 2 && cnp->cn_nameptr[0] == '.' &&
1337             cnp->cn_nameptr[1] == '.'
1338         ) {
1339                 cache_drop(ncp);
1340                 return;
1341         }
1342
1343         /*
1344          * Ok, no special cases, ncp is actually the parent directory so
1345          * assign it to par.  Note that it is held.
1346          */
1347         par = ncp;
1348
1349         /*
1350          * Try to find a match in the hash table, allocate a new entry if
1351          * we can't.  We have to retry the loop after any potential blocking
1352          * situation.
1353          */
1354         bpar = par;
1355         hash = fnv_32_buf(cnp->cn_nameptr, cnp->cn_namelen, FNV1_32_INIT);
1356         hash = fnv_32_buf(&bpar, sizeof(bpar), hash);
1357
1358         new_ncp = NULL;
1359 againagain:
1360         LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1361                 numchecks++;
1362
1363                 /*
1364                  * Break out if we find a matching entry.  Because cache_enter
1365                  * is called with one or more vnodes potentially locked, we
1366                  * cannot block trying to get the ncp lock (or we might 
1367                  * deadlock).
1368                  */
1369                 if (ncp->nc_parent == par &&
1370                     ncp->nc_nlen == cnp->cn_namelen &&
1371                     bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen) == 0
1372                 ) {
1373                         if (cache_get_nonblock(ncp) != 0) {
1374                                 printf("[diagnostic] cache_enter: avoided race on %p %*.*s\n", ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
1375                                 cache_drop(par);
1376                                 return;
1377                         }
1378                         break;
1379                 }
1380         }
1381         if (ncp == NULL) {
1382                 if (new_ncp == NULL) {
1383                         new_ncp = cache_alloc(cnp->cn_namelen);
1384                         goto againagain;
1385                 }
1386                 ncp = new_ncp;
1387                 bcopy(cnp->cn_nameptr, ncp->nc_name, cnp->cn_namelen);
1388                 nchpp = NCHHASH(hash);
1389                 LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
1390                 ncp->nc_flag |= NCF_HASHED;
1391                 ncp->nc_mount = dvp->v_mount;
1392                 cache_link_parent(ncp, par);
1393         } else if (new_ncp) {
1394                 cache_free(new_ncp);
1395         }
1396         cache_drop(par);
1397
1398         /*
1399          * Avoid side effects if we are simply re-entering the same
1400          * information.
1401          */
1402         if ((ncp->nc_flag & NCF_UNRESOLVED) == 0 && ncp->nc_vp == vp) {
1403                 ncp->nc_error = vp ? 0 : ENOENT;
1404         } else {
1405                 cache_setunresolved(ncp);
1406                 cache_setvp(ncp, vp);
1407         }
1408
1409         /*
1410          * Set a timeout
1411          */
1412         if (cnp->cn_flags & CNP_CACHETIMEOUT) {
1413                 if ((ncp->nc_timeout = ticks + cnp->cn_timeout) == 0)
1414                         ncp->nc_timeout = 1;
1415         }
1416
1417         /*
1418          * If the target vnode is NULL if this is to be a negative cache
1419          * entry.
1420          */
1421         if (vp == NULL) {
1422                 ncp->nc_flag &= ~NCF_WHITEOUT;
1423                 if (cnp->cn_flags & CNP_ISWHITEOUT)
1424                         ncp->nc_flag |= NCF_WHITEOUT;
1425         }
1426         cache_put(ncp);
1427         cache_hysteresis();
1428 }
1429
1430 void
1431 cache_cleanneg(int count)
1432 {
1433         struct namecache *ncp;
1434
1435         /*
1436          * Automode from the vnlru proc - clean out 10% of the negative cache
1437          * entries.
1438          */
1439         if (count == 0)
1440                 count = numneg / 10 + 1;
1441
1442         /*
1443          * Attempt to clean out the specified number of negative cache
1444          * entries.
1445          */
1446         while (count) {
1447                 ncp = TAILQ_FIRST(&ncneglist);
1448                 if (ncp == NULL) {
1449                         KKASSERT(numneg == 0);
1450                         break;
1451                 }
1452                 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
1453                 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
1454                 if (cache_get_nonblock(ncp) == 0)
1455                         cache_zap(ncp);
1456                 --count;
1457         }
1458 }
1459
1460 static void
1461 cache_rehash(struct namecache *ncp)
1462 {
1463         struct nchashhead *nchpp;
1464         u_int32_t hash;
1465
1466         if (ncp->nc_flag & NCF_HASHED) {
1467                 ncp->nc_flag &= ~NCF_HASHED;
1468                 LIST_REMOVE(ncp, nc_hash);
1469         }
1470         hash = fnv_32_buf(ncp->nc_name, ncp->nc_nlen, FNV1_32_INIT);
1471         hash = fnv_32_buf(&ncp->nc_parent, sizeof(ncp->nc_parent), hash);
1472         nchpp = NCHHASH(hash);
1473         LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
1474         ncp->nc_flag |= NCF_HASHED;
1475 }
1476
1477
1478 /*
1479  * Name cache initialization, from vfsinit() when we are booting
1480  */
1481 void
1482 nchinit(void)
1483 {
1484         int i;
1485         globaldata_t gd;
1486
1487         /* initialise per-cpu namecache effectiveness statistics. */
1488         for (i = 0; i < ncpus; ++i) {
1489                 gd = globaldata_find(i);
1490                 gd->gd_nchstats = &nchstats[i];
1491         }
1492         
1493         TAILQ_INIT(&ncneglist);
1494         nchashtbl = hashinit(desiredvnodes*2, M_VFSCACHE, &nchash);
1495 }
1496
1497 /*
1498  * Called from start_init() to bootstrap the root filesystem.  Returns
1499  * a referenced, unlocked namecache record.
1500  */
1501 struct namecache *
1502 cache_allocroot(struct mount *mp, struct vnode *vp)
1503 {
1504         struct namecache *ncp = cache_alloc(0);
1505
1506         ncp->nc_flag |= NCF_MOUNTPT | NCF_ROOT;
1507         ncp->nc_mount = mp;
1508         cache_setvp(ncp, vp);
1509         return(ncp);
1510 }
1511
1512 /*
1513  * vfs_cache_setroot()
1514  *
1515  *      Create an association between the root of our namecache and
1516  *      the root vnode.  This routine may be called several times during
1517  *      booting.
1518  *
1519  *      If the caller intends to save the returned namecache pointer somewhere
1520  *      it must cache_hold() it.
1521  */
1522 void
1523 vfs_cache_setroot(struct vnode *nvp, struct namecache *ncp)
1524 {
1525         struct vnode *ovp;
1526         struct namecache *oncp;
1527
1528         ovp = rootvnode;
1529         oncp = rootncp;
1530         rootvnode = nvp;
1531         rootncp = ncp;
1532
1533         if (ovp)
1534                 vrele(ovp);
1535         if (oncp)
1536                 cache_drop(oncp);
1537 }
1538
1539 /*
1540  * Invalidate all namecache entries to a particular vnode as well as 
1541  * any direct children of that vnode in the namecache.  This is a 
1542  * 'catch all' purge used by filesystems that do not know any better.
1543  *
1544  * A new vnode v_id is generated.  Note that no vnode will ever have a
1545  * v_id of 0.
1546  *
1547  * Note that the linkage between the vnode and its namecache entries will
1548  * be removed, but the namecache entries themselves might stay put due to
1549  * active references from elsewhere in the system or due to the existance of
1550  * the children.   The namecache topology is left intact even if we do not
1551  * know what the vnode association is.  Such entries will be marked
1552  * NCF_UNRESOLVED.
1553  *
1554  * XXX: Only time and the size of v_id prevents this from failing:
1555  * XXX: In theory we should hunt down all (struct vnode*, v_id)
1556  * XXX: soft references and nuke them, at least on the global
1557  * XXX: v_id wraparound.  The period of resistance can be extended
1558  * XXX: by incrementing each vnodes v_id individually instead of
1559  * XXX: using the global v_id.
1560  */
1561 void
1562 cache_purge(struct vnode *vp)
1563 {
1564         static u_long nextid;
1565
1566         cache_inval_vp(vp, CINV_PARENT | CINV_SELF | CINV_CHILDREN);
1567
1568         /*
1569          * Calculate a new unique id for ".." handling
1570          */
1571         do {
1572                 nextid++;
1573         } while (nextid == vp->v_id || nextid == 0);
1574         vp->v_id = nextid;
1575 }
1576
1577 /*
1578  * Flush all entries referencing a particular filesystem.
1579  *
1580  * Since we need to check it anyway, we will flush all the invalid
1581  * entries at the same time.
1582  */
1583 void
1584 cache_purgevfs(struct mount *mp)
1585 {
1586         struct nchashhead *nchpp;
1587         struct namecache *ncp, *nnp;
1588
1589         /*
1590          * Scan hash tables for applicable entries.
1591          */
1592         for (nchpp = &nchashtbl[nchash]; nchpp >= nchashtbl; nchpp--) {
1593                 ncp = LIST_FIRST(nchpp);
1594                 if (ncp)
1595                         cache_hold(ncp);
1596                 while (ncp) {
1597                         nnp = LIST_NEXT(ncp, nc_hash);
1598                         if (nnp)
1599                                 cache_hold(nnp);
1600                         if (ncp->nc_mount == mp) {
1601                                 cache_lock(ncp);
1602                                 cache_zap(ncp);
1603                         } else {
1604                                 cache_drop(ncp);
1605                         }
1606                         ncp = nnp;
1607                 }
1608         }
1609 }
1610
1611 /*
1612  * Perform canonical checks and cache lookup and pass on to filesystem
1613  * through the vop_cachedlookup only if needed.
1614  *
1615  * vop_lookup_args {
1616  *      struct vnode a_dvp;
1617  *      struct vnode **a_vpp;
1618  *      struct componentname *a_cnp;
1619  * }
1620  */
1621 int
1622 vfs_cache_lookup(struct vop_lookup_args *ap)
1623 {
1624         struct vnode *dvp, *vp;
1625         int lockparent;
1626         int error;
1627         struct vnode **vpp = ap->a_vpp;
1628         struct componentname *cnp = ap->a_cnp;
1629         struct ucred *cred = cnp->cn_cred;
1630         int flags = cnp->cn_flags;
1631         struct thread *td = cnp->cn_td;
1632         u_long vpid;    /* capability number of vnode */
1633
1634         *vpp = NULL;
1635         dvp = ap->a_dvp;
1636         lockparent = flags & CNP_LOCKPARENT;
1637
1638         if (dvp->v_type != VDIR)
1639                 return (ENOTDIR);
1640
1641         if ((flags & CNP_ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
1642             (cnp->cn_nameiop == NAMEI_DELETE || cnp->cn_nameiop == NAMEI_RENAME)) {
1643                 return (EROFS);
1644         }
1645
1646         error = VOP_ACCESS(dvp, VEXEC, cred, td);
1647
1648         if (error)
1649                 return (error);
1650
1651         error = cache_lookup(dvp, vpp, cnp);
1652
1653         /*
1654          * failure if error == 0, do a physical lookup
1655          */
1656         if (!error) 
1657                 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
1658
1659         if (error == ENOENT)
1660                 return (error);
1661
1662         vp = *vpp;
1663         vpid = vp->v_id;
1664         cnp->cn_flags &= ~CNP_PDIRUNLOCK;
1665         if (dvp == vp) {   /* lookup on "." */
1666                 /* already ref'd from cache_lookup() */
1667                 error = 0;
1668         } else if (flags & CNP_ISDOTDOT) {
1669                 VOP_UNLOCK(dvp, 0, td);
1670                 cnp->cn_flags |= CNP_PDIRUNLOCK;
1671                 error = vget(vp, LK_EXCLUSIVE, td);
1672                 vrele(vp);
1673                 if (!error && lockparent && (flags & CNP_ISLASTCN)) {
1674                         if ((error = vn_lock(dvp, LK_EXCLUSIVE, td)) == 0)
1675                                 cnp->cn_flags &= ~CNP_PDIRUNLOCK;
1676                 }
1677         } else {
1678                 error = vget(vp, LK_EXCLUSIVE, td);
1679                 vrele(vp);
1680                 if (!lockparent || error || !(flags & CNP_ISLASTCN)) {
1681                         VOP_UNLOCK(dvp, 0, td);
1682                         cnp->cn_flags |= CNP_PDIRUNLOCK;
1683                 }
1684         }
1685         /*
1686          * Check that the capability number did not change
1687          * while we were waiting for the lock.
1688          */
1689         if (!error) {
1690                 if (vpid == vp->v_id)
1691                         return (0);
1692                 vput(vp);
1693                 if (lockparent && dvp != vp && (flags & CNP_ISLASTCN)) {
1694                         VOP_UNLOCK(dvp, 0, td);
1695                         cnp->cn_flags |= CNP_PDIRUNLOCK;
1696                 }
1697         }
1698         if (cnp->cn_flags & CNP_PDIRUNLOCK) {
1699                 error = vn_lock(dvp, LK_EXCLUSIVE, td);
1700                 if (error)
1701                         return (error);
1702                 cnp->cn_flags &= ~CNP_PDIRUNLOCK;
1703         }
1704         return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
1705 }
1706
1707 static int disablecwd;
1708 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0, "");
1709
1710 static u_long numcwdcalls; STATNODE(CTLFLAG_RD, numcwdcalls, &numcwdcalls);
1711 static u_long numcwdfail1; STATNODE(CTLFLAG_RD, numcwdfail1, &numcwdfail1);
1712 static u_long numcwdfail2; STATNODE(CTLFLAG_RD, numcwdfail2, &numcwdfail2);
1713 static u_long numcwdfail3; STATNODE(CTLFLAG_RD, numcwdfail3, &numcwdfail3);
1714 static u_long numcwdfail4; STATNODE(CTLFLAG_RD, numcwdfail4, &numcwdfail4);
1715 static u_long numcwdfound; STATNODE(CTLFLAG_RD, numcwdfound, &numcwdfound);
1716
1717 int
1718 __getcwd(struct __getcwd_args *uap)
1719 {
1720         int buflen;
1721         int error;
1722         char *buf;
1723         char *bp;
1724
1725         if (disablecwd)
1726                 return (ENODEV);
1727
1728         buflen = uap->buflen;
1729         if (buflen < 2)
1730                 return (EINVAL);
1731         if (buflen > MAXPATHLEN)
1732                 buflen = MAXPATHLEN;
1733
1734         buf = malloc(buflen, M_TEMP, M_WAITOK);
1735         bp = kern_getcwd(buf, buflen, &error);
1736         if (error == 0)
1737                 error = copyout(bp, uap->buf, strlen(bp) + 1);
1738         free(buf, M_TEMP);
1739         return (error);
1740 }
1741
1742 char *
1743 kern_getcwd(char *buf, size_t buflen, int *error)
1744 {
1745         struct proc *p = curproc;
1746         char *bp;
1747         int i, slash_prefixed;
1748         struct filedesc *fdp;
1749         struct namecache *ncp;
1750
1751         numcwdcalls++;
1752         bp = buf;
1753         bp += buflen - 1;
1754         *bp = '\0';
1755         fdp = p->p_fd;
1756         slash_prefixed = 0;
1757
1758         ncp = fdp->fd_ncdir;
1759         while (ncp && ncp != fdp->fd_nrdir && (ncp->nc_flag & NCF_ROOT) == 0) {
1760                 if (ncp->nc_flag & NCF_MOUNTPT) {
1761                         if (ncp->nc_mount == NULL) {
1762                                 *error = EBADF;         /* forced unmount? */
1763                                 return(NULL);
1764                         }
1765                         ncp = ncp->nc_parent;
1766                         continue;
1767                 }
1768                 for (i = ncp->nc_nlen - 1; i >= 0; i--) {
1769                         if (bp == buf) {
1770                                 numcwdfail4++;
1771                                 *error = ENOMEM;
1772                                 return(NULL);
1773                         }
1774                         *--bp = ncp->nc_name[i];
1775                 }
1776                 if (bp == buf) {
1777                         numcwdfail4++;
1778                         *error = ENOMEM;
1779                         return(NULL);
1780                 }
1781                 *--bp = '/';
1782                 slash_prefixed = 1;
1783                 ncp = ncp->nc_parent;
1784         }
1785         if (ncp == NULL) {
1786                 numcwdfail2++;
1787                 *error = ENOENT;
1788                 return(NULL);
1789         }
1790         if (!slash_prefixed) {
1791                 if (bp == buf) {
1792                         numcwdfail4++;
1793                         *error = ENOMEM;
1794                         return(NULL);
1795                 }
1796                 *--bp = '/';
1797         }
1798         numcwdfound++;
1799         *error = 0;
1800         return (bp);
1801 }
1802
1803 /*
1804  * Thus begins the fullpath magic.
1805  */
1806
1807 #undef STATNODE
1808 #define STATNODE(name)                                                  \
1809         static u_int name;                                              \
1810         SYSCTL_UINT(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, "")
1811
1812 static int disablefullpath;
1813 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW,
1814     &disablefullpath, 0, "");
1815
1816 STATNODE(numfullpathcalls);
1817 STATNODE(numfullpathfail1);
1818 STATNODE(numfullpathfail2);
1819 STATNODE(numfullpathfail3);
1820 STATNODE(numfullpathfail4);
1821 STATNODE(numfullpathfound);
1822
1823 int
1824 vn_fullpath(struct proc *p, struct vnode *vn, char **retbuf, char **freebuf) 
1825 {
1826         char *bp, *buf;
1827         int i, slash_prefixed;
1828         struct filedesc *fdp;
1829         struct namecache *ncp;
1830
1831         numfullpathcalls++;
1832         if (disablefullpath)
1833                 return (ENODEV);
1834
1835         if (p == NULL)
1836                 return (EINVAL);
1837
1838         /* vn is NULL, client wants us to use p->p_textvp */
1839         if (vn == NULL) {
1840                 if ((vn = p->p_textvp) == NULL)
1841                         return (EINVAL);
1842         }
1843         ncp = TAILQ_FIRST(&vn->v_namecache);
1844         if (ncp == NULL)
1845                 return (EINVAL);
1846
1847         buf = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1848         bp = buf + MAXPATHLEN - 1;
1849         *bp = '\0';
1850         fdp = p->p_fd;
1851         slash_prefixed = 0;
1852         while (ncp && ncp != fdp->fd_nrdir && (ncp->nc_flag & NCF_ROOT) == 0) {
1853                 if (ncp->nc_flag & NCF_MOUNTPT) {
1854                         if (ncp->nc_mount == NULL) {
1855                                 free(buf, M_TEMP);
1856                                 return(EBADF);
1857                         }
1858                         ncp = ncp->nc_parent;
1859                         continue;
1860                 }
1861                 for (i = ncp->nc_nlen - 1; i >= 0; i--) {
1862                         if (bp == buf) {
1863                                 numfullpathfail4++;
1864                                 free(buf, M_TEMP);
1865                                 return (ENOMEM);
1866                         }
1867                         *--bp = ncp->nc_name[i];
1868                 }
1869                 if (bp == buf) {
1870                         numfullpathfail4++;
1871                         free(buf, M_TEMP);
1872                         return (ENOMEM);
1873                 }
1874                 *--bp = '/';
1875                 slash_prefixed = 1;
1876                 ncp = ncp->nc_parent;
1877         }
1878         if (ncp == NULL) {
1879                 numfullpathfail2++;
1880                 free(buf, M_TEMP);
1881                 return (ENOENT);
1882         }
1883         if (!slash_prefixed) {
1884                 if (bp == buf) {
1885                         numfullpathfail4++;
1886                         free(buf, M_TEMP);
1887                         return (ENOMEM);
1888                 }
1889                 *--bp = '/';
1890         }
1891         numfullpathfound++;
1892         *retbuf = bp; 
1893         *freebuf = buf;
1894         return (0);
1895 }
1896