1 // SPDX-License-Identifier: GPL-2.0
5 * Copyright (C) 1991, 1992 Linus Torvalds
9 * Some corrections by tytso.
12 /* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname
15 /* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture.
18 #include <linux/init.h>
19 #include <linux/export.h>
20 #include <linux/kernel.h>
21 #include <linux/slab.h>
23 #include <linux/namei.h>
24 #include <linux/pagemap.h>
25 #include <linux/fsnotify.h>
26 #include <linux/personality.h>
27 #include <linux/security.h>
28 #include <linux/ima.h>
29 #include <linux/syscalls.h>
30 #include <linux/mount.h>
31 #include <linux/audit.h>
32 #include <linux/capability.h>
33 #include <linux/file.h>
34 #include <linux/fcntl.h>
35 #include <linux/device_cgroup.h>
36 #include <linux/fs_struct.h>
37 #include <linux/posix_acl.h>
38 #include <linux/hash.h>
39 #include <linux/bitops.h>
40 #include <linux/init_task.h>
41 #include <linux/uaccess.h>
46 /* [Feb-1997 T. Schoebel-Theuer]
47 * Fundamental changes in the pathname lookup mechanisms (namei)
48 * were necessary because of omirr. The reason is that omirr needs
49 * to know the _real_ pathname, not the user-supplied one, in case
50 * of symlinks (and also when transname replacements occur).
52 * The new code replaces the old recursive symlink resolution with
53 * an iterative one (in case of non-nested symlink chains). It does
54 * this with calls to <fs>_follow_link().
55 * As a side effect, dir_namei(), _namei() and follow_link() are now
56 * replaced with a single function lookup_dentry() that can handle all
57 * the special cases of the former code.
59 * With the new dcache, the pathname is stored at each inode, at least as
60 * long as the refcount of the inode is positive. As a side effect, the
61 * size of the dcache depends on the inode cache and thus is dynamic.
63 * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
64 * resolution to correspond with current state of the code.
66 * Note that the symlink resolution is not *completely* iterative.
67 * There is still a significant amount of tail- and mid- recursion in
68 * the algorithm. Also, note that <fs>_readlink() is not used in
69 * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
70 * may return different results than <fs>_follow_link(). Many virtual
71 * filesystems (including /proc) exhibit this behavior.
74 /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
75 * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
76 * and the name already exists in form of a symlink, try to create the new
77 * name indicated by the symlink. The old code always complained that the
78 * name already exists, due to not following the symlink even if its target
79 * is nonexistent. The new semantics affects also mknod() and link() when
80 * the name is a symlink pointing to a non-existent name.
82 * I don't know which semantics is the right one, since I have no access
83 * to standards. But I found by trial that HP-UX 9.0 has the full "new"
84 * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
85 * "old" one. Personally, I think the new semantics is much more logical.
86 * Note that "ln old new" where "new" is a symlink pointing to a non-existing
87 * file does succeed in both HP-UX and SunOs, but not in Solaris
88 * and in the old Linux semantics.
91 /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
92 * semantics. See the comments in "open_namei" and "do_link" below.
94 * [10-Sep-98 Alan Modra] Another symlink change.
97 /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
98 * inside the path - always follow.
99 * in the last component in creation/removal/renaming - never follow.
100 * if LOOKUP_FOLLOW passed - follow.
101 * if the pathname has trailing slashes - follow.
102 * otherwise - don't follow.
103 * (applied in that order).
105 * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
106 * restored for 2.4. This is the last surviving part of old 4.2BSD bug.
107 * During the 2.4 we need to fix the userland stuff depending on it -
108 * hopefully we will be able to get rid of that wart in 2.5. So far only
109 * XEmacs seems to be relying on it...
112 * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
113 * implemented. Let's see if raised priority of ->s_vfs_rename_mutex gives
114 * any extra contention...
117 /* In order to reduce some races, while at the same time doing additional
118 * checking and hopefully speeding things up, we copy filenames to the
119 * kernel data space before using them..
121 * POSIX.1 2.4: an empty pathname is invalid (ENOENT).
122 * PATH_MAX includes the nul terminator --RR.
125 #define EMBEDDED_NAME_MAX (PATH_MAX - offsetof(struct filename, iname))
128 getname_flags(const char __user *filename, int flags, int *empty)
130 struct filename *result;
134 result = audit_reusename(filename);
138 result = __getname();
139 if (unlikely(!result))
140 return ERR_PTR(-ENOMEM);
143 * First, try to embed the struct filename inside the names_cache
146 kname = (char *)result->iname;
147 result->name = kname;
149 len = strncpy_from_user(kname, filename, EMBEDDED_NAME_MAX);
150 if (unlikely(len < 0)) {
156 * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a
157 * separate struct filename so we can dedicate the entire
158 * names_cache allocation for the pathname, and re-do the copy from
161 if (unlikely(len == EMBEDDED_NAME_MAX)) {
162 const size_t size = offsetof(struct filename, iname[1]);
163 kname = (char *)result;
166 * size is chosen that way we to guarantee that
167 * result->iname[0] is within the same object and that
168 * kname can't be equal to result->iname, no matter what.
170 result = kzalloc(size, GFP_KERNEL);
171 if (unlikely(!result)) {
173 return ERR_PTR(-ENOMEM);
175 result->name = kname;
176 len = strncpy_from_user(kname, filename, PATH_MAX);
177 if (unlikely(len < 0)) {
182 if (unlikely(len == PATH_MAX)) {
185 return ERR_PTR(-ENAMETOOLONG);
190 /* The empty path is special. */
191 if (unlikely(!len)) {
194 if (!(flags & LOOKUP_EMPTY)) {
196 return ERR_PTR(-ENOENT);
200 result->uptr = filename;
201 result->aname = NULL;
202 audit_getname(result);
207 getname(const char __user * filename)
209 return getname_flags(filename, 0, NULL);
213 getname_kernel(const char * filename)
215 struct filename *result;
216 int len = strlen(filename) + 1;
218 result = __getname();
219 if (unlikely(!result))
220 return ERR_PTR(-ENOMEM);
222 if (len <= EMBEDDED_NAME_MAX) {
223 result->name = (char *)result->iname;
224 } else if (len <= PATH_MAX) {
225 const size_t size = offsetof(struct filename, iname[1]);
226 struct filename *tmp;
228 tmp = kmalloc(size, GFP_KERNEL);
229 if (unlikely(!tmp)) {
231 return ERR_PTR(-ENOMEM);
233 tmp->name = (char *)result;
237 return ERR_PTR(-ENAMETOOLONG);
239 memcpy((char *)result->name, filename, len);
241 result->aname = NULL;
243 audit_getname(result);
248 void putname(struct filename *name)
250 BUG_ON(name->refcnt <= 0);
252 if (--name->refcnt > 0)
255 if (name->name != name->iname) {
256 __putname(name->name);
262 static int check_acl(struct inode *inode, int mask)
264 #ifdef CONFIG_FS_POSIX_ACL
265 struct posix_acl *acl;
267 if (mask & MAY_NOT_BLOCK) {
268 acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
271 /* no ->get_acl() calls in RCU mode... */
272 if (is_uncached_acl(acl))
274 return posix_acl_permission(inode, acl, mask & ~MAY_NOT_BLOCK);
277 acl = get_acl(inode, ACL_TYPE_ACCESS);
281 int error = posix_acl_permission(inode, acl, mask);
282 posix_acl_release(acl);
291 * This does the basic permission checking
293 static int acl_permission_check(struct inode *inode, int mask)
295 unsigned int mode = inode->i_mode;
297 if (likely(uid_eq(current_fsuid(), inode->i_uid)))
300 if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
301 int error = check_acl(inode, mask);
302 if (error != -EAGAIN)
306 if (in_group_p(inode->i_gid))
311 * If the DACs are ok we don't need any capability check.
313 if ((mask & ~mode & (MAY_READ | MAY_WRITE | MAY_EXEC)) == 0)
319 * generic_permission - check for access rights on a Posix-like filesystem
320 * @inode: inode to check access rights for
321 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC, ...)
323 * Used to check for read/write/execute permissions on a file.
324 * We use "fsuid" for this, letting us set arbitrary permissions
325 * for filesystem access without changing the "normal" uids which
326 * are used for other things.
328 * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
329 * request cannot be satisfied (eg. requires blocking or too much complexity).
330 * It would then be called again in ref-walk mode.
332 int generic_permission(struct inode *inode, int mask)
337 * Do the basic permission checks.
339 ret = acl_permission_check(inode, mask);
343 if (S_ISDIR(inode->i_mode)) {
344 /* DACs are overridable for directories */
345 if (!(mask & MAY_WRITE))
346 if (capable_wrt_inode_uidgid(inode,
347 CAP_DAC_READ_SEARCH))
349 if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))
355 * Searching includes executable on directories, else just read.
357 mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
358 if (mask == MAY_READ)
359 if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH))
362 * Read/write DACs are always overridable.
363 * Executable DACs are overridable when there is
364 * at least one exec bit set.
366 if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
367 if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))
372 EXPORT_SYMBOL(generic_permission);
375 * We _really_ want to just do "generic_permission()" without
376 * even looking at the inode->i_op values. So we keep a cache
377 * flag in inode->i_opflags, that says "this has not special
378 * permission function, use the fast case".
380 static inline int do_inode_permission(struct inode *inode, int mask)
382 if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
383 if (likely(inode->i_op->permission))
384 return inode->i_op->permission(inode, mask);
386 /* This gets set once for the inode lifetime */
387 spin_lock(&inode->i_lock);
388 inode->i_opflags |= IOP_FASTPERM;
389 spin_unlock(&inode->i_lock);
391 return generic_permission(inode, mask);
395 * sb_permission - Check superblock-level permissions
396 * @sb: Superblock of inode to check permission on
397 * @inode: Inode to check permission on
398 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
400 * Separate out file-system wide checks from inode-specific permission checks.
402 static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
404 if (unlikely(mask & MAY_WRITE)) {
405 umode_t mode = inode->i_mode;
407 /* Nobody gets write access to a read-only fs. */
408 if (sb_rdonly(sb) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
415 * inode_permission - Check for access rights to a given inode
416 * @inode: Inode to check permission on
417 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
419 * Check for read/write/execute permissions on an inode. We use fs[ug]id for
420 * this, letting us set arbitrary permissions for filesystem access without
421 * changing the "normal" UIDs which are used for other things.
423 * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
425 int inode_permission(struct inode *inode, int mask)
429 retval = sb_permission(inode->i_sb, inode, mask);
433 if (unlikely(mask & MAY_WRITE)) {
435 * Nobody gets write access to an immutable file.
437 if (IS_IMMUTABLE(inode))
441 * Updating mtime will likely cause i_uid and i_gid to be
442 * written back improperly if their true value is unknown
445 if (HAS_UNMAPPED_ID(inode))
449 retval = do_inode_permission(inode, mask);
453 retval = devcgroup_inode_permission(inode, mask);
457 return security_inode_permission(inode, mask);
459 EXPORT_SYMBOL(inode_permission);
462 * path_get - get a reference to a path
463 * @path: path to get the reference to
465 * Given a path increment the reference count to the dentry and the vfsmount.
467 void path_get(const struct path *path)
472 EXPORT_SYMBOL(path_get);
475 * path_put - put a reference to a path
476 * @path: path to put the reference to
478 * Given a path decrement the reference count to the dentry and the vfsmount.
480 void path_put(const struct path *path)
485 EXPORT_SYMBOL(path_put);
487 #define EMBEDDED_LEVELS 2
492 struct inode *inode; /* path.dentry.d_inode */
494 unsigned seq, m_seq, r_seq;
497 int total_link_count;
500 struct delayed_call done;
503 } *stack, internal[EMBEDDED_LEVELS];
504 struct filename *name;
505 struct nameidata *saved;
506 struct inode *link_inode;
509 } __randomize_layout;
511 static void set_nameidata(struct nameidata *p, int dfd, struct filename *name)
513 struct nameidata *old = current->nameidata;
514 p->stack = p->internal;
517 p->total_link_count = old ? old->total_link_count : 0;
519 current->nameidata = p;
522 static void restore_nameidata(void)
524 struct nameidata *now = current->nameidata, *old = now->saved;
526 current->nameidata = old;
528 old->total_link_count = now->total_link_count;
529 if (now->stack != now->internal)
533 static int __nd_alloc_stack(struct nameidata *nd)
537 if (nd->flags & LOOKUP_RCU) {
538 p= kmalloc_array(MAXSYMLINKS, sizeof(struct saved),
543 p= kmalloc_array(MAXSYMLINKS, sizeof(struct saved),
548 memcpy(p, nd->internal, sizeof(nd->internal));
554 * path_connected - Verify that a path->dentry is below path->mnt.mnt_root
555 * @path: nameidate to verify
557 * Rename can sometimes move a file or directory outside of a bind
558 * mount, path_connected allows those cases to be detected.
560 static bool path_connected(const struct path *path)
562 struct vfsmount *mnt = path->mnt;
563 struct super_block *sb = mnt->mnt_sb;
565 /* Bind mounts and multi-root filesystems can have disconnected paths */
566 if (!(sb->s_iflags & SB_I_MULTIROOT) && (mnt->mnt_root == sb->s_root))
569 return is_subdir(path->dentry, mnt->mnt_root);
572 static inline int nd_alloc_stack(struct nameidata *nd)
574 if (likely(nd->depth != EMBEDDED_LEVELS))
576 if (likely(nd->stack != nd->internal))
578 return __nd_alloc_stack(nd);
581 static void drop_links(struct nameidata *nd)
585 struct saved *last = nd->stack + i;
586 do_delayed_call(&last->done);
587 clear_delayed_call(&last->done);
591 static void terminate_walk(struct nameidata *nd)
594 if (!(nd->flags & LOOKUP_RCU)) {
597 for (i = 0; i < nd->depth; i++)
598 path_put(&nd->stack[i].link);
599 if (nd->flags & LOOKUP_ROOT_GRABBED) {
601 nd->flags &= ~LOOKUP_ROOT_GRABBED;
604 nd->flags &= ~LOOKUP_RCU;
610 /* path_put is needed afterwards regardless of success or failure */
611 static bool legitimize_path(struct nameidata *nd,
612 struct path *path, unsigned seq)
614 int res = __legitimize_mnt(path->mnt, nd->m_seq);
621 if (unlikely(!lockref_get_not_dead(&path->dentry->d_lockref))) {
625 return !read_seqcount_retry(&path->dentry->d_seq, seq);
628 static bool legitimize_links(struct nameidata *nd)
631 for (i = 0; i < nd->depth; i++) {
632 struct saved *last = nd->stack + i;
633 if (unlikely(!legitimize_path(nd, &last->link, last->seq))) {
642 static bool legitimize_root(struct nameidata *nd)
645 * For scoped-lookups (where nd->root has been zeroed), we need to
646 * restart the whole lookup from scratch -- because set_root() is wrong
647 * for these lookups (nd->dfd is the root, not the filesystem root).
649 if (!nd->root.mnt && (nd->flags & LOOKUP_IS_SCOPED))
651 /* Nothing to do if nd->root is zero or is managed by the VFS user. */
652 if (!nd->root.mnt || (nd->flags & LOOKUP_ROOT))
654 nd->flags |= LOOKUP_ROOT_GRABBED;
655 return legitimize_path(nd, &nd->root, nd->root_seq);
659 * Path walking has 2 modes, rcu-walk and ref-walk (see
660 * Documentation/filesystems/path-lookup.txt). In situations when we can't
661 * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
662 * normal reference counts on dentries and vfsmounts to transition to ref-walk
663 * mode. Refcounts are grabbed at the last known good point before rcu-walk
664 * got stuck, so ref-walk may continue from there. If this is not successful
665 * (eg. a seqcount has changed), then failure is returned and it's up to caller
666 * to restart the path walk from the beginning in ref-walk mode.
670 * unlazy_walk - try to switch to ref-walk mode.
671 * @nd: nameidata pathwalk data
672 * Returns: 0 on success, -ECHILD on failure
674 * unlazy_walk attempts to legitimize the current nd->path and nd->root
676 * Must be called from rcu-walk context.
677 * Nothing should touch nameidata between unlazy_walk() failure and
680 static int unlazy_walk(struct nameidata *nd)
682 struct dentry *parent = nd->path.dentry;
684 BUG_ON(!(nd->flags & LOOKUP_RCU));
686 nd->flags &= ~LOOKUP_RCU;
687 if (unlikely(!legitimize_links(nd)))
689 if (unlikely(!legitimize_path(nd, &nd->path, nd->seq)))
691 if (unlikely(!legitimize_root(nd)))
694 BUG_ON(nd->inode != parent->d_inode);
699 nd->path.dentry = NULL;
706 * unlazy_child - try to switch to ref-walk mode.
707 * @nd: nameidata pathwalk data
708 * @dentry: child of nd->path.dentry
709 * @seq: seq number to check dentry against
710 * Returns: 0 on success, -ECHILD on failure
712 * unlazy_child attempts to legitimize the current nd->path, nd->root and dentry
713 * for ref-walk mode. @dentry must be a path found by a do_lookup call on
714 * @nd. Must be called from rcu-walk context.
715 * Nothing should touch nameidata between unlazy_child() failure and
718 static int unlazy_child(struct nameidata *nd, struct dentry *dentry, unsigned seq)
720 BUG_ON(!(nd->flags & LOOKUP_RCU));
722 nd->flags &= ~LOOKUP_RCU;
723 if (unlikely(!legitimize_links(nd)))
725 if (unlikely(!legitimize_mnt(nd->path.mnt, nd->m_seq)))
727 if (unlikely(!lockref_get_not_dead(&nd->path.dentry->d_lockref)))
731 * We need to move both the parent and the dentry from the RCU domain
732 * to be properly refcounted. And the sequence number in the dentry
733 * validates *both* dentry counters, since we checked the sequence
734 * number of the parent after we got the child sequence number. So we
735 * know the parent must still be valid if the child sequence number is
737 if (unlikely(!lockref_get_not_dead(&dentry->d_lockref)))
739 if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
742 * Sequence counts matched. Now make sure that the root is
743 * still valid and get it if required.
745 if (unlikely(!legitimize_root(nd)))
753 nd->path.dentry = NULL;
763 static inline int d_revalidate(struct dentry *dentry, unsigned int flags)
765 if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE))
766 return dentry->d_op->d_revalidate(dentry, flags);
772 * complete_walk - successful completion of path walk
773 * @nd: pointer nameidata
775 * If we had been in RCU mode, drop out of it and legitimize nd->path.
776 * Revalidate the final result, unless we'd already done that during
777 * the path walk or the filesystem doesn't ask for it. Return 0 on
778 * success, -error on failure. In case of failure caller does not
779 * need to drop nd->path.
781 static int complete_walk(struct nameidata *nd)
783 struct dentry *dentry = nd->path.dentry;
786 if (nd->flags & LOOKUP_RCU) {
788 * We don't want to zero nd->root for scoped-lookups or
789 * externally-managed nd->root.
791 if (!(nd->flags & (LOOKUP_ROOT | LOOKUP_IS_SCOPED)))
793 if (unlikely(unlazy_walk(nd)))
797 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
799 * While the guarantee of LOOKUP_IS_SCOPED is (roughly) "don't
800 * ever step outside the root during lookup" and should already
801 * be guaranteed by the rest of namei, we want to avoid a namei
802 * BUG resulting in userspace being given a path that was not
803 * scoped within the root at some point during the lookup.
805 * So, do a final sanity-check to make sure that in the
806 * worst-case scenario (a complete bypass of LOOKUP_IS_SCOPED)
807 * we won't silently return an fd completely outside of the
808 * requested root to userspace.
810 * Userspace could move the path outside the root after this
811 * check, but as discussed elsewhere this is not a concern (the
812 * resolved file was inside the root at some point).
814 if (!path_is_under(&nd->path, &nd->root))
818 if (likely(!(nd->flags & LOOKUP_JUMPED)))
821 if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
824 status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
834 static int set_root(struct nameidata *nd)
836 struct fs_struct *fs = current->fs;
839 * Jumping to the real root in a scoped-lookup is a BUG in namei, but we
840 * still have to ensure it doesn't happen because it will cause a breakout
843 if (WARN_ON(nd->flags & LOOKUP_IS_SCOPED))
844 return -ENOTRECOVERABLE;
846 if (nd->flags & LOOKUP_RCU) {
850 seq = read_seqcount_begin(&fs->seq);
852 nd->root_seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
853 } while (read_seqcount_retry(&fs->seq, seq));
855 get_fs_root(fs, &nd->root);
856 nd->flags |= LOOKUP_ROOT_GRABBED;
861 static void path_put_conditional(struct path *path, struct nameidata *nd)
864 if (path->mnt != nd->path.mnt)
868 static inline void path_to_nameidata(const struct path *path,
869 struct nameidata *nd)
871 if (!(nd->flags & LOOKUP_RCU)) {
872 dput(nd->path.dentry);
873 if (nd->path.mnt != path->mnt)
874 mntput(nd->path.mnt);
876 nd->path.mnt = path->mnt;
877 nd->path.dentry = path->dentry;
880 static int nd_jump_root(struct nameidata *nd)
882 if (unlikely(nd->flags & LOOKUP_BENEATH))
884 if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
885 /* Absolute path arguments to path_init() are allowed. */
886 if (nd->path.mnt != NULL && nd->path.mnt != nd->root.mnt)
890 int error = set_root(nd);
894 if (nd->flags & LOOKUP_RCU) {
898 nd->inode = d->d_inode;
899 nd->seq = nd->root_seq;
900 if (unlikely(read_seqcount_retry(&d->d_seq, nd->seq)))
906 nd->inode = nd->path.dentry->d_inode;
908 nd->flags |= LOOKUP_JUMPED;
913 * Helper to directly jump to a known parsed path from ->get_link,
914 * caller must have taken a reference to path beforehand.
916 int nd_jump_link(struct path *path)
919 struct nameidata *nd = current->nameidata;
921 if (unlikely(nd->flags & LOOKUP_NO_MAGICLINKS))
925 if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
926 if (nd->path.mnt != path->mnt)
929 /* Not currently safe for scoped-lookups. */
930 if (unlikely(nd->flags & LOOKUP_IS_SCOPED))
935 nd->inode = nd->path.dentry->d_inode;
936 nd->flags |= LOOKUP_JUMPED;
944 static inline void put_link(struct nameidata *nd)
946 struct saved *last = nd->stack + --nd->depth;
947 do_delayed_call(&last->done);
948 if (!(nd->flags & LOOKUP_RCU))
949 path_put(&last->link);
952 int sysctl_protected_symlinks __read_mostly = 0;
953 int sysctl_protected_hardlinks __read_mostly = 0;
954 int sysctl_protected_fifos __read_mostly;
955 int sysctl_protected_regular __read_mostly;
958 * may_follow_link - Check symlink following for unsafe situations
959 * @nd: nameidata pathwalk data
961 * In the case of the sysctl_protected_symlinks sysctl being enabled,
962 * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
963 * in a sticky world-writable directory. This is to protect privileged
964 * processes from failing races against path names that may change out
965 * from under them by way of other users creating malicious symlinks.
966 * It will permit symlinks to be followed only when outside a sticky
967 * world-writable directory, or when the uid of the symlink and follower
968 * match, or when the directory owner matches the symlink's owner.
970 * Returns 0 if following the symlink is allowed, -ve on error.
972 static inline int may_follow_link(struct nameidata *nd)
974 const struct inode *inode;
975 const struct inode *parent;
978 if (!sysctl_protected_symlinks)
981 /* Allowed if owner and follower match. */
982 inode = nd->link_inode;
983 if (uid_eq(current_cred()->fsuid, inode->i_uid))
986 /* Allowed if parent directory not sticky and world-writable. */
988 if ((parent->i_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
991 /* Allowed if parent directory and link owner match. */
992 puid = parent->i_uid;
993 if (uid_valid(puid) && uid_eq(puid, inode->i_uid))
996 if (nd->flags & LOOKUP_RCU)
999 audit_inode(nd->name, nd->stack[0].link.dentry, 0);
1000 audit_log_path_denied(AUDIT_ANOM_LINK, "follow_link");
1005 * safe_hardlink_source - Check for safe hardlink conditions
1006 * @inode: the source inode to hardlink from
1008 * Return false if at least one of the following conditions:
1009 * - inode is not a regular file
1011 * - inode is setgid and group-exec
1012 * - access failure for read and write
1014 * Otherwise returns true.
1016 static bool safe_hardlink_source(struct inode *inode)
1018 umode_t mode = inode->i_mode;
1020 /* Special files should not get pinned to the filesystem. */
1024 /* Setuid files should not get pinned to the filesystem. */
1028 /* Executable setgid files should not get pinned to the filesystem. */
1029 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
1032 /* Hardlinking to unreadable or unwritable sources is dangerous. */
1033 if (inode_permission(inode, MAY_READ | MAY_WRITE))
1040 * may_linkat - Check permissions for creating a hardlink
1041 * @link: the source to hardlink from
1043 * Block hardlink when all of:
1044 * - sysctl_protected_hardlinks enabled
1045 * - fsuid does not match inode
1046 * - hardlink source is unsafe (see safe_hardlink_source() above)
1047 * - not CAP_FOWNER in a namespace with the inode owner uid mapped
1049 * Returns 0 if successful, -ve on error.
1051 static int may_linkat(struct path *link)
1053 struct inode *inode = link->dentry->d_inode;
1055 /* Inode writeback is not safe when the uid or gid are invalid. */
1056 if (!uid_valid(inode->i_uid) || !gid_valid(inode->i_gid))
1059 if (!sysctl_protected_hardlinks)
1062 /* Source inode owner (or CAP_FOWNER) can hardlink all they like,
1063 * otherwise, it must be a safe source.
1065 if (safe_hardlink_source(inode) || inode_owner_or_capable(inode))
1068 audit_log_path_denied(AUDIT_ANOM_LINK, "linkat");
1073 * may_create_in_sticky - Check whether an O_CREAT open in a sticky directory
1074 * should be allowed, or not, on files that already
1076 * @dir_mode: mode bits of directory
1077 * @dir_uid: owner of directory
1078 * @inode: the inode of the file to open
1080 * Block an O_CREAT open of a FIFO (or a regular file) when:
1081 * - sysctl_protected_fifos (or sysctl_protected_regular) is enabled
1082 * - the file already exists
1083 * - we are in a sticky directory
1084 * - we don't own the file
1085 * - the owner of the directory doesn't own the file
1086 * - the directory is world writable
1087 * If the sysctl_protected_fifos (or sysctl_protected_regular) is set to 2
1088 * the directory doesn't have to be world writable: being group writable will
1091 * Returns 0 if the open is allowed, -ve on error.
1093 static int may_create_in_sticky(umode_t dir_mode, kuid_t dir_uid,
1094 struct inode * const inode)
1096 if ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||
1097 (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||
1098 likely(!(dir_mode & S_ISVTX)) ||
1099 uid_eq(inode->i_uid, dir_uid) ||
1100 uid_eq(current_fsuid(), inode->i_uid))
1103 if (likely(dir_mode & 0002) ||
1105 ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||
1106 (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {
1107 const char *operation = S_ISFIFO(inode->i_mode) ?
1108 "sticky_create_fifo" :
1109 "sticky_create_regular";
1110 audit_log_path_denied(AUDIT_ANOM_CREAT, operation);
1116 static __always_inline
1117 const char *get_link(struct nameidata *nd)
1119 struct saved *last = nd->stack + nd->depth - 1;
1120 struct dentry *dentry = last->link.dentry;
1121 struct inode *inode = nd->link_inode;
1125 if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS))
1126 return ERR_PTR(-ELOOP);
1128 if (!(nd->flags & LOOKUP_RCU)) {
1129 touch_atime(&last->link);
1131 } else if (atime_needs_update(&last->link, inode)) {
1132 if (unlikely(unlazy_walk(nd)))
1133 return ERR_PTR(-ECHILD);
1134 touch_atime(&last->link);
1137 error = security_inode_follow_link(dentry, inode,
1138 nd->flags & LOOKUP_RCU);
1139 if (unlikely(error))
1140 return ERR_PTR(error);
1142 nd->last_type = LAST_BIND;
1143 res = READ_ONCE(inode->i_link);
1145 const char * (*get)(struct dentry *, struct inode *,
1146 struct delayed_call *);
1147 get = inode->i_op->get_link;
1148 if (nd->flags & LOOKUP_RCU) {
1149 res = get(NULL, inode, &last->done);
1150 if (res == ERR_PTR(-ECHILD)) {
1151 if (unlikely(unlazy_walk(nd)))
1152 return ERR_PTR(-ECHILD);
1153 res = get(dentry, inode, &last->done);
1156 res = get(dentry, inode, &last->done);
1158 if (IS_ERR_OR_NULL(res))
1162 error = nd_jump_root(nd);
1163 if (unlikely(error))
1164 return ERR_PTR(error);
1165 while (unlikely(*++res == '/'))
1174 * follow_up - Find the mountpoint of path's vfsmount
1176 * Given a path, find the mountpoint of its source file system.
1177 * Replace @path with the path of the mountpoint in the parent mount.
1180 * Return 1 if we went up a level and 0 if we were already at the
1183 int follow_up(struct path *path)
1185 struct mount *mnt = real_mount(path->mnt);
1186 struct mount *parent;
1187 struct dentry *mountpoint;
1189 read_seqlock_excl(&mount_lock);
1190 parent = mnt->mnt_parent;
1191 if (parent == mnt) {
1192 read_sequnlock_excl(&mount_lock);
1195 mntget(&parent->mnt);
1196 mountpoint = dget(mnt->mnt_mountpoint);
1197 read_sequnlock_excl(&mount_lock);
1199 path->dentry = mountpoint;
1201 path->mnt = &parent->mnt;
1204 EXPORT_SYMBOL(follow_up);
1207 * Perform an automount
1208 * - return -EISDIR to tell follow_managed() to stop and return the path we
1211 static int follow_automount(struct path *path, struct nameidata *nd,
1214 struct vfsmount *mnt;
1217 if (!path->dentry->d_op || !path->dentry->d_op->d_automount)
1220 /* We don't want to mount if someone's just doing a stat -
1221 * unless they're stat'ing a directory and appended a '/' to
1224 * We do, however, want to mount if someone wants to open or
1225 * create a file of any type under the mountpoint, wants to
1226 * traverse through the mountpoint or wants to open the
1227 * mounted directory. Also, autofs may mark negative dentries
1228 * as being automount points. These will need the attentions
1229 * of the daemon to instantiate them before they can be used.
1231 if (!(nd->flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
1232 LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
1233 path->dentry->d_inode)
1236 nd->total_link_count++;
1237 if (nd->total_link_count >= 40)
1240 mnt = path->dentry->d_op->d_automount(path);
1243 * The filesystem is allowed to return -EISDIR here to indicate
1244 * it doesn't want to automount. For instance, autofs would do
1245 * this so that its userspace daemon can mount on this dentry.
1247 * However, we can only permit this if it's a terminal point in
1248 * the path being looked up; if it wasn't then the remainder of
1249 * the path is inaccessible and we should say so.
1251 if (PTR_ERR(mnt) == -EISDIR && (nd->flags & LOOKUP_PARENT))
1253 return PTR_ERR(mnt);
1256 if (!mnt) /* mount collision */
1259 if (!*need_mntput) {
1260 /* lock_mount() may release path->mnt on error */
1262 *need_mntput = true;
1264 err = finish_automount(mnt, path);
1268 /* Someone else made a mount here whilst we were busy */
1273 path->dentry = dget(mnt->mnt_root);
1282 * Handle a dentry that is managed in some way.
1283 * - Flagged for transit management (autofs)
1284 * - Flagged as mountpoint
1285 * - Flagged as automount point
1287 * This may only be called in refwalk mode.
1288 * On success path->dentry is known positive.
1290 * Serialization is taken care of in namespace.c
1292 static int follow_managed(struct path *path, struct nameidata *nd)
1294 struct vfsmount *mnt = path->mnt; /* held by caller, must be left alone */
1296 bool need_mntput = false;
1299 /* Given that we're not holding a lock here, we retain the value in a
1300 * local variable for each dentry as we look at it so that we don't see
1301 * the components of that value change under us */
1302 while (flags = smp_load_acquire(&path->dentry->d_flags),
1303 unlikely(flags & DCACHE_MANAGED_DENTRY)) {
1304 /* Allow the filesystem to manage the transit without i_mutex
1306 if (flags & DCACHE_MANAGE_TRANSIT) {
1307 BUG_ON(!path->dentry->d_op);
1308 BUG_ON(!path->dentry->d_op->d_manage);
1309 ret = path->dentry->d_op->d_manage(path, false);
1310 flags = smp_load_acquire(&path->dentry->d_flags);
1315 /* Transit to a mounted filesystem. */
1316 if (flags & DCACHE_MOUNTED) {
1317 struct vfsmount *mounted = lookup_mnt(path);
1322 path->mnt = mounted;
1323 path->dentry = dget(mounted->mnt_root);
1328 /* Something is mounted on this dentry in another
1329 * namespace and/or whatever was mounted there in this
1330 * namespace got unmounted before lookup_mnt() could
1334 /* Handle an automount point */
1335 if (flags & DCACHE_NEED_AUTOMOUNT) {
1336 ret = follow_automount(path, nd, &need_mntput);
1342 /* We didn't change the current path point */
1347 if (path->mnt == mnt)
1349 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1352 nd->flags |= LOOKUP_JUMPED;
1354 if (ret == -EISDIR || !ret)
1356 if (ret > 0 && unlikely(d_flags_negative(flags)))
1358 if (unlikely(ret < 0))
1359 path_put_conditional(path, nd);
1363 int follow_down_one(struct path *path)
1365 struct vfsmount *mounted;
1367 mounted = lookup_mnt(path);
1371 path->mnt = mounted;
1372 path->dentry = dget(mounted->mnt_root);
1377 EXPORT_SYMBOL(follow_down_one);
1379 static inline int managed_dentry_rcu(const struct path *path)
1381 return (path->dentry->d_flags & DCACHE_MANAGE_TRANSIT) ?
1382 path->dentry->d_op->d_manage(path, true) : 0;
1386 * Try to skip to top of mountpoint pile in rcuwalk mode. Fail if
1387 * we meet a managed dentry that would need blocking.
1389 static bool __follow_mount_rcu(struct nameidata *nd, struct path *path,
1390 struct inode **inode, unsigned *seqp)
1393 struct mount *mounted;
1395 * Don't forget we might have a non-mountpoint managed dentry
1396 * that wants to block transit.
1398 switch (managed_dentry_rcu(path)) {
1408 if (!d_mountpoint(path->dentry))
1409 return !(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT);
1411 mounted = __lookup_mnt(path->mnt, path->dentry);
1414 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1416 path->mnt = &mounted->mnt;
1417 path->dentry = mounted->mnt.mnt_root;
1418 nd->flags |= LOOKUP_JUMPED;
1419 *seqp = read_seqcount_begin(&path->dentry->d_seq);
1421 * Update the inode too. We don't need to re-check the
1422 * dentry sequence number here after this d_inode read,
1423 * because a mount-point is always pinned.
1425 *inode = path->dentry->d_inode;
1427 return !read_seqretry(&mount_lock, nd->m_seq) &&
1428 !(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT);
1431 static int follow_dotdot_rcu(struct nameidata *nd)
1433 struct inode *inode = nd->inode;
1436 if (path_equal(&nd->path, &nd->root)) {
1437 if (unlikely(nd->flags & LOOKUP_BENEATH))
1441 if (nd->path.dentry != nd->path.mnt->mnt_root) {
1442 struct dentry *old = nd->path.dentry;
1443 struct dentry *parent = old->d_parent;
1446 inode = parent->d_inode;
1447 seq = read_seqcount_begin(&parent->d_seq);
1448 if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq)))
1450 nd->path.dentry = parent;
1452 if (unlikely(!path_connected(&nd->path)))
1456 struct mount *mnt = real_mount(nd->path.mnt);
1457 struct mount *mparent = mnt->mnt_parent;
1458 struct dentry *mountpoint = mnt->mnt_mountpoint;
1459 struct inode *inode2 = mountpoint->d_inode;
1460 unsigned seq = read_seqcount_begin(&mountpoint->d_seq);
1461 if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1463 if (&mparent->mnt == nd->path.mnt)
1465 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1467 /* we know that mountpoint was pinned */
1468 nd->path.dentry = mountpoint;
1469 nd->path.mnt = &mparent->mnt;
1474 while (unlikely(d_mountpoint(nd->path.dentry))) {
1475 struct mount *mounted;
1476 mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry);
1477 if (unlikely(read_seqretry(&mount_lock, nd->m_seq)))
1481 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1483 nd->path.mnt = &mounted->mnt;
1484 nd->path.dentry = mounted->mnt.mnt_root;
1485 inode = nd->path.dentry->d_inode;
1486 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
1493 * Follow down to the covering mount currently visible to userspace. At each
1494 * point, the filesystem owning that dentry may be queried as to whether the
1495 * caller is permitted to proceed or not.
1497 int follow_down(struct path *path)
1502 while (managed = READ_ONCE(path->dentry->d_flags),
1503 unlikely(managed & DCACHE_MANAGED_DENTRY)) {
1504 /* Allow the filesystem to manage the transit without i_mutex
1507 * We indicate to the filesystem if someone is trying to mount
1508 * something here. This gives autofs the chance to deny anyone
1509 * other than its daemon the right to mount on its
1512 * The filesystem may sleep at this point.
1514 if (managed & DCACHE_MANAGE_TRANSIT) {
1515 BUG_ON(!path->dentry->d_op);
1516 BUG_ON(!path->dentry->d_op->d_manage);
1517 ret = path->dentry->d_op->d_manage(path, false);
1519 return ret == -EISDIR ? 0 : ret;
1522 /* Transit to a mounted filesystem. */
1523 if (managed & DCACHE_MOUNTED) {
1524 struct vfsmount *mounted = lookup_mnt(path);
1529 path->mnt = mounted;
1530 path->dentry = dget(mounted->mnt_root);
1534 /* Don't handle automount points here */
1539 EXPORT_SYMBOL(follow_down);
1542 * Skip to top of mountpoint pile in refwalk mode for follow_dotdot()
1544 static void follow_mount(struct path *path)
1546 while (d_mountpoint(path->dentry)) {
1547 struct vfsmount *mounted = lookup_mnt(path);
1552 path->mnt = mounted;
1553 path->dentry = dget(mounted->mnt_root);
1557 static int path_parent_directory(struct path *path)
1559 struct dentry *old = path->dentry;
1560 /* rare case of legitimate dget_parent()... */
1561 path->dentry = dget_parent(path->dentry);
1563 if (unlikely(!path_connected(path)))
1568 static int follow_dotdot(struct nameidata *nd)
1571 if (path_equal(&nd->path, &nd->root)) {
1572 if (unlikely(nd->flags & LOOKUP_BENEATH))
1576 if (nd->path.dentry != nd->path.mnt->mnt_root) {
1577 int ret = path_parent_directory(&nd->path);
1582 if (!follow_up(&nd->path))
1584 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1587 follow_mount(&nd->path);
1588 nd->inode = nd->path.dentry->d_inode;
1593 * This looks up the name in dcache and possibly revalidates the found dentry.
1594 * NULL is returned if the dentry does not exist in the cache.
1596 static struct dentry *lookup_dcache(const struct qstr *name,
1600 struct dentry *dentry = d_lookup(dir, name);
1602 int error = d_revalidate(dentry, flags);
1603 if (unlikely(error <= 0)) {
1605 d_invalidate(dentry);
1607 return ERR_PTR(error);
1614 * Parent directory has inode locked exclusive. This is one
1615 * and only case when ->lookup() gets called on non in-lookup
1616 * dentries - as the matter of fact, this only gets called
1617 * when directory is guaranteed to have no in-lookup children
1620 static struct dentry *__lookup_hash(const struct qstr *name,
1621 struct dentry *base, unsigned int flags)
1623 struct dentry *dentry = lookup_dcache(name, base, flags);
1625 struct inode *dir = base->d_inode;
1630 /* Don't create child dentry for a dead directory. */
1631 if (unlikely(IS_DEADDIR(dir)))
1632 return ERR_PTR(-ENOENT);
1634 dentry = d_alloc(base, name);
1635 if (unlikely(!dentry))
1636 return ERR_PTR(-ENOMEM);
1638 old = dir->i_op->lookup(dir, dentry, flags);
1639 if (unlikely(old)) {
1646 static int lookup_fast(struct nameidata *nd,
1647 struct path *path, struct inode **inode,
1650 struct vfsmount *mnt = nd->path.mnt;
1651 struct dentry *dentry, *parent = nd->path.dentry;
1656 * Rename seqlock is not required here because in the off chance
1657 * of a false negative due to a concurrent rename, the caller is
1658 * going to fall back to non-racy lookup.
1660 if (nd->flags & LOOKUP_RCU) {
1663 dentry = __d_lookup_rcu(parent, &nd->last, &seq);
1664 if (unlikely(!dentry)) {
1665 if (unlazy_walk(nd))
1671 * This sequence count validates that the inode matches
1672 * the dentry name information from lookup.
1674 *inode = d_backing_inode(dentry);
1675 negative = d_is_negative(dentry);
1676 if (unlikely(read_seqcount_retry(&dentry->d_seq, seq)))
1680 * This sequence count validates that the parent had no
1681 * changes while we did the lookup of the dentry above.
1683 * The memory barrier in read_seqcount_begin of child is
1684 * enough, we can use __read_seqcount_retry here.
1686 if (unlikely(__read_seqcount_retry(&parent->d_seq, nd->seq)))
1690 status = d_revalidate(dentry, nd->flags);
1691 if (likely(status > 0)) {
1693 * Note: do negative dentry check after revalidation in
1694 * case that drops it.
1696 if (unlikely(negative))
1699 path->dentry = dentry;
1700 if (likely(__follow_mount_rcu(nd, path, inode, seqp)))
1703 if (unlazy_child(nd, dentry, seq))
1705 if (unlikely(status == -ECHILD))
1706 /* we'd been told to redo it in non-rcu mode */
1707 status = d_revalidate(dentry, nd->flags);
1709 dentry = __d_lookup(parent, &nd->last);
1710 if (unlikely(!dentry))
1712 status = d_revalidate(dentry, nd->flags);
1714 if (unlikely(status <= 0)) {
1716 d_invalidate(dentry);
1722 path->dentry = dentry;
1723 err = follow_managed(path, nd);
1724 if (likely(err > 0))
1725 *inode = d_backing_inode(path->dentry);
1729 /* Fast lookup failed, do it the slow way */
1730 static struct dentry *__lookup_slow(const struct qstr *name,
1734 struct dentry *dentry, *old;
1735 struct inode *inode = dir->d_inode;
1736 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
1738 /* Don't go there if it's already dead */
1739 if (unlikely(IS_DEADDIR(inode)))
1740 return ERR_PTR(-ENOENT);
1742 dentry = d_alloc_parallel(dir, name, &wq);
1745 if (unlikely(!d_in_lookup(dentry))) {
1746 int error = d_revalidate(dentry, flags);
1747 if (unlikely(error <= 0)) {
1749 d_invalidate(dentry);
1754 dentry = ERR_PTR(error);
1757 old = inode->i_op->lookup(inode, dentry, flags);
1758 d_lookup_done(dentry);
1759 if (unlikely(old)) {
1767 static struct dentry *lookup_slow(const struct qstr *name,
1771 struct inode *inode = dir->d_inode;
1773 inode_lock_shared(inode);
1774 res = __lookup_slow(name, dir, flags);
1775 inode_unlock_shared(inode);
1779 static inline int may_lookup(struct nameidata *nd)
1781 if (nd->flags & LOOKUP_RCU) {
1782 int err = inode_permission(nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
1785 if (unlazy_walk(nd))
1788 return inode_permission(nd->inode, MAY_EXEC);
1791 static inline int handle_dots(struct nameidata *nd, int type)
1793 if (type == LAST_DOTDOT) {
1796 if (!nd->root.mnt) {
1797 error = set_root(nd);
1801 if (nd->flags & LOOKUP_RCU)
1802 error = follow_dotdot_rcu(nd);
1804 error = follow_dotdot(nd);
1808 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
1810 * If there was a racing rename or mount along our
1811 * path, then we can't be sure that ".." hasn't jumped
1812 * above nd->root (and so userspace should retry or use
1816 if (unlikely(__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq)))
1818 if (unlikely(__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq)))
1825 static int pick_link(struct nameidata *nd, struct path *link,
1826 struct inode *inode, unsigned seq)
1830 if (unlikely(nd->total_link_count++ >= MAXSYMLINKS)) {
1831 path_to_nameidata(link, nd);
1834 if (!(nd->flags & LOOKUP_RCU)) {
1835 if (link->mnt == nd->path.mnt)
1838 error = nd_alloc_stack(nd);
1839 if (unlikely(error)) {
1840 if (error == -ECHILD) {
1841 if (unlikely(!legitimize_path(nd, link, seq))) {
1844 nd->flags &= ~LOOKUP_RCU;
1845 nd->path.mnt = NULL;
1846 nd->path.dentry = NULL;
1848 } else if (likely(unlazy_walk(nd)) == 0)
1849 error = nd_alloc_stack(nd);
1857 last = nd->stack + nd->depth++;
1859 clear_delayed_call(&last->done);
1860 nd->link_inode = inode;
1865 enum {WALK_FOLLOW = 1, WALK_MORE = 2};
1868 * Do we need to follow links? We _really_ want to be able
1869 * to do this check without having to look at inode->i_op,
1870 * so we keep a cache of "no, this doesn't need follow_link"
1871 * for the common case.
1873 static inline int step_into(struct nameidata *nd, struct path *path,
1874 int flags, struct inode *inode, unsigned seq)
1876 if (!(flags & WALK_MORE) && nd->depth)
1878 if (likely(!d_is_symlink(path->dentry)) ||
1879 !(flags & WALK_FOLLOW || nd->flags & LOOKUP_FOLLOW)) {
1880 /* not a symlink or should not follow */
1881 path_to_nameidata(path, nd);
1886 /* make sure that d_is_symlink above matches inode */
1887 if (nd->flags & LOOKUP_RCU) {
1888 if (read_seqcount_retry(&path->dentry->d_seq, seq))
1891 return pick_link(nd, path, inode, seq);
1894 static int walk_component(struct nameidata *nd, int flags)
1897 struct inode *inode;
1901 * "." and ".." are special - ".." especially so because it has
1902 * to be able to know about the current root directory and
1903 * parent relationships.
1905 if (unlikely(nd->last_type != LAST_NORM)) {
1906 err = handle_dots(nd, nd->last_type);
1907 if (!(flags & WALK_MORE) && nd->depth)
1911 err = lookup_fast(nd, &path, &inode, &seq);
1912 if (unlikely(err <= 0)) {
1915 path.dentry = lookup_slow(&nd->last, nd->path.dentry,
1917 if (IS_ERR(path.dentry))
1918 return PTR_ERR(path.dentry);
1920 path.mnt = nd->path.mnt;
1921 err = follow_managed(&path, nd);
1922 if (unlikely(err < 0))
1925 seq = 0; /* we are already out of RCU mode */
1926 inode = d_backing_inode(path.dentry);
1929 return step_into(nd, &path, flags, inode, seq);
1933 * We can do the critical dentry name comparison and hashing
1934 * operations one word at a time, but we are limited to:
1936 * - Architectures with fast unaligned word accesses. We could
1937 * do a "get_unaligned()" if this helps and is sufficiently
1940 * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
1941 * do not trap on the (extremely unlikely) case of a page
1942 * crossing operation.
1944 * - Furthermore, we need an efficient 64-bit compile for the
1945 * 64-bit case in order to generate the "number of bytes in
1946 * the final mask". Again, that could be replaced with a
1947 * efficient population count instruction or similar.
1949 #ifdef CONFIG_DCACHE_WORD_ACCESS
1951 #include <asm/word-at-a-time.h>
1955 /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
1957 #elif defined(CONFIG_64BIT)
1959 * Register pressure in the mixing function is an issue, particularly
1960 * on 32-bit x86, but almost any function requires one state value and
1961 * one temporary. Instead, use a function designed for two state values
1962 * and no temporaries.
1964 * This function cannot create a collision in only two iterations, so
1965 * we have two iterations to achieve avalanche. In those two iterations,
1966 * we have six layers of mixing, which is enough to spread one bit's
1967 * influence out to 2^6 = 64 state bits.
1969 * Rotate constants are scored by considering either 64 one-bit input
1970 * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
1971 * probability of that delta causing a change to each of the 128 output
1972 * bits, using a sample of random initial states.
1974 * The Shannon entropy of the computed probabilities is then summed
1975 * to produce a score. Ideally, any input change has a 50% chance of
1976 * toggling any given output bit.
1978 * Mixing scores (in bits) for (12,45):
1979 * Input delta: 1-bit 2-bit
1980 * 1 round: 713.3 42542.6
1981 * 2 rounds: 2753.7 140389.8
1982 * 3 rounds: 5954.1 233458.2
1983 * 4 rounds: 7862.6 256672.2
1984 * Perfect: 8192 258048
1985 * (64*128) (64*63/2 * 128)
1987 #define HASH_MIX(x, y, a) \
1989 y ^= x, x = rol64(x,12),\
1990 x += y, y = rol64(y,45),\
1994 * Fold two longs into one 32-bit hash value. This must be fast, but
1995 * latency isn't quite as critical, as there is a fair bit of additional
1996 * work done before the hash value is used.
1998 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2000 y ^= x * GOLDEN_RATIO_64;
2001 y *= GOLDEN_RATIO_64;
2005 #else /* 32-bit case */
2008 * Mixing scores (in bits) for (7,20):
2009 * Input delta: 1-bit 2-bit
2010 * 1 round: 330.3 9201.6
2011 * 2 rounds: 1246.4 25475.4
2012 * 3 rounds: 1907.1 31295.1
2013 * 4 rounds: 2042.3 31718.6
2014 * Perfect: 2048 31744
2015 * (32*64) (32*31/2 * 64)
2017 #define HASH_MIX(x, y, a) \
2019 y ^= x, x = rol32(x, 7),\
2020 x += y, y = rol32(y,20),\
2023 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2025 /* Use arch-optimized multiply if one exists */
2026 return __hash_32(y ^ __hash_32(x));
2032 * Return the hash of a string of known length. This is carfully
2033 * designed to match hash_name(), which is the more critical function.
2034 * In particular, we must end by hashing a final word containing 0..7
2035 * payload bytes, to match the way that hash_name() iterates until it
2036 * finds the delimiter after the name.
2038 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2040 unsigned long a, x = 0, y = (unsigned long)salt;
2045 a = load_unaligned_zeropad(name);
2046 if (len < sizeof(unsigned long))
2049 name += sizeof(unsigned long);
2050 len -= sizeof(unsigned long);
2052 x ^= a & bytemask_from_count(len);
2054 return fold_hash(x, y);
2056 EXPORT_SYMBOL(full_name_hash);
2058 /* Return the "hash_len" (hash and length) of a null-terminated string */
2059 u64 hashlen_string(const void *salt, const char *name)
2061 unsigned long a = 0, x = 0, y = (unsigned long)salt;
2062 unsigned long adata, mask, len;
2063 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2070 len += sizeof(unsigned long);
2072 a = load_unaligned_zeropad(name+len);
2073 } while (!has_zero(a, &adata, &constants));
2075 adata = prep_zero_mask(a, adata, &constants);
2076 mask = create_zero_mask(adata);
2077 x ^= a & zero_bytemask(mask);
2079 return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2081 EXPORT_SYMBOL(hashlen_string);
2084 * Calculate the length and hash of the path component, and
2085 * return the "hash_len" as the result.
2087 static inline u64 hash_name(const void *salt, const char *name)
2089 unsigned long a = 0, b, x = 0, y = (unsigned long)salt;
2090 unsigned long adata, bdata, mask, len;
2091 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2098 len += sizeof(unsigned long);
2100 a = load_unaligned_zeropad(name+len);
2101 b = a ^ REPEAT_BYTE('/');
2102 } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2104 adata = prep_zero_mask(a, adata, &constants);
2105 bdata = prep_zero_mask(b, bdata, &constants);
2106 mask = create_zero_mask(adata | bdata);
2107 x ^= a & zero_bytemask(mask);
2109 return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2112 #else /* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2114 /* Return the hash of a string of known length */
2115 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2117 unsigned long hash = init_name_hash(salt);
2119 hash = partial_name_hash((unsigned char)*name++, hash);
2120 return end_name_hash(hash);
2122 EXPORT_SYMBOL(full_name_hash);
2124 /* Return the "hash_len" (hash and length) of a null-terminated string */
2125 u64 hashlen_string(const void *salt, const char *name)
2127 unsigned long hash = init_name_hash(salt);
2128 unsigned long len = 0, c;
2130 c = (unsigned char)*name;
2133 hash = partial_name_hash(c, hash);
2134 c = (unsigned char)name[len];
2136 return hashlen_create(end_name_hash(hash), len);
2138 EXPORT_SYMBOL(hashlen_string);
2141 * We know there's a real path component here of at least
2144 static inline u64 hash_name(const void *salt, const char *name)
2146 unsigned long hash = init_name_hash(salt);
2147 unsigned long len = 0, c;
2149 c = (unsigned char)*name;
2152 hash = partial_name_hash(c, hash);
2153 c = (unsigned char)name[len];
2154 } while (c && c != '/');
2155 return hashlen_create(end_name_hash(hash), len);
2162 * This is the basic name resolution function, turning a pathname into
2163 * the final dentry. We expect 'base' to be positive and a directory.
2165 * Returns 0 and nd will have valid dentry and mnt on success.
2166 * Returns error and drops reference to input namei data on failure.
2168 static int link_path_walk(const char *name, struct nameidata *nd)
2173 return PTR_ERR(name);
2179 /* At this point we know we have a real path component. */
2184 err = may_lookup(nd);
2188 hash_len = hash_name(nd->path.dentry, name);
2191 if (name[0] == '.') switch (hashlen_len(hash_len)) {
2193 if (name[1] == '.') {
2195 nd->flags |= LOOKUP_JUMPED;
2201 if (likely(type == LAST_NORM)) {
2202 struct dentry *parent = nd->path.dentry;
2203 nd->flags &= ~LOOKUP_JUMPED;
2204 if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2205 struct qstr this = { { .hash_len = hash_len }, .name = name };
2206 err = parent->d_op->d_hash(parent, &this);
2209 hash_len = this.hash_len;
2214 nd->last.hash_len = hash_len;
2215 nd->last.name = name;
2216 nd->last_type = type;
2218 name += hashlen_len(hash_len);
2222 * If it wasn't NUL, we know it was '/'. Skip that
2223 * slash, and continue until no more slashes.
2227 } while (unlikely(*name == '/'));
2228 if (unlikely(!*name)) {
2230 /* pathname body, done */
2233 name = nd->stack[nd->depth - 1].name;
2234 /* trailing symlink, done */
2237 /* last component of nested symlink */
2238 err = walk_component(nd, WALK_FOLLOW);
2240 /* not the last component */
2241 err = walk_component(nd, WALK_FOLLOW | WALK_MORE);
2247 const char *s = get_link(nd);
2256 nd->stack[nd->depth - 1].name = name;
2261 if (unlikely(!d_can_lookup(nd->path.dentry))) {
2262 if (nd->flags & LOOKUP_RCU) {
2263 if (unlazy_walk(nd))
2271 /* must be paired with terminate_walk() */
2272 static const char *path_init(struct nameidata *nd, unsigned flags)
2275 const char *s = nd->name->name;
2278 flags &= ~LOOKUP_RCU;
2279 if (flags & LOOKUP_RCU)
2282 nd->last_type = LAST_ROOT; /* if there are only slashes... */
2283 nd->flags = flags | LOOKUP_JUMPED | LOOKUP_PARENT;
2286 nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2287 nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2290 if (flags & LOOKUP_ROOT) {
2291 struct dentry *root = nd->root.dentry;
2292 struct inode *inode = root->d_inode;
2293 if (*s && unlikely(!d_can_lookup(root)))
2294 return ERR_PTR(-ENOTDIR);
2295 nd->path = nd->root;
2297 if (flags & LOOKUP_RCU) {
2298 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2299 nd->root_seq = nd->seq;
2301 path_get(&nd->path);
2306 nd->root.mnt = NULL;
2307 nd->path.mnt = NULL;
2308 nd->path.dentry = NULL;
2310 /* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
2311 if (*s == '/' && !(flags & LOOKUP_IN_ROOT)) {
2312 error = nd_jump_root(nd);
2313 if (unlikely(error))
2314 return ERR_PTR(error);
2318 /* Relative pathname -- get the starting-point it is relative to. */
2319 if (nd->dfd == AT_FDCWD) {
2320 if (flags & LOOKUP_RCU) {
2321 struct fs_struct *fs = current->fs;
2325 seq = read_seqcount_begin(&fs->seq);
2327 nd->inode = nd->path.dentry->d_inode;
2328 nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2329 } while (read_seqcount_retry(&fs->seq, seq));
2331 get_fs_pwd(current->fs, &nd->path);
2332 nd->inode = nd->path.dentry->d_inode;
2335 /* Caller must check execute permissions on the starting path component */
2336 struct fd f = fdget_raw(nd->dfd);
2337 struct dentry *dentry;
2340 return ERR_PTR(-EBADF);
2342 dentry = f.file->f_path.dentry;
2344 if (*s && unlikely(!d_can_lookup(dentry))) {
2346 return ERR_PTR(-ENOTDIR);
2349 nd->path = f.file->f_path;
2350 if (flags & LOOKUP_RCU) {
2351 nd->inode = nd->path.dentry->d_inode;
2352 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2354 path_get(&nd->path);
2355 nd->inode = nd->path.dentry->d_inode;
2360 /* For scoped-lookups we need to set the root to the dirfd as well. */
2361 if (flags & LOOKUP_IS_SCOPED) {
2362 nd->root = nd->path;
2363 if (flags & LOOKUP_RCU) {
2364 nd->root_seq = nd->seq;
2366 path_get(&nd->root);
2367 nd->flags |= LOOKUP_ROOT_GRABBED;
2373 static const char *trailing_symlink(struct nameidata *nd)
2376 int error = may_follow_link(nd);
2377 if (unlikely(error))
2378 return ERR_PTR(error);
2379 nd->flags |= LOOKUP_PARENT;
2380 nd->stack[0].name = NULL;
2385 static inline int lookup_last(struct nameidata *nd)
2387 if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2388 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2390 nd->flags &= ~LOOKUP_PARENT;
2391 return walk_component(nd, 0);
2394 static int handle_lookup_down(struct nameidata *nd)
2396 struct path path = nd->path;
2397 struct inode *inode = nd->inode;
2398 unsigned seq = nd->seq;
2401 if (nd->flags & LOOKUP_RCU) {
2403 * don't bother with unlazy_walk on failure - we are
2404 * at the very beginning of walk, so we lose nothing
2405 * if we simply redo everything in non-RCU mode
2407 if (unlikely(!__follow_mount_rcu(nd, &path, &inode, &seq)))
2411 err = follow_managed(&path, nd);
2412 if (unlikely(err < 0))
2414 inode = d_backing_inode(path.dentry);
2417 path_to_nameidata(&path, nd);
2423 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2424 static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
2426 const char *s = path_init(nd, flags);
2429 if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
2430 err = handle_lookup_down(nd);
2431 if (unlikely(err < 0))
2435 while (!(err = link_path_walk(s, nd))
2436 && ((err = lookup_last(nd)) > 0)) {
2437 s = trailing_symlink(nd);
2440 err = complete_walk(nd);
2442 if (!err && nd->flags & LOOKUP_DIRECTORY)
2443 if (!d_can_lookup(nd->path.dentry))
2447 nd->path.mnt = NULL;
2448 nd->path.dentry = NULL;
2454 int filename_lookup(int dfd, struct filename *name, unsigned flags,
2455 struct path *path, struct path *root)
2458 struct nameidata nd;
2460 return PTR_ERR(name);
2461 if (unlikely(root)) {
2463 flags |= LOOKUP_ROOT;
2465 set_nameidata(&nd, dfd, name);
2466 retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2467 if (unlikely(retval == -ECHILD))
2468 retval = path_lookupat(&nd, flags, path);
2469 if (unlikely(retval == -ESTALE))
2470 retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2472 if (likely(!retval))
2473 audit_inode(name, path->dentry, 0);
2474 restore_nameidata();
2479 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
2480 static int path_parentat(struct nameidata *nd, unsigned flags,
2481 struct path *parent)
2483 const char *s = path_init(nd, flags);
2484 int err = link_path_walk(s, nd);
2486 err = complete_walk(nd);
2489 nd->path.mnt = NULL;
2490 nd->path.dentry = NULL;
2496 static struct filename *filename_parentat(int dfd, struct filename *name,
2497 unsigned int flags, struct path *parent,
2498 struct qstr *last, int *type)
2501 struct nameidata nd;
2505 set_nameidata(&nd, dfd, name);
2506 retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
2507 if (unlikely(retval == -ECHILD))
2508 retval = path_parentat(&nd, flags, parent);
2509 if (unlikely(retval == -ESTALE))
2510 retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2511 if (likely(!retval)) {
2513 *type = nd.last_type;
2514 audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
2517 name = ERR_PTR(retval);
2519 restore_nameidata();
2523 /* does lookup, returns the object with parent locked */
2524 struct dentry *kern_path_locked(const char *name, struct path *path)
2526 struct filename *filename;
2531 filename = filename_parentat(AT_FDCWD, getname_kernel(name), 0, path,
2533 if (IS_ERR(filename))
2534 return ERR_CAST(filename);
2535 if (unlikely(type != LAST_NORM)) {
2538 return ERR_PTR(-EINVAL);
2540 inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
2541 d = __lookup_hash(&last, path->dentry, 0);
2543 inode_unlock(path->dentry->d_inode);
2550 int kern_path(const char *name, unsigned int flags, struct path *path)
2552 return filename_lookup(AT_FDCWD, getname_kernel(name),
2555 EXPORT_SYMBOL(kern_path);
2558 * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
2559 * @dentry: pointer to dentry of the base directory
2560 * @mnt: pointer to vfs mount of the base directory
2561 * @name: pointer to file name
2562 * @flags: lookup flags
2563 * @path: pointer to struct path to fill
2565 int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
2566 const char *name, unsigned int flags,
2569 struct path root = {.mnt = mnt, .dentry = dentry};
2570 /* the first argument of filename_lookup() is ignored with root */
2571 return filename_lookup(AT_FDCWD, getname_kernel(name),
2572 flags , path, &root);
2574 EXPORT_SYMBOL(vfs_path_lookup);
2576 static int lookup_one_len_common(const char *name, struct dentry *base,
2577 int len, struct qstr *this)
2581 this->hash = full_name_hash(base, name, len);
2585 if (unlikely(name[0] == '.')) {
2586 if (len < 2 || (len == 2 && name[1] == '.'))
2591 unsigned int c = *(const unsigned char *)name++;
2592 if (c == '/' || c == '\0')
2596 * See if the low-level filesystem might want
2597 * to use its own hash..
2599 if (base->d_flags & DCACHE_OP_HASH) {
2600 int err = base->d_op->d_hash(base, this);
2605 return inode_permission(base->d_inode, MAY_EXEC);
2609 * try_lookup_one_len - filesystem helper to lookup single pathname component
2610 * @name: pathname component to lookup
2611 * @base: base directory to lookup from
2612 * @len: maximum length @len should be interpreted to
2614 * Look up a dentry by name in the dcache, returning NULL if it does not
2615 * currently exist. The function does not try to create a dentry.
2617 * Note that this routine is purely a helper for filesystem usage and should
2618 * not be called by generic code.
2620 * The caller must hold base->i_mutex.
2622 struct dentry *try_lookup_one_len(const char *name, struct dentry *base, int len)
2627 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2629 err = lookup_one_len_common(name, base, len, &this);
2631 return ERR_PTR(err);
2633 return lookup_dcache(&this, base, 0);
2635 EXPORT_SYMBOL(try_lookup_one_len);
2638 * lookup_one_len - filesystem helper to lookup single pathname component
2639 * @name: pathname component to lookup
2640 * @base: base directory to lookup from
2641 * @len: maximum length @len should be interpreted to
2643 * Note that this routine is purely a helper for filesystem usage and should
2644 * not be called by generic code.
2646 * The caller must hold base->i_mutex.
2648 struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2650 struct dentry *dentry;
2654 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
2656 err = lookup_one_len_common(name, base, len, &this);
2658 return ERR_PTR(err);
2660 dentry = lookup_dcache(&this, base, 0);
2661 return dentry ? dentry : __lookup_slow(&this, base, 0);
2663 EXPORT_SYMBOL(lookup_one_len);
2666 * lookup_one_len_unlocked - filesystem helper to lookup single pathname component
2667 * @name: pathname component to lookup
2668 * @base: base directory to lookup from
2669 * @len: maximum length @len should be interpreted to
2671 * Note that this routine is purely a helper for filesystem usage and should
2672 * not be called by generic code.
2674 * Unlike lookup_one_len, it should be called without the parent
2675 * i_mutex held, and will take the i_mutex itself if necessary.
2677 struct dentry *lookup_one_len_unlocked(const char *name,
2678 struct dentry *base, int len)
2684 err = lookup_one_len_common(name, base, len, &this);
2686 return ERR_PTR(err);
2688 ret = lookup_dcache(&this, base, 0);
2690 ret = lookup_slow(&this, base, 0);
2693 EXPORT_SYMBOL(lookup_one_len_unlocked);
2696 * Like lookup_one_len_unlocked(), except that it yields ERR_PTR(-ENOENT)
2697 * on negatives. Returns known positive or ERR_PTR(); that's what
2698 * most of the users want. Note that pinned negative with unlocked parent
2699 * _can_ become positive at any time, so callers of lookup_one_len_unlocked()
2700 * need to be very careful; pinned positives have ->d_inode stable, so
2701 * this one avoids such problems.
2703 struct dentry *lookup_positive_unlocked(const char *name,
2704 struct dentry *base, int len)
2706 struct dentry *ret = lookup_one_len_unlocked(name, base, len);
2707 if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
2709 ret = ERR_PTR(-ENOENT);
2713 EXPORT_SYMBOL(lookup_positive_unlocked);
2715 #ifdef CONFIG_UNIX98_PTYS
2716 int path_pts(struct path *path)
2718 /* Find something mounted on "pts" in the same directory as
2721 struct dentry *child, *parent;
2725 ret = path_parent_directory(path);
2729 parent = path->dentry;
2732 child = d_hash_and_lookup(parent, &this);
2736 path->dentry = child;
2743 int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
2744 struct path *path, int *empty)
2746 return filename_lookup(dfd, getname_flags(name, flags, empty),
2749 EXPORT_SYMBOL(user_path_at_empty);
2752 * path_mountpoint - look up a path to be umounted
2753 * @nd: lookup context
2754 * @flags: lookup flags
2755 * @path: pointer to container for result
2757 * Look up the given name, but don't attempt to revalidate the last component.
2758 * Returns 0 and "path" will be valid on success; Returns error otherwise.
2761 path_mountpoint(struct nameidata *nd, unsigned flags, struct path *path)
2763 const char *s = path_init(nd, flags);
2766 while (!(err = link_path_walk(s, nd)) &&
2767 (err = lookup_last(nd)) > 0) {
2768 s = trailing_symlink(nd);
2770 if (!err && (nd->flags & LOOKUP_RCU))
2771 err = unlazy_walk(nd);
2773 err = handle_lookup_down(nd);
2776 nd->path.mnt = NULL;
2777 nd->path.dentry = NULL;
2784 filename_mountpoint(int dfd, struct filename *name, struct path *path,
2787 struct nameidata nd;
2790 return PTR_ERR(name);
2791 set_nameidata(&nd, dfd, name);
2792 error = path_mountpoint(&nd, flags | LOOKUP_RCU, path);
2793 if (unlikely(error == -ECHILD))
2794 error = path_mountpoint(&nd, flags, path);
2795 if (unlikely(error == -ESTALE))
2796 error = path_mountpoint(&nd, flags | LOOKUP_REVAL, path);
2798 audit_inode(name, path->dentry, AUDIT_INODE_NOEVAL);
2799 restore_nameidata();
2805 * user_path_mountpoint_at - lookup a path from userland in order to umount it
2806 * @dfd: directory file descriptor
2807 * @name: pathname from userland
2808 * @flags: lookup flags
2809 * @path: pointer to container to hold result
2811 * A umount is a special case for path walking. We're not actually interested
2812 * in the inode in this situation, and ESTALE errors can be a problem. We
2813 * simply want track down the dentry and vfsmount attached at the mountpoint
2814 * and avoid revalidating the last component.
2816 * Returns 0 and populates "path" on success.
2819 user_path_mountpoint_at(int dfd, const char __user *name, unsigned int flags,
2822 return filename_mountpoint(dfd, getname(name), path, flags);
2826 kern_path_mountpoint(int dfd, const char *name, struct path *path,
2829 return filename_mountpoint(dfd, getname_kernel(name), path, flags);
2831 EXPORT_SYMBOL(kern_path_mountpoint);
2833 int __check_sticky(struct inode *dir, struct inode *inode)
2835 kuid_t fsuid = current_fsuid();
2837 if (uid_eq(inode->i_uid, fsuid))
2839 if (uid_eq(dir->i_uid, fsuid))
2841 return !capable_wrt_inode_uidgid(inode, CAP_FOWNER);
2843 EXPORT_SYMBOL(__check_sticky);
2846 * Check whether we can remove a link victim from directory dir, check
2847 * whether the type of victim is right.
2848 * 1. We can't do it if dir is read-only (done in permission())
2849 * 2. We should have write and exec permissions on dir
2850 * 3. We can't remove anything from append-only dir
2851 * 4. We can't do anything with immutable dir (done in permission())
2852 * 5. If the sticky bit on dir is set we should either
2853 * a. be owner of dir, or
2854 * b. be owner of victim, or
2855 * c. have CAP_FOWNER capability
2856 * 6. If the victim is append-only or immutable we can't do antyhing with
2857 * links pointing to it.
2858 * 7. If the victim has an unknown uid or gid we can't change the inode.
2859 * 8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
2860 * 9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
2861 * 10. We can't remove a root or mountpoint.
2862 * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
2863 * nfs_async_unlink().
2865 static int may_delete(struct inode *dir, struct dentry *victim, bool isdir)
2867 struct inode *inode = d_backing_inode(victim);
2870 if (d_is_negative(victim))
2874 BUG_ON(victim->d_parent->d_inode != dir);
2876 /* Inode writeback is not safe when the uid or gid are invalid. */
2877 if (!uid_valid(inode->i_uid) || !gid_valid(inode->i_gid))
2880 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
2882 error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
2888 if (check_sticky(dir, inode) || IS_APPEND(inode) ||
2889 IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) || HAS_UNMAPPED_ID(inode))
2892 if (!d_is_dir(victim))
2894 if (IS_ROOT(victim))
2896 } else if (d_is_dir(victim))
2898 if (IS_DEADDIR(dir))
2900 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
2905 /* Check whether we can create an object with dentry child in directory
2907 * 1. We can't do it if child already exists (open has special treatment for
2908 * this case, but since we are inlined it's OK)
2909 * 2. We can't do it if dir is read-only (done in permission())
2910 * 3. We can't do it if the fs can't represent the fsuid or fsgid.
2911 * 4. We should have write and exec permissions on dir
2912 * 5. We can't do it if dir is immutable (done in permission())
2914 static inline int may_create(struct inode *dir, struct dentry *child)
2916 struct user_namespace *s_user_ns;
2917 audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
2920 if (IS_DEADDIR(dir))
2922 s_user_ns = dir->i_sb->s_user_ns;
2923 if (!kuid_has_mapping(s_user_ns, current_fsuid()) ||
2924 !kgid_has_mapping(s_user_ns, current_fsgid()))
2926 return inode_permission(dir, MAY_WRITE | MAY_EXEC);
2930 * p1 and p2 should be directories on the same fs.
2932 struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
2937 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2941 mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
2943 p = d_ancestor(p2, p1);
2945 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
2946 inode_lock_nested(p1->d_inode, I_MUTEX_CHILD);
2950 p = d_ancestor(p1, p2);
2952 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2953 inode_lock_nested(p2->d_inode, I_MUTEX_CHILD);
2957 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
2958 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
2961 EXPORT_SYMBOL(lock_rename);
2963 void unlock_rename(struct dentry *p1, struct dentry *p2)
2965 inode_unlock(p1->d_inode);
2967 inode_unlock(p2->d_inode);
2968 mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
2971 EXPORT_SYMBOL(unlock_rename);
2973 int vfs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2976 int error = may_create(dir, dentry);
2980 if (!dir->i_op->create)
2981 return -EACCES; /* shouldn't it be ENOSYS? */
2984 error = security_inode_create(dir, dentry, mode);
2987 error = dir->i_op->create(dir, dentry, mode, want_excl);
2989 fsnotify_create(dir, dentry);
2992 EXPORT_SYMBOL(vfs_create);
2994 int vfs_mkobj(struct dentry *dentry, umode_t mode,
2995 int (*f)(struct dentry *, umode_t, void *),
2998 struct inode *dir = dentry->d_parent->d_inode;
2999 int error = may_create(dir, dentry);
3005 error = security_inode_create(dir, dentry, mode);
3008 error = f(dentry, mode, arg);
3010 fsnotify_create(dir, dentry);
3013 EXPORT_SYMBOL(vfs_mkobj);
3015 bool may_open_dev(const struct path *path)
3017 return !(path->mnt->mnt_flags & MNT_NODEV) &&
3018 !(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
3021 static int may_open(const struct path *path, int acc_mode, int flag)
3023 struct dentry *dentry = path->dentry;
3024 struct inode *inode = dentry->d_inode;
3030 switch (inode->i_mode & S_IFMT) {
3034 if (acc_mode & MAY_WRITE)
3039 if (!may_open_dev(path))
3048 error = inode_permission(inode, MAY_OPEN | acc_mode);
3053 * An append-only file must be opened in append mode for writing.
3055 if (IS_APPEND(inode)) {
3056 if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
3062 /* O_NOATIME can only be set by the owner or superuser */
3063 if (flag & O_NOATIME && !inode_owner_or_capable(inode))
3069 static int handle_truncate(struct file *filp)
3071 const struct path *path = &filp->f_path;
3072 struct inode *inode = path->dentry->d_inode;
3073 int error = get_write_access(inode);
3077 * Refuse to truncate files with mandatory locks held on them.
3079 error = locks_verify_locked(filp);
3081 error = security_path_truncate(path);
3083 error = do_truncate(path->dentry, 0,
3084 ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
3087 put_write_access(inode);
3091 static inline int open_to_namei_flags(int flag)
3093 if ((flag & O_ACCMODE) == 3)
3098 static int may_o_create(const struct path *dir, struct dentry *dentry, umode_t mode)
3100 struct user_namespace *s_user_ns;
3101 int error = security_path_mknod(dir, dentry, mode, 0);
3105 s_user_ns = dir->dentry->d_sb->s_user_ns;
3106 if (!kuid_has_mapping(s_user_ns, current_fsuid()) ||
3107 !kgid_has_mapping(s_user_ns, current_fsgid()))
3110 error = inode_permission(dir->dentry->d_inode, MAY_WRITE | MAY_EXEC);
3114 return security_inode_create(dir->dentry->d_inode, dentry, mode);
3118 * Attempt to atomically look up, create and open a file from a negative
3121 * Returns 0 if successful. The file will have been created and attached to
3122 * @file by the filesystem calling finish_open().
3124 * If the file was looked up only or didn't need creating, FMODE_OPENED won't
3125 * be set. The caller will need to perform the open themselves. @path will
3126 * have been updated to point to the new dentry. This may be negative.
3128 * Returns an error code otherwise.
3130 static int atomic_open(struct nameidata *nd, struct dentry *dentry,
3131 struct path *path, struct file *file,
3132 const struct open_flags *op,
3133 int open_flag, umode_t mode)
3135 struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
3136 struct inode *dir = nd->path.dentry->d_inode;
3139 if (!(~open_flag & (O_EXCL | O_CREAT))) /* both O_EXCL and O_CREAT */
3140 open_flag &= ~O_TRUNC;
3142 if (nd->flags & LOOKUP_DIRECTORY)
3143 open_flag |= O_DIRECTORY;
3145 file->f_path.dentry = DENTRY_NOT_SET;
3146 file->f_path.mnt = nd->path.mnt;
3147 error = dir->i_op->atomic_open(dir, dentry, file,
3148 open_to_namei_flags(open_flag), mode);
3149 d_lookup_done(dentry);
3151 if (file->f_mode & FMODE_OPENED) {
3153 * We didn't have the inode before the open, so check open
3156 int acc_mode = op->acc_mode;
3157 if (file->f_mode & FMODE_CREATED) {
3158 WARN_ON(!(open_flag & O_CREAT));
3159 fsnotify_create(dir, dentry);
3162 error = may_open(&file->f_path, acc_mode, open_flag);
3163 if (WARN_ON(error > 0))
3165 } else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
3168 if (file->f_path.dentry) {
3170 dentry = file->f_path.dentry;
3172 if (file->f_mode & FMODE_CREATED)
3173 fsnotify_create(dir, dentry);
3174 if (unlikely(d_is_negative(dentry))) {
3177 path->dentry = dentry;
3178 path->mnt = nd->path.mnt;
3188 * Look up and maybe create and open the last component.
3190 * Must be called with parent locked (exclusive in O_CREAT case).
3192 * Returns 0 on success, that is, if
3193 * the file was successfully atomically created (if necessary) and opened, or
3194 * the file was not completely opened at this time, though lookups and
3195 * creations were performed.
3196 * These case are distinguished by presence of FMODE_OPENED on file->f_mode.
3197 * In the latter case dentry returned in @path might be negative if O_CREAT
3198 * hadn't been specified.
3200 * An error code is returned on failure.
3202 static int lookup_open(struct nameidata *nd, struct path *path,
3204 const struct open_flags *op,
3207 struct dentry *dir = nd->path.dentry;
3208 struct inode *dir_inode = dir->d_inode;
3209 int open_flag = op->open_flag;
3210 struct dentry *dentry;
3211 int error, create_error = 0;
3212 umode_t mode = op->mode;
3213 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
3215 if (unlikely(IS_DEADDIR(dir_inode)))
3218 file->f_mode &= ~FMODE_CREATED;
3219 dentry = d_lookup(dir, &nd->last);
3222 dentry = d_alloc_parallel(dir, &nd->last, &wq);
3224 return PTR_ERR(dentry);
3226 if (d_in_lookup(dentry))
3229 error = d_revalidate(dentry, nd->flags);
3230 if (likely(error > 0))
3234 d_invalidate(dentry);
3238 if (dentry->d_inode) {
3239 /* Cached positive dentry: will open in f_op->open */
3244 * Checking write permission is tricky, bacuse we don't know if we are
3245 * going to actually need it: O_CREAT opens should work as long as the
3246 * file exists. But checking existence breaks atomicity. The trick is
3247 * to check access and if not granted clear O_CREAT from the flags.
3249 * Another problem is returing the "right" error value (e.g. for an
3250 * O_EXCL open we want to return EEXIST not EROFS).
3252 if (open_flag & O_CREAT) {
3253 if (!IS_POSIXACL(dir->d_inode))
3254 mode &= ~current_umask();
3255 if (unlikely(!got_write)) {
3256 create_error = -EROFS;
3257 open_flag &= ~O_CREAT;
3258 if (open_flag & (O_EXCL | O_TRUNC))
3260 /* No side effects, safe to clear O_CREAT */
3262 create_error = may_o_create(&nd->path, dentry, mode);
3264 open_flag &= ~O_CREAT;
3265 if (open_flag & O_EXCL)
3269 } else if ((open_flag & (O_TRUNC|O_WRONLY|O_RDWR)) &&
3270 unlikely(!got_write)) {
3272 * No O_CREATE -> atomicity not a requirement -> fall
3273 * back to lookup + open
3278 if (dir_inode->i_op->atomic_open) {
3279 error = atomic_open(nd, dentry, path, file, op, open_flag,
3281 if (unlikely(error == -ENOENT) && create_error)
3282 error = create_error;
3287 if (d_in_lookup(dentry)) {
3288 struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
3290 d_lookup_done(dentry);
3291 if (unlikely(res)) {
3293 error = PTR_ERR(res);
3301 /* Negative dentry, just create the file */
3302 if (!dentry->d_inode && (open_flag & O_CREAT)) {
3303 file->f_mode |= FMODE_CREATED;
3304 audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
3305 if (!dir_inode->i_op->create) {
3309 error = dir_inode->i_op->create(dir_inode, dentry, mode,
3310 open_flag & O_EXCL);
3313 fsnotify_create(dir_inode, dentry);
3315 if (unlikely(create_error) && !dentry->d_inode) {
3316 error = create_error;
3320 path->dentry = dentry;
3321 path->mnt = nd->path.mnt;
3330 * Handle the last step of open()
3332 static int do_last(struct nameidata *nd,
3333 struct file *file, const struct open_flags *op)
3335 struct dentry *dir = nd->path.dentry;
3336 kuid_t dir_uid = nd->inode->i_uid;
3337 umode_t dir_mode = nd->inode->i_mode;
3338 int open_flag = op->open_flag;
3339 bool will_truncate = (open_flag & O_TRUNC) != 0;
3340 bool got_write = false;
3341 int acc_mode = op->acc_mode;
3343 struct inode *inode;
3347 nd->flags &= ~LOOKUP_PARENT;
3348 nd->flags |= op->intent;
3350 if (nd->last_type != LAST_NORM) {
3351 error = handle_dots(nd, nd->last_type);
3352 if (unlikely(error))
3357 if (!(open_flag & O_CREAT)) {
3358 if (nd->last.name[nd->last.len])
3359 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
3360 /* we _can_ be in RCU mode here */
3361 error = lookup_fast(nd, &path, &inode, &seq);
3362 if (likely(error > 0))
3368 BUG_ON(nd->inode != dir->d_inode);
3369 BUG_ON(nd->flags & LOOKUP_RCU);
3371 /* create side of things */
3373 * This will *only* deal with leaving RCU mode - LOOKUP_JUMPED
3374 * has been cleared when we got to the last component we are
3377 error = complete_walk(nd);
3381 audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
3382 /* trailing slashes? */
3383 if (unlikely(nd->last.name[nd->last.len]))
3387 if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
3388 error = mnt_want_write(nd->path.mnt);
3392 * do _not_ fail yet - we might not need that or fail with
3393 * a different error; let lookup_open() decide; we'll be
3394 * dropping this one anyway.
3397 if (open_flag & O_CREAT)
3398 inode_lock(dir->d_inode);
3400 inode_lock_shared(dir->d_inode);
3401 error = lookup_open(nd, &path, file, op, got_write);
3402 if (open_flag & O_CREAT)
3403 inode_unlock(dir->d_inode);
3405 inode_unlock_shared(dir->d_inode);
3410 if (file->f_mode & FMODE_OPENED) {
3411 if ((file->f_mode & FMODE_CREATED) ||
3412 !S_ISREG(file_inode(file)->i_mode))
3413 will_truncate = false;
3415 audit_inode(nd->name, file->f_path.dentry, 0);
3419 if (file->f_mode & FMODE_CREATED) {
3420 /* Don't check for write permission, don't truncate */
3421 open_flag &= ~O_TRUNC;
3422 will_truncate = false;
3424 path_to_nameidata(&path, nd);
3425 goto finish_open_created;
3429 * If atomic_open() acquired write access it is dropped now due to
3430 * possible mount and symlink following (this might be optimized away if
3434 mnt_drop_write(nd->path.mnt);
3438 error = follow_managed(&path, nd);
3439 if (unlikely(error < 0))
3443 * create/update audit record if it already exists.
3445 audit_inode(nd->name, path.dentry, 0);
3447 if (unlikely((open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT))) {
3448 path_to_nameidata(&path, nd);
3452 seq = 0; /* out of RCU mode, so the value doesn't matter */
3453 inode = d_backing_inode(path.dentry);
3455 error = step_into(nd, &path, 0, inode, seq);
3456 if (unlikely(error))
3459 /* Why this, you ask? _Now_ we might have grown LOOKUP_JUMPED... */
3460 error = complete_walk(nd);
3463 audit_inode(nd->name, nd->path.dentry, 0);
3464 if (open_flag & O_CREAT) {
3466 if (d_is_dir(nd->path.dentry))
3468 error = may_create_in_sticky(dir_mode, dir_uid,
3469 d_backing_inode(nd->path.dentry));
3470 if (unlikely(error))
3474 if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
3476 if (!d_is_reg(nd->path.dentry))
3477 will_truncate = false;
3479 if (will_truncate) {
3480 error = mnt_want_write(nd->path.mnt);
3485 finish_open_created:
3486 error = may_open(&nd->path, acc_mode, open_flag);
3489 BUG_ON(file->f_mode & FMODE_OPENED); /* once it's opened, it's opened */
3490 error = vfs_open(&nd->path, file);
3494 error = ima_file_check(file, op->acc_mode);
3495 if (!error && will_truncate)
3496 error = handle_truncate(file);
3498 if (unlikely(error > 0)) {
3503 mnt_drop_write(nd->path.mnt);
3507 struct dentry *vfs_tmpfile(struct dentry *dentry, umode_t mode, int open_flag)
3509 struct dentry *child = NULL;
3510 struct inode *dir = dentry->d_inode;
3511 struct inode *inode;
3514 /* we want directory to be writable */
3515 error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
3518 error = -EOPNOTSUPP;
3519 if (!dir->i_op->tmpfile)
3522 child = d_alloc(dentry, &slash_name);
3523 if (unlikely(!child))
3525 error = dir->i_op->tmpfile(dir, child, mode);
3529 inode = child->d_inode;
3530 if (unlikely(!inode))
3532 if (!(open_flag & O_EXCL)) {
3533 spin_lock(&inode->i_lock);
3534 inode->i_state |= I_LINKABLE;
3535 spin_unlock(&inode->i_lock);
3537 ima_post_create_tmpfile(inode);
3542 return ERR_PTR(error);
3544 EXPORT_SYMBOL(vfs_tmpfile);
3546 static int do_tmpfile(struct nameidata *nd, unsigned flags,
3547 const struct open_flags *op,
3550 struct dentry *child;
3552 int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
3553 if (unlikely(error))
3555 error = mnt_want_write(path.mnt);
3556 if (unlikely(error))
3558 child = vfs_tmpfile(path.dentry, op->mode, op->open_flag);
3559 error = PTR_ERR(child);
3563 path.dentry = child;
3564 audit_inode(nd->name, child, 0);
3565 /* Don't check for other permissions, the inode was just created */
3566 error = may_open(&path, 0, op->open_flag);
3569 file->f_path.mnt = path.mnt;
3570 error = finish_open(file, child, NULL);
3572 mnt_drop_write(path.mnt);
3578 static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
3581 int error = path_lookupat(nd, flags, &path);
3583 audit_inode(nd->name, path.dentry, 0);
3584 error = vfs_open(&path, file);
3590 static struct file *path_openat(struct nameidata *nd,
3591 const struct open_flags *op, unsigned flags)
3596 file = alloc_empty_file(op->open_flag, current_cred());
3600 if (unlikely(file->f_flags & __O_TMPFILE)) {
3601 error = do_tmpfile(nd, flags, op, file);
3602 } else if (unlikely(file->f_flags & O_PATH)) {
3603 error = do_o_path(nd, flags, file);
3605 const char *s = path_init(nd, flags);
3606 while (!(error = link_path_walk(s, nd)) &&
3607 (error = do_last(nd, file, op)) > 0) {
3608 nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
3609 s = trailing_symlink(nd);
3613 if (likely(!error)) {
3614 if (likely(file->f_mode & FMODE_OPENED))
3620 if (error == -EOPENSTALE) {
3621 if (flags & LOOKUP_RCU)
3626 return ERR_PTR(error);
3629 struct file *do_filp_open(int dfd, struct filename *pathname,
3630 const struct open_flags *op)
3632 struct nameidata nd;
3633 int flags = op->lookup_flags;
3636 set_nameidata(&nd, dfd, pathname);
3637 filp = path_openat(&nd, op, flags | LOOKUP_RCU);
3638 if (unlikely(filp == ERR_PTR(-ECHILD)))
3639 filp = path_openat(&nd, op, flags);
3640 if (unlikely(filp == ERR_PTR(-ESTALE)))
3641 filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
3642 restore_nameidata();
3646 struct file *do_file_open_root(struct dentry *dentry, struct vfsmount *mnt,
3647 const char *name, const struct open_flags *op)
3649 struct nameidata nd;
3651 struct filename *filename;
3652 int flags = op->lookup_flags | LOOKUP_ROOT;
3655 nd.root.dentry = dentry;
3657 if (d_is_symlink(dentry) && op->intent & LOOKUP_OPEN)
3658 return ERR_PTR(-ELOOP);
3660 filename = getname_kernel(name);
3661 if (IS_ERR(filename))
3662 return ERR_CAST(filename);
3664 set_nameidata(&nd, -1, filename);
3665 file = path_openat(&nd, op, flags | LOOKUP_RCU);
3666 if (unlikely(file == ERR_PTR(-ECHILD)))
3667 file = path_openat(&nd, op, flags);
3668 if (unlikely(file == ERR_PTR(-ESTALE)))
3669 file = path_openat(&nd, op, flags | LOOKUP_REVAL);
3670 restore_nameidata();
3675 static struct dentry *filename_create(int dfd, struct filename *name,
3676 struct path *path, unsigned int lookup_flags)
3678 struct dentry *dentry = ERR_PTR(-EEXIST);
3683 bool is_dir = (lookup_flags & LOOKUP_DIRECTORY);
3686 * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any
3687 * other flags passed in are ignored!
3689 lookup_flags &= LOOKUP_REVAL;
3691 name = filename_parentat(dfd, name, lookup_flags, path, &last, &type);
3693 return ERR_CAST(name);
3696 * Yucky last component or no last component at all?
3697 * (foo/., foo/.., /////)
3699 if (unlikely(type != LAST_NORM))
3702 /* don't fail immediately if it's r/o, at least try to report other errors */
3703 err2 = mnt_want_write(path->mnt);
3705 * Do the final lookup.
3707 lookup_flags |= LOOKUP_CREATE | LOOKUP_EXCL;
3708 inode_lock_nested(path->dentry->d_inode, I_MUTEX_PARENT);
3709 dentry = __lookup_hash(&last, path->dentry, lookup_flags);
3714 if (d_is_positive(dentry))
3718 * Special case - lookup gave negative, but... we had foo/bar/
3719 * From the vfs_mknod() POV we just have a negative dentry -
3720 * all is fine. Let's be bastards - you had / on the end, you've
3721 * been asking for (non-existent) directory. -ENOENT for you.
3723 if (unlikely(!is_dir && last.name[last.len])) {
3727 if (unlikely(err2)) {
3735 dentry = ERR_PTR(error);
3737 inode_unlock(path->dentry->d_inode);
3739 mnt_drop_write(path->mnt);
3746 struct dentry *kern_path_create(int dfd, const char *pathname,
3747 struct path *path, unsigned int lookup_flags)
3749 return filename_create(dfd, getname_kernel(pathname),
3750 path, lookup_flags);
3752 EXPORT_SYMBOL(kern_path_create);
3754 void done_path_create(struct path *path, struct dentry *dentry)
3757 inode_unlock(path->dentry->d_inode);
3758 mnt_drop_write(path->mnt);
3761 EXPORT_SYMBOL(done_path_create);
3763 inline struct dentry *user_path_create(int dfd, const char __user *pathname,
3764 struct path *path, unsigned int lookup_flags)
3766 return filename_create(dfd, getname(pathname), path, lookup_flags);
3768 EXPORT_SYMBOL(user_path_create);
3770 int vfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3772 int error = may_create(dir, dentry);
3777 if ((S_ISCHR(mode) || S_ISBLK(mode)) && !capable(CAP_MKNOD))
3780 if (!dir->i_op->mknod)
3783 error = devcgroup_inode_mknod(mode, dev);
3787 error = security_inode_mknod(dir, dentry, mode, dev);
3791 error = dir->i_op->mknod(dir, dentry, mode, dev);
3793 fsnotify_create(dir, dentry);
3796 EXPORT_SYMBOL(vfs_mknod);
3798 static int may_mknod(umode_t mode)
3800 switch (mode & S_IFMT) {
3806 case 0: /* zero mode translates to S_IFREG */
3815 long do_mknodat(int dfd, const char __user *filename, umode_t mode,
3818 struct dentry *dentry;
3821 unsigned int lookup_flags = 0;
3823 error = may_mknod(mode);
3827 dentry = user_path_create(dfd, filename, &path, lookup_flags);
3829 return PTR_ERR(dentry);
3831 if (!IS_POSIXACL(path.dentry->d_inode))
3832 mode &= ~current_umask();
3833 error = security_path_mknod(&path, dentry, mode, dev);
3836 switch (mode & S_IFMT) {
3837 case 0: case S_IFREG:
3838 error = vfs_create(path.dentry->d_inode,dentry,mode,true);
3840 ima_post_path_mknod(dentry);
3842 case S_IFCHR: case S_IFBLK:
3843 error = vfs_mknod(path.dentry->d_inode,dentry,mode,
3844 new_decode_dev(dev));
3846 case S_IFIFO: case S_IFSOCK:
3847 error = vfs_mknod(path.dentry->d_inode,dentry,mode,0);
3851 done_path_create(&path, dentry);
3852 if (retry_estale(error, lookup_flags)) {
3853 lookup_flags |= LOOKUP_REVAL;
3859 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
3862 return do_mknodat(dfd, filename, mode, dev);
3865 SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
3867 return do_mknodat(AT_FDCWD, filename, mode, dev);
3870 int vfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
3872 int error = may_create(dir, dentry);
3873 unsigned max_links = dir->i_sb->s_max_links;
3878 if (!dir->i_op->mkdir)
3881 mode &= (S_IRWXUGO|S_ISVTX);
3882 error = security_inode_mkdir(dir, dentry, mode);
3886 if (max_links && dir->i_nlink >= max_links)
3889 error = dir->i_op->mkdir(dir, dentry, mode);
3891 fsnotify_mkdir(dir, dentry);
3894 EXPORT_SYMBOL(vfs_mkdir);
3896 long do_mkdirat(int dfd, const char __user *pathname, umode_t mode)
3898 struct dentry *dentry;
3901 unsigned int lookup_flags = LOOKUP_DIRECTORY;
3904 dentry = user_path_create(dfd, pathname, &path, lookup_flags);
3906 return PTR_ERR(dentry);
3908 if (!IS_POSIXACL(path.dentry->d_inode))
3909 mode &= ~current_umask();
3910 error = security_path_mkdir(&path, dentry, mode);
3912 error = vfs_mkdir(path.dentry->d_inode, dentry, mode);
3913 done_path_create(&path, dentry);
3914 if (retry_estale(error, lookup_flags)) {
3915 lookup_flags |= LOOKUP_REVAL;
3921 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
3923 return do_mkdirat(dfd, pathname, mode);
3926 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
3928 return do_mkdirat(AT_FDCWD, pathname, mode);
3931 int vfs_rmdir(struct inode *dir, struct dentry *dentry)
3933 int error = may_delete(dir, dentry, 1);
3938 if (!dir->i_op->rmdir)
3942 inode_lock(dentry->d_inode);
3945 if (is_local_mountpoint(dentry))
3948 error = security_inode_rmdir(dir, dentry);
3952 error = dir->i_op->rmdir(dir, dentry);
3956 shrink_dcache_parent(dentry);
3957 dentry->d_inode->i_flags |= S_DEAD;
3959 detach_mounts(dentry);
3960 fsnotify_rmdir(dir, dentry);
3963 inode_unlock(dentry->d_inode);
3969 EXPORT_SYMBOL(vfs_rmdir);
3971 long do_rmdir(int dfd, const char __user *pathname)
3974 struct filename *name;
3975 struct dentry *dentry;
3979 unsigned int lookup_flags = 0;
3981 name = filename_parentat(dfd, getname(pathname), lookup_flags,
3982 &path, &last, &type);
3984 return PTR_ERR(name);
3998 error = mnt_want_write(path.mnt);
4002 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4003 dentry = __lookup_hash(&last, path.dentry, lookup_flags);
4004 error = PTR_ERR(dentry);
4007 if (!dentry->d_inode) {
4011 error = security_path_rmdir(&path, dentry);
4014 error = vfs_rmdir(path.dentry->d_inode, dentry);
4018 inode_unlock(path.dentry->d_inode);
4019 mnt_drop_write(path.mnt);
4023 if (retry_estale(error, lookup_flags)) {
4024 lookup_flags |= LOOKUP_REVAL;
4030 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
4032 return do_rmdir(AT_FDCWD, pathname);
4036 * vfs_unlink - unlink a filesystem object
4037 * @dir: parent directory
4039 * @delegated_inode: returns victim inode, if the inode is delegated.
4041 * The caller must hold dir->i_mutex.
4043 * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
4044 * return a reference to the inode in delegated_inode. The caller
4045 * should then break the delegation on that inode and retry. Because
4046 * breaking a delegation may take a long time, the caller should drop
4047 * dir->i_mutex before doing so.
4049 * Alternatively, a caller may pass NULL for delegated_inode. This may
4050 * be appropriate for callers that expect the underlying filesystem not
4051 * to be NFS exported.
4053 int vfs_unlink(struct inode *dir, struct dentry *dentry, struct inode **delegated_inode)
4055 struct inode *target = dentry->d_inode;
4056 int error = may_delete(dir, dentry, 0);
4061 if (!dir->i_op->unlink)
4065 if (is_local_mountpoint(dentry))
4068 error = security_inode_unlink(dir, dentry);
4070 error = try_break_deleg(target, delegated_inode);
4073 error = dir->i_op->unlink(dir, dentry);
4076 detach_mounts(dentry);
4077 fsnotify_unlink(dir, dentry);
4082 inode_unlock(target);
4084 /* We don't d_delete() NFS sillyrenamed files--they still exist. */
4085 if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) {
4086 fsnotify_link_count(target);
4092 EXPORT_SYMBOL(vfs_unlink);
4095 * Make sure that the actual truncation of the file will occur outside its
4096 * directory's i_mutex. Truncate can take a long time if there is a lot of
4097 * writeout happening, and we don't want to prevent access to the directory
4098 * while waiting on the I/O.
4100 long do_unlinkat(int dfd, struct filename *name)
4103 struct dentry *dentry;
4107 struct inode *inode = NULL;
4108 struct inode *delegated_inode = NULL;
4109 unsigned int lookup_flags = 0;
4111 name = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
4113 return PTR_ERR(name);
4116 if (type != LAST_NORM)
4119 error = mnt_want_write(path.mnt);
4123 inode_lock_nested(path.dentry->d_inode, I_MUTEX_PARENT);
4124 dentry = __lookup_hash(&last, path.dentry, lookup_flags);
4125 error = PTR_ERR(dentry);
4126 if (!IS_ERR(dentry)) {
4127 /* Why not before? Because we want correct error value */
4128 if (last.name[last.len])
4130 inode = dentry->d_inode;
4131 if (d_is_negative(dentry))
4134 error = security_path_unlink(&path, dentry);
4137 error = vfs_unlink(path.dentry->d_inode, dentry, &delegated_inode);
4141 inode_unlock(path.dentry->d_inode);
4143 iput(inode); /* truncate the inode here */
4145 if (delegated_inode) {
4146 error = break_deleg_wait(&delegated_inode);
4150 mnt_drop_write(path.mnt);
4153 if (retry_estale(error, lookup_flags)) {
4154 lookup_flags |= LOOKUP_REVAL;
4162 if (d_is_negative(dentry))
4164 else if (d_is_dir(dentry))
4171 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
4173 if ((flag & ~AT_REMOVEDIR) != 0)
4176 if (flag & AT_REMOVEDIR)
4177 return do_rmdir(dfd, pathname);
4179 return do_unlinkat(dfd, getname(pathname));
4182 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
4184 return do_unlinkat(AT_FDCWD, getname(pathname));
4187 int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname)
4189 int error = may_create(dir, dentry);
4194 if (!dir->i_op->symlink)
4197 error = security_inode_symlink(dir, dentry, oldname);
4201 error = dir->i_op->symlink(dir, dentry, oldname);
4203 fsnotify_create(dir, dentry);
4206 EXPORT_SYMBOL(vfs_symlink);
4208 long do_symlinkat(const char __user *oldname, int newdfd,
4209 const char __user *newname)
4212 struct filename *from;
4213 struct dentry *dentry;
4215 unsigned int lookup_flags = 0;
4217 from = getname(oldname);
4219 return PTR_ERR(from);
4221 dentry = user_path_create(newdfd, newname, &path, lookup_flags);
4222 error = PTR_ERR(dentry);
4226 error = security_path_symlink(&path, dentry, from->name);
4228 error = vfs_symlink(path.dentry->d_inode, dentry, from->name);
4229 done_path_create(&path, dentry);
4230 if (retry_estale(error, lookup_flags)) {
4231 lookup_flags |= LOOKUP_REVAL;
4239 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
4240 int, newdfd, const char __user *, newname)
4242 return do_symlinkat(oldname, newdfd, newname);
4245 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
4247 return do_symlinkat(oldname, AT_FDCWD, newname);
4251 * vfs_link - create a new link
4252 * @old_dentry: object to be linked
4254 * @new_dentry: where to create the new link
4255 * @delegated_inode: returns inode needing a delegation break
4257 * The caller must hold dir->i_mutex
4259 * If vfs_link discovers a delegation on the to-be-linked file in need
4260 * of breaking, it will return -EWOULDBLOCK and return a reference to the
4261 * inode in delegated_inode. The caller should then break the delegation
4262 * and retry. Because breaking a delegation may take a long time, the
4263 * caller should drop the i_mutex before doing so.
4265 * Alternatively, a caller may pass NULL for delegated_inode. This may
4266 * be appropriate for callers that expect the underlying filesystem not
4267 * to be NFS exported.
4269 int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry, struct inode **delegated_inode)
4271 struct inode *inode = old_dentry->d_inode;
4272 unsigned max_links = dir->i_sb->s_max_links;
4278 error = may_create(dir, new_dentry);
4282 if (dir->i_sb != inode->i_sb)
4286 * A link to an append-only or immutable file cannot be created.
4288 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4291 * Updating the link count will likely cause i_uid and i_gid to
4292 * be writen back improperly if their true value is unknown to
4295 if (HAS_UNMAPPED_ID(inode))
4297 if (!dir->i_op->link)
4299 if (S_ISDIR(inode->i_mode))
4302 error = security_inode_link(old_dentry, dir, new_dentry);
4307 /* Make sure we don't allow creating hardlink to an unlinked file */
4308 if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
4310 else if (max_links && inode->i_nlink >= max_links)
4313 error = try_break_deleg(inode, delegated_inode);
4315 error = dir->i_op->link(old_dentry, dir, new_dentry);
4318 if (!error && (inode->i_state & I_LINKABLE)) {
4319 spin_lock(&inode->i_lock);
4320 inode->i_state &= ~I_LINKABLE;
4321 spin_unlock(&inode->i_lock);
4323 inode_unlock(inode);
4325 fsnotify_link(dir, inode, new_dentry);
4328 EXPORT_SYMBOL(vfs_link);
4331 * Hardlinks are often used in delicate situations. We avoid
4332 * security-related surprises by not following symlinks on the
4335 * We don't follow them on the oldname either to be compatible
4336 * with linux 2.0, and to avoid hard-linking to directories
4337 * and other special files. --ADM
4339 int do_linkat(int olddfd, const char __user *oldname, int newdfd,
4340 const char __user *newname, int flags)
4342 struct dentry *new_dentry;
4343 struct path old_path, new_path;
4344 struct inode *delegated_inode = NULL;
4348 if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0)
4351 * To use null names we require CAP_DAC_READ_SEARCH
4352 * This ensures that not everyone will be able to create
4353 * handlink using the passed filedescriptor.
4355 if (flags & AT_EMPTY_PATH) {
4356 if (!capable(CAP_DAC_READ_SEARCH))
4361 if (flags & AT_SYMLINK_FOLLOW)
4362 how |= LOOKUP_FOLLOW;
4364 error = user_path_at(olddfd, oldname, how, &old_path);
4368 new_dentry = user_path_create(newdfd, newname, &new_path,
4369 (how & LOOKUP_REVAL));
4370 error = PTR_ERR(new_dentry);
4371 if (IS_ERR(new_dentry))
4375 if (old_path.mnt != new_path.mnt)
4377 error = may_linkat(&old_path);
4378 if (unlikely(error))
4380 error = security_path_link(old_path.dentry, &new_path, new_dentry);
4383 error = vfs_link(old_path.dentry, new_path.dentry->d_inode, new_dentry, &delegated_inode);
4385 done_path_create(&new_path, new_dentry);
4386 if (delegated_inode) {
4387 error = break_deleg_wait(&delegated_inode);
4389 path_put(&old_path);
4393 if (retry_estale(error, how)) {
4394 path_put(&old_path);
4395 how |= LOOKUP_REVAL;
4399 path_put(&old_path);
4404 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
4405 int, newdfd, const char __user *, newname, int, flags)
4407 return do_linkat(olddfd, oldname, newdfd, newname, flags);
4410 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
4412 return do_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
4416 * vfs_rename - rename a filesystem object
4417 * @old_dir: parent of source
4418 * @old_dentry: source
4419 * @new_dir: parent of destination
4420 * @new_dentry: destination
4421 * @delegated_inode: returns an inode needing a delegation break
4422 * @flags: rename flags
4424 * The caller must hold multiple mutexes--see lock_rename()).
4426 * If vfs_rename discovers a delegation in need of breaking at either
4427 * the source or destination, it will return -EWOULDBLOCK and return a
4428 * reference to the inode in delegated_inode. The caller should then
4429 * break the delegation and retry. Because breaking a delegation may
4430 * take a long time, the caller should drop all locks before doing
4433 * Alternatively, a caller may pass NULL for delegated_inode. This may
4434 * be appropriate for callers that expect the underlying filesystem not
4435 * to be NFS exported.
4437 * The worst of all namespace operations - renaming directory. "Perverted"
4438 * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
4441 * a) we can get into loop creation.
4442 * b) race potential - two innocent renames can create a loop together.
4443 * That's where 4.4 screws up. Current fix: serialization on
4444 * sb->s_vfs_rename_mutex. We might be more accurate, but that's another
4446 * c) we have to lock _four_ objects - parents and victim (if it exists),
4447 * and source (if it is not a directory).
4448 * And that - after we got ->i_mutex on parents (until then we don't know
4449 * whether the target exists). Solution: try to be smart with locking
4450 * order for inodes. We rely on the fact that tree topology may change
4451 * only under ->s_vfs_rename_mutex _and_ that parent of the object we
4452 * move will be locked. Thus we can rank directories by the tree
4453 * (ancestors first) and rank all non-directories after them.
4454 * That works since everybody except rename does "lock parent, lookup,
4455 * lock child" and rename is under ->s_vfs_rename_mutex.
4456 * HOWEVER, it relies on the assumption that any object with ->lookup()
4457 * has no more than 1 dentry. If "hybrid" objects will ever appear,
4458 * we'd better make sure that there's no link(2) for them.
4459 * d) conversion from fhandle to dentry may come in the wrong moment - when
4460 * we are removing the target. Solution: we will have to grab ->i_mutex
4461 * in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
4462 * ->i_mutex on parents, which works but leads to some truly excessive
4465 int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
4466 struct inode *new_dir, struct dentry *new_dentry,
4467 struct inode **delegated_inode, unsigned int flags)
4470 bool is_dir = d_is_dir(old_dentry);
4471 struct inode *source = old_dentry->d_inode;
4472 struct inode *target = new_dentry->d_inode;
4473 bool new_is_dir = false;
4474 unsigned max_links = new_dir->i_sb->s_max_links;
4475 struct name_snapshot old_name;
4477 if (source == target)
4480 error = may_delete(old_dir, old_dentry, is_dir);
4485 error = may_create(new_dir, new_dentry);
4487 new_is_dir = d_is_dir(new_dentry);
4489 if (!(flags & RENAME_EXCHANGE))
4490 error = may_delete(new_dir, new_dentry, is_dir);
4492 error = may_delete(new_dir, new_dentry, new_is_dir);
4497 if (!old_dir->i_op->rename)
4501 * If we are going to change the parent - check write permissions,
4502 * we'll need to flip '..'.
4504 if (new_dir != old_dir) {
4506 error = inode_permission(source, MAY_WRITE);
4510 if ((flags & RENAME_EXCHANGE) && new_is_dir) {
4511 error = inode_permission(target, MAY_WRITE);
4517 error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
4522 take_dentry_name_snapshot(&old_name, old_dentry);
4524 if (!is_dir || (flags & RENAME_EXCHANGE))
4525 lock_two_nondirectories(source, target);
4530 if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
4533 if (max_links && new_dir != old_dir) {
4535 if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
4537 if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
4538 old_dir->i_nlink >= max_links)
4542 error = try_break_deleg(source, delegated_inode);
4546 if (target && !new_is_dir) {
4547 error = try_break_deleg(target, delegated_inode);
4551 error = old_dir->i_op->rename(old_dir, old_dentry,
4552 new_dir, new_dentry, flags);
4556 if (!(flags & RENAME_EXCHANGE) && target) {
4558 shrink_dcache_parent(new_dentry);
4559 target->i_flags |= S_DEAD;
4561 dont_mount(new_dentry);
4562 detach_mounts(new_dentry);
4564 if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
4565 if (!(flags & RENAME_EXCHANGE))
4566 d_move(old_dentry, new_dentry);
4568 d_exchange(old_dentry, new_dentry);
4571 if (!is_dir || (flags & RENAME_EXCHANGE))
4572 unlock_two_nondirectories(source, target);
4574 inode_unlock(target);
4577 fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
4578 !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
4579 if (flags & RENAME_EXCHANGE) {
4580 fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
4581 new_is_dir, NULL, new_dentry);
4584 release_dentry_name_snapshot(&old_name);
4588 EXPORT_SYMBOL(vfs_rename);
4590 static int do_renameat2(int olddfd, const char __user *oldname, int newdfd,
4591 const char __user *newname, unsigned int flags)
4593 struct dentry *old_dentry, *new_dentry;
4594 struct dentry *trap;
4595 struct path old_path, new_path;
4596 struct qstr old_last, new_last;
4597 int old_type, new_type;
4598 struct inode *delegated_inode = NULL;
4599 struct filename *from;
4600 struct filename *to;
4601 unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET;
4602 bool should_retry = false;
4605 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4608 if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
4609 (flags & RENAME_EXCHANGE))
4612 if ((flags & RENAME_WHITEOUT) && !capable(CAP_MKNOD))
4615 if (flags & RENAME_EXCHANGE)
4619 from = filename_parentat(olddfd, getname(oldname), lookup_flags,
4620 &old_path, &old_last, &old_type);
4622 error = PTR_ERR(from);
4626 to = filename_parentat(newdfd, getname(newname), lookup_flags,
4627 &new_path, &new_last, &new_type);
4629 error = PTR_ERR(to);
4634 if (old_path.mnt != new_path.mnt)
4638 if (old_type != LAST_NORM)
4641 if (flags & RENAME_NOREPLACE)
4643 if (new_type != LAST_NORM)
4646 error = mnt_want_write(old_path.mnt);
4651 trap = lock_rename(new_path.dentry, old_path.dentry);
4653 old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags);
4654 error = PTR_ERR(old_dentry);
4655 if (IS_ERR(old_dentry))
4657 /* source must exist */
4659 if (d_is_negative(old_dentry))
4661 new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags);
4662 error = PTR_ERR(new_dentry);
4663 if (IS_ERR(new_dentry))
4666 if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
4668 if (flags & RENAME_EXCHANGE) {
4670 if (d_is_negative(new_dentry))
4673 if (!d_is_dir(new_dentry)) {
4675 if (new_last.name[new_last.len])
4679 /* unless the source is a directory trailing slashes give -ENOTDIR */
4680 if (!d_is_dir(old_dentry)) {
4682 if (old_last.name[old_last.len])
4684 if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
4687 /* source should not be ancestor of target */
4689 if (old_dentry == trap)
4691 /* target should not be an ancestor of source */
4692 if (!(flags & RENAME_EXCHANGE))
4694 if (new_dentry == trap)
4697 error = security_path_rename(&old_path, old_dentry,
4698 &new_path, new_dentry, flags);
4701 error = vfs_rename(old_path.dentry->d_inode, old_dentry,
4702 new_path.dentry->d_inode, new_dentry,
4703 &delegated_inode, flags);
4709 unlock_rename(new_path.dentry, old_path.dentry);
4710 if (delegated_inode) {
4711 error = break_deleg_wait(&delegated_inode);
4715 mnt_drop_write(old_path.mnt);
4717 if (retry_estale(error, lookup_flags))
4718 should_retry = true;
4719 path_put(&new_path);
4722 path_put(&old_path);
4725 should_retry = false;
4726 lookup_flags |= LOOKUP_REVAL;
4733 SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
4734 int, newdfd, const char __user *, newname, unsigned int, flags)
4736 return do_renameat2(olddfd, oldname, newdfd, newname, flags);
4739 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
4740 int, newdfd, const char __user *, newname)
4742 return do_renameat2(olddfd, oldname, newdfd, newname, 0);
4745 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
4747 return do_renameat2(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
4750 int vfs_whiteout(struct inode *dir, struct dentry *dentry)
4752 int error = may_create(dir, dentry);
4756 if (!dir->i_op->mknod)
4759 return dir->i_op->mknod(dir, dentry,
4760 S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
4762 EXPORT_SYMBOL(vfs_whiteout);
4764 int readlink_copy(char __user *buffer, int buflen, const char *link)
4766 int len = PTR_ERR(link);
4771 if (len > (unsigned) buflen)
4773 if (copy_to_user(buffer, link, len))
4780 * vfs_readlink - copy symlink body into userspace buffer
4781 * @dentry: dentry on which to get symbolic link
4782 * @buffer: user memory pointer
4783 * @buflen: size of buffer
4785 * Does not touch atime. That's up to the caller if necessary
4787 * Does not call security hook.
4789 int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4791 struct inode *inode = d_inode(dentry);
4792 DEFINE_DELAYED_CALL(done);
4796 if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
4797 if (unlikely(inode->i_op->readlink))
4798 return inode->i_op->readlink(dentry, buffer, buflen);
4800 if (!d_is_symlink(dentry))
4803 spin_lock(&inode->i_lock);
4804 inode->i_opflags |= IOP_DEFAULT_READLINK;
4805 spin_unlock(&inode->i_lock);
4808 link = READ_ONCE(inode->i_link);
4810 link = inode->i_op->get_link(dentry, inode, &done);
4812 return PTR_ERR(link);
4814 res = readlink_copy(buffer, buflen, link);
4815 do_delayed_call(&done);
4818 EXPORT_SYMBOL(vfs_readlink);
4821 * vfs_get_link - get symlink body
4822 * @dentry: dentry on which to get symbolic link
4823 * @done: caller needs to free returned data with this
4825 * Calls security hook and i_op->get_link() on the supplied inode.
4827 * It does not touch atime. That's up to the caller if necessary.
4829 * Does not work on "special" symlinks like /proc/$$/fd/N
4831 const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
4833 const char *res = ERR_PTR(-EINVAL);
4834 struct inode *inode = d_inode(dentry);
4836 if (d_is_symlink(dentry)) {
4837 res = ERR_PTR(security_inode_readlink(dentry));
4839 res = inode->i_op->get_link(dentry, inode, done);
4843 EXPORT_SYMBOL(vfs_get_link);
4845 /* get the link contents into pagecache */
4846 const char *page_get_link(struct dentry *dentry, struct inode *inode,
4847 struct delayed_call *callback)
4851 struct address_space *mapping = inode->i_mapping;
4854 page = find_get_page(mapping, 0);
4856 return ERR_PTR(-ECHILD);
4857 if (!PageUptodate(page)) {
4859 return ERR_PTR(-ECHILD);
4862 page = read_mapping_page(mapping, 0, NULL);
4866 set_delayed_call(callback, page_put_link, page);
4867 BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
4868 kaddr = page_address(page);
4869 nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
4873 EXPORT_SYMBOL(page_get_link);
4875 void page_put_link(void *arg)
4879 EXPORT_SYMBOL(page_put_link);
4881 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4883 DEFINE_DELAYED_CALL(done);
4884 int res = readlink_copy(buffer, buflen,
4885 page_get_link(dentry, d_inode(dentry),
4887 do_delayed_call(&done);
4890 EXPORT_SYMBOL(page_readlink);
4893 * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
4895 int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
4897 struct address_space *mapping = inode->i_mapping;
4901 unsigned int flags = 0;
4903 flags |= AOP_FLAG_NOFS;
4906 err = pagecache_write_begin(NULL, mapping, 0, len-1,
4907 flags, &page, &fsdata);
4911 memcpy(page_address(page), symname, len-1);
4913 err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
4920 mark_inode_dirty(inode);
4925 EXPORT_SYMBOL(__page_symlink);
4927 int page_symlink(struct inode *inode, const char *symname, int len)
4929 return __page_symlink(inode, symname, len,
4930 !mapping_gfp_constraint(inode->i_mapping, __GFP_FS));
4932 EXPORT_SYMBOL(page_symlink);
4934 const struct inode_operations page_symlink_inode_operations = {
4935 .get_link = page_get_link,
4937 EXPORT_SYMBOL(page_symlink_inode_operations);