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