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