]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_lookup.c
awk: Merge upstream 2nd Edition Awk Book
[FreeBSD/FreeBSD.git] / sys / kern / vfs_lookup.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
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.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
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.
23  *
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
34  * SUCH DAMAGE.
35  *
36  *      @(#)vfs_lookup.c        8.4 (Berkeley) 2/16/94
37  */
38
39 #include <sys/cdefs.h>
40 #include "opt_capsicum.h"
41 #include "opt_ktrace.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/dirent.h>
46 #include <sys/kernel.h>
47 #include <sys/capsicum.h>
48 #include <sys/fcntl.h>
49 #include <sys/jail.h>
50 #include <sys/lock.h>
51 #include <sys/mutex.h>
52 #include <sys/namei.h>
53 #include <sys/vnode.h>
54 #include <sys/mount.h>
55 #include <sys/filedesc.h>
56 #include <sys/proc.h>
57 #include <sys/sdt.h>
58 #include <sys/syscallsubr.h>
59 #include <sys/sysctl.h>
60 #ifdef KTRACE
61 #include <sys/ktrace.h>
62 #endif
63 #ifdef INVARIANTS
64 #include <machine/_inttypes.h>
65 #endif
66
67 #include <security/audit/audit.h>
68 #include <security/mac/mac_framework.h>
69
70 #include <vm/uma.h>
71
72 #ifdef INVARIANTS
73 static void NDVALIDATE_impl(struct nameidata *, int);
74 #define NDVALIDATE(ndp) NDVALIDATE_impl(ndp, __LINE__)
75 #else
76 #define NDVALIDATE(ndp)
77 #endif
78
79 /*
80  * Prepare namei() to restart. Reset components to its original state and set
81  * ISRESTARTED flag which signals the underlying lookup code to change the root
82  * from ABI root to actual root and prevents a further restarts.
83  */
84 #define NDRESTART(ndp) do {                                             \
85         NDREINIT_DBG(ndp);                                              \
86         ndp->ni_resflags = 0;                                           \
87         ndp->ni_cnd.cn_flags &= ~NAMEI_INTERNAL_FLAGS;                  \
88         ndp->ni_cnd.cn_flags |= ISRESTARTED;                            \
89 } while (0)
90
91 SDT_PROVIDER_DEFINE(vfs);
92 SDT_PROBE_DEFINE4(vfs, namei, lookup, entry, "struct vnode *", "char *",
93     "unsigned long", "bool");
94 SDT_PROBE_DEFINE4(vfs, namei, lookup, return, "int", "struct vnode *", "bool",
95     "struct nameidata");
96
97 /* Allocation zone for namei. */
98 uma_zone_t namei_zone;
99
100 /* Placeholder vnode for mp traversal. */
101 static struct vnode *vp_crossmp;
102
103 static int
104 crossmp_vop_islocked(struct vop_islocked_args *ap)
105 {
106
107         return (LK_SHARED);
108 }
109
110 static int
111 crossmp_vop_lock1(struct vop_lock1_args *ap)
112 {
113         struct vnode *vp;
114         struct lock *lk __diagused;
115         int flags;
116
117         vp = ap->a_vp;
118         lk = vp->v_vnlock;
119         flags = ap->a_flags;
120
121         KASSERT((flags & (LK_SHARED | LK_NOWAIT)) == (LK_SHARED | LK_NOWAIT),
122             ("%s: invalid lock request 0x%x for crossmp", __func__, flags));
123
124         if ((flags & LK_INTERLOCK) != 0)
125                 VI_UNLOCK(vp);
126         LOCK_LOG_LOCK("SLOCK", &lk->lock_object, 0, 0, ap->a_file, ap->a_line);
127         return (0);
128 }
129
130 static int
131 crossmp_vop_unlock(struct vop_unlock_args *ap)
132 {
133         struct vnode *vp;
134         struct lock *lk __diagused;
135
136         vp = ap->a_vp;
137         lk = vp->v_vnlock;
138
139         LOCK_LOG_LOCK("SUNLOCK", &lk->lock_object, 0, 0, LOCK_FILE,
140             LOCK_LINE);
141         return (0);
142 }
143
144 static struct vop_vector crossmp_vnodeops = {
145         .vop_default =          &default_vnodeops,
146         .vop_islocked =         crossmp_vop_islocked,
147         .vop_lock1 =            crossmp_vop_lock1,
148         .vop_unlock =           crossmp_vop_unlock,
149 };
150 /*
151  * VFS_VOP_VECTOR_REGISTER(crossmp_vnodeops) is not used here since the vnode
152  * gets allocated early. See nameiinit for the direct call below.
153  */
154
155 struct nameicap_tracker {
156         struct vnode *dp;
157         TAILQ_ENTRY(nameicap_tracker) nm_link;
158 };
159
160 /* Zone for cap mode tracker elements used for dotdot capability checks. */
161 MALLOC_DEFINE(M_NAMEITRACKER, "namei_tracker", "namei tracking for dotdot");
162
163 static void
164 nameiinit(void *dummy __unused)
165 {
166
167         namei_zone = uma_zcreate("NAMEI", MAXPATHLEN, NULL, NULL, NULL, NULL,
168             UMA_ALIGN_PTR, 0);
169         vfs_vector_op_register(&crossmp_vnodeops);
170         getnewvnode("crossmp", NULL, &crossmp_vnodeops, &vp_crossmp);
171         vp_crossmp->v_state = VSTATE_CONSTRUCTED;
172         vp_crossmp->v_irflag |= VIRF_CROSSMP;
173 }
174 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nameiinit, NULL);
175
176 static int lookup_cap_dotdot = 1;
177 SYSCTL_INT(_vfs, OID_AUTO, lookup_cap_dotdot, CTLFLAG_RWTUN,
178     &lookup_cap_dotdot, 0,
179     "enables \"..\" components in path lookup in capability mode");
180 static int lookup_cap_dotdot_nonlocal = 1;
181 SYSCTL_INT(_vfs, OID_AUTO, lookup_cap_dotdot_nonlocal, CTLFLAG_RWTUN,
182     &lookup_cap_dotdot_nonlocal, 0,
183     "enables \"..\" components in path lookup in capability mode "
184     "on non-local mount");
185
186 static void
187 nameicap_tracker_add(struct nameidata *ndp, struct vnode *dp)
188 {
189         struct nameicap_tracker *nt;
190
191         if ((ndp->ni_lcf & NI_LCF_CAP_DOTDOT) == 0 || dp->v_type != VDIR)
192                 return;
193         nt = TAILQ_LAST(&ndp->ni_cap_tracker, nameicap_tracker_head);
194         if (nt != NULL && nt->dp == dp)
195                 return;
196         nt = malloc(sizeof(*nt), M_NAMEITRACKER, M_WAITOK);
197         vhold(dp);
198         nt->dp = dp;
199         TAILQ_INSERT_TAIL(&ndp->ni_cap_tracker, nt, nm_link);
200 }
201
202 static void
203 nameicap_cleanup_from(struct nameidata *ndp, struct nameicap_tracker *first)
204 {
205         struct nameicap_tracker *nt, *nt1;
206
207         nt = first;
208         TAILQ_FOREACH_FROM_SAFE(nt, &ndp->ni_cap_tracker, nm_link, nt1) {
209                 TAILQ_REMOVE(&ndp->ni_cap_tracker, nt, nm_link);
210                 vdrop(nt->dp);
211                 free(nt, M_NAMEITRACKER);
212         }
213 }
214
215 static void
216 nameicap_cleanup(struct nameidata *ndp)
217 {
218         KASSERT(TAILQ_EMPTY(&ndp->ni_cap_tracker) ||
219             (ndp->ni_lcf & NI_LCF_CAP_DOTDOT) != 0, ("not strictrelative"));
220         nameicap_cleanup_from(ndp, NULL);
221 }
222
223 /*
224  * For dotdot lookups in capability mode, only allow the component
225  * lookup to succeed if the resulting directory was already traversed
226  * during the operation.  This catches situations where already
227  * traversed directory is moved to different parent, and then we walk
228  * over it with dotdots.
229  *
230  * Also allow to force failure of dotdot lookups for non-local
231  * filesystems, where external agents might assist local lookups to
232  * escape the compartment.
233  */
234 static int
235 nameicap_check_dotdot(struct nameidata *ndp, struct vnode *dp)
236 {
237         struct nameicap_tracker *nt;
238         struct mount *mp;
239
240         if (dp == NULL || dp->v_type != VDIR || (ndp->ni_lcf &
241             NI_LCF_STRICTRELATIVE) == 0)
242                 return (0);
243         if ((ndp->ni_lcf & NI_LCF_CAP_DOTDOT) == 0)
244                 return (ENOTCAPABLE);
245         mp = dp->v_mount;
246         if (lookup_cap_dotdot_nonlocal == 0 && mp != NULL &&
247             (mp->mnt_flag & MNT_LOCAL) == 0)
248                 return (ENOTCAPABLE);
249         TAILQ_FOREACH_REVERSE(nt, &ndp->ni_cap_tracker, nameicap_tracker_head,
250             nm_link) {
251                 if (dp == nt->dp) {
252                         nt = TAILQ_NEXT(nt, nm_link);
253                         if (nt != NULL)
254                                 nameicap_cleanup_from(ndp, nt);
255                         return (0);
256                 }
257         }
258         return (ENOTCAPABLE);
259 }
260
261 static void
262 namei_cleanup_cnp(struct componentname *cnp)
263 {
264
265         uma_zfree(namei_zone, cnp->cn_pnbuf);
266         cnp->cn_pnbuf = NULL;
267         cnp->cn_nameptr = NULL;
268 }
269
270 static int
271 namei_handle_root(struct nameidata *ndp, struct vnode **dpp)
272 {
273         struct componentname *cnp;
274
275         cnp = &ndp->ni_cnd;
276         if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) != 0) {
277 #ifdef KTRACE
278                 if (KTRPOINT(curthread, KTR_CAPFAIL))
279                         ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
280 #endif
281                 return (ENOTCAPABLE);
282         }
283         while (*(cnp->cn_nameptr) == '/') {
284                 cnp->cn_nameptr++;
285                 ndp->ni_pathlen--;
286         }
287         *dpp = ndp->ni_rootdir;
288         vrefact(*dpp);
289         return (0);
290 }
291
292 static int
293 namei_setup(struct nameidata *ndp, struct vnode **dpp, struct pwd **pwdp)
294 {
295         struct componentname *cnp;
296         struct thread *td;
297         struct pwd *pwd;
298         int error;
299         bool startdir_used;
300
301         cnp = &ndp->ni_cnd;
302         td = curthread;
303
304         startdir_used = false;
305         *pwdp = NULL;
306         *dpp = NULL;
307
308 #ifdef CAPABILITY_MODE
309         /*
310          * In capability mode, lookups must be restricted to happen in
311          * the subtree with the root specified by the file descriptor:
312          * - The root must be real file descriptor, not the pseudo-descriptor
313          *   AT_FDCWD.
314          * - The passed path must be relative and not absolute.
315          * - If lookup_cap_dotdot is disabled, path must not contain the
316          *   '..' components.
317          * - If lookup_cap_dotdot is enabled, we verify that all '..'
318          *   components lookups result in the directories which were
319          *   previously walked by us, which prevents an escape from
320          *   the relative root.
321          */
322         if (IN_CAPABILITY_MODE(td) && (cnp->cn_flags & NOCAPCHECK) == 0) {
323                 ndp->ni_lcf |= NI_LCF_STRICTRELATIVE;
324                 ndp->ni_resflags |= NIRES_STRICTREL;
325                 if (ndp->ni_dirfd == AT_FDCWD) {
326 #ifdef KTRACE
327                         if (KTRPOINT(td, KTR_CAPFAIL))
328                                 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
329 #endif
330                         return (ECAPMODE);
331                 }
332         }
333 #endif
334         error = 0;
335
336         /*
337          * Get starting point for the translation.
338          */
339         pwd = pwd_hold(td);
340         /*
341          * The reference on ni_rootdir is acquired in the block below to avoid
342          * back-to-back atomics for absolute lookups.
343          */
344         namei_setup_rootdir(ndp, cnp, pwd);
345         ndp->ni_topdir = pwd->pwd_jdir;
346
347         if (cnp->cn_pnbuf[0] == '/') {
348                 ndp->ni_resflags |= NIRES_ABS;
349                 error = namei_handle_root(ndp, dpp);
350         } else {
351                 if (ndp->ni_startdir != NULL) {
352                         *dpp = ndp->ni_startdir;
353                         startdir_used = true;
354                 } else if (ndp->ni_dirfd == AT_FDCWD) {
355                         *dpp = pwd->pwd_cdir;
356                         vrefact(*dpp);
357                 } else {
358                         if (cnp->cn_flags & AUDITVNODE1)
359                                 AUDIT_ARG_ATFD1(ndp->ni_dirfd);
360                         if (cnp->cn_flags & AUDITVNODE2)
361                                 AUDIT_ARG_ATFD2(ndp->ni_dirfd);
362
363                         error = fgetvp_lookup(ndp->ni_dirfd, ndp, dpp);
364                 }
365                 if (error == 0 && (*dpp)->v_type != VDIR &&
366                     (cnp->cn_pnbuf[0] != '\0' ||
367                     (cnp->cn_flags & EMPTYPATH) == 0))
368                         error = ENOTDIR;
369         }
370         if (error == 0 && (cnp->cn_flags & RBENEATH) != 0) {
371                 if (cnp->cn_pnbuf[0] == '/') {
372                         error = ENOTCAPABLE;
373                 } else if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) == 0) {
374                         ndp->ni_lcf |= NI_LCF_STRICTRELATIVE |
375                             NI_LCF_CAP_DOTDOT;
376                 }
377         }
378
379         /*
380          * If we are auditing the kernel pathname, save the user pathname.
381          */
382         if (AUDITING_TD(td)) {
383                 if (cnp->cn_flags & AUDITVNODE1)
384                         AUDIT_ARG_UPATH1_VP(td, ndp->ni_rootdir, *dpp, cnp->cn_pnbuf);
385                 if (cnp->cn_flags & AUDITVNODE2)
386                         AUDIT_ARG_UPATH2_VP(td, ndp->ni_rootdir, *dpp, cnp->cn_pnbuf);
387         }
388         if (ndp->ni_startdir != NULL && !startdir_used)
389                 vrele(ndp->ni_startdir);
390         if (error != 0) {
391                 if (*dpp != NULL)
392                         vrele(*dpp);
393                 pwd_drop(pwd);
394                 return (error);
395         }
396         if ((ndp->ni_lcf & NI_LCF_STRICTRELATIVE) != 0 &&
397             lookup_cap_dotdot != 0)
398                 ndp->ni_lcf |= NI_LCF_CAP_DOTDOT;
399         SDT_PROBE4(vfs, namei, lookup, entry, *dpp, cnp->cn_pnbuf,
400             cnp->cn_flags, false);
401         *pwdp = pwd;
402         return (0);
403 }
404
405 static int
406 namei_getpath(struct nameidata *ndp)
407 {
408         struct componentname *cnp;
409         int error;
410
411         cnp = &ndp->ni_cnd;
412
413         /*
414          * Get a buffer for the name to be translated, and copy the
415          * name into the buffer.
416          */
417         cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
418         if (ndp->ni_segflg == UIO_SYSSPACE) {
419                 error = copystr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
420                     &ndp->ni_pathlen);
421         } else {
422                 error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf, MAXPATHLEN,
423                     &ndp->ni_pathlen);
424         }
425
426         return (error);
427 }
428
429 static int
430 namei_emptypath(struct nameidata *ndp)
431 {
432         struct componentname *cnp;
433         struct pwd *pwd;
434         struct vnode *dp;
435         int error;
436
437         cnp = &ndp->ni_cnd;
438         MPASS(*cnp->cn_pnbuf == '\0');
439         MPASS((cnp->cn_flags & EMPTYPATH) != 0);
440         MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
441
442         ndp->ni_resflags |= NIRES_EMPTYPATH;
443         error = namei_setup(ndp, &dp, &pwd);
444         if (error != 0) {
445                 goto errout;
446         }
447
448         /*
449          * Usecount on dp already provided by namei_setup.
450          */
451         ndp->ni_vp = dp;
452         pwd_drop(pwd);
453         NDVALIDATE(ndp);
454         if ((cnp->cn_flags & LOCKLEAF) != 0) {
455                 VOP_LOCK(dp, (cnp->cn_flags & LOCKSHARED) != 0 ?
456                     LK_SHARED : LK_EXCLUSIVE);
457                 if (VN_IS_DOOMED(dp)) {
458                         vput(dp);
459                         error = ENOENT;
460                         goto errout;
461                 }
462         }
463         SDT_PROBE4(vfs, namei, lookup, return, 0, ndp->ni_vp, false, ndp);
464         return (0);
465
466 errout:
467         SDT_PROBE4(vfs, namei, lookup, return, error, NULL, false, ndp);
468         namei_cleanup_cnp(cnp);
469         return (error);
470 }
471
472 static int __noinline
473 namei_follow_link(struct nameidata *ndp)
474 {
475         char *cp;
476         struct iovec aiov;
477         struct uio auio;
478         struct componentname *cnp;
479         struct thread *td;
480         int error, linklen;
481
482         error = 0;
483         cnp = &ndp->ni_cnd;
484         td = curthread;
485
486         if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
487                 error = ELOOP;
488                 goto out;
489         }
490 #ifdef MAC
491         if ((cnp->cn_flags & NOMACCHECK) == 0) {
492                 error = mac_vnode_check_readlink(td->td_ucred, ndp->ni_vp);
493                 if (error != 0)
494                         goto out;
495         }
496 #endif
497         if (ndp->ni_pathlen > 1)
498                 cp = uma_zalloc(namei_zone, M_WAITOK);
499         else
500                 cp = cnp->cn_pnbuf;
501         aiov.iov_base = cp;
502         aiov.iov_len = MAXPATHLEN;
503         auio.uio_iov = &aiov;
504         auio.uio_iovcnt = 1;
505         auio.uio_offset = 0;
506         auio.uio_rw = UIO_READ;
507         auio.uio_segflg = UIO_SYSSPACE;
508         auio.uio_td = td;
509         auio.uio_resid = MAXPATHLEN;
510         error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
511         if (error != 0) {
512                 if (ndp->ni_pathlen > 1)
513                         uma_zfree(namei_zone, cp);
514                 goto out;
515         }
516         linklen = MAXPATHLEN - auio.uio_resid;
517         if (linklen == 0) {
518                 if (ndp->ni_pathlen > 1)
519                         uma_zfree(namei_zone, cp);
520                 error = ENOENT;
521                 goto out;
522         }
523         if (linklen + ndp->ni_pathlen > MAXPATHLEN) {
524                 if (ndp->ni_pathlen > 1)
525                         uma_zfree(namei_zone, cp);
526                 error = ENAMETOOLONG;
527                 goto out;
528         }
529         if (ndp->ni_pathlen > 1) {
530                 bcopy(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
531                 uma_zfree(namei_zone, cnp->cn_pnbuf);
532                 cnp->cn_pnbuf = cp;
533         } else
534                 cnp->cn_pnbuf[linklen] = '\0';
535         ndp->ni_pathlen += linklen;
536 out:
537         return (error);
538 }
539
540 /*
541  * Convert a pathname into a pointer to a locked vnode.
542  *
543  * The FOLLOW flag is set when symbolic links are to be followed
544  * when they occur at the end of the name translation process.
545  * Symbolic links are always followed for all other pathname
546  * components other than the last.
547  *
548  * The segflg defines whether the name is to be copied from user
549  * space or kernel space.
550  *
551  * Overall outline of namei:
552  *
553  *      copy in name
554  *      get starting directory
555  *      while (!done && !error) {
556  *              call lookup to search path.
557  *              if symbolic link, massage name in buffer and continue
558  *      }
559  */
560 int
561 namei(struct nameidata *ndp)
562 {
563         struct vnode *dp;       /* the directory we are searching */
564         struct componentname *cnp;
565         struct thread *td;
566         struct pwd *pwd;
567         int error;
568         enum cache_fpl_status status;
569
570         cnp = &ndp->ni_cnd;
571         td = curthread;
572 #ifdef INVARIANTS
573         KASSERT((ndp->ni_debugflags & NAMEI_DBG_CALLED) == 0,
574             ("%s: repeated call to namei without NDREINIT", __func__));
575         KASSERT(ndp->ni_debugflags == NAMEI_DBG_INITED,
576             ("%s: bad debugflags %d", __func__, ndp->ni_debugflags));
577         ndp->ni_debugflags |= NAMEI_DBG_CALLED;
578         if (ndp->ni_startdir != NULL)
579                 ndp->ni_debugflags |= NAMEI_DBG_HADSTARTDIR;
580         if (cnp->cn_flags & FAILIFEXISTS) {
581                 KASSERT(cnp->cn_nameiop == CREATE,
582                     ("%s: FAILIFEXISTS passed for op %d", __func__, cnp->cn_nameiop));
583                 /*
584                  * The limitation below is to restrict hairy corner cases.
585                  */
586                 KASSERT((cnp->cn_flags & (LOCKPARENT | LOCKLEAF)) == LOCKPARENT,
587                     ("%s: FAILIFEXISTS must be passed with LOCKPARENT and without LOCKLEAF",
588                     __func__));
589         }
590 #endif
591         ndp->ni_cnd.cn_cred = td->td_ucred;
592         KASSERT(ndp->ni_resflags == 0, ("%s: garbage in ni_resflags: %x\n",
593             __func__, ndp->ni_resflags));
594         KASSERT(cnp->cn_cred && td->td_proc, ("namei: bad cred/proc"));
595         KASSERT((cnp->cn_flags & NAMEI_INTERNAL_FLAGS) == 0,
596             ("namei: unexpected flags: %" PRIx64 "\n",
597             cnp->cn_flags & NAMEI_INTERNAL_FLAGS));
598         if (cnp->cn_flags & NOCACHE)
599                 KASSERT(cnp->cn_nameiop != LOOKUP,
600                     ("%s: NOCACHE passed with LOOKUP", __func__));
601         MPASS(ndp->ni_startdir == NULL || ndp->ni_startdir->v_type == VDIR ||
602             ndp->ni_startdir->v_type == VBAD);
603
604 restart:
605         ndp->ni_lcf = 0;
606         ndp->ni_loopcnt = 0;
607         ndp->ni_vp = NULL;
608
609         error = namei_getpath(ndp);
610         if (__predict_false(error != 0)) {
611                 namei_cleanup_cnp(cnp);
612                 SDT_PROBE4(vfs, namei, lookup, return, error, NULL,
613                     false, ndp);
614                 return (error);
615         }
616
617         cnp->cn_nameptr = cnp->cn_pnbuf;
618
619 #ifdef KTRACE
620         if (KTRPOINT(td, KTR_NAMEI)) {
621                 ktrnamei(cnp->cn_pnbuf);
622         }
623 #endif
624         TSNAMEI(curthread->td_proc->p_pid, cnp->cn_pnbuf);
625
626         /*
627          * First try looking up the target without locking any vnodes.
628          *
629          * We may need to start from scratch or pick up where it left off.
630          */
631         error = cache_fplookup(ndp, &status, &pwd);
632         switch (status) {
633         case CACHE_FPL_STATUS_UNSET:
634                 __assert_unreachable();
635                 break;
636         case CACHE_FPL_STATUS_HANDLED:
637                 if (error == 0)
638                         NDVALIDATE(ndp);
639                 else if (__predict_false(pwd->pwd_adir != pwd->pwd_rdir &&
640                     (cnp->cn_flags & ISRESTARTED) == 0)) {
641                         namei_cleanup_cnp(cnp);
642                         NDRESTART(ndp);
643                         goto restart;
644                 }
645                 return (error);
646         case CACHE_FPL_STATUS_PARTIAL:
647                 TAILQ_INIT(&ndp->ni_cap_tracker);
648                 dp = ndp->ni_startdir;
649                 break;
650         case CACHE_FPL_STATUS_DESTROYED:
651                 ndp->ni_loopcnt = 0;
652                 error = namei_getpath(ndp);
653                 if (__predict_false(error != 0)) {
654                         namei_cleanup_cnp(cnp);
655                         return (error);
656                 }
657                 cnp->cn_nameptr = cnp->cn_pnbuf;
658                 /* FALLTHROUGH */
659         case CACHE_FPL_STATUS_ABORTED:
660                 TAILQ_INIT(&ndp->ni_cap_tracker);
661                 MPASS(ndp->ni_lcf == 0);
662                 if (*cnp->cn_pnbuf == '\0') {
663                         if ((cnp->cn_flags & EMPTYPATH) != 0) {
664                                 return (namei_emptypath(ndp));
665                         }
666                         namei_cleanup_cnp(cnp);
667                         SDT_PROBE4(vfs, namei, lookup, return, ENOENT, NULL,
668                             false, ndp);
669                         return (ENOENT);
670                 }
671                 error = namei_setup(ndp, &dp, &pwd);
672                 if (error != 0) {
673                         namei_cleanup_cnp(cnp);
674                         return (error);
675                 }
676                 break;
677         }
678
679         /*
680          * Locked lookup.
681          */
682         for (;;) {
683                 ndp->ni_startdir = dp;
684                 error = vfs_lookup(ndp);
685                 if (error != 0) {
686                         if (__predict_false(pwd->pwd_adir != pwd->pwd_rdir &&
687                             error == ENOENT &&
688                             (cnp->cn_flags & ISRESTARTED) == 0)) {
689                                 nameicap_cleanup(ndp);
690                                 pwd_drop(pwd);
691                                 namei_cleanup_cnp(cnp);
692                                 NDRESTART(ndp);
693                                 goto restart;
694                         } else
695                                 goto out;
696                 }
697
698                 /*
699                  * If not a symbolic link, we're done.
700                  */
701                 if ((cnp->cn_flags & ISSYMLINK) == 0) {
702                         SDT_PROBE4(vfs, namei, lookup, return, error,
703                             ndp->ni_vp, false, ndp);
704                         nameicap_cleanup(ndp);
705                         pwd_drop(pwd);
706                         NDVALIDATE(ndp);
707                         return (0);
708                 }
709                 error = namei_follow_link(ndp);
710                 if (error != 0)
711                         break;
712                 vput(ndp->ni_vp);
713                 dp = ndp->ni_dvp;
714                 /*
715                  * Check if root directory should replace current directory.
716                  */
717                 cnp->cn_nameptr = cnp->cn_pnbuf;
718                 if (*(cnp->cn_nameptr) == '/') {
719                         /*
720                          * Reset the lookup to start from the real root without
721                          * origin path name reloading.
722                          */
723                         if (__predict_false(ndp->ni_rootdir != pwd->pwd_rdir)) {
724                                 cnp->cn_flags |= ISRESTARTED;
725                                 ndp->ni_rootdir = pwd->pwd_rdir;
726                         }
727                         vrele(dp);
728                         error = namei_handle_root(ndp, &dp);
729                         if (error != 0)
730                                 goto out;
731                 }
732         }
733         vput(ndp->ni_vp);
734         ndp->ni_vp = NULL;
735         vrele(ndp->ni_dvp);
736 out:
737         MPASS(error != 0);
738         SDT_PROBE4(vfs, namei, lookup, return, error, NULL, false, ndp);
739         namei_cleanup_cnp(cnp);
740         nameicap_cleanup(ndp);
741         pwd_drop(pwd);
742         return (error);
743 }
744
745 static int
746 enforce_lkflags(struct mount *mp, int lkflags)
747 {
748
749         if (mp == NULL || ((lkflags & LK_SHARED) &&
750             !(mp->mnt_kern_flag & MNTK_LOOKUP_SHARED))) {
751                 lkflags &= ~LK_SHARED;
752                 lkflags |= LK_EXCLUSIVE;
753         }
754         lkflags |= LK_NODDLKTREAT;
755         return (lkflags);
756 }
757
758 static __inline int
759 needs_exclusive_leaf(struct mount *mp, int flags)
760 {
761
762         /*
763          * Intermediate nodes can use shared locks, we only need to
764          * force an exclusive lock for leaf nodes.
765          */
766         if ((flags & (ISLASTCN | LOCKLEAF)) != (ISLASTCN | LOCKLEAF))
767                 return (0);
768
769         /* Always use exclusive locks if LOCKSHARED isn't set. */
770         if (!(flags & LOCKSHARED))
771                 return (1);
772
773         /*
774          * For lookups during open(), if the mount point supports
775          * extended shared operations, then use a shared lock for the
776          * leaf node, otherwise use an exclusive lock.
777          */
778         if ((flags & ISOPEN) != 0)
779                 return (!MNT_EXTENDED_SHARED(mp));
780
781         /*
782          * Lookup requests outside of open() that specify LOCKSHARED
783          * only need a shared lock on the leaf vnode.
784          */
785         return (0);
786 }
787
788 /*
789  * Various filesystems expect to be able to copy a name component with length
790  * bounded by NAME_MAX into a directory entry buffer of size MAXNAMLEN.  Make
791  * sure that these are the same size.
792  */
793 _Static_assert(MAXNAMLEN == NAME_MAX,
794     "MAXNAMLEN and NAME_MAX have different values");
795
796 static int __noinline
797 vfs_lookup_degenerate(struct nameidata *ndp, struct vnode *dp, int wantparent)
798 {
799         struct componentname *cnp;
800         struct mount *mp;
801         int error;
802
803         cnp = &ndp->ni_cnd;
804
805         cnp->cn_flags |= ISLASTCN;
806
807         mp = atomic_load_ptr(&dp->v_mount);
808         if (needs_exclusive_leaf(mp, cnp->cn_flags)) {
809                 cnp->cn_lkflags &= ~LK_SHARED;
810                 cnp->cn_lkflags |= LK_EXCLUSIVE;
811         }
812
813         vn_lock(dp, enforce_lkflags(mp, cnp->cn_lkflags | LK_RETRY));
814
815         if (dp->v_type != VDIR) {
816                 error = ENOTDIR;
817                 goto bad;
818         }
819         if (cnp->cn_nameiop != LOOKUP) {
820                 error = EISDIR;
821                 goto bad;
822         }
823         if (wantparent) {
824                 ndp->ni_dvp = dp;
825                 VREF(dp);
826         }
827         ndp->ni_vp = dp;
828         cnp->cn_namelen = 0;
829
830         if (cnp->cn_flags & AUDITVNODE1)
831                 AUDIT_ARG_VNODE1(dp);
832         else if (cnp->cn_flags & AUDITVNODE2)
833                 AUDIT_ARG_VNODE2(dp);
834
835         if (!(cnp->cn_flags & (LOCKPARENT | LOCKLEAF)))
836                 VOP_UNLOCK(dp);
837         return (0);
838 bad:
839         VOP_UNLOCK(dp);
840         return (error);
841 }
842
843 /*
844  * FAILIFEXISTS handling.
845  *
846  * XXX namei called with LOCKPARENT but not LOCKLEAF has the strange
847  * behaviour of leaving the vnode unlocked if the target is the same
848  * vnode as the parent.
849  */
850 static int __noinline
851 vfs_lookup_failifexists(struct nameidata *ndp)
852 {
853         struct componentname *cnp __diagused;
854
855         cnp = &ndp->ni_cnd;
856
857         MPASS((cnp->cn_flags & ISSYMLINK) == 0);
858         if (ndp->ni_vp == ndp->ni_dvp)
859                 vrele(ndp->ni_dvp);
860         else
861                 vput(ndp->ni_dvp);
862         vrele(ndp->ni_vp);
863         ndp->ni_dvp = NULL;
864         ndp->ni_vp = NULL;
865         NDFREE_PNBUF(ndp);
866         return (EEXIST);
867 }
868
869 static int __noinline
870 vfs_lookup_cross_mount(struct nameidata *ndp)
871 {
872         struct componentname *cnp;
873         struct mount *mp;
874         struct vnode *dp, *tdp;
875         int error, crosslkflags;
876         bool crosslock;
877
878         cnp = &ndp->ni_cnd;
879         dp = ndp->ni_vp;
880
881         /*
882          * The vnode has been mounted on, find the root of the mounted
883          * filesystem.
884          */
885         do {
886                 mp = dp->v_mountedhere;
887                 ASSERT_VOP_LOCKED(dp, __func__);
888                 VNPASS((vn_irflag_read(dp) & VIRF_MOUNTPOINT) != 0 && mp != NULL, dp);
889
890                 crosslock = (dp->v_vflag & VV_CROSSLOCK) != 0;
891                 crosslkflags = enforce_lkflags(mp, cnp->cn_lkflags);
892                 if (__predict_false(crosslock)) {
893                         /*
894                          * We are going to be holding the vnode lock, which
895                          * in this case is shared by the root vnode of the
896                          * filesystem mounted at mp, across the call to
897                          * VFS_ROOT().  Make the situation clear to the
898                          * filesystem by passing LK_CANRECURSE if the
899                          * lock is held exclusive, or by clearinng
900                          * LK_NODDLKTREAT to allow recursion on the shared
901                          * lock in the presence of an exclusive waiter.
902                          */
903                         if (VOP_ISLOCKED(dp) == LK_EXCLUSIVE) {
904                                 crosslkflags &= ~LK_SHARED;
905                                 crosslkflags |= LK_EXCLUSIVE | LK_CANRECURSE;
906                         } else if ((crosslkflags & LK_EXCLUSIVE) != 0) {
907                                 error = vn_lock(dp, LK_UPGRADE);
908                                 if (error != 0) {
909                                         MPASS(error == ENOENT);
910                                         vrele(dp);
911                                         if (dp != ndp->ni_dvp)
912                                                 vput(ndp->ni_dvp);
913                                         else
914                                                 vrele(ndp->ni_dvp);
915                                         break;
916                                 }
917                                 if (dp->v_mountedhere != mp) {
918                                         /*
919                                          * Note that we rely on the
920                                          * VIRF_MOUNTPOINT loop condition to
921                                          * ensure we stop iterating if dp is
922                                          * no longer a mountpoint at all.
923                                          */
924                                         continue;
925                                 }
926                         } else
927                                 crosslkflags &= ~LK_NODDLKTREAT;
928                 }
929                 if (vfs_busy(mp, 0) != 0)
930                         continue;
931                 if (__predict_true(!crosslock))
932                         vput(dp);
933                 if (dp != ndp->ni_dvp)
934                         vput(ndp->ni_dvp);
935                 else
936                         vrele(ndp->ni_dvp);
937                 vrefact(vp_crossmp);
938                 ndp->ni_dvp = vp_crossmp;
939                 error = VFS_ROOT(mp, crosslkflags, &tdp);
940                 vfs_unbusy(mp);
941                 if (__predict_false(crosslock))
942                         vput(dp);
943                 if (vn_lock(vp_crossmp, LK_SHARED | LK_NOWAIT))
944                         panic("vp_crossmp exclusively locked or reclaimed");
945                 if (error != 0)
946                         break;
947                 ndp->ni_vp = dp = tdp;
948         } while ((vn_irflag_read(dp) & VIRF_MOUNTPOINT) != 0);
949
950         return (error);
951 }
952
953 /*
954  * Search a pathname.
955  * This is a very central and rather complicated routine.
956  *
957  * The pathname is pointed to by cn_nameptr and is of length ni_pathlen.
958  * The starting directory is taken from ni_startdir. The pathname is
959  * descended until done, or a symbolic link is encountered. The cn_flags
960  * has ISLASTCN or'ed if the path is completed or ISSYMLINK or'ed if a
961  * symbolic link needing interpretation is encountered.
962  *
963  * The cn_nameiop is LOOKUP, CREATE, RENAME, or DELETE depending on
964  * whether the name is to be looked up, created, renamed, or deleted.
965  * When CREATE, RENAME, or DELETE is specified, information usable in
966  * creating, renaming, or deleting a directory entry may be calculated.
967  * If cn_flags has LOCKPARENT or'ed into it, the parent directory is returned
968  * locked. If it has WANTPARENT or'ed into it, the parent directory is
969  * returned unlocked. Otherwise the parent directory is not returned. If
970  * the target of the pathname exists and LOCKLEAF is or'ed into the cn_flags
971  * the target is returned locked, otherwise it is returned unlocked.
972  *
973  * Overall outline of lookup:
974  *
975  *      handle degenerate case where name is null string
976  *
977  * dirloop:
978  *      identify next component of name at ndp->ni_cnd.cn_nameptr
979  *      handle .. special cases related to capabilities, chroot, jail
980  *      if .. and crossing mount points and on mounted filesys, find parent
981  *      call VOP_LOOKUP routine for next component name
982  *          directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
983  *          component vnode returned in ni_vp (if it exists), locked.
984  *      if result vnode is mounted on and crossing mount points,
985  *          find mounted on vnode
986  *      if more components of name, do next level at dirloop
987  *      if VOP_LOOKUP returns ERELOOKUP, repeat the same level at dirloop
988  *      return the answer in ni_vp, locked if LOCKLEAF set
989  *          if LOCKPARENT set, return locked parent in ni_dvp
990  *          if WANTPARENT set, return unlocked parent in ni_dvp
991  */
992 int
993 vfs_lookup(struct nameidata *ndp)
994 {
995         char *cp;                       /* pointer into pathname argument */
996         char *prev_ni_next;             /* saved ndp->ni_next */
997         char *nulchar;                  /* location of '\0' in cn_pnbuf */
998         char *lastchar;                 /* location of the last character */
999         struct vnode *dp = NULL;        /* the directory we are searching */
1000         struct vnode *tdp;              /* saved dp */
1001         struct prison *pr;
1002         size_t prev_ni_pathlen;         /* saved ndp->ni_pathlen */
1003         int docache;                    /* == 0 do not cache last component */
1004         int wantparent;                 /* 1 => wantparent or lockparent flag */
1005         int rdonly;                     /* lookup read-only flag bit */
1006         int error = 0;
1007         int relookup = 0;               /* do not consume the path component */
1008         struct componentname *cnp = &ndp->ni_cnd;
1009         int lkflags_save;
1010         int ni_dvp_unlocked;
1011
1012         /*
1013          * Setup: break out flag bits into variables.
1014          */
1015         ni_dvp_unlocked = 0;
1016         wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
1017         KASSERT(cnp->cn_nameiop == LOOKUP || wantparent,
1018             ("CREATE, DELETE, RENAME require LOCKPARENT or WANTPARENT."));
1019         /*
1020          * When set to zero, docache causes the last component of the
1021          * pathname to be deleted from the cache and the full lookup
1022          * of the name to be done (via VOP_CACHEDLOOKUP()). Often
1023          * filesystems need some pre-computed values that are made
1024          * during the full lookup, for instance UFS sets dp->i_offset.
1025          *
1026          * The docache variable is set to zero when requested by the
1027          * NOCACHE flag and for all modifying operations except CREATE.
1028          */
1029         docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
1030         if (cnp->cn_nameiop == DELETE ||
1031             (wantparent && cnp->cn_nameiop != CREATE &&
1032              cnp->cn_nameiop != LOOKUP))
1033                 docache = 0;
1034         rdonly = cnp->cn_flags & RDONLY;
1035         cnp->cn_flags &= ~ISSYMLINK;
1036         ndp->ni_dvp = NULL;
1037
1038         cnp->cn_lkflags = LK_SHARED;
1039         dp = ndp->ni_startdir;
1040         ndp->ni_startdir = NULLVP;
1041
1042         /*
1043          * Leading slashes, if any, are supposed to be skipped by the caller.
1044          */
1045         MPASS(cnp->cn_nameptr[0] != '/');
1046
1047         /*
1048          * Check for degenerate name (e.g. / or "") which is a way of talking
1049          * about a directory, e.g. like "/." or ".".
1050          */
1051         if (__predict_false(cnp->cn_nameptr[0] == '\0')) {
1052                 error = vfs_lookup_degenerate(ndp, dp, wantparent);
1053                 if (error == 0)
1054                         goto success_right_lock;
1055                 goto bad_unlocked;
1056         }
1057
1058         /*
1059          * Nul-out trailing slashes (e.g., "foo///" -> "foo").
1060          *
1061          * This must be done before VOP_LOOKUP() because some fs's don't know
1062          * about trailing slashes.  Remember if there were trailing slashes to
1063          * handle symlinks, existing non-directories and non-existing files
1064          * that won't be directories specially later.
1065          */
1066         MPASS(ndp->ni_pathlen >= 2);
1067         lastchar = &cnp->cn_nameptr[ndp->ni_pathlen - 2];
1068         if (*lastchar == '/') {
1069                 while (lastchar >= cnp->cn_pnbuf) {
1070                         *lastchar = '\0';
1071                         lastchar--;
1072                         ndp->ni_pathlen--;
1073                         if (*lastchar != '/') {
1074                                 break;
1075                         }
1076                 }
1077                 cnp->cn_flags |= TRAILINGSLASH;
1078         }
1079
1080         /*
1081          * We use shared locks until we hit the parent of the last cn then
1082          * we adjust based on the requesting flags.
1083          */
1084         vn_lock(dp,
1085             enforce_lkflags(dp->v_mount, cnp->cn_lkflags | LK_RETRY));
1086
1087 dirloop:
1088         /*
1089          * Search a new directory.
1090          *
1091          * The last component of the filename is left accessible via
1092          * cnp->cn_nameptr. It has to be freed with a call to NDFREE*.
1093          *
1094          * Store / as a temporary sentinel so that we only have one character
1095          * to test for. Pathnames tend to be short so this should not be
1096          * resulting in cache misses.
1097          */
1098         nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
1099         KASSERT(*nulchar == '\0',
1100             ("%s: expected nul at %p; string [%s]\n", __func__, nulchar,
1101             cnp->cn_pnbuf));
1102         *nulchar = '/';
1103         for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
1104                 KASSERT(*cp != '\0',
1105                     ("%s: encountered unexpected nul; string [%s]\n", __func__,
1106                     cnp->cn_nameptr));
1107                 continue;
1108         }
1109         *nulchar = '\0';
1110         cnp->cn_namelen = cp - cnp->cn_nameptr;
1111         if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
1112                 error = ENAMETOOLONG;
1113                 goto bad;
1114         }
1115         prev_ni_pathlen = ndp->ni_pathlen;
1116         ndp->ni_pathlen -= cnp->cn_namelen;
1117         KASSERT(ndp->ni_pathlen <= PATH_MAX,
1118             ("%s: ni_pathlen underflow to %zd\n", __func__, ndp->ni_pathlen));
1119         prev_ni_next = ndp->ni_next;
1120         ndp->ni_next = cp;
1121
1122         /*
1123          * Something else should be clearing this.
1124          */
1125         cnp->cn_flags &= ~(ISDOTDOT|ISLASTCN);
1126
1127         cnp->cn_flags |= MAKEENTRY;
1128         if (*cp == '\0' && docache == 0)
1129                 cnp->cn_flags &= ~MAKEENTRY;
1130         if (cnp->cn_namelen == 2 &&
1131             cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
1132                 cnp->cn_flags |= ISDOTDOT;
1133         if (*ndp->ni_next == 0) {
1134                 cnp->cn_flags |= ISLASTCN;
1135
1136                 if (__predict_false(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.' &&
1137                     (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))) {
1138                         error = EINVAL;
1139                         goto bad;
1140                 }
1141         }
1142
1143         nameicap_tracker_add(ndp, dp);
1144
1145         /*
1146          * Make sure degenerate names don't get here, their handling was
1147          * previously found in this spot.
1148          */
1149         MPASS(cnp->cn_nameptr[0] != '\0');
1150
1151         /*
1152          * Handle "..": five special cases.
1153          * 0. If doing a capability lookup and lookup_cap_dotdot is
1154          *    disabled, return ENOTCAPABLE.
1155          * 1. Return an error if this is the last component of
1156          *    the name and the operation is DELETE or RENAME.
1157          * 2. If at root directory (e.g. after chroot)
1158          *    or at absolute root directory
1159          *    then ignore it so can't get out.
1160          * 3. If this vnode is the root of a mounted
1161          *    filesystem, then replace it with the
1162          *    vnode which was mounted on so we take the
1163          *    .. in the other filesystem.
1164          * 4. If the vnode is the top directory of
1165          *    the jail or chroot, don't let them out.
1166          * 5. If doing a capability lookup and lookup_cap_dotdot is
1167          *    enabled, return ENOTCAPABLE if the lookup would escape
1168          *    from the initial file descriptor directory.  Checks are
1169          *    done by ensuring that namei() already traversed the
1170          *    result of dotdot lookup.
1171          */
1172         if (cnp->cn_flags & ISDOTDOT) {
1173                 if ((ndp->ni_lcf & (NI_LCF_STRICTRELATIVE | NI_LCF_CAP_DOTDOT))
1174                     == NI_LCF_STRICTRELATIVE) {
1175 #ifdef KTRACE
1176                         if (KTRPOINT(curthread, KTR_CAPFAIL))
1177                                 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1178 #endif
1179                         error = ENOTCAPABLE;
1180                         goto bad;
1181                 }
1182                 if ((cnp->cn_flags & ISLASTCN) != 0 &&
1183                     (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1184                         error = EINVAL;
1185                         goto bad;
1186                 }
1187                 for (;;) {
1188                         for (pr = cnp->cn_cred->cr_prison; pr != NULL;
1189                              pr = pr->pr_parent)
1190                                 if (dp == pr->pr_root)
1191                                         break;
1192                         bool isroot = dp == ndp->ni_rootdir ||
1193                             dp == ndp->ni_topdir || dp == rootvnode ||
1194                             pr != NULL;
1195                         if (isroot && (ndp->ni_lcf &
1196                             NI_LCF_STRICTRELATIVE) != 0) {
1197                                 error = ENOTCAPABLE;
1198                                 goto capdotdot;
1199                         }
1200                         if (isroot || ((dp->v_vflag & VV_ROOT) != 0 &&
1201                             (cnp->cn_flags & NOCROSSMOUNT) != 0)) {
1202                                 ndp->ni_dvp = dp;
1203                                 ndp->ni_vp = dp;
1204                                 VREF(dp);
1205                                 goto nextname;
1206                         }
1207                         if ((dp->v_vflag & VV_ROOT) == 0)
1208                                 break;
1209                         if (VN_IS_DOOMED(dp)) { /* forced unmount */
1210                                 error = ENOENT;
1211                                 goto bad;
1212                         }
1213                         tdp = dp;
1214                         dp = dp->v_mount->mnt_vnodecovered;
1215                         VREF(dp);
1216                         vput(tdp);
1217                         vn_lock(dp,
1218                             enforce_lkflags(dp->v_mount, cnp->cn_lkflags |
1219                             LK_RETRY));
1220                         error = nameicap_check_dotdot(ndp, dp);
1221                         if (error != 0) {
1222 capdotdot:
1223 #ifdef KTRACE
1224                                 if (KTRPOINT(curthread, KTR_CAPFAIL))
1225                                         ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1226 #endif
1227                                 goto bad;
1228                         }
1229                 }
1230         }
1231
1232         /*
1233          * We now have a segment name to search for, and a directory to search.
1234          */
1235 unionlookup:
1236 #ifdef MAC
1237         error = mac_vnode_check_lookup(cnp->cn_cred, dp, cnp);
1238         if (__predict_false(error))
1239                 goto bad;
1240 #endif
1241         ndp->ni_dvp = dp;
1242         ndp->ni_vp = NULL;
1243         ASSERT_VOP_LOCKED(dp, "lookup");
1244         /*
1245          * If we have a shared lock we may need to upgrade the lock for the
1246          * last operation.
1247          */
1248         if ((cnp->cn_flags & LOCKPARENT) && (cnp->cn_flags & ISLASTCN) &&
1249             dp != vp_crossmp && VOP_ISLOCKED(dp) == LK_SHARED)
1250                 vn_lock(dp, LK_UPGRADE|LK_RETRY);
1251         if (VN_IS_DOOMED(dp)) {
1252                 error = ENOENT;
1253                 goto bad;
1254         }
1255         /*
1256          * If we're looking up the last component and we need an exclusive
1257          * lock, adjust our lkflags.
1258          */
1259         if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags))
1260                 cnp->cn_lkflags = LK_EXCLUSIVE;
1261         lkflags_save = cnp->cn_lkflags;
1262         cnp->cn_lkflags = enforce_lkflags(dp->v_mount, cnp->cn_lkflags);
1263         error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp);
1264         cnp->cn_lkflags = lkflags_save;
1265         if (error != 0) {
1266                 KASSERT(ndp->ni_vp == NULL, ("leaf should be empty"));
1267                 if ((error == ENOENT) &&
1268                     (dp->v_vflag & VV_ROOT) && (dp->v_mount != NULL) &&
1269                     (dp->v_mount->mnt_flag & MNT_UNION)) {
1270                         tdp = dp;
1271                         dp = dp->v_mount->mnt_vnodecovered;
1272                         VREF(dp);
1273                         vput(tdp);
1274                         vn_lock(dp,
1275                             enforce_lkflags(dp->v_mount, cnp->cn_lkflags |
1276                             LK_RETRY));
1277                         nameicap_tracker_add(ndp, dp);
1278                         goto unionlookup;
1279                 }
1280
1281                 if (error == ERELOOKUP) {
1282                         vref(dp);
1283                         ndp->ni_vp = dp;
1284                         error = 0;
1285                         relookup = 1;
1286                         goto good;
1287                 }
1288
1289                 if (error != EJUSTRETURN)
1290                         goto bad;
1291                 /*
1292                  * At this point, we know we're at the end of the
1293                  * pathname.  If creating / renaming, we can consider
1294                  * allowing the file or directory to be created / renamed,
1295                  * provided we're not on a read-only filesystem.
1296                  */
1297                 if (rdonly) {
1298                         error = EROFS;
1299                         goto bad;
1300                 }
1301                 /* trailing slash only allowed for directories */
1302                 if ((cnp->cn_flags & TRAILINGSLASH) &&
1303                     !(cnp->cn_flags & WILLBEDIR)) {
1304                         error = ENOENT;
1305                         goto bad;
1306                 }
1307                 if ((cnp->cn_flags & LOCKPARENT) == 0)
1308                         VOP_UNLOCK(dp);
1309                 /*
1310                  * We return with ni_vp NULL to indicate that the entry
1311                  * doesn't currently exist, leaving a pointer to the
1312                  * (possibly locked) directory vnode in ndp->ni_dvp.
1313                  */
1314                 goto success;
1315         }
1316
1317 good:
1318         dp = ndp->ni_vp;
1319
1320         /*
1321          * Check for symbolic link
1322          */
1323         if ((dp->v_type == VLNK) &&
1324             ((cnp->cn_flags & FOLLOW) || (cnp->cn_flags & TRAILINGSLASH) ||
1325              *ndp->ni_next == '/')) {
1326                 cnp->cn_flags |= ISSYMLINK;
1327                 if (VN_IS_DOOMED(dp)) {
1328                         /*
1329                          * We can't know whether the directory was mounted with
1330                          * NOSYMFOLLOW, so we can't follow safely.
1331                          */
1332                         error = ENOENT;
1333                         goto bad2;
1334                 }
1335                 if (dp->v_mount->mnt_flag & MNT_NOSYMFOLLOW) {
1336                         error = EACCES;
1337                         goto bad2;
1338                 }
1339                 /*
1340                  * Symlink code always expects an unlocked dvp.
1341                  */
1342                 if (ndp->ni_dvp != ndp->ni_vp) {
1343                         VOP_UNLOCK(ndp->ni_dvp);
1344                         ni_dvp_unlocked = 1;
1345                 }
1346                 goto success;
1347         }
1348
1349         if ((vn_irflag_read(dp) & VIRF_MOUNTPOINT) != 0 &&
1350             (cnp->cn_flags & NOCROSSMOUNT) == 0) {
1351                 error = vfs_lookup_cross_mount(ndp);
1352                 if (error != 0)
1353                         goto bad_unlocked;
1354                 /*
1355                  * FALLTHROUGH to nextname
1356                  */
1357                 dp = ndp->ni_vp;
1358         }
1359
1360 nextname:
1361         /*
1362          * Not a symbolic link that we will follow.  Continue with the
1363          * next component if there is any; otherwise, we're done.
1364          */
1365         KASSERT((cnp->cn_flags & ISLASTCN) || *ndp->ni_next == '/',
1366             ("lookup: invalid path state."));
1367         if (relookup) {
1368                 relookup = 0;
1369                 ndp->ni_pathlen = prev_ni_pathlen;
1370                 ndp->ni_next = prev_ni_next;
1371                 if (ndp->ni_dvp != dp)
1372                         vput(ndp->ni_dvp);
1373                 else
1374                         vrele(ndp->ni_dvp);
1375                 goto dirloop;
1376         }
1377         if (cnp->cn_flags & ISDOTDOT) {
1378                 error = nameicap_check_dotdot(ndp, ndp->ni_vp);
1379                 if (error != 0) {
1380 #ifdef KTRACE
1381                         if (KTRPOINT(curthread, KTR_CAPFAIL))
1382                                 ktrcapfail(CAPFAIL_LOOKUP, NULL, NULL);
1383 #endif
1384                         goto bad2;
1385                 }
1386         }
1387         if (*ndp->ni_next == '/') {
1388                 cnp->cn_nameptr = ndp->ni_next;
1389                 while (*cnp->cn_nameptr == '/') {
1390                         cnp->cn_nameptr++;
1391                         ndp->ni_pathlen--;
1392                 }
1393                 if (ndp->ni_dvp != dp)
1394                         vput(ndp->ni_dvp);
1395                 else
1396                         vrele(ndp->ni_dvp);
1397                 goto dirloop;
1398         }
1399         /*
1400          * If we're processing a path with a trailing slash,
1401          * check that the end result is a directory.
1402          */
1403         if ((cnp->cn_flags & TRAILINGSLASH) && dp->v_type != VDIR) {
1404                 error = ENOTDIR;
1405                 goto bad2;
1406         }
1407         /*
1408          * Disallow directory write attempts on read-only filesystems.
1409          */
1410         if (rdonly &&
1411             (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1412                 error = EROFS;
1413                 goto bad2;
1414         }
1415         if (!wantparent) {
1416                 ni_dvp_unlocked = 2;
1417                 if (ndp->ni_dvp != dp)
1418                         vput(ndp->ni_dvp);
1419                 else
1420                         vrele(ndp->ni_dvp);
1421         } else if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp != dp) {
1422                 VOP_UNLOCK(ndp->ni_dvp);
1423                 ni_dvp_unlocked = 1;
1424         }
1425
1426         if (cnp->cn_flags & AUDITVNODE1)
1427                 AUDIT_ARG_VNODE1(dp);
1428         else if (cnp->cn_flags & AUDITVNODE2)
1429                 AUDIT_ARG_VNODE2(dp);
1430
1431         if ((cnp->cn_flags & LOCKLEAF) == 0)
1432                 VOP_UNLOCK(dp);
1433 success:
1434         /*
1435          * FIXME: for lookups which only cross a mount point to fetch the
1436          * root vnode, ni_dvp will be set to vp_crossmp. This can be a problem
1437          * if either WANTPARENT or LOCKPARENT is set.
1438          */
1439         /*
1440          * Because of shared lookup we may have the vnode shared locked, but
1441          * the caller may want it to be exclusively locked.
1442          */
1443         if (needs_exclusive_leaf(dp->v_mount, cnp->cn_flags) &&
1444             VOP_ISLOCKED(dp) != LK_EXCLUSIVE) {
1445                 vn_lock(dp, LK_UPGRADE | LK_RETRY);
1446                 if (VN_IS_DOOMED(dp)) {
1447                         error = ENOENT;
1448                         goto bad2;
1449                 }
1450         }
1451 success_right_lock:
1452         if (ndp->ni_vp != NULL) {
1453                 if ((cnp->cn_flags & ISDOTDOT) == 0)
1454                         nameicap_tracker_add(ndp, ndp->ni_vp);
1455                 if ((cnp->cn_flags & (FAILIFEXISTS | ISSYMLINK)) == FAILIFEXISTS)
1456                         return (vfs_lookup_failifexists(ndp));
1457         }
1458         return (0);
1459
1460 bad2:
1461         if (ni_dvp_unlocked != 2) {
1462                 if (dp != ndp->ni_dvp && !ni_dvp_unlocked)
1463                         vput(ndp->ni_dvp);
1464                 else
1465                         vrele(ndp->ni_dvp);
1466         }
1467 bad:
1468         vput(dp);
1469 bad_unlocked:
1470         ndp->ni_vp = NULL;
1471         return (error);
1472 }
1473
1474 /*
1475  * relookup - lookup a path name component
1476  *    Used by lookup to re-acquire things.
1477  */
1478 int
1479 vfs_relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1480     bool refstart)
1481 {
1482         struct vnode *dp = NULL;                /* the directory we are searching */
1483         int rdonly;                     /* lookup read-only flag bit */
1484         int error = 0;
1485
1486         KASSERT(cnp->cn_flags & ISLASTCN,
1487             ("relookup: Not given last component."));
1488         /*
1489          * Setup: break out flag bits into variables.
1490          */
1491         KASSERT((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) != 0,
1492             ("relookup: parent not wanted"));
1493         rdonly = cnp->cn_flags & RDONLY;
1494         cnp->cn_flags &= ~ISSYMLINK;
1495         dp = dvp;
1496         cnp->cn_lkflags = LK_EXCLUSIVE;
1497         vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
1498
1499         /*
1500          * Search a new directory.
1501          *
1502          * See a comment in vfs_lookup for cnp->cn_nameptr.
1503          *
1504          * Check for "" which represents the root directory after slash
1505          * removal.
1506          */
1507         if (cnp->cn_nameptr[0] == '\0') {
1508                 /*
1509                  * Support only LOOKUP for "/" because lookup()
1510                  * can't succeed for CREATE, DELETE and RENAME.
1511                  */
1512                 KASSERT(cnp->cn_nameiop == LOOKUP, ("nameiop must be LOOKUP"));
1513                 KASSERT(dp->v_type == VDIR, ("dp is not a directory"));
1514
1515                 if (!(cnp->cn_flags & LOCKLEAF))
1516                         VOP_UNLOCK(dp);
1517                 *vpp = dp;
1518                 /* XXX This should probably move to the top of function. */
1519                 if (refstart)
1520                         panic("lookup: SAVESTART");
1521                 return (0);
1522         }
1523
1524         if (cnp->cn_flags & ISDOTDOT)
1525                 panic ("relookup: lookup on dot-dot");
1526
1527         /*
1528          * We now have a segment name to search for, and a directory to search.
1529          */
1530         if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
1531                 KASSERT(*vpp == NULL, ("leaf should be empty"));
1532                 if (error != EJUSTRETURN)
1533                         goto bad;
1534                 /*
1535                  * If creating and at end of pathname, then can consider
1536                  * allowing file to be created.
1537                  */
1538                 if (rdonly) {
1539                         error = EROFS;
1540                         goto bad;
1541                 }
1542                 /* ASSERT(dvp == ndp->ni_startdir) */
1543                 if (refstart)
1544                         VREF(dvp);
1545                 if ((cnp->cn_flags & LOCKPARENT) == 0)
1546                         VOP_UNLOCK(dp);
1547                 /*
1548                  * We return with ni_vp NULL to indicate that the entry
1549                  * doesn't currently exist, leaving a pointer to the
1550                  * (possibly locked) directory vnode in ndp->ni_dvp.
1551                  */
1552                 return (0);
1553         }
1554
1555         dp = *vpp;
1556
1557         /*
1558          * Disallow directory write attempts on read-only filesystems.
1559          */
1560         if (rdonly &&
1561             (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
1562                 if (dvp == dp)
1563                         vrele(dvp);
1564                 else
1565                         vput(dvp);
1566                 error = EROFS;
1567                 goto bad;
1568         }
1569         /*
1570          * Set the parent lock/ref state to the requested state.
1571          */
1572         if ((cnp->cn_flags & LOCKPARENT) == 0 && dvp != dp)
1573                 VOP_UNLOCK(dvp);
1574         /*
1575          * Check for symbolic link
1576          */
1577         KASSERT(dp->v_type != VLNK || !(cnp->cn_flags & FOLLOW),
1578             ("relookup: symlink found.\n"));
1579
1580         /* ASSERT(dvp == ndp->ni_startdir) */
1581         if (refstart)
1582                 VREF(dvp);
1583
1584         if ((cnp->cn_flags & LOCKLEAF) == 0)
1585                 VOP_UNLOCK(dp);
1586         return (0);
1587 bad:
1588         vput(dp);
1589         *vpp = NULL;
1590         return (error);
1591 }
1592
1593 #ifdef INVARIANTS
1594 /*
1595  * Validate the final state of ndp after the lookup.
1596  */
1597 static void
1598 NDVALIDATE_impl(struct nameidata *ndp, int line)
1599 {
1600         struct componentname *cnp;
1601
1602         cnp = &ndp->ni_cnd;
1603         if (cnp->cn_pnbuf == NULL)
1604                 panic("%s: got no buf! called from %d", __func__, line);
1605 }
1606
1607 #endif