]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/kern/vfs_cache.c
MFC r191218 and related backout r191220.
[FreeBSD/releng/7.2.git] / sys / kern / vfs_cache.c
1 /*-
2  * Copyright (c) 1989, 1993, 1995
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Poul-Henning Kamp of the FreeBSD Project.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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 the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      @(#)vfs_cache.c 8.5 (Berkeley) 3/22/95
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include "opt_ktrace.h"
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/sysctl.h>
46 #include <sys/mount.h>
47 #include <sys/vnode.h>
48 #include <sys/namei.h>
49 #include <sys/malloc.h>
50 #include <sys/syscallsubr.h>
51 #include <sys/sysproto.h>
52 #include <sys/proc.h>
53 #include <sys/filedesc.h>
54 #include <sys/fnv_hash.h>
55 #ifdef KTRACE
56 #include <sys/ktrace.h>
57 #endif
58
59 #include <vm/uma.h>
60
61 /*
62  * This structure describes the elements in the cache of recent
63  * names looked up by namei.
64  */
65
66 struct  namecache {
67         LIST_ENTRY(namecache) nc_hash;  /* hash chain */
68         LIST_ENTRY(namecache) nc_src;   /* source vnode list */
69         TAILQ_ENTRY(namecache) nc_dst;  /* destination vnode list */
70         struct  vnode *nc_dvp;          /* vnode of parent of name */
71         struct  vnode *nc_vp;           /* vnode the name refers to */
72         u_char  nc_flag;                /* flag bits */
73         u_char  nc_nlen;                /* length of name */
74         char    nc_name[0];             /* segment name */
75 };
76
77 /*
78  * Name caching works as follows:
79  *
80  * Names found by directory scans are retained in a cache
81  * for future reference.  It is managed LRU, so frequently
82  * used names will hang around.  Cache is indexed by hash value
83  * obtained from (vp, name) where vp refers to the directory
84  * containing name.
85  *
86  * If it is a "negative" entry, (i.e. for a name that is known NOT to
87  * exist) the vnode pointer will be NULL.
88  *
89  * Upon reaching the last segment of a path, if the reference
90  * is for DELETE, or NOCACHE is set (rewrite), and the
91  * name is located in the cache, it will be dropped.
92  */
93
94 /*
95  * Structures associated with name cacheing.
96  */
97 #define NCHHASH(hash) \
98         (&nchashtbl[(hash) & nchash])
99 static LIST_HEAD(nchashhead, namecache) *nchashtbl;     /* Hash Table */
100 static TAILQ_HEAD(, namecache) ncneg;   /* Hash Table */
101 static u_long   nchash;                 /* size of hash table */
102 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0, "");
103 static u_long   ncnegfactor = 16;       /* ratio of negative entries */
104 SYSCTL_ULONG(_debug, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0, "");
105 static u_long   numneg;                 /* number of cache entries allocated */
106 SYSCTL_ULONG(_debug, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0, "");
107 static u_long   numcache;               /* number of cache entries allocated */
108 SYSCTL_ULONG(_debug, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0, "");
109 static u_long   numcachehv;             /* number of cache entries with vnodes held */
110 SYSCTL_ULONG(_debug, OID_AUTO, numcachehv, CTLFLAG_RD, &numcachehv, 0, "");
111 #if 0
112 static u_long   numcachepl;             /* number of cache purge for leaf entries */
113 SYSCTL_ULONG(_debug, OID_AUTO, numcachepl, CTLFLAG_RD, &numcachepl, 0, "");
114 #endif
115 struct  nchstats nchstats;              /* cache effectiveness statistics */
116
117 static struct mtx cache_lock;
118 MTX_SYSINIT(vfscache, &cache_lock, "Name Cache", MTX_DEF);
119
120 #define CACHE_LOCK()    mtx_lock(&cache_lock)
121 #define CACHE_UNLOCK()  mtx_unlock(&cache_lock)
122
123 /*
124  * UMA zones for the VFS cache.
125  *
126  * The small cache is used for entries with short names, which are the
127  * most common.  The large cache is used for entries which are too big to
128  * fit in the small cache.
129  */
130 static uma_zone_t cache_zone_small;
131 static uma_zone_t cache_zone_large;
132
133 #define CACHE_PATH_CUTOFF       32
134 #define CACHE_ZONE_SMALL        (sizeof(struct namecache) + CACHE_PATH_CUTOFF)
135 #define CACHE_ZONE_LARGE        (sizeof(struct namecache) + NAME_MAX)
136
137 #define cache_alloc(len)        uma_zalloc(((len) <= CACHE_PATH_CUTOFF) ? \
138         cache_zone_small : cache_zone_large, M_WAITOK)
139 #define cache_free(ncp)         do { \
140         if (ncp != NULL) \
141                 uma_zfree(((ncp)->nc_nlen <= CACHE_PATH_CUTOFF) ? \
142                     cache_zone_small : cache_zone_large, (ncp)); \
143 } while (0)
144
145 static int      doingcache = 1;         /* 1 => enable the cache */
146 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0, "");
147
148 /* Export size information to userland */
149 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, 0,
150         sizeof(struct namecache), "");
151
152 /*
153  * The new name cache statistics
154  */
155 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0, "Name cache statistics");
156 #define STATNODE(mode, name, var) \
157         SYSCTL_ULONG(_vfs_cache, OID_AUTO, name, mode, var, 0, "");
158 STATNODE(CTLFLAG_RD, numneg, &numneg);
159 STATNODE(CTLFLAG_RD, numcache, &numcache);
160 static u_long numcalls; STATNODE(CTLFLAG_RD, numcalls, &numcalls);
161 static u_long dothits; STATNODE(CTLFLAG_RD, dothits, &dothits);
162 static u_long dotdothits; STATNODE(CTLFLAG_RD, dotdothits, &dotdothits);
163 static u_long numchecks; STATNODE(CTLFLAG_RD, numchecks, &numchecks);
164 static u_long nummiss; STATNODE(CTLFLAG_RD, nummiss, &nummiss);
165 static u_long nummisszap; STATNODE(CTLFLAG_RD, nummisszap, &nummisszap);
166 static u_long numposzaps; STATNODE(CTLFLAG_RD, numposzaps, &numposzaps);
167 static u_long numposhits; STATNODE(CTLFLAG_RD, numposhits, &numposhits);
168 static u_long numnegzaps; STATNODE(CTLFLAG_RD, numnegzaps, &numnegzaps);
169 static u_long numneghits; STATNODE(CTLFLAG_RD, numneghits, &numneghits);
170
171 SYSCTL_OPAQUE(_vfs_cache, OID_AUTO, nchstats, CTLFLAG_RD | CTLFLAG_MPSAFE,
172         &nchstats, sizeof(nchstats), "LU", "VFS cache effectiveness statistics");
173
174
175
176 static void cache_zap(struct namecache *ncp);
177 static int vn_fullpath1(struct thread *td, struct vnode *vp, struct vnode *rdir,
178     char *buf, char **retbuf, u_int buflen);
179
180 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
181
182 /*
183  * Flags in namecache.nc_flag
184  */
185 #define NCF_WHITE       0x01
186 #define NCF_ISDOTDOT    0x02
187
188 #ifdef DIAGNOSTIC
189 /*
190  * Grab an atomic snapshot of the name cache hash chain lengths
191  */
192 SYSCTL_NODE(_debug, OID_AUTO, hashstat, CTLFLAG_RW, NULL, "hash table stats");
193
194 static int
195 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
196 {
197         int error;
198         struct nchashhead *ncpp;
199         struct namecache *ncp;
200         int n_nchash;
201         int count;
202
203         n_nchash = nchash + 1;  /* nchash is max index, not count */
204         if (!req->oldptr)
205                 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
206
207         /* Scan hash tables for applicable entries */
208         for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
209                 count = 0;
210                 LIST_FOREACH(ncp, ncpp, nc_hash) {
211                         count++;
212                 }
213                 error = SYSCTL_OUT(req, &count, sizeof(count));
214                 if (error)
215                         return (error);
216         }
217         return (0);
218 }
219 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
220         CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
221         "nchash chain lengths");
222
223 static int
224 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
225 {
226         int error;
227         struct nchashhead *ncpp;
228         struct namecache *ncp;
229         int n_nchash;
230         int count, maxlength, used, pct;
231
232         if (!req->oldptr)
233                 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
234
235         n_nchash = nchash + 1;  /* nchash is max index, not count */
236         used = 0;
237         maxlength = 0;
238
239         /* Scan hash tables for applicable entries */
240         for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
241                 count = 0;
242                 LIST_FOREACH(ncp, ncpp, nc_hash) {
243                         count++;
244                 }
245                 if (count)
246                         used++;
247                 if (maxlength < count)
248                         maxlength = count;
249         }
250         n_nchash = nchash + 1;
251         pct = (used * 100 * 100) / n_nchash;
252         error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
253         if (error)
254                 return (error);
255         error = SYSCTL_OUT(req, &used, sizeof(used));
256         if (error)
257                 return (error);
258         error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
259         if (error)
260                 return (error);
261         error = SYSCTL_OUT(req, &pct, sizeof(pct));
262         if (error)
263                 return (error);
264         return (0);
265 }
266 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
267         CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
268         "nchash chain lengths");
269 #endif
270
271 /*
272  * cache_zap():
273  *
274  *   Removes a namecache entry from cache, whether it contains an actual
275  *   pointer to a vnode or if it is just a negative cache entry.
276  */
277 static void
278 cache_zap(ncp)
279         struct namecache *ncp;
280 {
281         struct vnode *vp;
282
283         mtx_assert(&cache_lock, MA_OWNED);
284         CTR2(KTR_VFS, "cache_zap(%p) vp %p", ncp, ncp->nc_vp);
285         vp = NULL;
286         LIST_REMOVE(ncp, nc_hash);
287         if (ncp->nc_flag & NCF_ISDOTDOT) {
288                 if (ncp == ncp->nc_dvp->v_cache_dd)
289                         ncp->nc_dvp->v_cache_dd = NULL;
290         } else {
291                 LIST_REMOVE(ncp, nc_src);
292                 if (LIST_EMPTY(&ncp->nc_dvp->v_cache_src)) {
293                         vp = ncp->nc_dvp;
294                         numcachehv--;
295                 }
296         }
297         if (ncp->nc_vp) {
298                 TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst, ncp, nc_dst);
299                 if (ncp == ncp->nc_vp->v_cache_dd)
300                         ncp->nc_vp->v_cache_dd = NULL;
301         } else {
302                 TAILQ_REMOVE(&ncneg, ncp, nc_dst);
303                 numneg--;
304         }
305         numcache--;
306         cache_free(ncp);
307         if (vp)
308                 vdrop(vp);
309 }
310
311 /*
312  * Lookup an entry in the cache
313  *
314  * Lookup is called with dvp pointing to the directory to search,
315  * cnp pointing to the name of the entry being sought. If the lookup
316  * succeeds, the vnode is returned in *vpp, and a status of -1 is
317  * returned. If the lookup determines that the name does not exist
318  * (negative cacheing), a status of ENOENT is returned. If the lookup
319  * fails, a status of zero is returned.  If the directory vnode is
320  * recycled out from under us due to a forced unmount, a status of
321  * EBADF is returned.
322  *
323  * vpp is locked and ref'd on return.  If we're looking up DOTDOT, dvp is
324  * unlocked.  If we're looking up . an extra ref is taken, but the lock is
325  * not recursively acquired.
326  */
327
328 int
329 cache_lookup(dvp, vpp, cnp)
330         struct vnode *dvp;
331         struct vnode **vpp;
332         struct componentname *cnp;
333 {
334         struct namecache *ncp;
335         struct thread *td;
336         u_int32_t hash;
337         int error, ltype;
338
339         if (!doingcache) {
340                 cnp->cn_flags &= ~MAKEENTRY;
341                 return (0);
342         }
343         td = cnp->cn_thread;
344 retry:
345         CACHE_LOCK();
346         numcalls++;
347
348         if (cnp->cn_nameptr[0] == '.') {
349                 if (cnp->cn_namelen == 1) {
350                         *vpp = dvp;
351                         CTR2(KTR_VFS, "cache_lookup(%p, %s) found via .",
352                             dvp, cnp->cn_nameptr);
353                         dothits++;
354                         goto success;
355                 }
356                 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
357                         dotdothits++;
358                         if (dvp->v_cache_dd == NULL) {
359                                 CACHE_UNLOCK();
360                                 return (0);
361                         }
362                         if ((cnp->cn_flags & MAKEENTRY) == 0) {
363                                 if (dvp->v_cache_dd->nc_flag & NCF_ISDOTDOT)
364                                         cache_zap(dvp->v_cache_dd);
365                                 dvp->v_cache_dd = NULL;
366                                 CACHE_UNLOCK();
367                                 return (0);
368                         }
369                         if (dvp->v_cache_dd->nc_flag & NCF_ISDOTDOT)
370                                 *vpp = dvp->v_cache_dd->nc_vp;
371                         else
372                                 *vpp = dvp->v_cache_dd->nc_dvp;
373                         /* Return failure if negative entry was found. */
374                         if (*vpp == NULL) {
375                                 ncp = dvp->v_cache_dd;
376                                 goto negative_success;
377                         }
378                         CTR3(KTR_VFS, "cache_lookup(%p, %s) found %p via ..",
379                             dvp, cnp->cn_nameptr, *vpp);
380                         goto success;
381                 }
382         }
383
384         hash = fnv_32_buf(cnp->cn_nameptr, cnp->cn_namelen, FNV1_32_INIT);
385         hash = fnv_32_buf(&dvp, sizeof(dvp), hash);
386         LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
387                 numchecks++;
388                 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
389                     !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
390                         break;
391         }
392
393         /* We failed to find an entry */
394         if (ncp == 0) {
395                 if ((cnp->cn_flags & MAKEENTRY) == 0) {
396                         nummisszap++;
397                 } else {
398                         nummiss++;
399                 }
400                 nchstats.ncs_miss++;
401                 CACHE_UNLOCK();
402                 return (0);
403         }
404
405         /* We don't want to have an entry, so dump it */
406         if ((cnp->cn_flags & MAKEENTRY) == 0) {
407                 numposzaps++;
408                 nchstats.ncs_badhits++;
409                 cache_zap(ncp);
410                 CACHE_UNLOCK();
411                 return (0);
412         }
413
414         /* We found a "positive" match, return the vnode */
415         if (ncp->nc_vp) {
416                 numposhits++;
417                 nchstats.ncs_goodhits++;
418                 *vpp = ncp->nc_vp;
419                 CTR4(KTR_VFS, "cache_lookup(%p, %s) found %p via ncp %p",
420                     dvp, cnp->cn_nameptr, *vpp, ncp);
421                 goto success;
422         }
423
424 negative_success:
425         /* We found a negative match, and want to create it, so purge */
426         if (cnp->cn_nameiop == CREATE) {
427                 numnegzaps++;
428                 nchstats.ncs_badhits++;
429                 cache_zap(ncp);
430                 CACHE_UNLOCK();
431                 return (0);
432         }
433
434         numneghits++;
435         /*
436          * We found a "negative" match, so we shift it to the end of
437          * the "negative" cache entries queue to satisfy LRU.  Also,
438          * check to see if the entry is a whiteout; indicate this to
439          * the componentname, if so.
440          */
441         TAILQ_REMOVE(&ncneg, ncp, nc_dst);
442         TAILQ_INSERT_TAIL(&ncneg, ncp, nc_dst);
443         nchstats.ncs_neghits++;
444         if (ncp->nc_flag & NCF_WHITE)
445                 cnp->cn_flags |= ISWHITEOUT;
446         CACHE_UNLOCK();
447         return (ENOENT);
448
449 success:
450         /*
451          * On success we return a locked and ref'd vnode as per the lookup
452          * protocol.
453          */
454         if (dvp == *vpp) {   /* lookup on "." */
455                 VREF(*vpp);
456                 CACHE_UNLOCK();
457                 /*
458                  * When we lookup "." we still can be asked to lock it
459                  * differently...
460                  */
461                 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
462                 if (ltype != VOP_ISLOCKED(*vpp, td)) {
463                         if (ltype == LK_EXCLUSIVE) {
464                                 vn_lock(*vpp, LK_UPGRADE | LK_RETRY, td);
465                                 if ((*vpp)->v_iflag & VI_DOOMED) {
466                                         /* forced unmount */
467                                         vrele(*vpp);
468                                         *vpp = NULL;
469                                         return (EBADF);
470                                 }
471                         } else
472                                 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY, td);
473                 }
474                 return (-1);
475         }
476         ltype = 0;      /* silence gcc warning */
477         if (cnp->cn_flags & ISDOTDOT) {
478                 ltype = VOP_ISLOCKED(dvp, td);
479                 VOP_UNLOCK(dvp, 0, td);
480         }
481         VI_LOCK(*vpp);
482         CACHE_UNLOCK();
483         error = vget(*vpp, cnp->cn_lkflags | LK_INTERLOCK, td);
484         if (cnp->cn_flags & ISDOTDOT)
485                 vn_lock(dvp, ltype | LK_RETRY, td);
486         if (error) {
487                 *vpp = NULL;
488                 goto retry;
489         }
490         if ((cnp->cn_flags & ISLASTCN) &&
491             (cnp->cn_lkflags & LK_TYPE_MASK) == LK_EXCLUSIVE) {
492                 ASSERT_VOP_ELOCKED(*vpp, "cache_lookup");
493         }
494         return (-1);
495 }
496
497 /*
498  * Add an entry to the cache.
499  */
500 void
501 cache_enter(dvp, vp, cnp)
502         struct vnode *dvp;
503         struct vnode *vp;
504         struct componentname *cnp;
505 {
506         struct namecache *ncp, *n2;
507         struct nchashhead *ncpp;
508         u_int32_t hash;
509         int flag;
510         int hold;
511         int zap;
512         int len;
513
514         CTR3(KTR_VFS, "cache_enter(%p, %p, %s)", dvp, vp, cnp->cn_nameptr);
515         VNASSERT(vp == NULL || (vp->v_iflag & VI_DOOMED) == 0, vp,
516             ("cahe_enter: Adding a doomed vnode"));
517
518         if (!doingcache)
519                 return;
520
521         /*
522          * Avoid blowout in namecache entries.
523          */
524         if (numcache >= desiredvnodes * 2)
525                 return;
526
527         flag = 0;
528         if (cnp->cn_nameptr[0] == '.') {
529                 if (cnp->cn_namelen == 1)
530                         return;
531                 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
532                         CACHE_LOCK();
533                         /*
534                          * If dotdot entry already exists, just retarget it
535                          * to new parent vnode, otherwise continue with new
536                          * namecache entry allocation.
537                          */
538                         if ((ncp = dvp->v_cache_dd) != NULL &&
539                             ncp->nc_flag & NCF_ISDOTDOT) {
540                                 KASSERT(ncp->nc_dvp == dvp,
541                                     ("wrong isdotdot parent"));
542                                 if (ncp->nc_vp != NULL)
543                                         TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst,
544                                             ncp, nc_dst);
545                                 else
546                                         TAILQ_REMOVE(&ncneg, ncp, nc_dst);
547                                 if (vp != NULL)
548                                         TAILQ_INSERT_HEAD(&vp->v_cache_dst,
549                                             ncp, nc_dst);
550                                 else
551                                         TAILQ_INSERT_TAIL(&ncneg, ncp, nc_dst);
552                                 ncp->nc_vp = vp;
553                                 CACHE_UNLOCK();
554                                 return;
555                         }
556                         dvp->v_cache_dd = NULL;
557                         CACHE_UNLOCK();
558                         flag = NCF_ISDOTDOT;
559                 }
560         }
561
562         hold = 0;
563         zap = 0;
564
565         /*
566          * Calculate the hash key and setup as much of the new
567          * namecache entry as possible before acquiring the lock.
568          */
569         ncp = cache_alloc(cnp->cn_namelen);
570         ncp->nc_vp = vp;
571         ncp->nc_dvp = dvp;
572         ncp->nc_flag = flag;
573         len = ncp->nc_nlen = cnp->cn_namelen;
574         hash = fnv_32_buf(cnp->cn_nameptr, len, FNV1_32_INIT);
575         bcopy(cnp->cn_nameptr, ncp->nc_name, len);
576         hash = fnv_32_buf(&dvp, sizeof(dvp), hash);
577         CACHE_LOCK();
578
579         /*
580          * See if this vnode or negative entry is already in the cache
581          * with this name.  This can happen with concurrent lookups of
582          * the same path name.
583          */
584         ncpp = NCHHASH(hash);
585         LIST_FOREACH(n2, ncpp, nc_hash) {
586                 if (n2->nc_dvp == dvp &&
587                     n2->nc_nlen == cnp->cn_namelen &&
588                     !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
589                         CACHE_UNLOCK();
590                         cache_free(ncp);
591                         return;
592                 }
593         }
594
595         if (flag == NCF_ISDOTDOT) {
596                 /*
597                  * See if we are trying to add .. entry, but some other lookup
598                  * has populated v_cache_dd pointer already.
599                  */
600                 if (dvp->v_cache_dd != NULL) {
601                         CACHE_UNLOCK();
602                         cache_free(ncp);
603                         return;
604                 }
605                 KASSERT(vp == NULL || vp->v_type == VDIR,
606                     ("wrong vnode type %p", vp));
607                 dvp->v_cache_dd = ncp;
608         }
609
610         numcache++;
611         if (!vp) {
612                 numneg++;
613                 if (cnp->cn_flags & ISWHITEOUT)
614                         ncp->nc_flag |= NCF_WHITE;
615         } else if (vp->v_type == VDIR) {
616                 if (flag != NCF_ISDOTDOT) {
617                         if ((n2 = vp->v_cache_dd) != NULL &&
618                             (n2->nc_flag & NCF_ISDOTDOT) != 0)
619                                 cache_zap(n2);
620                         vp->v_cache_dd = ncp;
621                 }
622         } else {
623                 vp->v_cache_dd = NULL;
624         }
625
626         /*
627          * Insert the new namecache entry into the appropriate chain
628          * within the cache entries table.
629          */
630         LIST_INSERT_HEAD(ncpp, ncp, nc_hash);
631         if (flag != NCF_ISDOTDOT) {
632                 if (LIST_EMPTY(&dvp->v_cache_src)) {
633                         hold = 1;
634                         numcachehv++;
635                 }
636                 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
637         }
638
639         /*
640          * If the entry is "negative", we place it into the
641          * "negative" cache queue, otherwise, we place it into the
642          * destination vnode's cache entries queue.
643          */
644         if (vp) {
645                 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
646         } else {
647                 TAILQ_INSERT_TAIL(&ncneg, ncp, nc_dst);
648         }
649         if (numneg * ncnegfactor > numcache) {
650                 ncp = TAILQ_FIRST(&ncneg);
651                 zap = 1;
652         }
653         if (hold)
654                 vhold(dvp);
655         if (zap)
656                 cache_zap(ncp);
657         CACHE_UNLOCK();
658 }
659
660 /*
661  * Name cache initialization, from vfs_init() when we are booting
662  */
663 static void
664 nchinit(void *dummy __unused)
665 {
666
667         TAILQ_INIT(&ncneg);
668
669         cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL, NULL,
670             NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
671         cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE, NULL,
672             NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
673
674         nchashtbl = hashinit(desiredvnodes * 2, M_VFSCACHE, &nchash);
675 }
676 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
677
678
679 /*
680  * Invalidate all entries to a particular vnode.
681  */
682 void
683 cache_purge(vp)
684         struct vnode *vp;
685 {
686
687         CTR1(KTR_VFS, "cache_purge(%p)", vp);
688         CACHE_LOCK();
689         while (!LIST_EMPTY(&vp->v_cache_src))
690                 cache_zap(LIST_FIRST(&vp->v_cache_src));
691         while (!TAILQ_EMPTY(&vp->v_cache_dst))
692                 cache_zap(TAILQ_FIRST(&vp->v_cache_dst));
693         if (vp->v_cache_dd != NULL) {
694                 KASSERT(vp->v_cache_dd->nc_flag & NCF_ISDOTDOT,
695                    ("lost dotdot link"));
696                 cache_zap(vp->v_cache_dd);
697         }
698         KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
699         CACHE_UNLOCK();
700 }
701
702 /*
703  * Flush all entries referencing a particular filesystem.
704  */
705 void
706 cache_purgevfs(mp)
707         struct mount *mp;
708 {
709         struct nchashhead *ncpp;
710         struct namecache *ncp, *nnp;
711
712         /* Scan hash tables for applicable entries */
713         CACHE_LOCK();
714         for (ncpp = &nchashtbl[nchash]; ncpp >= nchashtbl; ncpp--) {
715                 LIST_FOREACH_SAFE(ncp, ncpp, nc_hash, nnp) {
716                         if (ncp->nc_dvp->v_mount == mp)
717                                 cache_zap(ncp);
718                 }
719         }
720         CACHE_UNLOCK();
721 }
722
723 /*
724  * Perform canonical checks and cache lookup and pass on to filesystem
725  * through the vop_cachedlookup only if needed.
726  */
727
728 int
729 vfs_cache_lookup(ap)
730         struct vop_lookup_args /* {
731                 struct vnode *a_dvp;
732                 struct vnode **a_vpp;
733                 struct componentname *a_cnp;
734         } */ *ap;
735 {
736         struct vnode *dvp;
737         int error;
738         struct vnode **vpp = ap->a_vpp;
739         struct componentname *cnp = ap->a_cnp;
740         struct ucred *cred = cnp->cn_cred;
741         int flags = cnp->cn_flags;
742         struct thread *td = cnp->cn_thread;
743
744         *vpp = NULL;
745         dvp = ap->a_dvp;
746
747         if (dvp->v_type != VDIR)
748                 return (ENOTDIR);
749
750         if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
751             (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
752                 return (EROFS);
753
754         error = VOP_ACCESS(dvp, VEXEC, cred, td);
755         if (error)
756                 return (error);
757
758         error = cache_lookup(dvp, vpp, cnp);
759         if (error == 0)
760                 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
761         if (error == -1)
762                 return (0);
763         return (error);
764 }
765
766
767 #ifndef _SYS_SYSPROTO_H_
768 struct  __getcwd_args {
769         u_char  *buf;
770         u_int   buflen;
771 };
772 #endif
773
774 /*
775  * XXX All of these sysctls would probably be more productive dead.
776  */
777 static int disablecwd;
778 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0,
779    "Disable the getcwd syscall");
780
781 /* Implementation of the getcwd syscall. */
782 int
783 __getcwd(td, uap)
784         struct thread *td;
785         struct __getcwd_args *uap;
786 {
787
788         return (kern___getcwd(td, uap->buf, UIO_USERSPACE, uap->buflen));
789 }
790
791 int
792 kern___getcwd(struct thread *td, u_char *buf, enum uio_seg bufseg, u_int buflen)
793 {
794         char *bp, *tmpbuf;
795         struct filedesc *fdp;
796         int error;
797
798         if (disablecwd)
799                 return (ENODEV);
800         if (buflen < 2)
801                 return (EINVAL);
802         if (buflen > MAXPATHLEN)
803                 buflen = MAXPATHLEN;
804
805         tmpbuf = malloc(buflen, M_TEMP, M_WAITOK);
806         fdp = td->td_proc->p_fd;
807         mtx_lock(&Giant);
808         FILEDESC_SLOCK(fdp);
809         error = vn_fullpath1(td, fdp->fd_cdir, fdp->fd_rdir, tmpbuf,
810             &bp, buflen);
811         FILEDESC_SUNLOCK(fdp);
812         mtx_unlock(&Giant);
813
814         if (!error) {
815                 if (bufseg == UIO_SYSSPACE)
816                         bcopy(bp, buf, strlen(bp) + 1);
817                 else
818                         error = copyout(bp, buf, strlen(bp) + 1);
819 #ifdef KTRACE
820         if (KTRPOINT(curthread, KTR_NAMEI))
821                 ktrnamei(bp);
822 #endif
823         }
824         free(tmpbuf, M_TEMP);
825         return (error);
826 }
827
828 /*
829  * Thus begins the fullpath magic.
830  */
831
832 #undef STATNODE
833 #define STATNODE(name)                                                  \
834         static u_int name;                                              \
835         SYSCTL_UINT(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, "")
836
837 static int disablefullpath;
838 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW, &disablefullpath, 0,
839         "Disable the vn_fullpath function");
840
841 /* These count for kern___getcwd(), too. */
842 STATNODE(numfullpathcalls);
843 STATNODE(numfullpathfail1);
844 STATNODE(numfullpathfail2);
845 STATNODE(numfullpathfail4);
846 STATNODE(numfullpathfound);
847
848 /*
849  * Retrieve the full filesystem path that correspond to a vnode from the name
850  * cache (if available)
851  */
852 int
853 vn_fullpath(struct thread *td, struct vnode *vn, char **retbuf, char **freebuf)
854 {
855         char *buf;
856         struct filedesc *fdp;
857         int error;
858
859         if (disablefullpath)
860                 return (ENODEV);
861         if (vn == NULL)
862                 return (EINVAL);
863
864         buf = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
865         fdp = td->td_proc->p_fd;
866         FILEDESC_SLOCK(fdp);
867         error = vn_fullpath1(td, vn, fdp->fd_rdir, buf, retbuf, MAXPATHLEN);
868         FILEDESC_SUNLOCK(fdp);
869
870         if (!error)
871                 *freebuf = buf;
872         else
873                 free(buf, M_TEMP);
874         return (error);
875 }
876
877 /*
878  * This function is similar to vn_fullpath, but it attempts to lookup the
879  * pathname relative to the global root mount point.  This is required for the
880  * auditing sub-system, as audited pathnames must be absolute, relative to the
881  * global root mount point.
882  */
883 int
884 vn_fullpath_global(struct thread *td, struct vnode *vn,
885     char **retbuf, char **freebuf)
886 {
887         char *buf;
888         int error;
889
890         if (disablefullpath)
891                 return (ENODEV);
892         if (vn == NULL)
893                 return (EINVAL);
894         buf = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
895         error = vn_fullpath1(td, vn, rootvnode, buf, retbuf, MAXPATHLEN);
896         if (!error)
897                 *freebuf = buf;
898         else
899                 free(buf, M_TEMP);
900         return (error);
901 }
902
903 /*
904  * The magic behind kern___getcwd() and vn_fullpath().
905  */
906 static int
907 vn_fullpath1(struct thread *td, struct vnode *vp, struct vnode *rdir,
908     char *buf, char **retbuf, u_int buflen)
909 {
910         char *bp;
911         int error, i, slash_prefixed;
912         struct namecache *ncp;
913
914         bp = buf + buflen - 1;
915         *bp = '\0';
916         error = 0;
917         slash_prefixed = 0;
918
919         CACHE_LOCK();
920         numfullpathcalls++;
921         if (vp->v_type != VDIR) {
922                 ncp = TAILQ_FIRST(&vp->v_cache_dst);
923                 if (!ncp) {
924                         numfullpathfail2++;
925                         CACHE_UNLOCK();
926                         return (ENOENT);
927                 }
928                 for (i = ncp->nc_nlen - 1; i >= 0 && bp > buf; i--)
929                         *--bp = ncp->nc_name[i];
930                 if (bp == buf) {
931                         numfullpathfail4++;
932                         CACHE_UNLOCK();
933                         return (ENOMEM);
934                 }
935                 *--bp = '/';
936                 slash_prefixed = 1;
937                 vp = ncp->nc_dvp;
938         }
939         while (vp != rdir && vp != rootvnode) {
940                 if (vp->v_vflag & VV_ROOT) {
941                         if (vp->v_iflag & VI_DOOMED) {  /* forced unmount */
942                                 error = EBADF;
943                                 break;
944                         }
945                         vp = vp->v_mount->mnt_vnodecovered;
946                         continue;
947                 }
948                 if (vp->v_type != VDIR) {
949                         numfullpathfail1++;
950                         error = ENOTDIR;
951                         break;
952                 }
953                 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
954                         if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
955                                 break;
956                 if (!ncp) {
957                         numfullpathfail2++;
958                         error = ENOENT;
959                         break;
960                 }
961                 for (i = ncp->nc_nlen - 1; i >= 0 && bp != buf; i--)
962                         *--bp = ncp->nc_name[i];
963                 if (bp == buf) {
964                         numfullpathfail4++;
965                         error = ENOMEM;
966                         break;
967                 }
968                 *--bp = '/';
969                 slash_prefixed = 1;
970                 vp = ncp->nc_dvp;
971         }
972         if (error) {
973                 CACHE_UNLOCK();
974                 return (error);
975         }
976         if (!slash_prefixed) {
977                 if (bp == buf) {
978                         numfullpathfail4++;
979                         CACHE_UNLOCK();
980                         return (ENOMEM);
981                 } else {
982                         *--bp = '/';
983                 }
984         }
985         numfullpathfound++;
986         CACHE_UNLOCK();
987
988         *retbuf = bp;
989         return (0);
990 }