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