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