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