]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_lookup.c
Remove the LOOKUP_SHARED kernel option. Instead, make vfs.lookup_shared
[FreeBSD/FreeBSD.git] / sys / kern / vfs_lookup.c
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)vfs_lookup.c        8.4 (Berkeley) 2/16/94
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 #include "opt_ktrace.h"
41 #include "opt_mac.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/kernel.h>
46 #include <sys/fcntl.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/namei.h>
50 #include <sys/vnode.h>
51 #include <sys/mount.h>
52 #include <sys/filedesc.h>
53 #include <sys/proc.h>
54 #include <sys/syscallsubr.h>
55 #include <sys/sysctl.h>
56 #ifdef KTRACE
57 #include <sys/ktrace.h>
58 #endif
59
60 #include <security/audit/audit.h>
61 #include <security/mac/mac_framework.h>
62
63 #include <vm/uma.h>
64
65 #define NAMEI_DIAGNOSTIC 1
66 #undef NAMEI_DIAGNOSTIC
67
68 /*
69  * Allocation zone for namei
70  */
71 uma_zone_t namei_zone;
72 /*
73  * Placeholder vnode for mp traversal
74  */
75 static struct vnode *vp_crossmp;
76
77 static void
78 nameiinit(void *dummy __unused)
79 {
80         int error;
81
82         namei_zone = uma_zcreate("NAMEI", MAXPATHLEN, NULL, NULL, NULL, NULL,
83             UMA_ALIGN_PTR, 0);
84         error = getnewvnode("crossmp", NULL, &dead_vnodeops, &vp_crossmp);
85         if (error != 0)
86                 panic("nameiinit: getnewvnode");
87         VN_LOCK_ASHARE(vp_crossmp);
88 }
89 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nameiinit, NULL);
90
91 static int lookup_shared = 0;
92 SYSCTL_INT(_vfs, OID_AUTO, lookup_shared, CTLFLAG_RW, &lookup_shared, 0,
93     "Enables/Disables shared locks for path name translation");
94 TUNABLE_INT("vfs.lookup_shared", &lookup_shared);
95
96 /*
97  * Convert a pathname into a pointer to a locked vnode.
98  *
99  * The FOLLOW flag is set when symbolic links are to be followed
100  * when they occur at the end of the name translation process.
101  * Symbolic links are always followed for all other pathname
102  * components other than the last.
103  *
104  * The segflg defines whether the name is to be copied from user
105  * space or kernel space.
106  *
107  * Overall outline of namei:
108  *
109  *      copy in name
110  *      get starting directory
111  *      while (!done && !error) {
112  *              call lookup to search path.
113  *              if symbolic link, massage name in buffer and continue
114  *      }
115  */
116 int
117 namei(struct nameidata *ndp)
118 {
119         struct filedesc *fdp;   /* pointer to file descriptor state */
120         char *cp;               /* pointer into pathname argument */
121         struct vnode *dp;       /* the directory we are searching */
122         struct iovec aiov;              /* uio for reading symbolic links */
123         struct uio auio;
124         int error, linklen;
125         struct componentname *cnp = &ndp->ni_cnd;
126         struct thread *td = cnp->cn_thread;
127         struct proc *p = td->td_proc;
128         int vfslocked;
129
130         KASSERT((cnp->cn_flags & MPSAFE) != 0 || mtx_owned(&Giant) != 0,
131             ("NOT MPSAFE and Giant not held"));
132         ndp->ni_cnd.cn_cred = ndp->ni_cnd.cn_thread->td_ucred;
133         KASSERT(cnp->cn_cred && p, ("namei: bad cred/proc"));
134         KASSERT((cnp->cn_nameiop & (~OPMASK)) == 0,
135             ("namei: nameiop contaminated with flags"));
136         KASSERT((cnp->cn_flags & OPMASK) == 0,
137             ("namei: flags contaminated with nameiops"));
138         if (!lookup_shared)
139                 cnp->cn_flags &= ~LOCKSHARED;
140         fdp = p->p_fd;
141
142         /*
143          * Get a buffer for the name to be translated, and copy the
144          * name into the buffer.
145          */
146         if ((cnp->cn_flags & HASBUF) == 0)
147                 cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
148         if (ndp->ni_segflg == UIO_SYSSPACE)
149                 error = copystr(ndp->ni_dirp, cnp->cn_pnbuf,
150                             MAXPATHLEN, (size_t *)&ndp->ni_pathlen);
151         else
152                 error = copyinstr(ndp->ni_dirp, cnp->cn_pnbuf,
153                             MAXPATHLEN, (size_t *)&ndp->ni_pathlen);
154
155         /* If we are auditing the kernel pathname, save the user pathname. */
156         if (cnp->cn_flags & AUDITVNODE1)
157                 AUDIT_ARG(upath, td, cnp->cn_pnbuf, ARG_UPATH1);
158         if (cnp->cn_flags & AUDITVNODE2)
159                 AUDIT_ARG(upath, td, cnp->cn_pnbuf, ARG_UPATH2);
160
161         /*
162          * Don't allow empty pathnames.
163          */
164         if (!error && *cnp->cn_pnbuf == '\0')
165                 error = ENOENT;
166
167         if (error) {
168                 uma_zfree(namei_zone, cnp->cn_pnbuf);
169 #ifdef DIAGNOSTIC
170                 cnp->cn_pnbuf = NULL;
171                 cnp->cn_nameptr = NULL;
172 #endif
173                 ndp->ni_vp = NULL;
174                 return (error);
175         }
176         ndp->ni_loopcnt = 0;
177 #ifdef KTRACE
178         if (KTRPOINT(td, KTR_NAMEI)) {
179                 KASSERT(cnp->cn_thread == curthread,
180                     ("namei not using curthread"));
181                 ktrnamei(cnp->cn_pnbuf);
182         }
183 #endif
184
185         /*
186          * Get starting point for the translation.
187          */
188         FILEDESC_SLOCK(fdp);
189         ndp->ni_rootdir = fdp->fd_rdir;
190         ndp->ni_topdir = fdp->fd_jdir;
191
192         if (cnp->cn_pnbuf[0] != '/' && ndp->ni_dirfd != AT_FDCWD) {
193                 error = fgetvp(td, ndp->ni_dirfd, &dp);
194                 FILEDESC_SUNLOCK(fdp);
195                 if (error == 0 && dp->v_type != VDIR) {
196                         vfslocked = VFS_LOCK_GIANT(dp->v_mount);
197                         vrele(dp);
198                         VFS_UNLOCK_GIANT(vfslocked);
199                         error = ENOTDIR;
200                 }
201                 if (error) {
202                         uma_zfree(namei_zone, cnp->cn_pnbuf);
203 #ifdef DIAGNOSTIC
204                         cnp->cn_pnbuf = NULL;
205                         cnp->cn_nameptr = NULL;
206 #endif
207                         return (error);
208                 }
209         } else {
210                 dp = fdp->fd_cdir;
211                 VREF(dp);
212                 FILEDESC_SUNLOCK(fdp);
213         }
214         vfslocked = VFS_LOCK_GIANT(dp->v_mount);
215         for (;;) {
216                 /*
217                  * Check if root directory should replace current directory.
218                  * Done at start of translation and after symbolic link.
219                  */
220                 cnp->cn_nameptr = cnp->cn_pnbuf;
221                 if (*(cnp->cn_nameptr) == '/') {
222                         vrele(dp);
223                         VFS_UNLOCK_GIANT(vfslocked);
224                         while (*(cnp->cn_nameptr) == '/') {
225                                 cnp->cn_nameptr++;
226                                 ndp->ni_pathlen--;
227                         }
228                         dp = ndp->ni_rootdir;
229                         vfslocked = VFS_LOCK_GIANT(dp->v_mount);
230                         VREF(dp);
231                 }
232                 if (vfslocked)
233                         ndp->ni_cnd.cn_flags |= GIANTHELD;
234                 ndp->ni_startdir = dp;
235                 error = lookup(ndp);
236                 if (error) {
237                         uma_zfree(namei_zone, cnp->cn_pnbuf);
238 #ifdef DIAGNOSTIC
239                         cnp->cn_pnbuf = NULL;
240                         cnp->cn_nameptr = NULL;
241 #endif
242                         return (error);
243                 }
244                 vfslocked = (ndp->ni_cnd.cn_flags & GIANTHELD) != 0;
245                 ndp->ni_cnd.cn_flags &= ~GIANTHELD;
246                 /*
247                  * Check for symbolic link
248                  */
249                 if ((cnp->cn_flags & ISSYMLINK) == 0) {
250                         if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0) {
251                                 uma_zfree(namei_zone, cnp->cn_pnbuf);
252 #ifdef DIAGNOSTIC
253                                 cnp->cn_pnbuf = NULL;
254                                 cnp->cn_nameptr = NULL;
255 #endif
256                         } else
257                                 cnp->cn_flags |= HASBUF;
258
259                         if ((cnp->cn_flags & MPSAFE) == 0) {
260                                 VFS_UNLOCK_GIANT(vfslocked);
261                         } else if (vfslocked)
262                                 ndp->ni_cnd.cn_flags |= GIANTHELD;
263                         return (0);
264                 }
265                 if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
266                         error = ELOOP;
267                         break;
268                 }
269 #ifdef MAC
270                 if ((cnp->cn_flags & NOMACCHECK) == 0) {
271                         error = mac_vnode_check_readlink(td->td_ucred,
272                             ndp->ni_vp);
273                         if (error)
274                                 break;
275                 }
276 #endif
277                 if (ndp->ni_pathlen > 1)
278                         cp = uma_zalloc(namei_zone, M_WAITOK);
279                 else
280                         cp = cnp->cn_pnbuf;
281                 aiov.iov_base = cp;
282                 aiov.iov_len = MAXPATHLEN;
283                 auio.uio_iov = &aiov;
284                 auio.uio_iovcnt = 1;
285                 auio.uio_offset = 0;
286                 auio.uio_rw = UIO_READ;
287                 auio.uio_segflg = UIO_SYSSPACE;
288                 auio.uio_td = (struct thread *)0;
289                 auio.uio_resid = MAXPATHLEN;
290                 error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
291                 if (error) {
292                         if (ndp->ni_pathlen > 1)
293                                 uma_zfree(namei_zone, cp);
294                         break;
295                 }
296                 linklen = MAXPATHLEN - auio.uio_resid;
297                 if (linklen == 0) {
298                         if (ndp->ni_pathlen > 1)
299                                 uma_zfree(namei_zone, cp);
300                         error = ENOENT;
301                         break;
302                 }
303                 if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
304                         if (ndp->ni_pathlen > 1)
305                                 uma_zfree(namei_zone, cp);
306                         error = ENAMETOOLONG;
307                         break;
308                 }
309                 if (ndp->ni_pathlen > 1) {
310                         bcopy(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
311                         uma_zfree(namei_zone, cnp->cn_pnbuf);
312                         cnp->cn_pnbuf = cp;
313                 } else
314                         cnp->cn_pnbuf[linklen] = '\0';
315                 ndp->ni_pathlen += linklen;
316                 vput(ndp->ni_vp);
317                 dp = ndp->ni_dvp;
318         }
319         uma_zfree(namei_zone, cnp->cn_pnbuf);
320 #ifdef DIAGNOSTIC
321         cnp->cn_pnbuf = NULL;
322         cnp->cn_nameptr = NULL;
323 #endif
324         vput(ndp->ni_vp);
325         ndp->ni_vp = NULL;
326         vrele(ndp->ni_dvp);
327         VFS_UNLOCK_GIANT(vfslocked);
328         return (error);
329 }
330
331 static int
332 compute_cn_lkflags(struct mount *mp, int lkflags)
333 {
334         if (mp == NULL || 
335             ((lkflags & LK_SHARED) && !(mp->mnt_kern_flag & MNTK_LOOKUP_SHARED))) {
336                 lkflags &= ~LK_SHARED;
337                 lkflags |= LK_EXCLUSIVE;
338         }
339         return lkflags;
340 }
341
342 /*
343  * Search a pathname.
344  * This is a very central and rather complicated routine.
345  *
346  * The pathname is pointed to by ni_ptr and is of length ni_pathlen.
347  * The starting directory is taken from ni_startdir. The pathname is
348  * descended until done, or a symbolic link is encountered. The variable
349  * ni_more is clear if the path is completed; it is set to one if a
350  * symbolic link needing interpretation is encountered.
351  *
352  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
353  * whether the name is to be looked up, created, renamed, or deleted.
354  * When CREATE, RENAME, or DELETE is specified, information usable in
355  * creating, renaming, or deleting a directory entry may be calculated.
356  * If flag has LOCKPARENT or'ed into it, the parent directory is returned
357  * locked. If flag has WANTPARENT or'ed into it, the parent directory is
358  * returned unlocked. Otherwise the parent directory is not returned. If
359  * the target of the pathname exists and LOCKLEAF is or'ed into the flag
360  * the target is returned locked, otherwise it is returned unlocked.
361  * When creating or renaming and LOCKPARENT is specified, the target may not
362  * be ".".  When deleting and LOCKPARENT is specified, the target may be ".".
363  *
364  * Overall outline of lookup:
365  *
366  * dirloop:
367  *      identify next component of name at ndp->ni_ptr
368  *      handle degenerate case where name is null string
369  *      if .. and crossing mount points and on mounted filesys, find parent
370  *      call VOP_LOOKUP routine for next component name
371  *          directory vnode returned in ni_dvp, unlocked unless LOCKPARENT set
372  *          component vnode returned in ni_vp (if it exists), locked.
373  *      if result vnode is mounted on and crossing mount points,
374  *          find mounted on vnode
375  *      if more components of name, do next level at dirloop
376  *      return the answer in ni_vp, locked if LOCKLEAF set
377  *          if LOCKPARENT set, return locked parent in ni_dvp
378  *          if WANTPARENT set, return unlocked parent in ni_dvp
379  */
380 int
381 lookup(struct nameidata *ndp)
382 {
383         char *cp;               /* pointer into pathname argument */
384         struct vnode *dp = 0;   /* the directory we are searching */
385         struct vnode *tdp;              /* saved dp */
386         struct mount *mp;               /* mount table entry */
387         int docache;                    /* == 0 do not cache last component */
388         int wantparent;                 /* 1 => wantparent or lockparent flag */
389         int rdonly;                     /* lookup read-only flag bit */
390         int trailing_slash;
391         int error = 0;
392         int dpunlocked = 0;             /* dp has already been unlocked */
393         struct componentname *cnp = &ndp->ni_cnd;
394         struct thread *td = cnp->cn_thread;
395         int vfslocked;                  /* VFS Giant state for child */
396         int dvfslocked;                 /* VFS Giant state for parent */
397         int tvfslocked;
398         int lkflags_save;
399         
400         /*
401          * Setup: break out flag bits into variables.
402          */
403         dvfslocked = (ndp->ni_cnd.cn_flags & GIANTHELD) != 0;
404         vfslocked = 0;
405         ndp->ni_cnd.cn_flags &= ~GIANTHELD;
406         wantparent = cnp->cn_flags & (LOCKPARENT | WANTPARENT);
407         KASSERT(cnp->cn_nameiop == LOOKUP || wantparent,
408             ("CREATE, DELETE, RENAME require LOCKPARENT or WANTPARENT."));
409         docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
410         if (cnp->cn_nameiop == DELETE ||
411             (wantparent && cnp->cn_nameiop != CREATE &&
412              cnp->cn_nameiop != LOOKUP))
413                 docache = 0;
414         rdonly = cnp->cn_flags & RDONLY;
415         cnp->cn_flags &= ~ISSYMLINK;
416         ndp->ni_dvp = NULL;
417         /*
418          * We use shared locks until we hit the parent of the last cn then
419          * we adjust based on the requesting flags.
420          */
421         if (lookup_shared)
422                 cnp->cn_lkflags = LK_SHARED;
423         else
424                 cnp->cn_lkflags = LK_EXCLUSIVE;
425         dp = ndp->ni_startdir;
426         ndp->ni_startdir = NULLVP;
427         vn_lock(dp,
428             compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags | LK_RETRY));
429
430 dirloop:
431         /*
432          * Search a new directory.
433          *
434          * The last component of the filename is left accessible via
435          * cnp->cn_nameptr for callers that need the name. Callers needing
436          * the name set the SAVENAME flag. When done, they assume
437          * responsibility for freeing the pathname buffer.
438          */
439         cnp->cn_consume = 0;
440         for (cp = cnp->cn_nameptr; *cp != 0 && *cp != '/'; cp++)
441                 continue;
442         cnp->cn_namelen = cp - cnp->cn_nameptr;
443         if (cnp->cn_namelen > NAME_MAX) {
444                 error = ENAMETOOLONG;
445                 goto bad;
446         }
447 #ifdef NAMEI_DIAGNOSTIC
448         { char c = *cp;
449         *cp = '\0';
450         printf("{%s}: ", cnp->cn_nameptr);
451         *cp = c; }
452 #endif
453         ndp->ni_pathlen -= cnp->cn_namelen;
454         ndp->ni_next = cp;
455
456         /*
457          * Replace multiple slashes by a single slash and trailing slashes
458          * by a null.  This must be done before VOP_LOOKUP() because some
459          * fs's don't know about trailing slashes.  Remember if there were
460          * trailing slashes to handle symlinks, existing non-directories
461          * and non-existing files that won't be directories specially later.
462          */
463         trailing_slash = 0;
464         while (*cp == '/' && (cp[1] == '/' || cp[1] == '\0')) {
465                 cp++;
466                 ndp->ni_pathlen--;
467                 if (*cp == '\0') {
468                         trailing_slash = 1;
469                         *ndp->ni_next = '\0';   /* XXX for direnter() ... */
470                 }
471         }
472         ndp->ni_next = cp;
473
474         cnp->cn_flags |= MAKEENTRY;
475         if (*cp == '\0' && docache == 0)
476                 cnp->cn_flags &= ~MAKEENTRY;
477         if (cnp->cn_namelen == 2 &&
478             cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
479                 cnp->cn_flags |= ISDOTDOT;
480         else
481                 cnp->cn_flags &= ~ISDOTDOT;
482         if (*ndp->ni_next == 0)
483                 cnp->cn_flags |= ISLASTCN;
484         else
485                 cnp->cn_flags &= ~ISLASTCN;
486
487
488         /*
489          * Check for degenerate name (e.g. / or "")
490          * which is a way of talking about a directory,
491          * e.g. like "/." or ".".
492          */
493         if (cnp->cn_nameptr[0] == '\0') {
494                 if (dp->v_type != VDIR) {
495                         error = ENOTDIR;
496                         goto bad;
497                 }
498                 if (cnp->cn_nameiop != LOOKUP) {
499                         error = EISDIR;
500                         goto bad;
501                 }
502                 if (wantparent) {
503                         ndp->ni_dvp = dp;
504                         VREF(dp);
505                 }
506                 ndp->ni_vp = dp;
507
508                 if (cnp->cn_flags & AUDITVNODE1)
509                         AUDIT_ARG(vnode, dp, ARG_VNODE1);
510                 else if (cnp->cn_flags & AUDITVNODE2)
511                         AUDIT_ARG(vnode, dp, ARG_VNODE2);
512
513                 if (!(cnp->cn_flags & (LOCKPARENT | LOCKLEAF)))
514                         VOP_UNLOCK(dp, 0);
515                 /* XXX This should probably move to the top of function. */
516                 if (cnp->cn_flags & SAVESTART)
517                         panic("lookup: SAVESTART");
518                 goto success;
519         }
520
521         /*
522          * Handle "..": four special cases.
523          * 1. Return an error if this is the last component of
524          *    the name and the operation is DELETE or RENAME.
525          * 2. If at root directory (e.g. after chroot)
526          *    or at absolute root directory
527          *    then ignore it so can't get out.
528          * 3. If this vnode is the root of a mounted
529          *    filesystem, then replace it with the
530          *    vnode which was mounted on so we take the
531          *    .. in the other filesystem.
532          * 4. If the vnode is the top directory of
533          *    the jail or chroot, don't let them out.
534          */
535         if (cnp->cn_flags & ISDOTDOT) {
536                 if ((cnp->cn_flags & ISLASTCN) != 0 &&
537                     (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
538                         error = EINVAL;
539                         goto bad;
540                 }
541                 for (;;) {
542                         if (dp == ndp->ni_rootdir || 
543                             dp == ndp->ni_topdir || 
544                             dp == rootvnode ||
545                             ((dp->v_vflag & VV_ROOT) != 0 &&
546                              (cnp->cn_flags & NOCROSSMOUNT) != 0)) {
547                                 ndp->ni_dvp = dp;
548                                 ndp->ni_vp = dp;
549                                 vfslocked = VFS_LOCK_GIANT(dp->v_mount);
550                                 VREF(dp);
551                                 goto nextname;
552                         }
553                         if ((dp->v_vflag & VV_ROOT) == 0)
554                                 break;
555                         if (dp->v_iflag & VI_DOOMED) {  /* forced unmount */
556                                 error = EBADF;
557                                 goto bad;
558                         }
559                         tdp = dp;
560                         dp = dp->v_mount->mnt_vnodecovered;
561                         tvfslocked = dvfslocked;
562                         dvfslocked = VFS_LOCK_GIANT(dp->v_mount);
563                         VREF(dp);
564                         vput(tdp);
565                         VFS_UNLOCK_GIANT(tvfslocked);
566                         vn_lock(dp,
567                             compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags |
568                             LK_RETRY));
569                 }
570         }
571
572         /*
573          * We now have a segment name to search for, and a directory to search.
574          */
575 unionlookup:
576 #ifdef MAC
577         if ((cnp->cn_flags & NOMACCHECK) == 0) {
578                 error = mac_vnode_check_lookup(td->td_ucred, dp, cnp);
579                 if (error)
580                         goto bad;
581         }
582 #endif
583         ndp->ni_dvp = dp;
584         ndp->ni_vp = NULL;
585         ASSERT_VOP_LOCKED(dp, "lookup");
586         VNASSERT(vfslocked == 0, dp, ("lookup: vfslocked %d", vfslocked));
587         /*
588          * If we have a shared lock we may need to upgrade the lock for the
589          * last operation.
590          */
591         if (dp != vp_crossmp &&
592             VOP_ISLOCKED(dp) == LK_SHARED &&
593             (cnp->cn_flags & ISLASTCN) && (cnp->cn_flags & LOCKPARENT))
594                 vn_lock(dp, LK_UPGRADE|LK_RETRY);
595         /*
596          * If we're looking up the last component and we need an exclusive
597          * lock, adjust our lkflags.
598          */
599         if ((cnp->cn_flags & (ISLASTCN|LOCKSHARED|LOCKLEAF)) ==
600             (ISLASTCN|LOCKLEAF))
601                 cnp->cn_lkflags = LK_EXCLUSIVE;
602 #ifdef NAMEI_DIAGNOSTIC
603         vprint("lookup in", dp);
604 #endif
605         lkflags_save = cnp->cn_lkflags;
606         cnp->cn_lkflags = compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags);
607         if ((error = VOP_LOOKUP(dp, &ndp->ni_vp, cnp)) != 0) {
608                 cnp->cn_lkflags = lkflags_save;
609                 KASSERT(ndp->ni_vp == NULL, ("leaf should be empty"));
610 #ifdef NAMEI_DIAGNOSTIC
611                 printf("not found\n");
612 #endif
613                 if ((error == ENOENT) &&
614                     (dp->v_vflag & VV_ROOT) && (dp->v_mount != NULL) &&
615                     (dp->v_mount->mnt_flag & MNT_UNION)) {
616                         tdp = dp;
617                         dp = dp->v_mount->mnt_vnodecovered;
618                         tvfslocked = dvfslocked;
619                         dvfslocked = VFS_LOCK_GIANT(dp->v_mount);
620                         VREF(dp);
621                         vput(tdp);
622                         VFS_UNLOCK_GIANT(tvfslocked);
623                         vn_lock(dp,
624                             compute_cn_lkflags(dp->v_mount, cnp->cn_lkflags |
625                             LK_RETRY));
626                         goto unionlookup;
627                 }
628
629                 if (error != EJUSTRETURN)
630                         goto bad;
631                 /*
632                  * If creating and at end of pathname, then can consider
633                  * allowing file to be created.
634                  */
635                 if (rdonly) {
636                         error = EROFS;
637                         goto bad;
638                 }
639                 if (*cp == '\0' && trailing_slash &&
640                      !(cnp->cn_flags & WILLBEDIR)) {
641                         error = ENOENT;
642                         goto bad;
643                 }
644                 if ((cnp->cn_flags & LOCKPARENT) == 0)
645                         VOP_UNLOCK(dp, 0);
646                 /*
647                  * This is a temporary assert to make sure I know what the
648                  * behavior here was.
649                  */
650                 KASSERT((cnp->cn_flags & (WANTPARENT|LOCKPARENT)) != 0,
651                    ("lookup: Unhandled case."));
652                 /*
653                  * We return with ni_vp NULL to indicate that the entry
654                  * doesn't currently exist, leaving a pointer to the
655                  * (possibly locked) directory vnode in ndp->ni_dvp.
656                  */
657                 if (cnp->cn_flags & SAVESTART) {
658                         ndp->ni_startdir = ndp->ni_dvp;
659                         VREF(ndp->ni_startdir);
660                 }
661                 goto success;
662         } else
663                 cnp->cn_lkflags = lkflags_save;
664 #ifdef NAMEI_DIAGNOSTIC
665         printf("found\n");
666 #endif
667         /*
668          * Take into account any additional components consumed by
669          * the underlying filesystem.
670          */
671         if (cnp->cn_consume > 0) {
672                 cnp->cn_nameptr += cnp->cn_consume;
673                 ndp->ni_next += cnp->cn_consume;
674                 ndp->ni_pathlen -= cnp->cn_consume;
675                 cnp->cn_consume = 0;
676         }
677
678         dp = ndp->ni_vp;
679         vfslocked = VFS_LOCK_GIANT(dp->v_mount);
680
681         /*
682          * Check to see if the vnode has been mounted on;
683          * if so find the root of the mounted filesystem.
684          */
685         while (dp->v_type == VDIR && (mp = dp->v_mountedhere) &&
686                (cnp->cn_flags & NOCROSSMOUNT) == 0) {
687                 if (vfs_busy(mp, 0, 0))
688                         continue;
689                 vput(dp);
690                 VFS_UNLOCK_GIANT(vfslocked);
691                 vfslocked = VFS_LOCK_GIANT(mp);
692                 if (dp != ndp->ni_dvp)
693                         vput(ndp->ni_dvp);
694                 else
695                         vrele(ndp->ni_dvp);
696                 VFS_UNLOCK_GIANT(dvfslocked);
697                 dvfslocked = 0;
698                 vref(vp_crossmp);
699                 ndp->ni_dvp = vp_crossmp;
700                 error = VFS_ROOT(mp, compute_cn_lkflags(mp, cnp->cn_lkflags), &tdp, td);
701                 vfs_unbusy(mp);
702                 if (vn_lock(vp_crossmp, LK_SHARED | LK_NOWAIT))
703                         panic("vp_crossmp exclusively locked or reclaimed");
704                 if (error) {
705                         dpunlocked = 1;
706                         goto bad2;
707                 }
708                 ndp->ni_vp = dp = tdp;
709         }
710
711         /*
712          * Check for symbolic link
713          */
714         if ((dp->v_type == VLNK) &&
715             ((cnp->cn_flags & FOLLOW) || trailing_slash ||
716              *ndp->ni_next == '/')) {
717                 cnp->cn_flags |= ISSYMLINK;
718                 if (dp->v_iflag & VI_DOOMED) {
719                         /* We can't know whether the directory was mounted with
720                          * NOSYMFOLLOW, so we can't follow safely. */
721                         error = EBADF;
722                         goto bad2;
723                 }
724                 if (dp->v_mount->mnt_flag & MNT_NOSYMFOLLOW) {
725                         error = EACCES;
726                         goto bad2;
727                 }
728                 /*
729                  * Symlink code always expects an unlocked dvp.
730                  */
731                 if (ndp->ni_dvp != ndp->ni_vp)
732                         VOP_UNLOCK(ndp->ni_dvp, 0);
733                 goto success;
734         }
735
736         /*
737          * Check for bogus trailing slashes.
738          */
739         if (trailing_slash && dp->v_type != VDIR) {
740                 error = ENOTDIR;
741                 goto bad2;
742         }
743
744 nextname:
745         /*
746          * Not a symbolic link.  If more pathname,
747          * continue at next component, else return.
748          */
749         KASSERT((cnp->cn_flags & ISLASTCN) || *ndp->ni_next == '/',
750             ("lookup: invalid path state."));
751         if (*ndp->ni_next == '/') {
752                 cnp->cn_nameptr = ndp->ni_next;
753                 while (*cnp->cn_nameptr == '/') {
754                         cnp->cn_nameptr++;
755                         ndp->ni_pathlen--;
756                 }
757                 if (ndp->ni_dvp != dp)
758                         vput(ndp->ni_dvp);
759                 else
760                         vrele(ndp->ni_dvp);
761                 VFS_UNLOCK_GIANT(dvfslocked);
762                 dvfslocked = vfslocked; /* dp becomes dvp in dirloop */
763                 vfslocked = 0;
764                 goto dirloop;
765         }
766         /*
767          * Disallow directory write attempts on read-only filesystems.
768          */
769         if (rdonly &&
770             (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
771                 error = EROFS;
772                 goto bad2;
773         }
774         if (cnp->cn_flags & SAVESTART) {
775                 ndp->ni_startdir = ndp->ni_dvp;
776                 VREF(ndp->ni_startdir);
777         }
778         if (!wantparent) {
779                 if (ndp->ni_dvp != dp)
780                         vput(ndp->ni_dvp);
781                 else
782                         vrele(ndp->ni_dvp);
783                 VFS_UNLOCK_GIANT(dvfslocked);
784                 dvfslocked = 0;
785         } else if ((cnp->cn_flags & LOCKPARENT) == 0 && ndp->ni_dvp != dp)
786                 VOP_UNLOCK(ndp->ni_dvp, 0);
787
788         if (cnp->cn_flags & AUDITVNODE1)
789                 AUDIT_ARG(vnode, dp, ARG_VNODE1);
790         else if (cnp->cn_flags & AUDITVNODE2)
791                 AUDIT_ARG(vnode, dp, ARG_VNODE2);
792
793         if ((cnp->cn_flags & LOCKLEAF) == 0)
794                 VOP_UNLOCK(dp, 0);
795 success:
796         /*
797          * Because of lookup_shared we may have the vnode shared locked, but
798          * the caller may want it to be exclusively locked.
799          */
800         if ((cnp->cn_flags & (ISLASTCN | LOCKSHARED | LOCKLEAF)) ==
801             (ISLASTCN | LOCKLEAF) && VOP_ISLOCKED(dp) != LK_EXCLUSIVE) {
802                 vn_lock(dp, LK_UPGRADE | LK_RETRY);
803         }
804         if (vfslocked && dvfslocked)
805                 VFS_UNLOCK_GIANT(dvfslocked);   /* Only need one */
806         if (vfslocked || dvfslocked)
807                 ndp->ni_cnd.cn_flags |= GIANTHELD;
808         return (0);
809
810 bad2:
811         if (dp != ndp->ni_dvp)
812                 vput(ndp->ni_dvp);
813         else
814                 vrele(ndp->ni_dvp);
815 bad:
816         if (!dpunlocked)
817                 vput(dp);
818         VFS_UNLOCK_GIANT(vfslocked);
819         VFS_UNLOCK_GIANT(dvfslocked);
820         ndp->ni_cnd.cn_flags &= ~GIANTHELD;
821         ndp->ni_vp = NULL;
822         return (error);
823 }
824
825 /*
826  * relookup - lookup a path name component
827  *    Used by lookup to re-acquire things.
828  */
829 int
830 relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp)
831 {
832         struct vnode *dp = 0;           /* the directory we are searching */
833         int wantparent;                 /* 1 => wantparent or lockparent flag */
834         int rdonly;                     /* lookup read-only flag bit */
835         int error = 0;
836
837         KASSERT(cnp->cn_flags & ISLASTCN,
838             ("relookup: Not given last component."));
839         /*
840          * Setup: break out flag bits into variables.
841          */
842         wantparent = cnp->cn_flags & (LOCKPARENT|WANTPARENT);
843         KASSERT(wantparent, ("relookup: parent not wanted."));
844         rdonly = cnp->cn_flags & RDONLY;
845         cnp->cn_flags &= ~ISSYMLINK;
846         dp = dvp;
847         cnp->cn_lkflags = LK_EXCLUSIVE;
848         vn_lock(dp, LK_EXCLUSIVE | LK_RETRY);
849
850         /*
851          * Search a new directory.
852          *
853          * The last component of the filename is left accessible via
854          * cnp->cn_nameptr for callers that need the name. Callers needing
855          * the name set the SAVENAME flag. When done, they assume
856          * responsibility for freeing the pathname buffer.
857          */
858 #ifdef NAMEI_DIAGNOSTIC
859         printf("{%s}: ", cnp->cn_nameptr);
860 #endif
861
862         /*
863          * Check for degenerate name (e.g. / or "")
864          * which is a way of talking about a directory,
865          * e.g. like "/." or ".".
866          */
867         if (cnp->cn_nameptr[0] == '\0') {
868                 if (cnp->cn_nameiop != LOOKUP || wantparent) {
869                         error = EISDIR;
870                         goto bad;
871                 }
872                 if (dp->v_type != VDIR) {
873                         error = ENOTDIR;
874                         goto bad;
875                 }
876                 if (!(cnp->cn_flags & LOCKLEAF))
877                         VOP_UNLOCK(dp, 0);
878                 *vpp = dp;
879                 /* XXX This should probably move to the top of function. */
880                 if (cnp->cn_flags & SAVESTART)
881                         panic("lookup: SAVESTART");
882                 return (0);
883         }
884
885         if (cnp->cn_flags & ISDOTDOT)
886                 panic ("relookup: lookup on dot-dot");
887
888         /*
889          * We now have a segment name to search for, and a directory to search.
890          */
891 #ifdef NAMEI_DIAGNOSTIC
892         vprint("search in:", dp);
893 #endif
894         if ((error = VOP_LOOKUP(dp, vpp, cnp)) != 0) {
895                 KASSERT(*vpp == NULL, ("leaf should be empty"));
896                 if (error != EJUSTRETURN)
897                         goto bad;
898                 /*
899                  * If creating and at end of pathname, then can consider
900                  * allowing file to be created.
901                  */
902                 if (rdonly) {
903                         error = EROFS;
904                         goto bad;
905                 }
906                 /* ASSERT(dvp == ndp->ni_startdir) */
907                 if (cnp->cn_flags & SAVESTART)
908                         VREF(dvp);
909                 if ((cnp->cn_flags & LOCKPARENT) == 0)
910                         VOP_UNLOCK(dp, 0);
911                 /*
912                  * This is a temporary assert to make sure I know what the
913                  * behavior here was.
914                  */
915                 KASSERT((cnp->cn_flags & (WANTPARENT|LOCKPARENT)) != 0,
916                    ("relookup: Unhandled case."));
917                 /*
918                  * We return with ni_vp NULL to indicate that the entry
919                  * doesn't currently exist, leaving a pointer to the
920                  * (possibly locked) directory vnode in ndp->ni_dvp.
921                  */
922                 return (0);
923         }
924
925         dp = *vpp;
926
927         /*
928          * Disallow directory write attempts on read-only filesystems.
929          */
930         if (rdonly &&
931             (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)) {
932                 if (dvp == dp)
933                         vrele(dvp);
934                 else
935                         vput(dvp);
936                 error = EROFS;
937                 goto bad;
938         }
939         /*
940          * Set the parent lock/ref state to the requested state.
941          */
942         if ((cnp->cn_flags & LOCKPARENT) == 0 && dvp != dp) {
943                 if (wantparent)
944                         VOP_UNLOCK(dvp, 0);
945                 else
946                         vput(dvp);
947         } else if (!wantparent)
948                 vrele(dvp);
949         /*
950          * Check for symbolic link
951          */
952         KASSERT(dp->v_type != VLNK || !(cnp->cn_flags & FOLLOW),
953             ("relookup: symlink found.\n"));
954
955         /* ASSERT(dvp == ndp->ni_startdir) */
956         if (cnp->cn_flags & SAVESTART)
957                 VREF(dvp);
958         
959         if ((cnp->cn_flags & LOCKLEAF) == 0)
960                 VOP_UNLOCK(dp, 0);
961         return (0);
962 bad:
963         vput(dp);
964         *vpp = NULL;
965         return (error);
966 }
967
968 /*
969  * Free data allocated by namei(); see namei(9) for details.
970  */
971 void
972 NDFREE(struct nameidata *ndp, const u_int flags)
973 {
974         int unlock_dvp;
975         int unlock_vp;
976
977         unlock_dvp = 0;
978         unlock_vp = 0;
979
980         if (!(flags & NDF_NO_FREE_PNBUF) &&
981             (ndp->ni_cnd.cn_flags & HASBUF)) {
982                 uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
983                 ndp->ni_cnd.cn_flags &= ~HASBUF;
984         }
985         if (!(flags & NDF_NO_VP_UNLOCK) &&
986             (ndp->ni_cnd.cn_flags & LOCKLEAF) && ndp->ni_vp)
987                 unlock_vp = 1;
988         if (!(flags & NDF_NO_VP_RELE) && ndp->ni_vp) {
989                 if (unlock_vp) {
990                         vput(ndp->ni_vp);
991                         unlock_vp = 0;
992                 } else
993                         vrele(ndp->ni_vp);
994                 ndp->ni_vp = NULL;
995         }
996         if (unlock_vp)
997                 VOP_UNLOCK(ndp->ni_vp, 0);
998         if (!(flags & NDF_NO_DVP_UNLOCK) &&
999             (ndp->ni_cnd.cn_flags & LOCKPARENT) &&
1000             ndp->ni_dvp != ndp->ni_vp)
1001                 unlock_dvp = 1;
1002         if (!(flags & NDF_NO_DVP_RELE) &&
1003             (ndp->ni_cnd.cn_flags & (LOCKPARENT|WANTPARENT))) {
1004                 if (unlock_dvp) {
1005                         vput(ndp->ni_dvp);
1006                         unlock_dvp = 0;
1007                 } else
1008                         vrele(ndp->ni_dvp);
1009                 ndp->ni_dvp = NULL;
1010         }
1011         if (unlock_dvp)
1012                 VOP_UNLOCK(ndp->ni_dvp, 0);
1013         if (!(flags & NDF_NO_STARTDIR_RELE) &&
1014             (ndp->ni_cnd.cn_flags & SAVESTART)) {
1015                 vrele(ndp->ni_startdir);
1016                 ndp->ni_startdir = NULL;
1017         }
1018 }
1019
1020 /*
1021  * Determine if there is a suitable alternate filename under the specified
1022  * prefix for the specified path.  If the create flag is set, then the
1023  * alternate prefix will be used so long as the parent directory exists.
1024  * This is used by the various compatiblity ABIs so that Linux binaries prefer
1025  * files under /compat/linux for example.  The chosen path (whether under
1026  * the prefix or under /) is returned in a kernel malloc'd buffer pointed
1027  * to by pathbuf.  The caller is responsible for free'ing the buffer from
1028  * the M_TEMP bucket if one is returned.
1029  */
1030 int
1031 kern_alternate_path(struct thread *td, const char *prefix, const char *path,
1032     enum uio_seg pathseg, char **pathbuf, int create, int dirfd)
1033 {
1034         struct nameidata nd, ndroot;
1035         char *ptr, *buf, *cp;
1036         size_t len, sz;
1037         int error;
1038
1039         buf = (char *) malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1040         *pathbuf = buf;
1041
1042         /* Copy the prefix into the new pathname as a starting point. */
1043         len = strlcpy(buf, prefix, MAXPATHLEN);
1044         if (len >= MAXPATHLEN) {
1045                 *pathbuf = NULL;
1046                 free(buf, M_TEMP);
1047                 return (EINVAL);
1048         }
1049         sz = MAXPATHLEN - len;
1050         ptr = buf + len;
1051
1052         /* Append the filename to the prefix. */
1053         if (pathseg == UIO_SYSSPACE)
1054                 error = copystr(path, ptr, sz, &len);
1055         else
1056                 error = copyinstr(path, ptr, sz, &len);
1057
1058         if (error) {
1059                 *pathbuf = NULL;
1060                 free(buf, M_TEMP);
1061                 return (error);
1062         }
1063
1064         /* Only use a prefix with absolute pathnames. */
1065         if (*ptr != '/') {
1066                 error = EINVAL;
1067                 goto keeporig;
1068         }
1069
1070         if (dirfd != AT_FDCWD) {
1071                 /*
1072                  * We want the original because the "prefix" is
1073                  * included in the already opened dirfd.
1074                  */
1075                 bcopy(ptr, buf, len);
1076                 return (0);
1077         }
1078
1079         /*
1080          * We know that there is a / somewhere in this pathname.
1081          * Search backwards for it, to find the file's parent dir
1082          * to see if it exists in the alternate tree. If it does,
1083          * and we want to create a file (cflag is set). We don't
1084          * need to worry about the root comparison in this case.
1085          */
1086
1087         if (create) {
1088                 for (cp = &ptr[len] - 1; *cp != '/'; cp--);
1089                 *cp = '\0';
1090
1091                 NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, buf, td);
1092                 error = namei(&nd);
1093                 *cp = '/';
1094                 if (error != 0)
1095                         goto keeporig;
1096         } else {
1097                 NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, buf, td);
1098
1099                 error = namei(&nd);
1100                 if (error != 0)
1101                         goto keeporig;
1102
1103                 /*
1104                  * We now compare the vnode of the prefix to the one
1105                  * vnode asked. If they resolve to be the same, then we
1106                  * ignore the match so that the real root gets used.
1107                  * This avoids the problem of traversing "../.." to find the
1108                  * root directory and never finding it, because "/" resolves
1109                  * to the emulation root directory. This is expensive :-(
1110                  */
1111                 NDINIT(&ndroot, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, prefix,
1112                     td);
1113
1114                 /* We shouldn't ever get an error from this namei(). */
1115                 error = namei(&ndroot);
1116                 if (error == 0) {
1117                         if (nd.ni_vp == ndroot.ni_vp)
1118                                 error = ENOENT;
1119
1120                         NDFREE(&ndroot, NDF_ONLY_PNBUF);
1121                         vrele(ndroot.ni_vp);
1122                         VFS_UNLOCK_GIANT(NDHASGIANT(&ndroot));
1123                 }
1124         }
1125
1126         NDFREE(&nd, NDF_ONLY_PNBUF);
1127         vrele(nd.ni_vp);
1128         VFS_UNLOCK_GIANT(NDHASGIANT(&nd));
1129
1130 keeporig:
1131         /* If there was an error, use the original path name. */
1132         if (error)
1133                 bcopy(ptr, buf, len);
1134         return (error);
1135 }