kernel - misc MPSAFe work
[dragonfly.git] / sys / kern / vfs_cache.c
... / ...
CommitLineData
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.91 2008/06/14 05:34:06 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 <sys/dirent.h>
89#include <ddb/ddb.h>
90
91#include <sys/sysref2.h>
92#include <sys/mplock2.h>
93
94#define MAX_RECURSION_DEPTH 64
95
96/*
97 * Random lookups in the cache are accomplished with a hash table using
98 * a hash key of (nc_src_vp, name).
99 *
100 * Negative entries may exist and correspond to structures where nc_vp
101 * is NULL. In a negative entry, NCF_WHITEOUT will be set if the entry
102 * corresponds to a whited-out directory entry (verses simply not finding the
103 * entry at all).
104 *
105 * Upon reaching the last segment of a path, if the reference is for DELETE,
106 * or NOCACHE is set (rewrite), and the name is located in the cache, it
107 * will be dropped.
108 */
109
110/*
111 * Structures associated with name cacheing.
112 */
113#define NCHHASH(hash) (&nchashtbl[(hash) & nchash])
114#define MINNEG 1024
115
116MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
117
118static LIST_HEAD(nchashhead, namecache) *nchashtbl; /* Hash Table */
119static struct namecache_list ncneglist; /* instead of vnode */
120
121/*
122 * ncvp_debug - debug cache_fromvp(). This is used by the NFS server
123 * to create the namecache infrastructure leading to a dangling vnode.
124 *
125 * 0 Only errors are reported
126 * 1 Successes are reported
127 * 2 Successes + the whole directory scan is reported
128 * 3 Force the directory scan code run as if the parent vnode did not
129 * have a namecache record, even if it does have one.
130 */
131static int ncvp_debug;
132SYSCTL_INT(_debug, OID_AUTO, ncvp_debug, CTLFLAG_RW, &ncvp_debug, 0, "");
133
134static u_long nchash; /* size of hash table */
135SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0, "");
136
137static u_long ncnegfactor = 16; /* ratio of negative entries */
138SYSCTL_ULONG(_debug, OID_AUTO, ncnegfactor, CTLFLAG_RW, &ncnegfactor, 0, "");
139
140static int nclockwarn; /* warn on locked entries in ticks */
141SYSCTL_INT(_debug, OID_AUTO, nclockwarn, CTLFLAG_RW, &nclockwarn, 0, "");
142
143static u_long numneg; /* number of cache entries allocated */
144SYSCTL_ULONG(_debug, OID_AUTO, numneg, CTLFLAG_RD, &numneg, 0, "");
145
146static u_long numcache; /* number of cache entries allocated */
147SYSCTL_ULONG(_debug, OID_AUTO, numcache, CTLFLAG_RD, &numcache, 0, "");
148
149static u_long numunres; /* number of unresolved entries */
150SYSCTL_ULONG(_debug, OID_AUTO, numunres, CTLFLAG_RD, &numunres, 0, "");
151
152SYSCTL_INT(_debug, OID_AUTO, vnsize, CTLFLAG_RD, 0, sizeof(struct vnode), "");
153SYSCTL_INT(_debug, OID_AUTO, ncsize, CTLFLAG_RD, 0, sizeof(struct namecache), "");
154
155static int cache_resolve_mp(struct mount *mp);
156static struct vnode *cache_dvpref(struct namecache *ncp);
157static void _cache_rehash(struct namecache *ncp);
158static void _cache_lock(struct namecache *ncp);
159static void _cache_setunresolved(struct namecache *ncp);
160
161/*
162 * The new name cache statistics
163 */
164SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW, 0, "Name cache statistics");
165#define STATNODE(mode, name, var) \
166 SYSCTL_ULONG(_vfs_cache, OID_AUTO, name, mode, var, 0, "");
167STATNODE(CTLFLAG_RD, numneg, &numneg);
168STATNODE(CTLFLAG_RD, numcache, &numcache);
169static u_long numcalls; STATNODE(CTLFLAG_RD, numcalls, &numcalls);
170static u_long dothits; STATNODE(CTLFLAG_RD, dothits, &dothits);
171static u_long dotdothits; STATNODE(CTLFLAG_RD, dotdothits, &dotdothits);
172static u_long numchecks; STATNODE(CTLFLAG_RD, numchecks, &numchecks);
173static u_long nummiss; STATNODE(CTLFLAG_RD, nummiss, &nummiss);
174static u_long nummisszap; STATNODE(CTLFLAG_RD, nummisszap, &nummisszap);
175static u_long numposzaps; STATNODE(CTLFLAG_RD, numposzaps, &numposzaps);
176static u_long numposhits; STATNODE(CTLFLAG_RD, numposhits, &numposhits);
177static u_long numnegzaps; STATNODE(CTLFLAG_RD, numnegzaps, &numnegzaps);
178static u_long numneghits; STATNODE(CTLFLAG_RD, numneghits, &numneghits);
179
180struct nchstats nchstats[SMP_MAXCPU];
181/*
182 * Export VFS cache effectiveness statistics to user-land.
183 *
184 * The statistics are left for aggregation to user-land so
185 * neat things can be achieved, like observing per-CPU cache
186 * distribution.
187 */
188static int
189sysctl_nchstats(SYSCTL_HANDLER_ARGS)
190{
191 struct globaldata *gd;
192 int i, error;
193
194 error = 0;
195 for (i = 0; i < ncpus; ++i) {
196 gd = globaldata_find(i);
197 if ((error = SYSCTL_OUT(req, (void *)&(*gd->gd_nchstats),
198 sizeof(struct nchstats))))
199 break;
200 }
201
202 return (error);
203}
204SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE|CTLFLAG_RD,
205 0, 0, sysctl_nchstats, "S,nchstats", "VFS cache effectiveness statistics");
206
207static void cache_zap(struct namecache *ncp);
208
209/*
210 * cache_hold() and cache_drop() prevent the premature deletion of a
211 * namecache entry but do not prevent operations (such as zapping) on
212 * that namecache entry.
213 *
214 * This routine may only be called from outside this source module if
215 * nc_refs is already at least 1.
216 *
217 * This is a rare case where callers are allowed to hold a spinlock,
218 * so we can't ourselves.
219 *
220 * MPSAFE
221 */
222static __inline
223struct namecache *
224_cache_hold(struct namecache *ncp)
225{
226 atomic_add_int(&ncp->nc_refs, 1);
227 return(ncp);
228}
229
230/*
231 * When dropping an entry, if only one ref remains and the entry has not
232 * been resolved, zap it. Since the one reference is being dropped the
233 * entry had better not be locked.
234 */
235static __inline
236void
237_cache_drop(struct namecache *ncp)
238{
239 KKASSERT(ncp->nc_refs > 0);
240 if (ncp->nc_refs == 1 &&
241 (ncp->nc_flag & NCF_UNRESOLVED) &&
242 TAILQ_EMPTY(&ncp->nc_list)
243 ) {
244 KKASSERT(ncp->nc_exlocks == 0);
245 _cache_lock(ncp);
246 cache_zap(ncp);
247 } else {
248 atomic_subtract_int(&ncp->nc_refs, 1);
249 }
250}
251
252/*
253 * Link a new namecache entry to its parent. Be careful to avoid races
254 * if vhold() blocks in the future.
255 */
256static void
257cache_link_parent(struct namecache *ncp, struct namecache *par)
258{
259 KKASSERT(ncp->nc_parent == NULL);
260 ncp->nc_parent = par;
261 if (TAILQ_EMPTY(&par->nc_list)) {
262 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
263 /*
264 * Any vp associated with an ncp which has children must
265 * be held to prevent it from being recycled.
266 */
267 if (par->nc_vp)
268 vhold(par->nc_vp);
269 } else {
270 TAILQ_INSERT_HEAD(&par->nc_list, ncp, nc_entry);
271 }
272}
273
274/*
275 * Remove the parent association from a namecache structure. If this is
276 * the last child of the parent the cache_drop(par) will attempt to
277 * recursively zap the parent.
278 */
279static void
280cache_unlink_parent(struct namecache *ncp)
281{
282 struct namecache *par;
283
284 if ((par = ncp->nc_parent) != NULL) {
285 ncp->nc_parent = NULL;
286 par = _cache_hold(par);
287 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
288 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
289 vdrop(par->nc_vp);
290 _cache_drop(par);
291 }
292}
293
294/*
295 * Allocate a new namecache structure. Most of the code does not require
296 * zero-termination of the string but it makes vop_compat_ncreate() easier.
297 */
298static struct namecache *
299cache_alloc(int nlen)
300{
301 struct namecache *ncp;
302
303 ncp = kmalloc(sizeof(*ncp), M_VFSCACHE, M_WAITOK|M_ZERO);
304 if (nlen)
305 ncp->nc_name = kmalloc(nlen + 1, M_VFSCACHE, M_WAITOK);
306 ncp->nc_nlen = nlen;
307 ncp->nc_flag = NCF_UNRESOLVED;
308 ncp->nc_error = ENOTCONN; /* needs to be resolved */
309 ncp->nc_refs = 1;
310
311 /*
312 * Construct a fake FSMID based on the time of day and a 32 bit
313 * roller for uniqueness. This is used to generate a useful
314 * FSMID for filesystems which do not support it.
315 */
316 ncp->nc_fsmid = cache_getnewfsmid();
317 TAILQ_INIT(&ncp->nc_list);
318 _cache_lock(ncp);
319 return(ncp);
320}
321
322static void
323_cache_free(struct namecache *ncp)
324{
325 KKASSERT(ncp->nc_refs == 1 && ncp->nc_exlocks == 1);
326 if (ncp->nc_name)
327 kfree(ncp->nc_name, M_VFSCACHE);
328 kfree(ncp, M_VFSCACHE);
329}
330
331void
332cache_zero(struct nchandle *nch)
333{
334 nch->ncp = NULL;
335 nch->mount = NULL;
336}
337
338/*
339 * Ref and deref a namecache structure.
340 *
341 * Warning: caller may hold an unrelated read spinlock, which means we can't
342 * use read spinlocks here.
343 *
344 * MPSAFE if nch is
345 */
346struct nchandle *
347cache_hold(struct nchandle *nch)
348{
349 _cache_hold(nch->ncp);
350 atomic_add_int(&nch->mount->mnt_refs, 1);
351 return(nch);
352}
353
354/*
355 * Create a copy of a namecache handle for an already-referenced
356 * entry.
357 *
358 * MPSAFE if nch is
359 */
360void
361cache_copy(struct nchandle *nch, struct nchandle *target)
362{
363 *target = *nch;
364 _cache_hold(target->ncp);
365 atomic_add_int(&nch->mount->mnt_refs, 1);
366}
367
368/*
369 * MPSAFE if nch is
370 */
371void
372cache_changemount(struct nchandle *nch, struct mount *mp)
373{
374 atomic_add_int(&nch->mount->mnt_refs, -1);
375 nch->mount = mp;
376 atomic_add_int(&nch->mount->mnt_refs, 1);
377}
378
379void
380cache_drop(struct nchandle *nch)
381{
382 atomic_add_int(&nch->mount->mnt_refs, -1);
383 _cache_drop(nch->ncp);
384 nch->ncp = NULL;
385 nch->mount = NULL;
386}
387
388/*
389 * Namespace locking. The caller must already hold a reference to the
390 * namecache structure in order to lock/unlock it. This function prevents
391 * the namespace from being created or destroyed by accessors other then
392 * the lock holder.
393 *
394 * Note that holding a locked namecache structure prevents other threads
395 * from making namespace changes (e.g. deleting or creating), prevents
396 * vnode association state changes by other threads, and prevents the
397 * namecache entry from being resolved or unresolved by other threads.
398 *
399 * The lock owner has full authority to associate/disassociate vnodes
400 * and resolve/unresolve the locked ncp.
401 *
402 * WARNING! Holding a locked ncp will prevent a vnode from being destroyed
403 * or recycled, but it does NOT help you if the vnode had already initiated
404 * a recyclement. If this is important, use cache_get() rather then
405 * cache_lock() (and deal with the differences in the way the refs counter
406 * is handled). Or, alternatively, make an unconditional call to
407 * cache_validate() or cache_resolve() after cache_lock() returns.
408 */
409static
410void
411_cache_lock(struct namecache *ncp)
412{
413 thread_t td;
414 int didwarn;
415
416 KKASSERT(ncp->nc_refs != 0);
417 didwarn = 0;
418 td = curthread;
419
420 for (;;) {
421 if (ncp->nc_exlocks == 0) {
422 ncp->nc_exlocks = 1;
423 ncp->nc_locktd = td;
424 /*
425 * The vp associated with a locked ncp must be held
426 * to prevent it from being recycled (which would
427 * cause the ncp to become unresolved).
428 *
429 * WARNING! If VRECLAIMED is set the vnode could
430 * already be in the middle of a recycle. Callers
431 * should not assume that nc_vp is usable when
432 * not NULL. cache_vref() or cache_vget() must be
433 * called.
434 *
435 * XXX loop on race for later MPSAFE work.
436 */
437 if (ncp->nc_vp)
438 vhold(ncp->nc_vp);
439 break;
440 }
441 if (ncp->nc_locktd == td) {
442 ++ncp->nc_exlocks;
443 break;
444 }
445 ncp->nc_flag |= NCF_LOCKREQ;
446 if (tsleep(ncp, 0, "clock", nclockwarn) == EWOULDBLOCK) {
447 if (didwarn)
448 continue;
449 didwarn = 1;
450 kprintf("[diagnostic] cache_lock: blocked on %p", ncp);
451 kprintf(" \"%*.*s\"\n",
452 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
453 }
454 }
455
456 if (didwarn == 1) {
457 kprintf("[diagnostic] cache_lock: unblocked %*.*s\n",
458 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
459 }
460}
461
462void
463cache_lock(struct nchandle *nch)
464{
465 _cache_lock(nch->ncp);
466}
467
468static
469int
470_cache_lock_nonblock(struct namecache *ncp)
471{
472 thread_t td;
473
474 KKASSERT(ncp->nc_refs != 0);
475 td = curthread;
476 if (ncp->nc_exlocks == 0) {
477 ncp->nc_exlocks = 1;
478 ncp->nc_locktd = td;
479 /*
480 * The vp associated with a locked ncp must be held
481 * to prevent it from being recycled (which would
482 * cause the ncp to become unresolved).
483 *
484 * WARNING! If VRECLAIMED is set the vnode could
485 * already be in the middle of a recycle. Callers
486 * should not assume that nc_vp is usable when
487 * not NULL. cache_vref() or cache_vget() must be
488 * called.
489 *
490 * XXX loop on race for later MPSAFE work.
491 */
492 if (ncp->nc_vp)
493 vhold(ncp->nc_vp);
494 return(0);
495 } else {
496 return(EWOULDBLOCK);
497 }
498}
499
500int
501cache_lock_nonblock(struct nchandle *nch)
502{
503 return(_cache_lock_nonblock(nch->ncp));
504}
505
506static
507void
508_cache_unlock(struct namecache *ncp)
509{
510 thread_t td __debugvar = curthread;
511
512 KKASSERT(ncp->nc_refs > 0);
513 KKASSERT(ncp->nc_exlocks > 0);
514 KKASSERT(ncp->nc_locktd == td);
515 if (--ncp->nc_exlocks == 0) {
516 if (ncp->nc_vp)
517 vdrop(ncp->nc_vp);
518 ncp->nc_locktd = NULL;
519 if (ncp->nc_flag & NCF_LOCKREQ) {
520 ncp->nc_flag &= ~NCF_LOCKREQ;
521 wakeup(ncp);
522 }
523 }
524}
525
526void
527cache_unlock(struct nchandle *nch)
528{
529 _cache_unlock(nch->ncp);
530}
531
532/*
533 * ref-and-lock, unlock-and-deref functions.
534 *
535 * This function is primarily used by nlookup. Even though cache_lock
536 * holds the vnode, it is possible that the vnode may have already
537 * initiated a recyclement. We want cache_get() to return a definitively
538 * usable vnode or a definitively unresolved ncp.
539 */
540static
541struct namecache *
542_cache_get(struct namecache *ncp)
543{
544 _cache_hold(ncp);
545 _cache_lock(ncp);
546 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
547 _cache_setunresolved(ncp);
548 return(ncp);
549}
550
551/*
552 * note: the same nchandle can be passed for both arguments.
553 */
554void
555cache_get(struct nchandle *nch, struct nchandle *target)
556{
557 target->mount = nch->mount;
558 target->ncp = _cache_get(nch->ncp);
559 atomic_add_int(&target->mount->mnt_refs, 1);
560}
561
562static int
563_cache_get_nonblock(struct namecache *ncp)
564{
565 /* XXX MP */
566 if (ncp->nc_exlocks == 0 || ncp->nc_locktd == curthread) {
567 _cache_hold(ncp);
568 _cache_lock(ncp);
569 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
570 _cache_setunresolved(ncp);
571 return(0);
572 }
573 return(EWOULDBLOCK);
574}
575
576int
577cache_get_nonblock(struct nchandle *nch)
578{
579 int error;
580
581 if ((error = _cache_get_nonblock(nch->ncp)) == 0)
582 atomic_add_int(&nch->mount->mnt_refs, 1);
583 return (error);
584}
585
586static __inline
587void
588_cache_put(struct namecache *ncp)
589{
590 _cache_unlock(ncp);
591 _cache_drop(ncp);
592}
593
594void
595cache_put(struct nchandle *nch)
596{
597 atomic_add_int(&nch->mount->mnt_refs, -1);
598 _cache_put(nch->ncp);
599 nch->ncp = NULL;
600 nch->mount = NULL;
601}
602
603/*
604 * Resolve an unresolved ncp by associating a vnode with it. If the
605 * vnode is NULL, a negative cache entry is created.
606 *
607 * The ncp should be locked on entry and will remain locked on return.
608 */
609static
610void
611_cache_setvp(struct mount *mp, struct namecache *ncp, struct vnode *vp)
612{
613 KKASSERT(ncp->nc_flag & NCF_UNRESOLVED);
614 ncp->nc_vp = vp;
615 if (vp != NULL) {
616 /*
617 * Any vp associated with an ncp which has children must
618 * be held. Any vp associated with a locked ncp must be held.
619 */
620 if (!TAILQ_EMPTY(&ncp->nc_list))
621 vhold(vp);
622 TAILQ_INSERT_HEAD(&vp->v_namecache, ncp, nc_vnode);
623 if (ncp->nc_exlocks)
624 vhold(vp);
625
626 /*
627 * Set auxiliary flags
628 */
629 switch(vp->v_type) {
630 case VDIR:
631 ncp->nc_flag |= NCF_ISDIR;
632 break;
633 case VLNK:
634 ncp->nc_flag |= NCF_ISSYMLINK;
635 /* XXX cache the contents of the symlink */
636 break;
637 default:
638 break;
639 }
640 ++numcache;
641 ncp->nc_error = 0;
642 } else {
643 /*
644 * When creating a negative cache hit we set the
645 * namecache_gen. A later resolve will clean out the
646 * negative cache hit if the mount point's namecache_gen
647 * has changed. Used by devfs, could also be used by
648 * other remote FSs.
649 */
650 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
651 ++numneg;
652 ncp->nc_error = ENOENT;
653 if (mp)
654 ncp->nc_namecache_gen = mp->mnt_namecache_gen;
655 }
656 ncp->nc_flag &= ~NCF_UNRESOLVED;
657}
658
659void
660cache_setvp(struct nchandle *nch, struct vnode *vp)
661{
662 _cache_setvp(nch->mount, nch->ncp, vp);
663}
664
665void
666cache_settimeout(struct nchandle *nch, int nticks)
667{
668 struct namecache *ncp = nch->ncp;
669
670 if ((ncp->nc_timeout = ticks + nticks) == 0)
671 ncp->nc_timeout = 1;
672}
673
674/*
675 * Disassociate the vnode or negative-cache association and mark a
676 * namecache entry as unresolved again. Note that the ncp is still
677 * left in the hash table and still linked to its parent.
678 *
679 * The ncp should be locked and refd on entry and will remain locked and refd
680 * on return.
681 *
682 * This routine is normally never called on a directory containing children.
683 * However, NFS often does just that in its rename() code as a cop-out to
684 * avoid complex namespace operations. This disconnects a directory vnode
685 * from its namecache and can cause the OLDAPI and NEWAPI to get out of
686 * sync.
687 *
688 * NOTE: NCF_FSMID must be cleared so a refurbishment of the ncp, such as
689 * in a create, properly propogates flag up the chain.
690 */
691static
692void
693_cache_setunresolved(struct namecache *ncp)
694{
695 struct vnode *vp;
696
697 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
698 ncp->nc_flag |= NCF_UNRESOLVED;
699 ncp->nc_timeout = 0;
700 ncp->nc_error = ENOTCONN;
701 ++numunres;
702 if ((vp = ncp->nc_vp) != NULL) {
703 --numcache;
704 ncp->nc_vp = NULL;
705 TAILQ_REMOVE(&vp->v_namecache, ncp, nc_vnode);
706
707 /*
708 * Any vp associated with an ncp with children is
709 * held by that ncp. Any vp associated with a locked
710 * ncp is held by that ncp. These conditions must be
711 * undone when the vp is cleared out from the ncp.
712 */
713 if (ncp->nc_flag & NCF_FSMID)
714 vupdatefsmid(vp);
715 if (!TAILQ_EMPTY(&ncp->nc_list))
716 vdrop(vp);
717 if (ncp->nc_exlocks)
718 vdrop(vp);
719 } else {
720 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
721 --numneg;
722 }
723 ncp->nc_flag &= ~(NCF_WHITEOUT|NCF_ISDIR|NCF_ISSYMLINK|
724 NCF_FSMID);
725 }
726}
727
728/*
729 * The cache_nresolve() code calls this function to automatically
730 * set a resolved cache element to unresolved if it has timed out
731 * or if it is a negative cache hit and the mount point namecache_gen
732 * has changed.
733 */
734static __inline void
735_cache_auto_unresolve(struct mount *mp, struct namecache *ncp)
736{
737 /*
738 * Already in an unresolved state, nothing to do.
739 */
740 if (ncp->nc_flag & NCF_UNRESOLVED)
741 return;
742
743 /*
744 * Try to zap entries that have timed out. We have
745 * to be careful here because locked leafs may depend
746 * on the vnode remaining intact in a parent, so only
747 * do this under very specific conditions.
748 */
749 if (ncp->nc_timeout && (int)(ncp->nc_timeout - ticks) < 0 &&
750 TAILQ_EMPTY(&ncp->nc_list)) {
751 _cache_setunresolved(ncp);
752 return;
753 }
754
755 /*
756 * If a resolved negative cache hit is invalid due to
757 * the mount's namecache generation being bumped, zap it.
758 */
759 if (ncp->nc_vp == NULL &&
760 ncp->nc_namecache_gen != mp->mnt_namecache_gen) {
761 _cache_setunresolved(ncp);
762 return;
763 }
764}
765
766void
767cache_setunresolved(struct nchandle *nch)
768{
769 _cache_setunresolved(nch->ncp);
770}
771
772/*
773 * Determine if we can clear NCF_ISMOUNTPT by scanning the mountlist
774 * looking for matches. This flag tells the lookup code when it must
775 * check for a mount linkage and also prevents the directories in question
776 * from being deleted or renamed.
777 */
778static
779int
780cache_clrmountpt_callback(struct mount *mp, void *data)
781{
782 struct nchandle *nch = data;
783
784 if (mp->mnt_ncmounton.ncp == nch->ncp)
785 return(1);
786 if (mp->mnt_ncmountpt.ncp == nch->ncp)
787 return(1);
788 return(0);
789}
790
791void
792cache_clrmountpt(struct nchandle *nch)
793{
794 int count;
795
796 count = mountlist_scan(cache_clrmountpt_callback, nch,
797 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
798 if (count == 0)
799 nch->ncp->nc_flag &= ~NCF_ISMOUNTPT;
800}
801
802/*
803 * Invalidate portions of the namecache topology given a starting entry.
804 * The passed ncp is set to an unresolved state and:
805 *
806 * The passed ncp must be locked.
807 *
808 * CINV_DESTROY - Set a flag in the passed ncp entry indicating
809 * that the physical underlying nodes have been
810 * destroyed... as in deleted. For example, when
811 * a directory is removed. This will cause record
812 * lookups on the name to no longer be able to find
813 * the record and tells the resolver to return failure
814 * rather then trying to resolve through the parent.
815 *
816 * The topology itself, including ncp->nc_name,
817 * remains intact.
818 *
819 * This only applies to the passed ncp, if CINV_CHILDREN
820 * is specified the children are not flagged.
821 *
822 * CINV_CHILDREN - Set all children (recursively) to an unresolved
823 * state as well.
824 *
825 * Note that this will also have the side effect of
826 * cleaning out any unreferenced nodes in the topology
827 * from the leaves up as the recursion backs out.
828 *
829 * Note that the topology for any referenced nodes remains intact.
830 *
831 * It is possible for cache_inval() to race a cache_resolve(), meaning that
832 * the namecache entry may not actually be invalidated on return if it was
833 * revalidated while recursing down into its children. This code guarentees
834 * that the node(s) will go through an invalidation cycle, but does not
835 * guarentee that they will remain in an invalidated state.
836 *
837 * Returns non-zero if a revalidation was detected during the invalidation
838 * recursion, zero otherwise. Note that since only the original ncp is
839 * locked the revalidation ultimately can only indicate that the original ncp
840 * *MIGHT* no have been reresolved.
841 *
842 * DEEP RECURSION HANDLING - If a recursive invalidation recurses deeply we
843 * have to avoid blowing out the kernel stack. We do this by saving the
844 * deep namecache node and aborting the recursion, then re-recursing at that
845 * node using a depth-first algorithm in order to allow multiple deep
846 * recursions to chain through each other, then we restart the invalidation
847 * from scratch.
848 */
849
850struct cinvtrack {
851 struct namecache *resume_ncp;
852 int depth;
853};
854
855static int _cache_inval_internal(struct namecache *, int, struct cinvtrack *);
856
857static
858int
859_cache_inval(struct namecache *ncp, int flags)
860{
861 struct cinvtrack track;
862 struct namecache *ncp2;
863 int r;
864
865 track.depth = 0;
866 track.resume_ncp = NULL;
867
868 for (;;) {
869 r = _cache_inval_internal(ncp, flags, &track);
870 if (track.resume_ncp == NULL)
871 break;
872 kprintf("Warning: deep namecache recursion at %s\n",
873 ncp->nc_name);
874 _cache_unlock(ncp);
875 while ((ncp2 = track.resume_ncp) != NULL) {
876 track.resume_ncp = NULL;
877 _cache_lock(ncp2);
878 _cache_inval_internal(ncp2, flags & ~CINV_DESTROY,
879 &track);
880 _cache_put(ncp2);
881 }
882 _cache_lock(ncp);
883 }
884 return(r);
885}
886
887int
888cache_inval(struct nchandle *nch, int flags)
889{
890 return(_cache_inval(nch->ncp, flags));
891}
892
893static int
894_cache_inval_internal(struct namecache *ncp, int flags, struct cinvtrack *track)
895{
896 struct namecache *kid;
897 struct namecache *nextkid;
898 int rcnt = 0;
899
900 KKASSERT(ncp->nc_exlocks);
901
902 _cache_setunresolved(ncp);
903 if (flags & CINV_DESTROY)
904 ncp->nc_flag |= NCF_DESTROYED;
905
906 if ((flags & CINV_CHILDREN) &&
907 (kid = TAILQ_FIRST(&ncp->nc_list)) != NULL
908 ) {
909 if (++track->depth > MAX_RECURSION_DEPTH) {
910 track->resume_ncp = ncp;
911 _cache_hold(ncp);
912 ++rcnt;
913 }
914 _cache_hold(kid);
915 _cache_unlock(ncp);
916 while (kid) {
917 if (track->resume_ncp) {
918 _cache_drop(kid);
919 break;
920 }
921 if ((nextkid = TAILQ_NEXT(kid, nc_entry)) != NULL)
922 _cache_hold(nextkid);
923 if ((kid->nc_flag & NCF_UNRESOLVED) == 0 ||
924 TAILQ_FIRST(&kid->nc_list)
925 ) {
926 _cache_lock(kid);
927 rcnt += _cache_inval_internal(kid, flags & ~CINV_DESTROY, track);
928 _cache_unlock(kid);
929 }
930 _cache_drop(kid);
931 kid = nextkid;
932 }
933 --track->depth;
934 _cache_lock(ncp);
935 }
936
937 /*
938 * Someone could have gotten in there while ncp was unlocked,
939 * retry if so.
940 */
941 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
942 ++rcnt;
943 return (rcnt);
944}
945
946/*
947 * Invalidate a vnode's namecache associations. To avoid races against
948 * the resolver we do not invalidate a node which we previously invalidated
949 * but which was then re-resolved while we were in the invalidation loop.
950 *
951 * Returns non-zero if any namecache entries remain after the invalidation
952 * loop completed.
953 *
954 * NOTE: unlike the namecache topology which guarentees that ncp's will not
955 * be ripped out of the topology while held, the vnode's v_namecache list
956 * has no such restriction. NCP's can be ripped out of the list at virtually
957 * any time if not locked, even if held.
958 */
959int
960cache_inval_vp(struct vnode *vp, int flags)
961{
962 struct namecache *ncp;
963 struct namecache *next;
964
965restart:
966 ncp = TAILQ_FIRST(&vp->v_namecache);
967 if (ncp)
968 _cache_hold(ncp);
969 while (ncp) {
970 /* loop entered with ncp held */
971 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
972 _cache_hold(next);
973 _cache_lock(ncp);
974 if (ncp->nc_vp != vp) {
975 kprintf("Warning: cache_inval_vp: race-A detected on "
976 "%s\n", ncp->nc_name);
977 _cache_put(ncp);
978 if (next)
979 _cache_drop(next);
980 goto restart;
981 }
982 _cache_inval(ncp, flags);
983 _cache_put(ncp); /* also releases reference */
984 ncp = next;
985 if (ncp && ncp->nc_vp != vp) {
986 kprintf("Warning: cache_inval_vp: race-B detected on "
987 "%s\n", ncp->nc_name);
988 _cache_drop(ncp);
989 goto restart;
990 }
991 }
992 return(TAILQ_FIRST(&vp->v_namecache) != NULL);
993}
994
995/*
996 * This routine is used instead of the normal cache_inval_vp() when we
997 * are trying to recycle otherwise good vnodes.
998 *
999 * Return 0 on success, non-zero if not all namecache records could be
1000 * disassociated from the vnode (for various reasons).
1001 */
1002int
1003cache_inval_vp_nonblock(struct vnode *vp)
1004{
1005 struct namecache *ncp;
1006 struct namecache *next;
1007
1008 ncp = TAILQ_FIRST(&vp->v_namecache);
1009 if (ncp)
1010 _cache_hold(ncp);
1011 while (ncp) {
1012 /* loop entered with ncp held */
1013 if ((next = TAILQ_NEXT(ncp, nc_vnode)) != NULL)
1014 _cache_hold(next);
1015 if (_cache_lock_nonblock(ncp)) {
1016 _cache_drop(ncp);
1017 if (next)
1018 _cache_drop(next);
1019 break;
1020 }
1021 if (ncp->nc_vp != vp) {
1022 kprintf("Warning: cache_inval_vp: race-A detected on "
1023 "%s\n", ncp->nc_name);
1024 _cache_put(ncp);
1025 if (next)
1026 _cache_drop(next);
1027 break;
1028 }
1029 _cache_inval(ncp, 0);
1030 _cache_put(ncp); /* also releases reference */
1031 ncp = next;
1032 if (ncp && ncp->nc_vp != vp) {
1033 kprintf("Warning: cache_inval_vp: race-B detected on "
1034 "%s\n", ncp->nc_name);
1035 _cache_drop(ncp);
1036 break;
1037 }
1038 }
1039 return(TAILQ_FIRST(&vp->v_namecache) != NULL);
1040}
1041
1042/*
1043 * The source ncp has been renamed to the target ncp. Both fncp and tncp
1044 * must be locked. The target ncp is destroyed (as a normal rename-over
1045 * would destroy the target file or directory).
1046 *
1047 * Because there may be references to the source ncp we cannot copy its
1048 * contents to the target. Instead the source ncp is relinked as the target
1049 * and the target ncp is removed from the namecache topology.
1050 */
1051void
1052cache_rename(struct nchandle *fnch, struct nchandle *tnch)
1053{
1054 struct namecache *fncp = fnch->ncp;
1055 struct namecache *tncp = tnch->ncp;
1056 char *oname;
1057
1058 _cache_setunresolved(tncp);
1059 cache_unlink_parent(fncp);
1060 cache_link_parent(fncp, tncp->nc_parent);
1061 cache_unlink_parent(tncp);
1062 oname = fncp->nc_name;
1063 fncp->nc_name = tncp->nc_name;
1064 fncp->nc_nlen = tncp->nc_nlen;
1065 tncp->nc_name = NULL;
1066 tncp->nc_nlen = 0;
1067 if (fncp->nc_flag & NCF_HASHED)
1068 _cache_rehash(fncp);
1069 if (tncp->nc_flag & NCF_HASHED)
1070 _cache_rehash(tncp);
1071 if (oname)
1072 kfree(oname, M_VFSCACHE);
1073}
1074
1075/*
1076 * vget the vnode associated with the namecache entry. Resolve the namecache
1077 * entry if necessary and deal with namecache/vp races. The passed ncp must
1078 * be referenced and may be locked. The ncp's ref/locking state is not
1079 * effected by this call.
1080 *
1081 * lk_type may be LK_SHARED, LK_EXCLUSIVE. A ref'd, possibly locked
1082 * (depending on the passed lk_type) will be returned in *vpp with an error
1083 * of 0, or NULL will be returned in *vpp with a non-0 error code. The
1084 * most typical error is ENOENT, meaning that the ncp represents a negative
1085 * cache hit and there is no vnode to retrieve, but other errors can occur
1086 * too.
1087 *
1088 * The main race we have to deal with are namecache zaps. The ncp itself
1089 * will not disappear since it is referenced, and it turns out that the
1090 * validity of the vp pointer can be checked simply by rechecking the
1091 * contents of ncp->nc_vp.
1092 */
1093int
1094cache_vget(struct nchandle *nch, struct ucred *cred,
1095 int lk_type, struct vnode **vpp)
1096{
1097 struct namecache *ncp;
1098 struct vnode *vp;
1099 int error;
1100
1101 ncp = nch->ncp;
1102again:
1103 vp = NULL;
1104 if (ncp->nc_flag & NCF_UNRESOLVED) {
1105 _cache_lock(ncp);
1106 error = cache_resolve(nch, cred);
1107 _cache_unlock(ncp);
1108 } else {
1109 error = 0;
1110 }
1111 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1112 /*
1113 * Accessing the vnode from the namecache is a bit
1114 * dangerous. Because there are no refs on the vnode, it
1115 * could be in the middle of a reclaim.
1116 */
1117 if (vp->v_flag & VRECLAIMED) {
1118 kprintf("Warning: vnode reclaim race detected in cache_vget on %p (%s)\n", vp, ncp->nc_name);
1119 _cache_lock(ncp);
1120 _cache_setunresolved(ncp);
1121 _cache_unlock(ncp);
1122 goto again;
1123 }
1124 error = vget(vp, lk_type);
1125 if (error) {
1126 if (vp != ncp->nc_vp)
1127 goto again;
1128 vp = NULL;
1129 } else if (vp != ncp->nc_vp) {
1130 vput(vp);
1131 goto again;
1132 } else if (vp->v_flag & VRECLAIMED) {
1133 panic("vget succeeded on a VRECLAIMED node! vp %p", vp);
1134 }
1135 }
1136 if (error == 0 && vp == NULL)
1137 error = ENOENT;
1138 *vpp = vp;
1139 return(error);
1140}
1141
1142int
1143cache_vref(struct nchandle *nch, struct ucred *cred, struct vnode **vpp)
1144{
1145 struct namecache *ncp;
1146 struct vnode *vp;
1147 int error;
1148
1149 ncp = nch->ncp;
1150
1151again:
1152 vp = NULL;
1153 if (ncp->nc_flag & NCF_UNRESOLVED) {
1154 _cache_lock(ncp);
1155 error = cache_resolve(nch, cred);
1156 _cache_unlock(ncp);
1157 } else {
1158 error = 0;
1159 }
1160 if (error == 0 && (vp = ncp->nc_vp) != NULL) {
1161 /*
1162 * Since we did not obtain any locks, a cache zap
1163 * race can occur here if the vnode is in the middle
1164 * of being reclaimed and has not yet been able to
1165 * clean out its cache node. If that case occurs,
1166 * we must lock and unresolve the cache, then loop
1167 * to retry.
1168 */
1169 if ((error = vget(vp, LK_SHARED)) != 0) {
1170 if (error == ENOENT) {
1171 kprintf("Warning: vnode reclaim race detected on cache_vref %p (%s)\n", vp, ncp->nc_name);
1172 _cache_lock(ncp);
1173 _cache_setunresolved(ncp);
1174 _cache_unlock(ncp);
1175 goto again;
1176 }
1177 /* fatal error */
1178 } else {
1179 /* caller does not want a lock */
1180 vn_unlock(vp);
1181 }
1182 }
1183 if (error == 0 && vp == NULL)
1184 error = ENOENT;
1185 *vpp = vp;
1186 return(error);
1187}
1188
1189/*
1190 * Return a referenced vnode representing the parent directory of
1191 * ncp. Because the caller has locked the ncp it should not be possible for
1192 * the parent ncp to go away.
1193 *
1194 * However, we might race against the parent dvp and not be able to
1195 * reference it. If we race, return NULL.
1196 */
1197static struct vnode *
1198cache_dvpref(struct namecache *ncp)
1199{
1200 struct namecache *par;
1201 struct vnode *dvp;
1202
1203 dvp = NULL;
1204 if ((par = ncp->nc_parent) != NULL) {
1205 if ((par->nc_flag & NCF_UNRESOLVED) == 0) {
1206 if ((dvp = par->nc_vp) != NULL) {
1207 if (vget(dvp, LK_SHARED) == 0) {
1208 vn_unlock(dvp);
1209 /* return referenced, unlocked dvp */
1210 } else {
1211 dvp = NULL;
1212 }
1213 }
1214 }
1215 }
1216 return(dvp);
1217}
1218
1219/*
1220 * Recursively set the FSMID update flag for namecache nodes leading
1221 * to root. This will cause the next getattr or reclaim to increment the
1222 * fsmid and mark the inode for lazy updating.
1223 *
1224 * Stop recursing when we hit a node whos NCF_FSMID flag is already set.
1225 * This makes FSMIDs work in an Einsteinian fashion - where the observation
1226 * effects the result. In this case a program monitoring a higher level
1227 * node will have detected some prior change and started its scan (clearing
1228 * NCF_FSMID in higher level nodes), but since it has not yet observed the
1229 * node where we find NCF_FSMID still set, we can safely make the related
1230 * modification without interfering with the theorized program.
1231 *
1232 * This also means that FSMIDs cannot represent time-domain quantities
1233 * in a hierarchical sense. But the main reason for doing it this way
1234 * is to reduce the amount of recursion that occurs in the critical path
1235 * when e.g. a program is writing to a file that sits deep in a directory
1236 * hierarchy.
1237 */
1238void
1239cache_update_fsmid(struct nchandle *nch)
1240{
1241 struct namecache *ncp;
1242 struct namecache *scan;
1243 struct vnode *vp;
1244
1245 ncp = nch->ncp;
1246
1247 /*
1248 * Warning: even if we get a non-NULL vp it could still be in the
1249 * middle of a recyclement. Don't do anything fancy, just set
1250 * NCF_FSMID.
1251 */
1252 if ((vp = ncp->nc_vp) != NULL) {
1253 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1254 for (scan = ncp; scan; scan = scan->nc_parent) {
1255 if (scan->nc_flag & NCF_FSMID)
1256 break;
1257 scan->nc_flag |= NCF_FSMID;
1258 }
1259 }
1260 } else {
1261 while (ncp && (ncp->nc_flag & NCF_FSMID) == 0) {
1262 ncp->nc_flag |= NCF_FSMID;
1263 ncp = ncp->nc_parent;
1264 }
1265 }
1266}
1267
1268void
1269cache_update_fsmid_vp(struct vnode *vp)
1270{
1271 struct namecache *ncp;
1272 struct namecache *scan;
1273
1274 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1275 for (scan = ncp; scan; scan = scan->nc_parent) {
1276 if (scan->nc_flag & NCF_FSMID)
1277 break;
1278 scan->nc_flag |= NCF_FSMID;
1279 }
1280 }
1281}
1282
1283/*
1284 * If getattr is called on a vnode (e.g. a stat call), the filesystem
1285 * may call this routine to determine if the namecache has the hierarchical
1286 * change flag set, requiring the fsmid to be updated.
1287 *
1288 * Since 0 indicates no support, make sure the filesystem fsmid is at least
1289 * 1.
1290 */
1291int
1292cache_check_fsmid_vp(struct vnode *vp, int64_t *fsmid)
1293{
1294 struct namecache *ncp;
1295 int changed = 0;
1296
1297 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1298 if (ncp->nc_flag & NCF_FSMID) {
1299 ncp->nc_flag &= ~NCF_FSMID;
1300 changed = 1;
1301 }
1302 }
1303 if (*fsmid == 0)
1304 ++*fsmid;
1305 if (changed)
1306 ++*fsmid;
1307 return(changed);
1308}
1309
1310/*
1311 * Obtain the FSMID for a vnode for filesystems which do not support
1312 * a built-in FSMID.
1313 */
1314int64_t
1315cache_sync_fsmid_vp(struct vnode *vp)
1316{
1317 struct namecache *ncp;
1318
1319 if ((ncp = TAILQ_FIRST(&vp->v_namecache)) != NULL) {
1320 if (ncp->nc_flag & NCF_FSMID) {
1321 ncp->nc_flag &= ~NCF_FSMID;
1322 ++ncp->nc_fsmid;
1323 }
1324 return(ncp->nc_fsmid);
1325 }
1326 return(VNOVAL);
1327}
1328
1329/*
1330 * Convert a directory vnode to a namecache record without any other
1331 * knowledge of the topology. This ONLY works with directory vnodes and
1332 * is ONLY used by the NFS server. dvp must be refd but unlocked, and the
1333 * returned ncp (if not NULL) will be held and unlocked.
1334 *
1335 * If 'makeit' is 0 and dvp has no existing namecache record, NULL is returned.
1336 * If 'makeit' is 1 we attempt to track-down and create the namecache topology
1337 * for dvp. This will fail only if the directory has been deleted out from
1338 * under the caller.
1339 *
1340 * Callers must always check for a NULL return no matter the value of 'makeit'.
1341 *
1342 * To avoid underflowing the kernel stack each recursive call increments
1343 * the makeit variable.
1344 */
1345
1346static int cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1347 struct vnode *dvp, char *fakename);
1348static int cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1349 struct vnode **saved_dvp);
1350
1351int
1352cache_fromdvp(struct vnode *dvp, struct ucred *cred, int makeit,
1353 struct nchandle *nch)
1354{
1355 struct vnode *saved_dvp;
1356 struct vnode *pvp;
1357 char *fakename;
1358 int error;
1359
1360 nch->ncp = NULL;
1361 nch->mount = dvp->v_mount;
1362 saved_dvp = NULL;
1363 fakename = NULL;
1364
1365 /*
1366 * Temporary debugging code to force the directory scanning code
1367 * to be exercised.
1368 */
1369 if (ncvp_debug >= 3 && makeit && TAILQ_FIRST(&dvp->v_namecache)) {
1370 nch->ncp = TAILQ_FIRST(&dvp->v_namecache);
1371 kprintf("cache_fromdvp: forcing %s\n", nch->ncp->nc_name);
1372 goto force;
1373 }
1374
1375 /*
1376 * Loop until resolution, inside code will break out on error.
1377 */
1378 while ((nch->ncp = TAILQ_FIRST(&dvp->v_namecache)) == NULL && makeit) {
1379force:
1380 /*
1381 * If dvp is the root of its filesystem it should already
1382 * have a namecache pointer associated with it as a side
1383 * effect of the mount, but it may have been disassociated.
1384 */
1385 if (dvp->v_flag & VROOT) {
1386 nch->ncp = _cache_get(nch->mount->mnt_ncmountpt.ncp);
1387 error = cache_resolve_mp(nch->mount);
1388 _cache_put(nch->ncp);
1389 if (ncvp_debug) {
1390 kprintf("cache_fromdvp: resolve root of mount %p error %d",
1391 dvp->v_mount, error);
1392 }
1393 if (error) {
1394 if (ncvp_debug)
1395 kprintf(" failed\n");
1396 nch->ncp = NULL;
1397 break;
1398 }
1399 if (ncvp_debug)
1400 kprintf(" succeeded\n");
1401 continue;
1402 }
1403
1404 /*
1405 * If we are recursed too deeply resort to an O(n^2)
1406 * algorithm to resolve the namecache topology. The
1407 * resolved pvp is left referenced in saved_dvp to
1408 * prevent the tree from being destroyed while we loop.
1409 */
1410 if (makeit > 20) {
1411 error = cache_fromdvp_try(dvp, cred, &saved_dvp);
1412 if (error) {
1413 kprintf("lookupdotdot(longpath) failed %d "
1414 "dvp %p\n", error, dvp);
1415 nch->ncp = NULL;
1416 break;
1417 }
1418 continue;
1419 }
1420
1421 /*
1422 * Get the parent directory and resolve its ncp.
1423 */
1424 if (fakename) {
1425 kfree(fakename, M_TEMP);
1426 fakename = NULL;
1427 }
1428 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
1429 &fakename);
1430 if (error) {
1431 kprintf("lookupdotdot failed %d dvp %p\n", error, dvp);
1432 break;
1433 }
1434 vn_unlock(pvp);
1435
1436 /*
1437 * Reuse makeit as a recursion depth counter. On success
1438 * nch will be fully referenced.
1439 */
1440 cache_fromdvp(pvp, cred, makeit + 1, nch);
1441 vrele(pvp);
1442 if (nch->ncp == NULL)
1443 break;
1444
1445 /*
1446 * Do an inefficient scan of pvp (embodied by ncp) to look
1447 * for dvp. This will create a namecache record for dvp on
1448 * success. We loop up to recheck on success.
1449 *
1450 * ncp and dvp are both held but not locked.
1451 */
1452 error = cache_inefficient_scan(nch, cred, dvp, fakename);
1453 if (error) {
1454 kprintf("cache_fromdvp: scan %p (%s) failed on dvp=%p\n",
1455 pvp, nch->ncp->nc_name, dvp);
1456 cache_drop(nch);
1457 /* nch was NULLed out, reload mount */
1458 nch->mount = dvp->v_mount;
1459 break;
1460 }
1461 if (ncvp_debug) {
1462 kprintf("cache_fromdvp: scan %p (%s) succeeded\n",
1463 pvp, nch->ncp->nc_name);
1464 }
1465 cache_drop(nch);
1466 /* nch was NULLed out, reload mount */
1467 nch->mount = dvp->v_mount;
1468 }
1469
1470 if (fakename)
1471 kfree(fakename, M_TEMP);
1472
1473 /*
1474 * hold it for real so the mount gets a ref
1475 */
1476 if (nch->ncp)
1477 cache_hold(nch);
1478 if (saved_dvp)
1479 vrele(saved_dvp);
1480 if (nch->ncp)
1481 return (0);
1482 return (EINVAL);
1483}
1484
1485/*
1486 * Go up the chain of parent directories until we find something
1487 * we can resolve into the namecache. This is very inefficient.
1488 */
1489static
1490int
1491cache_fromdvp_try(struct vnode *dvp, struct ucred *cred,
1492 struct vnode **saved_dvp)
1493{
1494 struct nchandle nch;
1495 struct vnode *pvp;
1496 int error;
1497 static time_t last_fromdvp_report;
1498 char *fakename;
1499
1500 /*
1501 * Loop getting the parent directory vnode until we get something we
1502 * can resolve in the namecache.
1503 */
1504 vref(dvp);
1505 nch.mount = dvp->v_mount;
1506 nch.ncp = NULL;
1507 fakename = NULL;
1508
1509 for (;;) {
1510 if (fakename) {
1511 kfree(fakename, M_TEMP);
1512 fakename = NULL;
1513 }
1514 error = vop_nlookupdotdot(*dvp->v_ops, dvp, &pvp, cred,
1515 &fakename);
1516 if (error) {
1517 vrele(dvp);
1518 break;
1519 }
1520 vn_unlock(pvp);
1521 if ((nch.ncp = TAILQ_FIRST(&pvp->v_namecache)) != NULL) {
1522 _cache_hold(nch.ncp);
1523 vrele(pvp);
1524 break;
1525 }
1526 if (pvp->v_flag & VROOT) {
1527 nch.ncp = _cache_get(pvp->v_mount->mnt_ncmountpt.ncp);
1528 error = cache_resolve_mp(nch.mount);
1529 _cache_unlock(nch.ncp);
1530 vrele(pvp);
1531 if (error) {
1532 _cache_drop(nch.ncp);
1533 nch.ncp = NULL;
1534 vrele(dvp);
1535 }
1536 break;
1537 }
1538 vrele(dvp);
1539 dvp = pvp;
1540 }
1541 if (error == 0) {
1542 if (last_fromdvp_report != time_second) {
1543 last_fromdvp_report = time_second;
1544 kprintf("Warning: extremely inefficient path "
1545 "resolution on %s\n",
1546 nch.ncp->nc_name);
1547 }
1548 error = cache_inefficient_scan(&nch, cred, dvp, fakename);
1549
1550 /*
1551 * Hopefully dvp now has a namecache record associated with
1552 * it. Leave it referenced to prevent the kernel from
1553 * recycling the vnode. Otherwise extremely long directory
1554 * paths could result in endless recycling.
1555 */
1556 if (*saved_dvp)
1557 vrele(*saved_dvp);
1558 *saved_dvp = dvp;
1559 _cache_drop(nch.ncp);
1560 }
1561 if (fakename)
1562 kfree(fakename, M_TEMP);
1563 return (error);
1564}
1565
1566/*
1567 * Do an inefficient scan of the directory represented by ncp looking for
1568 * the directory vnode dvp. ncp must be held but not locked on entry and
1569 * will be held on return. dvp must be refd but not locked on entry and
1570 * will remain refd on return.
1571 *
1572 * Why do this at all? Well, due to its stateless nature the NFS server
1573 * converts file handles directly to vnodes without necessarily going through
1574 * the namecache ops that would otherwise create the namecache topology
1575 * leading to the vnode. We could either (1) Change the namecache algorithms
1576 * to allow disconnect namecache records that are re-merged opportunistically,
1577 * or (2) Make the NFS server backtrack and scan to recover a connected
1578 * namecache topology in order to then be able to issue new API lookups.
1579 *
1580 * It turns out that (1) is a huge mess. It takes a nice clean set of
1581 * namecache algorithms and introduces a lot of complication in every subsystem
1582 * that calls into the namecache to deal with the re-merge case, especially
1583 * since we are using the namecache to placehold negative lookups and the
1584 * vnode might not be immediately assigned. (2) is certainly far less
1585 * efficient then (1), but since we are only talking about directories here
1586 * (which are likely to remain cached), the case does not actually run all
1587 * that often and has the supreme advantage of not polluting the namecache
1588 * algorithms.
1589 *
1590 * If a fakename is supplied just construct a namecache entry using the
1591 * fake name.
1592 */
1593static int
1594cache_inefficient_scan(struct nchandle *nch, struct ucred *cred,
1595 struct vnode *dvp, char *fakename)
1596{
1597 struct nlcomponent nlc;
1598 struct nchandle rncp;
1599 struct dirent *den;
1600 struct vnode *pvp;
1601 struct vattr vat;
1602 struct iovec iov;
1603 struct uio uio;
1604 int blksize;
1605 int eofflag;
1606 int bytes;
1607 char *rbuf;
1608 int error;
1609
1610 vat.va_blocksize = 0;
1611 if ((error = VOP_GETATTR(dvp, &vat)) != 0)
1612 return (error);
1613 if ((error = cache_vref(nch, cred, &pvp)) != 0)
1614 return (error);
1615 if (ncvp_debug) {
1616 kprintf("inefficient_scan: directory iosize %ld "
1617 "vattr fileid = %lld\n",
1618 vat.va_blocksize,
1619 (long long)vat.va_fileid);
1620 }
1621
1622 /*
1623 * Use the supplied fakename if not NULL. Fake names are typically
1624 * not in the actual filesystem hierarchy. This is used by HAMMER
1625 * to glue @@timestamp recursions together.
1626 */
1627 if (fakename) {
1628 nlc.nlc_nameptr = fakename;
1629 nlc.nlc_namelen = strlen(fakename);
1630 rncp = cache_nlookup(nch, &nlc);
1631 goto done;
1632 }
1633
1634 if ((blksize = vat.va_blocksize) == 0)
1635 blksize = DEV_BSIZE;
1636 rbuf = kmalloc(blksize, M_TEMP, M_WAITOK);
1637 rncp.ncp = NULL;
1638
1639 eofflag = 0;
1640 uio.uio_offset = 0;
1641again:
1642 iov.iov_base = rbuf;
1643 iov.iov_len = blksize;
1644 uio.uio_iov = &iov;
1645 uio.uio_iovcnt = 1;
1646 uio.uio_resid = blksize;
1647 uio.uio_segflg = UIO_SYSSPACE;
1648 uio.uio_rw = UIO_READ;
1649 uio.uio_td = curthread;
1650
1651 if (ncvp_debug >= 2)
1652 kprintf("cache_inefficient_scan: readdir @ %08x\n", (int)uio.uio_offset);
1653 error = VOP_READDIR(pvp, &uio, cred, &eofflag, NULL, NULL);
1654 if (error == 0) {
1655 den = (struct dirent *)rbuf;
1656 bytes = blksize - uio.uio_resid;
1657
1658 while (bytes > 0) {
1659 if (ncvp_debug >= 2) {
1660 kprintf("cache_inefficient_scan: %*.*s\n",
1661 den->d_namlen, den->d_namlen,
1662 den->d_name);
1663 }
1664 if (den->d_type != DT_WHT &&
1665 den->d_ino == vat.va_fileid) {
1666 if (ncvp_debug) {
1667 kprintf("cache_inefficient_scan: "
1668 "MATCHED inode %lld path %s/%*.*s\n",
1669 (long long)vat.va_fileid,
1670 nch->ncp->nc_name,
1671 den->d_namlen, den->d_namlen,
1672 den->d_name);
1673 }
1674 nlc.nlc_nameptr = den->d_name;
1675 nlc.nlc_namelen = den->d_namlen;
1676 rncp = cache_nlookup(nch, &nlc);
1677 KKASSERT(rncp.ncp != NULL);
1678 break;
1679 }
1680 bytes -= _DIRENT_DIRSIZ(den);
1681 den = _DIRENT_NEXT(den);
1682 }
1683 if (rncp.ncp == NULL && eofflag == 0 && uio.uio_resid != blksize)
1684 goto again;
1685 }
1686 kfree(rbuf, M_TEMP);
1687done:
1688 vrele(pvp);
1689 if (rncp.ncp) {
1690 if (rncp.ncp->nc_flag & NCF_UNRESOLVED) {
1691 _cache_setvp(rncp.mount, rncp.ncp, dvp);
1692 if (ncvp_debug >= 2) {
1693 kprintf("cache_inefficient_scan: setvp %s/%s = %p\n",
1694 nch->ncp->nc_name, rncp.ncp->nc_name, dvp);
1695 }
1696 } else {
1697 if (ncvp_debug >= 2) {
1698 kprintf("cache_inefficient_scan: setvp %s/%s already set %p/%p\n",
1699 nch->ncp->nc_name, rncp.ncp->nc_name, dvp,
1700 rncp.ncp->nc_vp);
1701 }
1702 }
1703 if (rncp.ncp->nc_vp == NULL)
1704 error = rncp.ncp->nc_error;
1705 /*
1706 * Release rncp after a successful nlookup. rncp was fully
1707 * referenced.
1708 */
1709 cache_put(&rncp);
1710 } else {
1711 kprintf("cache_inefficient_scan: dvp %p NOT FOUND in %s\n",
1712 dvp, nch->ncp->nc_name);
1713 error = ENOENT;
1714 }
1715 return (error);
1716}
1717
1718/*
1719 * Zap a namecache entry. The ncp is unconditionally set to an unresolved
1720 * state, which disassociates it from its vnode or ncneglist.
1721 *
1722 * Then, if there are no additional references to the ncp and no children,
1723 * the ncp is removed from the topology and destroyed. This function will
1724 * also run through the nc_parent chain and destroy parent ncps if possible.
1725 * As a side benefit, it turns out the only conditions that allow running
1726 * up the chain are also the conditions to ensure no deadlock will occur.
1727 *
1728 * References and/or children may exist if the ncp is in the middle of the
1729 * topology, preventing the ncp from being destroyed.
1730 *
1731 * This function must be called with the ncp held and locked and will unlock
1732 * and drop it during zapping.
1733 */
1734static void
1735cache_zap(struct namecache *ncp)
1736{
1737 struct namecache *par;
1738
1739 /*
1740 * Disassociate the vnode or negative cache ref and set NCF_UNRESOLVED.
1741 */
1742 _cache_setunresolved(ncp);
1743
1744 /*
1745 * Try to scrap the entry and possibly tail-recurse on its parent.
1746 * We only scrap unref'd (other then our ref) unresolved entries,
1747 * we do not scrap 'live' entries.
1748 */
1749 while (ncp->nc_flag & NCF_UNRESOLVED) {
1750 /*
1751 * Someone other then us has a ref, stop.
1752 */
1753 if (ncp->nc_refs > 1)
1754 goto done;
1755
1756 /*
1757 * We have children, stop.
1758 */
1759 if (!TAILQ_EMPTY(&ncp->nc_list))
1760 goto done;
1761
1762 /*
1763 * Remove ncp from the topology: hash table and parent linkage.
1764 */
1765 if (ncp->nc_flag & NCF_HASHED) {
1766 ncp->nc_flag &= ~NCF_HASHED;
1767 LIST_REMOVE(ncp, nc_hash);
1768 }
1769 if ((par = ncp->nc_parent) != NULL) {
1770 par = _cache_hold(par);
1771 TAILQ_REMOVE(&par->nc_list, ncp, nc_entry);
1772 ncp->nc_parent = NULL;
1773 if (par->nc_vp && TAILQ_EMPTY(&par->nc_list))
1774 vdrop(par->nc_vp);
1775 }
1776
1777 /*
1778 * ncp should not have picked up any refs. Physically
1779 * destroy the ncp.
1780 */
1781 KKASSERT(ncp->nc_refs == 1);
1782 --numunres;
1783 /* _cache_unlock(ncp) not required */
1784 ncp->nc_refs = -1; /* safety */
1785 if (ncp->nc_name)
1786 kfree(ncp->nc_name, M_VFSCACHE);
1787 kfree(ncp, M_VFSCACHE);
1788
1789 /*
1790 * Loop on the parent (it may be NULL). Only bother looping
1791 * if the parent has a single ref (ours), which also means
1792 * we can lock it trivially.
1793 */
1794 ncp = par;
1795 if (ncp == NULL)
1796 return;
1797 if (ncp->nc_refs != 1) {
1798 _cache_drop(ncp);
1799 return;
1800 }
1801 KKASSERT(par->nc_exlocks == 0);
1802 _cache_lock(ncp);
1803 }
1804done:
1805 _cache_unlock(ncp);
1806 atomic_subtract_int(&ncp->nc_refs, 1);
1807}
1808
1809static enum { CHI_LOW, CHI_HIGH } cache_hysteresis_state = CHI_LOW;
1810
1811static __inline
1812void
1813cache_hysteresis(void)
1814{
1815 /*
1816 * Don't cache too many negative hits. We use hysteresis to reduce
1817 * the impact on the critical path.
1818 */
1819 switch(cache_hysteresis_state) {
1820 case CHI_LOW:
1821 if (numneg > MINNEG && numneg * ncnegfactor > numcache) {
1822 cache_cleanneg(10);
1823 cache_hysteresis_state = CHI_HIGH;
1824 }
1825 break;
1826 case CHI_HIGH:
1827 if (numneg > MINNEG * 9 / 10 &&
1828 numneg * ncnegfactor * 9 / 10 > numcache
1829 ) {
1830 cache_cleanneg(10);
1831 } else {
1832 cache_hysteresis_state = CHI_LOW;
1833 }
1834 break;
1835 }
1836}
1837
1838/*
1839 * NEW NAMECACHE LOOKUP API
1840 *
1841 * Lookup an entry in the cache. A locked, referenced, non-NULL
1842 * entry is *always* returned, even if the supplied component is illegal.
1843 * The resulting namecache entry should be returned to the system with
1844 * cache_put() or _cache_unlock() + cache_drop().
1845 *
1846 * namecache locks are recursive but care must be taken to avoid lock order
1847 * reversals.
1848 *
1849 * Nobody else will be able to manipulate the associated namespace (e.g.
1850 * create, delete, rename, rename-target) until the caller unlocks the
1851 * entry.
1852 *
1853 * The returned entry will be in one of three states: positive hit (non-null
1854 * vnode), negative hit (null vnode), or unresolved (NCF_UNRESOLVED is set).
1855 * Unresolved entries must be resolved through the filesystem to associate the
1856 * vnode and/or determine whether a positive or negative hit has occured.
1857 *
1858 * It is not necessary to lock a directory in order to lock namespace under
1859 * that directory. In fact, it is explicitly not allowed to do that. A
1860 * directory is typically only locked when being created, renamed, or
1861 * destroyed.
1862 *
1863 * The directory (par) may be unresolved, in which case any returned child
1864 * will likely also be marked unresolved. Likely but not guarenteed. Since
1865 * the filesystem lookup requires a resolved directory vnode the caller is
1866 * responsible for resolving the namecache chain top-down. This API
1867 * specifically allows whole chains to be created in an unresolved state.
1868 */
1869struct nchandle
1870cache_nlookup(struct nchandle *par_nch, struct nlcomponent *nlc)
1871{
1872 struct nchandle nch;
1873 struct namecache *ncp;
1874 struct namecache *new_ncp;
1875 struct nchashhead *nchpp;
1876 struct mount *mp;
1877 u_int32_t hash;
1878 globaldata_t gd;
1879
1880 numcalls++;
1881 gd = mycpu;
1882 mp = par_nch->mount;
1883
1884 /*
1885 * Try to locate an existing entry
1886 */
1887 hash = fnv_32_buf(nlc->nlc_nameptr, nlc->nlc_namelen, FNV1_32_INIT);
1888 hash = fnv_32_buf(&par_nch->ncp, sizeof(par_nch->ncp), hash);
1889 new_ncp = NULL;
1890restart:
1891 LIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1892 numchecks++;
1893
1894 /*
1895 * Break out if we find a matching entry. Note that
1896 * UNRESOLVED entries may match, but DESTROYED entries
1897 * do not.
1898 */
1899 if (ncp->nc_parent == par_nch->ncp &&
1900 ncp->nc_nlen == nlc->nlc_namelen &&
1901 bcmp(ncp->nc_name, nlc->nlc_nameptr, ncp->nc_nlen) == 0 &&
1902 (ncp->nc_flag & NCF_DESTROYED) == 0
1903 ) {
1904 if (_cache_get_nonblock(ncp) == 0) {
1905 _cache_auto_unresolve(mp, ncp);
1906 if (new_ncp)
1907 _cache_free(new_ncp);
1908 goto found;
1909 }
1910 _cache_get(ncp);
1911 _cache_put(ncp);
1912 goto restart;
1913 }
1914 }
1915
1916 /*
1917 * We failed to locate an entry, create a new entry and add it to
1918 * the cache. We have to relookup after possibly blocking in
1919 * malloc.
1920 */
1921 if (new_ncp == NULL) {
1922 new_ncp = cache_alloc(nlc->nlc_namelen);
1923 goto restart;
1924 }
1925
1926 ncp = new_ncp;
1927
1928 /*
1929 * Initialize as a new UNRESOLVED entry, lock (non-blocking),
1930 * and link to the parent. The mount point is usually inherited
1931 * from the parent unless this is a special case such as a mount
1932 * point where nlc_namelen is 0. If nlc_namelen is 0 nc_name will
1933 * be NULL.
1934 */
1935 if (nlc->nlc_namelen) {
1936 bcopy(nlc->nlc_nameptr, ncp->nc_name, nlc->nlc_namelen);
1937 ncp->nc_name[nlc->nlc_namelen] = 0;
1938 }
1939 nchpp = NCHHASH(hash);
1940 LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
1941 ncp->nc_flag |= NCF_HASHED;
1942 cache_link_parent(ncp, par_nch->ncp);
1943found:
1944 /*
1945 * stats and namecache size management
1946 */
1947 if (ncp->nc_flag & NCF_UNRESOLVED)
1948 ++gd->gd_nchstats->ncs_miss;
1949 else if (ncp->nc_vp)
1950 ++gd->gd_nchstats->ncs_goodhits;
1951 else
1952 ++gd->gd_nchstats->ncs_neghits;
1953 cache_hysteresis();
1954 nch.mount = mp;
1955 nch.ncp = ncp;
1956 atomic_add_int(&nch.mount->mnt_refs, 1);
1957 return(nch);
1958}
1959
1960/*
1961 * The namecache entry is marked as being used as a mount point.
1962 * Locate the mount if it is visible to the caller.
1963 */
1964struct findmount_info {
1965 struct mount *result;
1966 struct mount *nch_mount;
1967 struct namecache *nch_ncp;
1968};
1969
1970static
1971int
1972cache_findmount_callback(struct mount *mp, void *data)
1973{
1974 struct findmount_info *info = data;
1975
1976 /*
1977 * Check the mount's mounted-on point against the passed nch.
1978 */
1979 if (mp->mnt_ncmounton.mount == info->nch_mount &&
1980 mp->mnt_ncmounton.ncp == info->nch_ncp
1981 ) {
1982 info->result = mp;
1983 return(-1);
1984 }
1985 return(0);
1986}
1987
1988struct mount *
1989cache_findmount(struct nchandle *nch)
1990{
1991 struct findmount_info info;
1992
1993 info.result = NULL;
1994 info.nch_mount = nch->mount;
1995 info.nch_ncp = nch->ncp;
1996 mountlist_scan(cache_findmount_callback, &info,
1997 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1998 return(info.result);
1999}
2000
2001/*
2002 * Resolve an unresolved namecache entry, generally by looking it up.
2003 * The passed ncp must be locked and refd.
2004 *
2005 * Theoretically since a vnode cannot be recycled while held, and since
2006 * the nc_parent chain holds its vnode as long as children exist, the
2007 * direct parent of the cache entry we are trying to resolve should
2008 * have a valid vnode. If not then generate an error that we can
2009 * determine is related to a resolver bug.
2010 *
2011 * However, if a vnode was in the middle of a recyclement when the NCP
2012 * got locked, ncp->nc_vp might point to a vnode that is about to become
2013 * invalid. cache_resolve() handles this case by unresolving the entry
2014 * and then re-resolving it.
2015 *
2016 * Note that successful resolution does not necessarily return an error
2017 * code of 0. If the ncp resolves to a negative cache hit then ENOENT
2018 * will be returned.
2019 */
2020int
2021cache_resolve(struct nchandle *nch, struct ucred *cred)
2022{
2023 struct namecache *par;
2024 struct namecache *ncp;
2025 struct nchandle nctmp;
2026 struct mount *mp;
2027 struct vnode *dvp;
2028 int error;
2029
2030 ncp = nch->ncp;
2031 mp = nch->mount;
2032restart:
2033 /*
2034 * If the ncp is already resolved we have nothing to do. However,
2035 * we do want to guarentee that a usable vnode is returned when
2036 * a vnode is present, so make sure it hasn't been reclaimed.
2037 */
2038 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
2039 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
2040 _cache_setunresolved(ncp);
2041 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0)
2042 return (ncp->nc_error);
2043 }
2044
2045 /*
2046 * Mount points need special handling because the parent does not
2047 * belong to the same filesystem as the ncp.
2048 */
2049 if (ncp == mp->mnt_ncmountpt.ncp)
2050 return (cache_resolve_mp(mp));
2051
2052 /*
2053 * We expect an unbroken chain of ncps to at least the mount point,
2054 * and even all the way to root (but this code doesn't have to go
2055 * past the mount point).
2056 */
2057 if (ncp->nc_parent == NULL) {
2058 kprintf("EXDEV case 1 %p %*.*s\n", ncp,
2059 ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
2060 ncp->nc_error = EXDEV;
2061 return(ncp->nc_error);
2062 }
2063
2064 /*
2065 * The vp's of the parent directories in the chain are held via vhold()
2066 * due to the existance of the child, and should not disappear.
2067 * However, there are cases where they can disappear:
2068 *
2069 * - due to filesystem I/O errors.
2070 * - due to NFS being stupid about tracking the namespace and
2071 * destroys the namespace for entire directories quite often.
2072 * - due to forced unmounts.
2073 * - due to an rmdir (parent will be marked DESTROYED)
2074 *
2075 * When this occurs we have to track the chain backwards and resolve
2076 * it, looping until the resolver catches up to the current node. We
2077 * could recurse here but we might run ourselves out of kernel stack
2078 * so we do it in a more painful manner. This situation really should
2079 * not occur all that often, or if it does not have to go back too
2080 * many nodes to resolve the ncp.
2081 */
2082 while ((dvp = cache_dvpref(ncp)) == NULL) {
2083 /*
2084 * This case can occur if a process is CD'd into a
2085 * directory which is then rmdir'd. If the parent is marked
2086 * destroyed there is no point trying to resolve it.
2087 */
2088 if (ncp->nc_parent->nc_flag & NCF_DESTROYED)
2089 return(ENOENT);
2090
2091 par = ncp->nc_parent;
2092 while (par->nc_parent && par->nc_parent->nc_vp == NULL)
2093 par = par->nc_parent;
2094 if (par->nc_parent == NULL) {
2095 kprintf("EXDEV case 2 %*.*s\n",
2096 par->nc_nlen, par->nc_nlen, par->nc_name);
2097 return (EXDEV);
2098 }
2099 kprintf("[diagnostic] cache_resolve: had to recurse on %*.*s\n",
2100 par->nc_nlen, par->nc_nlen, par->nc_name);
2101 /*
2102 * The parent is not set in stone, ref and lock it to prevent
2103 * it from disappearing. Also note that due to renames it
2104 * is possible for our ncp to move and for par to no longer
2105 * be one of its parents. We resolve it anyway, the loop
2106 * will handle any moves.
2107 */
2108 _cache_get(par);
2109 if (par == nch->mount->mnt_ncmountpt.ncp) {
2110 cache_resolve_mp(nch->mount);
2111 } else if ((dvp = cache_dvpref(par)) == NULL) {
2112 kprintf("[diagnostic] cache_resolve: raced on %*.*s\n", par->nc_nlen, par->nc_nlen, par->nc_name);
2113 _cache_put(par);
2114 continue;
2115 } else {
2116 if (par->nc_flag & NCF_UNRESOLVED) {
2117 nctmp.mount = mp;
2118 nctmp.ncp = par;
2119 par->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
2120 }
2121 vrele(dvp);
2122 }
2123 if ((error = par->nc_error) != 0) {
2124 if (par->nc_error != EAGAIN) {
2125 kprintf("EXDEV case 3 %*.*s error %d\n",
2126 par->nc_nlen, par->nc_nlen, par->nc_name,
2127 par->nc_error);
2128 _cache_put(par);
2129 return(error);
2130 }
2131 kprintf("[diagnostic] cache_resolve: EAGAIN par %p %*.*s\n",
2132 par, par->nc_nlen, par->nc_nlen, par->nc_name);
2133 }
2134 _cache_put(par);
2135 /* loop */
2136 }
2137
2138 /*
2139 * Call VOP_NRESOLVE() to get the vp, then scan for any disconnected
2140 * ncp's and reattach them. If this occurs the original ncp is marked
2141 * EAGAIN to force a relookup.
2142 *
2143 * NOTE: in order to call VOP_NRESOLVE(), the parent of the passed
2144 * ncp must already be resolved.
2145 */
2146 if (dvp) {
2147 nctmp.mount = mp;
2148 nctmp.ncp = ncp;
2149 ncp->nc_error = VOP_NRESOLVE(&nctmp, dvp, cred);
2150 vrele(dvp);
2151 } else {
2152 ncp->nc_error = EPERM;
2153 }
2154 if (ncp->nc_error == EAGAIN) {
2155 kprintf("[diagnostic] cache_resolve: EAGAIN ncp %p %*.*s\n",
2156 ncp, ncp->nc_nlen, ncp->nc_nlen, ncp->nc_name);
2157 goto restart;
2158 }
2159 return(ncp->nc_error);
2160}
2161
2162/*
2163 * Resolve the ncp associated with a mount point. Such ncp's almost always
2164 * remain resolved and this routine is rarely called. NFS MPs tends to force
2165 * re-resolution more often due to its mac-truck-smash-the-namecache
2166 * method of tracking namespace changes.
2167 *
2168 * The semantics for this call is that the passed ncp must be locked on
2169 * entry and will be locked on return. However, if we actually have to
2170 * resolve the mount point we temporarily unlock the entry in order to
2171 * avoid race-to-root deadlocks due to e.g. dead NFS mounts. Because of
2172 * the unlock we have to recheck the flags after we relock.
2173 */
2174static int
2175cache_resolve_mp(struct mount *mp)
2176{
2177 struct namecache *ncp = mp->mnt_ncmountpt.ncp;
2178 struct vnode *vp;
2179 int error;
2180
2181 KKASSERT(mp != NULL);
2182
2183 /*
2184 * If the ncp is already resolved we have nothing to do. However,
2185 * we do want to guarentee that a usable vnode is returned when
2186 * a vnode is present, so make sure it hasn't been reclaimed.
2187 */
2188 if ((ncp->nc_flag & NCF_UNRESOLVED) == 0) {
2189 if (ncp->nc_vp && (ncp->nc_vp->v_flag & VRECLAIMED))
2190 _cache_setunresolved(ncp);
2191 }
2192
2193 if (ncp->nc_flag & NCF_UNRESOLVED) {
2194 _cache_unlock(ncp);
2195 while (vfs_busy(mp, 0))
2196 ;
2197 error = VFS_ROOT(mp, &vp);
2198 _cache_lock(ncp);
2199
2200 /*
2201 * recheck the ncp state after relocking.
2202 */
2203 if (ncp->nc_flag & NCF_UNRESOLVED) {
2204 ncp->nc_error = error;
2205 if (error == 0) {
2206 _cache_setvp(mp, ncp, vp);
2207 vput(vp);
2208 } else {
2209 kprintf("[diagnostic] cache_resolve_mp: failed"
2210 " to resolve mount %p err=%d ncp=%p\n",
2211 mp, error, ncp);
2212 _cache_setvp(mp, ncp, NULL);
2213 }
2214 } else if (error == 0) {
2215 vput(vp);
2216 }
2217 vfs_unbusy(mp);
2218 }
2219 return(ncp->nc_error);
2220}
2221
2222void
2223cache_cleanneg(int count)
2224{
2225 struct namecache *ncp;
2226
2227 /*
2228 * Automode from the vnlru proc - clean out 10% of the negative cache
2229 * entries.
2230 */
2231 if (count == 0)
2232 count = numneg / 10 + 1;
2233
2234 /*
2235 * Attempt to clean out the specified number of negative cache
2236 * entries.
2237 */
2238 while (count) {
2239 ncp = TAILQ_FIRST(&ncneglist);
2240 if (ncp == NULL) {
2241 KKASSERT(numneg == 0);
2242 break;
2243 }
2244 TAILQ_REMOVE(&ncneglist, ncp, nc_vnode);
2245 TAILQ_INSERT_TAIL(&ncneglist, ncp, nc_vnode);
2246 if (_cache_get_nonblock(ncp) == 0)
2247 cache_zap(ncp);
2248 --count;
2249 }
2250}
2251
2252/*
2253 * Rehash a ncp. Rehashing is typically required if the name changes (should
2254 * not generally occur) or the parent link changes. This function will
2255 * unhash the ncp if the ncp is no longer hashable.
2256 */
2257static void
2258_cache_rehash(struct namecache *ncp)
2259{
2260 struct nchashhead *nchpp;
2261 u_int32_t hash;
2262
2263 if (ncp->nc_flag & NCF_HASHED) {
2264 ncp->nc_flag &= ~NCF_HASHED;
2265 LIST_REMOVE(ncp, nc_hash);
2266 }
2267 if (ncp->nc_nlen && ncp->nc_parent) {
2268 hash = fnv_32_buf(ncp->nc_name, ncp->nc_nlen, FNV1_32_INIT);
2269 hash = fnv_32_buf(&ncp->nc_parent,
2270 sizeof(ncp->nc_parent), hash);
2271 nchpp = NCHHASH(hash);
2272 LIST_INSERT_HEAD(nchpp, ncp, nc_hash);
2273 ncp->nc_flag |= NCF_HASHED;
2274 }
2275}
2276
2277/*
2278 * Name cache initialization, from vfsinit() when we are booting
2279 */
2280void
2281nchinit(void)
2282{
2283 int i;
2284 globaldata_t gd;
2285
2286 /* initialise per-cpu namecache effectiveness statistics. */
2287 for (i = 0; i < ncpus; ++i) {
2288 gd = globaldata_find(i);
2289 gd->gd_nchstats = &nchstats[i];
2290 }
2291 TAILQ_INIT(&ncneglist);
2292 nchashtbl = hashinit(desiredvnodes*2, M_VFSCACHE, &nchash);
2293 nclockwarn = 5 * hz;
2294}
2295
2296/*
2297 * Called from start_init() to bootstrap the root filesystem. Returns
2298 * a referenced, unlocked namecache record.
2299 */
2300void
2301cache_allocroot(struct nchandle *nch, struct mount *mp, struct vnode *vp)
2302{
2303 nch->ncp = cache_alloc(0);
2304 nch->mount = mp;
2305 atomic_add_int(&mp->mnt_refs, 1);
2306 if (vp)
2307 _cache_setvp(nch->mount, nch->ncp, vp);
2308}
2309
2310/*
2311 * vfs_cache_setroot()
2312 *
2313 * Create an association between the root of our namecache and
2314 * the root vnode. This routine may be called several times during
2315 * booting.
2316 *
2317 * If the caller intends to save the returned namecache pointer somewhere
2318 * it must cache_hold() it.
2319 */
2320void
2321vfs_cache_setroot(struct vnode *nvp, struct nchandle *nch)
2322{
2323 struct vnode *ovp;
2324 struct nchandle onch;
2325
2326 ovp = rootvnode;
2327 onch = rootnch;
2328 rootvnode = nvp;
2329 if (nch)
2330 rootnch = *nch;
2331 else
2332 cache_zero(&rootnch);
2333 if (ovp)
2334 vrele(ovp);
2335 if (onch.ncp)
2336 cache_drop(&onch);
2337}
2338
2339/*
2340 * XXX OLD API COMPAT FUNCTION. This really messes up the new namecache
2341 * topology and is being removed as quickly as possible. The new VOP_N*()
2342 * API calls are required to make specific adjustments using the supplied
2343 * ncp pointers rather then just bogusly purging random vnodes.
2344 *
2345 * Invalidate all namecache entries to a particular vnode as well as
2346 * any direct children of that vnode in the namecache. This is a
2347 * 'catch all' purge used by filesystems that do not know any better.
2348 *
2349 * Note that the linkage between the vnode and its namecache entries will
2350 * be removed, but the namecache entries themselves might stay put due to
2351 * active references from elsewhere in the system or due to the existance of
2352 * the children. The namecache topology is left intact even if we do not
2353 * know what the vnode association is. Such entries will be marked
2354 * NCF_UNRESOLVED.
2355 */
2356void
2357cache_purge(struct vnode *vp)
2358{
2359 cache_inval_vp(vp, CINV_DESTROY | CINV_CHILDREN);
2360}
2361
2362/*
2363 * Flush all entries referencing a particular filesystem.
2364 *
2365 * Since we need to check it anyway, we will flush all the invalid
2366 * entries at the same time.
2367 */
2368#if 0
2369
2370void
2371cache_purgevfs(struct mount *mp)
2372{
2373 struct nchashhead *nchpp;
2374 struct namecache *ncp, *nnp;
2375
2376 /*
2377 * Scan hash tables for applicable entries.
2378 */
2379 for (nchpp = &nchashtbl[nchash]; nchpp >= nchashtbl; nchpp--) {
2380 ncp = LIST_FIRST(nchpp);
2381 if (ncp)
2382 _cache_hold(ncp);
2383 while (ncp) {
2384 nnp = LIST_NEXT(ncp, nc_hash);
2385 if (nnp)
2386 _cache_hold(nnp);
2387 if (ncp->nc_mount == mp) {
2388 _cache_lock(ncp);
2389 cache_zap(ncp);
2390 } else {
2391 _cache_drop(ncp);
2392 }
2393 ncp = nnp;
2394 }
2395 }
2396}
2397
2398#endif
2399
2400/*
2401 * Create a new (theoretically) unique fsmid
2402 */
2403int64_t
2404cache_getnewfsmid(void)
2405{
2406 static int fsmid_roller;
2407 int64_t fsmid;
2408
2409 ++fsmid_roller;
2410 fsmid = ((int64_t)time_second << 32) |
2411 (fsmid_roller & 0x7FFFFFFF);
2412 return (fsmid);
2413}
2414
2415
2416static int disablecwd;
2417SYSCTL_INT(_debug, OID_AUTO, disablecwd, CTLFLAG_RW, &disablecwd, 0, "");
2418
2419static u_long numcwdcalls; STATNODE(CTLFLAG_RD, numcwdcalls, &numcwdcalls);
2420static u_long numcwdfail1; STATNODE(CTLFLAG_RD, numcwdfail1, &numcwdfail1);
2421static u_long numcwdfail2; STATNODE(CTLFLAG_RD, numcwdfail2, &numcwdfail2);
2422static u_long numcwdfail3; STATNODE(CTLFLAG_RD, numcwdfail3, &numcwdfail3);
2423static u_long numcwdfail4; STATNODE(CTLFLAG_RD, numcwdfail4, &numcwdfail4);
2424static u_long numcwdfound; STATNODE(CTLFLAG_RD, numcwdfound, &numcwdfound);
2425
2426/*
2427 * MPALMOSTSAFE
2428 */
2429int
2430sys___getcwd(struct __getcwd_args *uap)
2431{
2432 int buflen;
2433 int error;
2434 char *buf;
2435 char *bp;
2436
2437 if (disablecwd)
2438 return (ENODEV);
2439
2440 buflen = uap->buflen;
2441 if (buflen == 0)
2442 return (EINVAL);
2443 if (buflen > MAXPATHLEN)
2444 buflen = MAXPATHLEN;
2445
2446 buf = kmalloc(buflen, M_TEMP, M_WAITOK);
2447 get_mplock();
2448 bp = kern_getcwd(buf, buflen, &error);
2449 rel_mplock();
2450 if (error == 0)
2451 error = copyout(bp, uap->buf, strlen(bp) + 1);
2452 kfree(buf, M_TEMP);
2453 return (error);
2454}
2455
2456char *
2457kern_getcwd(char *buf, size_t buflen, int *error)
2458{
2459 struct proc *p = curproc;
2460 char *bp;
2461 int i, slash_prefixed;
2462 struct filedesc *fdp;
2463 struct nchandle nch;
2464
2465 numcwdcalls++;
2466 bp = buf;
2467 bp += buflen - 1;
2468 *bp = '\0';
2469 fdp = p->p_fd;
2470 slash_prefixed = 0;
2471
2472 nch = fdp->fd_ncdir;
2473 while (nch.ncp && (nch.ncp != fdp->fd_nrdir.ncp ||
2474 nch.mount != fdp->fd_nrdir.mount)
2475 ) {
2476 /*
2477 * While traversing upwards if we encounter the root
2478 * of the current mount we have to skip to the mount point
2479 * in the underlying filesystem.
2480 */
2481 if (nch.ncp == nch.mount->mnt_ncmountpt.ncp) {
2482 nch = nch.mount->mnt_ncmounton;
2483 continue;
2484 }
2485
2486 /*
2487 * Prepend the path segment
2488 */
2489 for (i = nch.ncp->nc_nlen - 1; i >= 0; i--) {
2490 if (bp == buf) {
2491 numcwdfail4++;
2492 *error = ERANGE;
2493 return(NULL);
2494 }
2495 *--bp = nch.ncp->nc_name[i];
2496 }
2497 if (bp == buf) {
2498 numcwdfail4++;
2499 *error = ERANGE;
2500 return(NULL);
2501 }
2502 *--bp = '/';
2503 slash_prefixed = 1;
2504
2505 /*
2506 * Go up a directory. This isn't a mount point so we don't
2507 * have to check again.
2508 */
2509 nch.ncp = nch.ncp->nc_parent;
2510 }
2511 if (nch.ncp == NULL) {
2512 numcwdfail2++;
2513 *error = ENOENT;
2514 return(NULL);
2515 }
2516 if (!slash_prefixed) {
2517 if (bp == buf) {
2518 numcwdfail4++;
2519 *error = ERANGE;
2520 return(NULL);
2521 }
2522 *--bp = '/';
2523 }
2524 numcwdfound++;
2525 *error = 0;
2526 return (bp);
2527}
2528
2529/*
2530 * Thus begins the fullpath magic.
2531 */
2532
2533#undef STATNODE
2534#define STATNODE(name) \
2535 static u_int name; \
2536 SYSCTL_UINT(_vfs_cache, OID_AUTO, name, CTLFLAG_RD, &name, 0, "")
2537
2538static int disablefullpath;
2539SYSCTL_INT(_debug, OID_AUTO, disablefullpath, CTLFLAG_RW,
2540 &disablefullpath, 0, "");
2541
2542STATNODE(numfullpathcalls);
2543STATNODE(numfullpathfail1);
2544STATNODE(numfullpathfail2);
2545STATNODE(numfullpathfail3);
2546STATNODE(numfullpathfail4);
2547STATNODE(numfullpathfound);
2548
2549int
2550cache_fullpath(struct proc *p, struct nchandle *nchp, char **retbuf, char **freebuf)
2551{
2552 char *bp, *buf;
2553 int i, slash_prefixed;
2554 struct nchandle fd_nrdir;
2555 struct nchandle nch;
2556
2557 numfullpathcalls--;
2558
2559 *retbuf = NULL;
2560 *freebuf = NULL;
2561
2562 buf = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
2563 bp = buf + MAXPATHLEN - 1;
2564 *bp = '\0';
2565 if (p != NULL)
2566 fd_nrdir = p->p_fd->fd_nrdir;
2567 else
2568 fd_nrdir = rootnch;
2569 slash_prefixed = 0;
2570 nch = *nchp;
2571
2572 while (nch.ncp &&
2573 (nch.ncp != fd_nrdir.ncp || nch.mount != fd_nrdir.mount)
2574 ) {
2575 /*
2576 * While traversing upwards if we encounter the root
2577 * of the current mount we have to skip to the mount point.
2578 */
2579 if (nch.ncp == nch.mount->mnt_ncmountpt.ncp) {
2580 nch = nch.mount->mnt_ncmounton;
2581 continue;
2582 }
2583
2584 /*
2585 * Prepend the path segment
2586 */
2587 for (i = nch.ncp->nc_nlen - 1; i >= 0; i--) {
2588 if (bp == buf) {
2589 numfullpathfail4++;
2590 kfree(buf, M_TEMP);
2591 return(ENOMEM);
2592 }
2593 *--bp = nch.ncp->nc_name[i];
2594 }
2595 if (bp == buf) {
2596 numfullpathfail4++;
2597 kfree(buf, M_TEMP);
2598 return(ENOMEM);
2599 }
2600 *--bp = '/';
2601 slash_prefixed = 1;
2602
2603 /*
2604 * Go up a directory. This isn't a mount point so we don't
2605 * have to check again.
2606 */
2607 nch.ncp = nch.ncp->nc_parent;
2608 }
2609 if (nch.ncp == NULL) {
2610 numfullpathfail2++;
2611 kfree(buf, M_TEMP);
2612 return(ENOENT);
2613 }
2614
2615 if (!slash_prefixed) {
2616 if (bp == buf) {
2617 numfullpathfail4++;
2618 kfree(buf, M_TEMP);
2619 return(ENOMEM);
2620 }
2621 *--bp = '/';
2622 }
2623 numfullpathfound++;
2624 *retbuf = bp;
2625 *freebuf = buf;
2626
2627 return(0);
2628}
2629
2630int
2631vn_fullpath(struct proc *p, struct vnode *vn, char **retbuf, char **freebuf)
2632{
2633 struct namecache *ncp;
2634 struct nchandle nch;
2635
2636 numfullpathcalls++;
2637 if (disablefullpath)
2638 return (ENODEV);
2639
2640 if (p == NULL)
2641 return (EINVAL);
2642
2643 /* vn is NULL, client wants us to use p->p_textvp */
2644 if (vn == NULL) {
2645 if ((vn = p->p_textvp) == NULL)
2646 return (EINVAL);
2647 }
2648 TAILQ_FOREACH(ncp, &vn->v_namecache, nc_vnode) {
2649 if (ncp->nc_nlen)
2650 break;
2651 }
2652 if (ncp == NULL)
2653 return (EINVAL);
2654
2655 numfullpathcalls--;
2656 nch.ncp = ncp;;
2657 nch.mount = vn->v_mount;
2658 return(cache_fullpath(p, &nch, retbuf, freebuf));
2659}