linux/fs/namei.c
<<
>>
Prefs
   1/*
   2 *  linux/fs/namei.c
   3 *
   4 *  Copyright (C) 1991, 1992  Linus Torvalds
   5 */
   6
   7/*
   8 * Some corrections by tytso.
   9 */
  10
  11/* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname
  12 * lookup logic.
  13 */
  14/* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture.
  15 */
  16
  17#include <linux/init.h>
  18#include <linux/export.h>
  19#include <linux/kernel.h>
  20#include <linux/slab.h>
  21#include <linux/fs.h>
  22#include <linux/namei.h>
  23#include <linux/pagemap.h>
  24#include <linux/fsnotify.h>
  25#include <linux/personality.h>
  26#include <linux/security.h>
  27#include <linux/ima.h>
  28#include <linux/syscalls.h>
  29#include <linux/mount.h>
  30#include <linux/audit.h>
  31#include <linux/capability.h>
  32#include <linux/file.h>
  33#include <linux/fcntl.h>
  34#include <linux/device_cgroup.h>
  35#include <linux/fs_struct.h>
  36#include <linux/posix_acl.h>
  37#include <asm/uaccess.h>
  38
  39#include "internal.h"
  40#include "mount.h"
  41
  42/* [Feb-1997 T. Schoebel-Theuer]
  43 * Fundamental changes in the pathname lookup mechanisms (namei)
  44 * were necessary because of omirr.  The reason is that omirr needs
  45 * to know the _real_ pathname, not the user-supplied one, in case
  46 * of symlinks (and also when transname replacements occur).
  47 *
  48 * The new code replaces the old recursive symlink resolution with
  49 * an iterative one (in case of non-nested symlink chains).  It does
  50 * this with calls to <fs>_follow_link().
  51 * As a side effect, dir_namei(), _namei() and follow_link() are now 
  52 * replaced with a single function lookup_dentry() that can handle all 
  53 * the special cases of the former code.
  54 *
  55 * With the new dcache, the pathname is stored at each inode, at least as
  56 * long as the refcount of the inode is positive.  As a side effect, the
  57 * size of the dcache depends on the inode cache and thus is dynamic.
  58 *
  59 * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
  60 * resolution to correspond with current state of the code.
  61 *
  62 * Note that the symlink resolution is not *completely* iterative.
  63 * There is still a significant amount of tail- and mid- recursion in
  64 * the algorithm.  Also, note that <fs>_readlink() is not used in
  65 * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
  66 * may return different results than <fs>_follow_link().  Many virtual
  67 * filesystems (including /proc) exhibit this behavior.
  68 */
  69
  70/* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
  71 * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
  72 * and the name already exists in form of a symlink, try to create the new
  73 * name indicated by the symlink. The old code always complained that the
  74 * name already exists, due to not following the symlink even if its target
  75 * is nonexistent.  The new semantics affects also mknod() and link() when
  76 * the name is a symlink pointing to a non-existent name.
  77 *
  78 * I don't know which semantics is the right one, since I have no access
  79 * to standards. But I found by trial that HP-UX 9.0 has the full "new"
  80 * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
  81 * "old" one. Personally, I think the new semantics is much more logical.
  82 * Note that "ln old new" where "new" is a symlink pointing to a non-existing
  83 * file does succeed in both HP-UX and SunOs, but not in Solaris
  84 * and in the old Linux semantics.
  85 */
  86
  87/* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
  88 * semantics.  See the comments in "open_namei" and "do_link" below.
  89 *
  90 * [10-Sep-98 Alan Modra] Another symlink change.
  91 */
  92
  93/* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
  94 *      inside the path - always follow.
  95 *      in the last component in creation/removal/renaming - never follow.
  96 *      if LOOKUP_FOLLOW passed - follow.
  97 *      if the pathname has trailing slashes - follow.
  98 *      otherwise - don't follow.
  99 * (applied in that order).
 100 *
 101 * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
 102 * restored for 2.4. This is the last surviving part of old 4.2BSD bug.
 103 * During the 2.4 we need to fix the userland stuff depending on it -
 104 * hopefully we will be able to get rid of that wart in 2.5. So far only
 105 * XEmacs seems to be relying on it...
 106 */
 107/*
 108 * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
 109 * implemented.  Let's see if raised priority of ->s_vfs_rename_mutex gives
 110 * any extra contention...
 111 */
 112
 113/* In order to reduce some races, while at the same time doing additional
 114 * checking and hopefully speeding things up, we copy filenames to the
 115 * kernel data space before using them..
 116 *
 117 * POSIX.1 2.4: an empty pathname is invalid (ENOENT).
 118 * PATH_MAX includes the nul terminator --RR.
 119 */
 120
 121#define EMBEDDED_NAME_MAX       (PATH_MAX - sizeof(struct filename))
 122
 123static struct filename *
 124getname_flags(const char __user *filename, int flags, int *empty)
 125{
 126        struct filename *result, *err;
 127        int len;
 128        long max;
 129        char *kname;
 130
 131        result = audit_reusename(filename);
 132        if (result)
 133                return result;
 134
 135        result = __getname();
 136        if (unlikely(!result))
 137                return ERR_PTR(-ENOMEM);
 138        result->refcnt = 1;
 139
 140        /*
 141         * First, try to embed the struct filename inside the names_cache
 142         * allocation
 143         */
 144        kname = (char *)result + sizeof(*result);
 145        result->name = kname;
 146        result->separate = false;
 147        max = EMBEDDED_NAME_MAX;
 148
 149recopy:
 150        len = strncpy_from_user(kname, filename, max);
 151        if (unlikely(len < 0)) {
 152                err = ERR_PTR(len);
 153                goto error;
 154        }
 155
 156        /*
 157         * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a
 158         * separate struct filename so we can dedicate the entire
 159         * names_cache allocation for the pathname, and re-do the copy from
 160         * userland.
 161         */
 162        if (len == EMBEDDED_NAME_MAX && max == EMBEDDED_NAME_MAX) {
 163                kname = (char *)result;
 164
 165                result = kzalloc(sizeof(*result), GFP_KERNEL);
 166                if (!result) {
 167                        err = ERR_PTR(-ENOMEM);
 168                        result = (struct filename *)kname;
 169                        goto error;
 170                }
 171                result->name = kname;
 172                result->separate = true;
 173                result->refcnt = 1;
 174                max = PATH_MAX;
 175                goto recopy;
 176        }
 177
 178        /* The empty path is special. */
 179        if (unlikely(!len)) {
 180                if (empty)
 181                        *empty = 1;
 182                err = ERR_PTR(-ENOENT);
 183                if (!(flags & LOOKUP_EMPTY))
 184                        goto error;
 185        }
 186
 187        err = ERR_PTR(-ENAMETOOLONG);
 188        if (unlikely(len >= PATH_MAX))
 189                goto error;
 190
 191        result->uptr = filename;
 192        result->aname = NULL;
 193        audit_getname(result);
 194        return result;
 195
 196error:
 197        putname(result);
 198        return err;
 199}
 200
 201struct filename *
 202getname(const char __user * filename)
 203{
 204        return getname_flags(filename, 0, NULL);
 205}
 206
 207struct filename *
 208getname_kernel(const char * filename)
 209{
 210        struct filename *result;
 211        int len = strlen(filename) + 1;
 212
 213        result = __getname();
 214        if (unlikely(!result))
 215                return ERR_PTR(-ENOMEM);
 216
 217        if (len <= EMBEDDED_NAME_MAX) {
 218                result->name = (char *)(result) + sizeof(*result);
 219                result->separate = false;
 220        } else if (len <= PATH_MAX) {
 221                struct filename *tmp;
 222
 223                tmp = kmalloc(sizeof(*tmp), GFP_KERNEL);
 224                if (unlikely(!tmp)) {
 225                        __putname(result);
 226                        return ERR_PTR(-ENOMEM);
 227                }
 228                tmp->name = (char *)result;
 229                tmp->separate = true;
 230                result = tmp;
 231        } else {
 232                __putname(result);
 233                return ERR_PTR(-ENAMETOOLONG);
 234        }
 235        memcpy((char *)result->name, filename, len);
 236        result->uptr = NULL;
 237        result->aname = NULL;
 238        result->refcnt = 1;
 239        audit_getname(result);
 240
 241        return result;
 242}
 243
 244void putname(struct filename *name)
 245{
 246        BUG_ON(name->refcnt <= 0);
 247
 248        if (--name->refcnt > 0)
 249                return;
 250
 251        if (name->separate) {
 252                __putname(name->name);
 253                kfree(name);
 254        } else
 255                __putname(name);
 256}
 257
 258static int check_acl(struct inode *inode, int mask)
 259{
 260#ifdef CONFIG_FS_POSIX_ACL
 261        struct posix_acl *acl;
 262
 263        if (mask & MAY_NOT_BLOCK) {
 264                acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
 265                if (!acl)
 266                        return -EAGAIN;
 267                /* no ->get_acl() calls in RCU mode... */
 268                if (acl == ACL_NOT_CACHED)
 269                        return -ECHILD;
 270                return posix_acl_permission(inode, acl, mask & ~MAY_NOT_BLOCK);
 271        }
 272
 273        acl = get_acl(inode, ACL_TYPE_ACCESS);
 274        if (IS_ERR(acl))
 275                return PTR_ERR(acl);
 276        if (acl) {
 277                int error = posix_acl_permission(inode, acl, mask);
 278                posix_acl_release(acl);
 279                return error;
 280        }
 281#endif
 282
 283        return -EAGAIN;
 284}
 285
 286/*
 287 * This does the basic permission checking
 288 */
 289static int acl_permission_check(struct inode *inode, int mask)
 290{
 291        unsigned int mode = inode->i_mode;
 292
 293        if (likely(uid_eq(current_fsuid(), inode->i_uid)))
 294                mode >>= 6;
 295        else {
 296                if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
 297                        int error = check_acl(inode, mask);
 298                        if (error != -EAGAIN)
 299                                return error;
 300                }
 301
 302                if (in_group_p(inode->i_gid))
 303                        mode >>= 3;
 304        }
 305
 306        /*
 307         * If the DACs are ok we don't need any capability check.
 308         */
 309        if ((mask & ~mode & (MAY_READ | MAY_WRITE | MAY_EXEC)) == 0)
 310                return 0;
 311        return -EACCES;
 312}
 313
 314/**
 315 * generic_permission -  check for access rights on a Posix-like filesystem
 316 * @inode:      inode to check access rights for
 317 * @mask:       right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC, ...)
 318 *
 319 * Used to check for read/write/execute permissions on a file.
 320 * We use "fsuid" for this, letting us set arbitrary permissions
 321 * for filesystem access without changing the "normal" uids which
 322 * are used for other things.
 323 *
 324 * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
 325 * request cannot be satisfied (eg. requires blocking or too much complexity).
 326 * It would then be called again in ref-walk mode.
 327 */
 328int generic_permission(struct inode *inode, int mask)
 329{
 330        int ret;
 331
 332        /*
 333         * Do the basic permission checks.
 334         */
 335        ret = acl_permission_check(inode, mask);
 336        if (ret != -EACCES)
 337                return ret;
 338
 339        if (S_ISDIR(inode->i_mode)) {
 340                /* DACs are overridable for directories */
 341                if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))
 342                        return 0;
 343                if (!(mask & MAY_WRITE))
 344                        if (capable_wrt_inode_uidgid(inode,
 345                                                     CAP_DAC_READ_SEARCH))
 346                                return 0;
 347                return -EACCES;
 348        }
 349        /*
 350         * Read/write DACs are always overridable.
 351         * Executable DACs are overridable when there is
 352         * at least one exec bit set.
 353         */
 354        if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
 355                if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))
 356                        return 0;
 357
 358        /*
 359         * Searching includes executable on directories, else just read.
 360         */
 361        mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
 362        if (mask == MAY_READ)
 363                if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH))
 364                        return 0;
 365
 366        return -EACCES;
 367}
 368
 369/*
 370 * We _really_ want to just do "generic_permission()" without
 371 * even looking at the inode->i_op values. So we keep a cache
 372 * flag in inode->i_opflags, that says "this has not special
 373 * permission function, use the fast case".
 374 */
 375static inline int do_inode_permission(struct inode *inode, int mask)
 376{
 377        if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
 378                if (likely(inode->i_op->permission))
 379                        return inode->i_op->permission(inode, mask);
 380
 381                /* This gets set once for the inode lifetime */
 382                spin_lock(&inode->i_lock);
 383                inode->i_opflags |= IOP_FASTPERM;
 384                spin_unlock(&inode->i_lock);
 385        }
 386        return generic_permission(inode, mask);
 387}
 388
 389/**
 390 * __inode_permission - Check for access rights to a given inode
 391 * @inode: Inode to check permission on
 392 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
 393 *
 394 * Check for read/write/execute permissions on an inode.
 395 *
 396 * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
 397 *
 398 * This does not check for a read-only file system.  You probably want
 399 * inode_permission().
 400 */
 401int __inode_permission(struct inode *inode, int mask)
 402{
 403        int retval;
 404
 405        if (unlikely(mask & MAY_WRITE)) {
 406                /*
 407                 * Nobody gets write access to an immutable file.
 408                 */
 409                if (IS_IMMUTABLE(inode))
 410                        return -EACCES;
 411
 412                /*
 413                 * Updating mtime will likely cause i_uid and i_gid to be
 414                 * written back improperly if their true value is unknown
 415                 * to the vfs.
 416                 */
 417                if (HAS_UNMAPPED_ID(inode))
 418                        return -EACCES;
 419        }
 420
 421        retval = do_inode_permission(inode, mask);
 422        if (retval)
 423                return retval;
 424
 425        retval = devcgroup_inode_permission(inode, mask);
 426        if (retval)
 427                return retval;
 428
 429        return security_inode_permission(inode, mask);
 430}
 431EXPORT_SYMBOL(__inode_permission);
 432
 433/**
 434 * sb_permission - Check superblock-level permissions
 435 * @sb: Superblock of inode to check permission on
 436 * @inode: Inode to check permission on
 437 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
 438 *
 439 * Separate out file-system wide checks from inode-specific permission checks.
 440 */
 441static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
 442{
 443        if (unlikely(mask & MAY_WRITE)) {
 444                umode_t mode = inode->i_mode;
 445
 446                /* Nobody gets write access to a read-only fs. */
 447                if ((sb->s_flags & MS_RDONLY) &&
 448                    (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
 449                        return -EROFS;
 450        }
 451        return 0;
 452}
 453
 454/**
 455 * inode_permission - Check for access rights to a given inode
 456 * @inode: Inode to check permission on
 457 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
 458 *
 459 * Check for read/write/execute permissions on an inode.  We use fs[ug]id for
 460 * this, letting us set arbitrary permissions for filesystem access without
 461 * changing the "normal" UIDs which are used for other things.
 462 *
 463 * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
 464 */
 465int inode_permission(struct inode *inode, int mask)
 466{
 467        int retval;
 468
 469        retval = sb_permission(inode->i_sb, inode, mask);
 470        if (retval)
 471                return retval;
 472        return __inode_permission(inode, mask);
 473}
 474
 475/**
 476 * path_get - get a reference to a path
 477 * @path: path to get the reference to
 478 *
 479 * Given a path increment the reference count to the dentry and the vfsmount.
 480 */
 481void path_get(const struct path *path)
 482{
 483        mntget(path->mnt);
 484        dget(path->dentry);
 485}
 486EXPORT_SYMBOL(path_get);
 487
 488/**
 489 * path_put - put a reference to a path
 490 * @path: path to put the reference to
 491 *
 492 * Given a path decrement the reference count to the dentry and the vfsmount.
 493 */
 494void path_put(const struct path *path)
 495{
 496        dput(path->dentry);
 497        mntput(path->mnt);
 498}
 499EXPORT_SYMBOL(path_put);
 500
 501/**
 502 * path_connected - Verify that a path->dentry is below path->mnt.mnt_root
 503 * @path: nameidate to verify
 504 *
 505 * Rename can sometimes move a file or directory outside of a bind
 506 * mount, path_connected allows those cases to be detected.
 507 */
 508static bool path_connected(const struct path *path)
 509{
 510        struct vfsmount *mnt = path->mnt;
 511        struct super_block *sb = mnt->mnt_sb;
 512
 513        /* Bind mounts and multi-root filesystems can have disconnected paths */
 514        if (!(sb->s_iflags & SB_I_MULTIROOT) && (mnt->mnt_root == sb->s_root))
 515                return true;
 516
 517        return is_subdir(path->dentry, mnt->mnt_root);
 518}
 519
 520
 521/*
 522 * Path walking has 2 modes, rcu-walk and ref-walk (see
 523 * Documentation/filesystems/path-lookup.txt).  In situations when we can't
 524 * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
 525 * normal reference counts on dentries and vfsmounts to transition to rcu-walk
 526 * mode.  Refcounts are grabbed at the last known good point before rcu-walk
 527 * got stuck, so ref-walk may continue from there. If this is not successful
 528 * (eg. a seqcount has changed), then failure is returned and it's up to caller
 529 * to restart the path walk from the beginning in ref-walk mode.
 530 */
 531
 532/**
 533 * unlazy_walk - try to switch to ref-walk mode.
 534 * @nd: nameidata pathwalk data
 535 * @dentry: child of nd->path.dentry or NULL
 536 * Returns: 0 on success, -ECHILD on failure
 537 *
 538 * unlazy_walk attempts to legitimize the current nd->path, nd->root and dentry
 539 * for ref-walk mode.  @dentry must be a path found by a do_lookup call on
 540 * @nd or NULL.  Must be called from rcu-walk context.
 541 */
 542static int unlazy_walk(struct nameidata *nd, struct dentry *dentry)
 543{
 544        struct fs_struct *fs = current->fs;
 545        struct dentry *parent = nd->path.dentry;
 546
 547        BUG_ON(!(nd->flags & LOOKUP_RCU));
 548
 549        /*
 550         * After legitimizing the bastards, terminate_walk()
 551         * will do the right thing for non-RCU mode, and all our
 552         * subsequent exit cases should rcu_read_unlock()
 553         * before returning.  Do vfsmount first; if dentry
 554         * can't be legitimized, just set nd->path.dentry to NULL
 555         * and rely on dput(NULL) being a no-op.
 556         */
 557        if (!legitimize_mnt(nd->path.mnt, nd->m_seq))
 558                return -ECHILD;
 559        nd->flags &= ~LOOKUP_RCU;
 560
 561        if (!lockref_get_not_dead(&parent->d_lockref)) {
 562                nd->path.dentry = NULL; 
 563                goto out;
 564        }
 565
 566        /*
 567         * For a negative lookup, the lookup sequence point is the parents
 568         * sequence point, and it only needs to revalidate the parent dentry.
 569         *
 570         * For a positive lookup, we need to move both the parent and the
 571         * dentry from the RCU domain to be properly refcounted. And the
 572         * sequence number in the dentry validates *both* dentry counters,
 573         * since we checked the sequence number of the parent after we got
 574         * the child sequence number. So we know the parent must still
 575         * be valid if the child sequence number is still valid.
 576         */
 577        if (!dentry) {
 578                if (read_seqcount_retry(&parent->d_seq, nd->seq))
 579                        goto out;
 580                BUG_ON(nd->inode != parent->d_inode);
 581        } else {
 582                if (!lockref_get_not_dead(&dentry->d_lockref))
 583                        goto out;
 584                if (read_seqcount_retry(&dentry->d_seq, nd->seq))
 585                        goto drop_dentry;
 586        }
 587
 588        /*
 589         * Sequence counts matched. Now make sure that the root is
 590         * still valid and get it if required.
 591         */
 592        if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) {
 593                spin_lock(&fs->lock);
 594                if (nd->root.mnt != fs->root.mnt || nd->root.dentry != fs->root.dentry)
 595                        goto unlock_and_drop_dentry;
 596                path_get(&nd->root);
 597                spin_unlock(&fs->lock);
 598        }
 599
 600        rcu_read_unlock();
 601        return 0;
 602
 603unlock_and_drop_dentry:
 604        spin_unlock(&fs->lock);
 605drop_dentry:
 606        rcu_read_unlock();
 607        dput(dentry);
 608        goto drop_root_mnt;
 609out:
 610        rcu_read_unlock();
 611drop_root_mnt:
 612        if (!(nd->flags & LOOKUP_ROOT))
 613                nd->root.mnt = NULL;
 614        return -ECHILD;
 615}
 616
 617static inline int d_revalidate(struct dentry *dentry, unsigned int flags)
 618{
 619        return dentry->d_op->d_revalidate(dentry, flags);
 620}
 621
 622/**
 623 * complete_walk - successful completion of path walk
 624 * @nd:  pointer nameidata
 625 *
 626 * If we had been in RCU mode, drop out of it and legitimize nd->path.
 627 * Revalidate the final result, unless we'd already done that during
 628 * the path walk or the filesystem doesn't ask for it.  Return 0 on
 629 * success, -error on failure.  In case of failure caller does not
 630 * need to drop nd->path.
 631 */
 632static int complete_walk(struct nameidata *nd)
 633{
 634        struct dentry *dentry = nd->path.dentry;
 635        int status;
 636
 637        if (nd->flags & LOOKUP_RCU) {
 638                nd->flags &= ~LOOKUP_RCU;
 639                if (!(nd->flags & LOOKUP_ROOT))
 640                        nd->root.mnt = NULL;
 641
 642                if (!legitimize_mnt(nd->path.mnt, nd->m_seq)) {
 643                        rcu_read_unlock();
 644                        return -ECHILD;
 645                }
 646                if (unlikely(!lockref_get_not_dead(&dentry->d_lockref))) {
 647                        rcu_read_unlock();
 648                        mntput(nd->path.mnt);
 649                        return -ECHILD;
 650                }
 651                if (read_seqcount_retry(&dentry->d_seq, nd->seq)) {
 652                        rcu_read_unlock();
 653                        dput(dentry);
 654                        mntput(nd->path.mnt);
 655                        return -ECHILD;
 656                }
 657                rcu_read_unlock();
 658        }
 659
 660        if (likely(!(nd->flags & LOOKUP_JUMPED)))
 661                return 0;
 662
 663        if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
 664                return 0;
 665
 666        status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
 667        if (status > 0)
 668                return 0;
 669
 670        if (!status)
 671                status = -ESTALE;
 672
 673        path_put(&nd->path);
 674        return status;
 675}
 676
 677static __always_inline void set_root(struct nameidata *nd)
 678{
 679        if (!nd->root.mnt)
 680                get_fs_root(current->fs, &nd->root);
 681}
 682
 683static int link_path_walk(const char *, struct nameidata *);
 684
 685static __always_inline void set_root_rcu(struct nameidata *nd)
 686{
 687        if (!nd->root.mnt) {
 688                struct fs_struct *fs = current->fs;
 689                unsigned seq;
 690
 691                do {
 692                        seq = read_seqcount_begin(&fs->seq);
 693                        nd->root = fs->root;
 694                        nd->seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
 695                } while (read_seqcount_retry(&fs->seq, seq));
 696        }
 697}
 698
 699static __always_inline int __vfs_follow_link(struct nameidata *nd, const char *link)
 700{
 701        int ret;
 702
 703        if (IS_ERR(link))
 704                goto fail;
 705
 706        if (*link == '/') {
 707                set_root(nd);
 708                path_put(&nd->path);
 709                nd->path = nd->root;
 710                path_get(&nd->root);
 711                nd->flags |= LOOKUP_JUMPED;
 712        }
 713        nd->inode = nd->path.dentry->d_inode;
 714
 715        ret = link_path_walk(link, nd);
 716        return ret;
 717fail:
 718        path_put(&nd->path);
 719        return PTR_ERR(link);
 720}
 721
 722static void path_put_conditional(struct path *path, struct nameidata *nd)
 723{
 724        dput(path->dentry);
 725        if (path->mnt != nd->path.mnt)
 726                mntput(path->mnt);
 727}
 728
 729static inline void path_to_nameidata(const struct path *path,
 730                                        struct nameidata *nd)
 731{
 732        if (!(nd->flags & LOOKUP_RCU)) {
 733                dput(nd->path.dentry);
 734                if (nd->path.mnt != path->mnt)
 735                        mntput(nd->path.mnt);
 736        }
 737        nd->path.mnt = path->mnt;
 738        nd->path.dentry = path->dentry;
 739}
 740
 741/*
 742 * Helper to directly jump to a known parsed path from ->follow_link,
 743 * caller must have taken a reference to path beforehand.
 744 */
 745void nd_jump_link(struct nameidata *nd, struct path *path)
 746{
 747        path_put(&nd->path);
 748
 749        nd->path = *path;
 750        nd->inode = nd->path.dentry->d_inode;
 751        nd->flags |= LOOKUP_JUMPED;
 752}
 753
 754static inline void put_link(struct nameidata *nd, struct path *link, void *cookie)
 755{
 756        struct inode *inode = link->dentry->d_inode;
 757        if (inode->i_op->put_link)
 758                inode->i_op->put_link(link->dentry, nd, cookie);
 759        path_put(link);
 760}
 761
 762int sysctl_protected_symlinks __read_mostly = 0;
 763int sysctl_protected_hardlinks __read_mostly = 0;
 764
 765/**
 766 * may_follow_link - Check symlink following for unsafe situations
 767 * @link: The path of the symlink
 768 * @nd: nameidata pathwalk data
 769 *
 770 * In the case of the sysctl_protected_symlinks sysctl being enabled,
 771 * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
 772 * in a sticky world-writable directory. This is to protect privileged
 773 * processes from failing races against path names that may change out
 774 * from under them by way of other users creating malicious symlinks.
 775 * It will permit symlinks to be followed only when outside a sticky
 776 * world-writable directory, or when the uid of the symlink and follower
 777 * match, or when the directory owner matches the symlink's owner.
 778 *
 779 * Returns 0 if following the symlink is allowed, -ve on error.
 780 */
 781static inline int may_follow_link(struct path *link, struct nameidata *nd)
 782{
 783        const struct inode *inode;
 784        const struct inode *parent;
 785        kuid_t puid;
 786
 787        if (!sysctl_protected_symlinks)
 788                return 0;
 789
 790        /* Allowed if owner and follower match. */
 791        inode = link->dentry->d_inode;
 792        if (uid_eq(current_cred()->fsuid, inode->i_uid))
 793                return 0;
 794
 795        /* Allowed if parent directory not sticky and world-writable. */
 796        parent = nd->path.dentry->d_inode;
 797        if ((parent->i_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
 798                return 0;
 799
 800        /* Allowed if parent directory and link owner match. */
 801        puid = parent->i_uid;
 802        if (uid_valid(puid) && uid_eq(puid, inode->i_uid))
 803                return 0;
 804
 805        audit_log_link_denied("follow_link", link);
 806        path_put_conditional(link, nd);
 807        path_put(&nd->path);
 808        return -EACCES;
 809}
 810
 811/**
 812 * safe_hardlink_source - Check for safe hardlink conditions
 813 * @inode: the source inode to hardlink from
 814 *
 815 * Return false if at least one of the following conditions:
 816 *    - inode is not a regular file
 817 *    - inode is setuid
 818 *    - inode is setgid and group-exec
 819 *    - access failure for read and write
 820 *
 821 * Otherwise returns true.
 822 */
 823static bool safe_hardlink_source(struct inode *inode)
 824{
 825        umode_t mode = inode->i_mode;
 826
 827        /* Special files should not get pinned to the filesystem. */
 828        if (!S_ISREG(mode))
 829                return false;
 830
 831        /* Setuid files should not get pinned to the filesystem. */
 832        if (mode & S_ISUID)
 833                return false;
 834
 835        /* Executable setgid files should not get pinned to the filesystem. */
 836        if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
 837                return false;
 838
 839        /* Hardlinking to unreadable or unwritable sources is dangerous. */
 840        if (inode_permission(inode, MAY_READ | MAY_WRITE))
 841                return false;
 842
 843        return true;
 844}
 845
 846/**
 847 * may_linkat - Check permissions for creating a hardlink
 848 * @link: the source to hardlink from
 849 *
 850 * Block hardlink when all of:
 851 *  - sysctl_protected_hardlinks enabled
 852 *  - fsuid does not match inode
 853 *  - hardlink source is unsafe (see safe_hardlink_source() above)
 854 *  - not CAP_FOWNER in a namespace with the inode owner uid mapped
 855 *
 856 * Returns 0 if successful, -ve on error.
 857 */
 858static int may_linkat(struct path *link)
 859{
 860        struct inode *inode = link->dentry->d_inode;
 861
 862        /* Inode writeback is not safe when the uid or gid are invalid. */
 863        if (!uid_valid(inode->i_uid) || !gid_valid(inode->i_gid))
 864                return -EOVERFLOW;
 865
 866        if (!sysctl_protected_hardlinks)
 867                return 0;
 868
 869        /* Source inode owner (or CAP_FOWNER) can hardlink all they like,
 870         * otherwise, it must be a safe source.
 871         */
 872        if (inode_owner_or_capable(inode) || safe_hardlink_source(inode))
 873                return 0;
 874
 875        audit_log_link_denied("linkat", link);
 876        return -EPERM;
 877}
 878
 879static __always_inline int
 880follow_link(struct path *link, struct nameidata *nd, void **p)
 881{
 882        struct dentry *dentry = link->dentry;
 883        int error;
 884        char *s;
 885
 886        BUG_ON(nd->flags & LOOKUP_RCU);
 887
 888        if (link->mnt == nd->path.mnt)
 889                mntget(link->mnt);
 890
 891        error = -ELOOP;
 892        if (unlikely(current->total_link_count >= 40))
 893                goto out_put_nd_path;
 894
 895        cond_resched();
 896        current->total_link_count++;
 897
 898        touch_atime(link);
 899        nd_set_link(nd, NULL);
 900
 901        error = security_inode_follow_link(link->dentry, nd);
 902        if (error)
 903                goto out_put_nd_path;
 904
 905        nd->last_type = LAST_BIND;
 906        *p = dentry->d_inode->i_op->follow_link(dentry, nd);
 907        error = PTR_ERR(*p);
 908        if (IS_ERR(*p))
 909                goto out_put_nd_path;
 910
 911        error = 0;
 912        s = nd_get_link(nd);
 913        if (s) {
 914                error = __vfs_follow_link(nd, s);
 915                if (unlikely(error))
 916                        put_link(nd, link, *p);
 917        }
 918
 919        return error;
 920
 921out_put_nd_path:
 922        *p = NULL;
 923        path_put(&nd->path);
 924        path_put(link);
 925        return error;
 926}
 927
 928static int follow_up_rcu(struct path *path)
 929{
 930        struct mount *mnt = real_mount(path->mnt);
 931        struct mount *parent;
 932        struct dentry *mountpoint;
 933
 934        parent = mnt->mnt_parent;
 935        if (&parent->mnt == path->mnt)
 936                return 0;
 937        mountpoint = mnt->mnt_mountpoint;
 938        path->dentry = mountpoint;
 939        path->mnt = &parent->mnt;
 940        return 1;
 941}
 942
 943/*
 944 * follow_up - Find the mountpoint of path's vfsmount
 945 *
 946 * Given a path, find the mountpoint of its source file system.
 947 * Replace @path with the path of the mountpoint in the parent mount.
 948 * Up is towards /.
 949 *
 950 * Return 1 if we went up a level and 0 if we were already at the
 951 * root.
 952 */
 953int follow_up(struct path *path)
 954{
 955        struct mount *mnt = real_mount(path->mnt);
 956        struct mount *parent;
 957        struct dentry *mountpoint;
 958
 959        read_seqlock_excl(&mount_lock);
 960        parent = mnt->mnt_parent;
 961        if (parent == mnt) {
 962                read_sequnlock_excl(&mount_lock);
 963                return 0;
 964        }
 965        mntget(&parent->mnt);
 966        mountpoint = dget(mnt->mnt_mountpoint);
 967        read_sequnlock_excl(&mount_lock);
 968        dput(path->dentry);
 969        path->dentry = mountpoint;
 970        mntput(path->mnt);
 971        path->mnt = &parent->mnt;
 972        return 1;
 973}
 974
 975/*
 976 * Perform an automount
 977 * - return -EISDIR to tell follow_managed() to stop and return the path we
 978 *   were called with.
 979 */
 980static int follow_automount(struct path *path, unsigned flags,
 981                            bool *need_mntput)
 982{
 983        struct vfsmount *mnt;
 984        int err;
 985
 986        if (!path->dentry->d_op || !path->dentry->d_op->d_automount)
 987                return -EREMOTE;
 988
 989        /* We don't want to mount if someone's just doing a stat -
 990         * unless they're stat'ing a directory and appended a '/' to
 991         * the name.
 992         *
 993         * We do, however, want to mount if someone wants to open or
 994         * create a file of any type under the mountpoint, wants to
 995         * traverse through the mountpoint or wants to open the
 996         * mounted directory.  Also, autofs may mark negative dentries
 997         * as being automount points.  These will need the attentions
 998         * of the daemon to instantiate them before they can be used.
 999         */
1000        if (!(flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
1001                     LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
1002            path->dentry->d_inode)
1003                return -EISDIR;
1004
1005        current->total_link_count++;
1006        if (current->total_link_count >= 40)
1007                return -ELOOP;
1008
1009        mnt = path->dentry->d_op->d_automount(path);
1010        if (IS_ERR(mnt)) {
1011                /*
1012                 * The filesystem is allowed to return -EISDIR here to indicate
1013                 * it doesn't want to automount.  For instance, autofs would do
1014                 * this so that its userspace daemon can mount on this dentry.
1015                 *
1016                 * However, we can only permit this if it's a terminal point in
1017                 * the path being looked up; if it wasn't then the remainder of
1018                 * the path is inaccessible and we should say so.
1019                 */
1020                if (PTR_ERR(mnt) == -EISDIR && (flags & LOOKUP_PARENT))
1021                        return -EREMOTE;
1022                return PTR_ERR(mnt);
1023        }
1024
1025        if (!mnt) /* mount collision */
1026                return 0;
1027
1028        if (!*need_mntput) {
1029                /* lock_mount() may release path->mnt on error */
1030                mntget(path->mnt);
1031                *need_mntput = true;
1032        }
1033        err = finish_automount(mnt, path);
1034
1035        switch (err) {
1036        case -EBUSY:
1037                /* Someone else made a mount here whilst we were busy */
1038                return 0;
1039        case 0:
1040                path_put(path);
1041                path->mnt = mnt;
1042                path->dentry = dget(mnt->mnt_root);
1043                return 0;
1044        default:
1045                return err;
1046        }
1047
1048}
1049
1050/*
1051 * Handle a dentry that is managed in some way.
1052 * - Flagged for transit management (autofs)
1053 * - Flagged as mountpoint
1054 * - Flagged as automount point
1055 *
1056 * This may only be called in refwalk mode.
1057 *
1058 * Serialization is taken care of in namespace.c
1059 */
1060static int follow_managed(struct path *path, unsigned flags)
1061{
1062        struct vfsmount *mnt = path->mnt; /* held by caller, must be left alone */
1063        unsigned managed;
1064        bool need_mntput = false;
1065        int ret = 0;
1066
1067        /* Given that we're not holding a lock here, we retain the value in a
1068         * local variable for each dentry as we look at it so that we don't see
1069         * the components of that value change under us */
1070        while (managed = ACCESS_ONCE(path->dentry->d_flags),
1071               managed &= DCACHE_MANAGED_DENTRY,
1072               unlikely(managed != 0)) {
1073                /* Allow the filesystem to manage the transit without i_mutex
1074                 * being held. */
1075                if (managed & DCACHE_MANAGE_TRANSIT) {
1076                        BUG_ON(!path->dentry->d_op);
1077                        BUG_ON(!path->dentry->d_op->d_manage);
1078                        ret = path->dentry->d_op->d_manage(path, false);
1079                        if (ret < 0)
1080                                break;
1081                }
1082
1083                /* Transit to a mounted filesystem. */
1084                if (managed & DCACHE_MOUNTED) {
1085                        struct vfsmount *mounted = lookup_mnt(path);
1086                        if (mounted) {
1087                                dput(path->dentry);
1088                                if (need_mntput)
1089                                        mntput(path->mnt);
1090                                path->mnt = mounted;
1091                                path->dentry = dget(mounted->mnt_root);
1092                                need_mntput = true;
1093                                continue;
1094                        }
1095
1096                        /* Something is mounted on this dentry in another
1097                         * namespace and/or whatever was mounted there in this
1098                         * namespace got unmounted before lookup_mnt() could
1099                         * get it */
1100                }
1101
1102                /* Handle an automount point */
1103                if (managed & DCACHE_NEED_AUTOMOUNT) {
1104                        ret = follow_automount(path, flags, &need_mntput);
1105                        if (ret < 0)
1106                                break;
1107                        continue;
1108                }
1109
1110                /* We didn't change the current path point */
1111                break;
1112        }
1113
1114        if (need_mntput && path->mnt == mnt)
1115                mntput(path->mnt);
1116        if (ret == -EISDIR)
1117                ret = 0;
1118        return ret < 0 ? ret : need_mntput;
1119}
1120
1121int follow_down_one(struct path *path)
1122{
1123        struct vfsmount *mounted;
1124
1125        mounted = lookup_mnt(path);
1126        if (mounted) {
1127                dput(path->dentry);
1128                mntput(path->mnt);
1129                path->mnt = mounted;
1130                path->dentry = dget(mounted->mnt_root);
1131                return 1;
1132        }
1133        return 0;
1134}
1135
1136static inline int managed_dentry_rcu(const struct path *path)
1137{
1138        return (path->dentry->d_flags & DCACHE_MANAGE_TRANSIT) ?
1139                path->dentry->d_op->d_manage(path, true) : 0;
1140}
1141
1142/*
1143 * Try to skip to top of mountpoint pile in rcuwalk mode.  Fail if
1144 * we meet a managed dentry that would need blocking.
1145 */
1146static bool __follow_mount_rcu(struct nameidata *nd, struct path *path,
1147                               struct inode **inode)
1148{
1149        for (;;) {
1150                struct mount *mounted;
1151                /*
1152                 * Don't forget we might have a non-mountpoint managed dentry
1153                 * that wants to block transit.
1154                 */
1155                switch (managed_dentry_rcu(path)) {
1156                case -ECHILD:
1157                default:
1158                        return false;
1159                case -EISDIR:
1160                        return true;
1161                case 0:
1162                        break;
1163                }
1164
1165                if (!d_mountpoint(path->dentry))
1166                        return !(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT);
1167
1168                mounted = __lookup_mnt(path->mnt, path->dentry);
1169                if (!mounted)
1170                        break;
1171                path->mnt = &mounted->mnt;
1172                path->dentry = mounted->mnt.mnt_root;
1173                nd->flags |= LOOKUP_JUMPED;
1174                nd->seq = read_seqcount_begin(&path->dentry->d_seq);
1175                /*
1176                 * Update the inode too. We don't need to re-check the
1177                 * dentry sequence number here after this d_inode read,
1178                 * because a mount-point is always pinned.
1179                 */
1180                *inode = path->dentry->d_inode;
1181        }
1182        return !read_seqretry(&mount_lock, nd->m_seq) &&
1183                !(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT);
1184}
1185
1186static int follow_dotdot_rcu(struct nameidata *nd)
1187{
1188        set_root_rcu(nd);
1189
1190        while (1) {
1191                if (nd->path.dentry == nd->root.dentry &&
1192                    nd->path.mnt == nd->root.mnt) {
1193                        break;
1194                }
1195                if (nd->path.dentry != nd->path.mnt->mnt_root) {
1196                        struct dentry *old = nd->path.dentry;
1197                        struct dentry *parent = old->d_parent;
1198                        unsigned seq;
1199
1200                        seq = read_seqcount_begin(&parent->d_seq);
1201                        if (read_seqcount_retry(&old->d_seq, nd->seq))
1202                                goto failed;
1203                        nd->path.dentry = parent;
1204                        nd->seq = seq;
1205                        if (unlikely(!path_connected(&nd->path)))
1206                                goto failed;
1207                        break;
1208                }
1209                if (!follow_up_rcu(&nd->path))
1210                        break;
1211                nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
1212        }
1213        while (d_mountpoint(nd->path.dentry)) {
1214                struct mount *mounted;
1215                mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry);
1216                if (!mounted)
1217                        break;
1218                nd->path.mnt = &mounted->mnt;
1219                nd->path.dentry = mounted->mnt.mnt_root;
1220                nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
1221                if (read_seqretry(&mount_lock, nd->m_seq))
1222                        goto failed;
1223        }
1224        nd->inode = nd->path.dentry->d_inode;
1225        return 0;
1226
1227failed:
1228        nd->flags &= ~LOOKUP_RCU;
1229        if (!(nd->flags & LOOKUP_ROOT))
1230                nd->root.mnt = NULL;
1231        rcu_read_unlock();
1232        return -ECHILD;
1233}
1234
1235/*
1236 * Follow down to the covering mount currently visible to userspace.  At each
1237 * point, the filesystem owning that dentry may be queried as to whether the
1238 * caller is permitted to proceed or not.
1239 */
1240int follow_down(struct path *path)
1241{
1242        unsigned managed;
1243        int ret;
1244
1245        while (managed = ACCESS_ONCE(path->dentry->d_flags),
1246               unlikely(managed & DCACHE_MANAGED_DENTRY)) {
1247                /* Allow the filesystem to manage the transit without i_mutex
1248                 * being held.
1249                 *
1250                 * We indicate to the filesystem if someone is trying to mount
1251                 * something here.  This gives autofs the chance to deny anyone
1252                 * other than its daemon the right to mount on its
1253                 * superstructure.
1254                 *
1255                 * The filesystem may sleep at this point.
1256                 */
1257                if (managed & DCACHE_MANAGE_TRANSIT) {
1258                        BUG_ON(!path->dentry->d_op);
1259                        BUG_ON(!path->dentry->d_op->d_manage);
1260                        ret = path->dentry->d_op->d_manage(path, false);
1261                        if (ret < 0)
1262                                return ret == -EISDIR ? 0 : ret;
1263                }
1264
1265                /* Transit to a mounted filesystem. */
1266                if (managed & DCACHE_MOUNTED) {
1267                        struct vfsmount *mounted = lookup_mnt(path);
1268                        if (!mounted)
1269                                break;
1270                        dput(path->dentry);
1271                        mntput(path->mnt);
1272                        path->mnt = mounted;
1273                        path->dentry = dget(mounted->mnt_root);
1274                        continue;
1275                }
1276
1277                /* Don't handle automount points here */
1278                break;
1279        }
1280        return 0;
1281}
1282
1283/*
1284 * Skip to top of mountpoint pile in refwalk mode for follow_dotdot()
1285 */
1286static void follow_mount(struct path *path)
1287{
1288        while (d_mountpoint(path->dentry)) {
1289                struct vfsmount *mounted = lookup_mnt(path);
1290                if (!mounted)
1291                        break;
1292                dput(path->dentry);
1293                mntput(path->mnt);
1294                path->mnt = mounted;
1295                path->dentry = dget(mounted->mnt_root);
1296        }
1297}
1298
1299static int follow_dotdot(struct nameidata *nd)
1300{
1301        set_root(nd);
1302
1303        while(1) {
1304                struct dentry *old = nd->path.dentry;
1305
1306                if (nd->path.dentry == nd->root.dentry &&
1307                    nd->path.mnt == nd->root.mnt) {
1308                        break;
1309                }
1310                if (nd->path.dentry != nd->path.mnt->mnt_root) {
1311                        /* rare case of legitimate dget_parent()... */
1312                        nd->path.dentry = dget_parent(nd->path.dentry);
1313                        dput(old);
1314                        if (unlikely(!path_connected(&nd->path))) {
1315                                path_put(&nd->path);
1316                                return -ENOENT;
1317                        }
1318                        break;
1319                }
1320                if (!follow_up(&nd->path))
1321                        break;
1322        }
1323        follow_mount(&nd->path);
1324        nd->inode = nd->path.dentry->d_inode;
1325        return 0;
1326}
1327
1328/*
1329 * This looks up the name in dcache, possibly revalidates the old dentry and
1330 * allocates a new one if not found or not valid.  In the need_lookup argument
1331 * returns whether i_op->lookup is necessary.
1332 *
1333 * dir->d_inode->i_mutex must be held
1334 */
1335static struct dentry *lookup_dcache(struct qstr *name, struct dentry *dir,
1336                                    unsigned int flags, bool *need_lookup)
1337{
1338        struct dentry *dentry;
1339        int error;
1340
1341        *need_lookup = false;
1342        dentry = d_lookup(dir, name);
1343        if (dentry) {
1344                if (dentry->d_flags & DCACHE_OP_REVALIDATE) {
1345                        error = d_revalidate(dentry, flags);
1346                        if (unlikely(error <= 0)) {
1347                                if (error < 0) {
1348                                        dput(dentry);
1349                                        return ERR_PTR(error);
1350                                } else if (!d_invalidate(dentry)) {
1351                                        dput(dentry);
1352                                        dentry = NULL;
1353                                }
1354                        }
1355                }
1356        }
1357
1358        if (!dentry) {
1359                dentry = d_alloc(dir, name);
1360                if (unlikely(!dentry))
1361                        return ERR_PTR(-ENOMEM);
1362
1363                *need_lookup = true;
1364        }
1365        return dentry;
1366}
1367
1368/*
1369 * Call i_op->lookup on the dentry.  The dentry must be negative but may be
1370 * hashed if it was pouplated with DCACHE_NEED_LOOKUP.
1371 *
1372 * dir->d_inode->i_mutex must be held
1373 */
1374static struct dentry *lookup_real(struct inode *dir, struct dentry *dentry,
1375                                  unsigned int flags)
1376{
1377        struct dentry *old;
1378
1379        /* Don't create child dentry for a dead directory. */
1380        if (unlikely(IS_DEADDIR(dir))) {
1381                dput(dentry);
1382                return ERR_PTR(-ENOENT);
1383        }
1384
1385        old = dir->i_op->lookup(dir, dentry, flags);
1386        if (unlikely(old)) {
1387                dput(dentry);
1388                dentry = old;
1389        }
1390        return dentry;
1391}
1392
1393static struct dentry *__lookup_hash(struct qstr *name,
1394                struct dentry *base, unsigned int flags)
1395{
1396        bool need_lookup;
1397        struct dentry *dentry;
1398
1399        dentry = lookup_dcache(name, base, flags, &need_lookup);
1400        if (!need_lookup)
1401                return dentry;
1402
1403        return lookup_real(base->d_inode, dentry, flags);
1404}
1405
1406/*
1407 *  It's more convoluted than I'd like it to be, but... it's still fairly
1408 *  small and for now I'd prefer to have fast path as straight as possible.
1409 *  It _is_ time-critical.
1410 */
1411static int lookup_fast(struct nameidata *nd,
1412                       struct path *path, struct inode **inode)
1413{
1414        struct vfsmount *mnt = nd->path.mnt;
1415        struct dentry *dentry, *parent = nd->path.dentry;
1416        int need_reval = 1;
1417        int status = 1;
1418        int err;
1419
1420        /*
1421         * Rename seqlock is not required here because in the off chance
1422         * of a false negative due to a concurrent rename, we're going to
1423         * do the non-racy lookup, below.
1424         */
1425        if (nd->flags & LOOKUP_RCU) {
1426                unsigned seq;
1427                dentry = __d_lookup_rcu(parent, &nd->last, &seq);
1428                if (!dentry)
1429                        goto unlazy;
1430
1431                /*
1432                 * This sequence count validates that the inode matches
1433                 * the dentry name information from lookup.
1434                 */
1435                *inode = dentry->d_inode;
1436                if (read_seqcount_retry(&dentry->d_seq, seq))
1437                        return -ECHILD;
1438
1439                /*
1440                 * This sequence count validates that the parent had no
1441                 * changes while we did the lookup of the dentry above.
1442                 *
1443                 * The memory barrier in read_seqcount_begin of child is
1444                 *  enough, we can use __read_seqcount_retry here.
1445                 */
1446                if (__read_seqcount_retry(&parent->d_seq, nd->seq))
1447                        return -ECHILD;
1448                nd->seq = seq;
1449
1450                if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE)) {
1451                        status = d_revalidate(dentry, nd->flags);
1452                        if (unlikely(status <= 0)) {
1453                                if (status != -ECHILD)
1454                                        need_reval = 0;
1455                                goto unlazy;
1456                        }
1457                }
1458                path->mnt = mnt;
1459                path->dentry = dentry;
1460                if (likely(__follow_mount_rcu(nd, path, inode)))
1461                        return 0;
1462unlazy:
1463                if (unlazy_walk(nd, dentry))
1464                        return -ECHILD;
1465        } else {
1466                dentry = __d_lookup(parent, &nd->last);
1467        }
1468
1469        if (unlikely(!dentry))
1470                goto need_lookup;
1471
1472        if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE) && need_reval)
1473                status = d_revalidate(dentry, nd->flags);
1474        if (unlikely(status <= 0)) {
1475                if (status < 0) {
1476                        dput(dentry);
1477                        return status;
1478                }
1479                if (!d_invalidate(dentry)) {
1480                        dput(dentry);
1481                        goto need_lookup;
1482                }
1483        }
1484
1485        path->mnt = mnt;
1486        path->dentry = dentry;
1487        err = follow_managed(path, nd->flags);
1488        if (unlikely(err < 0)) {
1489                path_put_conditional(path, nd);
1490                return err;
1491        }
1492        if (err)
1493                nd->flags |= LOOKUP_JUMPED;
1494        *inode = path->dentry->d_inode;
1495        return 0;
1496
1497need_lookup:
1498        return 1;
1499}
1500
1501/* Fast lookup failed, do it the slow way */
1502static int lookup_slow(struct nameidata *nd, struct path *path)
1503{
1504        struct dentry *dentry, *parent;
1505        int err;
1506
1507        parent = nd->path.dentry;
1508        BUG_ON(nd->inode != parent->d_inode);
1509
1510        mutex_lock(&parent->d_inode->i_mutex);
1511        dentry = __lookup_hash(&nd->last, parent, nd->flags);
1512        mutex_unlock(&parent->d_inode->i_mutex);
1513        if (IS_ERR(dentry))
1514                return PTR_ERR(dentry);
1515        path->mnt = nd->path.mnt;
1516        path->dentry = dentry;
1517        err = follow_managed(path, nd->flags);
1518        if (unlikely(err < 0)) {
1519                path_put_conditional(path, nd);
1520                return err;
1521        }
1522        if (err)
1523                nd->flags |= LOOKUP_JUMPED;
1524        return 0;
1525}
1526
1527static inline int may_lookup(struct nameidata *nd)
1528{
1529        if (nd->flags & LOOKUP_RCU) {
1530                int err = inode_permission(nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
1531                if (err != -ECHILD)
1532                        return err;
1533                if (unlazy_walk(nd, NULL))
1534                        return -ECHILD;
1535        }
1536        return inode_permission(nd->inode, MAY_EXEC);
1537}
1538
1539static inline int handle_dots(struct nameidata *nd, int type)
1540{
1541        if (type == LAST_DOTDOT) {
1542                if (nd->flags & LOOKUP_RCU) {
1543                        if (follow_dotdot_rcu(nd))
1544                                return -ECHILD;
1545                } else
1546                        return follow_dotdot(nd);
1547        }
1548        return 0;
1549}
1550
1551static void terminate_walk(struct nameidata *nd)
1552{
1553        if (!(nd->flags & LOOKUP_RCU)) {
1554                path_put(&nd->path);
1555        } else {
1556                nd->flags &= ~LOOKUP_RCU;
1557                if (!(nd->flags & LOOKUP_ROOT))
1558                        nd->root.mnt = NULL;
1559                rcu_read_unlock();
1560        }
1561}
1562
1563/*
1564 * Do we need to follow links? We _really_ want to be able
1565 * to do this check without having to look at inode->i_op,
1566 * so we keep a cache of "no, this doesn't need follow_link"
1567 * for the common case.
1568 */
1569static inline int should_follow_link(struct dentry *dentry, int follow)
1570{
1571        return unlikely(d_is_symlink(dentry)) ? follow : 0;
1572}
1573
1574static inline int walk_component(struct nameidata *nd, struct path *path,
1575                int follow)
1576{
1577        struct inode *inode;
1578        int err;
1579        /*
1580         * "." and ".." are special - ".." especially so because it has
1581         * to be able to know about the current root directory and
1582         * parent relationships.
1583         */
1584        if (unlikely(nd->last_type != LAST_NORM))
1585                return handle_dots(nd, nd->last_type);
1586        err = lookup_fast(nd, path, &inode);
1587        if (unlikely(err)) {
1588                if (err < 0)
1589                        goto out_err;
1590
1591                err = lookup_slow(nd, path);
1592                if (err < 0)
1593                        goto out_err;
1594
1595                inode = path->dentry->d_inode;
1596        }
1597        err = -ENOENT;
1598        if (!inode || d_is_negative(path->dentry))
1599                goto out_path_put;
1600
1601        if (should_follow_link(path->dentry, follow)) {
1602                if (nd->flags & LOOKUP_RCU) {
1603                        if (unlikely(unlazy_walk(nd, path->dentry))) {
1604                                err = -ECHILD;
1605                                goto out_err;
1606                        }
1607                }
1608                BUG_ON(inode != path->dentry->d_inode);
1609                return 1;
1610        }
1611        path_to_nameidata(path, nd);
1612        nd->inode = inode;
1613        return 0;
1614
1615out_path_put:
1616        path_to_nameidata(path, nd);
1617out_err:
1618        terminate_walk(nd);
1619        return err;
1620}
1621
1622/*
1623 * This limits recursive symlink follows to 8, while
1624 * limiting consecutive symlinks to 40.
1625 *
1626 * Without that kind of total limit, nasty chains of consecutive
1627 * symlinks can cause almost arbitrarily long lookups.
1628 */
1629static inline int nested_symlink(struct path *path, struct nameidata *nd)
1630{
1631        int res;
1632
1633        if (unlikely(current->link_count >= MAX_NESTED_LINKS)) {
1634                path_put_conditional(path, nd);
1635                path_put(&nd->path);
1636                return -ELOOP;
1637        }
1638        BUG_ON(nd->depth >= MAX_NESTED_LINKS);
1639
1640        nd->depth++;
1641        current->link_count++;
1642
1643        do {
1644                struct path link = *path;
1645                void *cookie;
1646
1647                res = follow_link(&link, nd, &cookie);
1648                if (res)
1649                        break;
1650                res = walk_component(nd, path, LOOKUP_FOLLOW);
1651                put_link(nd, &link, cookie);
1652        } while (res > 0);
1653
1654        current->link_count--;
1655        nd->depth--;
1656        return res;
1657}
1658
1659/*
1660 * We can do the critical dentry name comparison and hashing
1661 * operations one word at a time, but we are limited to:
1662 *
1663 * - Architectures with fast unaligned word accesses. We could
1664 *   do a "get_unaligned()" if this helps and is sufficiently
1665 *   fast.
1666 *
1667 * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
1668 *   do not trap on the (extremely unlikely) case of a page
1669 *   crossing operation.
1670 *
1671 * - Furthermore, we need an efficient 64-bit compile for the
1672 *   64-bit case in order to generate the "number of bytes in
1673 *   the final mask". Again, that could be replaced with a
1674 *   efficient population count instruction or similar.
1675 */
1676#ifdef CONFIG_DCACHE_WORD_ACCESS
1677
1678#include <asm/word-at-a-time.h>
1679
1680#ifdef CONFIG_64BIT
1681
1682static inline unsigned int fold_hash(unsigned long hash)
1683{
1684        hash += hash >> (8*sizeof(int));
1685        return hash;
1686}
1687
1688#else   /* 32-bit case */
1689
1690#define fold_hash(x) (x)
1691
1692#endif
1693
1694unsigned int full_name_hash(const unsigned char *name, unsigned int len)
1695{
1696        unsigned long a, mask;
1697        unsigned long hash = 0;
1698
1699        for (;;) {
1700                a = load_unaligned_zeropad(name);
1701                if (len < sizeof(unsigned long))
1702                        break;
1703                hash += a;
1704                hash *= 9;
1705                name += sizeof(unsigned long);
1706                len -= sizeof(unsigned long);
1707                if (!len)
1708                        goto done;
1709        }
1710        mask = bytemask_from_count(len);
1711        hash += mask & a;
1712done:
1713        return fold_hash(hash);
1714}
1715EXPORT_SYMBOL(full_name_hash);
1716
1717/*
1718 * Calculate the length and hash of the path component, and
1719 * return the length of the component;
1720 */
1721static inline unsigned long hash_name(const char *name, unsigned int *hashp)
1722{
1723        unsigned long a, b, adata, bdata, mask, hash, len;
1724        const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
1725
1726        hash = a = 0;
1727        len = -sizeof(unsigned long);
1728        do {
1729                hash = (hash + a) * 9;
1730                len += sizeof(unsigned long);
1731                a = load_unaligned_zeropad(name+len);
1732                b = a ^ REPEAT_BYTE('/');
1733        } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
1734
1735        adata = prep_zero_mask(a, adata, &constants);
1736        bdata = prep_zero_mask(b, bdata, &constants);
1737
1738        mask = create_zero_mask(adata | bdata);
1739
1740        hash += a & zero_bytemask(mask);
1741        *hashp = fold_hash(hash);
1742
1743        return len + find_zero(mask);
1744}
1745
1746#else
1747
1748unsigned int full_name_hash(const unsigned char *name, unsigned int len)
1749{
1750        unsigned long hash = init_name_hash();
1751        while (len--)
1752                hash = partial_name_hash(*name++, hash);
1753        return end_name_hash(hash);
1754}
1755EXPORT_SYMBOL(full_name_hash);
1756
1757/*
1758 * We know there's a real path component here of at least
1759 * one character.
1760 */
1761static inline unsigned long hash_name(const char *name, unsigned int *hashp)
1762{
1763        unsigned long hash = init_name_hash();
1764        unsigned long len = 0, c;
1765
1766        c = (unsigned char)*name;
1767        do {
1768                len++;
1769                hash = partial_name_hash(c, hash);
1770                c = (unsigned char)name[len];
1771        } while (c && c != '/');
1772        *hashp = end_name_hash(hash);
1773        return len;
1774}
1775
1776#endif
1777
1778/*
1779 * Name resolution.
1780 * This is the basic name resolution function, turning a pathname into
1781 * the final dentry. We expect 'base' to be positive and a directory.
1782 *
1783 * Returns 0 and nd will have valid dentry and mnt on success.
1784 * Returns error and drops reference to input namei data on failure.
1785 */
1786static int link_path_walk(const char *name, struct nameidata *nd)
1787{
1788        struct path next;
1789        int err;
1790        
1791        while (*name=='/')
1792                name++;
1793        if (!*name)
1794                return 0;
1795
1796        /* At this point we know we have a real path component. */
1797        for(;;) {
1798                struct qstr this;
1799                long len;
1800                int type;
1801
1802                err = may_lookup(nd);
1803                if (err)
1804                        break;
1805
1806                len = hash_name(name, &this.hash);
1807                this.name = name;
1808                this.len = len;
1809
1810                type = LAST_NORM;
1811                if (name[0] == '.') switch (len) {
1812                        case 2:
1813                                if (name[1] == '.') {
1814                                        type = LAST_DOTDOT;
1815                                        nd->flags |= LOOKUP_JUMPED;
1816                                }
1817                                break;
1818                        case 1:
1819                                type = LAST_DOT;
1820                }
1821                if (likely(type == LAST_NORM)) {
1822                        struct dentry *parent = nd->path.dentry;
1823                        nd->flags &= ~LOOKUP_JUMPED;
1824                        if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
1825                                err = parent->d_op->d_hash(parent, &this);
1826                                if (err < 0)
1827                                        break;
1828                        }
1829                }
1830
1831                nd->last = this;
1832                nd->last_type = type;
1833
1834                if (!name[len])
1835                        return 0;
1836                /*
1837                 * If it wasn't NUL, we know it was '/'. Skip that
1838                 * slash, and continue until no more slashes.
1839                 */
1840                do {
1841                        len++;
1842                } while (unlikely(name[len] == '/'));
1843                if (!name[len])
1844                        return 0;
1845
1846                name += len;
1847
1848                err = walk_component(nd, &next, LOOKUP_FOLLOW);
1849                if (err < 0)
1850                        return err;
1851
1852                if (err) {
1853                        err = nested_symlink(&next, nd);
1854                        if (err)
1855                                return err;
1856                }
1857                if (!d_can_lookup(nd->path.dentry)) {
1858                        err = -ENOTDIR; 
1859                        break;
1860                }
1861        }
1862        terminate_walk(nd);
1863        return err;
1864}
1865
1866static int path_init(int dfd, const char *name, unsigned int flags,
1867                     struct nameidata *nd, struct file **fp)
1868{
1869
1870        nd->last_type = LAST_ROOT; /* if there are only slashes... */
1871        nd->flags = flags | LOOKUP_JUMPED;
1872        nd->depth = 0;
1873        if (flags & LOOKUP_ROOT) {
1874                struct dentry *root = nd->root.dentry;
1875                struct inode *inode = root->d_inode;
1876                if (*name && unlikely(!d_can_lookup(root)))
1877                        return -ENOTDIR;
1878                nd->path = nd->root;
1879                nd->inode = inode;
1880                if (flags & LOOKUP_RCU) {
1881                        rcu_read_lock();
1882                        nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
1883                        nd->m_seq = read_seqbegin(&mount_lock);
1884                } else {
1885                        path_get(&nd->path);
1886                }
1887                return 0;
1888        }
1889
1890        nd->root.mnt = NULL;
1891
1892        nd->m_seq = read_seqbegin(&mount_lock);
1893        if (*name=='/') {
1894                if (flags & LOOKUP_RCU) {
1895                        rcu_read_lock();
1896                        set_root_rcu(nd);
1897                } else {
1898                        set_root(nd);
1899                        path_get(&nd->root);
1900                }
1901                nd->path = nd->root;
1902        } else if (dfd == AT_FDCWD) {
1903                if (flags & LOOKUP_RCU) {
1904                        struct fs_struct *fs = current->fs;
1905                        unsigned seq;
1906
1907                        rcu_read_lock();
1908
1909                        do {
1910                                seq = read_seqcount_begin(&fs->seq);
1911                                nd->path = fs->pwd;
1912                                nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
1913                        } while (read_seqcount_retry(&fs->seq, seq));
1914                } else {
1915                        get_fs_pwd(current->fs, &nd->path);
1916                }
1917        } else {
1918                /* Caller must check execute permissions on the starting path component */
1919                struct fd f = fdget_raw(dfd);
1920                struct dentry *dentry;
1921
1922                if (!f.file)
1923                        return -EBADF;
1924
1925                dentry = f.file->f_path.dentry;
1926
1927                if (*name) {
1928                        if (!d_can_lookup(dentry)) {
1929                                fdput(f);
1930                                return -ENOTDIR;
1931                        }
1932                }
1933
1934                nd->path = f.file->f_path;
1935                if (flags & LOOKUP_RCU) {
1936                        if (f.flags & FDPUT_FPUT)
1937                                *fp = f.file;
1938                        nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
1939                        rcu_read_lock();
1940                } else {
1941                        path_get(&nd->path);
1942                        fdput(f);
1943                }
1944        }
1945
1946        nd->inode = nd->path.dentry->d_inode;
1947        return 0;
1948}
1949
1950static inline int lookup_last(struct nameidata *nd, struct path *path)
1951{
1952        if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
1953                nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
1954
1955        nd->flags &= ~LOOKUP_PARENT;
1956        return walk_component(nd, path, nd->flags & LOOKUP_FOLLOW);
1957}
1958
1959static int handle_lookup_down(struct nameidata *nd)
1960{
1961        struct path path = nd->path;
1962        struct inode *inode = nd->inode;
1963        int err;
1964
1965        if (nd->flags & LOOKUP_RCU) {
1966                /*
1967                 * don't bother with unlazy_walk on failure - we are
1968                 * at the very beginning of walk, so we lose nothing
1969                 * if we simply redo everything in non-RCU mode
1970                 */
1971                if (unlikely(!__follow_mount_rcu(nd, &path, &inode)))
1972                        return -ECHILD;
1973        } else {
1974                dget(path.dentry);
1975                err = follow_managed(&path, nd->flags);
1976                if (unlikely(err < 0)) {
1977                        path_put_conditional(&path, nd);
1978                        return err;
1979                }
1980                if (err)
1981                        nd->flags |= LOOKUP_JUMPED;
1982                inode = d_backing_inode(path.dentry);
1983        }
1984        path_to_nameidata(&path, nd);
1985        nd->inode = inode;
1986        return 0;
1987}
1988
1989/* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
1990static int path_lookupat(int dfd, const char *name,
1991                                unsigned int flags, struct nameidata *nd)
1992{
1993        struct file *base = NULL;
1994        struct path path;
1995        int err;
1996
1997        /*
1998         * Path walking is largely split up into 2 different synchronisation
1999         * schemes, rcu-walk and ref-walk (explained in
2000         * Documentation/filesystems/path-lookup.txt). These share much of the
2001         * path walk code, but some things particularly setup, cleanup, and
2002         * following mounts are sufficiently divergent that functions are
2003         * duplicated. Typically there is a function foo(), and its RCU
2004         * analogue, foo_rcu().
2005         *
2006         * -ECHILD is the error number of choice (just to avoid clashes) that
2007         * is returned if some aspect of an rcu-walk fails. Such an error must
2008         * be handled by restarting a traditional ref-walk (which will always
2009         * be able to complete).
2010         */
2011        err = path_init(dfd, name, flags | LOOKUP_PARENT, nd, &base);
2012
2013        if (unlikely(err))
2014                return err;
2015
2016        current->total_link_count = 0;
2017
2018        if (unlikely(flags & LOOKUP_DOWN)) {
2019                err = handle_lookup_down(nd);
2020                if (unlikely(err < 0))
2021                        terminate_walk(nd);
2022        }
2023
2024        if (!err)
2025                err = link_path_walk(name, nd);
2026
2027        if (!err && !(flags & LOOKUP_PARENT)) {
2028                err = lookup_last(nd, &path);
2029                while (err > 0) {
2030                        void *cookie;
2031                        struct path link = path;
2032                        err = may_follow_link(&link, nd);
2033                        if (unlikely(err))
2034                                break;
2035                        nd->flags |= LOOKUP_PARENT;
2036                        err = follow_link(&link, nd, &cookie);
2037                        if (err)
2038                                break;
2039                        err = lookup_last(nd, &path);
2040                        put_link(nd, &link, cookie);
2041                }
2042        }
2043
2044        if (!err)
2045                err = complete_walk(nd);
2046
2047        if (!err && nd->flags & LOOKUP_DIRECTORY) {
2048                if (!d_can_lookup(nd->path.dentry)) {
2049                        path_put(&nd->path);
2050                        err = -ENOTDIR;
2051                }
2052        }
2053
2054        if (base)
2055                fput(base);
2056
2057        if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) {
2058                path_put(&nd->root);
2059                nd->root.mnt = NULL;
2060        }
2061        return err;
2062}
2063
2064static int filename_lookup(int dfd, struct filename *name,
2065                                unsigned int flags, struct nameidata *nd)
2066{
2067        int retval = path_lookupat(dfd, name->name, flags | LOOKUP_RCU, nd);
2068        if (unlikely(retval == -ECHILD))
2069                retval = path_lookupat(dfd, name->name, flags, nd);
2070        if (unlikely(retval == -ESTALE))
2071                retval = path_lookupat(dfd, name->name,
2072                                                flags | LOOKUP_REVAL, nd);
2073
2074        if (likely(!retval))
2075                audit_inode(name, nd->path.dentry, flags & LOOKUP_PARENT);
2076        return retval;
2077}
2078
2079static int do_path_lookup(int dfd, const char *name,
2080                                unsigned int flags, struct nameidata *nd)
2081{
2082        struct filename *filename = getname_kernel(name);
2083        int retval = PTR_ERR(filename);
2084
2085        if (!IS_ERR(filename)) {
2086                retval = filename_lookup(dfd, filename, flags, nd);
2087                putname(filename);
2088        }
2089        return retval;
2090}
2091
2092/* does lookup, returns the object with parent locked */
2093struct dentry *kern_path_locked(const char *name, struct path *path)
2094{
2095        struct filename *filename = getname_kernel(name);
2096        struct nameidata nd;
2097        struct dentry *d;
2098        int err;
2099
2100        if (IS_ERR(filename))
2101                return ERR_CAST(filename);
2102
2103        err = filename_lookup(AT_FDCWD, filename, LOOKUP_PARENT, &nd);
2104        if (err) {
2105                d = ERR_PTR(err);
2106                goto out;
2107        }
2108        if (nd.last_type != LAST_NORM) {
2109                path_put(&nd.path);
2110                d = ERR_PTR(-EINVAL);
2111                goto out;
2112        }
2113        mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
2114        d = __lookup_hash(&nd.last, nd.path.dentry, 0);
2115        if (IS_ERR(d)) {
2116                mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
2117                path_put(&nd.path);
2118                goto out;
2119        }
2120        *path = nd.path;
2121out:
2122        putname(filename);
2123        return d;
2124}
2125
2126int kern_path(const char *name, unsigned int flags, struct path *path)
2127{
2128        struct nameidata nd;
2129        int res = do_path_lookup(AT_FDCWD, name, flags, &nd);
2130        if (!res)
2131                *path = nd.path;
2132        return res;
2133}
2134
2135/**
2136 * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
2137 * @dentry:  pointer to dentry of the base directory
2138 * @mnt: pointer to vfs mount of the base directory
2139 * @name: pointer to file name
2140 * @flags: lookup flags
2141 * @path: pointer to struct path to fill
2142 */
2143int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
2144                    const char *name, unsigned int flags,
2145                    struct path *path)
2146{
2147        struct nameidata nd;
2148        int err;
2149        nd.root.dentry = dentry;
2150        nd.root.mnt = mnt;
2151        BUG_ON(flags & LOOKUP_PARENT);
2152        /* the first argument of do_path_lookup() is ignored with LOOKUP_ROOT */
2153        err = do_path_lookup(AT_FDCWD, name, flags | LOOKUP_ROOT, &nd);
2154        if (!err)
2155                *path = nd.path;
2156        return err;
2157}
2158
2159/*
2160 * Restricted form of lookup. Doesn't follow links, single-component only,
2161 * needs parent already locked. Doesn't follow mounts.
2162 * SMP-safe.
2163 */
2164static struct dentry *lookup_hash(struct nameidata *nd)
2165{
2166        return __lookup_hash(&nd->last, nd->path.dentry, nd->flags);
2167}
2168
2169/**
2170 * lookup_one_len - filesystem helper to lookup single pathname component
2171 * @name:       pathname component to lookup
2172 * @base:       base directory to lookup from
2173 * @len:        maximum length @len should be interpreted to
2174 *
2175 * Note that this routine is purely a helper for filesystem usage and should
2176 * not be called by generic code.  Also note that by using this function the
2177 * nameidata argument is passed to the filesystem methods and a filesystem
2178 * using this helper needs to be prepared for that.
2179 *
2180 * The caller must hold base->i_mutex.
2181 */
2182struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2183{
2184        struct qstr this;
2185        unsigned int c;
2186        int err;
2187
2188        WARN_ON_ONCE(!mutex_is_locked(&base->d_inode->i_mutex));
2189
2190        this.name = name;
2191        this.len = len;
2192        this.hash = full_name_hash(name, len);
2193        if (!len)
2194                return ERR_PTR(-EACCES);
2195
2196        if (unlikely(name[0] == '.')) {
2197                if (len < 2 || (len == 2 && name[1] == '.'))
2198                        return ERR_PTR(-EACCES);
2199        }
2200
2201        while (len--) {
2202                c = *(const unsigned char *)name++;
2203                if (c == '/' || c == '\0')
2204                        return ERR_PTR(-EACCES);
2205        }
2206        /*
2207         * See if the low-level filesystem might want
2208         * to use its own hash..
2209         */
2210        if (base->d_flags & DCACHE_OP_HASH) {
2211                int err = base->d_op->d_hash(base, &this);
2212                if (err < 0)
2213                        return ERR_PTR(err);
2214        }
2215
2216        err = inode_permission(base->d_inode, MAY_EXEC);
2217        if (err)
2218                return ERR_PTR(err);
2219
2220        return __lookup_hash(&this, base, 0);
2221}
2222
2223/**
2224 * lookup_one_len_unlocked - filesystem helper to lookup single pathname component
2225 * @name:       pathname component to lookup
2226 * @base:       base directory to lookup from
2227 * @len:        maximum length @len should be interpreted to
2228 *
2229 * Note that this routine is purely a helper for filesystem usage and should
2230 * not be called by generic code.
2231 *
2232 * Unlike lookup_one_len, it should be called without the parent
2233 * i_mutex held, and will take the i_mutex itself if necessary.
2234 */
2235struct dentry *lookup_one_len_unlocked(const char *name,
2236                                       struct dentry *base, int len)
2237{
2238        struct qstr this;
2239        unsigned int c;
2240        int err;
2241        struct dentry *ret;
2242
2243        this.name = name;
2244        this.len = len;
2245        this.hash = full_name_hash(name, len);
2246        if (!len)
2247                return ERR_PTR(-EACCES);
2248
2249        if (unlikely(name[0] == '.')) {
2250                if (len < 2 || (len == 2 && name[1] == '.'))
2251                        return ERR_PTR(-EACCES);
2252        }
2253
2254        while (len--) {
2255                c = *(const unsigned char *)name++;
2256                if (c == '/' || c == '\0')
2257                        return ERR_PTR(-EACCES);
2258        }
2259        /*
2260         * See if the low-level filesystem might want
2261         * to use its own hash..
2262         */
2263        if (base->d_flags & DCACHE_OP_HASH) {
2264                int err = base->d_op->d_hash(base, &this);
2265                if (err < 0)
2266                        return ERR_PTR(err);
2267        }
2268
2269        err = inode_permission(base->d_inode, MAY_EXEC);
2270        if (err)
2271                return ERR_PTR(err);
2272
2273        /*
2274         * __d_lookup() is used to try to get a quick answer and avoid the
2275         * mutex.  A false-negative does no harm.
2276         */
2277        ret = __d_lookup(base, &this);
2278        if (ret && unlikely(ret->d_flags & DCACHE_OP_REVALIDATE)) {
2279                dput(ret);
2280                ret = NULL;
2281        }
2282        if (ret)
2283                return ret;
2284
2285        mutex_lock(&base->d_inode->i_mutex);
2286        ret =  __lookup_hash(&this, base, 0);
2287        mutex_unlock(&base->d_inode->i_mutex);
2288        return ret;
2289}
2290EXPORT_SYMBOL(lookup_one_len_unlocked);
2291
2292int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
2293                 struct path *path, int *empty)
2294{
2295        struct nameidata nd;
2296        struct filename *tmp = getname_flags(name, flags, empty);
2297        int err = PTR_ERR(tmp);
2298        if (!IS_ERR(tmp)) {
2299
2300                BUG_ON(flags & LOOKUP_PARENT);
2301
2302                err = filename_lookup(dfd, tmp, flags, &nd);
2303                putname(tmp);
2304                if (!err)
2305                        *path = nd.path;
2306        }
2307        return err;
2308}
2309
2310int user_path_at(int dfd, const char __user *name, unsigned flags,
2311                 struct path *path)
2312{
2313        return user_path_at_empty(dfd, name, flags, path, NULL);
2314}
2315
2316/*
2317 * NB: most callers don't do anything directly with the reference to the
2318 *     to struct filename, but the nd->last pointer points into the name string
2319 *     allocated by getname. So we must hold the reference to it until all
2320 *     path-walking is complete.
2321 */
2322static struct filename *
2323user_path_parent(int dfd, const char __user *path, struct nameidata *nd,
2324                 unsigned int flags)
2325{
2326        struct filename *s = getname(path);
2327        int error;
2328
2329        /* only LOOKUP_REVAL is allowed in extra flags */
2330        flags &= LOOKUP_REVAL;
2331
2332        if (IS_ERR(s))
2333                return s;
2334
2335        error = filename_lookup(dfd, s, flags | LOOKUP_PARENT, nd);
2336        if (error) {
2337                putname(s);
2338                return ERR_PTR(error);
2339        }
2340
2341        return s;
2342}
2343
2344/**
2345 * mountpoint_last - look up last component for umount
2346 * @nd:   pathwalk nameidata - currently pointing at parent directory of "last"
2347 * @path: pointer to container for result
2348 *
2349 * This is a special lookup_last function just for umount. In this case, we
2350 * need to resolve the path without doing any revalidation.
2351 *
2352 * The nameidata should be the result of doing a LOOKUP_PARENT pathwalk. Since
2353 * mountpoints are always pinned in the dcache, their ancestors are too. Thus,
2354 * in almost all cases, this lookup will be served out of the dcache. The only
2355 * cases where it won't are if nd->last refers to a symlink or the path is
2356 * bogus and it doesn't exist.
2357 *
2358 * Returns:
2359 * -error: if there was an error during lookup. This includes -ENOENT if the
2360 *         lookup found a negative dentry. The nd->path reference will also be
2361 *         put in this case.
2362 *
2363 * 0:      if we successfully resolved nd->path and found it to not to be a
2364 *         symlink that needs to be followed. "path" will also be populated.
2365 *         The nd->path reference will also be put.
2366 *
2367 * 1:      if we successfully resolved nd->last and found it to be a symlink
2368 *         that needs to be followed. "path" will be populated with the path
2369 *         to the link, and nd->path will *not* be put.
2370 */
2371static int
2372mountpoint_last(struct nameidata *nd, struct path *path)
2373{
2374        int error = 0;
2375        struct dentry *dentry;
2376        struct dentry *dir = nd->path.dentry;
2377
2378        /* If we're in rcuwalk, drop out of it to handle last component */
2379        if (nd->flags & LOOKUP_RCU) {
2380                if (unlazy_walk(nd, NULL)) {
2381                        error = -ECHILD;
2382                        goto out;
2383                }
2384        }
2385
2386        nd->flags &= ~LOOKUP_PARENT;
2387
2388        if (unlikely(nd->last_type != LAST_NORM)) {
2389                error = handle_dots(nd, nd->last_type);
2390                if (error)
2391                        return error;
2392                dentry = dget(nd->path.dentry);
2393                goto done;
2394        }
2395
2396        mutex_lock(&dir->d_inode->i_mutex);
2397        dentry = d_lookup(dir, &nd->last);
2398        if (!dentry) {
2399                /*
2400                 * No cached dentry. Mounted dentries are pinned in the cache,
2401                 * so that means that this dentry is probably a symlink or the
2402                 * path doesn't actually point to a mounted dentry.
2403                 */
2404                dentry = d_alloc(dir, &nd->last);
2405                if (!dentry) {
2406                        error = -ENOMEM;
2407                        mutex_unlock(&dir->d_inode->i_mutex);
2408                        goto out;
2409                }
2410                dentry = lookup_real(dir->d_inode, dentry, nd->flags);
2411                error = PTR_ERR(dentry);
2412                if (IS_ERR(dentry)) {
2413                        mutex_unlock(&dir->d_inode->i_mutex);
2414                        goto out;
2415                }
2416        }
2417        mutex_unlock(&dir->d_inode->i_mutex);
2418
2419done:
2420        if (!dentry->d_inode || d_is_negative(dentry)) {
2421                error = -ENOENT;
2422                dput(dentry);
2423                goto out;
2424        }
2425        path->dentry = dentry;
2426        path->mnt = nd->path.mnt;
2427        if (should_follow_link(dentry, nd->flags & LOOKUP_FOLLOW))
2428                return 1;
2429        mntget(path->mnt);
2430        follow_mount(path);
2431        error = 0;
2432out:
2433        terminate_walk(nd);
2434        return error;
2435}
2436
2437/**
2438 * path_mountpoint - look up a path to be umounted
2439 * @dfd:        directory file descriptor to start walk from
2440 * @name:       full pathname to walk
2441 * @flags:      lookup flags
2442 *
2443 * Look up the given name, but don't attempt to revalidate the last component.
2444 * Returns 0 and "path" will be valid on success; Retuns error otherwise.
2445 */
2446static int
2447path_mountpoint(int dfd, const char *name, struct path *path, unsigned int flags)
2448{
2449        struct file *base = NULL;
2450        struct nameidata nd;
2451        int err;
2452
2453        err = path_init(dfd, name, flags | LOOKUP_PARENT, &nd, &base);
2454        if (unlikely(err))
2455                return err;
2456
2457        current->total_link_count = 0;
2458        err = link_path_walk(name, &nd);
2459        if (err)
2460                goto out;
2461
2462        err = mountpoint_last(&nd, path);
2463        while (err > 0) {
2464                void *cookie;
2465                struct path link = *path;
2466                err = may_follow_link(&link, &nd);
2467                if (unlikely(err))
2468                        break;
2469                nd.flags |= LOOKUP_PARENT;
2470                err = follow_link(&link, &nd, &cookie);
2471                if (err)
2472                        break;
2473                err = mountpoint_last(&nd, path);
2474                put_link(&nd, &link, cookie);
2475        }
2476out:
2477        if (base)
2478                fput(base);
2479
2480        if (nd.root.mnt && !(nd.flags & LOOKUP_ROOT))
2481                path_put(&nd.root);
2482
2483        return err;
2484}
2485
2486static int
2487filename_mountpoint(int dfd, struct filename *s, struct path *path,
2488                        unsigned int flags)
2489{
2490        int error;
2491        if (IS_ERR(s))
2492                return PTR_ERR(s);
2493        error = path_mountpoint(dfd, s->name, path, flags | LOOKUP_RCU);
2494        if (unlikely(error == -ECHILD))
2495                error = path_mountpoint(dfd, s->name, path, flags);
2496        if (unlikely(error == -ESTALE))
2497                error = path_mountpoint(dfd, s->name, path, flags | LOOKUP_REVAL);
2498        if (likely(!error))
2499                audit_inode(s, path->dentry, flags & LOOKUP_NO_EVAL);
2500        putname(s);
2501        return error;
2502}
2503
2504/**
2505 * user_path_mountpoint_at - lookup a path from userland in order to umount it
2506 * @dfd:        directory file descriptor
2507 * @name:       pathname from userland
2508 * @flags:      lookup flags
2509 * @path:       pointer to container to hold result
2510 *
2511 * A umount is a special case for path walking. We're not actually interested
2512 * in the inode in this situation, and ESTALE errors can be a problem. We
2513 * simply want track down the dentry and vfsmount attached at the mountpoint
2514 * and avoid revalidating the last component.
2515 *
2516 * Returns 0 and populates "path" on success.
2517 */
2518int
2519user_path_mountpoint_at(int dfd, const char __user *name, unsigned int flags,
2520                        struct path *path)
2521{
2522        return filename_mountpoint(dfd, getname(name), path, flags);
2523}
2524
2525int
2526kern_path_mountpoint(int dfd, const char *name, struct path *path,
2527                        unsigned int flags)
2528{
2529        return filename_mountpoint(dfd, getname_kernel(name), path, flags);
2530}
2531EXPORT_SYMBOL(kern_path_mountpoint);
2532
2533int __check_sticky(struct inode *dir, struct inode *inode)
2534{
2535        kuid_t fsuid = current_fsuid();
2536
2537        if (uid_eq(inode->i_uid, fsuid))
2538                return 0;
2539        if (uid_eq(dir->i_uid, fsuid))
2540                return 0;
2541        return !capable_wrt_inode_uidgid(inode, CAP_FOWNER);
2542}
2543EXPORT_SYMBOL(__check_sticky);
2544
2545/*
2546 *      Check whether we can remove a link victim from directory dir, check
2547 *  whether the type of victim is right.
2548 *  1. We can't do it if dir is read-only (done in permission())
2549 *  2. We should have write and exec permissions on dir
2550 *  3. We can't remove anything from append-only dir
2551 *  4. We can't do anything with immutable dir (done in permission())
2552 *  5. If the sticky bit on dir is set we should either
2553 *      a. be owner of dir, or
2554 *      b. be owner of victim, or
2555 *      c. have CAP_FOWNER capability
2556 *  6. If the victim is append-only or immutable we can't do antyhing with
2557 *     links pointing to it.
2558 *  7. If the victim has an unknown uid or gid we can't change the inode.
2559 *  8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
2560 *  9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
2561 * 10. We can't remove a root or mountpoint.
2562 * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
2563 *     nfs_async_unlink().
2564 */
2565static int may_delete(struct inode *dir, struct dentry *victim, bool isdir)
2566{
2567        struct inode *inode = victim->d_inode;
2568        int error;
2569
2570        if (d_is_negative(victim))
2571                return -ENOENT;
2572        BUG_ON(!inode);
2573
2574        BUG_ON(victim->d_parent->d_inode != dir);
2575
2576        /* Inode writeback is not safe when the uid or gid are invalid. */
2577        if (!uid_valid(inode->i_uid) || !gid_valid(inode->i_gid))
2578                return -EOVERFLOW;
2579
2580        audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
2581
2582        error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
2583        if (error)
2584                return error;
2585        if (IS_APPEND(dir))
2586                return -EPERM;
2587
2588        if (check_sticky(dir, inode) || IS_APPEND(inode) ||
2589            IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) || HAS_UNMAPPED_ID(inode))
2590                return -EPERM;
2591        if (isdir) {
2592                if (!d_is_dir(victim))
2593                        return -ENOTDIR;
2594                if (IS_ROOT(victim))
2595                        return -EBUSY;
2596        } else if (d_is_dir(victim))
2597                return -EISDIR;
2598        if (IS_DEADDIR(dir))
2599                return -ENOENT;
2600        if (victim->d_flags & DCACHE_NFSFS_RENAMED)
2601                return -EBUSY;
2602        return 0;
2603}
2604
2605/*      Check whether we can create an object with dentry child in directory
2606 *  dir.
2607 *  1. We can't do it if child already exists (open has special treatment for
2608 *     this case, but since we are inlined it's OK)
2609 *  2. We can't do it if dir is read-only (done in permission())
2610 *  3. We can't do it if the fs can't represent the fsuid or fsgid.
2611 *  4. We should have write and exec permissions on dir
2612 *  5. We can't do it if dir is immutable (done in permission())
2613 */
2614static inline int may_create(struct inode *dir, struct dentry *child)
2615{
2616        struct user_namespace *s_user_ns;
2617        audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
2618        if (child->d_inode)
2619                return -EEXIST;
2620        if (IS_DEADDIR(dir))
2621                return -ENOENT;
2622        s_user_ns = dir->i_sb->s_user_ns;
2623        if (!kuid_has_mapping(s_user_ns, current_fsuid()) ||
2624            !kgid_has_mapping(s_user_ns, current_fsgid()))
2625                return -EOVERFLOW;
2626        return inode_permission(dir, MAY_WRITE | MAY_EXEC);
2627}
2628
2629/*
2630 * p1 and p2 should be directories on the same fs.
2631 */
2632struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
2633{
2634        struct dentry *p;
2635
2636        if (p1 == p2) {
2637                mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
2638                return NULL;
2639        }
2640
2641        mutex_lock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
2642
2643        p = d_ancestor(p2, p1);
2644        if (p) {
2645                mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT);
2646                mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_CHILD);
2647                return p;
2648        }
2649
2650        p = d_ancestor(p1, p2);
2651        if (p) {
2652                mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
2653                mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD);
2654                return p;
2655        }
2656
2657        mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
2658        mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT2);
2659        return NULL;
2660}
2661
2662void unlock_rename(struct dentry *p1, struct dentry *p2)
2663{
2664        mutex_unlock(&p1->d_inode->i_mutex);
2665        if (p1 != p2) {
2666                mutex_unlock(&p2->d_inode->i_mutex);
2667                mutex_unlock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
2668        }
2669}
2670
2671int vfs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2672                bool want_excl)
2673{
2674        int error = may_create(dir, dentry);
2675        if (error)
2676                return error;
2677
2678        if (!dir->i_op->create)
2679                return -EACCES; /* shouldn't it be ENOSYS? */
2680        mode &= S_IALLUGO;
2681        mode |= S_IFREG;
2682        error = security_inode_create(dir, dentry, mode);
2683        if (error)
2684                return error;
2685        error = dir->i_op->create(dir, dentry, mode, want_excl);
2686        if (!error)
2687                fsnotify_create(dir, dentry);
2688        return error;
2689}
2690
2691int vfs_mkobj(struct dentry *dentry, umode_t mode,
2692                int (*f)(struct dentry *, umode_t, void *),
2693                void *arg)
2694{
2695        struct inode *dir = dentry->d_parent->d_inode;
2696        int error = may_create(dir, dentry);
2697        if (error)
2698                return error;
2699
2700        mode &= S_IALLUGO;
2701        mode |= S_IFREG;
2702        error = security_inode_create(dir, dentry, mode);
2703        if (error)
2704                return error;
2705        error = f(dentry, mode, arg);
2706        if (!error)
2707                fsnotify_create(dir, dentry);
2708        return error;
2709}
2710EXPORT_SYMBOL(vfs_mkobj);
2711
2712bool may_open_dev(const struct path *path)
2713{
2714        return !(path->mnt->mnt_flags & MNT_NODEV) &&
2715                !(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
2716}
2717
2718static int may_open(struct path *path, int acc_mode, int flag)
2719{
2720        struct dentry *dentry = path->dentry;
2721        struct inode *inode = dentry->d_inode;
2722        int error;
2723
2724        if (!inode)
2725                return -ENOENT;
2726
2727        switch (inode->i_mode & S_IFMT) {
2728        case S_IFLNK:
2729                return -ELOOP;
2730        case S_IFDIR:
2731                if (acc_mode & MAY_WRITE)
2732                        return -EISDIR;
2733                break;
2734        case S_IFBLK:
2735        case S_IFCHR:
2736                if (!may_open_dev(path))
2737                        return -EACCES;
2738                /*FALLTHRU*/
2739        case S_IFIFO:
2740        case S_IFSOCK:
2741                flag &= ~O_TRUNC;
2742                break;
2743        }
2744
2745        error = inode_permission(inode, MAY_OPEN | acc_mode);
2746        if (error)
2747                return error;
2748
2749        /*
2750         * An append-only file must be opened in append mode for writing.
2751         */
2752        if (IS_APPEND(inode)) {
2753                if  ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
2754                        return -EPERM;
2755                if (flag & O_TRUNC)
2756                        return -EPERM;
2757        }
2758
2759        /* O_NOATIME can only be set by the owner or superuser */
2760        if (flag & O_NOATIME && !inode_owner_or_capable(inode))
2761                return -EPERM;
2762
2763        return 0;
2764}
2765
2766static int handle_truncate(struct file *filp)
2767{
2768        struct path *path = &filp->f_path;
2769        struct inode *inode = path->dentry->d_inode;
2770        int error = get_write_access(inode);
2771        if (error)
2772                return error;
2773        /*
2774         * Refuse to truncate files with mandatory locks held on them.
2775         */
2776        error = locks_verify_locked(filp);
2777        if (!error)
2778                error = security_path_truncate(path);
2779        if (!error) {
2780                error = do_truncate(path->dentry, 0,
2781                                    ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
2782                                    filp);
2783        }
2784        put_write_access(inode);
2785        return error;
2786}
2787
2788static inline int open_to_namei_flags(int flag)
2789{
2790        if ((flag & O_ACCMODE) == 3)
2791                flag--;
2792        return flag;
2793}
2794
2795static int may_o_create(struct path *dir, struct dentry *dentry, umode_t mode)
2796{
2797        struct user_namespace *s_user_ns;
2798        int error = security_path_mknod(dir, dentry, mode, 0);
2799        if (error)
2800                return error;
2801
2802        s_user_ns = dir->dentry->d_sb->s_user_ns;
2803        if (!kuid_has_mapping(s_user_ns, current_fsuid()) ||
2804            !kgid_has_mapping(s_user_ns, current_fsgid()))
2805                return -EOVERFLOW;
2806
2807        error = inode_permission(dir->dentry->d_inode, MAY_WRITE | MAY_EXEC);
2808        if (error)
2809                return error;
2810
2811        return security_inode_create(dir->dentry->d_inode, dentry, mode);
2812}
2813
2814/*
2815 * Attempt to atomically look up, create and open a file from a negative
2816 * dentry.
2817 *
2818 * Returns 0 if successful.  The file will have been created and attached to
2819 * @file by the filesystem calling finish_open().
2820 *
2821 * Returns 1 if the file was looked up only or didn't need creating.  The
2822 * caller will need to perform the open themselves.  @path will have been
2823 * updated to point to the new dentry.  This may be negative.
2824 *
2825 * Returns an error code otherwise.
2826 */
2827static int atomic_open(struct nameidata *nd, struct dentry *dentry,
2828                        struct path *path, struct file *file,
2829                        const struct open_flags *op,
2830                        bool got_write, bool need_lookup,
2831                        int *opened)
2832{
2833        struct inode *dir =  nd->path.dentry->d_inode;
2834        unsigned open_flag = open_to_namei_flags(op->open_flag);
2835        umode_t mode;
2836        int error;
2837        int acc_mode;
2838        int create_error = 0;
2839        struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
2840        bool excl;
2841
2842        BUG_ON(dentry->d_inode);
2843
2844        /* Don't create child dentry for a dead directory. */
2845        if (unlikely(IS_DEADDIR(dir))) {
2846                error = -ENOENT;
2847                goto out;
2848        }
2849
2850        mode = op->mode;
2851        if ((open_flag & O_CREAT) && !IS_POSIXACL(dir))
2852                mode &= ~current_umask();
2853
2854        excl = (open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT);
2855        if (excl)
2856                open_flag &= ~O_TRUNC;
2857
2858        /*
2859         * Checking write permission is tricky, bacuse we don't know if we are
2860         * going to actually need it: O_CREAT opens should work as long as the
2861         * file exists.  But checking existence breaks atomicity.  The trick is
2862         * to check access and if not granted clear O_CREAT from the flags.
2863         *
2864         * Another problem is returing the "right" error value (e.g. for an
2865         * O_EXCL open we want to return EEXIST not EROFS).
2866         */
2867        if (((open_flag & (O_CREAT | O_TRUNC)) ||
2868            (open_flag & O_ACCMODE) != O_RDONLY) && unlikely(!got_write)) {
2869                if (!(open_flag & O_CREAT)) {
2870                        /*
2871                         * No O_CREATE -> atomicity not a requirement -> fall
2872                         * back to lookup + open
2873                         */
2874                        goto no_open;
2875                } else if (open_flag & (O_EXCL | O_TRUNC)) {
2876                        /* Fall back and fail with the right error */
2877                        create_error = -EROFS;
2878                        goto no_open;
2879                } else {
2880                        /* No side effects, safe to clear O_CREAT */
2881                        create_error = -EROFS;
2882                        open_flag &= ~O_CREAT;
2883                }
2884        }
2885
2886        if (open_flag & O_CREAT) {
2887                error = may_o_create(&nd->path, dentry, mode);
2888                if (error) {
2889                        create_error = error;
2890                        if (open_flag & O_EXCL)
2891                                goto no_open;
2892                        open_flag &= ~O_CREAT;
2893                }
2894        }
2895
2896        if (nd->flags & LOOKUP_DIRECTORY)
2897                open_flag |= O_DIRECTORY;
2898
2899        file->f_path.dentry = DENTRY_NOT_SET;
2900        file->f_path.mnt = nd->path.mnt;
2901        error = dir->i_op->atomic_open(dir, dentry, file, open_flag, mode,
2902                                      opened);
2903        if (error < 0) {
2904                if (create_error && error == -ENOENT)
2905                        error = create_error;
2906                goto out;
2907        }
2908
2909        if (error) {    /* returned 1, that is */
2910                if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
2911                        error = -EIO;
2912                        goto out;
2913                }
2914                if (file->f_path.dentry) {
2915                        dput(dentry);
2916                        dentry = file->f_path.dentry;
2917                }
2918                if (*opened & FILE_CREATED)
2919                        fsnotify_create(dir, dentry);
2920                if (!dentry->d_inode) {
2921                        WARN_ON(*opened & FILE_CREATED);
2922                        if (create_error) {
2923                                error = create_error;
2924                                goto out;
2925                        }
2926                } else {
2927                        if (excl && !(*opened & FILE_CREATED)) {
2928                                error = -EEXIST;
2929                                goto out;
2930                        }
2931                }
2932                goto looked_up;
2933        }
2934
2935        /*
2936         * We didn't have the inode before the open, so check open permission
2937         * here.
2938         */
2939        acc_mode = op->acc_mode;
2940        if (*opened & FILE_CREATED) {
2941                WARN_ON(!(open_flag & O_CREAT));
2942                fsnotify_create(dir, dentry);
2943                acc_mode = 0;
2944        }
2945        error = may_open(&file->f_path, acc_mode, open_flag);
2946        if (error)
2947                fput(file);
2948
2949out:
2950        dput(dentry);
2951        return error;
2952
2953no_open:
2954        if (need_lookup) {
2955                dentry = lookup_real(dir, dentry, nd->flags);
2956                if (IS_ERR(dentry))
2957                        return PTR_ERR(dentry);
2958        }
2959        if (create_error && !dentry->d_inode) {
2960                error = create_error;
2961                goto out;
2962        }
2963looked_up:
2964        path->dentry = dentry;
2965        path->mnt = nd->path.mnt;
2966        return 1;
2967}
2968
2969/*
2970 * Look up and maybe create and open the last component.
2971 *
2972 * Must be called with i_mutex held on parent.
2973 *
2974 * Returns 0 if the file was successfully atomically created (if necessary) and
2975 * opened.  In this case the file will be returned attached to @file.
2976 *
2977 * Returns 1 if the file was not completely opened at this time, though lookups
2978 * and creations will have been performed and the dentry returned in @path will
2979 * be positive upon return if O_CREAT was specified.  If O_CREAT wasn't
2980 * specified then a negative dentry may be returned.
2981 *
2982 * An error code is returned otherwise.
2983 *
2984 * FILE_CREATE will be set in @*opened if the dentry was created and will be
2985 * cleared otherwise prior to returning.
2986 */
2987static int lookup_open(struct nameidata *nd, struct path *path,
2988                        struct file *file,
2989                        const struct open_flags *op,
2990                        bool got_write, int *opened)
2991{
2992        struct dentry *dir = nd->path.dentry;
2993        struct inode *dir_inode = dir->d_inode;
2994        struct dentry *dentry;
2995        int error;
2996        bool need_lookup;
2997
2998        *opened &= ~FILE_CREATED;
2999        dentry = lookup_dcache(&nd->last, dir, nd->flags, &need_lookup);
3000        if (IS_ERR(dentry))
3001                return PTR_ERR(dentry);
3002
3003        /* Cached positive dentry: will open in f_op->open */
3004        if (!need_lookup && dentry->d_inode)
3005                goto out_no_open;
3006
3007        if ((nd->flags & LOOKUP_OPEN) && dir_inode->i_op->atomic_open) {
3008                return atomic_open(nd, dentry, path, file, op, got_write,
3009                                   need_lookup, opened);
3010        }
3011
3012        if (need_lookup) {
3013                BUG_ON(dentry->d_inode);
3014
3015                dentry = lookup_real(dir_inode, dentry, nd->flags);
3016                if (IS_ERR(dentry))
3017                        return PTR_ERR(dentry);
3018        }
3019
3020        /* Negative dentry, just create the file */
3021        if (!dentry->d_inode && (op->open_flag & O_CREAT)) {
3022                umode_t mode = op->mode;
3023                if (!IS_POSIXACL(dir->d_inode))
3024                        mode &= ~current_umask();
3025                /*
3026                 * This write is needed to ensure that a
3027                 * rw->ro transition does not occur between
3028                 * the time when the file is created and when
3029                 * a permanent write count is taken through
3030                 * the 'struct file' in finish_open().
3031                 */
3032                if (!got_write) {
3033                        error = -EROFS;
3034                        goto out_dput;
3035                }
3036                *opened |= FILE_CREATED;
3037                error = security_path_mknod(&nd->path, dentry, mode, 0);
3038                if (error)
3039                        goto out_dput;
3040                error = vfs_create(dir->d_inode, dentry, mode,
3041                                   nd->flags & LOOKUP_EXCL);
3042                if (error)
3043                        goto out_dput;
3044        }
3045out_no_open:
3046        path->dentry = dentry;
3047        path->mnt = nd->path.mnt;
3048        return 1;
3049
3050out_dput:
3051        dput(dentry);
3052        return error;
3053}
3054
3055/*
3056 * Handle the last step of open()
3057 */
3058static int do_last(struct nameidata *nd, struct path *path,
3059                   struct file *file, const struct open_flags *op,
3060                   int *opened, struct filename *name)
3061{
3062        struct dentry *dir = nd->path.dentry;
3063        int open_flag = op->open_flag;
3064        bool will_truncate = (open_flag & O_TRUNC) != 0;
3065        bool got_write = false;
3066        int acc_mode = op->acc_mode;
3067        struct inode *inode;
3068        bool symlink_ok = false;
3069        struct path save_parent = { .dentry = NULL, .mnt = NULL };
3070        bool retried = false;
3071        int error;
3072
3073        nd->flags &= ~LOOKUP_PARENT;
3074        nd->flags |= op->intent;
3075
3076        switch (nd->last_type) {
3077        case LAST_DOTDOT:
3078        case LAST_DOT:
3079                error = handle_dots(nd, nd->last_type);
3080                if (error)
3081                        return error;
3082                /* fallthrough */
3083        case LAST_ROOT:
3084                error = complete_walk(nd);
3085                if (error)
3086                        return error;
3087                audit_inode(name, nd->path.dentry, 0);
3088                if (open_flag & O_CREAT) {
3089                        error = -EISDIR;
3090                        goto out;
3091                }
3092                goto finish_open;
3093        case LAST_BIND:
3094                error = complete_walk(nd);
3095                if (error)
3096                        return error;
3097                audit_inode(name, dir, 0);
3098                goto finish_open;
3099        }
3100
3101        if (!(open_flag & O_CREAT)) {
3102                if (nd->last.name[nd->last.len])
3103                        nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3104                if (open_flag & O_PATH && !(nd->flags & LOOKUP_FOLLOW))
3105                        symlink_ok = true;
3106                /* we _can_ be in RCU mode here */
3107                error = lookup_fast(nd, path, &inode);
3108                if (likely(!error))
3109                        goto finish_lookup;
3110
3111                if (error < 0)
3112                        goto out;
3113
3114                BUG_ON(nd->inode != dir->d_inode);
3115        } else {
3116                /* create side of things */
3117                /*
3118                 * This will *only* deal with leaving RCU mode - LOOKUP_JUMPED
3119                 * has been cleared when we got to the last component we are
3120                 * about to look up
3121                 */
3122                error = complete_walk(nd);
3123                if (error)
3124                        return error;
3125
3126                audit_inode(name, dir, LOOKUP_PARENT);
3127                error = -EISDIR;
3128                /* trailing slashes? */
3129                if (nd->last.name[nd->last.len])
3130                        goto out;
3131        }
3132
3133retry_lookup:
3134        if (op->open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3135                error = mnt_want_write(nd->path.mnt);
3136                if (!error)
3137                        got_write = true;
3138                /*
3139                 * do _not_ fail yet - we might not need that or fail with
3140                 * a different error; let lookup_open() decide; we'll be
3141                 * dropping this one anyway.
3142                 */
3143        }
3144        mutex_lock(&dir->d_inode->i_mutex);
3145        error = lookup_open(nd, path, file, op, got_write, opened);
3146        mutex_unlock(&dir->d_inode->i_mutex);
3147
3148        if (error <= 0) {
3149                if (error)
3150                        goto out;
3151
3152                if ((*opened & FILE_CREATED) ||
3153                    !S_ISREG(file_inode(file)->i_mode))
3154                        will_truncate = false;
3155
3156                audit_inode(name, file->f_path.dentry, 0);
3157                goto opened;
3158        }
3159
3160        if (*opened & FILE_CREATED) {
3161                /* Don't check for write permission, don't truncate */
3162                open_flag &= ~O_TRUNC;
3163                will_truncate = false;
3164                acc_mode = 0;
3165                path_to_nameidata(path, nd);
3166                goto finish_open_created;
3167        }
3168
3169        /*
3170         * create/update audit record if it already exists.
3171         */
3172        if (d_is_positive(path->dentry))
3173                audit_inode(name, path->dentry, 0);
3174
3175        /*
3176         * If atomic_open() acquired write access it is dropped now due to
3177         * possible mount and symlink following (this might be optimized away if
3178         * necessary...)
3179         */
3180        if (got_write) {
3181                mnt_drop_write(nd->path.mnt);
3182                got_write = false;
3183        }
3184
3185        error = -EEXIST;
3186        if ((open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT))
3187                goto exit_dput;
3188
3189        error = follow_managed(path, nd->flags);
3190        if (error < 0)
3191                goto exit_dput;
3192
3193        if (error)
3194                nd->flags |= LOOKUP_JUMPED;
3195
3196        BUG_ON(nd->flags & LOOKUP_RCU);
3197        inode = path->dentry->d_inode;
3198finish_lookup:
3199        /* we _can_ be in RCU mode here */
3200        error = -ENOENT;
3201        if (!inode || d_is_negative(path->dentry)) {
3202                path_to_nameidata(path, nd);
3203                goto out;
3204        }
3205
3206        if (should_follow_link(path->dentry, !symlink_ok)) {
3207                if (nd->flags & LOOKUP_RCU) {
3208                        if (unlikely(unlazy_walk(nd, path->dentry))) {
3209                                error = -ECHILD;
3210                                goto out;
3211                        }
3212                }
3213                BUG_ON(inode != path->dentry->d_inode);
3214                return 1;
3215        }
3216
3217        if ((nd->flags & LOOKUP_RCU) || nd->path.mnt != path->mnt) {
3218                path_to_nameidata(path, nd);
3219        } else {
3220                save_parent.dentry = nd->path.dentry;
3221                save_parent.mnt = mntget(path->mnt);
3222                nd->path.dentry = path->dentry;
3223
3224        }
3225        nd->inode = inode;
3226        /* Why this, you ask?  _Now_ we might have grown LOOKUP_JUMPED... */
3227        error = complete_walk(nd);
3228        if (error) {
3229                path_put(&save_parent);
3230                return error;
3231        }
3232        error = -EISDIR;
3233        if ((open_flag & O_CREAT) && d_is_dir(nd->path.dentry))
3234                goto out;
3235        error = -ENOTDIR;
3236        if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3237                goto out;
3238        audit_inode(name, nd->path.dentry, 0);
3239finish_open:
3240        if (!S_ISREG(nd->inode->i_mode))
3241                will_truncate = false;
3242
3243        if (will_truncate) {
3244                error = mnt_want_write(nd->path.mnt);
3245                if (error)
3246                        goto out;
3247                got_write = true;
3248        }
3249finish_open_created:
3250        if (likely(!(open_flag & O_PATH))) {
3251                error = may_open(&nd->path, acc_mode, open_flag);
3252                if (error)
3253                        goto out;
3254        }
3255        BUG_ON(*opened & FILE_OPENED); /* once it's opened, it's opened */
3256        error = vfs_open(&nd->path, file, current_cred());
3257        if (!error) {
3258                *opened |= FILE_OPENED;
3259        } else {
3260                if (error == -EOPENSTALE)
3261                        goto stale_open;
3262                goto out;
3263        }
3264opened:
3265        error = open_check_o_direct(file);
3266        if (error)
3267                goto exit_fput;
3268        error = ima_file_check(file, op->acc_mode);
3269        if (error)
3270                goto exit_fput;
3271
3272        if (will_truncate) {
3273                error = handle_truncate(file);
3274                if (error)
3275                        goto exit_fput;
3276        }
3277out:
3278        if (got_write)
3279                mnt_drop_write(nd->path.mnt);
3280        path_put(&save_parent);
3281        terminate_walk(nd);
3282        return error;
3283
3284exit_dput:
3285        path_put_conditional(path, nd);
3286        goto out;
3287exit_fput:
3288        fput(file);
3289        goto out;
3290
3291stale_open:
3292        /* If no saved parent or already retried then can't retry */
3293        if (!save_parent.dentry || retried)
3294                goto out;
3295
3296        BUG_ON(save_parent.dentry != dir);
3297        path_put(&nd->path);
3298        nd->path = save_parent;
3299        nd->inode = dir->d_inode;
3300        save_parent.mnt = NULL;
3301        save_parent.dentry = NULL;
3302        if (got_write) {
3303                mnt_drop_write(nd->path.mnt);
3304                got_write = false;
3305        }
3306        retried = true;
3307        goto retry_lookup;
3308}
3309
3310struct dentry *vfs_tmpfile(struct dentry *dentry, umode_t mode, int open_flag)
3311{
3312        static const struct qstr name = QSTR_INIT("/", 1);
3313        struct dentry *child = NULL;
3314        iop_tmpfile_t tmpfile;
3315        struct inode *dir = dentry->d_inode;
3316        struct inode *inode;
3317        int error;
3318
3319        /* we want directory to be writable */
3320        error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
3321        if (error)
3322                goto out_err;
3323        error = -EOPNOTSUPP;
3324        tmpfile = get_tmpfile_iop(dir);
3325        if (!tmpfile)
3326                goto out_err;
3327        error = -ENOMEM;
3328        child = d_alloc(dentry, &name);
3329        if (unlikely(!child))
3330                goto out_err;
3331        error = tmpfile(dir, child, mode);
3332        if (error)
3333                goto out_err;
3334        error = -ENOENT;
3335        inode = child->d_inode;
3336        if (unlikely(!inode))
3337                goto out_err;
3338        if (!(open_flag & O_EXCL)) {
3339                spin_lock(&inode->i_lock);
3340                inode->i_state |= I_LINKABLE;
3341                spin_unlock(&inode->i_lock);
3342        }
3343        return child;
3344
3345out_err:
3346        dput(child);
3347        return ERR_PTR(error);
3348}
3349EXPORT_SYMBOL(vfs_tmpfile);
3350
3351static int do_tmpfile(int dfd, struct filename *pathname,
3352                struct nameidata *nd, int flags,
3353                const struct open_flags *op,
3354                struct file *file, int *opened)
3355{
3356        struct dentry *child;
3357        int error = path_lookupat(dfd, pathname->name,
3358                                  flags | LOOKUP_DIRECTORY, nd);
3359        if (unlikely(error))
3360                return error;
3361        error = mnt_want_write(nd->path.mnt);
3362        if (unlikely(error))
3363                goto out;
3364        child = vfs_tmpfile(nd->path.dentry, op->mode, op->open_flag);
3365        error = PTR_ERR(child);
3366        if (unlikely(IS_ERR(child)))
3367                goto out2;
3368        nd->flags &= ~LOOKUP_DIRECTORY;
3369        nd->flags |= op->intent;
3370        dput(nd->path.dentry);
3371        nd->path.dentry = child;
3372        audit_inode(pathname, nd->path.dentry, 0);
3373        /* Don't check for other permissions, the inode was just created */
3374        error = may_open(&nd->path, 0, op->open_flag);
3375        if (error)
3376                goto out2;
3377        file->f_path.mnt = nd->path.mnt;
3378        error = finish_open(file, nd->path.dentry, NULL, opened);
3379        if (error)
3380                goto out2;
3381        error = open_check_o_direct(file);
3382        if (error)
3383                fput(file);
3384out2:
3385        mnt_drop_write(nd->path.mnt);
3386out:
3387        path_put(&nd->path);
3388        return error;
3389}
3390
3391static struct file *path_openat(int dfd, struct filename *pathname,
3392                struct nameidata *nd, const struct open_flags *op, int flags)
3393{
3394        struct file *base = NULL;
3395        struct file *file;
3396        struct path path;
3397        int opened = 0;
3398        int error;
3399
3400        file = get_empty_filp();
3401        if (IS_ERR(file))
3402                return file;
3403
3404        file->f_flags = op->open_flag;
3405
3406        if (unlikely(file->f_flags & __O_TMPFILE)) {
3407                error = do_tmpfile(dfd, pathname, nd, flags, op, file, &opened);
3408                goto out2;
3409        }
3410
3411        error = path_init(dfd, pathname->name, flags | LOOKUP_PARENT, nd, &base);
3412        if (unlikely(error))
3413                goto out;
3414
3415        current->total_link_count = 0;
3416        error = link_path_walk(pathname->name, nd);
3417        if (unlikely(error))
3418                goto out;
3419
3420        error = do_last(nd, &path, file, op, &opened, pathname);
3421        while (unlikely(error > 0)) { /* trailing symlink */
3422                struct path link = path;
3423                void *cookie;
3424                if (!(nd->flags & LOOKUP_FOLLOW)) {
3425                        path_put_conditional(&path, nd);
3426                        path_put(&nd->path);
3427                        error = -ELOOP;
3428                        break;
3429                }
3430                error = may_follow_link(&link, nd);
3431                if (unlikely(error))
3432                        break;
3433                nd->flags |= LOOKUP_PARENT;
3434                nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3435                error = follow_link(&link, nd, &cookie);
3436                if (unlikely(error))
3437                        break;
3438                error = do_last(nd, &path, file, op, &opened, pathname);
3439                put_link(nd, &link, cookie);
3440        }
3441out:
3442        if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT))
3443                path_put(&nd->root);
3444        if (base)
3445                fput(base);
3446out2:
3447        if (!(opened & FILE_OPENED)) {
3448                BUG_ON(!error);
3449                put_filp(file);
3450        }
3451        if (unlikely(error)) {
3452                if (error == -EOPENSTALE) {
3453                        if (flags & LOOKUP_RCU)
3454                                error = -ECHILD;
3455                        else
3456                                error = -ESTALE;
3457                }
3458                file = ERR_PTR(error);
3459        }
3460        return file;
3461}
3462
3463struct file *do_filp_open(int dfd, struct filename *pathname,
3464                const struct open_flags *op)
3465{
3466        struct nameidata nd;
3467        int flags = op->lookup_flags;
3468        struct file *filp;
3469
3470        filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_RCU);
3471        if (unlikely(filp == ERR_PTR(-ECHILD)))
3472                filp = path_openat(dfd, pathname, &nd, op, flags);
3473        if (unlikely(filp == ERR_PTR(-ESTALE)))
3474                filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_REVAL);
3475        return filp;
3476}
3477
3478struct file *do_file_open_root(struct dentry *dentry, struct vfsmount *mnt,
3479                const char *name, const struct open_flags *op)
3480{
3481        struct nameidata nd;
3482        struct file *file;
3483        struct filename *filename;
3484        int flags = op->lookup_flags | LOOKUP_ROOT;
3485
3486        nd.root.mnt = mnt;
3487        nd.root.dentry = dentry;
3488
3489        if (d_is_symlink(dentry) && op->intent & LOOKUP_OPEN)
3490                return ERR_PTR(-ELOOP);
3491
3492        filename = getname_kernel(name);
3493        if (unlikely(IS_ERR(filename)))
3494                return ERR_CAST(filename);
3495
3496        file = path_openat(-1, filename, &nd, op, flags | LOOKUP_RCU);
3497        if (unlikely(file == ERR_PTR(-ECHILD)))
3498                file = path_openat(-1, filename, &nd, op, flags);
3499        if (unlikely(file == ERR_PTR(-ESTALE)))
3500                file = path_openat(-1, filename, &nd, op, flags | LOOKUP_REVAL);
3501        putname(filename);
3502        return file;
3503}
3504
3505static struct dentry *filename_create(int dfd, struct filename *name,
3506                                struct path *path, unsigned int lookup_flags)
3507{
3508        struct dentry *dentry = ERR_PTR(-EEXIST);
3509        struct nameidata nd;
3510        int err2;
3511        int error;
3512        bool is_dir = (lookup_flags & LOOKUP_DIRECTORY);
3513
3514        /*
3515         * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any
3516         * other flags passed in are ignored!
3517         */
3518        lookup_flags &= LOOKUP_REVAL;
3519
3520        error = filename_lookup(dfd, name, LOOKUP_PARENT|lookup_flags, &nd);
3521        if (error)
3522                return ERR_PTR(error);
3523
3524        /*
3525         * Yucky last component or no last component at all?
3526         * (foo/., foo/.., /////)
3527         */
3528        if (nd.last_type != LAST_NORM)
3529                goto out;
3530        nd.flags &= ~LOOKUP_PARENT;
3531        nd.flags |= LOOKUP_CREATE | LOOKUP_EXCL;
3532
3533        /* don't fail immediately if it's r/o, at least try to report other errors */
3534        err2 = mnt_want_write(nd.path.mnt);
3535        /*
3536         * Do the final lookup.
3537         */
3538        mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
3539        dentry = lookup_hash(&nd);
3540        if (IS_ERR(dentry))
3541                goto unlock;
3542
3543        error = -EEXIST;
3544        if (d_is_positive(dentry))
3545                goto fail;
3546
3547        /*
3548         * Special case - lookup gave negative, but... we had foo/bar/
3549         * From the vfs_mknod() POV we just have a negative dentry -
3550         * all is fine. Let's be bastards - you had / on the end, you've
3551         * been asking for (non-existent) directory. -ENOENT for you.
3552         */
3553        if (unlikely(!is_dir && nd.last.name[nd.last.len])) {
3554                error = -ENOENT;
3555                goto fail;
3556        }
3557        if (unlikely(err2)) {
3558                error = err2;
3559                goto fail;
3560        }
3561        *path = nd.path;
3562        return dentry;
3563fail:
3564        dput(dentry);
3565        dentry = ERR_PTR(error);
3566unlock:
3567        mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
3568        if (!err2)
3569                mnt_drop_write(nd.path.mnt);
3570out:
3571        path_put(&nd.path);
3572        return dentry;
3573}
3574
3575struct dentry *kern_path_create(int dfd, const char *pathname,
3576                                struct path *path, unsigned int lookup_flags)
3577{
3578        struct filename *filename = getname_kernel(pathname);
3579        struct dentry *res;
3580
3581        if (IS_ERR(filename))
3582                return ERR_CAST(filename);
3583        res = filename_create(dfd, filename, path, lookup_flags);
3584        putname(filename);
3585        return res;
3586}
3587EXPORT_SYMBOL(kern_path_create);
3588
3589void done_path_create(struct path *path, struct dentry *dentry)
3590{
3591        dput(dentry);
3592        mutex_unlock(&path->dentry->d_inode->i_mutex);
3593        mnt_drop_write(path->mnt);
3594        path_put(path);
3595}
3596EXPORT_SYMBOL(done_path_create);
3597
3598struct dentry *user_path_create(int dfd, const char __user *pathname,
3599                                struct path *path, unsigned int lookup_flags)
3600{
3601        struct filename *tmp = getname(pathname);
3602        struct dentry *res;
3603        if (IS_ERR(tmp))
3604                return ERR_CAST(tmp);
3605        res = filename_create(dfd, tmp, path, lookup_flags);
3606        putname(tmp);
3607        return res;
3608}
3609EXPORT_SYMBOL(user_path_create);
3610
3611int vfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3612{
3613        int error = may_create(dir, dentry);
3614
3615        if (error)
3616                return error;
3617
3618        if ((S_ISCHR(mode) || S_ISBLK(mode)) && !capable(CAP_MKNOD))
3619                return -EPERM;
3620
3621        if (!dir->i_op->mknod)
3622                return -EPERM;
3623
3624        error = devcgroup_inode_mknod(mode, dev);
3625        if (error)
3626                return error;
3627
3628        error = security_inode_mknod(dir, dentry, mode, dev);
3629        if (error)
3630                return error;
3631
3632        error = dir->i_op->mknod(dir, dentry, mode, dev);
3633        if (!error)
3634                fsnotify_create(dir, dentry);
3635        return error;
3636}
3637
3638static int may_mknod(umode_t mode)
3639{
3640        switch (mode & S_IFMT) {
3641        case S_IFREG:
3642        case S_IFCHR:
3643        case S_IFBLK:
3644        case S_IFIFO:
3645        case S_IFSOCK:
3646        case 0: /* zero mode translates to S_IFREG */
3647                return 0;
3648        case S_IFDIR:
3649                return -EPERM;
3650        default:
3651                return -EINVAL;
3652        }
3653}
3654
3655SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
3656                unsigned, dev)
3657{
3658        struct dentry *dentry;
3659        struct path path;
3660        int error;
3661        unsigned int lookup_flags = 0;
3662
3663        error = may_mknod(mode);
3664        if (error)
3665                return error;
3666retry:
3667        dentry = user_path_create(dfd, filename, &path, lookup_flags);
3668        if (IS_ERR(dentry))
3669                return PTR_ERR(dentry);
3670
3671        if (!IS_POSIXACL(path.dentry->d_inode))
3672                mode &= ~current_umask();
3673        error = security_path_mknod(&path, dentry, mode, dev);
3674        if (error)
3675                goto out;
3676        switch (mode & S_IFMT) {
3677                case 0: case S_IFREG:
3678                        error = vfs_create(path.dentry->d_inode,dentry,mode,true);
3679                        break;
3680                case S_IFCHR: case S_IFBLK:
3681                        error = vfs_mknod(path.dentry->d_inode,dentry,mode,
3682                                        new_decode_dev(dev));
3683                        break;
3684                case S_IFIFO: case S_IFSOCK:
3685                        error = vfs_mknod(path.dentry->d_inode,dentry,mode,0);
3686                        break;
3687        }
3688out:
3689        done_path_create(&path, dentry);
3690        if (retry_estale(error, lookup_flags)) {
3691                lookup_flags |= LOOKUP_REVAL;
3692                goto retry;
3693        }
3694        return error;
3695}
3696
3697SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
3698{
3699        return sys_mknodat(AT_FDCWD, filename, mode, dev);
3700}
3701
3702int vfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
3703{
3704        int error = may_create(dir, dentry);
3705        unsigned max_links = dir->i_sb->s_max_links;
3706
3707        if (error)
3708                return error;
3709
3710        if (!dir->i_op->mkdir)
3711                return -EPERM;
3712
3713        mode &= (S_IRWXUGO|S_ISVTX);
3714        error = security_inode_mkdir(dir, dentry, mode);
3715        if (error)
3716                return error;
3717
3718        if (max_links && dir->i_nlink >= max_links)
3719                return -EMLINK;
3720
3721        error = dir->i_op->mkdir(dir, dentry, mode);
3722        if (!error)
3723                fsnotify_mkdir(dir, dentry);
3724        return error;
3725}
3726
3727SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
3728{
3729        struct dentry *dentry;
3730        struct path path;
3731        int error;
3732        unsigned int lookup_flags = LOOKUP_DIRECTORY;
3733
3734retry:
3735        dentry = user_path_create(dfd, pathname, &path, lookup_flags);
3736        if (IS_ERR(dentry))
3737                return PTR_ERR(dentry);
3738
3739        if (!IS_POSIXACL(path.dentry->d_inode))
3740                mode &= ~current_umask();
3741        error = security_path_mkdir(&path, dentry, mode);
3742        if (!error)
3743                error = vfs_mkdir(path.dentry->d_inode, dentry, mode);
3744        done_path_create(&path, dentry);
3745        if (retry_estale(error, lookup_flags)) {
3746                lookup_flags |= LOOKUP_REVAL;
3747                goto retry;
3748        }
3749        return error;
3750}
3751
3752SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
3753{
3754        return sys_mkdirat(AT_FDCWD, pathname, mode);
3755}
3756
3757/*
3758 * The dentry_unhash() helper will try to drop the dentry early: we
3759 * should have a usage count of 1 if we're the only user of this
3760 * dentry, and if that is true (possibly after pruning the dcache),
3761 * then we drop the dentry now.
3762 *
3763 * A low-level filesystem can, if it choses, legally
3764 * do a
3765 *
3766 *      if (!d_unhashed(dentry))
3767 *              return -EBUSY;
3768 *
3769 * if it cannot handle the case of removing a directory
3770 * that is still in use by something else..
3771 */
3772void dentry_unhash(struct dentry *dentry)
3773{
3774        shrink_dcache_parent(dentry);
3775        spin_lock(&dentry->d_lock);
3776        if (dentry->d_lockref.count == 1)
3777                __d_drop(dentry);
3778        spin_unlock(&dentry->d_lock);
3779}
3780
3781int vfs_rmdir(struct inode *dir, struct dentry *dentry)
3782{
3783        int error = may_delete(dir, dentry, 1);
3784
3785        if (error)
3786                return error;
3787
3788        if (!dir->i_op->rmdir)
3789                return -EPERM;
3790
3791        dget(dentry);
3792        mutex_lock(&dentry->d_inode->i_mutex);
3793
3794        error = -EBUSY;
3795        if (is_local_mountpoint(dentry))
3796                goto out;
3797
3798        error = security_inode_rmdir(dir, dentry);
3799        if (error)
3800                goto out;
3801
3802        shrink_dcache_parent(dentry);
3803        error = dir->i_op->rmdir(dir, dentry);
3804        if (error)
3805                goto out;
3806
3807        dentry->d_inode->i_flags |= S_DEAD;
3808        dont_mount(dentry);
3809        detach_mounts(dentry);
3810
3811out:
3812        mutex_unlock(&dentry->d_inode->i_mutex);
3813        dput(dentry);
3814        if (!error)
3815                d_delete(dentry);
3816        return error;
3817}
3818
3819static long do_rmdir(int dfd, const char __user *pathname)
3820{
3821        int error = 0;
3822        struct filename *name;
3823        struct dentry *dentry;
3824        struct nameidata nd;
3825        unsigned int lookup_flags = 0;
3826retry:
3827        name = user_path_parent(dfd, pathname, &nd, lookup_flags);
3828        if (IS_ERR(name))
3829                return PTR_ERR(name);
3830
3831        switch(nd.last_type) {
3832        case LAST_DOTDOT:
3833                error = -ENOTEMPTY;
3834                goto exit1;
3835        case LAST_DOT:
3836                error = -EINVAL;
3837                goto exit1;
3838        case LAST_ROOT:
3839                error = -EBUSY;
3840                goto exit1;
3841        }
3842
3843        nd.flags &= ~LOOKUP_PARENT;
3844        error = mnt_want_write(nd.path.mnt);
3845        if (error)
3846                goto exit1;
3847
3848        mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
3849        dentry = lookup_hash(&nd);
3850        error = PTR_ERR(dentry);
3851        if (IS_ERR(dentry))
3852                goto exit2;
3853        if (!dentry->d_inode) {
3854                error = -ENOENT;
3855                goto exit3;
3856        }
3857        error = security_path_rmdir(&nd.path, dentry);
3858        if (error)
3859                goto exit3;
3860        error = vfs_rmdir(nd.path.dentry->d_inode, dentry);
3861exit3:
3862        dput(dentry);
3863exit2:
3864        mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
3865        mnt_drop_write(nd.path.mnt);
3866exit1:
3867        path_put(&nd.path);
3868        putname(name);
3869        if (retry_estale(error, lookup_flags)) {
3870                lookup_flags |= LOOKUP_REVAL;
3871                goto retry;
3872        }
3873        return error;
3874}
3875
3876SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
3877{
3878        return do_rmdir(AT_FDCWD, pathname);
3879}
3880
3881/**
3882 * vfs_unlink - unlink a filesystem object
3883 * @dir:        parent directory
3884 * @dentry:     victim
3885 * @delegated_inode: returns victim inode, if the inode is delegated.
3886 *
3887 * The caller must hold dir->i_mutex.
3888 *
3889 * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
3890 * return a reference to the inode in delegated_inode.  The caller
3891 * should then break the delegation on that inode and retry.  Because
3892 * breaking a delegation may take a long time, the caller should drop
3893 * dir->i_mutex before doing so.
3894 *
3895 * Alternatively, a caller may pass NULL for delegated_inode.  This may
3896 * be appropriate for callers that expect the underlying filesystem not
3897 * to be NFS exported.
3898 */
3899int vfs_unlink(struct inode *dir, struct dentry *dentry, struct inode **delegated_inode)
3900{
3901        struct inode *target = dentry->d_inode;
3902        int error = may_delete(dir, dentry, 0);
3903
3904        if (error)
3905                return error;
3906
3907        if (!dir->i_op->unlink)
3908                return -EPERM;
3909
3910        mutex_lock(&target->i_mutex);
3911        if (is_local_mountpoint(dentry))
3912                error = -EBUSY;
3913        else {
3914                error = security_inode_unlink(dir, dentry);
3915                if (!error) {
3916                        error = try_break_deleg(target, delegated_inode);
3917                        if (error)
3918                                goto out;
3919                        error = dir->i_op->unlink(dir, dentry);
3920                        if (!error) {
3921                                dont_mount(dentry);
3922                                detach_mounts(dentry);
3923                        }
3924                }
3925        }
3926out:
3927        mutex_unlock(&target->i_mutex);
3928
3929        /* We don't d_delete() NFS sillyrenamed files--they still exist. */
3930        if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) {
3931                fsnotify_link_count(target);
3932                d_delete(dentry);
3933        }
3934
3935        return error;
3936}
3937
3938/*
3939 * Make sure that the actual truncation of the file will occur outside its
3940 * directory's i_mutex.  Truncate can take a long time if there is a lot of
3941 * writeout happening, and we don't want to prevent access to the directory
3942 * while waiting on the I/O.
3943 */
3944static long do_unlinkat(int dfd, const char __user *pathname)
3945{
3946        int error;
3947        struct filename *name;
3948        struct dentry *dentry;
3949        struct nameidata nd;
3950        struct inode *inode = NULL;
3951        struct inode *delegated_inode = NULL;
3952        unsigned int lookup_flags = 0;
3953retry:
3954        name = user_path_parent(dfd, pathname, &nd, lookup_flags);
3955        if (IS_ERR(name))
3956                return PTR_ERR(name);
3957
3958        error = -EISDIR;
3959        if (nd.last_type != LAST_NORM)
3960                goto exit1;
3961
3962        nd.flags &= ~LOOKUP_PARENT;
3963        error = mnt_want_write(nd.path.mnt);
3964        if (error)
3965                goto exit1;
3966retry_deleg:
3967        mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
3968        dentry = lookup_hash(&nd);
3969        error = PTR_ERR(dentry);
3970        if (!IS_ERR(dentry)) {
3971                /* Why not before? Because we want correct error value */
3972                if (nd.last.name[nd.last.len])
3973                        goto slashes;
3974                inode = dentry->d_inode;
3975                if (d_is_negative(dentry))
3976                        goto slashes;
3977                ihold(inode);
3978                error = security_path_unlink(&nd.path, dentry);
3979                if (error)
3980                        goto exit2;
3981                error = vfs_unlink(nd.path.dentry->d_inode, dentry, &delegated_inode);
3982exit2:
3983                dput(dentry);
3984        }
3985        mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
3986        if (inode)
3987                iput(inode);    /* truncate the inode here */
3988        inode = NULL;
3989        if (delegated_inode) {
3990                error = break_deleg_wait(&delegated_inode);
3991                if (!error)
3992                        goto retry_deleg;
3993        }
3994        mnt_drop_write(nd.path.mnt);
3995exit1:
3996        path_put(&nd.path);
3997        putname(name);
3998        if (retry_estale(error, lookup_flags)) {
3999                lookup_flags |= LOOKUP_REVAL;
4000                inode = NULL;
4001                goto retry;
4002        }
4003        return error;
4004
4005slashes:
4006        if (d_is_negative(dentry))
4007                error = -ENOENT;
4008        else if (d_is_dir(dentry))
4009                error = -EISDIR;
4010        else
4011                error = -ENOTDIR;
4012        goto exit2;
4013}
4014
4015SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
4016{
4017        if ((flag & ~AT_REMOVEDIR) != 0)
4018                return -EINVAL;
4019
4020        if (flag & AT_REMOVEDIR)
4021                return do_rmdir(dfd, pathname);
4022
4023        return do_unlinkat(dfd, pathname);
4024}
4025
4026SYSCALL_DEFINE1(unlink, const char __user *, pathname)
4027{
4028        return do_unlinkat(AT_FDCWD, pathname);
4029}
4030
4031int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname)
4032{
4033        int error = may_create(dir, dentry);
4034
4035        if (error)
4036                return error;
4037
4038        if (!dir->i_op->symlink)
4039                return -EPERM;
4040
4041        error = security_inode_symlink(dir, dentry, oldname);
4042        if (error)
4043                return error;
4044
4045        error = dir->i_op->symlink(dir, dentry, oldname);
4046        if (!error)
4047                fsnotify_create(dir, dentry);
4048        return error;
4049}
4050
4051SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4052                int, newdfd, const char __user *, newname)
4053{
4054        int error;
4055        struct filename *from;
4056        struct dentry *dentry;
4057        struct path path;
4058        unsigned int lookup_flags = 0;
4059
4060        from = getname(oldname);
4061        if (IS_ERR(from))
4062                return PTR_ERR(from);
4063retry:
4064        dentry = user_path_create(newdfd, newname, &path, lookup_flags);
4065        error = PTR_ERR(dentry);
4066        if (IS_ERR(dentry))
4067                goto out_putname;
4068
4069        error = security_path_symlink(&path, dentry, from->name);
4070        if (!error)
4071                error = vfs_symlink(path.dentry->d_inode, dentry, from->name);
4072        done_path_create(&path, dentry);
4073        if (retry_estale(error, lookup_flags)) {
4074                lookup_flags |= LOOKUP_REVAL;
4075                goto retry;
4076        }
4077out_putname:
4078        putname(from);
4079        return error;
4080}
4081
4082SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
4083{
4084        return sys_symlinkat(oldname, AT_FDCWD, newname);
4085}
4086
4087/**
4088 * vfs_link - create a new link
4089 * @old_dentry: object to be linked
4090 * @dir:        new parent
4091 * @new_dentry: where to create the new link
4092 * @delegated_inode: returns inode needing a delegation break
4093 *
4094 * The caller must hold dir->i_mutex
4095 *
4096 * If vfs_link discovers a delegation on the to-be-linked file in need
4097 * of breaking, it will return -EWOULDBLOCK and return a reference to the
4098 * inode in delegated_inode.  The caller should then break the delegation
4099 * and retry.  Because breaking a delegation may take a long time, the
4100 * caller should drop the i_mutex before doing so.
4101 *
4102 * Alternatively, a caller may pass NULL for delegated_inode.  This may
4103 * be appropriate for callers that expect the underlying filesystem not
4104 * to be NFS exported.
4105 */
4106int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry, struct inode **delegated_inode)
4107{
4108        struct inode *inode = old_dentry->d_inode;
4109        unsigned max_links = dir->i_sb->s_max_links;
4110        int error;
4111
4112        if (!inode)
4113                return -ENOENT;
4114
4115        error = may_create(dir, new_dentry);
4116        if (error)
4117                return error;
4118
4119        if (dir->i_sb != inode->i_sb)
4120                return -EXDEV;
4121
4122        /*
4123         * A link to an append-only or immutable file cannot be created.
4124         */
4125        if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4126                return -EPERM;
4127        /*
4128         * Updating the link count will likely cause i_uid and i_gid to
4129         * be writen back improperly if their true value is unknown to
4130         * the vfs.
4131         */
4132        if (HAS_UNMAPPED_ID(inode))
4133                return -EPERM;
4134        if (!dir->i_op->link)
4135                return -EPERM;
4136        if (S_ISDIR(inode->i_mode))
4137                return -EPERM;
4138
4139        error = security_inode_link(old_dentry, dir, new_dentry);
4140        if (error)
4141                return error;
4142
4143        mutex_lock(&inode->i_mutex);
4144        /* Make sure we don't allow creating hardlink to an unlinked file */
4145        if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4146                error =  -ENOENT;
4147        else if (max_links && inode->i_nlink >= max_links)
4148                error = -EMLINK;
4149        else {
4150                error = try_break_deleg(inode, delegated_inode);
4151                if (!error)
4152                        error = dir->i_op->link(old_dentry, dir, new_dentry);
4153        }
4154
4155        if (!error && (inode->i_state & I_LINKABLE)) {
4156                spin_lock(&inode->i_lock);
4157                inode->i_state &= ~I_LINKABLE;
4158                spin_unlock(&inode->i_lock);
4159        }
4160        mutex_unlock(&inode->i_mutex);
4161        if (!error)
4162                fsnotify_link(dir, inode, new_dentry);
4163        return error;
4164}
4165
4166/*
4167 * Hardlinks are often used in delicate situations.  We avoid
4168 * security-related surprises by not following symlinks on the
4169 * newname.  --KAB
4170 *
4171 * We don't follow them on the oldname either to be compatible
4172 * with linux 2.0, and to avoid hard-linking to directories
4173 * and other special files.  --ADM
4174 */
4175SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
4176                int, newdfd, const char __user *, newname, int, flags)
4177{
4178        struct dentry *new_dentry;
4179        struct path old_path, new_path;
4180        struct inode *delegated_inode = NULL;
4181        int how = 0;
4182        int error;
4183
4184        if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0)
4185                return -EINVAL;
4186        /*
4187         * To use null names we require CAP_DAC_READ_SEARCH
4188         * This ensures that not everyone will be able to create
4189         * handlink using the passed filedescriptor.
4190         */
4191        if (flags & AT_EMPTY_PATH) {
4192                if (!capable(CAP_DAC_READ_SEARCH))
4193                        return -ENOENT;
4194                how = LOOKUP_EMPTY;
4195        }
4196
4197        if (flags & AT_SYMLINK_FOLLOW)
4198                how |= LOOKUP_FOLLOW;
4199retry:
4200        error = user_path_at(olddfd, oldname, how, &old_path);
4201        if (error)
4202                return error;
4203
4204        new_dentry = user_path_create(newdfd, newname, &new_path,
4205                                        (how & LOOKUP_REVAL));
4206        error = PTR_ERR(new_dentry);
4207        if (IS_ERR(new_dentry))
4208                goto out;
4209
4210        error = -EXDEV;
4211        if (old_path.mnt != new_path.mnt)
4212                goto out_dput;
4213        error = may_linkat(&old_path);
4214        if (unlikely(error))
4215                goto out_dput;
4216        error = security_path_link(old_path.dentry, &new_path, new_dentry);
4217        if (error)
4218                goto out_dput;
4219        error = vfs_link(old_path.dentry, new_path.dentry->d_inode, new_dentry, &delegated_inode);
4220out_dput:
4221        done_path_create(&new_path, new_dentry);
4222        if (delegated_inode) {
4223                error = break_deleg_wait(&delegated_inode);
4224                if (!error) {
4225                        path_put(&old_path);
4226                        goto retry;
4227                }
4228        }
4229        if (retry_estale(error, how)) {
4230                path_put(&old_path);
4231                how |= LOOKUP_REVAL;
4232                goto retry;
4233        }
4234out:
4235        path_put(&old_path);
4236
4237        return error;
4238}
4239
4240SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
4241{
4242        return sys_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
4243}
4244
4245/**
4246 * vfs_rename - rename a filesystem object
4247 * @old_dir:    parent of source
4248 * @old_dentry: source
4249 * @new_dir:    parent of destination
4250 * @new_dentry: destination
4251 * @delegated_inode: returns an inode needing a delegation break
4252 * @flags:      rename flags
4253 *
4254 * The caller must hold multiple mutexes--see lock_rename()).
4255 *
4256 * If vfs_rename discovers a delegation in need of breaking at either
4257 * the source or destination, it will return -EWOULDBLOCK and return a
4258 * reference to the inode in delegated_inode.  The caller should then
4259 * break the delegation and retry.  Because breaking a delegation may
4260 * take a long time, the caller should drop all locks before doing
4261 * so.
4262 *
4263 * Alternatively, a caller may pass NULL for delegated_inode.  This may
4264 * be appropriate for callers that expect the underlying filesystem not
4265 * to be NFS exported.
4266 *
4267 * The worst of all namespace operations - renaming directory. "Perverted"
4268 * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
4269 * Problems:
4270 *      a) we can get into loop creation.
4271 *      b) race potential - two innocent renames can create a loop together.
4272 *         That's where 4.4 screws up. Current fix: serialization on
4273 *         sb->s_vfs_rename_mutex. We might be more accurate, but that's another
4274 *         story.
4275 *      c) we have to lock _four_ objects - parents and victim (if it exists),
4276 *         and source (if it is not a directory).
4277 *         And that - after we got ->i_mutex on parents (until then we don't know
4278 *         whether the target exists).  Solution: try to be smart with locking
4279 *         order for inodes.  We rely on the fact that tree topology may change
4280 *         only under ->s_vfs_rename_mutex _and_ that parent of the object we
4281 *         move will be locked.  Thus we can rank directories by the tree
4282 *         (ancestors first) and rank all non-directories after them.
4283 *         That works since everybody except rename does "lock parent, lookup,
4284 *         lock child" and rename is under ->s_vfs_rename_mutex.
4285 *         HOWEVER, it relies on the assumption that any object with ->lookup()
4286 *         has no more than 1 dentry.  If "hybrid" objects will ever appear,
4287 *         we'd better make sure that there's no link(2) for them.
4288 *      d) conversion from fhandle to dentry may come in the wrong moment - when
4289 *         we are removing the target. Solution: we will have to grab ->i_mutex
4290 *         in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4291 *         ->i_mutex on parents, which works but leads to some truly excessive
4292 *         locking].
4293 */
4294int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
4295               struct inode *new_dir, struct dentry *new_dentry,
4296               struct inode **delegated_inode, unsigned int flags)
4297{
4298        int error;
4299        bool is_dir = d_is_dir(old_dentry);
4300        struct inode *source = old_dentry->d_inode;
4301        struct inode *target = new_dentry->d_inode;
4302        bool new_is_dir = false;
4303        unsigned max_links = new_dir->i_sb->s_max_links;
4304        struct name_snapshot old_name;
4305        iop_rename2_t rename2;
4306
4307        if (source == target)
4308                return 0;
4309
4310        error = may_delete(old_dir, old_dentry, is_dir);
4311        if (error)
4312                return error;
4313
4314        if (!target) {
4315                error = may_create(new_dir, new_dentry);
4316        } else {
4317                new_is_dir = d_is_dir(new_dentry);
4318
4319                if (!(flags & RENAME_EXCHANGE))
4320                        error = may_delete(new_dir, new_dentry, is_dir);
4321                else
4322                        error = may_delete(new_dir, new_dentry, new_is_dir);
4323        }
4324        if (error)
4325                return error;
4326
4327        rename2 = get_rename2_iop(old_dir);
4328        if (!old_dir->i_op->rename && !rename2)
4329                return -EPERM;
4330
4331        if (flags && !rename2)
4332                return -EINVAL;
4333
4334        /*
4335         * If we are going to change the parent - check write permissions,
4336         * we'll need to flip '..'.
4337         */
4338        if (new_dir != old_dir) {
4339                if (is_dir) {
4340                        error = inode_permission(source, MAY_WRITE);
4341                        if (error)
4342                                return error;
4343                }
4344                if ((flags & RENAME_EXCHANGE) && new_is_dir) {
4345                        error = inode_permission(target, MAY_WRITE);
4346                        if (error)
4347                                return error;
4348                }
4349        }
4350
4351        error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
4352                                      flags);
4353        if (error)
4354                return error;
4355
4356        take_dentry_name_snapshot(&old_name, old_dentry);
4357        dget(new_dentry);
4358        if (!is_dir || (flags & RENAME_EXCHANGE))
4359                lock_two_nondirectories(source, target);
4360        else if (target)
4361                mutex_lock(&target->i_mutex);
4362
4363        error = -EBUSY;
4364        if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4365                goto out;
4366
4367        if (max_links && new_dir != old_dir) {
4368                error = -EMLINK;
4369                if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4370                        goto out;
4371                if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4372                    old_dir->i_nlink >= max_links)
4373                        goto out;
4374        }
4375        if (is_dir && !(flags & RENAME_EXCHANGE) && target)
4376                shrink_dcache_parent(new_dentry);
4377        if (!is_dir) {
4378                error = try_break_deleg(source, delegated_inode);
4379                if (error)
4380                        goto out;
4381        }
4382        if (target && !new_is_dir) {
4383                error = try_break_deleg(target, delegated_inode);
4384                if (error)
4385                        goto out;
4386        }
4387        if (!rename2) {
4388                error = old_dir->i_op->rename(old_dir, old_dentry,
4389                                              new_dir, new_dentry);
4390        } else {
4391                //WARN_ON(old_dir->i_op->rename != NULL);
4392                error = rename2(old_dir, old_dentry,
4393                                new_dir, new_dentry, flags);
4394        }
4395        if (error)
4396                goto out;
4397
4398        if (!(flags & RENAME_EXCHANGE) && target) {
4399                if (is_dir)
4400                        target->i_flags |= S_DEAD;
4401                dont_mount(new_dentry);
4402                detach_mounts(new_dentry);
4403        }
4404        if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4405                if (!(flags & RENAME_EXCHANGE))
4406                        d_move(old_dentry, new_dentry);
4407                else
4408                        d_exchange(old_dentry, new_dentry);
4409        }
4410out:
4411        if (!is_dir || (flags & RENAME_EXCHANGE))
4412                unlock_two_nondirectories(source, target);
4413        else if (target)
4414                mutex_unlock(&target->i_mutex);
4415        dput(new_dentry);
4416        if (!error) {
4417                fsnotify_move(old_dir, new_dir, old_name.name, is_dir,
4418                              !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4419                if (flags & RENAME_EXCHANGE) {
4420                        fsnotify_move(new_dir, old_dir, old_dentry->d_name.name,
4421                                      new_is_dir, NULL, new_dentry);
4422                }
4423        }
4424        release_dentry_name_snapshot(&old_name);
4425
4426        return error;
4427}
4428
4429SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
4430                int, newdfd, const char __user *, newname, unsigned int, flags)
4431{
4432        struct dentry *old_dir, *new_dir;
4433        struct dentry *old_dentry, *new_dentry;
4434        struct dentry *trap;
4435        struct nameidata oldnd, newnd;
4436        struct inode *delegated_inode = NULL;
4437        struct filename *from;
4438        struct filename *to;
4439        unsigned int lookup_flags = 0;
4440        bool should_retry = false;
4441        int error;
4442
4443        if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4444                return -EINVAL;
4445
4446        if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
4447            (flags & RENAME_EXCHANGE))
4448                return -EINVAL;
4449
4450        if ((flags & RENAME_WHITEOUT) && !capable(CAP_MKNOD))
4451                return -EPERM;
4452
4453retry:
4454        from = user_path_parent(olddfd, oldname, &oldnd, lookup_flags);
4455        if (IS_ERR(from)) {
4456                error = PTR_ERR(from);
4457                goto exit;
4458        }
4459
4460        to = user_path_parent(newdfd, newname, &newnd, lookup_flags);
4461        if (IS_ERR(to)) {
4462                error = PTR_ERR(to);
4463                goto exit1;
4464        }
4465
4466        error = -EXDEV;
4467        if (oldnd.path.mnt != newnd.path.mnt)
4468                goto exit2;
4469
4470        old_dir = oldnd.path.dentry;
4471        error = -EBUSY;
4472        if (oldnd.last_type != LAST_NORM)
4473                goto exit2;
4474
4475        new_dir = newnd.path.dentry;
4476        if (flags & RENAME_NOREPLACE)
4477                error = -EEXIST;
4478        if (newnd.last_type != LAST_NORM)
4479                goto exit2;
4480
4481        error = mnt_want_write(oldnd.path.mnt);
4482        if (error)
4483                goto exit2;
4484
4485        oldnd.flags &= ~LOOKUP_PARENT;
4486        newnd.flags &= ~LOOKUP_PARENT;
4487        if (!(flags & RENAME_EXCHANGE))
4488                newnd.flags |= LOOKUP_RENAME_TARGET;
4489
4490retry_deleg:
4491        trap = lock_rename(new_dir, old_dir);
4492
4493        old_dentry = lookup_hash(&oldnd);
4494        error = PTR_ERR(old_dentry);
4495        if (IS_ERR(old_dentry))
4496                goto exit3;
4497        /* source must exist */
4498        error = -ENOENT;
4499        if (d_is_negative(old_dentry))
4500                goto exit4;
4501        new_dentry = lookup_hash(&newnd);
4502        error = PTR_ERR(new_dentry);
4503        if (IS_ERR(new_dentry))
4504                goto exit4;
4505        error = -EEXIST;
4506        if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
4507                goto exit5;
4508        if (flags & RENAME_EXCHANGE) {
4509                error = -ENOENT;
4510                if (d_is_negative(new_dentry))
4511                        goto exit5;
4512
4513                if (!d_is_dir(new_dentry)) {
4514                        error = -ENOTDIR;
4515                        if (newnd.last.name[newnd.last.len])
4516                                goto exit5;
4517                }
4518        }
4519        /* unless the source is a directory trailing slashes give -ENOTDIR */
4520        if (!d_is_dir(old_dentry)) {
4521                error = -ENOTDIR;
4522                if (oldnd.last.name[oldnd.last.len])
4523                        goto exit5;
4524                if (!(flags & RENAME_EXCHANGE) && newnd.last.name[newnd.last.len])
4525                        goto exit5;
4526        }
4527        /* source should not be ancestor of target */
4528        error = -EINVAL;
4529        if (old_dentry == trap)
4530                goto exit5;
4531        /* target should not be an ancestor of source */
4532        if (!(flags & RENAME_EXCHANGE))
4533                error = -ENOTEMPTY;
4534        if (new_dentry == trap)
4535                goto exit5;
4536
4537        error = security_path_rename(&oldnd.path, old_dentry,
4538                                     &newnd.path, new_dentry, flags);
4539        if (error)
4540                goto exit5;
4541        error = vfs_rename(old_dir->d_inode, old_dentry,
4542                           new_dir->d_inode, new_dentry,
4543                           &delegated_inode, flags);
4544exit5:
4545        dput(new_dentry);
4546exit4:
4547        dput(old_dentry);
4548exit3:
4549        unlock_rename(new_dir, old_dir);
4550        if (delegated_inode) {
4551                error = break_deleg_wait(&delegated_inode);
4552                if (!error)
4553                        goto retry_deleg;
4554        }
4555        mnt_drop_write(oldnd.path.mnt);
4556exit2:
4557        if (retry_estale(error, lookup_flags))
4558                should_retry = true;
4559        path_put(&newnd.path);
4560        putname(to);
4561exit1:
4562        path_put(&oldnd.path);
4563        putname(from);
4564        if (should_retry) {
4565                should_retry = false;
4566                lookup_flags |= LOOKUP_REVAL;
4567                goto retry;
4568        }
4569exit:
4570        return error;
4571}
4572
4573SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
4574                int, newdfd, const char __user *, newname)
4575{
4576        return sys_renameat2(olddfd, oldname, newdfd, newname, 0);
4577}
4578
4579SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
4580{
4581        return sys_renameat2(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
4582}
4583
4584int vfs_whiteout(struct inode *dir, struct dentry *dentry)
4585{
4586        int error = may_create(dir, dentry);
4587        if (error)
4588                return error;
4589
4590        if (!dir->i_op->mknod)
4591                return -EPERM;
4592
4593        return dir->i_op->mknod(dir, dentry,
4594                                S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
4595}
4596EXPORT_SYMBOL(vfs_whiteout);
4597
4598int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen, const char *link)
4599{
4600        int len;
4601
4602        len = PTR_ERR(link);
4603        if (IS_ERR(link))
4604                goto out;
4605
4606        len = strlen(link);
4607        if (len > (unsigned) buflen)
4608                len = buflen;
4609        if (copy_to_user(buffer, link, len))
4610                len = -EFAULT;
4611out:
4612        return len;
4613}
4614
4615/*
4616 * A helper for ->readlink().  This should be used *ONLY* for symlinks that
4617 * have ->follow_link() touching nd only in nd_set_link().  Using (or not
4618 * using) it for any given inode is up to filesystem.
4619 */
4620int generic_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4621{
4622        struct nameidata nd;
4623        void *cookie;
4624        int res;
4625
4626        nd.depth = 0;
4627        cookie = dentry->d_inode->i_op->follow_link(dentry, &nd);
4628        if (IS_ERR(cookie))
4629                return PTR_ERR(cookie);
4630
4631        res = vfs_readlink(dentry, buffer, buflen, nd_get_link(&nd));
4632        if (dentry->d_inode->i_op->put_link)
4633                dentry->d_inode->i_op->put_link(dentry, &nd, cookie);
4634        return res;
4635}
4636
4637int vfs_follow_link(struct nameidata *nd, const char *link)
4638{
4639        return __vfs_follow_link(nd, link);
4640}
4641
4642/* get the link contents into pagecache */
4643static char *page_getlink(struct dentry * dentry, struct page **ppage)
4644{
4645        char *kaddr;
4646        struct page *page;
4647        struct address_space *mapping = dentry->d_inode->i_mapping;
4648        page = read_mapping_page(mapping, 0, NULL);
4649        if (IS_ERR(page))
4650                return (char*)page;
4651        *ppage = page;
4652        kaddr = kmap(page);
4653        nd_terminate_link(kaddr, dentry->d_inode->i_size, PAGE_SIZE - 1);
4654        return kaddr;
4655}
4656
4657int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4658{
4659        struct page *page = NULL;
4660        char *s = page_getlink(dentry, &page);
4661        int res = vfs_readlink(dentry,buffer,buflen,s);
4662        if (page) {
4663                kunmap(page);
4664                page_cache_release(page);
4665        }
4666        return res;
4667}
4668
4669void *page_follow_link_light(struct dentry *dentry, struct nameidata *nd)
4670{
4671        struct page *page = NULL;
4672        nd_set_link(nd, page_getlink(dentry, &page));
4673        return page;
4674}
4675
4676void page_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie)
4677{
4678        struct page *page = cookie;
4679
4680        if (page) {
4681                kunmap(page);
4682                page_cache_release(page);
4683        }
4684}
4685
4686/*
4687 * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
4688 */
4689int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
4690{
4691        struct address_space *mapping = inode->i_mapping;
4692        struct page *page;
4693        void *fsdata;
4694        int err;
4695        char *kaddr;
4696        unsigned int flags = AOP_FLAG_UNINTERRUPTIBLE;
4697        if (nofs)
4698                flags |= AOP_FLAG_NOFS;
4699
4700retry:
4701        err = pagecache_write_begin(NULL, mapping, 0, len-1,
4702                                flags, &page, &fsdata);
4703        if (err)
4704                goto fail;
4705
4706        kaddr = kmap_atomic(page);
4707        memcpy(kaddr, symname, len-1);
4708        kunmap_atomic(kaddr);
4709
4710        err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
4711                                                        page, fsdata);
4712        if (err < 0)
4713                goto fail;
4714        if (err < len-1)
4715                goto retry;
4716
4717        mark_inode_dirty(inode);
4718        return 0;
4719fail:
4720        return err;
4721}
4722
4723int page_symlink(struct inode *inode, const char *symname, int len)
4724{
4725        return __page_symlink(inode, symname, len,
4726                        !(mapping_gfp_mask(inode->i_mapping) & __GFP_FS));
4727}
4728
4729const struct inode_operations page_symlink_inode_operations = {
4730        .readlink       = generic_readlink,
4731        .follow_link    = page_follow_link_light,
4732        .put_link       = page_put_link,
4733};
4734
4735EXPORT_SYMBOL(user_path_at);
4736EXPORT_SYMBOL(follow_down_one);
4737EXPORT_SYMBOL(follow_down);
4738EXPORT_SYMBOL(follow_up);
4739EXPORT_SYMBOL(get_write_access); /* nfsd */
4740EXPORT_SYMBOL(lock_rename);
4741EXPORT_SYMBOL(lookup_one_len);
4742EXPORT_SYMBOL(page_follow_link_light);
4743EXPORT_SYMBOL(page_put_link);
4744EXPORT_SYMBOL(page_readlink);
4745EXPORT_SYMBOL(__page_symlink);
4746EXPORT_SYMBOL(page_symlink);
4747EXPORT_SYMBOL(page_symlink_inode_operations);
4748EXPORT_SYMBOL(kern_path);
4749EXPORT_SYMBOL(vfs_path_lookup);
4750EXPORT_SYMBOL(inode_permission);
4751EXPORT_SYMBOL(unlock_rename);
4752EXPORT_SYMBOL(vfs_create);
4753EXPORT_SYMBOL(vfs_follow_link);
4754EXPORT_SYMBOL(vfs_link);
4755EXPORT_SYMBOL(vfs_mkdir);
4756EXPORT_SYMBOL(vfs_mknod);
4757EXPORT_SYMBOL(generic_permission);
4758EXPORT_SYMBOL(vfs_readlink);
4759EXPORT_SYMBOL(vfs_rename);
4760EXPORT_SYMBOL(vfs_rmdir);
4761EXPORT_SYMBOL(vfs_symlink);
4762EXPORT_SYMBOL(vfs_unlink);
4763EXPORT_SYMBOL(dentry_unhash);
4764EXPORT_SYMBOL(generic_readlink);
4765