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