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