]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/kern/vfs_cache.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[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                         CTR3(KTR_VFS, "cache_lookup(%p, %s) found %p via ..",
374                             dvp, cnp->cn_nameptr, *vpp);
375                         goto success;
376                 }
377         }
378
379         hash = fnv_32_buf(cnp->cn_nameptr, cnp->cn_namelen, FNV1_32_INIT);
380         hash = fnv_32_buf(&dvp, sizeof(dvp), hash);
381         LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
382                 numchecks++;
383                 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
384                     !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
385                         break;
386         }
387
388         /* We failed to find an entry */
389         if (ncp == 0) {
390                 if ((cnp->cn_flags & MAKEENTRY) == 0) {
391                         nummisszap++;
392                 } else {
393                         nummiss++;
394                 }
395                 nchstats.ncs_miss++;
396                 CACHE_UNLOCK();
397                 return (0);
398         }
399
400         /* We don't want to have an entry, so dump it */
401         if ((cnp->cn_flags & MAKEENTRY) == 0) {
402                 numposzaps++;
403                 nchstats.ncs_badhits++;
404                 cache_zap(ncp);
405                 CACHE_UNLOCK();
406                 return (0);
407         }
408
409         /* We found a "positive" match, return the vnode */
410         if (ncp->nc_vp) {
411                 numposhits++;
412                 nchstats.ncs_goodhits++;
413                 *vpp = ncp->nc_vp;
414                 CTR4(KTR_VFS, "cache_lookup(%p, %s) found %p via ncp %p",
415                     dvp, cnp->cn_nameptr, *vpp, ncp);
416                 goto success;
417         }
418
419         /* We found a negative match, and want to create it, so purge */
420         if (cnp->cn_nameiop == CREATE) {
421                 numnegzaps++;
422                 nchstats.ncs_badhits++;
423                 cache_zap(ncp);
424                 CACHE_UNLOCK();
425                 return (0);
426         }
427
428         numneghits++;
429         /*
430          * We found a "negative" match, so we shift it to the end of
431          * the "negative" cache entries queue to satisfy LRU.  Also,
432          * check to see if the entry is a whiteout; indicate this to
433          * the componentname, if so.
434          */
435         TAILQ_REMOVE(&ncneg, ncp, nc_dst);
436         TAILQ_INSERT_TAIL(&ncneg, ncp, nc_dst);
437         nchstats.ncs_neghits++;
438         if (ncp->nc_flag & NCF_WHITE)
439                 cnp->cn_flags |= ISWHITEOUT;
440         CACHE_UNLOCK();
441         return (ENOENT);
442
443 success:
444         /*
445          * On success we return a locked and ref'd vnode as per the lookup
446          * protocol.
447          */
448         if (dvp == *vpp) {   /* lookup on "." */
449                 VREF(*vpp);
450                 CACHE_UNLOCK();
451                 /*
452                  * When we lookup "." we still can be asked to lock it
453                  * differently...
454                  */
455                 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
456                 if (ltype != VOP_ISLOCKED(*vpp, td)) {
457                         if (ltype == LK_EXCLUSIVE) {
458                                 vn_lock(*vpp, LK_UPGRADE | LK_RETRY, td);
459                                 if ((*vpp)->v_iflag & VI_DOOMED) {
460                                         /* forced unmount */
461                                         vrele(*vpp);
462                                         *vpp = NULL;
463                                         return (EBADF);
464                                 }
465                         } else
466                                 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY, td);
467                 }
468                 return (-1);
469         }
470         ltype = 0;      /* silence gcc warning */
471         if (cnp->cn_flags & ISDOTDOT) {
472                 ltype = VOP_ISLOCKED(dvp, td);
473                 VOP_UNLOCK(dvp, 0, td);
474         }
475         VI_LOCK(*vpp);
476         CACHE_UNLOCK();
477         error = vget(*vpp, cnp->cn_lkflags | LK_INTERLOCK, td);
478         if (cnp->cn_flags & ISDOTDOT)
479                 vn_lock(dvp, ltype | LK_RETRY, td);
480         if (error) {
481                 *vpp = NULL;
482                 goto retry;
483         }
484         if ((cnp->cn_flags & ISLASTCN) &&
485             (cnp->cn_lkflags & LK_TYPE_MASK) == LK_EXCLUSIVE) {
486                 ASSERT_VOP_ELOCKED(*vpp, "cache_lookup");
487         }
488         return (-1);
489 }
490
491 /*
492  * Add an entry to the cache.
493  */
494 void
495 cache_enter(dvp, vp, cnp)
496         struct vnode *dvp;
497         struct vnode *vp;
498         struct componentname *cnp;
499 {
500         struct namecache *ncp, *n2;
501         struct nchashhead *ncpp;
502         u_int32_t hash;
503         int flag;
504         int hold;
505         int zap;
506         int len;
507
508         CTR3(KTR_VFS, "cache_enter(%p, %p, %s)", dvp, vp, cnp->cn_nameptr);
509         VNASSERT(vp == NULL || (vp->v_iflag & VI_DOOMED) == 0, vp,
510             ("cahe_enter: Adding a doomed vnode"));
511
512         if (!doingcache)
513                 return;
514
515         /*
516          * Avoid blowout in namecache entries.
517          */
518         if (numcache >= desiredvnodes * 2)
519                 return;
520
521         flag = 0;
522         if (cnp->cn_nameptr[0] == '.') {
523                 if (cnp->cn_namelen == 1)
524                         return;
525                 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
526                         CACHE_LOCK();
527                         /*
528                          * If dotdot entry already exists, just retarget it
529                          * to new parent vnode, otherwise continue with new
530                          * namecache entry allocation.
531                          */
532                         if ((ncp = dvp->v_cache_dd) != NULL) {
533                                 if (ncp->nc_flag & NCF_ISDOTDOT) {
534                                         KASSERT(ncp->nc_dvp == dvp,
535                                             ("wrong isdotdot parent"));
536                                         TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst,
537                                             ncp, nc_dst);
538                                         TAILQ_INSERT_HEAD(&vp->v_cache_dst,
539                                             ncp, nc_dst);
540                                         ncp->nc_vp = vp;
541                                         CACHE_UNLOCK();
542                                         return;
543                                 }
544                         }
545                         dvp->v_cache_dd = NULL;
546                         CACHE_UNLOCK();
547                         flag = NCF_ISDOTDOT;
548                 }
549         }
550
551         hold = 0;
552         zap = 0;
553
554         /*
555          * Calculate the hash key and setup as much of the new
556          * namecache entry as possible before acquiring the lock.
557          */
558         ncp = cache_alloc(cnp->cn_namelen);
559         ncp->nc_vp = vp;
560         ncp->nc_dvp = dvp;
561         ncp->nc_flag = flag;
562         len = ncp->nc_nlen = cnp->cn_namelen;
563         hash = fnv_32_buf(cnp->cn_nameptr, len, FNV1_32_INIT);
564         bcopy(cnp->cn_nameptr, ncp->nc_name, len);
565         hash = fnv_32_buf(&dvp, sizeof(dvp), hash);
566         CACHE_LOCK();
567
568         /*
569          * See if this vnode or negative entry is already in the cache
570          * with this name.  This can happen with concurrent lookups of
571          * the same path name.
572          */
573         ncpp = NCHHASH(hash);
574         LIST_FOREACH(n2, ncpp, nc_hash) {
575                 if (n2->nc_dvp == dvp &&
576                     n2->nc_nlen == cnp->cn_namelen &&
577                     !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
578                         CACHE_UNLOCK();
579                         cache_free(ncp);
580                         return;
581                 }
582         }
583
584         if (flag == NCF_ISDOTDOT) {
585                 /*
586                  * See if we are trying to add .. entry, but some other lookup
587                  * has populated v_cache_dd pointer already.
588                  */
589                 if (dvp->v_cache_dd != NULL) {
590                         CACHE_UNLOCK();
591                         cache_free(ncp);
592                         return;
593                 }
594                 KASSERT(vp == NULL || vp->v_type == VDIR,
595                     ("wrong vnode type %p", vp));
596                 dvp->v_cache_dd = ncp;
597         }
598
599         numcache++;
600         if (!vp) {
601                 numneg++;
602                 if (cnp->cn_flags & ISWHITEOUT)
603                         ncp->nc_flag |= NCF_WHITE;
604         } else if (vp->v_type == VDIR) {
605                 if (flag != NCF_ISDOTDOT) {
606                         if ((n2 = vp->v_cache_dd) != NULL &&
607                             (n2->nc_flag & NCF_ISDOTDOT) != 0)
608                                 cache_zap(n2);
609                         vp->v_cache_dd = ncp;
610                 }
611         } else {
612                 vp->v_cache_dd = NULL;
613         }
614
615         /*
616          * Insert the new namecache entry into the appropriate chain
617          * within the cache entries table.
618          */
619         LIST_INSERT_HEAD(ncpp, ncp, nc_hash);
620         if (flag != NCF_ISDOTDOT) {
621                 if (LIST_EMPTY(&dvp->v_cache_src)) {
622                         hold = 1;
623                         numcachehv++;
624                 }
625                 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
626         }
627
628         /*
629          * If the entry is "negative", we place it into the
630          * "negative" cache queue, otherwise, we place it into the
631          * destination vnode's cache entries queue.
632          */
633         if (vp) {
634                 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
635         } else {
636                 TAILQ_INSERT_TAIL(&ncneg, ncp, nc_dst);
637         }
638         if (numneg * ncnegfactor > numcache) {
639                 ncp = TAILQ_FIRST(&ncneg);
640                 zap = 1;
641         }
642         if (hold)
643                 vhold(dvp);
644         if (zap)
645                 cache_zap(ncp);
646         CACHE_UNLOCK();
647 }
648
649 /*
650  * Name cache initialization, from vfs_init() when we are booting
651  */
652 static void
653 nchinit(void *dummy __unused)
654 {
655
656         TAILQ_INIT(&ncneg);
657
658         cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL, NULL,
659             NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
660         cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE, NULL,
661             NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
662
663         nchashtbl = hashinit(desiredvnodes * 2, M_VFSCACHE, &nchash);
664 }
665 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
666
667
668 /*
669  * Invalidate all entries to a particular vnode.
670  */
671 void
672 cache_purge(vp)
673         struct vnode *vp;
674 {
675
676         CTR1(KTR_VFS, "cache_purge(%p)", vp);
677         CACHE_LOCK();
678         while (!LIST_EMPTY(&vp->v_cache_src))
679                 cache_zap(LIST_FIRST(&vp->v_cache_src));
680         while (!TAILQ_EMPTY(&vp->v_cache_dst))
681                 cache_zap(TAILQ_FIRST(&vp->v_cache_dst));
682         if (vp->v_cache_dd != NULL) {
683                 KASSERT(vp->v_cache_dd->nc_flag & NCF_ISDOTDOT,
684                    ("lost dotdot link"));
685                 cache_zap(vp->v_cache_dd);
686         }
687         KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
688         CACHE_UNLOCK();
689 }
690
691 /*
692  * Flush all entries referencing a particular filesystem.
693  */
694 void
695 cache_purgevfs(mp)
696         struct mount *mp;
697 {
698         struct nchashhead *ncpp;
699         struct namecache *ncp, *nnp;
700
701         /* Scan hash tables for applicable entries */
702         CACHE_LOCK();
703         for (ncpp = &nchashtbl[nchash]; ncpp >= nchashtbl; ncpp--) {
704                 LIST_FOREACH_SAFE(ncp, ncpp, nc_hash, nnp) {
705                         if (ncp->nc_dvp->v_mount == mp)
706                                 cache_zap(ncp);
707                 }
708         }
709         CACHE_UNLOCK();
710 }
711
712 /*
713  * Perform canonical checks and cache lookup and pass on to filesystem
714  * through the vop_cachedlookup only if needed.
715  */
716
717 int
718 vfs_cache_lookup(ap)
719         struct vop_lookup_args /* {
720                 struct vnode *a_dvp;
721                 struct vnode **a_vpp;
722                 struct componentname *a_cnp;
723         } */ *ap;
724 {
725         struct vnode *dvp;
726         int error;
727         struct vnode **vpp = ap->a_vpp;
728         struct componentname *cnp = ap->a_cnp;
729         struct ucred *cred = cnp->cn_cred;
730         int flags = cnp->cn_flags;
731         struct thread *td = cnp->cn_thread;
732
733         *vpp = NULL;
734         dvp = ap->a_dvp;
735
736         if (dvp->v_type != VDIR)
737                 return (ENOTDIR);
738
739         if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
740             (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
741                 return (EROFS);
742
743         error = VOP_ACCESS(dvp, VEXEC, cred, td);
744         if (error)
745                 return (error);
746
747         error = cache_lookup(dvp, vpp, cnp);
748         if (error == 0)
749                 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
750         if (error == -1)
751                 return (0);
752         return (error);
753 }
754
755
756 #ifndef _SYS_SYSPROTO_H_
757 struct  __getcwd_args {
758         u_char  *buf;
759         u_int   buflen;
760 };
761 #endif
762
763 /*
764  * XXX All of these sysctls would probably be more productive dead.
765  */
766 static int disablecwd;
767 SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0,
768    "Disable the getcwd syscall");
769
770 /* Implementation of the getcwd syscall. */
771 int
772 __getcwd(td, uap)
773         struct thread *td;
774         struct __getcwd_args *uap;
775 {
776
777         return (kern___getcwd(td, uap->buf, UIO_USERSPACE, uap->buflen));
778 }
779
780 int
781 kern___getcwd(struct thread *td, u_char *buf, enum uio_seg bufseg, u_int buflen)
782 {
783         char *bp, *tmpbuf;
784         struct filedesc *fdp;
785         int error;
786
787         if (disablecwd)
788                 return (ENODEV);
789         if (buflen < 2)
790                 return (EINVAL);
791         if (buflen > MAXPATHLEN)
792                 buflen = MAXPATHLEN;
793
794         tmpbuf = malloc(buflen, M_TEMP, M_WAITOK);
795         fdp = td->td_proc->p_fd;
796         mtx_lock(&Giant);
797         FILEDESC_SLOCK(fdp);
798         error = vn_fullpath1(td, fdp->fd_cdir, fdp->fd_rdir, tmpbuf,
799             &bp, buflen);
800         FILEDESC_SUNLOCK(fdp);
801         mtx_unlock(&Giant);
802
803         if (!error) {
804                 if (bufseg == UIO_SYSSPACE)
805                         bcopy(bp, buf, strlen(bp) + 1);
806                 else
807                         error = copyout(bp, buf, strlen(bp) + 1);
808 #ifdef KTRACE
809         if (KTRPOINT(curthread, KTR_NAMEI))
810                 ktrnamei(bp);
811 #endif
812         }
813         free(tmpbuf, M_TEMP);
814         return (error);
815 }
816
817 /*
818  * Thus begins the fullpath magic.
819  */
820
821 #undef STATNODE
822 #define STATNODE(name)                                                  \
823         static u_int name;                                              \
824         SYSCTL_UINT(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, "")
825
826 static int disablefullpath;
827 SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW, &disablefullpath, 0,
828         "Disable the vn_fullpath function");
829
830 /* These count for kern___getcwd(), too. */
831 STATNODE(numfullpathcalls);
832 STATNODE(numfullpathfail1);
833 STATNODE(numfullpathfail2);
834 STATNODE(numfullpathfail4);
835 STATNODE(numfullpathfound);
836
837 /*
838  * Retrieve the full filesystem path that correspond to a vnode from the name
839  * cache (if available)
840  */
841 int
842 vn_fullpath(struct thread *td, struct vnode *vn, char **retbuf, char **freebuf)
843 {
844         char *buf;
845         struct filedesc *fdp;
846         int error;
847
848         if (disablefullpath)
849                 return (ENODEV);
850         if (vn == NULL)
851                 return (EINVAL);
852
853         buf = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
854         fdp = td->td_proc->p_fd;
855         FILEDESC_SLOCK(fdp);
856         error = vn_fullpath1(td, vn, fdp->fd_rdir, buf, retbuf, MAXPATHLEN);
857         FILEDESC_SUNLOCK(fdp);
858
859         if (!error)
860                 *freebuf = buf;
861         else
862                 free(buf, M_TEMP);
863         return (error);
864 }
865
866 /*
867  * This function is similar to vn_fullpath, but it attempts to lookup the
868  * pathname relative to the global root mount point.  This is required for the
869  * auditing sub-system, as audited pathnames must be absolute, relative to the
870  * global root mount point.
871  */
872 int
873 vn_fullpath_global(struct thread *td, struct vnode *vn,
874     char **retbuf, char **freebuf)
875 {
876         char *buf;
877         int error;
878
879         if (disablefullpath)
880                 return (ENODEV);
881         if (vn == NULL)
882                 return (EINVAL);
883         buf = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
884         error = vn_fullpath1(td, vn, rootvnode, buf, retbuf, MAXPATHLEN);
885         if (!error)
886                 *freebuf = buf;
887         else
888                 free(buf, M_TEMP);
889         return (error);
890 }
891
892 /*
893  * The magic behind kern___getcwd() and vn_fullpath().
894  */
895 static int
896 vn_fullpath1(struct thread *td, struct vnode *vp, struct vnode *rdir,
897     char *buf, char **retbuf, u_int buflen)
898 {
899         char *bp;
900         int error, i, slash_prefixed;
901         struct namecache *ncp;
902
903         bp = buf + buflen - 1;
904         *bp = '\0';
905         error = 0;
906         slash_prefixed = 0;
907
908         CACHE_LOCK();
909         numfullpathcalls++;
910         if (vp->v_type != VDIR) {
911                 ncp = TAILQ_FIRST(&vp->v_cache_dst);
912                 if (!ncp) {
913                         numfullpathfail2++;
914                         CACHE_UNLOCK();
915                         return (ENOENT);
916                 }
917                 for (i = ncp->nc_nlen - 1; i >= 0 && bp > buf; i--)
918                         *--bp = ncp->nc_name[i];
919                 if (bp == buf) {
920                         numfullpathfail4++;
921                         CACHE_UNLOCK();
922                         return (ENOMEM);
923                 }
924                 *--bp = '/';
925                 slash_prefixed = 1;
926                 vp = ncp->nc_dvp;
927         }
928         while (vp != rdir && vp != rootvnode) {
929                 if (vp->v_vflag & VV_ROOT) {
930                         if (vp->v_iflag & VI_DOOMED) {  /* forced unmount */
931                                 error = EBADF;
932                                 break;
933                         }
934                         vp = vp->v_mount->mnt_vnodecovered;
935                         continue;
936                 }
937                 if (vp->v_type != VDIR) {
938                         numfullpathfail1++;
939                         error = ENOTDIR;
940                         break;
941                 }
942                 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
943                         if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
944                                 break;
945                 if (!ncp) {
946                         numfullpathfail2++;
947                         error = ENOENT;
948                         break;
949                 }
950                 for (i = ncp->nc_nlen - 1; i >= 0 && bp != buf; i--)
951                         *--bp = ncp->nc_name[i];
952                 if (bp == buf) {
953                         numfullpathfail4++;
954                         error = ENOMEM;
955                         break;
956                 }
957                 *--bp = '/';
958                 slash_prefixed = 1;
959                 vp = ncp->nc_dvp;
960         }
961         if (error) {
962                 CACHE_UNLOCK();
963                 return (error);
964         }
965         if (!slash_prefixed) {
966                 if (bp == buf) {
967                         numfullpathfail4++;
968                         CACHE_UNLOCK();
969                         return (ENOMEM);
970                 } else {
971                         *--bp = '/';
972                 }
973         }
974         numfullpathfound++;
975         CACHE_UNLOCK();
976
977         *retbuf = bp;
978         return (0);
979 }