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