2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)vfs_lookup.c 8.4 (Berkeley) 2/16/94
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
42 #include "opt_capsicum.h"
43 #include "opt_ktrace.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/dirent.h>
48 #include <sys/kernel.h>
49 #include <sys/capsicum.h>
50 #include <sys/fcntl.h>
53 #include <sys/mutex.h>
54 #include <sys/namei.h>
55 #include <sys/vnode.h>
56 #include <sys/mount.h>
57 #include <sys/filedesc.h>
60 #include <sys/syscallsubr.h>
61 #include <sys/sysctl.h>
63 #include <sys/ktrace.h>
66 #include <machine/_inttypes.h>
69 #include <security/audit/audit.h>
70 #include <security/mac/mac_framework.h>
74 #define NAMEI_DIAGNOSTIC 1
75 #undef NAMEI_DIAGNOSTIC
78 static void NDVALIDATE_impl(struct nameidata *, int);
79 #define NDVALIDATE(ndp) NDVALIDATE_impl(ndp, __LINE__)
81 #define NDVALIDATE(ndp)
85 * Prepare namei() to restart. Reset components to its original state and set
86 * ISRESTARTED flag which signals the underlying lookup code to change the root
87 * from ABI root to actual root and prevents a further restarts.
89 #define NDRESTART(ndp) do { \
91 ndp->ni_resflags = 0; \
92 ndp->ni_cnd.cn_flags &= ~NAMEI_INTERNAL_FLAGS; \
93 ndp->ni_cnd.cn_flags |= ISRESTARTED; \
96 SDT_PROVIDER_DEFINE(vfs);
97 SDT_PROBE_DEFINE4(vfs, namei, lookup, entry, "struct vnode *", "char *",
98 "unsigned long", "bool");
99 SDT_PROBE_DEFINE4(vfs, namei, lookup, return, "int", "struct vnode *", "bool",
102 /* Allocation zone for namei. */
103 uma_zone_t namei_zone;
105 /* Placeholder vnode for mp traversal. */
106 static struct vnode *vp_crossmp;
109 crossmp_vop_islocked(struct vop_islocked_args *ap)
116 crossmp_vop_lock1(struct vop_lock1_args *ap)
119 struct lock *lk __diagused;
126 KASSERT((flags & (LK_SHARED | LK_NOWAIT)) == (LK_SHARED | LK_NOWAIT),
127 ("%s: invalid lock request 0x%x for crossmp", __func__, flags));
129 if ((flags & LK_INTERLOCK) != 0)
131 LOCK_LOG_LOCK("SLOCK", &lk->lock_object, 0, 0, ap->a_file, ap->a_line);
136 crossmp_vop_unlock(struct vop_unlock_args *ap)
139 struct lock *lk __diagused;
144 LOCK_LOG_LOCK("SUNLOCK", &lk->lock_object, 0, 0, LOCK_FILE,
149 static struct vop_vector crossmp_vnodeops = {
150 .vop_default = &default_vnodeops,
151 .vop_islocked = crossmp_vop_islocked,
152 .vop_lock1 = crossmp_vop_lock1,
153 .vop_unlock = crossmp_vop_unlock,
156 * VFS_VOP_VECTOR_REGISTER(crossmp_vnodeops) is not used here since the vnode
157 * gets allocated early. See nameiinit for the direct call below.
160 struct nameicap_tracker {
162 TAILQ_ENTRY(nameicap_tracker) nm_link;
165 /* Zone for cap mode tracker elements used for dotdot capability checks. */
166 MALLOC_DEFINE(M_NAMEITRACKER, "namei_tracker", "namei tracking for dotdot");
169 nameiinit(void *dummy __unused)
172 namei_zone = uma_zcreate("NAMEI", MAXPATHLEN, NULL, NULL, NULL, NULL,
174 vfs_vector_op_register(&crossmp_vnodeops);
175 getnewvnode("crossmp", NULL, &crossmp_vnodeops, &vp_crossmp);
176 vp_crossmp->v_state = VSTATE_CONSTRUCTED;
177 vp_crossmp->v_irflag |= VIRF_CROSSMP;
179 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nameiinit, NULL);
181 static int lookup_cap_dotdot = 1;
182 SYSCTL_INT(_vfs, OID_AUTO, lookup_cap_dotdot, CTLFLAG_RWTUN,
183 &lookup_cap_dotdot, 0,
184 "enables \"..\" components in path lookup in capability mode");
185 static int lookup_cap_dotdot_nonlocal = 1;
186 SYSCTL_INT(_vfs, OID_AUTO, lookup_cap_dotdot_nonlocal, CTLFLAG_RWTUN,
187 &lookup_cap_dotdot_nonlocal, 0,
188 "enables \"..\" components in path lookup in capability mode "
189 "on non-local mount");
192 nameicap_tracker_add(struct nameidata *ndp, struct vnode *dp)
194 struct nameicap_tracker *nt;
196 if ((ndp->ni_lcf & NI_LCF_CAP_DOTDOT) == 0 || dp->v_type != VDIR)
198 nt = TAILQ_LAST(&ndp->ni_cap_tracker, nameicap_tracker_head);
199 if (nt != NULL && nt->dp == dp)
201 nt = malloc(sizeof(*nt), M_NAMEITRACKER, M_WAITOK);
204 TAILQ_INSERT_TAIL(&ndp->ni_cap_tracker, nt, nm_link);
208 nameicap_cleanup_from(struct nameidata *ndp, struct nameicap_tracker *first)
210 struct nameicap_tracker *nt, *nt1;
213 TAILQ_FOREACH_FROM_SAFE(nt, &ndp->ni_cap_tracker, nm_link, nt1) {
214 TAILQ_REMOVE(&ndp->ni_cap_tracker, nt, nm_link);
216 free(nt, M_NAMEITRACKER);
221 nameicap_cleanup(struct nameidata *ndp)
223 KASSERT(TAILQ_EMPTY(&ndp->ni_cap_tracker) ||
224 (ndp->ni_lcf & NI_LCF_CAP_DOTDOT) != 0, ("not strictrelative"));
225 nameicap_cleanup_from(ndp, NULL);
229 * For dotdot lookups in capability mode, only allow the component
230 * lookup to succeed if the resulting directory was already traversed
231 * during the operation. This catches situations where already
232 * traversed directory is moved to different parent, and then we walk
233 * over it with dotdots.
235 * Also allow to force failure of dotdot lookups for non-local
236 * filesystems, where external agents might assist local lookups to
237 * escape the compartment.
240 nameicap_check_dotdot(struct nameidata *ndp, struct vnode *dp)
242 struct nameicap_tracker *nt;
245 if (dp == NULL || dp->v_type != VDIR || (ndp->ni_lcf &
246 NI_LCF_STRICTRELATIVE) == 0)
248 if ((ndp->ni_lcf & NI_LCF_CAP_DOTDOT) == 0)
249 return (ENOTCAPABLE);
251 if (lookup_cap_dotdot_nonlocal == 0 && mp != NULL &&
252 (mp->mnt_flag & MNT_LOCAL) == 0)
253 return (ENOTCAPABLE);
254 TAILQ_FOREACH_REVERSE(nt, &ndp->ni_cap_tracker, nameicap_tracker_head,
257 nt = TAILQ_NEXT(nt, nm_link);
259 nameicap_cleanup_from(ndp, nt);
263 return (ENOTCAPABLE);
267 namei_cleanup_cnp(struct componentname *cnp)
270 uma_zfree(namei_zone, cnp->cn_pnbuf);
271 cnp->cn_pnbuf = NULL;
272 cnp->cn_nameptr = NULL;
276 namei_handle_root(struct nameidata *ndp, struct vnode **dpp)
278 struct componentname *cnp;
281 if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) != 0) {
283 if (KTRPOINT(curthread, KTR_CAPFAIL))
284 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
286 return (ENOTCAPABLE);
288 while (*(cnp->cn_nameptr) == '/') {
292 *dpp = ndp->ni_rootdir;
298 namei_setup(struct nameidata *ndp, struct vnode **dpp, struct pwd **pwdp)
300 struct componentname *cnp;
309 startdir_used = false;
313 #ifdef CAPABILITY_MODE
315 * In capability mode, lookups must be restricted to happen in
316 * the subtree with the root specified by the file descriptor:
317 * - The root must be real file descriptor, not the pseudo-descriptor
319 * - The passed path must be relative and not absolute.
320 * - If lookup_cap_dotdot is disabled, path must not contain the
322 * - If lookup_cap_dotdot is enabled, we verify that all '..'
323 * components lookups result in the directories which were
324 * previously walked by us, which prevents an escape from
327 if (IN_CAPABILITY_MODE(td) && (cnp->cn_flags & NOCAPCHECK) == 0) {
328 ndp->ni_lcf |= NI_LCF_STRICTRELATIVE;
329 ndp->ni_resflags |= NIRES_STRICTREL;
330 if (ndp->ni_dirfd == AT_FDCWD) {
332 if (KTRPOINT(td, KTR_CAPFAIL))
333 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
342 * Get starting point for the translation.
346 * The reference on ni_rootdir is acquired in the block below to avoid
347 * back-to-back atomics for absolute lookups.
349 namei_setup_rootdir(ndp, cnp, pwd);
350 ndp->ni_topdir = pwd->pwd_jdir;
352 if (cnp->cn_pnbuf[0] == '/') {
353 ndp->ni_resflags |= NIRES_ABS;
354 error = namei_handle_root(ndp, dpp);
356 if (ndp->ni_startdir != NULL) {
357 *dpp = ndp->ni_startdir;
358 startdir_used = true;
359 } else if (ndp->ni_dirfd == AT_FDCWD) {
360 *dpp = pwd->pwd_cdir;
363 if (cnp->cn_flags & AUDITVNODE1)
364 AUDIT_ARG_ATFD1(ndp->ni_dirfd);
365 if (cnp->cn_flags & AUDITVNODE2)
366 AUDIT_ARG_ATFD2(ndp->ni_dirfd);
368 error = fgetvp_lookup(ndp->ni_dirfd, ndp, dpp);
370 if (error == 0 && (*dpp)->v_type != VDIR &&
371 (cnp->cn_pnbuf[0] != '\0' ||
372 (cnp->cn_flags & EMPTYPATH) == 0))
375 if (error == 0 && (cnp->cn_flags & RBENEATH) != 0) {
376 if (cnp->cn_pnbuf[0] == '/') {
378 } else if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) == 0) {
379 ndp->ni_lcf |= NI_LCF_STRICTRELATIVE |
385 * If we are auditing the kernel pathname, save the user pathname.
387 if (AUDITING_TD(td)) {
388 if (cnp->cn_flags & AUDITVNODE1)
389 AUDIT_ARG_UPATH1_VP(td, ndp->ni_rootdir, *dpp, cnp->cn_pnbuf);
390 if (cnp->cn_flags & AUDITVNODE2)
391 AUDIT_ARG_UPATH2_VP(td, ndp->ni_rootdir, *dpp, cnp->cn_pnbuf);
393 if (ndp->ni_startdir != NULL && !startdir_used)
394 vrele(ndp->ni_startdir);
401 if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) != 0 &&
402 lookup_cap_dotdot != 0)
403 ndp->ni_lcf |= NI_LCF_CAP_DOTDOT;
404 SDT_PROBE4(vfs, namei, lookup, entry, *dpp, cnp->cn_pnbuf,
405 cnp->cn_flags, false);
411 namei_getpath(struct nameidata *ndp)
413 struct componentname *cnp;
419 * Get a buffer for the name to be translated, and copy the
420 * name into the buffer.
422 cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
423 if (ndp->ni_segflg == UIO_SYSSPACE) {
424 error = copystr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
427 error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
435 namei_emptypath(struct nameidata *ndp)
437 struct componentname *cnp;
443 MPASS(*cnp->cn_pnbuf == '\0');
444 MPASS((cnp->cn_flags & EMPTYPATH) != 0);
445 MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
447 ndp->ni_resflags |= NIRES_EMPTYPATH;
448 error = namei_setup(ndp, &dp, &pwd);
454 * Usecount on dp already provided by namei_setup.
459 if ((cnp->cn_flags & LOCKLEAF) != 0) {
460 VOP_LOCK(dp, (cnp->cn_flags & LOCKSHARED) != 0 ?
461 LK_SHARED : LK_EXCLUSIVE);
462 if (VN_IS_DOOMED(dp)) {
468 SDT_PROBE4(vfs, namei, lookup, return, 0, ndp->ni_vp, false, ndp);
472 SDT_PROBE4(vfs, namei, lookup, return, error, NULL, false, ndp);
473 namei_cleanup_cnp(cnp);
477 static int __noinline
478 namei_follow_link(struct nameidata *ndp)
483 struct componentname *cnp;
491 if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
496 if ((cnp->cn_flags & NOMACCHECK) == 0) {
497 error = mac_vnode_check_readlink(td->td_ucred, ndp->ni_vp);
502 if (ndp->ni_pathlen > 1)
503 cp = uma_zalloc(namei_zone, M_WAITOK);
507 aiov.iov_len = MAXPATHLEN;
508 auio.uio_iov = &aiov;
511 auio.uio_rw = UIO_READ;
512 auio.uio_segflg = UIO_SYSSPACE;
514 auio.uio_resid = MAXPATHLEN;
515 error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
517 if (ndp->ni_pathlen > 1)
518 uma_zfree(namei_zone, cp);
521 linklen = MAXPATHLEN - auio.uio_resid;
523 if (ndp->ni_pathlen > 1)
524 uma_zfree(namei_zone, cp);
528 if (linklen + ndp->ni_pathlen > MAXPATHLEN) {
529 if (ndp->ni_pathlen > 1)
530 uma_zfree(namei_zone, cp);
531 error = ENAMETOOLONG;
534 if (ndp->ni_pathlen > 1) {
535 bcopy(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
536 uma_zfree(namei_zone, cnp->cn_pnbuf);
539 cnp->cn_pnbuf[linklen] = '\0';
540 ndp->ni_pathlen += linklen;
546 * Convert a pathname into a pointer to a locked vnode.
548 * The FOLLOW flag is set when symbolic links are to be followed
549 * when they occur at the end of the name translation process.
550 * Symbolic links are always followed for all other pathname
551 * components other than the last.
553 * The segflg defines whether the name is to be copied from user
554 * space or kernel space.
556 * Overall outline of namei:
559 * get starting directory
560 * while (!done && !error) {
561 * call lookup to search path.
562 * if symbolic link, massage name in buffer and continue
566 namei(struct nameidata *ndp)
568 struct vnode *dp; /* the directory we are searching */
569 struct componentname *cnp;
573 enum cache_fpl_status status;
578 KASSERT((ndp->ni_debugflags & NAMEI_DBG_CALLED) == 0,
579 ("%s: repeated call to namei without NDREINIT", __func__));
580 KASSERT(ndp->ni_debugflags == NAMEI_DBG_INITED,
581 ("%s: bad debugflags %d", __func__, ndp->ni_debugflags));
582 ndp->ni_debugflags |= NAMEI_DBG_CALLED;
583 if (ndp->ni_startdir != NULL)
584 ndp->ni_debugflags |= NAMEI_DBG_HADSTARTDIR;
585 if (cnp->cn_flags & FAILIFEXISTS) {
586 KASSERT(cnp->cn_nameiop == CREATE,
587 ("%s: FAILIFEXISTS passed for op %d", __func__, cnp->cn_nameiop));
589 * The limitation below is to restrict hairy corner cases.
591 KASSERT((cnp->cn_flags & (LOCKPARENT | LOCKLEAF)) == LOCKPARENT,
592 ("%s: FAILIFEXISTS must be passed with LOCKPARENT and without LOCKLEAF",
596 ndp->ni_cnd.cn_cred = td->td_ucred;
597 KASSERT(ndp->ni_resflags == 0, ("%s: garbage in ni_resflags: %x\n",
598 __func__, ndp->ni_resflags));
599 KASSERT(cnp->cn_cred && td->td_proc, ("namei: bad cred/proc"));
600 KASSERT((cnp->cn_flags & NAMEI_INTERNAL_FLAGS) == 0,
601 ("namei: unexpected flags: %" PRIx64 "\n",
602 cnp->cn_flags & NAMEI_INTERNAL_FLAGS));
603 if (cnp->cn_flags & NOCACHE)
604 KASSERT(cnp->cn_nameiop != LOOKUP,
605 ("%s: NOCACHE passed with LOOKUP", __func__));
606 MPASS(ndp->ni_startdir == NULL || ndp->ni_startdir->v_type == VDIR ||
607 ndp->ni_startdir->v_type == VBAD);
614 error = namei_getpath(ndp);
615 if (__predict_false(error != 0)) {
616 namei_cleanup_cnp(cnp);
617 SDT_PROBE4(vfs, namei, lookup, return, error, NULL,
622 cnp->cn_nameptr = cnp->cn_pnbuf;
625 if (KTRPOINT(td, KTR_NAMEI)) {
626 ktrnamei(cnp->cn_pnbuf);
629 TSNAMEI(curthread->td_proc->p_pid, cnp->cn_pnbuf);
632 * First try looking up the target without locking any vnodes.
634 * We may need to start from scratch or pick up where it left off.
636 error = cache_fplookup(ndp, &status, &pwd);
638 case CACHE_FPL_STATUS_UNSET:
639 __assert_unreachable();
641 case CACHE_FPL_STATUS_HANDLED:
644 else if (__predict_false(pwd->pwd_adir != pwd->pwd_rdir &&
645 (cnp->cn_flags & ISRESTARTED) == 0)) {
646 namei_cleanup_cnp(cnp);
651 case CACHE_FPL_STATUS_PARTIAL:
652 TAILQ_INIT(&ndp->ni_cap_tracker);
653 dp = ndp->ni_startdir;
655 case CACHE_FPL_STATUS_DESTROYED:
657 error = namei_getpath(ndp);
658 if (__predict_false(error != 0)) {
659 namei_cleanup_cnp(cnp);
662 cnp->cn_nameptr = cnp->cn_pnbuf;
664 case CACHE_FPL_STATUS_ABORTED:
665 TAILQ_INIT(&ndp->ni_cap_tracker);
666 MPASS(ndp->ni_lcf == 0);
667 if (*cnp->cn_pnbuf == '\0') {
668 if ((cnp->cn_flags & EMPTYPATH) != 0) {
669 return (namei_emptypath(ndp));
671 namei_cleanup_cnp(cnp);
672 SDT_PROBE4(vfs, namei, lookup, return, ENOENT, NULL,
676 error = namei_setup(ndp, &dp, &pwd);
678 namei_cleanup_cnp(cnp);
688 ndp->ni_startdir = dp;
689 error = vfs_lookup(ndp);
691 if (__predict_false(pwd->pwd_adir != pwd->pwd_rdir &&
693 (cnp->cn_flags & ISRESTARTED) == 0)) {
694 nameicap_cleanup(ndp);
696 namei_cleanup_cnp(cnp);
704 * If not a symbolic link, we're done.
706 if ((cnp->cn_flags & ISSYMLINK) == 0) {
707 SDT_PROBE4(vfs, namei, lookup, return, error,
708 ndp->ni_vp, false, ndp);
709 nameicap_cleanup(ndp);
714 error = namei_follow_link(ndp);
720 * Check if root directory should replace current directory.
722 cnp->cn_nameptr = cnp->cn_pnbuf;
723 if (*(cnp->cn_nameptr) == '/') {
725 * Reset the lookup to start from the real root without
726 * origin path name reloading.
728 if (__predict_false(ndp->ni_rootdir != pwd->pwd_rdir)) {
729 cnp->cn_flags |= ISRESTARTED;
730 ndp->ni_rootdir = pwd->pwd_rdir;
733 error = namei_handle_root(ndp, &dp);
743 SDT_PROBE4(vfs, namei, lookup, return, error, NULL, false, ndp);
744 namei_cleanup_cnp(cnp);
745 nameicap_cleanup(ndp);
751 compute_cn_lkflags(struct mount *mp, int lkflags, int cnflags)
754 if (mp == NULL || ((lkflags & LK_SHARED) &&
755 !(mp->mnt_kern_flag & MNTK_LOOKUP_SHARED))) {
756 lkflags &= ~LK_SHARED;
757 lkflags |= LK_EXCLUSIVE;
759 lkflags |= LK_NODDLKTREAT;
764 needs_exclusive_leaf(struct mount *mp, int flags)
768 * Intermediate nodes can use shared locks, we only need to
769 * force an exclusive lock for leaf nodes.
771 if ((flags & (ISLASTCN | LOCKLEAF)) != (ISLASTCN | LOCKLEAF))
774 /* Always use exclusive locks if LOCKSHARED isn't set. */
775 if (!(flags & LOCKSHARED))
779 * For lookups during open(), if the mount point supports
780 * extended shared operations, then use a shared lock for the
781 * leaf node, otherwise use an exclusive lock.
783 if ((flags & ISOPEN) != 0)
784 return (!MNT_EXTENDED_SHARED(mp));
787 * Lookup requests outside of open() that specify LOCKSHARED
788 * only need a shared lock on the leaf vnode.
794 * Various filesystems expect to be able to copy a name component with length
795 * bounded by NAME_MAX into a directory entry buffer of size MAXNAMLEN. Make
796 * sure that these are the same size.
798 _Static_assert(MAXNAMLEN == NAME_MAX,
799 "MAXNAMLEN and NAME_MAX have different values");
801 static int __noinline
802 vfs_lookup_degenerate(struct nameidata *ndp, struct vnode *dp, int wantparent)
804 struct componentname *cnp;
810 cnp->cn_flags |= ISLASTCN;
812 mp = atomic_load_ptr(&dp->v_mount);
813 if (needs_exclusive_leaf(mp, cnp->cn_flags)) {
814 cnp->cn_lkflags &= ~LK_SHARED;
815 cnp->cn_lkflags |= LK_EXCLUSIVE;
819 compute_cn_lkflags(mp, cnp->cn_lkflags | LK_RETRY,
822 if (dp->v_type != VDIR) {
826 if (cnp->cn_nameiop != LOOKUP) {
837 if (cnp->cn_flags & AUDITVNODE1)
838 AUDIT_ARG_VNODE1(dp);
839 else if (cnp->cn_flags & AUDITVNODE2)
840 AUDIT_ARG_VNODE2(dp);
842 if (!(cnp->cn_flags & (LOCKPARENT | LOCKLEAF)))
851 * FAILIFEXISTS handling.
853 * XXX namei called with LOCKPARENT but not LOCKLEAF has the strange
854 * behaviour of leaving the vnode unlocked if the target is the same
855 * vnode as the parent.
857 static int __noinline
858 vfs_lookup_failifexists(struct nameidata *ndp)
860 struct componentname *cnp __diagused;
864 MPASS((cnp->cn_flags & ISSYMLINK) == 0);
865 if (ndp->ni_vp == ndp->ni_dvp)
878 * This is a very central and rather complicated routine.
880 * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
881 * The starting directory is taken from ni_startdir. The pathname is
882 * descended until done, or a symbolic link is encountered. The variable
883 * ni_more is clear if the path is completed; it is set to one if a
884 * symbolic link needing interpretation is encountered.
886 * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
887 * whether the name is to be looked up, created, renamed, or deleted.
888 * When CREATE, RENAME, or DELETE is specified, information usable in
889 * creating, renaming, or deleting a directory entry may be calculated.
890 * If flag has LOCKPARENT or'ed into it, the parent directory is returned
891 * locked. If flag has WANTPARENT or'ed into it, the parent directory is
892 * returned unlocked. Otherwise the parent directory is not returned. If
893 * the target of the pathname exists and LOCKLEAF is or'ed into the flag
894 * the target is returned locked, otherwise it is returned unlocked.
895 * When creating or renaming and LOCKPARENT is specified, the target may not
896 * be ".". When deleting and LOCKPARENT is specified, the target may be ".".
898 * Overall outline of lookup:
901 * identify next component of name at ndp->ni_ptr
902 * handle degenerate case where name is null string
903 * if .. and crossing mount points and on mounted filesys, find parent
904 * call VOP_LOOKUP routine for next component name
905 * directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
906 * component vnode returned in ni_vp (if it exists), locked.
907 * if result vnode is mounted on and crossing mount points,
908 * find mounted on vnode
909 * if more components of name, do next level at dirloop
910 * return the answer in ni_vp, locked if LOCKLEAF set
911 * if LOCKPARENT set, return locked parent in ni_dvp
912 * if WANTPARENT set, return unlocked parent in ni_dvp
915 vfs_lookup(struct nameidata *ndp)
917 char *cp; /* pointer into pathname argument */
918 char *prev_ni_next; /* saved ndp->ni_next */
919 char *nulchar; /* location of '\0' in cn_pnbuf */
920 char *lastchar; /* location of the last character */
921 struct vnode *dp = NULL; /* the directory we are searching */
922 struct vnode *tdp; /* saved dp */
923 struct mount *mp; /* mount table entry */
925 size_t prev_ni_pathlen; /* saved ndp->ni_pathlen */
926 int docache; /* == 0 do not cache last component */
927 int wantparent; /* 1 => wantparent or lockparent flag */
928 int rdonly; /* lookup read-only flag bit */
930 int dpunlocked = 0; /* dp has already been unlocked */
931 int relookup = 0; /* do not consume the path component */
932 struct componentname *cnp = &ndp->ni_cnd;
939 * Setup: break out flag bits into variables.
942 wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
943 KASSERT(cnp->cn_nameiop == LOOKUP || wantparent,
944 ("CREATE, DELETE, RENAME require LOCKPARENT or WANTPARENT."));
946 * When set to zero, docache causes the last component of the
947 * pathname to be deleted from the cache and the full lookup
948 * of the name to be done (via VOP_CACHEDLOOKUP()). Often
949 * filesystems need some pre-computed values that are made
950 * during the full lookup, for instance UFS sets dp->i_offset.
952 * The docache variable is set to zero when requested by the
953 * NOCACHE flag and for all modifying operations except CREATE.
955 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
956 if (cnp->cn_nameiop == DELETE ||
957 (wantparent && cnp->cn_nameiop != CREATE &&
958 cnp->cn_nameiop != LOOKUP))
960 rdonly = cnp->cn_flags & RDONLY;
961 cnp->cn_flags &= ~ISSYMLINK;
964 cnp->cn_lkflags = LK_SHARED;
965 dp = ndp->ni_startdir;
966 ndp->ni_startdir = NULLVP;
969 * Leading slashes, if any, are supposed to be skipped by the caller.
971 MPASS(cnp->cn_nameptr[0] != '/');
974 * Check for degenerate name (e.g. / or "") which is a way of talking
975 * about a directory, e.g. like "/." or ".".
977 if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
978 error = vfs_lookup_degenerate(ndp, dp, wantparent);
980 goto success_right_lock;
985 * Nul-out trailing slashes (e.g., "foo///" -> "foo").
987 * This must be done before VOP_LOOKUP() because some fs's don't know
988 * about trailing slashes. Remember if there were trailing slashes to
989 * handle symlinks, existing non-directories and non-existing files
990 * that won't be directories specially later.
992 MPASS(ndp->ni_pathlen >= 2);
993 lastchar = &cnp->cn_nameptr[ndp->ni_pathlen - 2];
994 if (*lastchar == '/') {
995 while (lastchar >= cnp->cn_pnbuf) {
999 if (*lastchar != '/') {
1003 cnp->cn_flags |= TRAILINGSLASH;
1007 * We use shared locks until we hit the parent of the last cn then
1008 * we adjust based on the requesting flags.
1011 compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags | LK_RETRY,
1016 * Search a new directory.
1018 * The last component of the filename is left accessible via
1019 * cnp->cn_nameptr. It has to be freed with a call to NDFREE*.
1021 * Store / as a temporary sentinel so that we only have one character
1022 * to test for. Pathnames tend to be short so this should not be
1023 * resulting in cache misses.
1025 nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
1026 KASSERT(*nulchar == '\0',
1027 ("%s: expected nul at %p; string [%s]\n", __func__, nulchar,
1030 for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
1031 KASSERT(*cp != '\0',
1032 ("%s: encountered unexpected nul; string [%s]\n", __func__,
1037 cnp->cn_namelen = cp - cnp->cn_nameptr;
1038 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
1039 error = ENAMETOOLONG;
1042 #ifdef NAMEI_DIAGNOSTIC
1045 printf("{%s}: ", cnp->cn_nameptr);
1048 prev_ni_pathlen = ndp->ni_pathlen;
1049 ndp->ni_pathlen -= cnp->cn_namelen;
1050 KASSERT(ndp->ni_pathlen <= PATH_MAX,
1051 ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
1052 prev_ni_next = ndp->ni_next;
1056 * Something else should be clearing this.
1058 cnp->cn_flags &= ~(ISDOTDOT|ISLASTCN);
1060 cnp->cn_flags |= MAKEENTRY;
1061 if (*cp == '\0' && docache == 0)
1062 cnp->cn_flags &= ~MAKEENTRY;
1063 if (cnp->cn_namelen == 2 &&
1064 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
1065 cnp->cn_flags |= ISDOTDOT;
1066 if (*ndp->ni_next == 0) {
1067 cnp->cn_flags |= ISLASTCN;
1069 if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.' &&
1070 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))) {
1076 nameicap_tracker_add(ndp, dp);
1079 * Make sure degenerate names don't get here, their handling was
1080 * previously found in this spot.
1082 MPASS(cnp->cn_nameptr[0] != '\0');
1085 * Handle "..": five special cases.
1086 * 0. If doing a capability lookup and lookup_cap_dotdot is
1087 * disabled, return ENOTCAPABLE.
1088 * 1. Return an error if this is the last component of
1089 * the name and the operation is DELETE or RENAME.
1090 * 2. If at root directory (e.g. after chroot)
1091 * or at absolute root directory
1092 * then ignore it so can't get out.
1093 * 3. If this vnode is the root of a mounted
1094 * filesystem, then replace it with the
1095 * vnode which was mounted on so we take the
1096 * .. in the other filesystem.
1097 * 4. If the vnode is the top directory of
1098 * the jail or chroot, don't let them out.
1099 * 5. If doing a capability lookup and lookup_cap_dotdot is
1100 * enabled, return ENOTCAPABLE if the lookup would escape
1101 * from the initial file descriptor directory. Checks are
1102 * done by ensuring that namei() already traversed the
1103 * result of dotdot lookup.
1105 if (cnp->cn_flags & ISDOTDOT) {
1106 if ((ndp->ni_lcf & (NI_LCF_STRICTRELATIVE | NI_LCF_CAP_DOTDOT))
1107 == NI_LCF_STRICTRELATIVE) {
1109 if (KTRPOINT(curthread, KTR_CAPFAIL))
1110 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1112 error = ENOTCAPABLE;
1115 if ((cnp->cn_flags & ISLASTCN) != 0 &&
1116 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1121 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
1123 if (dp == pr->pr_root)
1125 bool isroot = dp == ndp->ni_rootdir ||
1126 dp == ndp->ni_topdir || dp == rootvnode ||
1128 if (isroot && (ndp->ni_lcf &
1129 NI_LCF_STRICTRELATIVE) != 0) {
1130 error = ENOTCAPABLE;
1133 if (isroot || ((dp->v_vflag & VV_ROOT) != 0 &&
1134 (cnp->cn_flags & NOCROSSMOUNT) != 0)) {
1140 if ((dp->v_vflag & VV_ROOT) == 0)
1142 if (VN_IS_DOOMED(dp)) { /* forced unmount */
1147 dp = dp->v_mount->mnt_vnodecovered;
1151 compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags |
1152 LK_RETRY, ISDOTDOT));
1153 error = nameicap_check_dotdot(ndp, dp);
1157 if (KTRPOINT(curthread, KTR_CAPFAIL))
1158 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1166 * We now have a segment name to search for, and a directory to search.
1170 error = mac_vnode_check_lookup(cnp->cn_cred, dp, cnp);
1171 if (__predict_false(error))
1176 ASSERT_VOP_LOCKED(dp, "lookup");
1178 * If we have a shared lock we may need to upgrade the lock for the
1181 if ((cnp->cn_flags & LOCKPARENT) && (cnp->cn_flags & ISLASTCN) &&
1182 dp != vp_crossmp && VOP_ISLOCKED(dp) == LK_SHARED)
1183 vn_lock(dp, LK_UPGRADE|LK_RETRY);
1184 if (VN_IS_DOOMED(dp)) {
1189 * If we're looking up the last component and we need an exclusive
1190 * lock, adjust our lkflags.
1192 if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags))
1193 cnp->cn_lkflags = LK_EXCLUSIVE;
1194 #ifdef NAMEI_DIAGNOSTIC
1195 vn_printf(dp, "lookup in ");
1197 lkflags_save = cnp->cn_lkflags;
1198 cnp->cn_lkflags = compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags,
1200 error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp);
1201 cnp->cn_lkflags = lkflags_save;
1203 KASSERT(ndp->ni_vp == NULL, ("leaf should be empty"));
1204 #ifdef NAMEI_DIAGNOSTIC
1205 printf("not found\n");
1207 if ((error == ENOENT) &&
1208 (dp->v_vflag & VV_ROOT) && (dp->v_mount != NULL) &&
1209 (dp->v_mount->mnt_flag & MNT_UNION)) {
1211 dp = dp->v_mount->mnt_vnodecovered;
1215 compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags |
1216 LK_RETRY, cnp->cn_flags));
1217 nameicap_tracker_add(ndp, dp);
1221 if (error == ERELOOKUP) {
1229 if (error != EJUSTRETURN)
1232 * At this point, we know we're at the end of the
1233 * pathname. If creating / renaming, we can consider
1234 * allowing the file or directory to be created / renamed,
1235 * provided we're not on a read-only filesystem.
1241 /* trailing slash only allowed for directories */
1242 if ((cnp->cn_flags & TRAILINGSLASH) &&
1243 !(cnp->cn_flags & WILLBEDIR)) {
1247 if ((cnp->cn_flags & LOCKPARENT) == 0)
1250 * We return with ni_vp NULL to indicate that the entry
1251 * doesn't currently exist, leaving a pointer to the
1252 * (possibly locked) directory vnode in ndp->ni_dvp.
1258 #ifdef NAMEI_DIAGNOSTIC
1264 * Check for symbolic link
1266 if ((dp->v_type == VLNK) &&
1267 ((cnp->cn_flags & FOLLOW) || (cnp->cn_flags & TRAILINGSLASH) ||
1268 *ndp->ni_next == '/')) {
1269 cnp->cn_flags |= ISSYMLINK;
1270 if (VN_IS_DOOMED(dp)) {
1272 * We can't know whether the directory was mounted with
1273 * NOSYMFOLLOW, so we can't follow safely.
1278 if (dp->v_mount->mnt_flag & MNT_NOSYMFOLLOW) {
1283 * Symlink code always expects an unlocked dvp.
1285 if (ndp->ni_dvp != ndp->ni_vp) {
1286 VOP_UNLOCK(ndp->ni_dvp);
1287 ni_dvp_unlocked = 1;
1290 } else if ((vn_irflag_read(dp) & VIRF_MOUNTPOINT) != 0) {
1291 if ((cnp->cn_flags & NOCROSSMOUNT) != 0)
1297 * Check to see if the vnode has been mounted on;
1298 * if so find the root of the mounted filesystem.
1301 mp = dp->v_mountedhere;
1303 ("%s: NULL mountpoint for VIRF_MOUNTPOINT vnode", __func__));
1304 crosslock = (dp->v_vflag & VV_CROSSLOCK) != 0;
1305 crosslkflags = compute_cn_lkflags(mp, cnp->cn_lkflags,
1307 if (__predict_false(crosslock)) {
1309 * We are going to be holding the vnode lock, which
1310 * in this case is shared by the root vnode of the
1311 * filesystem mounted at mp, across the call to
1312 * VFS_ROOT(). Make the situation clear to the
1313 * filesystem by passing LK_CANRECURSE if the
1314 * lock is held exclusive, or by clearinng
1315 * LK_NODDLKTREAT to allow recursion on the shared
1316 * lock in the presence of an exclusive waiter.
1318 if (VOP_ISLOCKED(dp) == LK_EXCLUSIVE) {
1319 crosslkflags &= ~LK_SHARED;
1320 crosslkflags |= LK_EXCLUSIVE | LK_CANRECURSE;
1321 } else if ((crosslkflags & LK_EXCLUSIVE) != 0) {
1322 vn_lock(dp, LK_UPGRADE | LK_RETRY);
1323 if (VN_IS_DOOMED(dp)) {
1327 if (dp->v_mountedhere != mp) {
1331 crosslkflags &= ~LK_NODDLKTREAT;
1333 if (vfs_busy(mp, 0) != 0)
1335 if (__predict_true(!crosslock))
1337 if (dp != ndp->ni_dvp)
1341 vrefact(vp_crossmp);
1342 ndp->ni_dvp = vp_crossmp;
1343 error = VFS_ROOT(mp, crosslkflags, &tdp);
1345 if (__predict_false(crosslock))
1347 if (vn_lock(vp_crossmp, LK_SHARED | LK_NOWAIT))
1348 panic("vp_crossmp exclusively locked or reclaimed");
1353 ndp->ni_vp = dp = tdp;
1354 } while ((vn_irflag_read(dp) & VIRF_MOUNTPOINT) != 0);
1358 * Not a symbolic link that we will follow. Continue with the
1359 * next component if there is any; otherwise, we're done.
1361 KASSERT((cnp->cn_flags & ISLASTCN) || *ndp->ni_next == '/',
1362 ("lookup: invalid path state."));
1365 ndp->ni_pathlen = prev_ni_pathlen;
1366 ndp->ni_next = prev_ni_next;
1367 if (ndp->ni_dvp != dp)
1373 if (cnp->cn_flags & ISDOTDOT) {
1374 error = nameicap_check_dotdot(ndp, ndp->ni_vp);
1377 if (KTRPOINT(curthread, KTR_CAPFAIL))
1378 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1383 if (*ndp->ni_next == '/') {
1384 cnp->cn_nameptr = ndp->ni_next;
1385 while (*cnp->cn_nameptr == '/') {
1389 if (ndp->ni_dvp != dp)
1396 * If we're processing a path with a trailing slash,
1397 * check that the end result is a directory.
1399 if ((cnp->cn_flags & TRAILINGSLASH) && dp->v_type != VDIR) {
1404 * Disallow directory write attempts on read-only filesystems.
1407 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1412 ni_dvp_unlocked = 2;
1413 if (ndp->ni_dvp != dp)
1417 } else if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp != dp) {
1418 VOP_UNLOCK(ndp->ni_dvp);
1419 ni_dvp_unlocked = 1;
1422 if (cnp->cn_flags & AUDITVNODE1)
1423 AUDIT_ARG_VNODE1(dp);
1424 else if (cnp->cn_flags & AUDITVNODE2)
1425 AUDIT_ARG_VNODE2(dp);
1427 if ((cnp->cn_flags & LOCKLEAF) == 0)
1431 * FIXME: for lookups which only cross a mount point to fetch the
1432 * root vnode, ni_dvp will be set to vp_crossmp. This can be a problem
1433 * if either WANTPARENT or LOCKPARENT is set.
1436 * Because of shared lookup we may have the vnode shared locked, but
1437 * the caller may want it to be exclusively locked.
1439 if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags) &&
1440 VOP_ISLOCKED(dp) != LK_EXCLUSIVE) {
1441 vn_lock(dp, LK_UPGRADE | LK_RETRY);
1442 if (VN_IS_DOOMED(dp)) {
1448 if (ndp->ni_vp != NULL) {
1449 if ((cnp->cn_flags & ISDOTDOT) == 0)
1450 nameicap_tracker_add(ndp, ndp->ni_vp);
1451 if ((cnp->cn_flags & (FAILIFEXISTS | ISSYMLINK)) == FAILIFEXISTS)
1452 return (vfs_lookup_failifexists(ndp));
1457 if (ni_dvp_unlocked != 2) {
1458 if (dp != ndp->ni_dvp && !ni_dvp_unlocked)
1472 * relookup - lookup a path name component
1473 * Used by lookup to re-acquire things.
1476 vfs_relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1479 struct vnode *dp = NULL; /* the directory we are searching */
1480 int rdonly; /* lookup read-only flag bit */
1483 KASSERT(cnp->cn_flags & ISLASTCN,
1484 ("relookup: Not given last component."));
1486 * Setup: break out flag bits into variables.
1488 KASSERT((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) != 0,
1489 ("relookup: parent not wanted"));
1490 rdonly = cnp->cn_flags & RDONLY;
1491 cnp->cn_flags &= ~ISSYMLINK;
1493 cnp->cn_lkflags = LK_EXCLUSIVE;
1494 vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
1497 * Search a new directory.
1499 * See a comment in vfs_lookup for cnp->cn_nameptr.
1501 #ifdef NAMEI_DIAGNOSTIC
1502 printf("{%s}: ", cnp->cn_nameptr);
1506 * Check for "" which represents the root directory after slash
1509 if (cnp->cn_nameptr[0] == '\0') {
1511 * Support only LOOKUP for "/" because lookup()
1512 * can't succeed for CREATE, DELETE and RENAME.
1514 KASSERT(cnp->cn_nameiop == LOOKUP, ("nameiop must be LOOKUP"));
1515 KASSERT(dp->v_type == VDIR, ("dp is not a directory"));
1517 if (!(cnp->cn_flags & LOCKLEAF))
1520 /* XXX This should probably move to the top of function. */
1522 panic("lookup: SAVESTART");
1526 if (cnp->cn_flags & ISDOTDOT)
1527 panic ("relookup: lookup on dot-dot");
1530 * We now have a segment name to search for, and a directory to search.
1532 #ifdef NAMEI_DIAGNOSTIC
1533 vn_printf(dp, "search in ");
1535 if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
1536 KASSERT(*vpp == NULL, ("leaf should be empty"));
1537 if (error != EJUSTRETURN)
1540 * If creating and at end of pathname, then can consider
1541 * allowing file to be created.
1547 /* ASSERT(dvp == ndp->ni_startdir) */
1550 if ((cnp->cn_flags & LOCKPARENT) == 0)
1553 * We return with ni_vp NULL to indicate that the entry
1554 * doesn't currently exist, leaving a pointer to the
1555 * (possibly locked) directory vnode in ndp->ni_dvp.
1563 * Disallow directory write attempts on read-only filesystems.
1566 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1575 * Set the parent lock/ref state to the requested state.
1577 if ((cnp->cn_flags & LOCKPARENT) == 0 && dvp != dp)
1580 * Check for symbolic link
1582 KASSERT(dp->v_type != VLNK || !(cnp->cn_flags & FOLLOW),
1583 ("relookup: symlink found.\n"));
1585 /* ASSERT(dvp == ndp->ni_startdir) */
1589 if ((cnp->cn_flags & LOCKLEAF) == 0)
1600 * Validate the final state of ndp after the lookup.
1603 NDVALIDATE_impl(struct nameidata *ndp, int line)
1605 struct componentname *cnp;
1608 if (cnp->cn_pnbuf == NULL)
1609 panic("%s: got no buf! called from %d", __func__, line);