xref: /openbsd/sys/kern/vfs_cache.c (revision 891d7ab6)
1 /*	$OpenBSD: vfs_cache.c,v 1.33 2010/05/19 08:31:23 thib Exp $	*/
2 /*	$NetBSD: vfs_cache.c,v 1.13 1996/02/04 02:18:09 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1989, 1993
6  *	The Regents of the University of California.  All rights reserved.
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  * 3. 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.3 (Berkeley) 8/22/94
33  */
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/time.h>
38 #include <sys/mount.h>
39 #include <sys/vnode.h>
40 #include <sys/namei.h>
41 #include <sys/errno.h>
42 #include <sys/malloc.h>
43 #include <sys/pool.h>
44 
45 /*
46  * TODO: namecache access should really be locked.
47  */
48 
49 /*
50  * For simplicity (and economy of storage), names longer than
51  * a maximum length of NCHNAMLEN are not cached; they occur
52  * infrequently in any case, and are almost never of interest.
53  *
54  * Upon reaching the last segment of a path, if the reference
55  * is for DELETE, or NOCACHE is set (rewrite), and the
56  * name is located in the cache, it will be dropped.
57  */
58 
59 /*
60  * Structures associated with name caching.
61  */
62 long	numcache;	/* total number of cache entries allocated */
63 long	numneg;		/* number of negative cache entries */
64 
65 TAILQ_HEAD(, namecache) nclruhead;	/* Regular Entry LRU chain */
66 TAILQ_HEAD(, namecache) nclruneghead;	/* Negative Entry LRU chain */
67 struct	nchstats nchstats;		/* cache effectiveness statistics */
68 
69 int doingcache = 1;			/* 1 => enable the cache */
70 
71 struct pool nch_pool;
72 
73 void cache_zap(struct namecache *);
74 u_long nextvnodeid;
75 
76 static int
77 namecache_compare(struct namecache *n1, struct namecache *n2)
78 {
79 	if (n1->nc_nlen == n2->nc_nlen)
80 		return (memcmp(n1->nc_name, n2->nc_name, n1->nc_nlen));
81 	else
82 		return (n1->nc_nlen - n2->nc_nlen);
83 }
84 
85 RB_GENERATE(namecache_rb_cache, namecache, n_rbcache, namecache_compare);
86 
87 /*
88  * blow away a namecache entry
89  */
90 void
91 cache_zap(struct namecache *ncp)
92 {
93 	struct vnode *dvp = NULL;
94 
95 	if (ncp->nc_vp != NULL) {
96 		TAILQ_REMOVE(&nclruhead, ncp, nc_lru);
97 		numcache--;
98 	} else {
99 		TAILQ_REMOVE(&nclruneghead, ncp, nc_neg);
100 		numneg--;
101 	}
102 	if (ncp->nc_dvp) {
103 		RB_REMOVE(namecache_rb_cache, &ncp->nc_dvp->v_nc_tree, ncp);
104 		if (RB_EMPTY(&ncp->nc_dvp->v_nc_tree))
105 			dvp = ncp->nc_dvp;
106 	}
107 	if (ncp->nc_vp && (ncp->nc_vpid == ncp->nc_vp->v_id)) {
108 		if (ncp->nc_vp != ncp->nc_dvp &&
109 		    ncp->nc_vp->v_type == VDIR &&
110 		    (ncp->nc_nlen > 2 ||
111 			(ncp->nc_nlen > 1 &&
112 			    ncp->nc_name[1] != '.') ||
113 			(ncp->nc_nlen > 0 &&
114 			    ncp->nc_name[0] != '.'))) {
115 			TAILQ_REMOVE(&ncp->nc_vp->v_cache_dst, ncp, nc_me);
116 		}
117 	}
118 	pool_put(&nch_pool, ncp);
119 	if (dvp)
120 		vdrop(dvp);
121 }
122 
123 /*
124  * Look for a name in the cache. We don't do this if the segment name is
125  * long, simply so the cache can avoid holding long names (which would
126  * either waste space, or add greatly to the complexity).
127  * dvp points to the directory to search. The componentname cnp holds
128  * the information on the entry being sought, such as its length
129  * and its name. If the lookup succeeds, vpp is set to point to the vnode
130  * and an error of 0 is returned. If the lookup determines the name does
131  * not exist (negative caching) an error of ENOENT is returned. If the
132  * lookup fails, an error of -1 is returned.
133  */
134 int
135 cache_lookup(struct vnode *dvp, struct vnode **vpp,
136     struct componentname *cnp)
137 {
138 	struct namecache *ncp;
139 	struct namecache n;
140 	struct vnode *vp;
141 	struct proc *p = curproc;
142 	u_long vpid;
143 	int error;
144 
145 	*vpp = NULL;
146 
147 	if (!doingcache) {
148 		cnp->cn_flags &= ~MAKEENTRY;
149 		return (-1);
150 	}
151 	if (cnp->cn_namelen > NCHNAMLEN) {
152 		nchstats.ncs_long++;
153 		cnp->cn_flags &= ~MAKEENTRY;
154 		return (-1);
155 	}
156 
157 	/* lookup in directory vnode's redblack tree */
158 	n.nc_nlen = cnp->cn_namelen;
159 	memcpy(n.nc_name, cnp->cn_nameptr, n.nc_nlen);
160 	ncp = RB_FIND(namecache_rb_cache, &dvp->v_nc_tree, &n);
161 
162 	if (ncp == NULL) {
163 		nchstats.ncs_miss++;
164 		return (-1);
165 	}
166 	if ((cnp->cn_flags & MAKEENTRY) == 0) {
167 		nchstats.ncs_badhits++;
168 		goto remove;
169 	} else if (ncp->nc_vp == NULL) {
170 		if (cnp->cn_nameiop != CREATE ||
171 		    (cnp->cn_flags & ISLASTCN) == 0) {
172 			nchstats.ncs_neghits++;
173 			/*
174 			 * Move this slot to end of the negative LRU chain,
175 			 */
176 			if (TAILQ_NEXT(ncp, nc_neg) != NULL) {
177 				TAILQ_REMOVE(&nclruneghead, ncp, nc_neg);
178 				TAILQ_INSERT_TAIL(&nclruneghead, ncp,
179 				    nc_neg);
180 			}
181 			return (ENOENT);
182 		} else {
183 			nchstats.ncs_badhits++;
184 			goto remove;
185 		}
186 	} else if (ncp->nc_vpid != ncp->nc_vp->v_id) {
187 		nchstats.ncs_falsehits++;
188 		goto remove;
189 	}
190 
191 	vp = ncp->nc_vp;
192 	vpid = vp->v_id;
193 	if (vp == dvp) {	/* lookup on "." */
194 		vref(dvp);
195 		error = 0;
196 	} else if (cnp->cn_flags & ISDOTDOT) {
197 		VOP_UNLOCK(dvp, 0, p);
198 		cnp->cn_flags |= PDIRUNLOCK;
199 		error = vget(vp, LK_EXCLUSIVE, p);
200 		/*
201 		 * If the above vget() succeeded and both LOCKPARENT and
202 		 * ISLASTCN is set, lock the directory vnode as well.
203 		 */
204 		if (!error && (~cnp->cn_flags & (LOCKPARENT|ISLASTCN)) == 0) {
205 			if ((error = vn_lock(dvp, LK_EXCLUSIVE, p)) != 0) {
206 				vput(vp);
207 				return (error);
208 			}
209 			cnp->cn_flags &= ~PDIRUNLOCK;
210 		}
211 	} else {
212 		error = vget(vp, LK_EXCLUSIVE, p);
213 		/*
214 		 * If the above vget() failed or either of LOCKPARENT or
215 		 * ISLASTCN is set, unlock the directory vnode.
216 		 */
217 		if (error || (~cnp->cn_flags & (LOCKPARENT|ISLASTCN)) != 0) {
218 			VOP_UNLOCK(dvp, 0, p);
219 			cnp->cn_flags |= PDIRUNLOCK;
220 		}
221 	}
222 
223 	/*
224 	 * Check that the lock succeeded, and that the capability number did
225 	 * not change while we were waiting for the lock.
226 	 */
227 	if (error || vpid != vp->v_id) {
228 		if (!error) {
229 			vput(vp);
230 			nchstats.ncs_falsehits++;
231 		} else
232 			nchstats.ncs_badhits++;
233 		/*
234 		 * The parent needs to be locked when we return to VOP_LOOKUP().
235 		 * The `.' case here should be extremely rare (if it can happen
236 		 * at all), so we don't bother optimizing out the unlock/relock.
237 		 */
238 		if (vp == dvp || error ||
239 		    (~cnp->cn_flags & (LOCKPARENT|ISLASTCN)) != 0) {
240 			if ((error = vn_lock(dvp, LK_EXCLUSIVE, p)) != 0)
241 				return (error);
242 			cnp->cn_flags &= ~PDIRUNLOCK;
243 		}
244 		return (-1);
245 	}
246 
247 	nchstats.ncs_goodhits++;
248 	/*
249 	 * Move this slot to end of the regular LRU chain.
250 	 */
251 	if (TAILQ_NEXT(ncp, nc_lru) != NULL) {
252 		TAILQ_REMOVE(&nclruhead, ncp, nc_lru);
253 		TAILQ_INSERT_TAIL(&nclruhead, ncp, nc_lru);
254 	}
255 	*vpp = vp;
256 	return (0);
257 
258 remove:
259 	/*
260 	 * Last component and we are renaming or deleting,
261 	 * the cache entry is invalid, or otherwise don't
262 	 * want cache entry to exist.
263 	 */
264 	cache_zap(ncp);
265 	return (-1);
266 }
267 
268 /*
269  * Scan cache looking for name of directory entry pointing at vp.
270  *
271  * Fill in dvpp.
272  *
273  * If bufp is non-NULL, also place the name in the buffer which starts
274  * at bufp, immediately before *bpp, and move bpp backwards to point
275  * at the start of it.  (Yes, this is a little baroque, but it's done
276  * this way to cater to the whims of getcwd).
277  *
278  * Returns 0 on success, -1 on cache miss, positive errno on failure.
279  *
280  * TODO: should we return *dvpp locked?
281  */
282 
283 int
284 cache_revlookup(struct vnode *vp, struct vnode **dvpp, char **bpp, char *bufp)
285 {
286 	struct namecache *ncp;
287 	struct vnode *dvp = NULL;
288 	char *bp;
289 
290 	if (!doingcache)
291 		goto out;
292 	TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_me) {
293 		dvp = ncp->nc_dvp;
294 		if (dvp && dvp != vp && ncp->nc_dvpid == dvp->v_id)
295 			goto found;
296 	}
297 	goto miss;
298 found:
299 #ifdef DIAGNOSTIC
300 	if (ncp->nc_nlen == 1 &&
301 	    ncp->nc_name[0] == '.')
302 		panic("cache_revlookup: found entry for .");
303 	if (ncp->nc_nlen == 2 &&
304 	    ncp->nc_name[0] == '.' &&
305 	    ncp->nc_name[1] == '.')
306 		panic("cache_revlookup: found entry for ..");
307 #endif
308 	nchstats.ncs_revhits++;
309 
310 	if (bufp != NULL) {
311 		bp = *bpp;
312 		bp -= ncp->nc_nlen;
313 		if (bp <= bufp) {
314 			*dvpp = NULL;
315 			return (ERANGE);
316 		}
317 		memcpy(bp, ncp->nc_name, ncp->nc_nlen);
318 		*bpp = bp;
319 	}
320 
321 	*dvpp = dvp;
322 
323 	/*
324 	 * XXX: Should we vget() here to have more
325 	 * consistent semantics with cache_lookup()?
326 	 */
327 	return (0);
328 
329 miss:
330 	nchstats.ncs_revmiss++;
331 out:
332 	*dvpp = NULL;
333 	return (-1);
334 }
335 
336 /*
337  * Add an entry to the cache
338  */
339 void
340 cache_enter(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
341 {
342 	struct namecache *ncp, *lncp;
343 
344 	if (!doingcache || cnp->cn_namelen > NCHNAMLEN)
345 		return;
346 
347 	/*
348 	 * allocate, or recycle (free and allocate) an ncp.
349 	 */
350 	if (numcache >= desiredvnodes) {
351 		if ((ncp = TAILQ_FIRST(&nclruhead)) != NULL)
352 			cache_zap(ncp);
353 		else if ((ncp = TAILQ_FIRST(&nclruneghead)) != NULL)
354 			cache_zap(ncp);
355 		else
356 			panic("wtf? leak?");
357 	}
358 	ncp = pool_get(&nch_pool, PR_WAITOK|PR_ZERO);
359 
360 	/* grab the vnode we just found */
361 	ncp->nc_vp = vp;
362 	if (vp)
363 		ncp->nc_vpid = vp->v_id;
364 
365 	/* fill in cache info */
366 	ncp->nc_dvp = dvp;
367 	ncp->nc_dvpid = dvp->v_id;
368 	ncp->nc_nlen = cnp->cn_namelen;
369 	bcopy(cnp->cn_nameptr, ncp->nc_name, (unsigned)ncp->nc_nlen);
370 	if (RB_EMPTY(&dvp->v_nc_tree)) {
371 		vhold(dvp);
372 	}
373 	if ((lncp = RB_INSERT(namecache_rb_cache, &dvp->v_nc_tree, ncp))
374 	    != NULL) {
375 		/* someone has raced us and added a different entry
376 		 * for the same vnode (different ncp) - we don't need
377 		 * this entry, so free it and we are done.
378 		 */
379 	  	pool_put(&nch_pool, ncp);
380 		/* we know now dvp->v_nc_tree is not empty, no need
381 		 * to vdrop here
382 		 */
383 		goto done;
384 	}
385 	if (vp) {
386 		TAILQ_INSERT_TAIL(&nclruhead, ncp, nc_lru);
387 		numcache++;
388 		/* don't put . or .. in the reverse map */
389 		if (vp != dvp && vp->v_type == VDIR &&
390 		    (ncp->nc_nlen > 2 ||
391 			(ncp->nc_nlen > 1 &&
392 			    ncp->nc_name[1] != '.') ||
393 			(ncp->nc_nlen > 0 &&
394 			    ncp->nc_name[0] != '.')))
395 			TAILQ_INSERT_TAIL(&vp->v_cache_dst, ncp,
396 			    nc_me);
397 	} else {
398 		TAILQ_INSERT_TAIL(&nclruneghead, ncp, nc_neg);
399 		numneg++;
400 	}
401 	if (numneg  > desiredvnodes) {
402 		if ((ncp = TAILQ_FIRST(&nclruneghead))
403 		    != NULL)
404 			cache_zap(ncp);
405 	}
406 done:
407 	return;
408 }
409 
410 
411 /*
412  * Name cache initialization, from vfs_init() when we are booting
413  */
414 void
415 nchinit()
416 {
417 	TAILQ_INIT(&nclruhead);
418 	TAILQ_INIT(&nclruneghead);
419 	pool_init(&nch_pool, sizeof(struct namecache), 0, 0, 0, "nchpl",
420 	    &pool_allocator_nointr);
421 }
422 
423 /*
424  * Cache flush, a particular vnode; called when a vnode is renamed to
425  * hide entries that would now be invalid
426  */
427 void
428 cache_purge(struct vnode *vp)
429 {
430 	struct namecache *ncp;
431 
432 	while ((ncp = TAILQ_FIRST(&vp->v_cache_dst)))
433 		cache_zap(ncp);
434 	while ((ncp = RB_ROOT(&vp->v_nc_tree)))
435 		cache_zap(ncp);
436 
437 	/* XXX this blows goats */
438 	vp->v_id = ++nextvnodeid;
439 	if (vp->v_id == 0)
440 		vp->v_id = ++nextvnodeid;
441 }
442 
443 /*
444  * Cache flush, a whole filesystem; called when filesys is umounted to
445  * remove entries that would now be invalid
446  *
447  * The line "nxtcp = nchhead" near the end is to avoid potential problems
448  * if the cache lru chain is modified while we are dumping the
449  * inode.  This makes the algorithm O(n^2), but do you think I care?
450  */
451 void
452 cache_purgevfs(struct mount *mp)
453 {
454 	struct namecache *ncp, *nxtcp;
455 
456 	/* whack the regular entries */
457 	for (ncp = TAILQ_FIRST(&nclruhead); ncp != TAILQ_END(&nclruhead);
458 	    ncp = nxtcp) {
459 		if (ncp->nc_dvp == NULL || ncp->nc_dvp->v_mount != mp) {
460 			nxtcp = TAILQ_NEXT(ncp, nc_lru);
461 			continue;
462 		}
463 		/* free the resources we had */
464 		cache_zap(ncp);
465 		/* cause rescan of list, it may have altered */
466 		nxtcp = TAILQ_FIRST(&nclruhead);
467 	}
468 	/* whack the negative entries */
469 	for (ncp = TAILQ_FIRST(&nclruneghead); ncp != TAILQ_END(&nclruneghead);
470 	    ncp = nxtcp) {
471 		if (ncp->nc_dvp == NULL || ncp->nc_dvp->v_mount != mp) {
472 			nxtcp = TAILQ_NEXT(ncp, nc_neg);
473 			continue;
474 		}
475 		/* free the resources we had */
476 		cache_zap(ncp);
477 		/* cause rescan of list, it may have altered */
478 		nxtcp = TAILQ_FIRST(&nclruneghead);
479 	}
480 }
481